text
stringlengths
14
6.51M
unit enet_callbacks; (** @file callbacks.c @brief ENet callback functions 1.3.12 freepascal - fix callback pointer nil check *) interface uses enet_consts, enet_socket; function enet_initialize_with_callbacks (version : integer; inits : pENetCallbacks):integer; function enet_malloc (size : enet_size_t):pointer; procedure enet_free (memory : pointer); function enet_linked_version:enet_uint32; implementation uses sysutils; var callbacks : ENetCallbacks; (** Gives the linked version of the ENet library. @returns the version number *) function enet_linked_version:enet_uint32; begin Result:=ENET_VERSION; end; function enet_initialize_with_callbacks (version : integer; inits : pENetCallbacks):integer; begin if (version < $00103000) then begin result := -1; exit; end; if (inits^ . malloc <> nil) or (inits^ . free <> nil) then begin if (inits^ . malloc = nil) or (inits^ . free = nil) then begin result := -1; exit; end; callbacks.malloc := ENETCALLBACK_malloc(inits^. malloc); callbacks.free := ENETCALLBACK_free(inits ^. free); end; if (inits^ . nomemory <> nil) then callbacks.nomemory := ENETCALLBACK_nomemory(inits^ . nomemory); result := enet_initialize; end; function enet_malloc (size : enet_size_t):pointer; begin result := callbacks.malloc (size); if (result = nil) then callbacks.nomemory; end; procedure enet_free (memory : pointer); begin callbacks.free (memory); end; function __malloc(size : enet_size_t):pointer; stdcall; begin getmem(result,size); end; procedure __free(memory : pointer); stdcall; begin freemem(memory); end; procedure __nomemory; stdcall; begin raise Exception.Create('Out of Memory'); end; initialization callbacks.malloc := @__malloc; callbacks.free := @__free; callbacks.nomemory := @__nomemory; end.
unit uGame; interface uses glr_math, glr_core, glr_scene, glr_render, glr_mesh, glr_filesystem, glr_utils, glr_resload; type { TGame } TGame = class (TglrGame) protected dx, dy: Integer; Camera: TglrCamera; Material: TglrMaterial; Shader: TglrShaderProgram; mesh: TglrMesh; procedure PrepareMesh(); procedure PrepareMaterial(); procedure SaveMeshDataAsGlr(); public procedure OnFinish; override; procedure OnInput(Event: PglrInputEvent); override; procedure OnPause; override; procedure OnRender; override; procedure OnResize(aNewWidth, aNewHeight: Integer); override; procedure OnResume; override; procedure OnStart; override; procedure OnUpdate(const dt: Double); override; end; var Game: TGame; implementation { TGame } procedure TGame.PrepareMesh(); begin // mesh := TglrMesh.Create(FileSystem.ReadResource('data/Lara_Croft_default.obj'), mfObj); mesh := TglrMesh.Create(FileSystem.ReadResource('data/mesh.raw'), mfRawGlr); end; procedure TGame.PrepareMaterial; begin Shader := TglrShaderProgram.Create(); Shader.Attach(FileSystem.ReadResource('data/MeshShaderV.txt'), stVertex); Shader.Attach(FileSystem.ReadResource('data/MeshShaderF.txt'), stFragment); Shader.Link(); Material := TglrMaterial.Create(Shader); Material.AddTexture(Default.BlankTexture, 'uDiffuse'); Material.PolygonMode := pmLines; end; procedure TGame.SaveMeshDataAsGlr; var f: TglrStream; begin f := glr_resload.SaveMesh(mesh.Data, mfRawGlr); FileSystem.WriteResource('data/mesh.raw', f); f.Free(); end; procedure TGame.OnStart; begin PrepareMesh(); PrepareMaterial(); Camera := TglrCamera.Create(); Camera.SetProjParams(0, 0, Render.Width, Render.Height, 45, 0.1, 500, pmPerspective, pTopLeft); Camera.SetViewParams(Vec3f(5, 7, 5), Vec3f(0, 2, 0), Vec3f(0, 1, 0)); end; procedure TGame.OnFinish; begin mesh.Free(); Shader.Free(); Material.Free(); Camera.Free(); end; procedure TGame.OnInput(Event: PglrInputEvent); begin if (Event.InputType = itTouchDown) and (Event.Key = kLeftButton) then begin dx := Event.X; dy := Event.Y; end; if (Event.InputType = itTouchMove) and (Event.Key = kLeftButton) then begin Camera.Rotate((Event.X - dx) * deg2rad * 0.2, Vec3f(0, 1, 0)); Camera.Rotate((Event.Y - dy) * deg2rad * 0.2, Camera.Right); dx := Event.X; dy := Event.Y; end; if (Event.InputType = itWheel) then Camera.Translate(0, 0, -Sign(2 * Event.W)); end; procedure TGame.OnUpdate(const dt: Double); var v: TglrVec2f; begin v.Reset(); if (Core.Input.KeyDown[kW]) then v.x := -1 else if (Core.Input.KeyDown[kS]) then v.x := 1; if (Core.Input.KeyDown[kA]) then v.y := -1 else if (Core.Input.KeyDown[kD]) then v.y := 1; Camera.Translate(0, v.y * 15 * dt, v.x * 15 * dt); end; procedure TGame.OnRender; begin Camera.Update(); Material.Bind(); with mesh.Data do Render.DrawTriangles(vBuffer, iBuffer, 0, iBuffer.Count); end; procedure TGame.OnPause; begin // Calls when app' window has lost focus end; procedure TGame.OnResume; begin // Calls when app' window was focused end; procedure TGame.OnResize(aNewWidth, aNewHeight: Integer); begin // Calls when window has changed size end; end.
unit uCidadeController; interface uses System.SysUtils, uDMCidade, uRegras, uEnumerador, uDM, Data.DB, Vcl.Forms, uFuncoesSIDomper, Data.DBXJSON, Data.DBXJSONReflect, uConverter, uGenericProperty; type TCidadeController = class private FModel: TDMCidade; FOperacao: TOperacao; procedure Post; public procedure Filtrar(ACampo, ATexto, AAtivo: string; AContem: Boolean = False); procedure FiltrarCodigo(ACodigo: Integer); procedure FiltrarPrograma(AObservacaoPrograma: TEnumPrograma; ACampo, ATexto, AAtivo: string; AContem: Boolean = False); procedure LocalizarPadrao(APrograma: TEnumPrograma); procedure LocalizarId(AId: Integer); procedure LocalizarCodigo(ACodigo: integer); procedure Novo(AIdUsuario: Integer); procedure Editar(AId: Integer; AFormulario: TForm); function Salvar(AIdUsuario: Integer): Integer; procedure Excluir(AIdUsuario, AId: Integer); procedure Cancelar(); procedure Imprimir(AIdUsuario: Integer); function ProximoId(): Integer; function ProximoCodigo(): Integer; procedure Pesquisar(AId, Codigo: Integer); function CodigoAtual: Integer; property Model: TDMCidade read FModel write FModel; constructor Create(); destructor Destroy; override; end; implementation { TObservacaoController } uses uObservacaoVO; procedure TCidadeController.Cancelar; begin if FModel.CDSCadastro.State in [dsEdit, dsInsert] then FModel.CDSCadastro.Cancel; end; function TCidadeController.CodigoAtual: Integer; begin Result := FModel.CDSCadastroCid_Codigo.AsInteger; end; constructor TCidadeController.Create; begin inherited Create; FModel := TDMCidade.Create(nil); end; destructor TCidadeController.Destroy; begin FreeAndNil(FModel); inherited; end; procedure TCidadeController.Editar(AId: Integer; AFormulario: TForm); var Negocio: TServerModule2Client; Resultado: Boolean; begin if AId = 0 then raise Exception.Create('Não há Registro para Editar!'); dm.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try FModel.CDSCadastro.Close; Resultado := Negocio.Editar(CCidade, dm.IdUsuario, AId); FModel.CDSCadastro.Open; TFuncoes.HabilitarCampo(AFormulario, Resultado); FOperacao := opEditar; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TCidadeController.Excluir(AIdUsuario, AId: Integer); var Negocio: TServerModule2Client; begin if AId = 0 then raise Exception.Create('Não há Registro para Excluir!'); dm.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try try Negocio.Excluir(CCidade, AIdUsuario, AId); FModel.CDSConsulta.Delete; dm.Desconectar; except on E: Exception do begin dm.ErroConexao(E.Message); end; end; finally FreeAndNil(Negocio); end; end; procedure TCidadeController.Filtrar(ACampo, ATexto, AAtivo: string; AContem: Boolean); var Negocio: TServerModule2Client; begin dm.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try try FModel.CDSConsulta.Close; Negocio.Filtrar(CCidade, ACampo, ATexto, AAtivo, AContem); FModel.CDSConsulta.Open; dm.Desconectar; except on E: Exception do begin dm.ErroConexao(E.Message); end; end; finally FreeAndNil(Negocio); end; end; procedure TCidadeController.FiltrarCodigo(ACodigo: Integer); var Negocio: TServerModule2Client; begin dm.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try try FModel.CDSConsulta.Close; Negocio.FiltrarCodigo(CCidade, ACodigo); FModel.CDSConsulta.Open; dm.Desconectar; except on E: Exception do begin dm.ErroConexao(E.Message); end; end; finally FreeAndNil(Negocio); end; end; procedure TCidadeController.FiltrarPrograma(AObservacaoPrograma: TEnumPrograma; ACampo, ATexto, AAtivo: string; AContem: Boolean); var Negocio: TServerModule2Client; iEnum: Integer; begin dm.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try try iEnum := Integer(AObservacaoPrograma); FModel.CDSConsulta.Close; Negocio.FiltrarObservacaoPrograma(ACampo, ATexto, AAtivo, iEnum, AContem); FModel.CDSConsulta.Open; dm.Desconectar; except on E: Exception do begin dm.ErroConexao(E.Message); end; end; finally FreeAndNil(Negocio); end; end; procedure TCidadeController.Imprimir(AIdUsuario: Integer); var Negocio: TServerModule2Client; begin dm.Conectar; Negocio := TServerModule2Client.Create(dm.Conexao.DBXConnection); try try Negocio.Relatorio(CCidade, AIdUsuario); FModel.Rel.Print; dm.Desconectar; except on E: Exception do begin dm.ErroConexao(E.Message); end; end; finally FreeAndNil(Negocio); end; end; procedure TCidadeController.LocalizarCodigo(ACodigo: integer); var Negocio: TServerModule2Client; begin dm.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try try FModel.CDSCadastro.Close; Negocio.LocalizarCodigo(CCidade, ACodigo); FModel.CDSCadastro.Open; dm.Desconectar; except on E: Exception do begin dm.ErroConexao(E.Message); end; end; finally FreeAndNil(Negocio); end; end; procedure TCidadeController.LocalizarId(AId: Integer); var Negocio: TServerModule2Client; begin dm.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try try FModel.CDSCadastro.Close; Negocio.LocalizarId(CCidade, AId); FModel.CDSCadastro.Open; dm.Desconectar; except on E: Exception do begin dm.ErroConexao(E.Message); end; end; finally FreeAndNil(Negocio); end; end; procedure TCidadeController.LocalizarPadrao(APrograma: TEnumPrograma); var Negocio: TServerModule2Client; iEnum: Integer; begin dm.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try try iEnum := Integer(APrograma); FModel.CDSCadastro.Close; Negocio.ObservacaoPadrao(iEnum); FModel.CDSCadastro.Open; dm.Desconectar; except on E: Exception do begin dm.ErroConexao(E.Message); end; end; finally FreeAndNil(Negocio); end; end; procedure TCidadeController.Novo(AIdUsuario: Integer); var Negocio: TServerModule2Client; begin dm.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try try FModel.CDSCadastro.Close; Negocio.Novo(CCidade, AIdUsuario); FModel.CDSCadastro.Open; FModel.CDSCadastro.Append; FModel.CDSCadastroCid_Codigo.AsInteger := ProximoCodigo(); FOperacao := opIncluir; dm.Desconectar; except on E: Exception do begin dm.ErroConexao(E.Message); end; end; finally FreeAndNil(Negocio); end; end; procedure TCidadeController.Pesquisar(AId, Codigo: Integer); begin if AId > 0 then LocalizarId(AId) else LocalizarCodigo(Codigo); end; procedure TCidadeController.Post; begin if FModel.CDSConsulta.State in [dsEdit, dsInsert] then FModel.CDSConsulta.Post; end; function TCidadeController.ProximoCodigo: Integer; var Negocio: TServerModule2Client; iCodigo: Integer; begin dm.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try try iCodigo := StrToInt(Negocio.ProximoCodigo(CCidade).ToString); Result := iCodigo; dm.Desconectar; except on E: Exception do begin dm.ErroConexao(E.Message); end; end; finally FreeAndNil(Negocio); end; end; function TCidadeController.ProximoId: Integer; var Negocio: TServerModule2Client; iCodigo: Integer; begin dm.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try try iCodigo := StrToInt(Negocio.ProximoId(CCidade).ToString); Result := iCodigo; dm.Desconectar; except on E: Exception do begin dm.ErroConexao(E.Message); end; end; finally FreeAndNil(Negocio); end; end; function TCidadeController.Salvar(AIdUsuario: Integer): Integer; var Negocio: TServerModule2Client; begin dm.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try try if FModel.CDSCadastroCid_Codigo.AsInteger <= 0 then raise Exception.Create('Informe o Código!'); if FModel.CDSCadastroCid_Nome.AsString = '' then raise Exception.Create('Informe o Nome!'); Post; Negocio.Salvar(CCidade, AIdUsuario); FModel.CDSCadastro.ApplyUpdates(0); FOperacao := opNavegar; dm.Desconectar; except on E: Exception do begin dm.ErroConexao(E.Message); end; end; finally FreeAndNil(Negocio); end; end; end.
PROGRAM TestRemove(INPUT, OUTPUT); {Программа тестирует модуль Queue: 1) Записывает в Q INPUT 2) Выводит Q в OUTPUT} USES Queue; VAR Ch: CHAR; BEGIN {TestRemove} EmptyQ; WHILE NOT EOLN DO BEGIN READ(Ch); AddQ(Ch) END; WRITE('Вход: '); WriteQ; EmptyQ; WRITE('Выход: '); WriteQ END. {TestRemove}
unit vcmHistory; {* Объект, реализующий работу с историей приложения. } { Библиотека "vcm" } { Автор: Люлин А.В. © } { Модуль: vcmHistory - } { Начат: 06.06.2003 15:58 } { $Id: vcmHistory.pas,v 1.185 2012/10/26 14:14:26 lulin Exp $ } // $Log: vcmHistory.pas,v $ // Revision 1.185 2012/10/26 14:14:26 lulin // {RequestLink:406489593} // // Revision 1.184 2012/09/29 15:24:43 lulin // {RequestLink:397301416} // // Revision 1.183 2012/09/29 10:20:53 lulin // {RquestLink:397279284} // // Revision 1.182 2012/09/29 09:13:43 lulin // - чистка кода. // // Revision 1.181 2012/07/11 18:25:09 lulin // {RequestLink:237994598} // // Revision 1.180 2012/07/10 12:27:03 lulin // {RequestLink:237994598} // // Revision 1.179 2012/07/04 15:22:31 lulin // - переименовываем безликое поле, чтобы хоть как-то было понятно. // // Revision 1.178 2012/05/29 14:28:44 lulin // {RequestLink:367212011} // // Revision 1.177 2012/04/13 14:37:25 lulin // {RequestLink:237994598} // // Revision 1.176 2012/04/09 08:38:54 lulin // {RequestLink:237994598} // - думаем о VGScene. // // Revision 1.175 2012/02/08 15:06:50 lulin // - защищаемся от падений при очистки истории в тестах. // // Revision 1.174 2012/02/01 17:25:10 lulin // {RequestLink:332566811} // // Revision 1.173 2012/02/01 16:20:23 lulin // {RequestLink:332566005} // // Revision 1.172 2012/01/27 17:49:44 lulin // {RequestLink:321989072} // // Revision 1.171 2012/01/25 18:31:40 lulin // {RequestLink:326773370} // - вставляем Assert в странную ветку логики. // // Revision 1.170 2012/01/25 16:43:02 lulin // {RequestLink:326773370} // // Revision 1.169 2012/01/24 16:30:02 lulin // {RequestLink:330139744} // - вставляем диагностику на предмет того, что формы не могут иметь одинаковые идентификаторы. // - избавляемся от нетипизированных списков. // // Revision 1.168 2011/10/24 10:12:00 gensnet // http://mdp.garant.ru/pages/viewpage.action?pageId=268347831 // // Revision 1.167 2011/09/28 09:19:23 lulin // {RequestLink:284164589}. // // Revision 1.166 2011/06/15 12:15:26 lulin // {RequestLink:267324195}. // // Revision 1.165 2011/04/21 13:06:04 lulin // {RequestLink:236719181}. // // Revision 1.164 2011/03/28 17:19:55 lulin // {RequestLink:257393788}. // // Revision 1.163 2011/03/25 17:28:53 lulin // {RequestLink:259168102}. // // Revision 1.162 2010/06/21 11:09:39 lulin // {RequestLink:219121927}. // - неправильная логика - это не повод для падений. // // Revision 1.161 2010/04/30 15:15:42 lulin // {RequestLink:207389954}. // - чистка комментариев. // // Revision 1.160 2010/03/10 12:48:39 lulin // {RequestLink:193826739}. // // Revision 1.159 2010/03/04 12:13:52 lulin // {RequestLink:193826739}. // // Revision 1.158 2010/02/02 16:09:43 lulin // {RequestLink:185828256}. Попытка анализа ситуации. // // Revision 1.157 2009/10/20 17:30:06 lulin // {RequestLink:159360578}. №4. // // Revision 1.156 2009/10/16 15:14:24 lulin // {RequestLink:159360578}. №52. // // Revision 1.155 2009/10/16 11:19:53 lulin // - вычищаем очередного коня в вакууме. // // Revision 1.154 2009/10/01 15:59:30 lulin // {RequestLink:159360578}. №47. // // Revision 1.153 2009/09/30 15:22:58 lulin // - убираем ненужное приведение ко вполне понятным интерфейсам. // // Revision 1.152 2009/08/13 13:38:54 lulin // - вставляем assert на ненужные данные. // // Revision 1.151 2009/08/12 12:09:48 lulin // - правильнее определяем зону формы. // // Revision 1.150 2009/08/06 16:08:13 lulin // {RequestLink:159352843}. // // Revision 1.149 2009/05/20 10:27:22 migel // - add: обрезание истории при шаге назад. // // Revision 1.148 2009/04/21 12:47:49 lulin // [124453728]. Обрабатываем Back/Forward. // // Revision 1.147 2009/03/24 14:19:47 oman // - fix: Боремся с историей и оптимизацией создания сборок - [$140281380] // // Revision 1.146 2009/03/06 10:01:40 oman // - fix: При утилизации форм не сообщали об укладке в историю (К-138547424) // // Revision 1.145 2009/02/20 15:18:56 lulin // - <K>: 136941122. // // Revision 1.144 2009/02/20 10:08:34 lulin // - чистка комментариев. // // Revision 1.143 2009/02/16 12:59:41 lulin // - <K>: 135604584. // // Revision 1.142 2009/02/12 16:06:46 lulin // - <K>: 135604584. Выделен модуль локализации. // // Revision 1.141 2009/02/12 12:26:37 lulin // - <K>: 135604584. Выделен новый интерфейсный модуль. // // Revision 1.140 2009/02/10 10:05:36 oman // - fix: При утилизации форм сносим им сначала ds (К-136262540) // // Revision 1.139 2009/01/30 13:51:32 lulin // - чистка кода. // // Revision 1.138 2008/12/12 19:19:23 lulin // - <K>: 129762414. // // Revision 1.137 2008/05/14 12:46:24 mmorozov // - new behaviour: при возврате по истории проверяем необходимость показа вкладки предупреждения (CQ: OIT5-29048); // // Revision 1.136 2008/03/20 09:48:17 lulin // - cleanup. // // Revision 1.135 2008/03/19 14:23:42 lulin // - cleanup. // // Revision 1.134 2008/02/07 19:13:02 lulin // - избавляемся от излишне универсальных методов базовых списков. // // Revision 1.133 2008/02/07 15:41:24 lulin // - базовый класс списков переехал в отдельный модуль. // // Revision 1.132 2008/01/31 18:53:32 lulin // - избавляемся от излишней универсальности списков. // // Revision 1.131 2007/12/21 07:34:33 mmorozov // - new: подписка на уведомление об обновлении данных (CQ: OIT5-27823); // // Revision 1.130 2007/07/17 08:28:23 oman // - fix: Некорректная обработка vcmParams.ItemIndex (cq25684) // // Revision 1.129 2007/06/28 14:56:11 lulin // - cleanup. // // Revision 1.128 2007/06/22 13:09:42 mmorozov // - new behaviour: на время нахождения сборки в истории запрещаем выполнять обновление представления, при этот все поступающие запросы на обновление регистрируются и будут выполнены когда сборку откроют из истории, после загрузки всех форм (в рамках CQ: OIT5-25280, по плану изменений описанному в K<7438844>); // // Revision 1.127 2007/05/21 13:33:16 lulin // - cleanup. // // Revision 1.126 2007/05/08 14:18:37 demon // - new: property IvcmHistory.InProcess - история находится в процессе сохранения (между сколбками _Start-Finish) // // Revision 1.125 2007/04/10 13:29:07 lulin // - bug fix: не собиралась библиотека. // // Revision 1.124 2007/03/20 07:50:38 lulin // - теперь у формы заголовок поддерживает различные кодировки (отрисовка пока не изменена). // // Revision 1.123 2007/03/12 12:36:18 lulin // - cleanup. // // Revision 1.122 2007/02/12 16:40:27 lulin // - переводим на строки с кодировкой. // // Revision 1.121 2007/02/02 12:25:37 lulin // - переводим на строки с кодировкой. // // Revision 1.120 2007/01/20 19:11:34 lulin // - запрещаем править поле с данными у параметров. // // Revision 1.119 2007/01/20 15:31:07 lulin // - разделяем параметры операции для выполнения и для тестирования. // // Revision 1.118 2007/01/18 11:47:38 oman // - new: Локализация библиотек - vcm (cq24078) // // Revision 1.117 2007/01/17 18:47:31 lulin // - сужаем список параметров для тестирования операции. // // Revision 1.116 2007/01/10 13:58:44 lulin // - от параметра по индексу переходим к свойству в параметрах операции. // // Revision 1.115 2007/01/10 11:57:50 lulin // - cleanup. // // Revision 1.114 2006/12/10 16:35:34 lulin // - cleanup. // // Revision 1.113 2006/11/03 11:00:29 lulin // - объединил с веткой 6.4. // // Revision 1.112.2.1 2006/10/19 08:49:08 oman // warning fix // // Revision 1.112 2006/07/14 13:48:32 mmorozov // - new: реализация элемента истории - _TvcmObjectWithDataHistoryItem; // - new: сохрение в истории данных бизнес объекта прецедента; // - new behaviour: при записи в историю форм с изменившимися _DataSource также пишем закрытые формы сборки; // - bugfix: не к меcту выполненный абстрактный метод (CQ: OIT500021865); // // Revision 1.111 2006/07/13 13:28:51 mmorozov // - change: IvcmHistoryItem перенесен в vcmInterfaces; // - new: у бизнес объекта прецедента появилось понятие данные; // // Revision 1.110 2006/07/11 14:16:37 mmorozov // - change: базывый элемент IvcmHistoryItem попилен на два, появился _IvcmFormHistoryItem; // - change: один из методов Back теперь _HasInPreviousStep; // // Revision 1.109 2006/06/19 11:55:31 oman // - fix: Откат предыдущих изменений по (CQ: OIT500021332), которые точно приводили к AV в КЗ // внутри сборки и появлению ряда скользких мест (cq21369) // // Revision 1.108 2006/06/16 08:36:10 mmorozov // - new behaviour: при выгрузке формы из истории сначала устанавливаем источник данных потом грузим данные формы и контролов (CQ: OIT500021332); // // Revision 1.107 2006/02/02 14:48:48 mmorozov // new: вычисление модуля в котором зарегистрирована формы, по классу формы; // change: убрано указание модуля при создании формы; // // Revision 1.106 2005/11/17 08:37:52 mmorozov // - bugfix: при определенной ситуации были проблемы с элементами истории связанными со сборкой, сделан контейнер, который правильным образом активирует элементы истории; // // Revision 1.105 2005/11/01 15:20:35 mmorozov // bugfix: формирование идентификатора формы элемента истории (класс формы не используется, т.к. для закрытых форм он не определен); // // Revision 1.104 2005/10/21 14:23:41 mmorozov // change: переименована функция; // // Revision 1.103 2005/10/18 08:29:51 mmorozov // new: методы истории расширены параметром aSubUserType, который используется при поиске/инициализации формы; // bugfix: не правильно инициализировался TvcmHistoryItemPrim в TvcmHistory._SaveClose; // // Revision 1.102 2005/09/28 18:16:23 mmorozov // new: в ChangedDataSource подается параметр aFromHistory; // // Revision 1.101 2005/09/28 16:00:15 mmorozov // - bugfix; // // Revision 1.100 2005/09/28 13:31:14 mmorozov // new behaviour: если форма входит в сборку, то для поиска используется троица UserType, ZoneType, _FormId; // // Revision 1.99 2005/09/23 10:10:19 lulin // - bug fix: при шагании по истории не изменялся _DataSource формы. // // Revision 1.98 2005/09/22 14:13:54 mmorozov // - не компилировался пакет; // // Revision 1.97 2005/09/22 11:06:00 mmorozov // - работа с историей в контексте сборок; // // Revision 1.96 2005/08/25 12:52:29 lulin // - new behavior: по возможности используем не имена, а индексы форм. // // Revision 1.95 2005/08/25 10:24:09 lulin // - new behavior: теперь в историю сохраняется _DataSource от формы. // // Revision 1.94 2005/04/28 15:03:52 lulin // - переложил ветку B_Tag_Box в HEAD. // // Revision 1.93 2005/04/26 07:24:21 dinishev // Merge с веткой // // Revision 1.92 2005/04/22 13:26:48 dinishev // new function: IsLast // // Revision 1.91.10.2 2005/04/25 11:37:16 dinishev // Bug fix: небыло инициализации флага множественного прохода + флаг выставляется и при переходе по истории вперед. // // Revision 1.91.10.1 2005/04/25 09:03:41 lulin // - объединил с HEAD. // // Revision 1.92 2005/04/22 13:26:48 dinishev // new function: IsLast // // Revision 1.91 2005/01/18 13:28:11 lulin // - new behavior: вызовы _SaveState/LoadState при смене контента стали парными (CQ OIT5-10983). // // Revision 1.90 2005/01/18 12:16:01 lulin // - обновлена документация. // // Revision 1.89 2005/01/18 11:18:07 lulin // - убрано ненужное исключение. // // Revision 1.88 2005/01/18 10:58:39 lulin // - спрятаны ненужные пользователю методы. // // Revision 1.87 2005/01/18 10:13:46 lulin // - поправлено форматирование. // // Revision 1.86 2005/01/18 10:06:32 lulin // - cleanup: убран ненужный закомментированный код. // // Revision 1.85 2005/01/14 10:42:27 lulin // - методы Get*ParentForm переехали в библиотеку AFW. // // Revision 1.84 2004/12/23 07:27:54 lulin // - перевел обработку статусной строки на библиотеку AFW. // // Revision 1.83 2004/12/07 14:56:45 mmorozov // - не компилировалась библиотека; // // Revision 1.82 2004/12/07 11:54:17 lulin // - new method: _Tl3LongintList.IndexOf. // // Revision 1.81 2004/10/13 16:20:47 mmorozov // new: в _NeedSaveForm используется g_MenuManager._HistoryZones; // // Revision 1.80 2004/10/08 14:30:33 lulin // - задел на вымещение истории на диск. // // Revision 1.79 2004/10/05 11:35:05 am // change: TvcmHistory.Back(aFormClass, UserType) стала функцией и теперь возвращает bool признак: удалось ли откатиться по истории, пропустив формы, переданные в параметрах. // // Revision 1.78 2004/10/01 08:37:26 lulin // - new behavior: количество шагов истории теперь ограничен переменной g_vcmHistoryLimit. // // Revision 1.77 2004/09/30 15:24:22 lulin // - new var: g_vcmHistoryLimit - пока ни на что не влияет. // // Revision 1.76 2004/09/27 14:08:22 am // new: IvcmHistory.Back(aFormClass: _TvcmFormID; aUserType: TvcmUserType = vcm_utAny) - сделать шаг по истории назад и идти, пока FormClass и UserType совпадают с соотв. свойствами форм в истории // // Revision 1.75 2004/09/17 11:22:54 lulin // - параметр vcm_opStrings переименован в _vcm_opItems, и ему изменен тип с _IvcmHolder на IvcmStrings (!). // // Revision 1.74 2004/09/07 16:19:41 law // - перевел VCM на кшированные обьекты. // // Revision 1.73 2004/09/01 14:48:53 demon // - new behavior: из операций IvcmDispatcher BeginOp/EndOp убраны вызовы _StoreFocus/_RestoreFocus. Где требовалось сохранение фокуса эти вызовы вставлены явно. // // Revision 1.72 2004/07/12 17:20:30 law // - bug fix: не освобождался интерфейс. // // Revision 1.71 2004/06/02 12:18:56 law // - change: список форм сделан сортированным. // // Revision 1.70 2004/06/02 11:45:38 nikitin75 // в истории запоминаем/восстанавливаем фокус // // Revision 1.69 2004/06/02 10:20:37 law // - удален конструктор Tl3VList.MakeIUnknown - пользуйтесь _Tl3InterfaceList._Make. // // Revision 1.68 2004/06/01 14:56:31 law // - удалены конструкторы Tl3VList.MakeLongint, MakeLongintSorted - пользуйтесь _Tl3LongintList. // // Revision 1.67 2004/05/24 12:32:56 law // - new behavior: если форма находится в списке добавленных и руками дернули ее сохранение, то сохраняем ее независимо от того в какой зоне она находится (CQ OIT5-6887). // // Revision 1.66 2004/04/01 13:44:37 law // - bug fix: поиск по истории при _MakeSingleChild не учитывал GUID формы (CQ OIT5-6957). // // Revision 1.65 2004/03/31 14:19:13 law // - new behavior: при создании формы из истории, если есть контейнер, то используем _MakeSingleChild. // // Revision 1.64 2004/03/25 08:56:41 law // - change: изменен тип параметра anOwner. // // Revision 1.63 2004/03/23 13:43:49 mmorozov // bugfix; // // Revision 1.62 2004/03/22 12:37:38 law // - bug fix: по Back не сохранялись дополнительные формы (Навигатор и т.п.) (CQ OIT5-6094). // // Revision 1.61 2004/02/26 14:35:30 demon // - new: реализация операции Reset в TvcmHistoryItemRec (дополнительно перебираем _f_Children и f_Docked) // // Revision 1.60 2004/02/25 12:15:47 demon // - new: реализация интерфейса IvcmDataReset и метода Reset на IvcmHistory // // Revision 1.59 2004/01/10 14:28:38 law // - new behavior: Обрезание названий списков в истории (CQ OIT5-4706). // // Revision 1.58 2003/12/26 16:51:15 law // - new behavior: переделана логика обработки BottonCombo - теперь если меню нету, то и стрелки вниз нету. // - bug fix: иногда при восстановлении из истории портился _Caption главного окна. // // Revision 1.57 2003/12/26 11:05:37 law // - change: добавлен комментарий. // // Revision 1.56 2003/12/26 10:57:27 law // - bug fix: неправильно работала история с ППР (CQ OIT5-5685). // // Revision 1.55 2003/12/25 15:56:06 law // - new behavior: вставил _Lock/Unlock в Back/Forward. // // Revision 1.54 2003/12/24 11:41:23 law // - bug fix: разобрался с бардаком History и MainForm (CQ IOT5-5526). // // Revision 1.53 2003/12/04 15:54:43 law // - new event: _TvcmEntityForm.OnGetStatus. // // Revision 1.52 2003/11/26 17:33:41 law // - bug fix: учитвыаем, что _Container не может быть = nil, а может быть IsNull. // // Revision 1.51 2003/11/11 17:09:16 law // - new behavior: для закрываемой формы сохраняем Content, а не Position. // // Revision 1.50 2003/10/27 15:22:59 law // - new behavior: при записи формы в историю, не спрашиваем CloseQuery - так ка сделан механизм отложеннного удаления форм. // // Revision 1.49 2003/10/23 16:24:25 law // - bug fix: запись не в ту историю. // // Revision 1.48 2003/10/23 15:09:49 law // - new behavior: History теперь знает про MainForm, что более правильно. // // Revision 1.47 2003/10/22 15:37:00 law // - new behavior: вызываем BeginOp/EndOp при обработке Back/Forward (проблема с отложенным удалением форм). // // Revision 1.46 2003/10/08 12:06:09 law // - new param: IvcmDispatcher.UpdateStatus - aSender. // // Revision 1.45 2003/09/23 10:32:03 law // - bug fix: автоматические формы писались в историю, хотя больше ничего не менялось (OIT5-4743). // // Revision 1.44 2003/09/22 12:32:38 law // - bug fix: теперь форма при смене контента сохраняет все свои дочерние формы. // // Revision 1.43 2003/09/22 10:20:19 law // - change: реструкторизовал иерархию записей истории. // // Revision 1.42 2003/09/22 09:33:16 law // - bug fix: переключение между закладками в синхронном просмотре сохраняло мусор в историю. // // Revision 1.41 2003/09/18 14:27:01 law // - bug fix: изменен порядок сохранения/восстановления форм (теперь дочерние формы восстанавливаются после родительской). // // Revision 1.40 2003/09/17 16:08:58 law // - new behavior: создаем форму, если не нашли ее при восстановлении Content. // // Revision 1.39 2003/09/17 14:31:29 law // - bug fix: в историю записывался неправильный _Caption (OIT5-4654). // // Revision 1.38 2003/09/17 11:39:34 law // - new behavior: корректно автосохраняются формы. // // Revision 1.37 2003/09/17 09:07:06 law // - bug fix: был неправильный _Caption после автоматического сохранения форм. // // Revision 1.36 2003/09/17 08:56:59 law // - new behavior: автоматически сохраняем указанные формы. // // Revision 1.35 2003/09/16 17:05:12 law // - new methods: IvcmHistory.AddForm, _RemoveForm (пока только добавляют,удпляют формы, но не записывают их при _Start). // // Revision 1.34 2003/09/16 11:37:12 law // - new behavior: убрана проверка необходимости записи формы в историю внутри операторных скобок. // // Revision 1.33 2003/09/15 17:09:12 law // - new behavior: реализована функциональность методов _Start и Finish. // // Revision 1.32 2003/09/15 15:31:27 law // - new methods: IvcmHistory._Start, Finish (пока ничего не делают). // // Revision 1.31 2003/09/12 16:38:15 law // - bug fix: при Back/Forward проверяем возможность закрытия формы. // // Revision 1.30 2003/09/12 13:44:51 demon // - bug fix: вставлено место для проверки возможности закрытия формы. // // Revision 1.29 2003/09/10 13:09:15 law // - bug fix: не компилировалось без опции _vcmNeedL3. // // Revision 1.28 2003/09/08 14:46:34 law // - new behavior: сделано обрезание длины строк истории и их количества. // // Revision 1.27 2003/09/04 10:11:07 law // - bug fix: при путешествии по истории неправильно восстанавливались названия форм. // // Revision 1.26 2003/09/03 14:04:30 law // - change: добавлен тип TvcmStateType (задел на сохранение перехода по локальным ссылкам). // // Revision 1.25 2003/09/03 09:53:45 law // - new behavior: реализован список истории по _Caption'ам форм. // // Revision 1.24 2003/09/03 08:07:38 law // - new methods versions: IvcmHistory.Back, Forward. // // Revision 1.23 2003/09/03 07:36:59 law // - new: реализованы операции IvcmHistory.GetBackStrings, GetForwardStrings (пока вместо _Caption выводятся цифры). // // Revision 1.22 2003/09/02 17:21:13 law // - new method: IvcmHistory.GetBacLines (пока fake). // // Revision 1.21 2003/07/24 13:07:12 law // - new prop: IvcmOperationDef._ExcludeUserTypes. // // Revision 1.20 2003/07/21 13:31:09 law // - bug fix: не обрезался "хвост" истории. // // Revision 1.19 2003/07/15 16:19:45 law // - new behavior: строка статуса очищается при удалении формы, которая записывается в историю. // // Revision 1.18 2003/07/02 15:20:08 law // - new prop: IvcmEntityForm.UserType - поле, которое характеризует некий тип формы и записывается в историю. // // Revision 1.17 2003/07/01 14:16:57 law // - new method: IvcmHistory._SaveState. // // Revision 1.16 2003/06/30 15:39:40 law // - cleanup: удаление возможности подмены Owner'а у _TvcmEntityForm. // // Revision 1.15 2003/06/27 14:25:06 law // - new prop: TvcmMainForm._HistoryZones. // - new behavior: не восстанавливаем по новой формы, которые уже восстановили (почему они два раза пишутся в историю - надо разбираться отдельно). // // Revision 1.14 2003/06/23 15:31:35 law // - cleanup. // // Revision 1.13 2003/06/23 15:14:36 law // Задел на восстановление Owner'а форм при операциях Back/Forward: // - remove method: IvcmFormDispatcher.FindContainer. // - new method: IvcmFormDispatcher._FindForm. // // Revision 1.12 2003/06/23 15:03:21 law // - change: свойство IvcmContainer.GUID переехало в IvcmEntityForm.GUID - теперь каждая форма имеет свой идентификатор. // - remove interface: IvcmGUIDSetter. // - new param: конструктор _TvcmEntityForm._Make имее еще один параметр - aGUID - для восстановления идентификатора формы при операциях Back/Forward. // // Revision 1.11 2003/06/23 14:27:04 law // - new behavior: теперь контейнер восстанавливает свой GUID при операциях Back/Forward. // // Revision 1.10 2003/06/23 13:54:17 law // - bug fix: не очищалось поле _f_Container. // // Revision 1.9 2003/06/23 13:45:10 law // - new prop: IvcmEntityForm._Module. // // Revision 1.8 2003/06/23 13:37:27 law // - new behavior: сделано запоминание контейнера при операциях Back/Forward. // // Revision 1.7 2003/06/23 12:37:12 law // - new behavior: восстанавливаем агрегацию при операциях Back/Forward. // // Revision 1.6 2003/06/23 11:52:46 law // - bug fix: не работала история (Back/Forward). Пока не запоминается аггрегация и насильно установленный контейнер. // // Revision 1.5 2003/06/19 11:46:00 law // - bug fix: не работала история навигации. До конца не починено - сейчас восстанавливается только самая верхняя форма. // // Revision 1.4 2003/06/09 14:01:01 law // - new behavior: история запоминает зону, куда была вставлена уничтожаемая форма. // // Revision 1.3 2003/06/06 15:49:51 law // - new methods: IvcmHistory.CanBack, CanForward. // // Revision 1.2 2003/06/06 14:22:44 law // - new methods: Back, Forward. // // Revision 1.1 2003/06/06 12:56:27 law // - new prop: IvcmDispathcher.History. // - new behavior: сохранение форм в истории по их закрытии (пока до конца не доделано). // {$Include vcmDefine.inc } interface {$IfNDef NoVCM} uses l3IID, l3Interfaces, vcmExternalInterfaces, vcmUserControls, vcmInterfaces, vcmBase, vcmIEntityFormPtrList ; type IvcmFormHistoryItem = interface(IvcmHistoryItem) ['{E222914E-C670-4076-B662-9CB403B711EB}'] {* Элемент истории для хранения данных формы. } // property methods function pm_GetFormClass: TvcmFormId; {-} function pm_GetUserType: TvcmUserType; {-} function pm_GetItemType : TvcmHistoryItemType; {* - тип элемента истории. } // public properties property FormClass: TvcmFormId read pm_GetFormClass; {* - класс формы, который содержит данный элемент. } property UserType: TvcmUserType read pm_GetUserType; {* - пользовательский тип формы, который содержит данный элемент. } property ItemType : TvcmHistoryItemType read pm_GetItemType; {* - тип элемента истории. } end;//IvcmFormHistoryItem IvcmContainerHistoryItem = interface(IvcmHistoryItem) {* Элемент истории приложения, состоящий из нескольких подзаписей. } ['{A8ABFC1F-E4A9-4B26-BB55-28C9427B6124}'] // public methods function Add(const anItem: IvcmHistoryItem; aDelta: Integer): Boolean; {* - добавляет подзапись. } function IsEmpty: Boolean; {* - есть ли в контейнере записи. } function ItemsCount: Integer; {* - количество записей в контейнере. } function GetItem(anIndex: Integer): IvcmHistoryItem; {* - элемент контейнера. } end;//IvcmContainerHistoryItem IvcmInternalHistory = interface(IvcmHistory) {* Внутренний интерфес для доступа к истории приложения. } ['{E27F90D6-DAA3-4227-AB8B-B56D4D251553}'] // public methods function SaveState(const aForm : IvcmEntityForm; aStateType : TvcmStateType; InDestroy : Boolean; aForceSave : Boolean = False): Boolean; overload; {* - сохраняет уничтожаемую форму. } end;//IvcmInternalHistory TvcmHistory = class(TvcmCacheableBase, IvcmHistory, IvcmInternalHistory) {* Объект, реализующий работу с историей приложения. } private // internal fields f_History : TvcmInterfaceList; f_Last : Boolean; {* - признак того, что вызов последний. } f_Multy : Boolean; {* - скобки для множественного вызова Back из одноименной процедуры. } f_Current : Integer; f_InBF : Boolean; f_InBack : Boolean; f_Starts : Integer; f_ForceSave : Boolean; f_ContainerItem : IvcmContainerHistoryItem; f_Forms : TvcmIEntityFormPtrList; f_Delta : Integer; f_MainForm : Pointer; protected // property methods function pm_GetMainForm: IvcmEntityForm; {-} protected // interface methods // IvcmHistory function pm_GetInBF: Boolean; {-} function InBack: Boolean; {-} function pm_GetInProcess: Boolean; {-} function NeedSaveForm(const aForm : IvcmEntityForm; InDestroy : Boolean): Boolean; {* - нужно ли сохранять заданную форму. } procedure BeforeFormDestroy(const aForm: IvcmEntityForm); {* - сохраняет уничтожаемую форму. } function CheckAnother(const aForm : IvcmEntityForm; out theHistory : IvcmHistory): Boolean; {* - проверяет от этой ли формы история, и если не от этой, то возвращает правильную историю. } function ForceSaveState(const aForm : IvcmEntityForm; aStateType : TvcmStateType = vcm_stContent): Boolean; {* - сохранение без проверки необходимости сохранения формы. } function SaveState(const aForm : IvcmEntityForm; aStateType : TvcmStateType = vcm_stContent): Boolean; overload; {* - сохраняет форму. } function SaveState(const aForm : IvcmEntityForm; aStateType : TvcmStateType; InDestroy : Boolean; aForceSave : Boolean = False): Boolean; overload; {* - сохраняет уничтожаемую форму. } procedure SaveClose(const aForm : IvcmEntityForm; const aFormId : TvcmFormId; aUserType : TvcmUserType; aZoneType : TvcmZoneType; aSubUserType : TvcmUserType); {* - форма которая должна быть закрыта при переходе по истории. } function Back(aTruncate: Boolean = False): Boolean; overload; {* - назад по истории. } function Forward: Boolean; overload; {* - вперед по истории. } function HasInPreviousStep(const aFormClass : TvcmFormID; aUserType : TvcmUserType = vcm_utAny): Boolean; {* Если мы дошли до формы, не удовлетворяющей переданным параметрам, возвращает True. } procedure Back(const aParams: IvcmExecuteParamsPrim; aTruncate: Boolean = False); overload; {* - назад по истории на N шагов. N лежит в 0-м параметре aParams. } procedure Forward(const aParams: IvcmExecuteParamsPrim); overload; {* - вперед по истории на N шагов. N лежит в 0-м параметре aParams. } function CanBack: Boolean; {* - можно ли двигаться по истории назад. } function CanForward: Boolean; {* - можно ли двигаться по истории вперед. } procedure GetBackStrings(const aParams: IvcmTestParamsPrim); {* - возвращает список шагов истории назад. } procedure GetForwardStrings(const aParams: IvcmTestParamsPrim); {* - возвращает список шагов истории вперед. } function GetBackCount: Integer; function GetForwardCount: Integer; function GetBackItem(anIndex: Integer): Il3CString; function GetForwardItem(anIndex: Integer): Il3CString; function GetCaption(anIndex: Integer): IvcmCString; {* - возвращает название одного шага истории. } procedure Start(const aSender : IvcmEntityForm; const aCaption : IvcmCString = nil; aFormSet : Boolean = False); {* - начинает процесс записи в историю (работает как скобка). } procedure Finish(const aSender : IvcmEntityForm); {* - заканчмвает процесс записи в историю (работает как скобка). } function Add(const anItem: IvcmHistoryItem): Boolean; {* - добавляет запись в историю. } procedure AddForm(const aForm: IvcmEntityForm); {* - регистрирует форму для автоматической записи в историю. } procedure RemoveForm(const aForm: IvcmEntityForm); {* - дерегистрирует форму для автоматической записи в историю. } function IsLast: Boolean; {* - проверка, является ли функция конечной. } procedure Clear(aHeedCheckCurrent : Boolean = true); {-} procedure DeleteBackItem; {-} protected // internal methods procedure Cleanup; override; {-} public // public methods constructor Create(const aMainForm: IvcmEntityForm); reintroduce; {* - создает объект истории. } public // public properties property MainForm: IvcmEntityForm read pm_GetMainForm; {* - главная форма приложения, к которой привязан данный объект истории. } end;//TvcmHistory (* IvcmObjectWithDataHistoryItem = interface ['{A3A15899-9BD4-46BB-9F83-87918A8EC5BC}'] end;//IvcmObjectWithDataHistoryItem*) // Это всё попытки залечить http://mdp.garant.ru/pages/viewpage.action?pageId=267324195 // но дело оказалось не в этом TvcmObjectWithDataHistoryItem = class(TvcmBase, IvcmHistoryItem (* , IvcmObjectWithDataHistoryItem*) // Это всё попытки залечить http://mdp.garant.ru/pages/viewpage.action?pageId=267324195 // но дело оказалось не в этом ) private // internal fields f_Object : IvcmObjectWithData; f_Data : IvcmData; private // internal methods procedure DoActivate; {-} private // IvcmHistoryItem function pm_GetCaption: IvcmCString; {-} procedure Activate(const aMainForm : IvcmEntityForm); overload; {* - активизирет данные элемента в приложении. } procedure Activate(const aMainForm : IvcmEntityForm; const anOwner : IvcmEntityForm); overload; {* - активизирет данные элемента в приложении. } function Drop: Boolean; {* - сбросить запись на диск. } public // methods constructor Create(const aObject : IvcmObjectWithData; const aData : IvcmData); reintroduce; {-} class function Make(const aObject : IvcmObjectWithData; const aData : IvcmData): IvcmHistoryItem; {-} (* function COMQueryInterface(const IID: Tl3GUID; out Obj): Tl3HResult; override; {-}*) // Это всё попытки залечить http://mdp.garant.ru/pages/viewpage.action?pageId=267324195 // но дело оказалось не в этом end;//TvcmObjectWithDataHistoryItem var g_vcmHistoryLimit : Integer = High(Integer); {* Лимит количества записей в истории приложения. } g_LockHistory : Integer = 0; {$EndIf NoVCM} implementation {$IfNDef NoVCM} uses Windows, Classes, SysUtils, Controls, Forms, l3MinMax, l3Base, l3String, afwFacade, vcmInternalInterfaces, vcmExcept, vcmAggregate, vcmEntityForm, vcmForm, vcmMainForm, vcmBaseMenuManager, vcmUtils, vcmTaskPanelInterfaces, vcmHistoryRes ; // start class TvcmHistoryItemBase type TvcmHistoryItemBase = class(TvcmCacheableBase, IvcmFormHistoryItem) private // internal fields f_FormClass : RvcmEntityForm; f_FormId : TvcmFormId; f_Caption : IvcmCString; f_Focused : String; f_FormData : IvcmBase; f_FormGUID : TGUID; f_ZoneType : TvcmZoneType; f_Aggregate : PGUID; f_ContainerGUID : PGUID; f_Owner : PGUID; f_UserType : TvcmUserType; f_DataSource : IvcmFormDataSource; f_ItemType : TvcmHistoryItemType; f_SubUserType : TvcmUserType; protected // interface methods // IvcmFormHistoryItem function pm_GetCaption: IvcmCString; {-} function pm_GetFormClass: TvcmFormId; {-} function pm_GetUserType: TvcmUserType; {-} function pm_GetItemType : TvcmHistoryItemType; {* - тип элемента истории. } procedure Activate(const aMainForm : IvcmEntityForm); overload; {-} procedure Activate(const aMainForm : IvcmEntityForm; const anOwner : IvcmEntityForm); overload; {-} procedure DoActivate(const aMainForm : IvcmEntityForm; const anOwner : IvcmEntityForm); virtual; abstract; {-} function Drop: Boolean; {* - сбросить запись на диск. } procedure UpdateContainer(const aForm: IvcmEntityForm); {* - устанавливает контейнер формы. } procedure UpdateOwner(const aForm: IvcmEntityForm); {* - устанавливает владельца формы. } procedure UpdateAggregate(const aForm: IvcmEntityForm); {* - меняет агрегацию формы. } procedure UpdateFormInfo(const aForm: IvcmEntityForm); {* - обновляет информацию формы. } procedure FreeContainer; {-} procedure FreeOwner; {-} procedure FreeAggregate; {-} function Container(const aMainForm: IvcmEntityForm): IvcmContainer; {-} protected // internal methods procedure Cleanup; override; {-} function MakeForm(const aMainForm : IvcmEntityForm; const anOwner : IvcmEntityForm; const aDataSource : IvcmFormDataSource): IvcmEntityForm; {-} procedure StoreFocused(const aForm : IvcmEntityForm); {-} procedure RestoreFocused(const aForm : IvcmEntityForm); {-} public // public methods constructor Create(const aForm : IvcmEntityForm; const aStateType : TvcmStateType; const aFormId : TvcmFormId; const aUserType : TvcmUserType; const aZoneType : TvcmZoneType; const aItemType : TvcmHistoryItemType; const aSubUserType : TvcmUserType); reintroduce; virtual; {-} class function Make(const aForm : IvcmEntityForm; const aStateType : TvcmStateType): IvcmFormHistoryItem; overload; {-} class function Make(const aForm : IvcmEntityForm; const aStateType : TvcmStateType; const aFormId : TvcmFormId; const aUserType : TvcmUserType; const aZoneType : TvcmZoneType; const aItemType : TvcmHistoryItemType; const aSubUserType : TvcmUserType): IvcmFormHistoryItem; overload; {-} function COMQueryInterface(const IID: Tl3GUID; out Obj): Tl3HResult; override; {-} end;//TvcmHistoryItemBase procedure TvcmHistoryItemBase.UpdateContainer(const aForm: IvcmEntityForm); begin if not aForm.Container.IsNull then begin if not Assigned(f_ContainerGUID) then New(f_ContainerGUID); f_ContainerGUID^ := aForm.Container.AsForm.GUID; end//not l_Container.IsNull else FreeContainer; end; procedure TvcmHistoryItemBase.UpdateOwner(const aForm: IvcmEntityForm); var l_Owner: TComponent; begin l_Owner := aForm.VCLWinControl.Owner; if (l_Owner Is TvcmEntityForm) then begin if not Assigned(f_Owner) then New(f_Owner); f_Owner^ := TvcmEntityForm(l_Owner).As_IvcmEntityForm.GUID; end//l_Owner Is TvcmEntityForm else FreeOwner; end; procedure TvcmHistoryItemBase.FreeContainer; begin if Assigned(f_ContainerGUID) then begin Dispose(f_ContainerGUID); f_ContainerGUID := nil; end; end; procedure TvcmHistoryItemBase.FreeOwner; begin if Assigned(f_Owner) then begin Dispose(f_Owner); f_Owner := nil; end; end; function TvcmHistoryItemBase.Container(const aMainForm: IvcmEntityForm): IvcmContainer; {-} var l_Form: IvcmEntityForm; begin if (f_ContainerGUID = nil) then Result := aMainForm.AsContainer else if g_Dispatcher.FormDispatcher.FindForm(f_ContainerGUID^, l_Form) then begin Assert(not l_Form.VCMClosing); // - если форма УЖЕ закрывается, то её наверное повторно использовать НЕЛЬЗЯ Result := l_Form.AsContainer end//g_Dispatcher.FormDispatcher.FindForm(f_ContainerGUID^, l_Form) else begin Result := aMainForm.AsContainer; Assert(false, Format('А возможна ли такая ситуация, что у формы "%s" не нашёлся контейнер, который запомнили. И правильная ли она? http://mdp.garant.ru/pages/viewpage.action?pageId=326773370&focusedCommentId=330698389#comment-330698389', [f_FormClass.ClassName])); end;//g_Dispatcher.FormDispatcher.FindForm(f_ContainerGUID^, l_Form) end; procedure TvcmHistoryItemBase.FreeAggregate; begin if Assigned(f_Aggregate) then begin Dispose(f_Aggregate); f_Aggregate := nil; end;//Assigned(f_Aggregate) end; procedure TvcmHistoryItemBase.UpdateAggregate(const aForm: IvcmEntityForm); begin if Assigned(aForm.Aggregate) then begin if not Assigned(f_Aggregate) then New(f_Aggregate); f_Aggregate^ := aForm.Aggregate.GUID; end//aForm.Aggregate <> nil else FreeAggregate; end; procedure TvcmHistoryItemBase.UpdateFormInfo(const aForm: IvcmEntityForm); begin if Assigned(aForm) then begin f_FormClass := RvcmEntityForm(aForm.VCLWinControl.ClassType); f_Caption := aForm.{VCLForm.}MainCaption; f_FormGUID := aForm.GUID; f_DataSource := aForm.DataSource; UpdateAggregate(aForm); UpdateContainer(aForm); UpdateOwner(aForm); end;//Assigned(aForm) end; type EvcmFormWasClosedInSave = class(Exception) end;//EvcmFormWasClosedInSave constructor TvcmHistoryItemBase.Create(const aForm : IvcmEntityForm; const aStateType : TvcmStateType; const aFormId : TvcmFormId; const aUserType : TvcmUserType; const aZoneType : TvcmZoneType; const aItemType : TvcmHistoryItemType; const aSubUserType : TvcmUserType); // reintroduce; // overload; // virtual; {-} var l_PrevVCMClosing : Boolean; l_NowVCMClosing : Boolean; begin inherited Create; f_ZoneType := aZoneType; f_UserType := aUserType; f_FormId := aFormId; f_ItemType := aItemType; f_SubUserType := aSubUserType; StoreFocused(aForm); if Assigned(aForm) then begin UpdateFormInfo(aForm); l_PrevVCMClosing := aForm.VCMClosing; if not aForm.SaveState(f_FormData, aStateType) then begin l_NowVCMClosing := aForm.VCMClosing; if l_NowVCMClosing then begin Assert(not l_PrevVCMClosing); f_FormClass := nil; end;//aForm.VCMClosing f_FormData := nil; if l_NowVCMClosing then raise EvcmFormWasClosedInSave.Create('Форма была закрыта во время сохранения'); end;//not aForm.SaveState(f_FormData, aStateType) end;//if Assigned(aForm) then end; function TvcmHistoryItemBase.COMQueryInterface(const IID: Tl3GUID; out Obj): Tl3HResult; //override; {-} var l_FormSet: IvcmFormSet; begin Result := inherited COMQueryInterface(IID, Obj); if Result.Fail then begin if IID.EQ(IvcmFormSet) and vcmInFormSet(f_DataSource, @l_FormSet) then begin IvcmFormSet(Obj) := l_FormSet; Result.SetOK; end//if IID.EQ(IvcmFormSet) else Result.SetNOINTERFACE; end;//if l3IFail(Result) then end; class function TvcmHistoryItemBase.Make(const aForm : IvcmEntityForm; const aStateType : TvcmStateType; const aFormId : TvcmFormId; const aUserType : TvcmUserType; const aZoneType : TvcmZoneType; const aItemType : TvcmHistoryItemType; const aSubUserType : TvcmUserType): IvcmFormHistoryItem; // overload; {-} var lTemp: TvcmHistoryItemBase; begin lTemp := Create(aForm, aStateType, aFormId, aUserType, aZoneType, aItemType, aSubUserType); try Result := lTemp; finally FreeAndNil(lTemp); end;//try..finally end; (*class function TvcmHistoryItemBase.Make(const aFormId : TvcmFormId; const aUserType : TvcmUserType; const aZoneType : TvcmZoneType; const aItemType : TvcmHistoryItemType; const aSubUserType : TvcmUserType): IvcmFormHistoryItem; // overload; {-} begin Result := Make(nil, vcm_stContent, aFormId, aUserType, aZoneType, aItemType, aSubUserType); end;*) class function TvcmHistoryItemBase.Make(const aForm : IvcmEntityForm; const aStateType : TvcmStateType): IvcmFormHistoryItem; {-} var l_Form : TvcmEntityForm; begin l_Form := (aForm.VCLWinControl As TvcmEntityForm); Result := Make(aForm, aStateType, l_Form.FormID, l_Form.UserType, l_Form.ZoneType, vcm_hitNone, l_Form.SubUserType); end; procedure TvcmHistoryItemBase.Cleanup; //override; {-} begin f_DataSource := nil; f_FormData := nil; f_Caption := nil; FreeContainer; FreeOwner; FreeAggregate; inherited; end; function TvcmHistoryItemBase.MakeForm(const aMainForm : IvcmEntityForm; const anOwner : IvcmEntityForm; const aDataSource : IvcmFormDataSource): IvcmEntityForm; {-} var l_Container : IvcmContainer; l_Aggregate : IvcmAggregate; l_Owner : IvcmEntityForm; begin Result := nil; // Если элемента не было до этого, то при переходе назад он должен быть удален f_ItemType := vcm_hitClose; (*if (f_FormData = nil) then Result := nil else*) // !!! - закомментрировал, т.к. иначе неправильно сохранялись формы-контейнеры begin l_Container := Container(aMainForm); if (f_Aggregate = nil) then l_Aggregate := nil else l_Aggregate := TvcmAggregate.Make(f_Aggregate); if (anOwner = nil) then begin if (f_Owner = nil) then l_Owner := nil else begin if g_Dispatcher.FormDispatcher.FindForm(f_Owner^, l_Owner) then Assert(not l_Owner.VCMClosing); // - если форма УЖЕ закрывается, то её наверное повторно использовать НЕЛЬЗЯ end;//f_Owner = nil end//anOwner = nil else l_Owner := anOwner; if (l_Container <> nil) AND not l_Container.IsNull then Result := f_FormClass.MakeSingleChild(l_Container, vcmMakeParams(l_Aggregate, l_Container, l_Owner.VCLWinControl), f_ZoneType, f_UserType, @f_FormGUID, aDataSource, f_SubUserType) else Result := f_FormClass.Make(vcmMakeParams(l_Aggregate, l_Container, l_Owner.VCLWinControl), f_ZoneType, f_UserType, @f_FormGUID, aDataSource, f_SubUserType); end;//f_FormData = nil end; procedure TvcmHistoryItemBase.StoreFocused(const aForm : IvcmEntityForm); {-} var l_Form, l_Parent, l_Control : TWinControl; begin f_Focused := ''; if Assigned(aForm) and Assigned(aForm.VCLWinControl) then begin l_Form := aForm.VCLWinControl; l_Control := FindControl(Windows.GetFocus); if Assigned(l_Control) then begin l_Parent := l_Control.Parent; while Assigned(l_Parent) do if l_Parent = l_Form then begin f_Focused := l_Control.Name; break; end else if l_Parent is TCustomForm then break else l_Parent := l_Parent.Parent; end; end; end; procedure TvcmHistoryItemBase.RestoreFocused(const aForm : IvcmEntityForm); {-} var l_Control : TWinControl; begin if (f_Focused <> '') and Assigned(aForm) and Assigned(aForm.VCLWinControl) then begin l_Control := aForm.VCLWinControl.FindComponent(f_Focused) as TWinControl; if Assigned(l_Control) then g_Dispatcher.StoreFocused(l_Control.Handle); end;//f_Focused <> ''.. end; procedure TvcmHistoryItemBase.Activate(const aMainForm : IvcmEntityForm); //overload; {-} begin Activate(aMainForm, nil); end; procedure TvcmHistoryItemBase.Activate(const aMainForm : IvcmEntityForm; const anOwner : IvcmEntityForm); //overload; {-} var l_SaveSelf : IUnknown; begin l_SaveSelf := Self; try DoActivate(aMainForm, anOwner); finally l_SaveSelf := nil; end;//try..finally end; function TvcmHistoryItemBase.Drop: Boolean; {* - сбросить запись на диск. } begin Result := False; end; function TvcmHistoryItemBase.pm_GetCaption: IvcmCString; {-} begin Result := f_Caption; end; // start class TvcmHistoryItemRec type TvcmHistoryItemRec = class(TvcmHistoryItemBase) private // internal fields f_Children : TvcmInterfaceList; f_Docked : TvcmInterfaceList; protected // internal methods procedure Cleanup; override; {-} function MakeChild(const aForm : IvcmEntityForm; aStateType : TvcmStateType): IvcmFormHistoryItem; virtual; abstract; {-} procedure SaveOwned(const aForm : IvcmEntityForm; aStateType : TvcmStateType; out aList : TvcmInterfaceList); {-} procedure SaveDocked(const aForm : IvcmEntityForm; aStateType : TvcmStateType; out aList : TvcmInterfaceList); {-} procedure ActivateList(const aMainForm : IvcmEntityForm; const aForm : IvcmEntityForm; aList : TvcmInterfaceList; const aInFormSet : Boolean); {-} public // public methods constructor Create(const aForm : IvcmEntityForm; const aStateType : TvcmStateType; const aFormId : TvcmFormId; const aUserType : TvcmUserType; const aZoneType : TvcmZoneType; const aItemType : TvcmHistoryItemType; const aSubUserType : TvcmUserType); override; {-} end;//TvcmHistoryItemRec constructor TvcmHistoryItemRec.Create(const aForm : IvcmEntityForm; const aStateType : TvcmStateType; const aFormId : TvcmFormId; const aUserType : TvcmUserType; const aZoneType : TvcmZoneType; const aItemType : TvcmHistoryItemType; const aSubUserType : TvcmUserType); //reintroduce; {-} begin try inherited Create(aForm, aStateType, aFormId, aUserType, aZoneType, aItemType, aSubUserType); except on EvcmFormWasClosedInSave do // - форму закрыли в процессе сохранения // Например БП из-за: // http://mdp.garant.ru/pages/viewpage.action?pageId=321989072&focusedCommentId=330698655#comment-330698655 begin f_Caption := aForm.MainCaption; FreeAndNil(f_Children); FreeAndNil(f_Docked); f_ItemType := vcm_hitClose; end;//on EvcmFormWasClosedInSave end;//try..except if Assigned(aForm) then begin f_Caption := aForm.MainCaption; FreeAndNil(f_Children); FreeAndNil(f_Docked); SaveOwned(aForm, aStateType, f_Children); SaveDocked(aForm, aStateType, f_Docked); end;//Assigned(aForm) end; procedure TvcmHistoryItemRec.Cleanup; //override; {-} begin FreeAndNil(f_Children); FreeAndNil(f_Docked); inherited; end; procedure TvcmHistoryItemRec.SaveOwned(const aForm : IvcmEntityForm; aStateType : TvcmStateType; out aList : TvcmInterfaceList); {-} procedure l_SaveOwned(aControl: TComponent); var l_Index : Integer; l_Child : TComponent; l_Form : IvcmEntityForm; begin//SaveOwned with aControl do for l_Index := 0 to Pred(ComponentCount) do begin l_Child := Components[l_Index]; if (l_Child Is TCustomForm) AND Supports(l_Child, IvcmEntityForm, l_Form) then try if (aList = nil) then aList := TvcmInterfaceList.Make; aList.Add(MakeChild(l_Form, aStateType)); finally l_Form := nil; end;//try..finally end;//for l_Index end;//l_SaveOwned var l_OwnerForm : TWinControl; begin aList := nil; if not Assigned(aForm.FormSet) and (aStateType = vcm_stContent) then begin l_OwnerForm := aForm.VCLWinControl; l_SaveOwned(l_OwnerForm); end;//aStateType = vcm_stContent end; procedure TvcmHistoryItemRec.SaveDocked(const aForm : IvcmEntityForm; aStateType : TvcmStateType; out aList : TvcmInterfaceList); {-} var l_OwnerForm : TWinControl; procedure l_SaveDocked(aControl: TWinControl); var l_Index : Integer; l_Child : TControl; l_Form : IvcmEntityForm; begin//l_SaveDocked with aControl do for l_Index := 0 to Pred(ControlCount) do begin l_Child := Controls[l_Index]; if (l_Child Is TCustomForm) AND (l_Child.Owner <> l_OwnerForm) AND Supports(l_Child, IvcmEntityForm, l_Form) then try if (aList = nil) then aList := TvcmInterfaceList.Make; aList.Add(MakeChild(l_Form, aStateType)); finally l_Child := nil; end;//try..finally if (l_Child Is TWinControl) then l_SaveDocked(TWinControl(l_Child)); end;//for l_Index end;//l_SaveDocked begin aList := nil; if not Assigned(aForm.FormSet) and (aStateType = vcm_stContent) then begin l_OwnerForm := aForm.VCLWinControl; l_SaveDocked(l_OwnerForm); end;//aStateType = vcm_stContent end; procedure TvcmHistoryItemRec.ActivateList(const aMainForm : IvcmEntityForm; const aForm : IvcmEntityForm; aList : TvcmInterfaceList; const aInFormSet : Boolean); {-} var l_Index : Integer; begin if not aInFormSet and (aList <> nil) then with aList do for l_Index := Lo to Hi do IvcmFormHistoryItem(Items[l_Index]).Activate(aMainForm, aForm); end; // start class TvcmHistoryItemPrim type TvcmHistoryItemPrim = class(TvcmHistoryItemRec) private // internal fields f_StateType : TvcmStateType; protected // interface methods procedure DoActivate(const aMainForm : IvcmEntityForm; const anOwner : IvcmEntityForm); override; {-} function MakeChild(const aForm : IvcmEntityForm; aStateType : TvcmStateType): IvcmFormHistoryItem; override; {-} public // public methods constructor Create(const aForm : IvcmEntityForm; const aStateType : TvcmStateType; const aFormId : TvcmFormId; const aUserType : TvcmUserType; const aZoneType : TvcmZoneType; const aItemType : TvcmHistoryItemType; const aSubUserType : TvcmUserType); override; {-} end;//TvcmHistoryItemPrim constructor TvcmHistoryItemPrim.Create(const aForm : IvcmEntityForm; const aStateType : TvcmStateType; const aFormId : TvcmFormId; const aUserType : TvcmUserType; const aZoneType : TvcmZoneType; const aItemType : TvcmHistoryItemType; const aSubUserType : TvcmUserType); //reintroduce; {-} begin inherited Create(aForm, aStateType, aFormId, aUserType, aZoneType, aItemType, aSubUserType); f_StateType := aStateType; end; function TvcmHistoryItemPrim.MakeChild(const aForm : IvcmEntityForm; aStateType : TvcmStateType): IvcmFormHistoryItem; //override; {-} begin Result := Make(aForm, aStateType); end; procedure TvcmHistoryItemPrim.DoActivate(const aMainForm : IvcmEntityForm; const anOwner : IvcmEntityForm); //overload; {-} function lpFindForm(out aForm: IvcmEntityForm): Boolean; begin//lpFindForm if vcmInFormSet(f_DataSource) then begin Result := Container(aMainForm).HasForm(f_FormId, f_ZoneType, True, @aForm, f_UserType, nil, f_SubUserType); if Result then Assert(not aForm.VCMClosing); // - если форма УЖЕ закрывается, то её наверное повторно использовать НЕЛЬЗЯ end//vcmInFormSet(f_DataSource) else begin Result := g_Dispatcher.FormDispatcher.FindForm(f_FormGUID, aForm); if Result then begin //Assert(not aForm.VCMClosing); if aForm.VCMClosing then // - если форма УЖЕ закрывается, то её наверное повторно использовать НЕЛЬЗЯ begin g_Dispatcher.FormDispatcher.RemoveForm(aForm); // - удалить её надо из диспетчера, чтобы больше не находилась aForm := nil; Result := false; end;//aForm.VCMClosing end;//Result end;//vcmInFormSet(f_DataSource) end;//lpFindForm function lp_SameUseCase(const aForm: IvcmEntityForm): Boolean; begin//lp_SameUseCase Result := true; if Assigned(f_DataSource) and Assigned(f_DataSource.UseCaseController) and Assigned(aForm.DataSource) and Assigned(aForm.DataSource.UseCaseController) then Result := vcmIEQ(f_DataSource.UseCaseController, aForm.DataSource.UseCaseController); end;//lp_SameUseCase var l_FormData : IvcmBase; l_Form : IvcmEntityForm; l_Caption : IvcmCString; l_Children : TvcmInterfaceList; l_Docked : TvcmInterfaceList; l_DataSource : IvcmFormDataSource; l_UtilizeForm: Boolean; begin // Форма должна быть закрыта if f_ItemType = vcm_hitClose then begin aMainForm.AsContainer.HasForm(f_FormId, f_ZoneType, True, @l_Form, f_UserType, nil, f_SubUserType); if Assigned(l_Form) then try f_ItemType := vcm_hitContent; UpdateFormInfo(l_Form); if not l_Form.SaveState(l_FormData, f_StateType) then l_FormData := nil; f_FormData := l_FormData; l_Form.SafeClose; finally l_Form := nil; end;//try..finally end//if f_StateType = vcm_stMissing then // Создадим форму из истории else begin l_Children := nil; l_Docked := nil; try l_FormData := f_FormData; // Форма ничего не знает про тип if lpFindForm(l_Form) then begin // Форма была открыта в процессе работы l_UtilizeForm := True; if (f_ItemType = vcm_hitContent) then f_ItemType := vcm_hitNone; SaveOwned(l_Form, f_StateType, l_Children); SaveDocked(l_Form, f_StateType, l_Docked); if not l_Form.SaveState(l_FormData, f_StateType) then // - сохраняем данные, для симметричности вызовов SaveState/LoadState. l_FormData := nil; end//lpFindForm(l_Form) else begin l_Form := MakeForm(aMainForm, anOwner, f_DataSource); if (l_Form = nil) then Exit; l_Children := nil; l_Docked := nil; // Форма должна быть закрыта f_ItemType := vcm_hitClose; l_UtilizeForm := False; end;//lpFindForm(l_Form) l_Caption := l_Form.{VCLForm.}MainCaption; //l_Form.DataSource := f_DataSource; // ^Если ты бля такой умный и хочешь переставить эту строчку сюда, // то читай внимательно - http://mdp.garant.ru/pages/viewpage.action?pageId=267324195&focusedCommentId=269072024#comment-269072024 l_Form.LoadState(f_FormData, f_StateType); l_Form.Caption := f_Caption; RestoreFocused(l_Form); f_Caption := l_Caption; // Только для форм без сборки, сборка сама контролирует запись в историю ActivateList(aMainForm, l_Form, f_Children, Assigned(l_Form.FormSet)); ActivateList(aMainForm, nil, f_Docked, Assigned(l_Form.FormSet)); l_DataSource := l_Form.DataSource; // Если утилизируем форму снесем ей сначала DataSource // чтоб эмулировать удаление/создание K-136262540 if l_UtilizeForm then begin if l_Form.IsMainInFormSet and not lp_SameUseCase(l_Form) then l_Form.FormSet.PopToHistory; l_Form.DataSource := nil; end;//l_UtilizeForm l_Form.DataSource := f_DataSource; f_DataSource := l_DataSource; f_FormData := l_FormData; // - устанавливаем новые данные формы vcmSet(f_Children, l_Children); // - устанавливаем информацию о новых детях vcmSet(f_Docked, l_Docked); // - устанавливаем информацию о новых подчиненных if (f_ItemType = vcm_hitContent) then f_ItemType := vcm_hitClose; finally FreeAndNil(l_Children); FreeAndNil(l_Docked); end;//try..finally end;//if f_StateType = vcm_stMissing then end; // start class TvcmHistoryItem type TvcmHistoryItem = class(TvcmHistoryItemRec) protected // interface methods // IvcmFormHistoryItem procedure DoActivate(const aMainForm : IvcmEntityForm; const anOwner : IvcmEntityForm); override; {-} protected // internal methods function MakeChild(const aForm : IvcmEntityForm; aStateType : TvcmStateType): IvcmFormHistoryItem; override; {-} public // public methods class function Make(const aForm : IvcmEntityForm; aStateType : TvcmStateType; InDestroy : Boolean): IvcmFormHistoryItem; reintroduce; {-} end;//TvcmHistoryItem class function TvcmHistoryItem.Make(const aForm : IvcmEntityForm; aStateType : TvcmStateType; InDestroy : Boolean): IvcmFormHistoryItem; {-} var l_Item : TvcmHistoryItem; begin if InDestroy then begin g_Dispatcher.UpdateStatus; with (aForm.VCLWinControl As TvcmEntityForm) do l_Item := Self.Create(aForm, aStateType, FormId, UserType, ZoneType, vcm_hitNone, SubUserType); try Result := l_Item; finally FreeAndNil(l_Item); end;//try..finally end//InDestroy else Result := TvcmHistoryItemPrim.Make(aForm, aStateType); end; function TvcmHistoryItem.MakeChild(const aForm : IvcmEntityForm; aStateType : TvcmStateType): IvcmFormHistoryItem; //override; {-} begin Result := Make(aForm, aStateType, true); end; procedure TvcmHistoryItem.DoActivate(const aMainForm : IvcmEntityForm; const anOwner : IvcmEntityForm); //overload; {-} var l_Form : IvcmEntityForm; l_Caption : IvcmCString; l_DataSource : IvcmFormDataSource; begin if g_Dispatcher.FormDispatcher.FindForm(f_FormGUID, l_Form) then begin //Assert(not l_Form.VCMClosing); // - если форма УЖЕ закрывается, то её наверное повторно использовать НЕЛЬЗЯ if not l_Form.VCMClosing then // - например это ОДНО ОМ уже ЗАКРЫВАЕТСЯ, а хочется создать НОВОЕ // http://mdp.garant.ru/pages/viewpage.action?pageId=332566005 Exit // - форма уже восстановлена else g_Dispatcher.FormDispatcher.RemoveForm(l_Form); // - удалить её надо из диспетчера, чтобы больше не находилась end;//g_Dispatcher.FormDispatcher.FindForm(f_FormGUID, l_Form) l_Form := MakeForm(aMainForm, anOwner, nil); if (f_FormClass <> nil) then Assert(l_Form <> nil, Format('А может ли тут быть такое, что форма не создана? FormClass = %s Caption = %s', [f_FormClass.ClassName, l3Str(f_Caption)])); if (l_Form = nil) then Exit; l_Caption := l_Form.{VCLForm.}MainCaption; l_Form.LoadState(f_FormData, vcm_stContent); l_Form.Caption := f_Caption; l_DataSource := l_Form.DataSource; l_Form.DataSource := f_DataSource; f_DataSource := l_DataSource; RestoreFocused(l_Form); f_Caption := l_Caption; ActivateList(aMainForm, l_Form, f_Children, Assigned(l_Form.FormSet)); ActivateList(aMainForm, nil, f_Docked, Assigned(l_Form.FormSet)); end;//DoActivate // start class TvcmHistory constructor TvcmHistory.Create(const aMainForm: IvcmEntityForm); //reintroduce; {-} begin inherited Create; f_MainForm := Pointer(aMainForm); f_Last := True; end;//Create procedure TvcmHistory.Cleanup; //override; {-} begin f_ContainerItem := nil; f_MainForm := nil; f_Current := 0; FreeAndNil(f_History); FreeAndNil(f_Forms); inherited; end;//Cleanup function TvcmHistory.pm_GetMainForm: IvcmEntityForm; {-} begin Result := IvcmEntityForm(f_MainForm); end;//pm_GetMainForm function TvcmHistory.pm_GetInBF: Boolean; {-} begin Result := f_InBF; end;//pm_GetInBF function TvcmHistory.InBack: Boolean; {-} begin Result := f_InBack; end; function TvcmHistory.pm_GetInProcess: Boolean; {-} begin Result := (f_Starts <> 0); end; function TvcmHistory.NeedSaveForm(const aForm : IvcmEntityForm; InDestroy : Boolean) : Boolean; {-} var l_Main : IvcmEntityForm; l_VMain : TvcmMainForm; l_Container : IvcmContainer; l_Form : IvcmEntityForm; begin Result := False; if (aForm = nil) then Exit; if f_ForceSave AND not InDestroy then begin Result := true; Exit; end;//f_ForceSave.. l_Main := MainForm; if (l_Main = nil) then Exit; try l_VMain := (l_Main.VCLWinControl As TvcmMainForm); l_Form := aForm; l_Container := aForm.Container; while true do begin if (l_Container = nil) then Exit; if (l_Container.AsForm.VCLWinControl = l_VMain) then if (l_Form.ZoneType in g_MenuManager.HistoryZones) then break else Exit; l_Form := l_Container.AsForm; l_Container := l_Container.AsForm.Container; end;//while true Result := true; finally // - если форма находится в списке добавленных и руками дернули ее сохранение if not Result AND (f_Forms <> nil) then Result := (f_Forms.IndexOf(aForm) >= 0); end;//try..finally end;//NeedSaveForm var g_LockBeforeFormDestroy : Integer = 0; procedure TvcmHistory.BeforeFormDestroy(const aForm: IvcmEntityForm); {-} begin // Только для форм без сборки (сборка сама занимается сохранением) if not Assigned(aForm.FormSet) then SaveState(aForm, vcm_stContent, true) else if aForm.IsMainInFormSet then if (g_LockBeforeFormDestroy = 0) then with aForm.FormSet do begin PopToHistory; SaveHistory; end;//if aForm.IsMainInFormSet then end;//BeforeFormDestroy function TvcmHistory.CheckAnother(const aForm : IvcmEntityForm; out theHistory : IvcmHistory): Boolean; {-} var l_Form : TCustomForm; l_MainForm : IvcmMainForm; l_History : IvcmHistory; begin Result := False; if (aForm <> nil) then begin l_Form := (aForm.VCLWinControl As TCustomForm); while (l_Form <> nil) do begin if Supports(l_Form, IvcmMainForm, l_MainForm) then try l_History := l_MainForm.History; if not vcmIEQ(Self, l_History) then begin Result := true; theHistory := l_History; end;//not vcmIEQ(Self, l_History) break; finally l_MainForm := nil; end;//try..finally l_Form := afw.GetAnotherParentForm(l_Form); end;//while true end;//aForm = nil end;//CheckAnother function TvcmHistory.SaveState(const aForm : IvcmEntityForm; aStateType : TvcmStateType): Boolean; {-} begin Result := SaveState(aForm, aStateType, False); end; procedure TvcmHistory.SaveClose(const aForm : IvcmEntityForm; const aFormId : TvcmFormId; aUserType : TvcmUserType; aZoneType : TvcmZoneType; aSubUserType : TvcmUserType); {* - форма которая должна быть закрыта при переходе по истории. } var l_History : IvcmHistory; begin if CheckAnother(aForm, l_History) then (l_History As IvcmInternalHistory).SaveClose(aForm, aFormId, aUserType, aZoneType, aSubUserType) else Add(TvcmHistoryItemPrim.Make(aForm, vcm_stContent, aFormId, aUserType, aZoneType, vcm_hitClose, aSubUserType)); end; function TvcmHistory.ForceSaveState(const aForm : IvcmEntityForm; aStateType : TvcmStateType = vcm_stContent): Boolean; {* - сохранение без проверки необходимости сохранения формы. } begin Result := SaveState(aForm, aStateType, False, True); end; function TvcmHistory.SaveState(const aForm : IvcmEntityForm; aStateType : TvcmStateType; InDestroy : Boolean; aForceSave : Boolean = False): Boolean; //overload; {-} var l_History : IvcmHistory; begin if (g_LockHistory > 0) then Result := false else if CheckAnother(aForm, l_History) then Result := (l_History As IvcmInternalHistory).SaveState(aForm, aStateType, InDestroy) else begin if aForceSave or NeedSaveForm(aForm, InDestroy) then begin if InDestroy then Start(aForm); try Result := Add(TvcmHistoryItem.Make(aForm, aStateType, InDestroy)); finally if InDestroy then Finish(aForm); end;//try..finally end//NeedSaveForm else Result := False; end;//CheckAnother(aForm, l_History) end; function TvcmHistory.Add(const anItem: IvcmHistoryItem): Boolean; {-} var l_Index : Integer; begin if (f_ContainerItem <> nil) then begin Result := f_ContainerItem.Add(anItem, f_Delta); end//f_ContainerItem <> nil else begin if (f_History = nil) then f_History := TvcmInterfaceList.Make; if (f_Current >= f_History.Count) then Result := (f_History.Add(anItem) >=0) else begin Result := true; f_History[f_Current] := anItem; if not f_InBF then f_History.Count := Succ(f_Current); end; if not f_InBF then begin l_Index := 0; while (f_History.Count - l_Index > g_vcmHistoryLimit) do begin if IvcmHistoryItem(f_History[l_Index]).Drop then // - удалось выместить на диск Inc(l_Index) else begin f_History.Delete(l_Index); Dec(f_Current); end;//IvcmHistoryItem(f_History[l_Index]).Drop end;//f_History.Count > g_vcmHistoryLimit end;//not f_InBF Inc(f_Current); end;//f_ContainerItem <> nil end;//Add function TvcmHistory.Back(aTruncate: Boolean): Boolean; {-} var l_Current : Integer; l_Item : IvcmHistoryItem; begin Result := CanBack; if not f_Multy then f_Last := True; if Result then begin g_Dispatcher.FormDispatcher.Lock; try g_Dispatcher.StoreFocus; try g_Dispatcher.BeginOp; try Dec(f_Current); l_Current := f_Current; f_InBF := true; try f_InBack := true; l_Item := IvcmHistoryItem(f_History[l_Current]); l_Item.Activate(MainForm); // if aTruncate AND (l_Current >= 0) then f_History.Count := l_Current; finally f_InBF := False; end;//try..finally f_Current := l_Current; finally g_Dispatcher.EndOp; end;//try..finally finally g_Dispatcher.RestoreFocus; end;//try..finally finally g_Dispatcher.FormDispatcher.Unlock; end;//try..finally end;//f_Current > 0 end; function TvcmHistory.Forward: Boolean; {-} var l_Current : Integer; l_Item : IvcmHistoryItem; begin Result := CanForward; if not f_Multy then f_Last := True; if Result then begin g_Dispatcher.FormDispatcher.Lock; try g_Dispatcher.StoreFocus; try g_Dispatcher.BeginOp; try l_Current := f_Current; f_InBF := true; try f_InBack := false; l_Item := IvcmHistoryItem(f_History[l_Current]); l_Item.Activate(MainForm); finally f_InBF := False; end;//try..finally f_Current := Succ(l_Current); finally g_Dispatcher.EndOp; end;//try..finally finally g_Dispatcher.RestoreFocus; end;//try..finally finally g_Dispatcher.FormDispatcher.Unlock; end;//try..finally end;//f_Current >= 0 end; procedure TvcmHistory.Back(const aParams: IvcmExecuteParamsPrim; aTruncate: Boolean); //overload; {-} var l_To : Integer; begin l_To := aParams.ItemIndex; if (l_To <= 0) then l_To := 1; f_Multy := True; try f_Last := l_To = 1; while (l_To > 0) AND Back(aTruncate) do begin Dec(l_To); f_Last := l_To = 1; end; finally f_Multy := False; f_Last := True; end; end; procedure TvcmHistory.Forward(const aParams: IvcmExecuteParamsPrim); //overload; {-} var l_To : Integer; begin l_To := aParams.ItemIndex; if (l_To <= 0) then l_To := 1; f_Multy := True; f_Last := l_To = 1; try while (l_To > 0) AND Forward do begin Dec(l_To); f_Last := l_To = 1; end; finally f_Multy := False; f_Last := True; end; end; function TvcmHistory.CanBack: Boolean; {-} begin Result := (f_History <> nil) AND (f_Current > 0) AND (f_Current <= f_History.Count); end; function TvcmHistory.CanForward: Boolean; {-} begin Result := (f_History <> nil) AND (f_Current >= 0) AND (f_Current < f_History.Count); end; const cMaxCount = 10; procedure TvcmHistory.GetBackStrings(const aParams: IvcmTestParamsPrim); {-} var l_Index : Integer; begin with aParams.Op.SubItems do begin Clear; if (f_History <> nil) then for l_Index := Pred(f_Current) downto Max(f_Current - cMaxCount, 0) do Add(GetCaption(l_Index)); end;//with aParams.Op.SubItems end; procedure TvcmHistory.GetForwardStrings(const aParams: IvcmTestParamsPrim); {-} var l_Index : Integer; begin with aParams.Op.SubItems do begin Clear; if (f_History <> nil) then for l_Index := f_Current to Pred(Min(f_Current + cMaxCount, f_History.Count)) do Add(GetCaption(l_Index)); end;//with aParams.Op.SubItems end; function TvcmHistory.GetBackCount: Integer; begin Result := Max(f_Current, 0); end; function TvcmHistory.GetForwardCount: Integer; begin Result := Max(f_History.Count - f_Current, 0); end; function TvcmHistory.GetBackItem(anIndex: Integer): Il3CString; begin Result := GetCaption(GetBackCount - anIndex - 1); end; function TvcmHistory.GetForwardItem(anIndex: Integer): Il3CString; begin Result := GetCaption(GetBackCount + anIndex); end; function TvcmHistory.GetCaption(anIndex: Integer): IvcmCString; {-} const cCont = '...'; cLen = 73; var l_Res : String; begin if (f_History = nil) OR (anIndex < 0) OR (anIndex >= f_History.Count) then Result := str_vcmWrongHistoryElement.AsCStr else begin Result := IvcmHistoryItem(f_History[anIndex]).Caption; if vcmIsNil(Result) then Result := vcmCStr(IntToStr(Succ(anIndex))); end;//f_History = nil.. if (vcmLen(Result) > cLen) then begin l_Res := vcmStr(Result); SetLength(l_Res, cLen - Length(cCont)); Result := vcmCStr(l_Res + cCont); end;//Length(Result) end; type TvcmContainerHistoryItem = class(TvcmInterfaceList, IvcmHistoryItem, IvcmContainerHistoryItem) private // internal fields f_Caption : IvcmCString; private // interface methods // IvcmHistoryItem function pm_GetCaption: IvcmCString; {-} procedure Activate(const aMainForm : IvcmEntityForm); overload; {-} procedure Activate(const aMainForm : IvcmEntityForm; const anOwner : IvcmEntityForm); overload; virtual; {-} function Drop: Boolean; {* - сбросить запись на диск. } // IvcmContainerHistoryItem function Add(const anItem: IvcmHistoryItem; aDelta: Integer): Boolean; reintroduce; {-} function IsEmpty: Boolean; {-} function ItemsCount: Integer; {-} function GetItem(anIndex: Integer): IvcmHistoryItem; reintroduce; {-} procedure Cleanup; override; {-} public // public methods constructor Create(const aCaption: IvcmCString); reintroduce; {-} class function Make(const aCaption : IvcmCString): IvcmContainerHistoryItem; {-} end;//TvcmContainerHistoryItem TvcmContainerFormSetHistoryItem = class(TvcmContainerHistoryItem) {* - контейнер для хранения элементов истории сборки. } private // private methods procedure Activate(const aMainForm : IvcmEntityForm; const anOwner : IvcmEntityForm); overload; override; {-} end;//TvcmContainerFormSetHistoryItem constructor TvcmContainerHistoryItem.Create(const aCaption: IvcmCString); //reintroduce; {-} begin inherited Make; f_Caption := aCaption; end; class function TvcmContainerHistoryItem.Make(const aCaption : IvcmCString): IvcmContainerHistoryItem; {-} var l_Item : TvcmContainerHistoryItem; begin l_Item := Create(aCaption); try Result := l_Item; finally FreeAndNil(l_Item); end;//try..finally end; procedure TvcmContainerHistoryItem.Cleanup; //override; {-} begin f_Caption := nil; inherited; end; function TvcmContainerHistoryItem.pm_GetCaption: IvcmCString; {-} var l_Index : Integer; begin Result := f_Caption; l_Index := 0; while vcmIsNil(Result) AND (l_Index < ItemsCount) do begin Result := GetItem(l_Index).Caption; Inc(l_Index); end;//while (Result = '') end; procedure TvcmContainerHistoryItem.Activate(const aMainForm : IvcmEntityForm); //overload; {-} begin Activate(aMainForm, nil); end; procedure TvcmContainerHistoryItem.Activate(const aMainForm : IvcmEntityForm; const anOwner : IvcmEntityForm); //overload; {-} var l_SaveSelf : IUnknown; l_Index : Integer; begin l_SaveSelf := Self; try if not IsEmpty then for l_Index := Lo to Hi do IvcmHistoryItem(Items[l_Index]).Activate(aMainForm); finally l_SaveSelf := nil; end;//try..finally end; function TvcmContainerHistoryItem.Drop: Boolean; {* - сбросить запись на диск. } begin Result := False; end; function TvcmContainerHistoryItem.Add(const anItem: IvcmHistoryItem; aDelta: Integer): Boolean; {-} begin if (anItem = nil) then Result := False else begin Insert(Count - aDelta, IUnknown(anItem)); Result := true; end;//anItem = nil end; function TvcmContainerHistoryItem.IsEmpty: Boolean; {-} begin Result := Empty; end; function TvcmContainerHistoryItem.ItemsCount: Integer; {-} begin Result := Count; end; function TvcmContainerHistoryItem.GetItem(anIndex: Integer): IvcmHistoryItem; {-} begin Result := IvcmHistoryItem(Items[anIndex]); end; procedure TvcmHistory.Start(const aSender : IvcmEntityForm; const aCaption : IvcmCString = nil; aFormSet : Boolean = False); {-} var l_Index : Integer; l_Delta : Integer; l_History : IvcmHistory; l_Form : IvcmEntityForm; begin if CheckAnother(aSender, l_History) then l_History.Start(aSender) else begin if (f_Starts = 0) then begin Assert(aCaption = nil); // - проверяем необходимомсть параметра if not aFormSet then f_ContainerItem := TvcmContainerHistoryItem.Make(aCaption) else f_ContainerItem := TvcmContainerFormSetHistoryItem.Make(aCaption); end;//f_Starts = 0 Inc(f_Starts); if (f_Starts = 1) then begin f_Delta := 0; if (f_Forms <> nil) then begin f_ForceSave := true; try l_Delta := 0; with f_Forms do begin l_Index := 0; while (l_Index < Count) do begin l_Form := Items[l_Index]; if l_Form.InClose then begin if SaveState(l_Form, vcm_stContent) then Inc(l_Delta); end//l_Form.InClose else begin if SaveState(l_Form, vcm_stPosition) then Inc(l_Delta); end;//l_Form.InClose Inc(l_Index); end;//while (l_Index < Count) end;//with f_Forms f_Delta := l_Delta; finally f_ForceSave := False; end;//try..finally end;//f_Forms <> nil end;//f_Starts = 1 end;//CheckAnother(aForm, l_History) end; procedure TvcmHistory.Finish(const aSender : IvcmEntityForm); {-} var l_Container : IvcmContainerHistoryItem; l_History : IvcmHistory; begin if CheckAnother(aSender, l_History) then l_History.Finish(aSender) else begin Dec(f_Starts); if (f_Starts = 0) then begin l_Container := f_ContainerItem; f_ContainerItem := nil; if (l_Container <> nil) AND not l_Container.IsEmpty AND (l_Container.ItemsCount > f_Delta) then begin if (l_Container.ItemsCount > 1) then Add(l_Container) else Add(l_Container.GetItem(0)); end;//not l_Container.IsEmpty end;//f_Starts = 0 end;//CheckAnother(aSender, l_History) end; procedure TvcmHistory.AddForm(const aForm: IvcmEntityForm); {-} var l_History : IvcmHistory; begin if CheckAnother(aForm, l_History) then l_History.AddForm(aForm) else begin if (f_Forms = nil) then f_Forms := TvcmIEntityFormPtrList.MakeSorted; f_Forms.Add(aForm); end;//CheckAnother(aForm, l_History) end; procedure TvcmHistory.RemoveForm(const aForm: IvcmEntityForm); {-} var l_History : IvcmHistory; begin if CheckAnother(aForm, l_History) then begin if (l_History <> nil) then // здесь эта проверка нужна !!! l_History.RemoveForm(aForm) end else begin if (f_Forms <> nil) then f_Forms.Remove(aForm); end;//CheckAnother(aForm, l_History) end; function TvcmHistory.HasInPreviousStep(const aFormClass : TvcmFormID; aUserType : TvcmUserType = vcm_utAny): Boolean; var l_ContItem : IvcmContainerHistoryItem; l_Check : Boolean; l_Index : Integer; function Check(const aItem: IvcmHistoryItem): Boolean; var l_FormItem : IvcmFormHistoryItem; begin//Check Result := Supports(aItem, IvcmFormHistoryItem, l_FormItem) and not l_FormItem.FormClass.EQ(aFormClass) and ((aUserType = vcm_utAny) or (l_FormItem.UserType = aUserType)); end;//Check begin l_Check := true; while (f_Current > 0) do begin if Supports(f_History[f_Current - 1], IvcmContainerHistoryItem, l_ContItem) then begin l_Check := False; for l_Index := 0 to l_ContItem.ItemsCount - 1 do if Check(l_ContItem.GetItem(l_Index)) then begin l_Check := true; break; end;//Check(l_ContItem.GetItem(l_Index)) end//Supports(f_History[f_Current - 1], IvcmContainerHistoryItem, l_ContItem) else l_Check := Check(IvcmHistoryItem(f_History[f_Current - 1])); Back; if not l_Check then break; end;//while (f_Current > 0) Result := not l_Check; end;//Back function TvcmHistoryItemBase.pm_GetFormClass: TvcmFormId; begin Result := f_FormId; end;//pm_GetFormClass function TvcmHistoryItemBase.pm_GetItemType : TvcmHistoryItemType; {* - тип элемента истории. } begin Result := f_ItemType; end;//pm_GetItemType function TvcmHistoryItemBase.pm_GetUserType: TvcmUserType; begin Result := f_UserType; end;//pm_GetUserType function TvcmHistory.IsLast: Boolean; begin Result := f_Last; end;//IsLast procedure TvcmHistory.Clear(aHeedCheckCurrent : Boolean = true); {-} begin Assert(not f_InBF); Assert({$IfDef nsTest}not aHeedCheckCurrent OR {$EndIf}(f_Starts <= 0)); f_Starts := 0; f_Current := 0; if (f_History <> nil) then f_History.Clear; end; procedure TvcmHistory.DeleteBackItem; {-} begin Assert(not f_InBF); Assert(f_Starts <= 0); Assert(f_Current > 0); Assert(f_Current <= f_History.Count); Dec(f_Current); f_History.Delete(f_Current); end; { TvcmContainerFormSetHistoryItem } procedure TvcmContainerFormSetHistoryItem.Activate(const aMainForm : IvcmEntityForm; const anOwner : IvcmEntityForm); var l_SaveSelf : IUnknown; l_Index : Integer; l_List : TvcmInterfaceList; l_FormItem : IvcmFormHistoryItem; l_FormSet : IvcmFormSet; l_MainObjectForm : IvcmEntityForm; l_NeedLock : Boolean; begin l_SaveSelf := Self; try if not IsEmpty then begin l_NeedLock := false; if aMainForm.AsContainer.HasForm(vcm_ztMainObjectForm, true, @l_MainObjectForm) then begin if not l_MainObjectForm.IsMainInFormSet then l_MainObjectForm := l_MainObjectForm.Container.AsForm; if (l_MainObjectForm <> nil) then if (l_MainObjectForm.IsMainInFormSet) then begin l_NeedLock := true; g_Dispatcher.History.BeforeFormDestroy(l_MainObjectForm); end;//l_MainObjectForm.IsMainInFormSet end;//aMainForm.AsContainer.HasForm(vcm_ztMainObjectForm if l_NeedLock then Inc(g_LockBeforeFormDestroy); try l_List := TvcmInterfaceList.Make; try // Нам нужно получить FormSet до того как мы начнем активировать элементы, // т.к. в процессе активации данные элементов будут замененны: l_FormSet := nil; if (Hi >= 0) then Supports(Items[0], IvcmFormSet, l_FormSet); // Формы которые должны быть закрыты. Сохраняем сначала, поэтому что была // ситуация, когда в текущем и предыдущем шаге разные формы находились в // одном контейнере, при создании Формы1 существующая Форма2 удалялась и // когда доходили до элемента истории связанного с Формой2 он не заполнялся, // поскольку Формы2 уже не было (cq 00018103). Поэтому сначала сохраняются // формы, которые должны быть закрыты, потом создаются новые, или // перегружаются существующие. // for l_Index := Hi downto Lo do // for l_Index := Hi downto Lo do // - потому, что формы из сборки записываются рекурсивным обходом дерева // сборки и нам нужно сначала закрыть детей потом родителей, в которые // они вложены. if Supports(Items[l_Index], IvcmFormHistoryItem, l_FormItem) then begin with l_FormItem do if ItemType = vcm_hitClose then Activate(aMainForm) else // l_List.Insert(0, Items[l_Index]) - // - с точностью до наоборот, создаем родителей, потом детей. l_List.Insert(0, Items[l_Index]); end//Supports(Items[l_Index], IvcmFormHistoryItem, l_FormItem) (* else if Supports(Items[l_Index], IvcmObjectWithDataHistoryItem) then IvcmHistoryItem(Items[l_Index]).Activate(aMainForm)*) // Это всё попытки залечить http://mdp.garant.ru/pages/viewpage.action?pageId=267324195 // но дело оказалось не в этом ; // Формы которые должны быть созданы for l_Index := l_List.Lo to l_List.Hi do with IvcmHistoryItem(l_List.Items[l_Index]) do Activate(aMainForm); // Сообщим, что можно обновлять представление сборки: if l_FormSet <> nil then l_FormSet.PushFromHistory; finally FreeAndNil(l_List); end;//try..finally finally if l_NeedLock then Dec(g_LockBeforeFormDestroy); end;//try..finally end;//if not IsEmpty then finally l_SaveSelf := nil; end;//try..finally end; { TvcmObjectWithDataHistoryItem } procedure TvcmObjectWithDataHistoryItem.Activate(const aMainForm: IvcmEntityForm); // overload; {* - активизирет данные элемента в приложении. } begin DoActivate; end; procedure TvcmObjectWithDataHistoryItem.Activate(const aMainForm : IvcmEntityForm; const anOwner : IvcmEntityForm); // overload; {* - активизирет данные элемента в приложении. } begin DoActivate; end; constructor TvcmObjectWithDataHistoryItem.Create(const aObject : IvcmObjectWithData; const aData : IvcmData); begin inherited Create; f_Object := aObject; f_Data := aData; end; procedure TvcmObjectWithDataHistoryItem.DoActivate; var l_Temp: IvcmData; begin l_Temp := f_Object.DataForSave; f_Object.DataForSave := f_Data; f_Data := l_Temp; end; function TvcmObjectWithDataHistoryItem.Drop: Boolean; {* - сбросить запись на диск. } begin Result := False; end; class function TvcmObjectWithDataHistoryItem.Make(const aObject: IvcmObjectWithData; const aData: IvcmData): IvcmHistoryItem; var l_Class: TvcmObjectWithDataHistoryItem; begin l_Class := Create(aObject, aData); try Result := l_Class; finally FreeAndNil(l_Class); end; end; function TvcmObjectWithDataHistoryItem.pm_GetCaption: IvcmCString; begin Result := nil; end; (*function TvcmObjectWithDataHistoryItem.COMQueryInterface(const IID: Tl3GUID; out Obj): Tl3HResult; //override; {-} var l_DS : IvcmFormSetDataSource; begin Result := inherited COMQueryInterface(IID, Obj); if Result.Fail then begin if IID.EQ(IvcmObjectWithData) then begin IvcmObjectWithData(Obj) := f_Object; Result.SetOK; end//IID.EQ(IvcmObjectWithData) else if IID.EQ(IvcmFormSetDataSource) then begin if Supports(f_Object, IID.IID, Obj) then Result.SetOK; end//if IID.EQ(IvcmFormSetDataSource) else if IID.EQ(IvcmFormSet) then begin if Supports(f_Object, IvcmFormSetDataSource, l_DS) then begin IvcmFormSet(Obj) := l_DS.FormSet; if (IvcmFormSet(Obj) <> nil) then Result.SetOK; end;//Supports(f_Object, IvcmFormSetDataSource, l_DS) end//IID.EQ(IvcmFormSet) else Result.SetNOINTERFACE; end;//if l3IFail(Result) then end;*) // Это всё попытки залечить http://mdp.garant.ru/pages/viewpage.action?pageId=267324195 // но дело оказалось не в этом {$EndIf NoVCM} end.
unit SendToF; interface uses Windows, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, DBTables, DB, StdCtrls, Grids, DBGrids, ComCtrls, DBClient; type TForm1 = class(TForm) EditCapital: TEdit; EditPopulation: TEdit; EditArea: TEdit; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; ComboContinent: TComboBox; Button1: TButton; Button2: TButton; ComboName: TComboBox; cds: TClientDataSet; cdsName: TStringField; cdsCapital: TStringField; cdsContinent: TStringField; cdsArea: TFloatField; cdsPopulation: TFloatField; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure ComboNameKeyPress(Sender: TObject; var Key: Char); procedure ComboNameClick(Sender: TObject); private { Private declarations } public procedure GetData; procedure SendData; end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.GetData; begin cds.Locate ('Name', ComboName.Text, [loCaseInsensitive]); ComboName.Text := cdsName.AsString; EditCapital.Text := cdsCapital.AsString; ComboContinent.Text := cdsContinent.AsString; EditArea.Text := cdsArea.AsString; EditPopulation.Text := cdsPopulation.AsString; end; procedure TForm1.SendData; begin // raise an exception if there is no name if ComboName.Text = '' then raise Exception.Create ('Insert the name'); // check if the record is already in the table if cds.Locate ('Name', ComboName.Text, [loCaseInsensitive]) then begin // modify found record cds.Edit; cdsCapital.AsString := EditCapital.Text; cdsContinent.AsString := ComboContinent.Text; cdsArea.AsString := EditArea.Text; cdsPopulation.AsString := EditPopulation.Text; cds.Post; end else begin // insert new record cds.InsertRecord ([ComboName.Text, EditCapital.Text, ComboContinent.Text, EditArea.Text, EditPopulation.Text]); // add to list ComboName.Items.Add (ComboName.Text) end; end; procedure TForm1.Button1Click(Sender: TObject); begin GetData; end; procedure TForm1.Button2Click(Sender: TObject); begin SendData; end; procedure TForm1.FormCreate(Sender: TObject); begin // fill the list of names cds.Open; while not cds.Eof do begin ComboName.Items.Add (cdsName.AsString); cds.Next; end; end; procedure TForm1.ComboNameKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then GetData; end; procedure TForm1.ComboNameClick(Sender: TObject); begin GetData; end; end.
unit RTTIUtils; interface type // TTypeValidade = (NotNull, MinLength); // // Validade = class(TCustomAttribute) // private // public // constructor Create(TypeValidade : TTypeValidade); // end; NotNull = class(TCustomAttribute) private FMensagem: String; procedure SetMensagem(const Value: String); public constructor Create ( aMsg : String ); property Mensagem : String read FMensagem write SetMensagem; end; MinLength = class(TCustomAttribute) private FLength: Integer; FMsg: String; procedure SetLength(const Value: Integer); procedure SetMsg(const Value: String); public constructor Create( aLength : Integer; Msg : String); property Length : Integer read FLength write SetLength; property Msg : String read FMsg write SetMsg; end; TRTTIUtils = class private public class procedure ValidarCampos( aObject : TObject); end; implementation uses System.RTTI, System.SysUtils; { TRTTIUtils } class procedure TRTTIUtils.ValidarCampos(aObject: TObject); var ctxContext : TRttiContext; typRtti : TRttiType; prpRtti : TRttiProperty; cusAttr : TCustomAttribute; begin ctxContext := TRttiContext.Create; try typRtti := ctxContext.GetType(aObject.ClassType); for prpRtti in typRtti.GetProperties do for cusAttr in prpRtti.GetAttributes do begin if cusAttr is NotNull then begin case prpRtti.GetValue(aObject).TypeInfo.Kind of tkUString : begin if prpRtti.GetValue(aObject).AsString.Trim.IsEmpty then raise Exception.Create(NotNull(cusAttr).Mensagem); end; end; end; if cusAttr is MinLength then begin if Length(prpRtti.GetValue(aObject).AsString) < MinLength(cusAttr).Length then raise Exception.Create(MinLength(cusAttr).Msg); end; end; finally ctxContext.Free; end; end; { NotNull } constructor NotNull.Create(aMsg: String); begin FMensagem := aMsg; end; procedure NotNull.SetMensagem(const Value: String); begin FMensagem := Value; end; { MinLength } constructor MinLength.Create(aLength: Integer; Msg: String); begin FLength := aLength; FMsg := Msg; end; procedure MinLength.SetLength(const Value: Integer); begin FLength := Value; end; procedure MinLength.SetMsg(const Value: String); begin FMsg := Value; end; end.
{ You must register your application for "Show notifications in action center" "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Notifications\Settings\$prodName" -Name "ShowInActionCenter" -Type Dword -Value "1" } unit uNotify; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, System.Notification, Vcl.StdCtrls, System.Hash, System.Win.Registry, System.UITypes; type TfmMain = class(TForm) NotificationCenter1: TNotificationCenter; btnShowNotification: TButton; btnToggleActionCentre: TButton; lblAC: TLabel; lblRegKeyExists: TLabel; procedure btnShowNotificationClick(Sender: TObject); function getRegisterToastMessageKey : String; procedure btnToggleActionCentreClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); private { Private declarations } public { Public declarations } end; var fmMain: TfmMain; procedure InsertKeysToReg(HKey: Cardinal; OurRegKeyPath, ourKey: string; NewKeyValue: integer); procedure DeleteKeyFromReg(HKey: Cardinal; OurRegKeyPath: string); function DoesRegKeyExist: Boolean; procedure UpdateLabel; implementation var OurRegKeyPath: string; HKey: Cardinal = HKEY_CURRENT_USER; {$R *.dfm} procedure TfmMain.btnShowNotificationClick(Sender: TObject); var AppNotification: TNotification; begin AppNotification := NotificationCenter1.CreateNotification; try AppNotification.Name := 'Windows10Notification'; AppNotification.Title := 'Windows 10 Notification #1'; AppNotification.AlertBody := 'RAD Studio 10 Seattle'; NotificationCenter1.PresentNotification(AppNotification); finally AppNotification.Free; end; end; procedure TfmMain.btnToggleActionCentreClick(Sender: TObject); begin if btnToggleActionCentre.Caption = 'Enable' then begin btnToggleActionCentre.Caption := 'Disable'; InsertKeysToReg(HKey, OurRegKeyPath, 'ShowInActionCenter', 1); end else begin DeleteKeyFromReg(HKey, OurRegKeyPath); btnToggleActionCentre.Caption := 'Enable'; end; UpdateLabel; end; procedure TfmMain.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin if DoesRegKeyExist then begin if MessageDlg('Remove RegKey before Exit?', mtConfirmation, [mbYes, mbNo], 0) = mrYes then DeleteKeyFromReg(HKey, OurRegKeyPath); end; end; procedure TfmMain.FormCreate(Sender: TObject); begin UpdateLabel; end; procedure InsertKeysToReg(HKey: Cardinal; OurRegKeyPath, ourKey: string; NewKeyValue: integer); var reg : TRegistry; openResult : Boolean; begin reg := TRegistry.Create(KEY_READ OR KEY_WOW64_64KEY); reg.RootKey := HKey; //HKEY_USERS; //HKEY_LOCAL_MACHINE; { Checking if the values exist and inserting when neccesary } reg.Access := KEY_WRITE; openResult := reg.OpenKey(OurRegKeyPath, True); if not openResult = True then begin MessageDlg('Unable to create key! Exiting.', mtError, mbOKCancel, 0); Exit(); end; try //reg.RootKey := HKEY_CURRENT_USER; if reg.OpenKey(OurRegKeyPath, true) then try reg.WriteInteger(ourKey, NewKeyValue); finally reg.CloseKey; end; finally reg.Free; end; end; procedure DeleteKeyFromReg(HKey: Cardinal; OurRegKeyPath: string); var reg : TRegistry; begin reg := TRegistry.Create(KEY_WRITE); reg.RootKey := HKey; reg.DeleteKey(OurRegKeyPath); reg.CloseKey(); reg.Free; end; function TfmMain.getRegisterToastMessageKey : String; const // It appears that you can't change this atm :( AppId = 'Embarcadero.DesktopToasts.'; begin result := AppId + THashBobJenkins.GetHashString(ParamStr(0)); end; function DoesRegKeyExist: Boolean; var reg: TRegistry; begin // Set the global variable Result := False; OurRegKeyPath := '\SOFTWARE\Microsoft\Windows\CurrentVersion\Notifications\Settings\'; OurRegKeyPath := OurRegKeyPath + fmMain.getRegisterToastMessageKey; //$prodName reg := TRegistry.Create(KEY_READ); reg.RootKey := HKey; if reg.KeyExists(OurRegKeyPath) then Result := True; end; procedure UpdateLabel; begin if DoesRegKeyExist then fmMain.lblRegKeyExists.Caption := 'Reg key is PRESENT' else fmMain.lblRegKeyExists.Caption := 'Reg key is ABSENT'; end; end.
{====================================================} { } { EldoS Visual Components } { } { Copyright (c) 1998-2003, EldoS Corporation } { } {====================================================} {$include elpack2.inc} {$ifdef ELPACK_SINGLECOMP} {$I ElPack.inc} {$else} {$ifdef LINUX} {$I ../ElPack.inc} {$else} {$I ..\ElPack.inc} {$endif} {$endif} (* Version History 03/22/2002 (c) Alexander V. Hramov Add TElStack.ShiftUp method for shifting stack contents up. *) unit ElStack; interface uses Classes, SysUtils, ElContBase ; type EElStackError = class(exception) end; type TElStack = class(TObject) private FList :PPointerList; FCount : Integer; FCapacity : Integer; function Get(index : integer) : TxListItem; procedure Put(index : integer; value : TxListItem); procedure Grow; procedure SetCapacity(NewCapacity : Integer); protected function GetLast: TxListItem; public destructor Destroy; override; procedure Clear; procedure ShiftUp(ACount: integer); procedure Push(value : TxListItem); function Pop : TxListItem; function Empty : boolean; property Capacity : integer read FCapacity write SetCapacity; property Items[Index : Integer] : TxListItem read Get write Put; default; property Count : integer read FCount; property Last: TxListItem read GetLast; end; implementation function TElStack.Empty : boolean; begin result := Count = 0; end; function TElStack.Get(index : integer) : TxListItem; begin result := FList^[index]; end; procedure TElStack.Put(index : integer; value : TxListItem); begin FList^[index] := value; end; destructor TElStack.Destroy; begin FreeMem(FList, FCapacity); inherited Destroy; end; procedure TElStack.Grow; var Delta : Integer; begin if FCapacity > 64 then Delta := FCapacity div 4 else if FCapacity > 8 then Delta := 16 else Delta := 4; SetCapacity(FCapacity + Delta); end; procedure TElStack.SetCapacity(NewCapacity : Integer); begin if (NewCapacity < FCount) or (NewCapacity > MaxListSize) then raise EElStackError.Create('Invalid ElStack capacity.'); if NewCapacity <> FCapacity then begin ReallocMem(FList, NewCapacity * SizeOf(TxListItem)); FCapacity := NewCapacity; end; end; procedure TElStack.Push(value : TxListItem); begin if FCount = FCapacity then Grow; FList^[FCount] := value; Inc(FCount); end; function TElStack.Pop: TxListItem; begin if FCount = 0 then raise EElStackError.Create('ElStack is empty.'); result := FList^[FCount - 1]; dec(FCount); if FCount < (FCapacity div 2) then SetCapacity(FCapacity div 2); end; procedure TElStack.Clear; begin FCount := 0; SetCapacity(0); end; function TElStack.GetLast: TxListItem; begin if FCount = 0 then raise EElStackError.Create('ElStack is empty.'); Result := FList^[FCount - 1]; end; procedure TElStack.ShiftUp(ACount: integer); begin if ACount > FCount then raise EElStackError.Create('Cannot shift ElStack'); if FCount = 0 then raise EElStackError.Create('ElStack is empty.'); Move(FList^[ACount], FList^, (FCount - ACount) * SizeOf(TxListItem)); FCount := FCount - ACount; SetCapacity(FCount); end; end.
unit DW.Androidapi.JNI.Support; {*******************************************************} { } { Kastri Free } { } { DelphiWorlds Cross-Platform Library } { } {*******************************************************} {$I DW.GlobalDefines.inc} interface uses Androidapi.JNI.Support, Androidapi.JNI.JavaTypes, Androidapi.JNIBridge, Androidapi.JNI.GraphicsContentViewText, Androidapi.JNI.App, Androidapi.JNI.Widget, Androidapi.JNI.Net; type JNotificationCompat_Builder = interface; JNotificationCompat_BuilderClass = interface(JObjectClass) ['{6EC74C2C-EBCC-4A55-98B6-6DD36DE3BA8C}'] {class} function init(context: JContext): JNotificationCompat_Builder; cdecl; end; [JavaSignature('android/support/v4/app/NotificationCompat$Builder')] JNotificationCompat_Builder = interface(Androidapi.JNI.Support.JNotificationCompat_Builder) ['{81FD10B1-0D7F-4F6E-BF92-6A74F52C424C}'] function addAction(icon: Integer; title: JCharSequence; intent: JPendingIntent): JNotificationCompat_Builder; cdecl; function build: JNotification; cdecl; function getNotification: JNotification; cdecl;//Deprecated function setAutoCancel(autoCancel: Boolean): JNotificationCompat_Builder; cdecl; function setChannelId(channelId: JString): JNotificationCompat_Builder; cdecl; function setContent(views: JRemoteViews): JNotificationCompat_Builder; cdecl; function setContentInfo(info: JCharSequence): JNotificationCompat_Builder; cdecl; function setContentIntent(intent: JPendingIntent): JNotificationCompat_Builder; cdecl; function setContentText(text: JCharSequence): JNotificationCompat_Builder; cdecl; function setContentTitle(title: JCharSequence): JNotificationCompat_Builder; cdecl; function setDefaults(defaults: Integer): JNotificationCompat_Builder; cdecl; function setDeleteIntent(intent: JPendingIntent): JNotificationCompat_Builder; cdecl; function setFullScreenIntent(intent: JPendingIntent; highPriority: Boolean): JNotificationCompat_Builder; cdecl; function setLargeIcon(icon: JBitmap): JNotificationCompat_Builder; cdecl; function setLights(argb: Integer; onMs: Integer; offMs: Integer): JNotificationCompat_Builder; cdecl; function setNumber(number: Integer): JNotificationCompat_Builder; cdecl; function setOngoing(ongoing: Boolean): JNotificationCompat_Builder; cdecl; function setOnlyAlertOnce(onlyAlertOnce: Boolean): JNotificationCompat_Builder; cdecl; function setPriority(pri: Integer): JNotificationCompat_Builder; cdecl; function setProgress(max: Integer; progress: Integer; indeterminate: Boolean): JNotificationCompat_Builder; cdecl; function setSmallIcon(icon: Integer): JNotificationCompat_Builder; cdecl; overload; function setSmallIcon(icon: Integer; level: Integer): JNotificationCompat_Builder; cdecl; overload; function setSound(sound: Jnet_Uri): JNotificationCompat_Builder; cdecl; overload; function setSound(sound: Jnet_Uri; streamType: Integer): JNotificationCompat_Builder; cdecl; overload; function setStyle(style: JNotificationCompat_Style): JNotificationCompat_Builder; cdecl; function setSubText(text: JCharSequence): JNotificationCompat_Builder; cdecl; function setTicker(tickerText: JCharSequence): JNotificationCompat_Builder; cdecl; overload; function setTicker(tickerText: JCharSequence; views: JRemoteViews): JNotificationCompat_Builder; cdecl; overload; function setUsesChronometer(b: Boolean): JNotificationCompat_Builder; cdecl; function setVibrate(pattern: TJavaArray<Int64>): JNotificationCompat_Builder; cdecl; function setWhen(when: Int64): JNotificationCompat_Builder; cdecl; end; TJNotificationCompat_Builder = class(TJavaGenericImport<JNotificationCompat_BuilderClass, JNotificationCompat_Builder>) end; implementation end.
object Form1: TForm1 Left = 307 Top = 138 Width = 849 Height = 636 Caption = 'Pearson Hash Code Generator (Monte Carlo Method)' Color = clBtnFace Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [] OldCreateOrder = False OnCreate = FormCreate OnDestroy = FormDestroy PixelsPerInch = 96 TextHeight = 13 object Memo1: TMemo Left = 28 Top = 39 Width = 229 Height = 479 Lines.Strings = ( '12345' 'Abstand' 'Aktien' 'anfall' 'Arm' 'Arrogant' 'at least' 'Auto' 'Bauarbeiter' 'Bier' 'Bildschirm' 'Bitburger' 'blau' 'Blei' 'Bleibtreu' 'Blitzkrieg' 'Blut' 'Computer' 'Datenbank' 'Delphi' 'Delphi-Praxis' 'Dreck' 'Dumm' 'Dummkopf' 'Elefant' 'Ende' 'Fahrrad' 'Feile' 'fertig' 'Fischer' 'For-Schleife' 'fort' 'Frank' 'Geheim' 'Gehirn' 'Geld' 'Gleichung' 'Gold' 'hässlich' 'Hallo' 'Hand' 'Hashing' 'Held' 'Herbert' 'Herz' 'Heuboden' 'Hilfe' 'http://www.embacadero.com' 'Idiot' 'Kaliber' 'Kampf' 'Katze' 'keine' 'Knie' 'Krank' 'langsam' 'Langweilig' 'Leber' 'Lunge' 'Maria' 'Maus' 'Monitor' 'Nicht Gut' 'obst' 'Ohne' 'Ohr' 'OOP' 'Organisch' 'Passwort' 'Paul' 'Paulaner' 'Pause' 'Pearson' 'Pech' 'Perfekt' 'Peter' 'Plastik' 'poppen' 'Power' 'Prärie' 'Praxis' 'Programmieren' 'Prolog' 'Python' 'Salat' 'saufen' 'Schön' 'Schüssel' 'Schicksal' 'schlafen' 'schnackeln' 'Schnake' 'schnell' 'Schwefel' 'Schwein' 'Silber' 'Sofort' 'Stier' 'Tasche' 'Tasse' 'Tasten' 'Team Foundation Server sucks' 'The art of coding' 'Tor' 'Trank' 'Treibgut' 'trinken' 'Trottel' 'Unfall' 'VW' 'Wanda' 'Was soll das?' 'Wer andern eine Grube gräbt' 'Windows' 'Xenia' 'Zange' 'Zeilen') ScrollBars = ssVertical TabOrder = 0 end object ButtonStart: TButton Left = 306 Top = 500 Width = 75 Height = 41 Caption = 'Start' Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -16 Font.Name = 'MS Sans Serif' Font.Style = [fsBold] ParentFont = False TabOrder = 1 OnClick = ButtonStartClick end object Button2: TButton Left = 30 Top = 527 Width = 160 Height = 25 Caption = 'Add 100 Random Strings' TabOrder = 2 OnClick = Button2Click end object BtnOpenFile: TButton Left = 30 Top = 12 Width = 117 Height = 25 Caption = 'Load Text file...' TabOrder = 3 OnClick = BtnOpenFileClick end object PageControl1: TPageControl Left = 276 Top = 21 Width = 486 Height = 450 ActivePage = TabSheet1 TabOrder = 4 OnChange = PageControl1Change object TabSheet1: TTabSheet Caption = 'Results' object MemoBest: TMemo Left = 0 Top = 0 Width = 478 Height = 422 Align = alClient TabOrder = 0 end end object TabSheet2: TTabSheet Caption = 'Pearson Hash Table' ImageIndex = 1 object Memo3: TMemo Left = 0 Top = 0 Width = 478 Height = 422 Align = alClient Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -9 Font.Name = 'Courier New' Font.Style = [] ParentFont = False TabOrder = 0 end end object TabSheet3: TTabSheet Caption = 'Pascal Source Code' ImageIndex = 2 object Memo4: TMemo Left = 0 Top = 0 Width = 478 Height = 422 Align = alClient ScrollBars = ssBoth TabOrder = 0 end end end object OpenDialog1: TOpenDialog Left = 145 Top = 13 end end
unit noise; {$ifdef fpc} {$mode delphi} {$endif} interface uses Classes, SysUtils; function IntNoise(x: Integer): Double; function Linear_Interpolate(a, b, x: Double): Double; function Cosine_Interpolate(a, b, x: Double): Double; function Cubic_Interpolate(v0, v1, v2, v3, x: Double): Double; implementation function IntNoise(x: Integer): Double; var xl: Integer; begin xl := (x shl 13) xor x; Result := (xl * (xl * xl * 15731 + 789221) + 1376312589) and $7fffffff; Result := 1.0 - (Result / 1073741824.0); end; function Linear_Interpolate(a, b, x: Double): Double; begin Result := a * (1-x) + b * x; end; function Cosine_Interpolate(a, b, x: Double): Double; var f, ft: Double; begin ft := x * Pi; f := (1.0 - cos(ft)) * 0.5; Result := a * (1 - f) + b * f; end; function Cubic_Interpolate(v0, v1, v2, v3, x: Double): Double; var P, Q, R, S: Double; begin P := (v3 - v2) - (v0 - v1); Q := (v0 - v1) - P; R := v2 - v0; S := v1; Result := P * x * x * x + Q * x * x + R * x + S; end; end.
unit DataTypes; interface type TCMDType = (cmtIOCPEvent, cmtAccept, cmtDisconnect, cmtTR_CODE); type TR_CODE = (ctDestAdd, ctDestDel, ctDestPushSend, ctDestRRSend, ctDestRRSendResponse, ctUserID, ctDisconnect, ctUserConnectOk, ctUsersAlready, ctClientUniqKey); type TDeliveryMode = (Delivery_RR, Delivery_RR_Response, Delivery_Push); const MESSAGE_TO_SEND = 0; const RECEIVED_MESSAGE = 1; const RESPOND_MESSAGE = 2; type TInitialize = function : integer; stdcall; type TSMCreateInstance = function : integer; stdcall; type TSMGetObjectsNumber = function : integer; stdcall; type TSMGetMaximumObjectsNumber = function : integer; stdcall; type TSMClientConnect = function (index : integer; host : PChar; port : integer) : integer; stdcall; type TSMClientDisconnect = function (index : integer) : integer; stdcall; type TSMClientIsConnected = function (index : integer) : boolean; stdcall; type TSMGetClientUniqKey = function (index : integer) : PChar; stdcall; type TSMGetClientIP = function (index : integer) : PChar; stdcall; type TSMSetMessageParameters = function (index, messtype : integer; DeliveryMode : TDeliveryMode; Destination : PChar; Msg : PChar) : integer; stdcall; type TSMSetMessageBinaryField = function (index, messtype : integer; FieldName : PChar; Data : Pointer; DataSize : integer) : integer; stdcall; type TSMSetMessageStringField = function (index, messtype : integer; FieldName : PChar; Str : Pointer) : integer; stdcall; type TSMSendMessage = function (index, messtype : integer) : integer; stdcall; type TSMEventAddDestination = function (index : integer; Dest : PChar; Msg : PChar) : integer; stdcall; type TSMEventRemoveDestination = function (index : integer; Dest : PChar; Msg : PChar) : integer; stdcall; type TSMEventAllRemoveDestination = function (index : integer) : integer; stdcall; type TSMSetWorkEventCallBack = function (index : integer; Addr : pointer) : integer; stdcall; type TSMMessageGetBinaryFieldValue = function (index, messtype : integer; FieldName : PChar) : PChar; stdcall; type TSMMessageGetStringFieldValue = function (index, messtype : integer; FieldName : PChar) : PChar; stdcall; type TSMMessageGetIntegerFieldValue = function (index, messtype : integer; FieldName : PChar) : integer; stdcall; type TSMSetMessageIntegerField = function (index, messtype : integer; FieldName : PChar; Val : integer) : integer; stdcall; type TSMSetMessageDoubleField = function (index, messtype : integer; FieldName : PChar; Val : double) : integer; stdcall; type TSMSMessageToSMessage = function (index, inmesstype, outmesstype : integer) : integer; stdcall; type TSMSendResponse = function (index, messtype : integer) : integer; stdcall; type TSMMessageGetDeliveryType = function (index, messtype : integer) : integer; stdcall; implementation end.
unit SPService; //monitorear una app //la app si termina ok crea el fichero // sino esta corriendo y esta el fichero lanzo la app // si esta corriendo la dejo corriendo // si el fichero no esta y no esta corriendo pongo en la traza // y envio un email a una address interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, SvcMgr, Dialogs; type TSMSWatcher = class(TService) procedure ServiceAfterInstall(Sender: TService); procedure ServiceAfterUninstall(Sender: TService); procedure ServiceStart(Sender: TService; var Started: Boolean); procedure ServiceStop(Sender: TService; var Stopped: Boolean); procedure ServicePause(Sender: TService; var Paused: Boolean); procedure ServiceContinue(Sender: TService; var Continued: Boolean); private { Private declarations } public function GetServiceController: TServiceController; override; { Public declarations } end; var SMSWatcher: TSMSWatcher; implementation uses DoTask, inifiles ; {$R *.DFM} var MyDoTask : TDoTask ; procedure ServiceController(CtrlCode: DWord); stdcall; begin SMSWatcher.Controller(CtrlCode); end; function TSMSWatcher.GetServiceController: TServiceController; begin Result := ServiceController; end; procedure TSMSWatcher.ServiceAfterInstall(Sender: TService); begin LogMessage('MSWatcher Service has just installed', EVENTLOG_INFORMATION_TYPE , 0, 0); end; procedure TSMSWatcher.ServiceAfterUninstall(Sender: TService); begin LogMessage('MSWatcher Service has just uninstalled', EVENTLOG_INFORMATION_TYPE , 0, 0); end; procedure TSMSWatcher.ServiceStart(Sender: TService; var Started: Boolean); var AppName : string ; CheckPeriod : integer ; CheckPeriodS : string ; FileToCheck : string ; i : integer ; S : string ; WinDir : array [1..150] of char ; TIF : TIniFile ; MailServer, EmailToNotify : string ; begin // main stuff for the service goes here AppName := '' ; CheckPeriod := 2 ; FileToCheck := '' ; try //Str ( ParamCount, s ) ; //LogMessage ( 'MSWatcher: paramcount: ' + s, EVENTLOG_INFORMATION_TYPE , 0, 0); //LogMessage ( 'MSWatcher: param 1 : '+ Param[0] ) ; GetCurrentDirectory ( 150, PChar(@WinDir[1]) ) ; S := StrPas ( PChar(@WinDir[1]) ) ; S := S + '\MSWatcher.ini' ; TIF := TIniFile.Create ( S ) ; AppName := TIF.ReadString ( 'MSWatcher params', 'Program to Watch', '' ) ; FileToCheck := TIF.ReadString ( 'MSWatcher params', 'File to Check', '' ) ; CheckPeriodS := TIF.ReadString ( 'MSWatcher params', 'CheckPeriod','' ) ; MailServer := TIF.ReadString ( 'MSWatcher params', 'Server','' ) ; EmailToNotify := TIF.ReadString ( 'MSWatcher params', 'email','' ) ; TIF.Free ; if CheckPeriodS <> '' then Val ( CheckPeriodS, CheckPeriod, i ) ; // AppName := 'C:\winnt\system32\calc.exe' ; // FileToCheck := 'C:\file.txt' ; LogMessage ( 'MSWatcher: service params AppName:'+AppName+' FileToCheck:'+FileToCheck+ ' CheckPeriod:'+CheckPeriodS+ ' MailServer:'+MailServer+ ' Email:'+ EmailToNotify+' inifile:'+S , EVENTLOG_INFORMATION_TYPE , 0, 0 ) ; if (AppName = '') or (FileToCheck = '') then begin LogMessage ( 'MSWatcher: service do not start, you must supply Exe to run and File to check' , EVENTLOG_ERROR_TYPE, 0, 0 ) ; Started := False ; end ; MyDoTask := TDoTask.Create ( AppName, FileToCheck, CheckPeriod, SMSWatcher, MailServer, EmailToNotify ) ; Started := True; except //rudimentary error handling on e:Exception do begin LogMessage('MSWatcher: an error occurred in MSWatcher. The error was ' + e.Message, EVENTLOG_ERROR_TYPE, 0, 0); Started := False; end; end; end; procedure TSMSWatcher.ServiceStop(Sender: TService; var Stopped: Boolean); begin //is there is any thread then call its terminate if MyDoTask <> nil then begin MyDoTask.Terminate ; Stopped := True; end ; end; procedure TSMSWatcher.ServicePause(Sender: TService; var Paused: Boolean); begin //if there is any thread then suspend it if MyDoTask <> nil then begin MyDoTask.Suspend ; Paused := True; end ; end; procedure TSMSWatcher.ServiceContinue(Sender: TService; var Continued: Boolean); begin //if there is any thread then resume it if MyDoTask <> nil then begin MyDoTask.Resume ; Continued := true ; end ; end; end.
unit Solid.Samples.SRP.BookWrong; interface uses System.SysUtils; type TBook = class private FAuthor: string; FPage: Integer; FTitle: string; procedure SetAuthor(const AValue: string); procedure SetTitle(const AValue: string); procedure SetPage(const Value: Integer); public property Author: string read FAuthor write SetAuthor; // Entity/DTO property Page: Integer read FPage write SetPage; // Entity/DTO property Title: string read FTitle write SetTitle; // Entity/DTO procedure Print; // Printing procedure Save; // Persistence & IO procedure ShowPage; // UI procedure TurnPage; // Interaction end; implementation procedure TBook.Print; begin // TODO: Send book contents to a printer. end; procedure TBook.SetAuthor(const AValue: string); begin FAuthor := Trim(AValue); end; procedure TBook.SetPage(const Value: Integer); begin FPage := Value; end; procedure TBook.SetTitle(const AValue: string); begin FTitle := Trim(AValue); end; procedure TBook.ShowPage; begin // TODO: Show current page to a device. end; procedure TBook.Save; begin // TODO: Open database connection or output file. // TODO: Make some logic checks. // TODO: DB CRUD operations. // TODO: Close connection/file. end; procedure TBook.TurnPage; begin // TODO: Fetch the next available page. end; end.
program ch10 (data9cust, data9apts, output); { Alberto Villalobos April 20, 2014 Chapter 10 assignment Description: A users fills out a string of 30 characters, y or n, representing a feature they desire, then there is a 20 character long address. Compare it to other entries and type possible if the matches are at least 80%, and NO if they're not. Input Customer file Apartments file Output Table of entries with a "possible" or "no" next to them level 0 initialize variables read customer file into array foreach line put into array compare arrays ouput level 1 initialize variables readcustomer foreach customer compare against each answer add to the total divide over total amount ouput percentage if over 80%, output possible print like: address noOfMatches Possibility level 2 } {variables} type myArray = Array[1..30] of char; var data9cust, data9apts: text; i, matches: integer; customer, apartments, address, decision : char; customerArray, apartmentsArray:myArray; {match stuff} {begin program} begin matches := 0; reset (data9cust); reset (data9apts); {load customer data} for i:= 1 to 30 do begin {read file} read(data9cust, customer); {put customer data into the array} customerArray [i]:=customer; {writeln(customerArray[i]);} end; {compare to others} {loop over each line} while not eof (data9apts) do begin {loop through each apartment} for i:=1 to 30 do begin {read file} read(data9apts, apartments); {load apartments to array} if apartments = customerArray[i] then matches := matches + 1; end; while not eoln(data9apts) do begin read(data9apts, address); write (address); end; if eoln (data9apts) then begin readln(data9apts); if matches >= 24 then writeln(matches, ' Possible') else writeln(matches, ' no'); matches := 0; end; end; end.
PROGRAM TreeSort(INPUT, OUTPUT); { Сортировка бинарным деревом } TYPE Tree = ^Node; Node = RECORD Key: CHAR; BalanceLeft, BalanceRight: INTEGER; Left, Right: Tree; END; VAR Root: Tree; Ch: CHAR; Balanced: BOOLEAN; PROCEDURE DoBalance(VAR Ptr: Tree); VAR SavedRoot: Tree; BEGIN { DoBalance } SavedRoot := Ptr; IF (Ptr^.Right = NIL) AND (Ptr^.Left^.Right = NIL) //Right rotation THEN BEGIN //WRITELN(' NOT BALANCED! NEEDS RIGHT ROTATION! FOR: ', // Ptr^.Key, ' ', Ptr^.BalanceLeft, ' ', Ptr^.BalanceRight); Ptr := SavedRoot^.Left; SavedRoot^.Left := NIL; // / <- Ptr Ptr^.Right := SavedRoot; // input: 321 ----------> 3 Ptr^.BalanceLeft := 1; // / Ptr^.BalanceRight := 1; // Ptr -> 2 <---------- 2 Ptr^.Left^.BalanceLeft := 0; // / \ / Ptr^.Left^.BalanceRight := 0; // 1 3 1 Ptr^.Right^.BalanceLeft := 0; // Ptr^.Right^.BalanceRight := 0 // 1,3 now has Lbalance&RBalance = 0, but 2 has LBalance&RBalance = 1 END; IF (Ptr^.Left = NIL) AND (Ptr^.Right^.Left = NIL) //Left rotation THEN BEGIN //WRITELN(' NOT BALANCED! NEEDS LEFT ROTATION! FOR: ', // Ptr^.Key, ' ', Ptr^.BalanceLeft, ' ', Ptr^.BalanceRight); Ptr := SavedRoot^.Right; SavedRoot^.Right := NIL; // / <- Ptr Ptr^.Left := SavedRoot; // input: 123 ----------> 1 Ptr^.BalanceLeft := 1; // / Ptr^.BalanceRight := 1; // Ptr -> 2 <---------- 2 Ptr^.Left^.BalanceLeft := 0; // / \ / Ptr^.Left^.BalanceRight := 0; // 1 3 3 Ptr^.Right^.BalanceLeft := 0; // Ptr^.Right^.BalanceRight := 0 // 1,3 now has Lbalance&RBalance = 0, but 2 has LBalance&RBalance = 1 END; IF (Ptr^.Right = NIL) AND (Ptr^.Left^.Left = NIL) //Left-Right rotation THEN BEGIN //WRITELN(' NOT BALANCED! NEEDS LEFT-RIGHT ROTATION! FOR: ', // Ptr^.Key, ' ', Ptr^.BalanceLeft, ' ', Ptr^.BalanceRight); Ptr := SavedRoot^.Left^.Right; Ptr^.Left := SavedRoot^.Left; Ptr^.Left^.Right := NIL; Ptr^.Right := SavedRoot; Ptr^.Right^.Left := NIL; Ptr^.BalanceLeft := 1; Ptr^.BalanceRight := 1; Ptr^.Left^.BalanceLeft := 0; Ptr^.Left^.BalanceRight := 0; Ptr^.Right^.BalanceLeft := 0; Ptr^.Right^.BalanceRight := 0 END; IF (Ptr^.Left = NIL) AND (Ptr^.Right^.Right = NIL) //Right-Left rotation THEN BEGIN //WRITELN(' NOT BALANCED! NEEDS RIGHT-LEFT ROTATION! FOR: ', // Ptr^.Key, ' ', Ptr^.BalanceLeft, ' ', Ptr^.BalanceRight); Ptr := SavedRoot^.Right^.Left; Ptr^.Right := SavedRoot^.Right; Ptr^.Right^.Left := NIL; Ptr^.Left := SavedRoot; Ptr^.Left^.Right := NIL; Ptr^.BalanceLeft := 1; Ptr^.BalanceRight := 1; Ptr^.Left^.BalanceLeft := 0; Ptr^.Left^.BalanceRight := 0; Ptr^.Right^.BalanceLeft := 0; Ptr^.Right^.BalanceRight := 0 END; WRITELN(' ROTATION IS DONE! ', Ptr^.Left^.Key, ' ', Ptr^.Key, ' ', Ptr^.Right^.Key) END; { DoBalance } PROCEDURE Insert(VAR Ptr: Tree; Data: CHAR; VAR Balanced: BOOLEAN); BEGIN {Insert} IF Ptr = NIL THEN BEGIN NEW(Ptr); Ptr^.Key := Data; WRITELN(' DATA IS SET ', Data); Ptr^.Left := NIL; Ptr^.Right := NIL; Ptr^.BalanceLeft := 0; Ptr^.BalanceRight := 0 END ELSE BEGIN IF Ptr^.Key > Data THEN BEGIN Ptr^.BalanceLeft := Ptr^.BalanceLeft + 1; Insert(Ptr^.Left, Data, Balanced); IF NOT Balanced THEN BEGIN DoBalance(Ptr); Balanced := TRUE; Ptr^.BalanceLeft := Ptr^.BalanceLeft - 1; END END ELSE BEGIN Ptr^.BalanceRight := Ptr^.BalanceRight + 1; Insert(Ptr^.Right, Data, Balanced); IF NOT Balanced THEN BEGIN DoBalance(Ptr); Balanced := TRUE; Ptr^.BalanceRight := Ptr^.BalanceRight - 1; END END END; IF abs(Ptr^.BalanceLeft - Ptr^.BalanceRight) > 1 THEN Balanced := FALSE; //WRITELN(' FOR: ', Ptr^.Key, ' LeftBalance: ', Ptr^.BalanceLeft, ' RightBalance: ', Ptr^.BalanceRight); END; {Insert} PROCEDURE PrintTree(Ptr: Tree); BEGIN {PrintTree} IF Ptr <> NIL THEN BEGIN PrintTree(Ptr^.Left); WRITE(Ptr^.Key); PrintTree(Ptr^.Right); END END; {PrintTree} BEGIN { TreeSort } Root := NIL; Balanced := TRUE; WHILE NOT EOLN DO BEGIN READ(Ch); Insert(Root, Ch, Balanced) END; PrintTree(Root); WRITELN END. { TreeSort }
unit tdLDAPEnum; interface uses System.Classes, Winapi.Windows, System.SysUtils, System.AnsiStrings, System.TypInfo, System.DateUtils, Winapi.ActiveX, ADC.LDAP, JwaRpcdce, ActiveDs_TLB, MSXML2_TLB, ADC.Types, ADC.DC, ADC.Attributes, ADC.ADObject, ADC.ADObjectList, ADC.Common, ADC.AD; type TLDAPEnum = class(TThread) private FProgressProc: TProgressProc; FExceptionProc: TExceptionProc; FProgressValue: Integer; FExceptionCode: ULONG; FExceptionMsg: string; FLDAP: PLDAP; FLDAPSearchResult: PLDAPMessage; FAttrCatalog: TAttrCatalog; FAttributes: array of PAnsiChar; FOutList: TADObjectList<TADObject>; FObj: TADObject; FDomainHostName: string; FMaxPwdAge_Secs: Int64; FMaxPwdAge_Days: Int64; procedure FillEventList(AStringStream: TStringStream; AOutList: TStringList); procedure SyncProgress; procedure SyncException; procedure Clear; procedure ProcessObjects; function GetDomainDN: AnsiString; procedure GetMaxPasswordAge(ABase: AnsiString); function TimestampToDateTime(AAttrVal: PAnsiChar): TDateTime; function FormatExtDNFlags(iFlagValue: Integer): PLDAPControl; protected destructor Destroy; override; procedure Execute; override; procedure DoProgress(AProgress: Integer); overload; procedure DoProgress; overload; procedure DoException(AMsg: string; ACode: ULONG); public constructor Create(AConnection: PLDAP; AAttrCatalog: TAttrCatalog; AOutList: TADObjectList<TADObject>; AProgressProc: TProgressProc; AExceptionProc: TExceptionProc; CreateSuspended: Boolean = False); reintroduce; end; implementation { TLDAPEnum } procedure TLDAPEnum.ProcessObjects; var ldapEntry: PLDAPMessage; ldapValues: PPAnsiChar; ldapBinValues: PPLDAPBerVal; attr: TADAttribute; i: Integer; dn: PAnsiChar; memStream: TMemoryStream; strStream: TStringStream; d: TDateTime; begin ldapEntry := ldap_first_entry(FLDAP, FLDAPSearchResult); while ldapEntry <> nil do begin if Terminated then Break; FObj := TADObject.Create; FObj.DomainHostName := FDomainHostName; for i := 0 to FAttrCatalog.Count - 1 do begin attr := FAttrCatalog[i]^; if attr.ObjProperty = 'nearestEvent' then begin ldapBinValues := ldap_get_values_len(FLDAP, ldapEntry, PAnsiChar(AnsiString(attr.Name))); if (ldapBinValues <> nil) and (ldapBinValues^.bv_len > 0) then begin strStream := TStringStream.Create; try strStream.Write( ldapBinValues^.bv_val^, ldapBinValues^.bv_len ); strStream.Seek(0, soFromBeginning); FillEventList(strStream, FObj.events); finally strStream.Free; end; end; ldap_value_free_len(ldapBinValues); end else case IndexText(attr.Name, [ 'lastLogon', { 0 } 'pwdLastSet', { 1 } 'badPwdCount', { 2 } 'groupType', { 3 } 'userAccountControl', { 4 } 'objectSid', { 5 } 'thumbnailPhoto', { 6 } 'distinguishedName', { 7 } 'primaryGroupToken' { 8 } ] ) of 0: begin { lastLogon } ldapBinValues := ldap_get_values_len(FLDAP, ldapEntry, PAnsiChar(AnsiString(attr.Name))); if (ldapBinValues <> nil) and (ldapBinValues^.bv_len > 0) then SetFloatProp(FObj, string(attr.ObjProperty), Self.TimestampToDateTime(ldapBinValues^.bv_val)); ldap_value_free_len(ldapBinValues); end; 1: begin { pwdLastSet } ldapBinValues := ldap_get_values_len(FLDAP, ldapEntry, PAnsiChar(AnsiString(attr.Name))); if (ldapBinValues <> nil) and (ldapBinValues^.bv_len > 0) then begin d := Self.TimestampToDateTime(ldapBinValues^.bv_val); if d > 0 then SetFloatProp(FObj, string(attr.ObjProperty), IncSecond(d, FMaxPwdAge_Secs)) else SetFloatProp(FObj, string(attr.ObjProperty), 0) end; ldap_value_free_len(ldapBinValues); end; 2..4: begin { badPwdCount, groupType, userAccountControl } ldapBinValues := ldap_get_values_len(FLDAP, ldapEntry, PAnsiChar(AnsiString(attr.Name))); if (ldapBinValues <> nil) and (ldapBinValues^.bv_len > 0) then SetPropValue(FObj, string(attr.ObjProperty), StrToIntDef(ldapBinValues^.bv_val, 0)); ldap_value_free_len(ldapBinValues); end; 5: begin { objectSid } ldapBinValues := ldap_get_values_len(FLDAP, ldapEntry, PAnsiChar(AnsiString(attr.Name))); if (ldapBinValues <> nil) and (ldapBinValues^.bv_len > 0) then SetPropValue(FObj, string(attr.ObjProperty), SIDToString(ldapBinValues^.bv_val)); ldap_value_free_len(ldapBinValues); end; 6: begin { thumbnailPhoto } ldapBinValues := ldap_get_values_len(FLDAP, ldapEntry, PAnsiChar(AnsiString(attr.Name))); if (ldapBinValues <> nil) and (ldapBinValues^.bv_len > 0) then begin memStream := TMemoryStream.Create; try memStream.Write( ldapBinValues^.bv_val^, ldapBinValues^.bv_len ); memStream.Seek(0, soFromBeginning); FObj.thumbnailPhoto.LoadFromStream(memStream); finally memStream.Free; end; end; ldap_value_free_len(ldapBinValues); end; 7: begin { distinguishedName } dn := ldap_get_dn(FLDAP, ldapEntry); if dn <> nil then SetPropValue(FObj, string(attr.ObjProperty), string(dn)); ldap_memfree(dn); end; 8: begin { primaryGroupToken } ldapBinValues := ldap_get_values_len(FLDAP, ldapEntry, PAnsiChar(AnsiString(attr.Name))); if (ldapBinValues <> nil) and (ldapBinValues^.bv_len > 0) then SetPropValue(FObj, string(attr.ObjProperty), StrToIntDef(ldapBinValues^.bv_val, 0)); ldap_value_free_len(ldapBinValues); end; else begin { Все текстовые атрибуты } ldapValues := ldap_get_values(FLDAP, ldapEntry, PAnsiChar(AnsiString(attr.Name))); if ldap_count_values(ldapValues) > 0 then SetPropValue(FObj, string(attr.ObjProperty), string(AnsiString(ldapValues^))); ldap_value_free(ldapValues); end; end; end; FOutList.Add(FObj); ldapEntry := ldap_next_entry(FLDAP, ldapEntry); DoProgress; end; end; procedure TLDAPEnum.Clear; var i: Integer; begin if Terminated then FOutList.Clear else FOutList.SortObjects; FLDAP := nil; FProgressProc := nil; FProgressValue := 0; FExceptionProc := nil; FExceptionCode := 0; FExceptionMsg := ''; FAttrCatalog := nil; FMaxPwdAge_Secs := 0; FMaxPwdAge_Days := 0; FOutList := nil; FObj := nil; if FLDAPSearchResult <> nil then ldap_msgfree(FLDAPSearchResult); for i := Low(FAttributes) to High(FAttributes) do System.AnsiStrings.StrDispose(FAttributes[i]); end; constructor TLDAPEnum.Create(AConnection: PLDAP; AAttrCatalog: TAttrCatalog; AOutList: TADObjectList<TADObject>; AProgressProc: TProgressProc; AExceptionProc: TExceptionProc; CreateSuspended: Boolean = False); var i: Integer; begin inherited Create(CreateSuspended); FreeOnTerminate := True; FLDAP := AConnection; FAttrCatalog := AAttrCatalog; FOutList := AOutList; FOutList.Clear; FProgressProc := AProgressProc; FExceptionProc := AExceptionProc; if AConnection = nil then begin Self.Terminate; DoException('No server binding.', 0); Exit; end; SetLength(FAttributes, FAttrCatalog.Count + 1); for i := 0 to FAttrCatalog.Count - 1 do FAttributes[i] := System.AnsiStrings.StrNew(PAnsiChar(AnsiString(FAttrCatalog[i]^.Name))); end; destructor TLDAPEnum.Destroy; begin inherited; end; procedure TLDAPEnum.DoException(AMsg: string; ACode: ULONG); begin FExceptionCode := ACode; FExceptionMsg := AMsg; Synchronize(SyncException); end; procedure TLDAPEnum.DoProgress; begin FProgressValue := FProgressValue + 1; Synchronize(SyncProgress); end; procedure TLDAPEnum.DoProgress(AProgress: Integer); begin FProgressValue := AProgress; Synchronize(SyncProgress); end; procedure TLDAPEnum.Execute; var returnCode: ULONG; errorCode: ULONG; ldapBase: AnsiString; ldapFilter: AnsiString; ldapCookie: PLDAPBerVal; ldapPage: PLDAPControl; ldapExtDN: PLDAPControl; ldapControls: array[0..1] of PLDAPControl; ldapServerControls: PPLDAPControl; ldapCount: ULONG; morePages: Boolean; i: Integer; begin try if Terminated then raise Exception.Create('No server binding.'); { Из подключения получаем DNS-имя КД } ldapBase := GetDomainDN; { Получаем значение атрибута maxPwdAge, которое используем для расчета } { срока действия пароля пользователя в секундах и днях (FMaxPwdAge_Seconds } { и FMaxPwdAge_Days соотв.) а затем используем одно из этих значений в } { процедуре ProcessObjects для расчета даты окончания действия пароля } GetMaxPasswordAge(ldapBase); { Формируем фильтр объектов AD } ldapFilter := '(|' + '(&(objectCategory=person)(objectClass=user))' + '(objectCategory=group)' + '(objectCategory=computer)' + ')'; ldapExtDN := nil; ldapCookie := nil; DoProgress(0); // ldapExtDN := FormatExtDNFlags(1); ldapControls[1] := ldapExtDN; { Постраничный поиск объектов AD } repeat if Terminated then Break; returnCode := ldap_create_page_control( FLDAP, ADC_SEARCH_PAGESIZE, ldapCookie, 1, ldapPage ); if returnCode <> LDAP_SUCCESS then raise Exception.Create('Failure during ldap_create_page_control: ' + ldap_err2string(returnCode)); ldapControls[0] := ldapPage; returnCode := ldap_search_ext_s( FLDAP, PAnsiChar(ldapBase), LDAP_SCOPE_SUBTREE, PAnsiChar(ldapFilter), PAnsiChar(@FAttributes[0]), 0, @ldapControls, nil, nil, 0, FLDAPSearchResult ); if not (returnCode in [LDAP_SUCCESS, LDAP_PARTIAL_RESULTS]) then raise Exception.Create('Failure during ldap_search_ext_s: ' + ldap_err2string(returnCode)); returnCode := ldap_parse_result( FLDAP^, FLDAPSearchResult, @errorCode, nil, nil, nil, ldapServerControls, False ); if ldapCookie <> nil then begin ber_bvfree(ldapCookie); ldapCookie := nil; end; returnCode := ldap_parse_page_control( FLDAP, ldapServerControls, ldapCount, ldapCookie ); if (ldapCookie <> nil) and (ldapCookie.bv_val <> nil) and (System.SysUtils.StrLen(ldapCookie.bv_val) > 0) then morePages := True else morePages := False; if ldapServerControls <> nil then begin ldap_controls_free(ldapServerControls^); ldapServerControls := nil; end; ldapControls[0]:= nil; ldap_control_free(ldapPage^); ldapPage := nil; ProcessObjects; ldap_msgfree(FLDAPSearchResult); FLDAPSearchResult := nil; until (morePages = False); ber_bvfree(ldapCookie); ldapCookie := nil; except on E: Exception do begin DoException(E.Message, returnCode); Clear; end; end; Clear; end; function TLDAPEnum.GetDomainDN: AnsiString; var attr: PAnsiChar; attrArray: array of PAnsiChar; returnCode: ULONG; searchResult: PLDAPMessage; ldapEntry: PLDAPMessage; ldapValue: PPAnsiChar; begin SetLength(attrArray, 3); attrArray[0] := PAnsiChar('defaultNamingContext'); attrArray[1] := PAnsiChar('dnsHostName'); attrArray[2] := nil; returnCode := ldap_search_ext_s( FLDAP, nil, LDAP_SCOPE_BASE, PAnsiChar('(objectclass=*)'), PAnsiChar(@attrArray[0]), 0, nil, nil, nil, 0, searchResult ); if (returnCode = LDAP_SUCCESS) and (ldap_count_entries(FLDAP, searchResult) > 0 ) then begin ldapEntry := ldap_first_entry(FLDAP, searchResult); ldapValue := ldap_get_values(FLDAP, ldapEntry, attrArray[0]); if ldapValue <> nil then Result := ldapValue^; ldap_value_free(ldapValue); ldapValue := ldap_get_values(FLDAP, ldapEntry, attrArray[1]); if ldapValue <> nil then FDomainHostName := ldapValue^; ldap_value_free(ldapValue); end; if searchResult <> nil then ldap_msgfree(searchResult); end; procedure TLDAPEnum.GetMaxPasswordAge(ABase: AnsiString); const ONE_HUNDRED_NANOSECOND = 0.000000100; SECONDS_IN_DAY = 86400; var attr: PAnsiChar; attrArray: array of PAnsiChar; returnCode: ULONG; searchResult: PLDAPMessage; ldapEntry: PLDAPMessage; ldapBinValues: PPLDAPBerVal; begin SetLength(attrArray, 2); attrArray[0] := PAnsiChar('maxPwdAge'); returnCode := ldap_search_ext_s( FLDAP, PAnsiChar(ABase), LDAP_SCOPE_BASE, PAnsiChar('objectCategory=domain'), PAnsiChar(@attrArray[0]), 0, nil, nil, nil, 0, searchResult ); if (returnCode = LDAP_SUCCESS) and (ldap_count_entries(FLDAP, searchResult) > 0 ) then begin ldapEntry := ldap_first_entry(FLDAP, searchResult); ldapBinValues := ldap_get_values_len(FLDAP, ldapEntry, PAnsiChar('maxPwdAge')); if (ldapBinValues <> nil) and (ldapBinValues^.bv_len > 0) then begin FMaxPwdAge_Secs := Abs(Round(ONE_HUNDRED_NANOSECOND * StrToInt64Def(ldapBinValues^.bv_val, 0))); FMaxPwdAge_Days := Round(FMaxPwdAge_Secs / SECONDS_IN_DAY); end; ldap_value_free_len(ldapBinValues); end; if searchResult <> nil then ldap_msgfree(searchResult); end; procedure TLDAPEnum.FillEventList(AStringStream: TStringStream; AOutList: TStringList); var XMLDoc: IXMLDOMDocument; XMLNodeList: IXMLDOMNodeList; XMLNode: IXMLDOMNode; i: Integer; eventString: string; begin AOutList.Clear; XMLDoc := CoDOMDocument60.Create; try XMLDoc.async := False; XMLDoc.load(TStreamAdapter.Create(AStringStream) as IStream); if XMLDoc.parseError.errorCode = 0 then begin XMLNodeList := XMLDoc.documentElement.selectNodes('event'); for i := 0 to XMLNodeList.length - 1 do begin XMLNode := XMLNodeList.item[i].selectSingleNode('date'); eventString := XMLNode.text; XMLNode := XMLNodeList.item[i].selectSingleNode('description'); eventString := eventString + '=' + XMLNode.text; AOutList.Add(eventString); end; end; finally XMLDoc := nil; end; end; function TLDAPEnum.FormatExtDNFlags(iFlagValue: Integer): PLDAPControl; const LDAP_SERVER_EXTENDED_DN_OID = '1.2.840.113556.1.4.529'; var pber: PBerElement; pLControl: PLDAPControl; pldctrl_value: PBERVAL; res: Integer; begin pber := nil; pLControl := nil; pldctrl_value := nil; res := -1; if iFlagValue <> 0 then iFlagValue := 1; pber := ber_alloc_t(LBER_USE_DER); if pber = nil then begin Result := nil; Exit; end; New(pLControl); ZeroMemory(pLControl, SizeOf(LDAPControl)); if pLControl= nil then begin Dispose(pLControl); ber_free(pber, 1); Result := nil end; ber_printf(pber, AnsiString('{i}'), iFlagValue); res := ber_flatten(pber, pldctrl_value); ber_free(pber, 1); if res <> 0 then begin Dispose(pLControl); Result := nil; Exit; end; pLControl.ldctl_oid := PAnsiChar(LDAP_SERVER_EXTENDED_DN_OID); pLControl.ldctl_iscritical := True; New(pLControl.ldctl_value.bv_val); ZeroMemory(pLControl.ldctl_value.bv_val, pldctrl_value.bv_len); CopyMemory( pLControl.ldctl_value.bv_val, pldctrl_value.bv_val, pldctrl_value.bv_len ); pLControl.ldctl_value.bv_len := pldctrl_value.bv_len; ber_bvfree(PLDAPBerVal(pldctrl_value)); Result := pLControl; end; procedure TLDAPEnum.SyncException; begin if Assigned(FExceptionProc) then FExceptionProc(FExceptionMsg, FExceptionCode); end; procedure TLDAPEnum.SyncProgress; begin if Assigned(FProgressProc) then FProgressProc(FProgressValue); end; function TLDAPEnum.TimestampToDateTime(AAttrVal: PAnsiChar): TDateTime; var int64Value: Int64; LocalTime: TFileTime; SystemTime: TSystemTime; FileTime : TFileTime; begin int64Value := StrToInt64Def(AAttrVal, 0); if int64Value = 0 then Result := 0 else try {int64Value := LastLogon.HighPart; int64Value := int64Value shl 32; int64Value := int64Value + LastLogon.LowPart;} Result := EncodeDate(1601,1,1); FileTime := TFileTime(int64Value); if FileTimeToLocalFileTime(FileTime, LocalTime) then if FileTimeToSystemTime(LocalTime, SystemTime) then Result := SystemTimeToDateTime(SystemTime); except Result := 0; end; end; end.
program crctest; {$mode objfpc} {$h+} uses sysutils, crc; const testseq1: string = 'MNIIQGNLVGTGLKIGIVVGRFNDFITSKLLSGAEDALLRHGVDTNDIDVAWVPGAFEIPFAAKKMAETKKYDAIITLGTVIRGATTSYDYVCNEAAKGIAQAANTTGVPVIFGIVTTENIEQAIERAGTKAGNKGVDCAVSAIEMANLNRSFE'; testseq2: string = 'MNIIQGNLVGTGLKIGIVVGRFNDFITSKLLSGAEDALLRHGVDTNDIDVAWVPGAFEIPFAAKKMAETKKYDAIITLGDVIRGATTHYDYVCNEAAKGIAQAANTTGVPVIFGIVTTENIEQAIERAGTKAGNKGVDCAVSAIEMANLNRSFE'; test1_crc64: qword = 14444300186948028230; test2_crc64: qword = 3310614217963326015; test1_crc32: longword = 3319070459; test2_crc32: longword = 1148765760; procedure perform_crc32(const name, testcase: string; result: longword); var crc: longword; begin crc := crc32(0,nil,0); crc := crc32(crc,@testcase[1],length(testcase)); write(name,'(size=',length(testcase),'): '); if crc=result then writeln('passed') else writeln('failed (got=',crc,',expected=',result,')'); end; procedure perform_crc64(const name, testcase: string; result: qword); var crc: qword; begin crc := crc64(0,nil,0); crc := crc64(crc,@testcase[1],length(testcase)); write(name,'(size=',length(testcase),'): '); if crc=result then writeln('passed') else writeln('failed (got=',crc,',expected=',result,')'); end; begin perform_crc32('crc32', testseq1, test1_crc32); perform_crc32('crc32', testseq2, test2_crc32); perform_crc64('crc64', testseq1, test1_crc64); perform_crc64('crc64', testseq2, test2_crc64); end.
unit UBaseType; interface uses U32Bytes, UDynRawBytes, URawBytes, U256RawBytes; type { TBaseType } TBaseType = Class public class procedure T32BytesToRawBytes(const source : T32Bytes; var dest : TDynRawBytes); overload; class function T32BytesToRawBytes(const source : T32Bytes) : TDynRawBytes; overload; class function TRawBytesTo32Left0Padded(const source : TDynRawBytes) : T32Bytes; class function Copy(const source : T32bytes; start, length : Integer) : ShortString; overload; class function Copy(const source : T256RawBytes; var dest : T256RawBytes) : ShortString; overload; class function To256RawBytes(const source : TRawBytes) : T256RawBytes; overload; class procedure To256RawBytes(const source : TRawBytes; var dest : T256RawBytes); overload; class function ToRawBytes(const source : T256RawBytes) : TRawBytes; overload; class procedure ToRawBytes(const source : T256RawBytes; var dest: TRawBytes); overload; class function ToRawBytes(const source : T32Bytes) : TRawBytes; overload; class procedure ToRawBytes(const source : T32Bytes; var dest: TRawBytes); overload; class function To32Bytes(const source : TRawBytes) : T32Bytes; overload; class procedure To32Bytes(const source : TRawBytes; var dest: T32Bytes); overload; class procedure Fill0(var dest : T32Bytes); class function IsEmpty(const value : T32Bytes) : Boolean; class procedure Concat(const addBytes : T32Bytes; var target : TDynRawBytes); overload; class procedure Concat(const leftBytes,rightBytes : T32Bytes; var target : TDynRawBytes); overload; class function Equals(const v1,v2 : T32Bytes) : Boolean; overload; class function Equals(const v1,v2 : TDynRawBytes) : Boolean; overload; class function Higher(const vHigh,vLow : T32Bytes) : Boolean; class function Compare(const leftBytes,rightBytes : T32Bytes) : Integer; // Herman functions moved from "Common" { Binary-safe StrComp replacement. StrComp will return 0 for when str1 and str2 both start with NUL character. } class function BinStrComp(const Str1, Str2 : AnsiString): Integer; end; implementation uses SysUtils; { TBaseType } {$IFnDEF FPC} procedure FillByte(var X; count : Integer; value : Byte); begin FillChar(X,count,value); end; {$ENDIF} class procedure TBaseType.T32BytesToRawBytes(const source: T32Bytes; var dest: TDynRawBytes); begin SetLength(dest,32); Move(source[0],dest[0],32); end; class function TBaseType.T32BytesToRawBytes(const source: T32Bytes): TDynRawBytes; begin T32BytesToRawBytes(source,Result); end; class function TBaseType.TRawBytesTo32Left0Padded(const source: TDynRawBytes): T32Bytes; var i : Integer; begin FillByte(Result,32,0); i := 0; while (i<32) And (i<=high(source)) do begin Result[i+32-length(source)] := source[i]; inc(i); end; end; class function TBaseType.Copy(const source: T32bytes; start, length: Integer): ShortString; begin if (length+start)>32 then raise Exception.Create('ERROR DEV 20170601-1'); SetLength(Result,length); move(source[start],Result[1],length); end; class function TBaseType.Copy(const source: T256RawBytes; var dest: T256RawBytes): ShortString; var i : Integer; begin SetLength(dest,length(source)); for i:=0 to high(dest) do begin dest[i] := source[i]; end; end; class function TBaseType.To256RawBytes(const source: TRawBytes): T256RawBytes; begin SetLength(Result,length(source)); move(source[1],Result[0],length(source)); end; class procedure TBaseType.To256RawBytes(const source: TRawBytes; var dest: T256RawBytes); begin SetLength(dest,length(source)); move(source[1],dest[0],length(source)); end; class function TBaseType.ToRawBytes(const source: T256RawBytes): TRawBytes; begin SetLength(Result,length(source)); move(source[0],Result[1],length(source)); end; class procedure TBaseType.ToRawBytes(const source: T256RawBytes; var dest: TRawBytes); begin SetLength(dest,length(source)); move(source[0],dest[1],length(source)); end; class function TBaseType.ToRawBytes(const source: T32Bytes): TRawBytes; begin SetLength(Result,length(source)); move(source[0],Result[1],length(source)); end; class procedure TBaseType.ToRawBytes(const source: T32Bytes; var dest: TRawBytes); begin SetLength(dest,length(source)); move(source[0],dest[1],length(source)); end; class function TBaseType.To32Bytes(const source: TRawBytes): T32Bytes; begin To32Bytes(source,Result); end; class procedure TBaseType.To32Bytes(const source: TRawBytes; var dest: T32Bytes); var i : Integer; begin FillByte(dest[0],32,0); i := length(source); if (i>32) then i:=32; move(source[1],dest[0],i); end; class procedure TBaseType.Fill0(var dest: T32Bytes); begin FillByte(dest[0],32,0); end; class function TBaseType.IsEmpty(const value: T32Bytes): Boolean; Var i : Integer; begin For i:=0 to 31 do begin if value[i]<>0 then begin Result := False; Exit; end; end; Result := True; end; class procedure TBaseType.Concat(const addBytes: T32Bytes; var target: TDynRawBytes); begin SetLength(target,length(target)+32); move(addBytes,target[length(target)-32],32); end; class procedure TBaseType.Concat(const leftBytes, rightBytes: T32Bytes; var target: TDynRawBytes); begin SetLength(target,64); move(leftBytes,target[0],32); move(rightBytes,target[32],32); end; class function TBaseType.Equals(const v1, v2: T32Bytes) : Boolean; Var i : Integer; begin for i:=0 to 31 do begin If v1[i]<>v2[i] then begin Result := False; Exit; end; end; Result := True; end; class function TBaseType.Equals(const v1, v2: TDynRawBytes): Boolean; Var i : Integer; begin If Length(v1)<>Length(v2) then begin Result := False; Exit; end; for i:=0 to high(v1) do begin If v1[i]<>v2[i] then begin Result := False; Exit; end; end; Result := True; end; class function TBaseType.Higher(const vHigh, vLow: T32Bytes): Boolean; Var i : Integer; begin for i:=0 to 31 do begin If vHigh[i]<vLow[i] then begin Result := False; Exit; end else if vHigh[i]>vLow[i] then begin Result := True; Exit; end; end; Result := False; // No higher, equal end; class function TBaseType.BinStrComp(const Str1, Str2: AnsiString): Integer; var Str1Len, Str2Len, i : Integer; begin Str1Len := Length(Str1); Str2Len := Length(Str2); if (Str1Len < Str2Len) then Result := -1 else if (Str1Len > Str2Len) then Result := 1 else begin Result := 0; for i:= 1 to Str1Len do begin if Str1[i] < Str2[i] then begin Result := -1; break; end else if Str1[i] > Str2[i] then begin Result := 1; break; end end; end; End; class function TBaseType.Compare(const leftBytes, rightBytes: T32Bytes): Integer; var i : Integer; begin for i:=0 to 31 do begin Result := leftBytes[i] - rightBytes[i]; if Result<>0 then exit; end; end; end.
{ *********************************************************** } { * TForge Library * } { * Copyright (c) Sergey Kasandrov 1997, 2017 * } { *********************************************************** } unit tfSalsa20; {$I TFL.inc} interface uses tfTypes; type PSalsaBlock = ^TSalsaBlock; TSalsaBlock = array[0..15] of UInt32; PSalsa20Instance = ^TSalsa20Instance; TSalsa20Instance = record private type PKey = ^TKey; TKey = array[0..7] of UInt32; // 256-bit key PBlock = ^TBlock; TBlock = array[0..15] of UInt32; TNonce = record case Byte of 0: (Value: UInt64); 1: (Words: array[0..1] of UInt32); end; private {$HINTS OFF} // -- inherited fields begin -- // from tfRecord FVTable: Pointer; FRefCount: Integer; // from tfBaseStreamCipher FValidKey: Boolean; FAlgID: UInt32; // -- inherited fields end -- FExpandedKey: TBlock; FRounds: Cardinal; // 2..254 {$HINTS ON} class function SetIV(Inst: PSalsa20Instance; Data: Pointer; DataLen: Cardinal): TF_RESULT; static; public class function Release(Inst: PSalsa20Instance): Integer; stdcall; static; class function ExpandKey(Inst: PSalsa20Instance; Key: PByte; KeySize: Cardinal): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function GetBlockSize(Inst: PSalsa20Instance): Integer; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function DuplicateKey(Inst: PSalsa20Instance; var Key: PSalsa20Instance): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class procedure DestroyKey(Inst: PSalsa20Instance);{$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function SetKeyParam(Inst: PSalsa20Instance; Param: UInt32; Data: Pointer; DataLen: Cardinal): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function KeyBlock(Inst: PSalsa20Instance; Data: TSalsa20Instance.PBlock): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function GetKeyParam(Inst: PSalsa20Instance; Param: UInt32; Data: Pointer; var DataLen: Cardinal): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function ExpandKeyIV(Inst: PSalsa20Instance; Key: PByte; KeySize: Cardinal; IV: PByte; IVSize: Cardinal): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function ExpandKeyNonce(Inst: PSalsa20Instance; Key: PByte; KeySize: Cardinal; Nonce: UInt64): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; end; type TChaCha20 = record public class function SetIV(Inst: PSalsa20Instance; Data: Pointer; DataLen: Cardinal): TF_RESULT; static; class function ExpandKey(Inst: PSalsa20Instance; Key: PByte; KeySize: Cardinal): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function DuplicateKey(Inst: PSalsa20Instance; var Key: PSalsa20Instance): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function SetKeyParam(Inst: PSalsa20Instance; Param: UInt32; Data: Pointer; DataLen: Cardinal): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function KeyBlock(Inst: PSalsa20Instance; Data: TSalsa20Instance.PBlock): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function GetKeyParam(Inst: PSalsa20Instance; Param: UInt32; Data: Pointer; var DataLen: Cardinal): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function ExpandKeyIV(Inst: PSalsa20Instance; Key: PByte; KeySize: Cardinal; IV: PByte; IVSize: Cardinal): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function ExpandKeyNonce(Inst: PSalsa20Instance; Key: PByte; KeySize: Cardinal; Nonce: UInt64): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; end; function GetSalsa20Instance(var A: PSalsa20Instance): TF_RESULT; function GetSalsa20InstanceEx(var A: PSalsa20Instance; Rounds: Integer): TF_RESULT; function GetChaCha20Instance(var A: PSalsa20Instance): TF_RESULT; function GetChaCha20InstanceEx(var A: PSalsa20Instance; Rounds: Integer): TF_RESULT; type TChaChaPRG = record private type TBlock = array[0..15] of UInt32; private FExpandedKey: TBlock; public function Init(Seed: PByte; SeedSize: Cardinal): TF_RESULT; function GetKeyStream(Buf: PByte; BufSize: Cardinal): TF_RESULT; end; implementation uses tfRecords, tfUtils, tfBaseCiphers; const SALSA_BLOCK_SIZE = 64; Salsa20VTable: array[0..18] of Pointer = ( @TForgeInstance.QueryIntf, @TForgeInstance.Addref, @TSalsa20Instance.Release, @TSalsa20Instance.DestroyKey, @TSalsa20Instance.DuplicateKey, @TSalsa20Instance.ExpandKey, @TSalsa20Instance.SetKeyParam, @TSalsa20Instance.GetKeyParam, @TSalsa20Instance.GetBlockSize, @TBaseStreamCipher.Encrypt, // @TBaseStreamCipher.Decrypt, @TBaseStreamCipher.Encrypt, @TBaseStreamCipher.EncryptBlock, @TBaseStreamCipher.EncryptBlock, @TBaseStreamCipher.GetRand, @TSalsa20Instance.KeyBlock, @TBaseStreamCipher.RandCrypt, @TBaseStreamCipher.GetIsBlockCipher, @TSalsa20Instance.ExpandKeyIV, @TSalsa20Instance.ExpandKeyNonce ); ChaCha20VTable: array[0..18] of Pointer = ( @TForgeInstance.QueryIntf, @TForgeInstance.Addref, @TSalsa20Instance.Release, @TSalsa20Instance.DestroyKey, @TChaCha20.DuplicateKey, @TChaCha20.ExpandKey, @TChaCha20.SetKeyParam, @TChaCha20.GetKeyParam, @TSalsa20Instance.GetBlockSize, @TBaseStreamCipher.Encrypt, // @TBaseStreamCipher.Decrypt, @TBaseStreamCipher.Encrypt, @TBaseStreamCipher.EncryptBlock, @TBaseStreamCipher.EncryptBlock, @TBaseStreamCipher.GetRand, @TChaCha20.KeyBlock, @TBaseStreamCipher.RandCrypt, @TBaseStreamCipher.GetIsBlockCipher, @TChaCha20.ExpandKeyIV, @TChaCha20.ExpandKeyNonce ); function GetSalsa20Instance(var A: PSalsa20Instance): TF_RESULT; begin Result:= GetSalsa20InstanceEx(A, 20); end; function GetSalsa20InstanceEx(var A: PSalsa20Instance; Rounds: Integer): TF_RESULT; var Tmp: PSalsa20Instance; begin if (Rounds < 1) or (Rounds > 255) or Odd(Rounds) then begin Result:= TF_E_INVALIDARG; Exit; end; try Tmp:= AllocMem(SizeOf(TSalsa20Instance)); Tmp^.FVTable:= @Salsa20VTable; Tmp^.FRefCount:= 1; Tmp^.FAlgID:= TF_ALG_SALSA20; Tmp^.FRounds:= Rounds shr 1; if A <> nil then TSalsa20Instance.Release(A); A:= Tmp; Result:= TF_S_OK; except Result:= TF_E_OUTOFMEMORY; end; end; function GetChaCha20Instance(var A: PSalsa20Instance): TF_RESULT; begin Result:= GetChaCha20InstanceEx(A, 20); end; function GetChaCha20InstanceEx(var A: PSalsa20Instance; Rounds: Integer): TF_RESULT; var Tmp: PSalsa20Instance; begin if (Rounds < 1) or (Rounds > 255) or Odd(Rounds) then begin Result:= TF_E_INVALIDARG; Exit; end; try Tmp:= AllocMem(SizeOf(TSalsa20Instance)); Tmp^.FVTable:= @ChaCha20VTable; Tmp^.FRefCount:= 1; Tmp^.FAlgID:= TF_ALG_CHACHA20; Tmp^.FRounds:= Rounds shr 1; if A <> nil then TSalsa20Instance.Release(A); A:= Tmp; Result:= TF_S_OK; except Result:= TF_E_OUTOFMEMORY; end; end; const // Sigma = 'expand 32-byte k' Sigma0 = $61707865; Sigma1 = $3320646e; Sigma2 = $79622d32; Sigma3 = $6b206574; // Tau = 'expand 16-byte k' Tau0 = $61707865; Tau1 = $3120646e; Tau2 = $79622d36; Tau3 = $6b206574; { TSalsa20 } procedure BurnKey(Inst: PSalsa20Instance); inline; var BurnSize: Integer; begin BurnSize:= SizeOf(TSalsa20Instance) - Integer(@PSalsa20Instance(nil)^.FValidKey); FillChar(Inst.FValidKey, BurnSize, 0); end; class function TSalsa20Instance.Release(Inst: PSalsa20Instance): Integer; begin if Inst.FRefCount > 0 then begin Result:= tfDecrement(Inst.FRefCount); if Result = 0 then begin BurnKey(Inst); FreeMem(Inst); end; end else Result:= Inst.FRefCount; end; class procedure TSalsa20Instance.DestroyKey(Inst: PSalsa20Instance); begin BurnKey(Inst); end; procedure SalsaDoubleRound(x: TSalsa20Instance.PBlock); var y: UInt32; begin y := x[ 0] + x[12]; x[ 4] := x[ 4] xor ((y shl 07) or (y shr (32-07))); y := x[ 4] + x[ 0]; x[ 8] := x[ 8] xor ((y shl 09) or (y shr (32-09))); y := x[ 8] + x[ 4]; x[12] := x[12] xor ((y shl 13) or (y shr (32-13))); y := x[12] + x[ 8]; x[ 0] := x[ 0] xor ((y shl 18) or (y shr (32-18))); y := x[ 5] + x[ 1]; x[ 9] := x[ 9] xor ((y shl 07) or (y shr (32-07))); y := x[ 9] + x[ 5]; x[13] := x[13] xor ((y shl 09) or (y shr (32-09))); y := x[13] + x[ 9]; x[ 1] := x[ 1] xor ((y shl 13) or (y shr (32-13))); y := x[ 1] + x[13]; x[ 5] := x[ 5] xor ((y shl 18) or (y shr (32-18))); y := x[10] + x[ 6]; x[14] := x[14] xor ((y shl 07) or (y shr (32-07))); y := x[14] + x[10]; x[ 2] := x[ 2] xor ((y shl 09) or (y shr (32-09))); y := x[ 2] + x[14]; x[ 6] := x[ 6] xor ((y shl 13) or (y shr (32-13))); y := x[ 6] + x[ 2]; x[10] := x[10] xor ((y shl 18) or (y shr (32-18))); y := x[15] + x[11]; x[ 3] := x[ 3] xor ((y shl 07) or (y shr (32-07))); y := x[ 3] + x[15]; x[ 7] := x[ 7] xor ((y shl 09) or (y shr (32-09))); y := x[ 7] + x[ 3]; x[11] := x[11] xor ((y shl 13) or (y shr (32-13))); y := x[11] + x[ 7]; x[15] := x[15] xor ((y shl 18) or (y shr (32-18))); y := x[ 0] + x[ 3]; x[ 1] := x[ 1] xor ((y shl 07) or (y shr (32-07))); y := x[ 1] + x[ 0]; x[ 2] := x[ 2] xor ((y shl 09) or (y shr (32-09))); y := x[ 2] + x[ 1]; x[ 3] := x[ 3] xor ((y shl 13) or (y shr (32-13))); y := x[ 3] + x[ 2]; x[ 0] := x[ 0] xor ((y shl 18) or (y shr (32-18))); y := x[ 5] + x[ 4]; x[ 6] := x[ 6] xor ((y shl 07) or (y shr (32-07))); y := x[ 6] + x[ 5]; x[ 7] := x[ 7] xor ((y shl 09) or (y shr (32-09))); y := x[ 7] + x[ 6]; x[ 4] := x[ 4] xor ((y shl 13) or (y shr (32-13))); y := x[ 4] + x[ 7]; x[ 5] := x[ 5] xor ((y shl 18) or (y shr (32-18))); y := x[10] + x[ 9]; x[11] := x[11] xor ((y shl 07) or (y shr (32-07))); y := x[11] + x[10]; x[ 8] := x[ 8] xor ((y shl 09) or (y shr (32-09))); y := x[ 8] + x[11]; x[ 9] := x[ 9] xor ((y shl 13) or (y shr (32-13))); y := x[ 9] + x[ 8]; x[10] := x[10] xor ((y shl 18) or (y shr (32-18))); y := x[15] + x[14]; x[12] := x[12] xor ((y shl 07) or (y shr (32-07))); y := x[12] + x[15]; x[13] := x[13] xor ((y shl 09) or (y shr (32-09))); y := x[13] + x[12]; x[14] := x[14] xor ((y shl 13) or (y shr (32-13))); y := x[14] + x[13]; x[15] := x[15] xor ((y shl 18) or (y shr (32-18))); end; procedure ChaChaDoubleRound(x: TSalsa20Instance.PBlock); var a, b, c, d: UInt32; begin a := x[0]; b := x[4]; c := x[8]; d:= x[12]; inc(a, b); d := a xor d; d := (d shl 16) or (d shr (32-16)); inc(c, d); b := c xor b; b := (b shl 12) or (b shr (32-12)); inc(a, b); d := a xor d; d := (d shl 8) or (d shr (32- 8)); inc(c, d); b := c xor b; b := (b shl 7) or (b shr (32- 7)); x[0] := a; x[4] := b; x[8] := c; x[12] := d; a := x[1]; b := x[5]; c := x[9]; d := x[13]; inc(a, b); d := a xor d; d := (d shl 16) or (d shr (32-16)); inc(c, d); b := c xor b; b := (b shl 12) or (b shr (32-12)); inc(a, b); d := a xor d; d := (d shl 8) or (d shr (32- 8)); inc(c, d); b := c xor b; b := (b shl 7) or (b shr (32- 7)); x[1] := a; x[5] := b; x[9] := c; x[13] := d; a := x[2]; b := x[6]; c := x[10]; d := x[14]; inc(a, b); d := a xor d; d := (d shl 16) or (d shr (32-16)); inc(c, d); b := c xor b; b := (b shl 12) or (b shr (32-12)); inc(a, b); d := a xor d; d := (d shl 8) or (d shr (32- 8)); inc(c, d); b := c xor b; b := (b shl 7) or (b shr (32- 7)); x[2] := a; x[6] := b; x[10] := c; x[14] := d; a := x[3]; b := x[7]; c := x[11]; d := x[15]; inc(a, b); d := a xor d; d := (d shl 16) or (d shr (32-16)); inc(c, d); b := c xor b; b := (b shl 12) or (b shr (32-12)); inc(a, b); d := a xor d; d := (d shl 8) or (d shr (32- 8)); inc(c, d); b := c xor b; b := (b shl 7) or (b shr (32- 7)); x[3] := a; x[7] := b; x[11] := c; x[15] := d; a := x[0]; b := x[5]; c := x[10]; d := x[15]; inc(a, b); d := a xor d; d := (d shl 16) or (d shr (32-16)); inc(c, d); b := c xor b; b := (b shl 12) or (b shr (32-12)); inc(a, b); d := a xor d; d := (d shl 8) or (d shr (32- 8)); inc(c, d); b := c xor b; b := (b shl 7) or (b shr (32- 7)); x[0] := a; x[5] := b; x[10] := c; x[15] := d; a := x[1]; b := x[6]; c := x[11]; d := x[12]; inc(a, b); d := a xor d; d := (d shl 16) or (d shr (32-16)); inc(c, d); b := c xor b; b := (b shl 12) or (b shr (32-12)); inc(a, b); d := a xor d; d := (d shl 8) or (d shr (32- 8)); inc(c, d); b := c xor b; b := (b shl 7) or (b shr (32- 7)); x[1] := a; x[6] := b; x[11] := c; x[12] := d; a := x[2]; b := x[7]; c := x[8]; d := x[13]; inc(a, b); d := a xor d; d := (d shl 16) or (d shr (32-16)); inc(c, d); b := c xor b; b := (b shl 12) or (b shr (32-12)); inc(a, b); d := a xor d; d := (d shl 8) or (d shr (32- 8)); inc(c, d); b := c xor b; b := (b shl 7) or (b shr (32- 7)); x[2] := a; x[7] := b; x[8] := c; x[13] := d; a := x[3]; b := x[4]; c := x[9]; d := x[14]; inc(a, b); d := a xor d; d := (d shl 16) or (d shr (32-16)); inc(c, d); b := c xor b; b := (b shl 12) or (b shr (32-12)); inc(a, b); d := a xor d; d := (d shl 8) or (d shr (32- 8)); inc(c, d); b := c xor b; b := (b shl 7) or (b shr (32- 7)); x[3] := a; x[4] := b; x[9] := c; x[14] := d; end; class function TSalsa20Instance.GetBlockSize(Inst: PSalsa20Instance): Integer; begin Result:= SALSA_BLOCK_SIZE; end; class function TSalsa20Instance.GetKeyParam(Inst: PSalsa20Instance; Param: UInt32; Data: Pointer; var DataLen: Cardinal): TF_RESULT; begin if (Param = TF_KP_NONCE) then begin if (DataLen >= SizeOf(UInt64)) then begin Move(Inst.FExpandedKey[6], Data^, SizeOf(UInt64)); DataLen:= SizeOf(UInt64); Result:= TF_S_OK; Exit; end end; Result:= TF_E_INVALIDARG; end; class function TSalsa20Instance.KeyBlock(Inst: PSalsa20Instance; Data: TSalsa20Instance.PBlock): TF_RESULT; var N: Cardinal; begin Move(Inst.FExpandedKey, Data^, SizeOf(TBlock)); N:= Inst.FRounds; repeat SalsaDoubleRound(Data); Dec(N); until N = 0; repeat Data[N]:= Data[N] + Inst.FExpandedKey[N]; Inc(N); until N = 16; Inc(Inst.FExpandedKey[8]); if (Inst.FExpandedKey[8] = 0) then Inc(Inst.FExpandedKey[9]); Result:= TF_S_OK; end; class function TSalsa20Instance.DuplicateKey(Inst: PSalsa20Instance; var Key: PSalsa20Instance): TF_RESULT; begin Result:= GetSalsa20InstanceEx(Key, Inst.FRounds shl 1); if Result = TF_S_OK then begin Key.FValidKey:= Inst.FValidKey; Key.FExpandedKey:= Inst.FExpandedKey; // Key.FRounds:= Inst.FRounds; end; end; class function TSalsa20Instance.ExpandKey(Inst: PSalsa20Instance; Key: PByte; KeySize: Cardinal): TF_RESULT; begin if (KeySize <> 16) and (KeySize <> 32) then begin Result:= TF_E_INVALIDARG; Exit; end; Move(Key^, Inst.FExpandedKey[1], 16); if KeySize = 16 then begin // 128-bit key Inst.FExpandedKey[0]:= Tau0; Inst.FExpandedKey[5]:= Tau1; Inst.FExpandedKey[10]:= Tau2; Inst.FExpandedKey[15]:= Tau3; Move(Key^, Inst.FExpandedKey[11], 16); end else begin // 256-bit key Inst.FExpandedKey[0]:= Sigma0; Inst.FExpandedKey[5]:= Sigma1; Inst.FExpandedKey[10]:= Sigma2; Inst.FExpandedKey[15]:= Sigma3; Move(PByte(Key)[16], Inst.FExpandedKey[11], 16); end; // 64-bit block number Inst.FExpandedKey[8]:= 0; Inst.FExpandedKey[9]:= 0; Inst.FValidKey:= True; Result:= TF_S_OK; end; class function TSalsa20Instance.ExpandKeyIV(Inst: PSalsa20Instance; Key: PByte; KeySize: Cardinal; IV: PByte; IVSize: Cardinal): TF_RESULT; begin Result:= TSalsa20Instance.SetIV(Inst, IV, IVSize); if Result = TF_S_OK then Result:= ExpandKey(Inst, Key, KeySize); end; class function TSalsa20Instance.ExpandKeyNonce(Inst: PSalsa20Instance; Key: PByte; KeySize: Cardinal; Nonce: UInt64): TF_RESULT; begin Result:= TSalsa20Instance.SetKeyParam(Inst, TF_KP_NONCE, @Nonce, SizeOf(Nonce)); if Result = TF_S_OK then Result:= ExpandKey(Inst, Key, KeySize); end; class function TSalsa20Instance.SetIV(Inst: PSalsa20Instance; Data: Pointer; DataLen: Cardinal): TF_RESULT; begin if (DataLen = SizeOf(UInt64)) then begin Move(Data^, Inst.FExpandedKey[6], SizeOf(UInt64)); // 64-byte block number Inst.FExpandedKey[8]:= 0; Inst.FExpandedKey[9]:= 0; Result:= TF_S_OK; end else Result:= TF_E_INVALIDARG; end; class function TSalsa20Instance.SetKeyParam(Inst: PSalsa20Instance; Param: UInt32; Data: Pointer; DataLen: Cardinal): TF_RESULT; type TUInt64Rec = record Lo, Hi: UInt32; end; var Tmp, Tmp1: UInt64; begin if (Param = TF_KP_IV) then begin { if (DataLen = SizeOf(UInt64)) then begin Move(Data^, Inst.FExpandedKey[6], SizeOf(UInt64)); // 64-byte block number Inst.FExpandedKey[8]:= 0; Inst.FExpandedKey[9]:= 0; Result:= TF_S_OK; Exit; end; Result:= TF_E_INVALIDARG; } Result:= TSalsa20Instance.SetIV(Inst, Data, DataLen); Exit; end; if (Param = TF_KP_NONCE) then begin if (DataLen > 0) and (DataLen <= SizeOf(UInt64)) then begin Inst.FExpandedKey[6]:= 0; Inst.FExpandedKey[7]:= 0; Move(Data^, Inst.FExpandedKey[6], DataLen); // 64-byte block number Inst.FExpandedKey[8]:= 0; Inst.FExpandedKey[9]:= 0; Result:= TF_S_OK; end else Result:= TF_E_INVALIDARG; Exit; end; if (Param = TF_KP_INCNO) then begin if (DataLen > 0) and (DataLen <= SizeOf(UInt64)) then begin // Salsa20 uses little-endian block numbers Tmp:= 0; TUInt64Rec(Tmp1).Lo:= Inst.FExpandedKey[8]; TUInt64Rec(Tmp1).Hi:= Inst.FExpandedKey[9]; Move(Data^, Tmp, DataLen); Tmp:= Tmp + Tmp1; Inst.FExpandedKey[8]:= TUInt64Rec(Tmp).Lo; Inst.FExpandedKey[9]:= TUInt64Rec(Tmp).Hi; Result:= TF_S_OK; end else Result:= TF_E_INVALIDARG; Exit; end; if (Param = TF_KP_DECNO) then begin if (DataLen > 0) and (DataLen <= SizeOf(UInt64)) then begin // Salsa20 uses little-endian block numbers Tmp1:= 0; TUInt64Rec(Tmp).Lo:= Inst.FExpandedKey[8]; TUInt64Rec(Tmp).Hi:= Inst.FExpandedKey[9]; Move(Data^, Tmp1, DataLen); Tmp:= Tmp - Tmp1; Inst.FExpandedKey[8]:= TUInt64Rec(Tmp).Lo; Inst.FExpandedKey[9]:= TUInt64Rec(Tmp).Hi; Result:= TF_S_OK; end else Result:= TF_E_INVALIDARG; Exit; end; Result:= TF_E_INVALIDARG; // Result:= TF_E_NOTIMPL; end; { TChaCha20 } class function TChaCha20.DuplicateKey(Inst: PSalsa20Instance; var Key: PSalsa20Instance): TF_RESULT; begin Result:= GetChaCha20InstanceEx(Key, Inst.FRounds shl 1); if Result = TF_S_OK then begin Key.FValidKey:= Inst.FValidKey; Key.FExpandedKey:= Inst.FExpandedKey; // Key.FRounds:= Inst.FRounds; end; end; class function TChaCha20.ExpandKey(Inst: PSalsa20Instance; Key: PByte; KeySize: Cardinal): TF_RESULT; begin if (KeySize <> 16) and (KeySize <> 32) then begin Result:= TF_E_INVALIDARG; Exit; end; if KeySize = 16 then begin // 128-bit key Inst.FExpandedKey[0]:= Tau0; Inst.FExpandedKey[1]:= Tau1; Inst.FExpandedKey[2]:= Tau2; Inst.FExpandedKey[3]:= Tau3; Move(Key^, Inst.FExpandedKey[4], 16); Move(Key^, Inst.FExpandedKey[8], 16); end else begin // 256-bit key Inst.FExpandedKey[0]:= Sigma0; Inst.FExpandedKey[1]:= Sigma1; Inst.FExpandedKey[2]:= Sigma2; Inst.FExpandedKey[3]:= Sigma3; Move(Key^, Inst.FExpandedKey[4], 32); end; // 64-bit block number Inst.FExpandedKey[12]:= 0; Inst.FExpandedKey[13]:= 0; Inst.FValidKey:= True; Result:= TF_S_OK; end; class function TChaCha20.ExpandKeyIV(Inst: PSalsa20Instance; Key: PByte; KeySize: Cardinal; IV: PByte; IVSize: Cardinal): TF_RESULT; begin Result:= TChaCha20.SetIV(Inst, IV, IVSize); if Result = TF_S_OK then Result:= ExpandKey(Inst, Key, KeySize); end; class function TChaCha20.ExpandKeyNonce(Inst: PSalsa20Instance; Key: PByte; KeySize: Cardinal; Nonce: UInt64): TF_RESULT; begin Result:= TChaCha20.SetKeyParam(Inst, TF_KP_NONCE, @Nonce, SizeOf(Nonce)); if Result = TF_S_OK then Result:= ExpandKey(Inst, Key, KeySize); end; class function TChaCha20.GetKeyParam(Inst: PSalsa20Instance; Param: UInt32; Data: Pointer; var DataLen: Cardinal): TF_RESULT; begin if (Param = TF_KP_NONCE) then begin if (DataLen >= SizeOf(UInt64)) then begin Move(Inst.FExpandedKey[14], Data^, SizeOf(UInt64)); DataLen:= SizeOf(UInt64); Result:= TF_S_OK; Exit; end end; Result:= TF_E_INVALIDARG; end; class function TChaCha20.KeyBlock(Inst: PSalsa20Instance; Data: TSalsa20Instance.PBlock): TF_RESULT; var N: Cardinal; begin Move(Inst.FExpandedKey, Data^, SizeOf(TSalsa20Instance.TBlock)); N:= Inst.FRounds; repeat ChaChaDoubleRound(Data); Dec(N); until N = 0; repeat Data[N]:= Data[N] + Inst.FExpandedKey[N]; Inc(N); until N = 16; Inc(Inst.FExpandedKey[12]); if (Inst.FExpandedKey[12] = 0) then Inc(Inst.FExpandedKey[13]); Result:= TF_S_OK; end; class function TChaCha20.SetIV(Inst: PSalsa20Instance; Data: Pointer; DataLen: Cardinal): TF_RESULT; begin if (DataLen = SizeOf(UInt64)) then begin Move(Data^, Inst.FExpandedKey[14], SizeOf(UInt64)); // 64-byte block number Inst.FExpandedKey[12]:= 0; Inst.FExpandedKey[13]:= 0; Result:= TF_S_OK; end else begin Result:= TF_E_INVALIDARG; end; end; class function TChaCha20.SetKeyParam(Inst: PSalsa20Instance; Param: UInt32; Data: Pointer; DataLen: Cardinal): TF_RESULT; type TUInt64Rec = record Lo, Hi: UInt32; end; var Tmp, Tmp1: UInt64; begin if (Param = TF_KP_IV) then begin Result:= TChaCha20.SetIV(Inst, Data, DataLen); { if (DataLen = SizeOf(UInt64)) then begin Move(Data^, Inst.FExpandedKey[14], SizeOf(UInt64)); // 64-byte block number Inst.FExpandedKey[12]:= 0; Inst.FExpandedKey[13]:= 0; Result:= TF_S_OK; end else begin Result:= TF_E_INVALIDARG; end; } Exit; end; if (Param = TF_KP_NONCE) then begin if (DataLen > 0) and (DataLen <= SizeOf(UInt64)) then begin Inst.FExpandedKey[14]:= 0; Inst.FExpandedKey[15]:= 0; Move(Data^, Inst.FExpandedKey[14], DataLen); // 64-byte block number Inst.FExpandedKey[12]:= 0; Inst.FExpandedKey[13]:= 0; Result:= TF_S_OK; end else Result:= TF_E_INVALIDARG; Exit; end; if (Param = TF_KP_INCNO) then begin if (DataLen > 0) and (DataLen <= SizeOf(UInt64)) then begin // Salsa20 uses little-endian block numbers Tmp:= 0; TUInt64Rec(Tmp1).Lo:= Inst.FExpandedKey[12]; TUInt64Rec(Tmp1).Hi:= Inst.FExpandedKey[13]; Move(Data^, Tmp, DataLen); Tmp:= Tmp + Tmp1; Inst.FExpandedKey[12]:= TUInt64Rec(Tmp).Lo; Inst.FExpandedKey[13]:= TUInt64Rec(Tmp).Hi; Result:= TF_S_OK; end else Result:= TF_E_INVALIDARG; Exit; end; if (Param = TF_KP_DECNO) then begin if (DataLen > 0) and (DataLen <= SizeOf(UInt64)) then begin // Salsa20 uses little-endian block numbers Tmp1:= 0; TUInt64Rec(Tmp).Lo:= Inst.FExpandedKey[12]; TUInt64Rec(Tmp).Hi:= Inst.FExpandedKey[13]; Move(Data^, Tmp1, DataLen); Tmp:= Tmp - Tmp1; Inst.FExpandedKey[12]:= TUInt64Rec(Tmp).Lo; Inst.FExpandedKey[13]:= TUInt64Rec(Tmp).Hi; Result:= TF_S_OK; end else Result:= TF_E_INVALIDARG; Exit; end; Result:= TF_E_INVALIDARG; end; { TChaChaPRG } function TChaChaPRG.Init(Seed: PByte; SeedSize: Cardinal): TF_RESULT; begin if (SeedSize <> 24) and (SeedSize <> 40) then begin Result:= TF_E_INVALIDARG; Exit; end; if SeedSize = 24 then begin // 128-bit key FExpandedKey[0]:= Tau0; FExpandedKey[1]:= Tau1; FExpandedKey[2]:= Tau2; FExpandedKey[3]:= Tau3; Move(Seed^, FExpandedKey[4], 16); Move(Seed^, FExpandedKey[8], 16); Move((Seed + 16)^, FExpandedKey[14], 8); end else begin // 256-bit key FExpandedKey[0]:= Sigma0; FExpandedKey[1]:= Sigma1; FExpandedKey[2]:= Sigma2; FExpandedKey[3]:= Sigma3; Move(Seed^, FExpandedKey[4], 32); Move((Seed + 32)^, FExpandedKey[14], 8); end; // 64-bit block number FExpandedKey[12]:= 0; FExpandedKey[13]:= 0; Result:= TF_S_OK; end; function TChaChaPRG.GetKeyStream(Buf: PByte; BufSize: Cardinal): TF_RESULT; var N: Cardinal; begin // should be multiple of 64 if BufSize and $3F <> 0 then begin Result:= TF_E_INVALIDARG; Exit; end; while BufSize > 0 do begin Move(FExpandedKey, Buf^, SizeOf(FExpandedKey)); N:= 10; repeat ChaChaDoubleRound(TSalsa20Instance.PBlock(Buf)); Dec(N); until N = 0; repeat PUInt32(Buf)^:= PUInt32(Buf)^ + FExpandedKey[N]; Inc(PUInt32(Buf)); Inc(N); until N = 16; Inc(FExpandedKey[12]); if (FExpandedKey[12] = 0) then Inc(FExpandedKey[13]); Dec(BufSize, 64); end; Result:= TF_S_OK; end; end.
unit dcLabel; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, DataController, dbctrls, db, FFSTypes; type TdcLabel = class(TLabel) private { Private declarations } fdcLink : TdcLink; fTranData : String; function GetDatabufIndex: integer; procedure SetDataBufIndex(const Value: integer); protected { Protected declarations } // std data awareness function GetDataSource:TDataSource; procedure SetDataSource(value:Tdatasource); function GetDataField:string; procedure SetDataField(value:string); // data controller function GetDataController:TDataController; procedure SetDataController(value:TDataController); procedure ReadData(sender:TObject); procedure ClearData(sender:TObject); public { Public declarations } constructor Create(AOwner:Tcomponent);override; destructor Destroy;override; property TranData : String read fTranData; published { Published declarations } property DataController : TDataController read GetDataController write setDataController; property DataField : String read GetDataField write SetDataField; property DataSource : TDataSource read getDataSource write SetDatasource; property DatabufIndex:integer read GetDatabufIndex write SetDataBufIndex; end; procedure Register; implementation constructor TdcLabel.Create(AOwner:Tcomponent); begin inherited; fdclink := tdclink.create(self); with fdcLink do begin OnReadData := ReadData; OnWriteData := nil; OnClearData := ClearData; end; AutoSize := false; end; destructor TdcLabel.Destroy; begin fdclink.Free; inherited; end; procedure TdcLabel.SetDataController(value:TDataController); begin fdcLink.datacontroller := value; end; function TdcLabel.GetDataController:TDataController; begin result := fdcLink.DataController; end; procedure TdcLabel.SetDataSource(value:TDataSource); begin end; function TdcLabel.GetDataField:string; begin result := fdclink.FieldName; end; function TdcLabel.GetDataSource:TDataSource; begin result := fdclink.DataSource; end; procedure TdcLabel.SetDataField(value:string); begin fdclink.FieldName := value; end; procedure TdcLabel.ReadData; begin if fdclink.DataController <> nil then begin if assigned(fdclink.datacontroller.databuf) then text := fdclink.datacontroller.databuf.AsString[DataBufIndex]; end; end; procedure TdcLabel.ClearData; begin if fdclink.Field <> nil then begin caption := trim(fdclink.Field.DefaultExpression); end; end; procedure Register; begin RegisterComponents('FFS Data Entry', [TdcLabel]); end; function TdcLabel.GetDatabufIndex: integer; begin result := 0; if assigned(fdclink.Datacontroller) then if assigned(fdclink.datacontroller.databuf) then result := fdclink.datacontroller.databuf.FieldNameToIndex(fdclink.FieldName); end; procedure TdcLabel.SetDataBufIndex(const Value: integer); begin end; end.
unit Model.ListagemMovimentacoesJornal; interface uses FireDAC.Comp.Client, System.SysUtils, DAO.Conexao, Controller.Sistema, Common.ENum, Common.Utils, System.DateUtils, Model.PlanilhaMovimentacaoJornal; type TMovimentacoes = class private FProduto: String; FBairro: String; FCodigo: String; FAgente: Integer; FComplemento: String; FModalidade: Integer; FNome: String; FEndereco: String; FEdicao: TDateTime; FAcao: TAcao; FString: String; FID: Integer; FConexao : TConexao; function Insert(): Boolean; function Update(): Boolean; function Delete(): Boolean; public constructor Create(); property ID: Integer read FID write FID; property Agente: Integer read FAgente write FAgente; property Status: String read FString write FString; property Edicao: TDateTime read FEdicao write FEdicao; property Endereco: String read FEndereco write FEndereco; property Complemento: String read FComplemento write FComplemento; property Bairro: String read FBairro write FBairro; property Codigo: String read FCodigo write FCodigo; property Nome: String read FNome write FNome; property Produto: String read FProduto write FProduto; property Modalidade: Integer read FModalidade write FModalidade; property Acao: TAcao read FAcao write FAcao; function Gravar(): Boolean; function DeleteEdicao(): Boolean; function Localizar(aParam: array of variant): TFDQuery; function QueryInsertMode(): TFDQuery; end; const TABLENAME = 'listagem_movimentacoes'; SQLINSERT = 'INSERT INTO ' + TABLENAME + '(cod_agente, dat_edicao, des_status, des_endereco, des_complemento, ' + 'des_bairro, cod_assinante, nom_assinante, des_produto, cod_modalidade) ' + 'VALUES ' + '(:cod_agente, :dat_edicao, :des_status, :des_endereco, :des_complemento, :des_bairro, ' + ':cod_assinante, :nom_assinante, :des_produto, :cod_modalidade);'; SQLUPDATE = 'UPDATE ' + TABLENAME + 'SET cod_agente = :cod_agente, dat_edicao = :dat_edicao, ' + 'des_status = :des_status, des_endereco = :des_endereco, des_complemento = :des_complemento, ' + 'des_bairro = :des_bairro, cod_assinante = :cod_assinante, nom_assinante = :nom_assinante, ' + 'des_produto = :des_produto, cod_modalidade = :cod_modalidade '+ 'WHERE id_registro = :id_registro;'; implementation { TMovimentacoes } constructor TMovimentacoes.Create; begin FConexao := TConexao.Create; end; function TMovimentacoes.Delete: Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FDQuery.ExecSQL('delete from ' + TABLENAME + ' WHERE id_registro = :pid_registro', [FID]); Result := True; finally FDquery.Free; end; end; function TMovimentacoes.DeleteEdicao: Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FDQuery.ExecSQL('delete from ' + TABLENAME + ' WHERE dat_edicao = :pdat_edicao', [FEdicao]); FEdicao := IncDaY(FEdicao - 7); FDQuery.ExecSQL('delete from ' + TABLENAME + ' WHERE dat_edicao <= :pdat_edicao', [FEdicao]); Result := True; finally FDquery.Free; end; end; function TMovimentacoes.Gravar: Boolean; begin case FAcao of tacIncluir: Result := Self.Insert(); tacAlterar: Result := Self.Update(); tacExcluir: Result := Self.Delete(); tacDeleteData: Result := Self.DeleteEdicao(); end; end; function TMovimentacoes.Insert: Boolean; var FDQuery: TFDQuery; begin try Result := False; FConexao:= TConexao.Create; FDQuery := FConexao.ReturnQuery; FDQuery.ExecSQL(SQLINSERT,[Self.FAgente,Self.FEdicao, Self.FEdicao, Self.FEndereco, Self.FComplemento, Self.FBairro, Self.FCodigo, Self.Nome, Self.FProduto, Self.FModalidade]); Result := True; finally FDQuery.Free; FConexao.Free; end; end; function TMovimentacoes.Localizar(aParam: array of variant): TFDQuery; var FDQuery: TFDQuery; begin try FConexao:= TConexao.Create; FDQuery := FConexao.ReturnQuery(); if Length(aParam) < 2 then Exit; FDQuery.SQL.Clear; FDQuery.SQL.Add('select * from ' + TABLENAME); if aParam[0] = 'ID' then begin FDQuery.SQL.Add('WHERE id_registro = :pid_registro'); FDQuery.ParamByName('pid_registro').AsInteger := aParam[1]; end; if aParam[0] = 'AGENTE' then begin FDQuery.SQL.Add('WHERE cod_agente = :pcod_agente'); FDQuery.ParamByName('pcod_agente').AsString := aParam[1]; end; if aParam[0] = 'EDICAO' then begin FDQuery.SQL.Add('WHERE dat_edicao = :pdat_edicao'); FDQuery.ParamByName('pdat_edicao').AsDate := aParam[1]; end; if aParam[0] = 'CODIGO' then begin FDQuery.SQL.Add('WHERE cod_assinatura = :pcod_assinatura'); FDQuery.ParamByName('pcod_assinatura').AsString := aParam[1]; end; if aParam[0] = 'NOME' then begin FDQuery.SQL.Add('WHERE nom_assinante like :pnom_assinante'); FDQuery.ParamByName('pnom_assinante').AsString := aParam[1]; end; if aParam[0] = 'FILTRO' then begin FDQuery.SQL.Add('WHERE ' + 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(); Result := FDQuery; finally FConexao.Free; end; end; function TMovimentacoes.QueryInsertMode: TFDQuery; var FDQuery: TFDQuery; begin FConexao:= TConexao.Create; FDQuery := FConexao.ReturnQuery(); FDQuery.SQL.Text := SQLINSERT; Result := FDQuery; end; function TMovimentacoes.Update: Boolean; var FDQuery: TFDQuery; begin try Result := False; FConexao:= TConexao.Create; FDQuery := FConexao.ReturnQuery; FDQuery.ExecSQL(SQLUPDATE,[Self.FAgente,Self.FEdicao, Self.FEdicao, Self.FEndereco, Self.FComplemento, Self.FBairro, Self.FCodigo, Self.Nome, Self.FProduto, Self.FModalidade, Self.FID]); Result := True; finally FDQuery.Free; FConexao.Free; end; end; end.
{ Clever Internet Suite Copyright (C) 2013 Clever Components All Rights Reserved www.CleverComponents.com } unit clZLibBuffer; interface {$I clVer.inc} uses {$IFNDEF DELPHIXE2} Classes, SysUtils, {$ELSE} System.Classes, System.SysUtils, {$ENDIF} clUtils, clZLibBase, clWUtils; type TclDeflateBuffer = class private FStart: Integer; FEnd: Integer; FBits: LongWord; FBitCount: Integer; FBuf: TclByteArray; procedure WriteBuf(b: Byte); function GetIsFlushed: Boolean; public constructor Create; overload; constructor Create(ABufSize: Integer); overload; procedure Reset(); procedure WriteByte(AValue: Integer); procedure WriteShort(AValue: Integer); procedure WriteInt(AValue: Integer); procedure WriteBlock(const ABlock: TclByteArray; AOffset, ALen: Integer); procedure WriteBits(AValue, ACount: Integer); procedure WriteShortMSB(AValue: Integer); procedure AlignToByte; function Flush(var AOutput: TclByteArray; AOffset, ALen: Integer): Integer; property BitCount: Integer read FBitCount; property IsFlushed: Boolean read GetIsFlushed; end; TclInflateBuffer = class private FWindow: PclChar; FWindow_start: Integer; FWindow_end: Integer; FBuffer: LongWord; FBits_in_buffer: Integer; function GetAvailableBytes: Integer; function GetIsNeedingInput: Boolean; public constructor Create; function PeekBits(n: Integer): Integer; procedure DropBits(n: Integer); procedure SkipToByteBoundary; function CopyBytes(var AOutput: TclByteArray; AOffset, ALen: Integer): Integer; procedure SetInput(const ABuffer; AOffset, ALen: Integer); procedure Reset; property AvailableBits: Integer read FBits_in_buffer; property AvailableBytes: Integer read GetAvailableBytes; property IsNeedingInput: Boolean read GetIsNeedingInput; end; implementation { TclDeflateBuffer } constructor TclDeflateBuffer.Create; begin Create(4096); end; procedure TclDeflateBuffer.AlignToByte; begin if (FBitCount > 0) then begin WriteBuf(Byte(FBits)); if (FBitCount > 8) then begin WriteBuf(Byte(FBits shr 8)); end; end; FBits := 0; FBitCount := 0; end; constructor TclDeflateBuffer.Create(ABufSize: Integer); begin inherited Create(); SetLength(FBuf, ABufSize); end; function TclDeflateBuffer.Flush(var AOutput: TclByteArray; AOffset, ALen: Integer): Integer; begin if (FBitCount >= 8) then begin WriteBuf(Byte(FBits)); FBits := FBits shr 8; Dec(FBitCount, 8); end; if (ALen > FEnd - FStart) then begin ALen := FEnd - FStart; Move(FBuf[FStart], AOutput[AOffset], ALen); FStart := 0; FEnd := 0; end else begin Move(FBuf[FStart], AOutput[AOffset], ALen); Inc(FStart, ALen); end; Result := ALen; end; function TclDeflateBuffer.GetIsFlushed: Boolean; begin Result := (FEnd = 0); end; procedure TclDeflateBuffer.Reset; begin FStart := 0; FEnd := 0; FBitCount := 0; end; procedure TclDeflateBuffer.WriteBits(AValue, ACount: Integer); begin FBits := FBits or LongWord(AValue shl FBitCount); Inc(FBitCount, ACount); if (FBitCount >= 16) then begin WriteBuf(Byte(FBits)); WriteBuf(Byte(FBits shr 8)); FBits := FBits shr 16; Dec(FBitCount, 16); end; end; procedure TclDeflateBuffer.WriteBlock(const ABlock: TclByteArray; AOffset, ALen: Integer); begin Move(ABlock[AOffset], FBuf[FEnd], ALen); Inc(FEnd, ALen); end; procedure TclDeflateBuffer.WriteByte(AValue: Integer); begin WriteBuf(Byte(AValue)); end; procedure TclDeflateBuffer.WriteBuf(b: Byte); begin FBuf[FEnd] := b; Inc(FEnd); end; procedure TclDeflateBuffer.WriteInt(AValue: Integer); begin WriteBuf(Byte(AValue)); WriteBuf(Byte(AValue shr 8)); WriteBuf(Byte(AValue shr 16)); WriteBuf(Byte(AValue shr 24)); end; procedure TclDeflateBuffer.WriteShort(AValue: Integer); begin WriteBuf(Byte(AValue)); WriteBuf(Byte(AValue shr 8)); end; procedure TclDeflateBuffer.WriteShortMSB(AValue: Integer); begin WriteBuf(Byte(AValue shr 8)); WriteBuf(Byte(AValue)); end; { TclInflateBuffer } function TclInflateBuffer.CopyBytes(var AOutput: TclByteArray; AOffset, ALen: Integer): Integer; var count, avail: Integer; begin if (ALen < 0) then begin raise EclZLibError.Create(ZLibOutOfRange, ZLibOutOfRangeCode); end; if ((FBits_in_buffer and 7) <> 0) then begin raise EclZLibError.Create(ZLibInvalidBitBuffer, ZLibInvalidBitBufferCode); end; count := 0; while (FBits_in_buffer > 0) and (ALen > 0) do begin AOutput[AOffset] := Byte(FBuffer); Inc(AOffset); FBuffer := FBuffer shr 8; Dec(FBits_in_buffer, 8); Dec(ALen); Inc(count); end; if (ALen = 0) then begin Result := count; Exit; end; avail := FWindow_end - FWindow_start; if (ALen > avail) then begin ALen := avail; end; Move(FWindow[FWindow_start], AOutput[AOffset], ALen); Inc(FWindow_start, ALen); if (((FWindow_start - FWindow_end) and 1) <> 0) then begin FBuffer := LongWord(Byte(FWindow[FWindow_start]) and $ff); Inc(FWindow_start); FBits_in_buffer := 8; end; Result := count + ALen; end; constructor TclInflateBuffer.Create; begin inherited Create(); Reset(); end; procedure TclInflateBuffer.DropBits(n: Integer); begin FBuffer := FBuffer shr n; Dec(FBits_in_buffer, n); end; function TclInflateBuffer.GetAvailableBytes: Integer; begin Result := FWindow_end - FWindow_start + (FBits_in_buffer shr 3); end; function TclInflateBuffer.GetIsNeedingInput: Boolean; begin Result := (FWindow_start = FWindow_end); end; function TclInflateBuffer.PeekBits(n: Integer): Integer; begin if (FBits_in_buffer < n) then begin if (FWindow_start = FWindow_end) then begin Result := -1; Exit; end; FBuffer := FBuffer or LongWord((Byte(FWindow[FWindow_start]) and $ff or (Byte(FWindow[FWindow_start + 1]) and $ff) shl 8) shl FBits_in_buffer); Inc(FWindow_start, 2); Inc(FBits_in_buffer, 16); end; Result := Integer(FBuffer and ((1 shl n) - 1)); end; procedure TclInflateBuffer.Reset; begin FWindow_start := 0; FWindow_end := 0; FBuffer := 0; FBits_in_buffer := 0; end; procedure TclInflateBuffer.SetInput(const ABuffer; AOffset, ALen: Integer); var _end: Integer; begin if (FWindow_start < FWindow_end) then begin raise EclZLibError.Create(ZLibInputNotProcessed, ZLibInputNotProcessedCode); end; _end := AOffset + ALen; if (0 > AOffset) or (AOffset > _end) then begin raise EclZLibError.Create(ZLibOutOfRange, ZLibOutOfRangeCode); end; FWindow := @ABuffer; if ((ALen and 1) <> 0) then begin FBuffer := FBuffer or LongWord((Byte(FWindow[AOffset]) and $ff) shl FBits_in_buffer); Inc(AOffset); Inc(FBits_in_buffer, 8); end; FWindow_start := AOffset; FWindow_end := _end; end; procedure TclInflateBuffer.SkipToByteBoundary; begin FBuffer := FBuffer shr (FBits_in_buffer and 7); FBits_in_buffer := FBits_in_buffer and (not 7); end; end.
unit uTokenThread; interface uses Winapi.Windows, System.SysUtils, System.Classes, Winapi.ActiveX, Winapi.WinInet, Winapi.ShellAPI, Winapi.Messages, ManSoy.Encode, uData, IdTCPClient, IdHTTP; type PQQTokensData = ^TQQTokensData; TQQTokensData = packed record szEvent:string[50]; szQQUin:string[50]; szInitCode:string[100]; szOriginalSn:string[50]; szSerialNumber:string[200]; szDnyPsw:string[50]; szDnyPswTime:string[100]; end; TTokenThread = class(TThread) private FAccount : string; FMBType : Integer; FKey : string; FTokenServerIp : string; FTokenServerPort : WORD; function DownloadKMFiles(AFileName: string): Boolean; function InitTokenFiles: boolean; function GetToken(AMBType: Integer): string; protected procedure Execute; override; public constructor Create(AAccount: string; AMBType: Integer); destructor Destroy; override; property Account : string read FAccount write FAccount; property MBType : Integer read FMBType write FMBType; property Key : string read FKey write FKey; property TokenServerIp : string read FTokenServerIp write FTokenServerIp; property TokenServerPort: WORD read FTokenServerPort write FTokenServerPort; end; var URL_Download_KM_File : string = ''; TokenPackData : TQQTokensData; IdTCPClient: TIdTcpClient; implementation uses System.IniFiles, System.StrUtils, System.Win.ComObj, ManSoy.MsgBox, ManSoy.Global, uFun, DmUtils; { TDispatchThread } constructor TTokenThread.Create(AAccount: string; AMBType: Integer); begin FAccount := AAccount; FMBType := AMBType; FKey := ''; with TIniFile.Create(ExtractFilePath(ParamStr(0))+'QuitSafeConfig\Cfg.ini') do try FTokenServerIp := ReadString('TokenSvr', 'Host', '113.140.30.46'); //192.168.192.252 FTokenServerPort := ReadInteger('TokenSvr', 'Port', 59998); //8899 URL_Download_KM_File := ReadString('KEmulator', 'url', ''); finally Free; end; InitTokenFiles; FreeOnTerminate := True; inherited Create(false); end; destructor TTokenThread.Destroy; begin inherited; end; function TTokenThread.InitTokenFiles: Boolean; var tokenSrc_dir,tokenSrcZip_file, tokenDir_old,kemulatorDir_old, tokenDir_new,kemulatorDir_new: string; begin result := false; tokenSrc_dir := Format(TOKEN_SRC_DIR, [ExtractFileDir(ParamStr(0)), FAccount]); tokenSrcZip_file := Format(TOKEN_SRC_ZIP_FILE, [ExtractFileDir(ParamStr(0)), FAccount]); tokenDir_old := Format(TOKEN_DIR_OLD, [ExtractFileDir(ParamStr(0))]); kemulatorDir_old := Format(KEMULATOR_DIR_OLD, [ExtractFileDir(ParamStr(0))]); tokenDir_new := Format(TOKEN_DIR_NEW, [ExtractFileDir(ParamStr(0))]); kemulatorDir_new := Format(KEMULATOR_DIR_NEW, [ExtractFileDir(ParamStr(0))]); case FMBType of 40: //KM(new) begin DeleteFile(tokenSrcZip_file); //删除令牌压缩文件 DelDir(tokenSrc_dir); //删除令牌解压后的文件夹 LogOut('下载令牌文件(new)...', []); if not DownloadKMFiles(tokenSrcZip_file) then Exit; //下载令牌文件 LogOut('解压令牌文件...', []); Unzip(tokenSrcZip_file, tokenSrc_dir); //解压令牌文件 LogOut('清理.token_config目录...', []); ClearDir(tokenDir_new); LogOut('拷贝令牌文件到.token_config目录...', []); CopyDir(tokenSrc_dir, tokenDir_new, false); end; 50: //KM(old) begin DeleteFile(tokenSrcZip_file); //删除令牌压缩文件 DelDir(tokenSrc_dir); //删除令牌解压后的文件夹 LogOut('下载令牌文件(old)...', []); if not DownloadKMFiles(tokenSrcZip_file) then Exit; //下载令牌文件 LogOut('解压令牌文件...', []); Unzip(tokenSrcZip_file, tokenSrc_dir); //解压令牌文件 LogOut('清理.token_config目录...', []); ClearDir(tokenDir_new); LogOut('拷贝令牌文件到.token_config目录...', []); CopyDir(tokenSrc_dir, tokenDir_old, false); end; end; result:= true; end; function TTokenThread.DownloadKMFiles(AFileName: string): Boolean; var vResponseContent: TMemoryStream; vParam: TStrings; hFile: HWND; http: TIdHTTP; dir: string; begin Result := False; DeleteFile(AFileName); vResponseContent := TMemoryStream.Create; vParam := TStringList.Create; http := TIdHTTP.Create(nil); try vParam.Add('GAME_ACCOUNT_NAME='+FAccount); vParam.Add('SAFE_CODE='+SAFE_CODE); http.Post(URL_Download_KM_File, vParam, vResponseContent); dir := ExtractFileDir(AFileName); if not DirectoryExists(dir) then ForceDirectories(dir); vResponseContent.SaveToFile(AFileName); hFile := FileOpen(AFileName, 0); Result := GetFileSize(hFile, nil) > 0; FileClose(hFile); finally vResponseContent.Free; vParam.Free; http.Disconnect; FreeAndNil(http); end; end; procedure TTokenThread.Execute; var sToken:string; begin try ManSoy.Global.DebugInf('MS - 开始账号登录...', []); sToken := GetToken(FMBType); if sToken <> '' then begin ManSoy.MsgBox.InfoMsg(0, '令牌数字【%s】'#13'已经复制到剪切板', [sToken]); WriteClipboard(sToken); end else begin ManSoy.MsgBox.WarnMsg(0, '获取令牌失败', []); end; except on E: Exception do begin ManSoy.MsgBox.WarnMsg(0, '获取动态口令异常'#13'%s', [E.Message]); Exit; end; end; end; function TTokenThread.GetToken(AMBType: Integer): string; var hKEmulator,dwDealyTimes: HWND; tokenSrc_dir,tokenSrcZip_file, tokenDir_old,kemulatorDir_old, tokenDir_new,kemulatorDir_new: string; I: Integer; pt: TPoint; s, subPic: string; begin Result := ''; tokenSrc_dir := Format(TOKEN_SRC_DIR, [ExtractFileDir(ParamStr(0)), FAccount]); tokenSrcZip_file := Format(TOKEN_SRC_ZIP_FILE, [ExtractFileDir(ParamStr(0)), FAccount]); tokenDir_old := Format(TOKEN_DIR_OLD, [ExtractFileDir(ParamStr(0))]); kemulatorDir_old := Format(KEMULATOR_DIR_OLD, [ExtractFileDir(ParamStr(0))]); tokenDir_new := Format(TOKEN_DIR_NEW, [ExtractFileDir(ParamStr(0))]); kemulatorDir_new := Format(KEMULATOR_DIR_NEW, [ExtractFileDir(ParamStr(0))]); try try case AMBType of 40: //KM(new) begin LogOut('打开手机令牌模拟器...', []); ShellExecute(0, nil, PChar(KEMULATOR_BAT), nil, PChar(kemulatorDir_new), SW_HIDE); dwDealyTimes := GetTickCount; while GetTickCount - dwDealyTimes < 1 * 60 * 1000 do begin hKEmulator := FindWindow(nil, 'KEmulator Lite v0.9.8'); if not IsWindow(hKEmulator) then continue; pt := DmUtils.fnFindWordOnWindow(hKEmulator, '动态密码', 'ffffff-000000', SYS_DICT); if (pt.X <> -1) and (pt.Y <> -1) then Break; end; if (pt.X = -1) or (pt.Y = -1) then begin LogOut('打开手机令牌模拟器超时,退出...', []); Exit; end; LogOut('获取手机令牌...', []); s := ''; subPic := ExtractFilePath(ParamStr(0)) + 'Bmp\%d.bmp'; //第1位 for I := 0 to 9 do begin if DmUtils.fnPicExistOnWindowArea(hKEmulator, 49,128,75,177, Format(subPic, [I])) then //if DmUtils.fnPicExistOnWindowArea(hKEmulator, 46,87,72,126,ExtractFilePath(ParamStr(0))+Format('Bmp\%d.bmp', [I])) then begin s := s + IntToStr(I); Break; end; end; //第2位 for I := 0 to 9 do begin if DmUtils.fnPicExistOnWindowArea(hKEmulator, 74,128,100,177,Format(subPic, [I])) then //if DmUtils.fnPicExistOnWindowArea(hKEmulator, 71,87,97,126,ExtractFilePath(ParamStr(0))+Format('Bmp\%d.bmp', [I])) then begin s := s + IntToStr(I); Break; end; end; //第3位 for I := 0 to 9 do begin if DmUtils.fnPicExistOnWindowArea(hKEmulator, 99,128,125,177,Format(subPic, [I])) then //if DmUtils.fnPicExistOnWindowArea(hKEmulator, 96,87,122,126,ExtractFilePath(ParamStr(0))+Format('Bmp\%d.bmp', [I])) then begin s := s + IntToStr(I); Break; end; end; //第4位 for I := 0 to 9 do begin if DmUtils.fnPicExistOnWindowArea(hKEmulator, 124,128,150,177,Format(subPic, [I])) then //if DmUtils.fnPicExistOnWindowArea(hKEmulator, 121,87,147,126,ExtractFilePath(ParamStr(0))+Format('Bmp\%d.bmp', [I])) then begin s := s + IntToStr(I); Break; end; end; //第5位 for I := 0 to 9 do begin if DmUtils.fnPicExistOnWindowArea(hKEmulator, 149,128,175,177,Format(subPic, [I])) then //if DmUtils.fnPicExistOnWindowArea(hKEmulator, 146,87,172,126,ExtractFilePath(ParamStr(0))+Format('Bmp\%d.bmp', [I])) then begin s := s + IntToStr(I); Break; end; end; //第6位 for I := 0 to 9 do begin if DmUtils.fnPicExistOnWindowArea(hKEmulator, 174,128,200,177,Format(subPic, [I])) then //if DmUtils.fnPicExistOnWindowArea(hKEmulator, 171,87,197,126,ExtractFilePath(ParamStr(0))+Format('Bmp\%d.bmp', [I])) then begin s := s + IntToStr(I); Break; end; end; SendMessage(hKEmulator, WM_CLOSE, 0, 0); LogOut('得到令牌:%s', [s]); if Length(s) <> 6 then begin LogOut('手机令牌错误,退出...', []); Exit; end; TokenPackData.szDnyPsw := s; LogOut('删除令牌文件...', []); end; 50: //KM(old) begin LogOut('打开手机令牌模拟器...', []); ShellExecute(0, nil, PChar(KEMULATOR_BAT), nil, PChar(kemulatorDir_old), SW_HIDE); dwDealyTimes := GetTickCount; while GetTickCount - dwDealyTimes < 1 * 60 * 1000 do begin hKEmulator := FindWindow(nil, 'KEmulator Lite v0.9.8'); if IsWindow(hKEmulator) then Break; end; if not IsWindow(hKEmulator) then begin LogOut('打开手机令牌模拟器超时,退出...', []); Exit; end; LogOut('获取手机令牌...', []); TokenPackData.szDnyPsw := DmUtils.fnFindWordByColor(hKEmulator, 50, 60, 200, 110, 'ffffff-000000', DIGIT_DICT, 1, 10); LogOut('得到令牌:%s', [TokenPackData.szDnyPsw]); SendMessage(hKEmulator, WM_CLOSE, 0, 0); if StrToIntDef(TokenPackData.szDnyPsw, -1) = -1 then begin LogOut('手机令牌错误,退出...', []); Exit; end; LogOut('删除令牌文件...', []); end; else //9891 KJava begin try IdTCPClient := TIdTCPClient.Create(nil); IdTCPClient.Host := FTokenServerIp; //113.140.30.46 IdTCPClient.Port := FTokenServerPort; //59998 IdTCPClient.Connect; //连接中间服 if IdTCPClient.Connected then begin try s := Base64ToStr(IdTCPClient.IOHandler.ReadLn()); //接收中间服的连接消息 logout(s, []); try s := 'DATA:' + FAccount+'|'+FKey; IdTCPClient.IOHandler.WriteLn(s); //发送数据 s := Base64ToStr(IdTCPClient.IOHandler.ReadLn()); //接收token logout(s, []); if Pos('token:', s) > 0 then begin s := copy(s, 7, length(s) - 6); TokenPackData.szDnyPsw := s; end; except logout('Reauest Middle-Server failed!', []); IdTCPClient.Disconnect(); logout('Disconnect with Middle-Server!', []); end; except logout('Middle-Server no response!', []); IdTCPClient.Disconnect(); end; end; except logout('Connect Middle-Server failed!', []); end; end; end; Result := TokenPackData.szDnyPsw; except on e:Exception do LogOut('获取令牌异常[%s]', [e.message]); end; finally if IdTCPClient <> nil then FreeAndNil(IdTCPClient); end; end; end.
unit OrgForm; interface uses Windows, Forms, SysUtils, Messages, Classes, ExtCtrls, Controls, Dialogs; type TOrgForm = class private FFormActivo: TForm; FPanel: TPanel; FParent: string; procedure SetFormActivo(const Value: TForm); protected public property FormActivo: TForm read FFormActivo write SetFormActivo; Procedure AddForm( form : TForm); Virtual; Procedure RemoveForm( form : TForm ); Virtual; Procedure RemoveFormActivo; Virtual; Procedure ShowForm( form : TForm); Virtual; Procedure HideForm( form : TForm); Virtual; Procedure SetFocus( form : TForm); Virtual; procedure ChangeForm; constructor Create( pnl: TPanel ); virtual; destructor Destroy; override; end; implementation { TOrgForm } procedure TOrgForm.AddForm(form: TForm); begin form.parent := FPanel; form.BorderStyle := bsNone; form.align := alClient; end; procedure TOrgForm.HideForm(form: TForm); begin If FFormActivo = form Then begin form.Visible := False; ChangeForm; end; end; procedure TOrgForm.RemoveForm(form: TForm); begin if Form <> nil then begin Form.Close; ChangeForm; end; end; procedure TOrgForm.SetFormActivo(const Value: TForm); begin FFormActivo := Value; end; procedure TOrgForm.SetFocus(form: TForm); begin if ( form <> FFormActivo ) Then begin FFormActivo := Form; form.Show; end; end; procedure TOrgForm.ShowForm(form: TForm); begin if (form <> FFormActivo ) Then begin FFormActivo := Form; Form.Show; if ( Form.ActiveControl <> nil ) then Form.SetFocusedControl( Form.ActiveControl); end; end; constructor TOrgForm.Create(pnl: TPanel); begin FPanel := pnl; FParent := TForm( FPanel.Owner ).Name; end; destructor TOrgForm.Destroy; begin inherited destroy; end; procedure TOrgForm.ChangeForm; var lFound: boolean; i: integer; begin lFound := false; i := 0; while (i <= screen.FormCount - 1) and not ( lFound ) Do begin if ( Screen.Forms[ i ].visible ) and ( FParent <> Screen.forms[ i ].Name ) and ( Screen.Forms[ i ] <> FFormActivo ) then lFound := true else Inc( i ); end; if lFound then SetFocus( Screen.forms[ i ] ) else FFormActivo := nil; end; procedure TOrgForm.RemoveFormActivo; begin if FormActivo <> nil then begin FFormActivo.Close; ChangeForm; end; end; end.
unit eePicture; { Библиотека "Эверест" } { Автор: Люлин А.В. © } { Модуль: eePicture - } { Начат: 12.02.2003 18:34 } { $Id: eePicture.pas,v 1.1 2015/01/20 11:54:23 lulin Exp $ } // $Log: eePicture.pas,v $ // Revision 1.1 2015/01/20 11:54:23 lulin // - правим зависимости. // // Revision 1.1 2014/12/09 14:16:03 kostitsin // {requestlink: 580710238 } // // Revision 1.7 2014/12/05 14:51:04 kostitsin // {requestlink: 570118718 } - eeInterfaces // // Revision 1.6 2009/04/06 17:51:28 lulin // [$140837386]. №11. // // Revision 1.5 2007/12/04 12:47:33 lulin // - перекладываем ветку в HEAD. // // Revision 1.4.8.7 2007/09/14 13:26:09 lulin // - объединил с веткой B_Tag_Clean. // // Revision 1.4.8.6.2.1 2007/09/12 19:56:50 lulin // - bug fix: не собиралась библиотека. // // Revision 1.4.8.6 2007/09/03 12:29:06 lulin // - переименовываем тег. // // Revision 1.4.8.5 2007/04/18 11:00:13 oman // warning fix // // Revision 1.4.8.4 2007/02/16 17:54:08 lulin // - избавляемся от стандартного строкового типа. // // Revision 1.4.8.3 2006/11/03 11:00:11 lulin // - объединил с веткой 6.4. // // Revision 1.4.8.2.22.1 2006/10/26 11:24:15 lulin // - избавляемся от лишних преобразований типов. // // Revision 1.4.8.2 2005/10/28 09:31:30 lulin // - cleanup. // // Revision 1.4.8.1 2005/10/28 08:21:42 lulin // - bug fix: не открывались картинки по ссылке. // // Revision 1.4 2005/03/19 16:39:54 lulin // - спрятаны ненужные методы. // // Revision 1.3 2003/11/06 11:27:08 law // - new prop: IeePicture.Name. // // Revision 1.2 2003/11/05 15:54:40 law // - new method: IeePicture.SaveToStream. // // Revision 1.1 2003/02/12 15:50:20 law // - new interface: IeePicture. // - new unit: eePicture. // {$Include evDefine.inc } interface uses l3Interfaces, l3Types, l3Base, eeInterfaces, eePara ; type TeePicture = class(TeePara, IeePicture) private // interface methods // IeePicture function Get_Name: Il3CString; {-} procedure SaveToStream(const aStream: IStream); {-} end;//TeePicture implementation uses k2Base, k2Tags ; // start class TeePicture function TeePicture.Get_Name: Il3CString; {-} begin Result := l3CStr(TagInst.PCharLenA[k2_tiShortName]); end; procedure TeePicture.SaveToStream(const aStream: IStream); {-} var l_Stream : IStream; l_Read : Int64; l_Written : Int64; l_Position : Int64; begin with TagInst.Attr[k2_tiData] do if IsValid AND l3IOk(QueryInterface(IStream, l_Stream)) then try l_Stream.Seek(0, STREAM_SEEK_SET, l_Position); l_Stream.CopyTo(aStream, High(Int64), l_Read, l_Written); finally l_Stream := nil; end;{try..finally} end; end.
{====================================================} { } { EldoS Visual Components } { } { Copyright (c) 1998-2003, EldoS Corporation } { } {====================================================} {$include elpack2.inc} {$ifdef ELPACK_SINGLECOMP} {$I ElPack.inc} {$else} {$ifdef LINUX} {$I ../ElPack.inc} {$else} {$I ..\ElPack.inc} {$endif} {$endif} unit ElStrPool; interface uses Classes, {$ifdef ELPACK_UNICODE} ElUnicodeStrings; {$else} ElStrArray; {$endif} type {$ifdef ELPACK_UNICODE} TElFStringArray = TElWideStringArray; {$else} TElFStringArray = TElStringArray; {$endif} TElStringPool = class(TComponent) private FItems : TElFStringArray; procedure SetItems(newValue : TElFStringArray); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Assign(Source : TPersistent); override; published property Items : TElFStringArray read FItems write SetItems; end; implementation constructor TElStringPool.Create(AOwner : TComponent); begin inherited Create(AOwner); FItems := TElFStringArray.Create; end; destructor TElStringPool.Destroy; begin FItems.Free; inherited; end; procedure TElStringPool.Assign(Source : TPersistent); begin if Source is TStrings then FItems.Assign(Source) else inherited; end; procedure TElStringPool.SetItems(newValue : TElFStringArray); begin FItems.Assign(newValue); end; end.
{ *********************************************************************************** } { * CryptoLib Library * } { * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * } { * Github Repository <https://github.com/Xor-el> * } { * Distributed under the MIT software license, see the accompanying file LICENSE * } { * or visit http://www.opensource.org/licenses/mit-license.php. * } { * Acknowledgements: * } { * * } { * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * } { * development of this library * } { * ******************************************************************************* * } (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *) unit ClpDerEnumerated; {$I ..\Include\CryptoLib.inc} interface uses Classes, SysUtils, ClpCryptoLibTypes, ClpArrayUtils, ClpBigInteger, ClpIAsn1OctetString, ClpAsn1Tags, ClpDerOutputStream, ClpIProxiedInterface, ClpIDerEnumerated, ClpIAsn1TaggedObject, ClpAsn1Object; resourcestring SMalformedEnumerated = 'Malformed Enumerated'; SZeroLength = 'Enumerated has Zero Length, "enc"'; SIllegalObject = 'Illegal Object in GetInstance: %s'; type TDerEnumerated = class(TAsn1Object, IDerEnumerated) strict private class var Fcache: TCryptoLibGenericArray<IDerEnumerated>; function GetValue: TBigInteger; inline; function GetBytes: TCryptoLibByteArray; inline; class constructor DerEnumerated(); var Fbytes: TCryptoLibByteArray; strict protected function Asn1Equals(const asn1Object: IAsn1Object): Boolean; override; function Asn1GetHashCode(): Int32; override; public constructor Create(val: Int32); overload; constructor Create(const val: TBigInteger); overload; constructor Create(const bytes: TCryptoLibByteArray); overload; procedure Encode(const derOut: TStream); override; property Value: TBigInteger read GetValue; property bytes: TCryptoLibByteArray read GetBytes; /// <summary> /// return an integer from the passed in object /// </summary> /// <exception cref="ClpCryptoLibTypes|EArgumentCryptoLibException"> /// if the object cannot be converted. /// </exception> class function GetInstance(const obj: TObject): IDerEnumerated; overload; static; inline; /// <summary> /// return an Enumerated from a tagged object. /// </summary> /// <param name="obj"> /// the tagged object holding the object we want /// </param> /// <param name="isExplicit"> /// true if the object is meant to be explicitly tagged false otherwise. /// </param> /// <exception cref="ClpCryptoLibTypes|EArgumentCryptoLibException"> /// if the tagged object cannot be converted. /// </exception> class function GetInstance(const obj: IAsn1TaggedObject; isExplicit: Boolean): IDerEnumerated; overload; static; inline; class function FromOctetString(const enc: TCryptoLibByteArray) : IDerEnumerated; static; end; implementation { TDerEnumerated } function TDerEnumerated.GetBytes: TCryptoLibByteArray; begin result := Fbytes; end; function TDerEnumerated.Asn1Equals(const asn1Object: IAsn1Object): Boolean; var other: IDerEnumerated; begin if (not Supports(asn1Object, IDerEnumerated, other)) then begin result := false; Exit; end; result := TArrayUtils.AreEqual(bytes, other.bytes); end; function TDerEnumerated.Asn1GetHashCode: Int32; begin result := TArrayUtils.GetArrayHashCode(bytes); end; constructor TDerEnumerated.Create(val: Int32); begin Inherited Create(); Fbytes := TBigInteger.ValueOf(val).ToByteArray(); end; constructor TDerEnumerated.Create(const val: TBigInteger); begin Inherited Create(); Fbytes := val.ToByteArray(); end; constructor TDerEnumerated.Create(const bytes: TCryptoLibByteArray); begin Inherited Create(); if (System.Length(bytes) > 1) then begin if ((bytes[0] = 0) and ((bytes[1] and $80) = 0)) then begin raise EArgumentCryptoLibException.CreateRes(@SMalformedEnumerated); end; if ((bytes[0] = Byte($FF)) and ((bytes[1] and $80) <> 0)) then begin raise EArgumentCryptoLibException.CreateRes(@SMalformedEnumerated); end; end; Fbytes := System.Copy(bytes); end; class constructor TDerEnumerated.DerEnumerated; begin System.SetLength(Fcache, 12); end; procedure TDerEnumerated.Encode(const derOut: TStream); begin (derOut as TDerOutputStream).WriteEncoded(TAsn1Tags.Enumerated, Fbytes); end; class function TDerEnumerated.FromOctetString(const enc: TCryptoLibByteArray) : IDerEnumerated; var LValue: Int32; cached: IDerEnumerated; begin if (System.Length(enc) = 0) then begin raise EArgumentCryptoLibException.CreateRes(@SZeroLength); end; if (System.Length(enc) = 1) then begin LValue := enc[0]; if (LValue < System.Length(Fcache)) then begin cached := Fcache[LValue]; if (cached <> Nil) then begin result := cached; Exit; end; Fcache[LValue] := TDerEnumerated.Create(System.Copy(enc)); result := Fcache[LValue]; Exit; end; end; result := TDerEnumerated.Create(System.Copy(enc)); end; class function TDerEnumerated.GetInstance(const obj: TObject): IDerEnumerated; begin if ((obj = Nil) or (obj is TDerEnumerated)) then begin result := obj as TDerEnumerated; Exit; end; raise EArgumentCryptoLibException.CreateResFmt(@SIllegalObject, [obj.ClassName]); end; class function TDerEnumerated.GetInstance(const obj: IAsn1TaggedObject; isExplicit: Boolean): IDerEnumerated; var o: IAsn1Object; begin o := obj.GetObject(); if (isExplicit or (Supports(o, IDerEnumerated))) then begin result := GetInstance(o as TObject); Exit; end; result := FromOctetString((o as IAsn1OctetString).GetOctets()); end; function TDerEnumerated.GetValue: TBigInteger; begin result := TBigInteger.Create(Fbytes); end; end.
unit uFireDAC; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Data.DBXFirebird, Data.FMTBcd, Data.SqlExpr, Datasnap.DBClient, Datasnap.Provider, System.Generics.Collections, uDMMSS; type TFireDAC = class private FModel: TFDQuery; FLista: TList<string>; function Conexao: TFDConnection; procedure SetLista(const Value: TList<string>); function GetIncrementar: string; public procedure OpenSQL(InstrucaoSQL: string = ''); procedure ExecutarSQL(InstrucaoSQL: string=''); function ExecutarScala(InstrucaoSQL: string=''): Integer; procedure StartTransacao; procedure Commit; Procedure Roolback; property Lista: TList<string> read FLista write SetLista; property Model: TFDQuery read FModel write FModel; property Incrementar: string read GetIncrementar; constructor create; destructor destroy; override; end; implementation { TFireDAC } procedure TFireDAC.Commit; begin if DMMSS.Conexao.InTransaction then DMMSS.Conexao.Commit; end; function TFireDAC.Conexao: TFDConnection; begin Result := DMMSS.Conexao; end; constructor TFireDAC.create; begin FModel := TFDQuery.Create(nil); FModel.Connection := Conexao; FLista := TList<string>.Create; end; destructor TFireDAC.destroy; begin if FModel.Active then FModel.Close; FreeAndNil(FModel); FreeAndNil(FLista); inherited; end; function TFireDAC.ExecutarScala(InstrucaoSQL: string): Integer; var sInstrucao: string; i: Integer; begin if InstrucaoSQL = '' then begin sInstrucao := ''; for I := 0 to FLista.Count -1 do sInstrucao := sInstrucao + FLista.Items[i]; end else sInstrucao := InstrucaoSQL; Result := DMMSS.Conexao.ExecSQLScalar(sInstrucao); end; procedure TFireDAC.ExecutarSQL(InstrucaoSQL: string); var sInstrucao: string; i: Integer; begin if InstrucaoSQL = '' then begin sInstrucao := ''; for I := 0 to FLista.Count -1 do sInstrucao := sInstrucao + FLista.Items[i]; end else sInstrucao := InstrucaoSQL; DMMSS.Conexao.ExecSQL(sInstrucao); end; function TFireDAC.GetIncrementar: string; begin Result := ' SELECT SCOPE_IDENTITY();'; end; procedure TFireDAC.Roolback; begin if DMMSS.Conexao.InTransaction then DMMSS.Conexao.Rollback; end; procedure TFireDAC.OpenSQL(InstrucaoSQL: string); var sInstrucao: string; i: Integer; begin if InstrucaoSQL = '' then begin sInstrucao := ''; for I := 0 to FLista.Count -1 do sInstrucao := sInstrucao + FLista.Items[i]; end else sInstrucao := InstrucaoSQL; FModel.SQL.Text := sInstrucao; FModel.Open(); end; procedure TFireDAC.SetLista(const Value: TList<string>); begin FLista := Value; end; procedure TFireDAC.StartTransacao; begin if not DMMSS.Conexao.InTransaction then DMMSS.Conexao.StartTransaction; end; end.
unit PI.View.DeviceInfo; interface uses // RTL System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, // FMX FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, FMX.Objects, FMX.Layouts, FMX.Controls.Presentation, FMX.Edit, FMX.ImgList, // PushIt PI.Types; type TDeviceInfoView = class(TFrame) DetailsLayout: TLayout; DeviceIDLabel: TLabel; DeviceIDEdit: TEdit; TokenLabel: TLabel; TokenEdit: TEdit; OSImage: TGlyph; procedure ControlClickHandler(Sender: TObject); private FDeviceInfo: TDeviceInfo; procedure SetDeviceInfo(const ADeviceInfo: TDeviceInfo); public property DeviceInfo: TDeviceInfo read FDeviceInfo write SetDeviceInfo; end; implementation {$R *.fmx} uses // PushIt PI.Resources; { TDeviceInfoView } procedure TDeviceInfoView.ControlClickHandler(Sender: TObject); begin OnClick(Self); end; procedure TDeviceInfoView.SetDeviceInfo(const ADeviceInfo: TDeviceInfo); begin FDeviceInfo := ADeviceInfo; DeviceIDEdit.Text := FDeviceInfo.DeviceID; TokenEdit.Text := FDeviceInfo.Token; if FDeviceInfo.OS.Equals('Android') then OSImage.ImageIndex := 0 else if FDeviceInfo.OS.Equals('IOS') then OSImage.ImageIndex := 1; 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.0 11/29/2004 2:44:16 AM JPMugaas New FTP list parsers for some legacy FTP servers. } unit IdFTPListParseChameleonNewt; interface {$i IdCompilerDefines.inc} uses Classes, IdFTPList, IdFTPListParseBase,IdFTPListTypes; type TIdChameleonNewtFTPListItem = class(TIdDOSBaseFTPListItem); TIdFTPLPChameleonNewt = class(TIdFTPLPBaseDOS) protected class function MakeNewItem(AOwner : TIdFTPListItems) : TIdFTPListItem; override; class function ParseLine(const AItem : TIdFTPListItem; const APath : String = ''): Boolean; override; public class function GetIdent : String; override; class function CheckListing(AListing : TStrings; const ASysDescript : String = ''; const ADetails : Boolean = True): Boolean; override; end; // RLebeau 2/14/09: this forces C++Builder to link to this unit so // RegisterFTPListParser can be called correctly at program startup... (*$HPPEMIT '#pragma link "IdFTPListParseChameleonNewt"'*) implementation uses IdFTPCommon, IdGlobal, IdGlobalProtocols, SysUtils; { TIdFTPLPChameleonNewt } class function TIdFTPLPChameleonNewt.CheckListing(AListing: TStrings; const ASysDescript: String; const ADetails: Boolean): Boolean; {Look for something like this: . <DIR> Nov 16 1994 17:16 .. <DIR> Nov 16 1994 17:16 INSTALL <DIR> Nov 16 1994 17:17 CMT <DIR> Nov 21 1994 10:17 DESIGN1.DOC 11264 May 11 1995 14:20 A README.TXT 1045 May 10 1995 11:01 WPKIT1.EXE 960338 Jun 21 1995 17:01 R CMT.CSV 0 Jul 06 1995 14:56 RHA } var i : Integer; LBuf, LBuf2 : String; LInt : Integer; begin Result := False; for i := 0 to AListing.Count -1 do begin LBuf := AListing[i]; //filename and extension - we assume an 8.3 filename type because //Windows 3.1 only supports that. Fetch(LBuf); LBuf := TrimLeft(LBuf); //<DIR> or file size LBuf2 := Fetch(LBuf); Result := (LBuf2 = '<DIR>') or IsNumeric(LBuf2); {Do not localize} if not Result then begin Exit; end; LBuf := TrimLeft(LBuf); //month LBuf2 := Fetch(LBuf); Result := StrToMonth(LBuf2) > 0; if not Result then begin Exit; end; //day LBuf := TrimLeft(LBuf); LInt := IndyStrToInt64(Fetch(LBuf), 0); Result := (LInt > 0) and (LInt < 32); if not Result then begin Exit; end; //year LBuf := TrimLeft(LBuf); Result := IsNumeric(Fetch(LBuf)); if not Result then begin Exit; end; //time LBuf := TrimLeft(LBuf); LBuf2 := Fetch(LBuf); Result := IsHHMMSS(LBuf2, ':'); if not Result then begin Exit; end; //attributes repeat LBuf := TrimLeft(LBuf); if LBuf = '' then begin Break; end; LBuf2 := Fetch(LBuf); Result := IsValidAttr(LBuf2); until not Result; end; end; class function TIdFTPLPChameleonNewt.GetIdent: String; begin Result := 'NetManage Chameleon/Newt'; {Do not localize} end; class function TIdFTPLPChameleonNewt.MakeNewItem(AOwner: TIdFTPListItems): TIdFTPListItem; begin Result := TIdChameleonNewtFTPListItem.Create(AOwner); end; class function TIdFTPLPChameleonNewt.ParseLine(const AItem: TIdFTPListItem; const APath: String): Boolean; var LI : TIdChameleonNewtFTPListItem; LBuf, LBuf2 : String; LDay, LMonth, LYear : Integer; begin LI := AItem as TIdChameleonNewtFTPListItem; LBuf := AItem.Data; //filename and extension - we assume an 8.3 filename type because //Windows 3.1 only supports that. LI.FileName := Fetch(LBuf); LBuf := TrimLeft(LBuf); //<DIR> or file size LBuf2 := Fetch(LBuf); if LBuf2 = '<DIR>' then {Do not localize} begin LI.ItemType := ditDirectory; LI.SizeAvail := False; end else begin LI.ItemType := ditFile; Result := IsNumeric(LBuf2); if not Result then begin Exit; end; LI.Size := IndyStrToInt64(LBuf2, 0); end; //month LBuf := TrimLeft(LBuf); LBuf2 := Fetch(LBuf); LMonth := StrToMonth(LBuf2); Result := LMonth > 0; if not Result then begin Exit; end; //day LBuf := TrimLeft(LBuf); LBuf2 := Fetch(LBuf); LDay := IndyStrToInt64(LBuf2, 0); Result := (LDay > 0) and (LDay < 32); if not Result then begin Exit; end; //year LBuf := TrimLeft(LBuf); LBuf2 := Fetch(LBuf); Result := IsNumeric(LBuf2); if not Result then begin Exit; end; LYear := Y2Year(IndyStrToInt(LBuf2, 0)); LI.ModifiedDate := EncodeDate(LYear, LMonth, LDay); //time LBuf := TrimLeft(LBuf); LBuf2 := Fetch(LBuf); Result := IsHHMMSS(LBuf2, ':'); if not Result then begin Exit; end; LI.ModifiedDate := LI.ModifiedDate + TimeHHMMSS(LBuf2); //attributes repeat LBuf := TrimLeft(LBuf); if LBuf = '' then begin Break; end; LBuf2 := Fetch(LBuf); Result := LI.FAttributes.AddAttribute(LBuf2); until not Result; end; initialization RegisterFTPListParser(TIdFTPLPChameleonNewt); finalization UnRegisterFTPListParser(TIdFTPLPChameleonNewt); end.
unit UNPC; interface uses Classes, SysUtils, Graphics, Controls, TypInfo, // self-made units UMapCommon, UConfig, UCommon; type NNpcParam = (npID, npName, npScript, npDialog, npPortrait, npWanderModel, npWanderRatio, npTradeType, npObjImgID, npWanderPoints); NWanderModel = (wmStand, wmRandom, wmHost, wmGuard, wmSpec); TNpcConfig = class(TConfig) private FBMPs: array of TBitmap; FBMPsFName : string; function GetItem(Index: Integer; Param: NNpcParam): string; procedure SetItem(Index: Integer; Param: NNpcParam; const Value: string); function GetBMPs(Index: Integer): TBitmap; function GetItemText(Index: Integer; Param: NNpcParam): string; procedure SetItemText(Index: Integer; Param: NNpcParam; const Value: string); public //** Конструктор. constructor Create(AWrapperClass: TWrapperClass); destructor Destroy (); override; property Items[Index: Integer; Param: NNpcParam]: string read GetItem write SetItem; function IDString(Index: Integer; Param: NNpcParam): string; function GetBMPsFName(): string; property BMPs[Index: Integer]: TBitmap read GetBMPs; procedure OnLoad(Sender: TObject); property ItemText[Index: Integer; Param: NNpcParam]: string read GetItemText write SetItemText; procedure Write(Key, Value: string); function Read(Key: string): string; end; CNPC = class(THODObject) private public Deleted: Boolean; X, Y, ID: Integer; // Script: string; //** Конструктор. constructor Create(AX, AY: Integer; AID: Integer = 0); overload; //** Конструктор. constructor Create(AString: string); overload; procedure Edit(AX, AY, AID: Integer); function ToString(): string; class procedure Split(Astr: string; out AX, AY, AID: Integer); end; CNPCList = class(TObjList) private function GetItem(Index: Integer): CNPC; procedure SetItem(Index: Integer; const Value: CNPC); public function Add(const Value: CNPC): Integer; function Find(AX, AY: Integer; FindPrm: NFindParam = fpNumber): Integer; property Items[Index: Integer]: CNPC read GetItem write SetItem; default; end; const NPCMapSectionName = '[NPC]'; GeneralSection = 'General'; BMPname = 'BmpName'; Delim = '|'; NpcParamColWidths: array[NNpcParam] of Integer = (20, 90, 200, 200, 150, 90, 70, 70, 80, 0); NpcParamColCount = Ord(High(NNpcParam)) + 1; NpcParamType: array[NNpcParam] of NParamType = (npInteger, npString, npFname, npFname, npImgFName, npList, npInteger, npInteger, npImageID, npOrderSet); function NPCConfig(): TNpcConfig; function NPCList(): CNPCList; function IsSpecWanderModel(Str: string): Boolean; var NpcParamNames: array[NNpcParam] of string; implementation uses uUtils; var TheNPCConfig: TNpcConfig; TheNPCList: CNPCList; function NPCConfig(): TNpcConfig; begin Result := TheNPCConfig; end; function NPCList(): CNPCList; begin Result := TheNPCList; end; function IsSpecWanderModel(Str: string): Boolean; var p : Pointer; begin p := TypeInfo(NWanderModel); Result := not ((Str = GetEnumName(p, Ord(wmStand))) or (Str = GetEnumName(p, Ord(wmRandom)))); end; { CNPCList } function CNPCList.Add(const Value: CNPC): Integer; begin Result := inherited Add(Value); end; function CNPCList.Find(AX, AY: Integer; FindPrm: NFindParam = fpNumber): Integer; var j: Integer; begin Result := -1; for j := 0 to Count - 1 do if (Items[j].X = AX) and (Items[j].Y = AY) then begin case FindPrm of fpNumber: Result := j; fpID: Result := Items[j].ID; end; Exit; end; end; function CNPCList.GetItem(Index: Integer): CNPC; begin Result := inherited Get(Index); end; procedure CNPCList.SetItem(Index: Integer; const Value: CNPC); begin inherited Put(Index, Value); end; { CNPC } constructor CNPC.Create(AX, AY: Integer; AID: Integer = 0); begin inherited Create(); X := AX; Y := AY; ID := AID; end; constructor CNPC.Create(AString: string); begin inherited Create(); Split(AString, X, Y, ID); end; procedure CNPC.Edit(AX, AY, AID: Integer); begin X := AX; Y := AY; ID := AID; end; class procedure CNPC.Split(Astr: string; out AX, AY, AID: Integer); var sl : Tstringlist; begin sl := Tstringlist.Create; try sl.Delimiter := delim; sl.DelimitedText := AStr; Ax := StrToIntDef(sl[0], 0); Ay := StrToIntDef(sl[1], 0); AID := StrToIntDef(sl[2], 0); finally sl.Free; end; end; function CNPC.ToString: string; begin Result := Format('%d%s%d%s%d', [X, delim, Y, delim, ID]); end; { TNpcConfig } constructor TNpcConfig.Create(AWrapperClass: TWrapperClass); begin inherited; Wrapper.Onload := OnLoad; end; destructor TNpcConfig.Destroy; var I: Integer; begin inherited; for I := 0 to Length(FBMPs) - 1 do FreeAndNil(FBMPs[i]); end; function TNpcConfig.GetBMPsFName: string; begin Result := FBMPsFName; end; function TNpcConfig.GetBMPs(Index: Integer): TBitmap; begin Result := FBMPs[Index]; end; function TNpcConfig.GetItem(Index: Integer; Param: NNpcParam): string; begin if Param = npID then Result := IntToStr(Index) else Result := FWrapper.ReadString(IDString(Index, Param)); end; function TNpcConfig.GetItemText(Index: Integer; Param: NNpcParam): string; begin case Param of // npID: ; // npName: ; // npScript: ; // npPortrait: ; // npObjImgID: ; npWanderModel: Result := GetEnumName(TypeInfo(NWanderModel), StrToIntDef(Items[Index, Param], 0)); else Result := Items[Index, Param]; end; end; function TNpcConfig.IDString(Index: Integer; Param: NNpcParam): string; begin Result := Format('%d%s%s', [Index, FWrapper.Delim, NpcParamNames[Param]]); end; procedure TNpcConfig.OnLoad(Sender: TObject); var i: Integer; ImgLst: TImageList; BufPic: TBitmap; begin FBMPsFName := Wrapper.ReadString(GeneralSection + Wrapper.Delim + BMPname); ImgLst := TImageList.CreateSize(CellSize, CellSize); BufPic := TBitmap.Create(); try BufPic.LoadFromFile(ExtractFilePath(ParamStr(0)) + 'data\images\' + GetBMPsFName); ImgLst.AddMasked(BufPic, TransCol); SetLength(FBMPs, ImgLst.Count); for i := 0 to ImgLst.Count - 1 do begin fbmps[i] := TBitmap.Create; fbmps[i].Width := CellSize; fbmps[i].Height := CellSize; fbmps[i].PixelFormat := pf24bit; fbmps[i].Transparent := True; fbmps[i].TransparentColor := fbmps[i].Canvas.Pixels[0, 0]; ImgLst.Draw(fbmps[i].Canvas, 0, 0, i); end; finally BufPic.Free; ImgLst.Free; end; end; function TNpcConfig.Read(Key: string): string; begin Result := FWrapper.ReadString(Key); end; procedure TNpcConfig.SetItem(Index: Integer; Param: NNpcParam; const Value: string); begin if Param <> npID then FWrapper.WriteString(IDString(Index, Param), Value); end; procedure TNpcConfig.SetItemText(Index: Integer; Param: NNpcParam; const Value: string); begin case Param of npID: ; npName: ; npScript: ; npPortrait: ; npObjImgID: ; npWanderModel: Items[Index, Param] := IntToStr(Getenumvalue(TypeInfo(NWanderModel), Value)); else Items[Index, Param] := Value; end; end; procedure TNpcConfig.write(Key, Value: string); begin FWrapper.WriteString(Key, Value); end; var i: NNpcParam; initialization TheNPCConfig := TNpcConfig.Create(TIniWrapper); TheNPCConfig.LoadFromFile(Path + 'data\npcs.ini'); TheNPCList := CNPCList.Create; for i := Low(NNpcParam) to High(NNpcParam) do NpcParamNames[i] := EnumText(TypeInfo(NNpcParam), Ord(i)); finalization FreeAndNil(TheNPCConfig); FreeAndNil(TheNPCList); end.
{ *********************************************************************************** } { * CryptoLib Library * } { * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * } { * Github Repository <https://github.com/Xor-el> * } { * Distributed under the MIT software license, see the accompanying file LICENSE * } { * or visit http://www.opensource.org/licenses/mit-license.php. * } { * Acknowledgements: * } { * * } { * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * } { * development of this library * } { * ******************************************************************************* * } (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *) unit ClpIESWithCipherParameters; {$I ..\..\Include\CryptoLib.inc} interface uses ClpIESParameters, ClpIIESParameters, ClpIIESWithCipherParameters, ClpCryptoLibTypes; type TIESWithCipherParameters = class(TIESParameters, IIESParameters, IIESWithCipherParameters) strict private var Fnonce: TCryptoLibByteArray; FcipherKeySize: Int32; FusePointCompression: Boolean; function GetCipherKeySize: Int32; inline; function GetNonce: TCryptoLibByteArray; inline; function GetPointCompression: Boolean; inline; public /// <summary> /// Set the IES engine parameters. /// </summary> /// <param name="derivation"> /// the optional derivation vector for the KDF. /// </param> /// <param name="encoding"> /// the optional encoding vector for the KDF. /// </param> /// <param name="macKeySize"> /// the key size (in bits) for the MAC. /// </param> /// <param name="CipherKeySize"> /// the key size (in bits) for the block cipher. /// </param> constructor Create(const derivation, encoding: TCryptoLibByteArray; macKeySize, CipherKeySize: Int32); overload; /// <summary> /// Set the IES engine parameters. /// </summary> /// <param name="derivation"> /// the optional derivation vector for the KDF. /// </param> /// <param name="encoding"> /// the optional encoding vector for the KDF. /// </param> /// <param name="macKeySize"> /// the key size (in bits) for the MAC. /// </param> /// <param name="CipherKeySize"> /// the key size (in bits) for the block cipher. /// </param> /// <param name="nonce"> /// an IV to use initialising the block cipher. /// </param> constructor Create(const derivation, encoding: TCryptoLibByteArray; macKeySize, CipherKeySize: Int32; const nonce: TCryptoLibByteArray); overload; /// <summary> /// Set the IES engine parameters. /// </summary> /// <param name="derivation"> /// the optional derivation vector for the KDF. /// </param> /// <param name="encoding"> /// the optional encoding vector for the KDF. /// </param> /// <param name="macKeySize"> /// the key size (in bits) for the MAC. /// </param> /// <param name="CipherKeySize"> /// the key size (in bits) for the block cipher. /// </param> /// <param name="nonce"> /// an IV to use initialising the block cipher. /// </param> /// <param name="UsePointCompression"> /// whether to use EC point compression or not (false by default) /// </param> constructor Create(const derivation, encoding: TCryptoLibByteArray; macKeySize, CipherKeySize: Int32; const nonce: TCryptoLibByteArray; UsePointCompression: Boolean); overload; /// <summary> /// Return the key size in bits for the block cipher used with the message /// </summary> /// <value> /// the key size in bits for the block cipher used with the message /// </value> property CipherKeySize: Int32 read GetCipherKeySize; /// <summary> /// Return the nonce (IV) value to be associated with message. /// </summary> /// <value> /// block cipher IV for message. /// </value> property nonce: TCryptoLibByteArray read GetNonce; /// <summary> /// Return the 'point compression' flag. /// </summary> /// <value> /// the point compression flag /// </value> property PointCompression: Boolean read GetPointCompression; end; implementation { TIESWithCipherParameters } function TIESWithCipherParameters.GetCipherKeySize: Int32; begin Result := FcipherKeySize; end; function TIESWithCipherParameters.GetNonce: TCryptoLibByteArray; begin Result := System.Copy(Fnonce); end; function TIESWithCipherParameters.GetPointCompression: Boolean; begin Result := FusePointCompression; end; constructor TIESWithCipherParameters.Create(const derivation, encoding: TCryptoLibByteArray; macKeySize, CipherKeySize: Int32); begin Create(derivation, encoding, macKeySize, CipherKeySize, Nil); end; constructor TIESWithCipherParameters.Create(const derivation, encoding: TCryptoLibByteArray; macKeySize, CipherKeySize: Int32; const nonce: TCryptoLibByteArray); begin Create(derivation, encoding, macKeySize, CipherKeySize, nonce, false); end; constructor TIESWithCipherParameters.Create(const derivation, encoding: TCryptoLibByteArray; macKeySize, CipherKeySize: Int32; const nonce: TCryptoLibByteArray; UsePointCompression: Boolean); begin Inherited Create(derivation, encoding, macKeySize); FcipherKeySize := CipherKeySize; Fnonce := System.Copy(nonce); FusePointCompression := UsePointCompression; end; end.
unit FiltersKeywordsPack; {* Набор слов словаря для доступа к экземплярам контролов формы Filters } // Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\View\Filters\Forms\FiltersKeywordsPack.pas" // Стереотип: "ScriptKeywordsPack" // Элемент модели: "FiltersKeywordsPack" MUID: (4ABCD2BC0302_Pack) {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL)} uses l3IntfUses ; {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL) implementation {$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL)} uses l3ImplUses , Filters_Form , tfwPropertyLike , nscTreeViewWithAdapterDragDrop , tfwScriptingInterfaces , TypInfo , tfwTypeInfo , tfwControlString , kwBynameControlPush , TtfwClassRef_Proxy , SysUtils , TtfwTypeRegistrator_Proxy , tfwScriptingTypes //#UC START# *4ABCD2BC0302_Packimpl_uses* //#UC END# *4ABCD2BC0302_Packimpl_uses* ; type TkwEnFiltersFiltersList = {final} class(TtfwPropertyLike) {* Слово скрипта .TenFilters.FiltersList } private function FiltersList(const aCtx: TtfwContext; aenFilters: TenFilters): TnscTreeViewWithAdapterDragDrop; {* Реализация слова скрипта .TenFilters.FiltersList } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwEnFiltersFiltersList Tkw_Form_Filters = {final} class(TtfwControlString) {* Слово словаря для идентификатора формы Filters ---- *Пример использования*: [code]форма::Filters TryFocus ASSERT[code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_Form_Filters Tkw_Filters_Control_FiltersList = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола FiltersList ---- *Пример использования*: [code]контрол::FiltersList TryFocus ASSERT[code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_Filters_Control_FiltersList Tkw_Filters_Control_FiltersList_Push = {final} class(TkwBynameControlPush) {* Слово словаря для контрола FiltersList ---- *Пример использования*: [code]контрол::FiltersList:push pop:control:SetFocus ASSERT[code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_Filters_Control_FiltersList_Push function TkwEnFiltersFiltersList.FiltersList(const aCtx: TtfwContext; aenFilters: TenFilters): TnscTreeViewWithAdapterDragDrop; {* Реализация слова скрипта .TenFilters.FiltersList } begin Result := aenFilters.FiltersList; end;//TkwEnFiltersFiltersList.FiltersList class function TkwEnFiltersFiltersList.GetWordNameForRegister: AnsiString; begin Result := '.TenFilters.FiltersList'; end;//TkwEnFiltersFiltersList.GetWordNameForRegister function TkwEnFiltersFiltersList.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TnscTreeViewWithAdapterDragDrop); end;//TkwEnFiltersFiltersList.GetResultTypeInfo function TkwEnFiltersFiltersList.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwEnFiltersFiltersList.GetAllParamsCount function TkwEnFiltersFiltersList.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TenFilters)]); end;//TkwEnFiltersFiltersList.ParamsTypes procedure TkwEnFiltersFiltersList.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству FiltersList', aCtx); end;//TkwEnFiltersFiltersList.SetValuePrim procedure TkwEnFiltersFiltersList.DoDoIt(const aCtx: TtfwContext); var l_aenFilters: TenFilters; begin try l_aenFilters := TenFilters(aCtx.rEngine.PopObjAs(TenFilters)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aenFilters: TenFilters : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(FiltersList(aCtx, l_aenFilters)); end;//TkwEnFiltersFiltersList.DoDoIt function Tkw_Form_Filters.GetString: AnsiString; begin Result := 'enFilters'; end;//Tkw_Form_Filters.GetString class procedure Tkw_Form_Filters.RegisterInEngine; begin inherited; TtfwClassRef.Register(TenFilters); end;//Tkw_Form_Filters.RegisterInEngine class function Tkw_Form_Filters.GetWordNameForRegister: AnsiString; begin Result := 'форма::Filters'; end;//Tkw_Form_Filters.GetWordNameForRegister function Tkw_Filters_Control_FiltersList.GetString: AnsiString; begin Result := 'FiltersList'; end;//Tkw_Filters_Control_FiltersList.GetString class procedure Tkw_Filters_Control_FiltersList.RegisterInEngine; begin inherited; TtfwClassRef.Register(TnscTreeViewWithAdapterDragDrop); end;//Tkw_Filters_Control_FiltersList.RegisterInEngine class function Tkw_Filters_Control_FiltersList.GetWordNameForRegister: AnsiString; begin Result := 'контрол::FiltersList'; end;//Tkw_Filters_Control_FiltersList.GetWordNameForRegister procedure Tkw_Filters_Control_FiltersList_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('FiltersList'); inherited; end;//Tkw_Filters_Control_FiltersList_Push.DoDoIt class function Tkw_Filters_Control_FiltersList_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::FiltersList:push'; end;//Tkw_Filters_Control_FiltersList_Push.GetWordNameForRegister initialization TkwEnFiltersFiltersList.RegisterInEngine; {* Регистрация enFilters_FiltersList } Tkw_Form_Filters.RegisterInEngine; {* Регистрация Tkw_Form_Filters } Tkw_Filters_Control_FiltersList.RegisterInEngine; {* Регистрация Tkw_Filters_Control_FiltersList } Tkw_Filters_Control_FiltersList_Push.RegisterInEngine; {* Регистрация Tkw_Filters_Control_FiltersList_Push } TtfwTypeRegistrator.RegisterType(TypeInfo(TenFilters)); {* Регистрация типа TenFilters } TtfwTypeRegistrator.RegisterType(TypeInfo(TnscTreeViewWithAdapterDragDrop)); {* Регистрация типа TnscTreeViewWithAdapterDragDrop } {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL) end.
unit DAO.LogradourosCEP; interface uses FireDAC.Comp.Client, System.SysUtils, DAO.Conexao, Model.LogradourosCEP; type TLogradourosCEPDAO = class private FConexao: TConexao; public constructor Create; function GetID(): Integer; function Inserir(ALogradouros: TLogradouroCEP): Boolean; function Alterar(ALogradouros: TLogradouroCEP): Boolean; function Excluir(ALogradouros: TLogradouroCEP): Boolean; function Pesquisar(aParam: array of variant): TFDQuery; end; const TABLENAME = 'cadastro_logradouros'; implementation uses Control.Sistema; { TLogradourosCEPDAO } function TLogradourosCEPDAO.Alterar(ALogradouros: TLogradouroCEP): Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FDQuery.ExecSQL('update ' + TABLENAME + ' set num_cep = :num_cep, des_tipo = :des_tipo, ' + 'des_descricao = :des_descricao, id_cidade = :id_cidade, uf_estado = :uf_estado, ' + 'des_complemento = :des_complemento, des_descricao_sem_numero = :des_descricao_sem_numero, ' + 'des_descricao_cidade = :des_descricao_cidade, cod_cidade_ibge = :cod_cidade_ibge, des_bairro = :des_bairro ' + 'where id_logradouro = :id_logradouro;', [ALogradouros.CEP, ALogradouros.Tipo, ALogradouros.Descricao, ALogradouros.IDCidade, ALogradouros.UF, ALogradouros.Complemento, ALogradouros.DescricaoSemNumero, ALogradouros.Cidade, ALogradouros.CodigoIBGE, ALogradouros.Bairro, ALogradouros.ID]); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; constructor TLogradourosCEPDAO.Create; begin FConexao := TSistemaControl.GetInstance.Conexao; end; function TLogradourosCEPDAO.Excluir(ALogradouros: TLogradouroCEP): Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FDQuery.ExecSQL('delete from ' + TABLENAME + ' where id_logradouro = :id_logradouro', [ALogradouros.ID]); Result := True; finally FDQuery.Connection.Close; FDquery.Free; end; end; function TLogradourosCEPDAO.GetID: Integer; var FDQuery: TFDQuery; begin try FDQuery := FConexao.ReturnQuery(); FDQuery.Open('select coalesce(max(id_logradouro),0) + 1 from ' + TABLENAME); try Result := FDQuery.Fields[0].AsInteger; finally FDQuery.Close; end; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TLogradourosCEPDAO.Inserir(ALogradouros: TLogradouroCEP): Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FDQuery.ExecSQL('insert into ' + TABLENAME + '(id_logradouro, num_cep, des_tipo, des_descricao, id_cidade, uf_estado, ' + 'des_complemento, des_descricao_sem_numero, des_descricao_cidade, cod_cidade_ibge, des_bairro)' + 'vales ' + '(:id_logradouro, :num_cep, :des_tipo, :des_descricao, :id_cidade, :uf_estado, :des_complemento, ' + ':des_descricao_sem_numero, :des_descricao_cidade, :cod_cidade_ibge, :des_bairro);' , [ALogradouros.ID, ALogradouros.CEP, ALogradouros.Tipo, ALogradouros.Descricao, ALogradouros.IDCidade, ALogradouros.UF, ALogradouros.Complemento, ALogradouros.DescricaoSemNumero, ALogradouros.Cidade, ALogradouros.CodigoIBGE, ALogradouros.Bairro]); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TLogradourosCEPDAO.Pesquisar(aParam: array of variant): TFDQuery; var FDQuery: TFDQuery; begin FDQuery := FConexao.ReturnQuery(); if Length(aParam) < 2 then Exit; FDQuery.SQL.Clear; FDQuery.SQL.Add('select * from ' + TABLENAME); if aParam[0] = 'ID' then begin FDQuery.SQL.Add('where id_logradouro = :id_logradouro'); FDQuery.ParamByName('id_logradouro').AsInteger := aParam[1]; end; if aParam[0] = 'CEP' then begin FDQuery.SQL.Add('where num_cep = :num_cep'); FDQuery.ParamByName('num_cep').AsString := aParam[1]; end; if aParam[0] = 'UF' then begin FDQuery.SQL.Add('where uf_estado = :uf_estado'); FDQuery.ParamByName('uf_estado').AsString := aParam[1]; end; if aParam[0] = 'LOGRADOURO' then begin FDQuery.SQL.Add('where des_descricao_sem_numero like :des_descricao_sem_numero'); FDQuery.ParamByName('des_descricao_sem_numero').AsString := aParam[1]; end; if aParam[0] = 'CIDADE' then begin FDQuery.SQL.Add('where des_descricao_cidade like :des_descricao_cidade'); FDQuery.ParamByName('des_descricao_cidade').AsString := aParam[1]; end; if aParam[0] = 'BAIRRO' then begin FDQuery.SQL.Add('where des_bairro like :des_bairro'); FDQuery.ParamByName('num_nossonumero').AsString := aParam[1]; end; if aParam[0] = 'FILTRO' then begin FDQuery.SQL.Add('where ' + 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; Result := FDQuery; end; end.
unit daSelectField; // Модуль: "w:\common\components\rtl\Garant\DA\daSelectField.pas" // Стереотип: "SimpleClass" // Элемент модели: "TdaSelectField" MUID: (5551DCD200EE) {$Include w:\common\components\rtl\Garant\DA\daDefine.inc} interface uses l3IntfUses , l3ProtoObject , daInterfaces ; type TdaSelectField = class(Tl3ProtoObject, IdaSelectField, IdaFieldFromTable) private f_Alias: AnsiString; f_TableAlias: AnsiString; f_Field: IdaFieldDescription; protected function Get_TableAlias: AnsiString; function Get_Field: IdaFieldDescription; function Get_Alias: AnsiString; function BuildSQLValue(AddAlias: Boolean = True): AnsiString; procedure Cleanup; override; {* Функция очистки полей объекта. } public constructor Create(const aTableAlias: AnsiString; const aField: IdaFieldDescription; const anAlias: AnsiString = ''); reintroduce; virtual; class function Make(const aTableAlias: AnsiString; const aField: IdaFieldDescription; const anAlias: AnsiString = ''): IdaSelectField; reintroduce; procedure IterateTables(anAction: daSelectFieldIterator_IterateTables_Action); virtual; procedure IterateTablesF(anAction: daSelectFieldIterator_IterateTables_Action); end;//TdaSelectField implementation uses l3ImplUses , l3Base //#UC START# *5551DCD200EEimpl_uses* //#UC END# *5551DCD200EEimpl_uses* ; constructor TdaSelectField.Create(const aTableAlias: AnsiString; const aField: IdaFieldDescription; const anAlias: AnsiString = ''); //#UC START# *5551F6DC02D0_5551DCD200EE_var* //#UC END# *5551F6DC02D0_5551DCD200EE_var* begin //#UC START# *5551F6DC02D0_5551DCD200EE_impl* inherited Create; if anAlias = '' then f_Alias := aField.SQLName else f_Alias := anAlias; f_TableAlias := f_TableALias; f_Field := aField; //#UC END# *5551F6DC02D0_5551DCD200EE_impl* end;//TdaSelectField.Create class function TdaSelectField.Make(const aTableAlias: AnsiString; const aField: IdaFieldDescription; const anAlias: AnsiString = ''): IdaSelectField; var l_Inst : TdaSelectField; begin l_Inst := Create(aTableAlias, aField, anAlias); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//TdaSelectField.Make function TdaSelectField.Get_TableAlias: AnsiString; //#UC START# *555351D702B3_5551DCD200EEget_var* //#UC END# *555351D702B3_5551DCD200EEget_var* begin //#UC START# *555351D702B3_5551DCD200EEget_impl* Result := f_TableAlias; if Result <> '' then Result := Result + '.'; //#UC END# *555351D702B3_5551DCD200EEget_impl* end;//TdaSelectField.Get_TableAlias function TdaSelectField.Get_Field: IdaFieldDescription; //#UC START# *555351F500BC_5551DCD200EEget_var* //#UC END# *555351F500BC_5551DCD200EEget_var* begin //#UC START# *555351F500BC_5551DCD200EEget_impl* Result := f_Field; //#UC END# *555351F500BC_5551DCD200EEget_impl* end;//TdaSelectField.Get_Field function TdaSelectField.Get_Alias: AnsiString; //#UC START# *555352070022_5551DCD200EEget_var* //#UC END# *555352070022_5551DCD200EEget_var* begin //#UC START# *555352070022_5551DCD200EEget_impl* Result := f_Alias; //#UC END# *555352070022_5551DCD200EEget_impl* end;//TdaSelectField.Get_Alias function TdaSelectField.BuildSQLValue(AddAlias: Boolean = True): AnsiString; //#UC START# *5608E5A4025F_5551DCD200EE_var* //#UC END# *5608E5A4025F_5551DCD200EE_var* begin //#UC START# *5608E5A4025F_5551DCD200EE_impl* Result := f_Field.SQLName; if AddAlias and (f_Alias <> '') then Result := Result + ' as ' + f_Alias; if f_TableAlias <> '' then Result := f_TableAlias + '.' + Result; //#UC END# *5608E5A4025F_5551DCD200EE_impl* end;//TdaSelectField.BuildSQLValue procedure TdaSelectField.IterateTables(anAction: daSelectFieldIterator_IterateTables_Action); //#UC START# *5756AC9B0213_5551DCD200EE_var* //#UC END# *5756AC9B0213_5551DCD200EE_var* begin //#UC START# *5756AC9B0213_5551DCD200EE_impl* anAction(f_Field.Table); //#UC END# *5756AC9B0213_5551DCD200EE_impl* end;//TdaSelectField.IterateTables procedure TdaSelectField.IterateTablesF(anAction: daSelectFieldIterator_IterateTables_Action); var Hack : Pointer absolute anAction; begin try IterateTables(anAction); finally l3FreeLocalStub(Hack); end;//try..finally end;//TdaSelectField.IterateTablesF procedure TdaSelectField.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_5551DCD200EE_var* //#UC END# *479731C50290_5551DCD200EE_var* begin //#UC START# *479731C50290_5551DCD200EE_impl* f_Field := nil; inherited; //#UC END# *479731C50290_5551DCD200EE_impl* end;//TdaSelectField.Cleanup end.
unit IDocSpc; {$Include l3Define.inc} { $Id: IDocSpc.pas,v 1.118 2015/04/06 09:38:27 lukyanets Exp $ } {.$I evDefine.inc} interface Uses SysUtils, Windows, l3Types, l3Base, l3Date, evTypes, evCustomEditor, DT_Types, DT_Query, DT_IndexSupport, D_TxSrch, CustEditWin, EditWin; type TSrchByTextProc = function (const aSrchStr : AnsiString): TdtQuery; IDocSpecial = class(Tl3Base) private fDocWnd : TCustomEditorWindow; function cbfGetSelectStr(Sender : TObject; Var B: PAnsiChar; Var L: Long; Var CharSet: Smallint; Data : Pointer) : Boolean; procedure SetVLControlPrim; //procedure SetAnoncedPrim; procedure SelectTextAction(aActionProc : TSrchByTextProc); public constructor Create(aDocWnd : TCustomEditorWindow); reintroduce; procedure SetAbolished; procedure SetVChanged; procedure SetAnonced; procedure SetVLControl; procedure SetMoJNotReg; procedure ParseSelectTextAndSearch; procedure SearchBySelectText(aIndexKind : TIndexType); procedure AnalyseTextForParam(const aAnalizeStr : AnsiString = ''); procedure ShowDocInfo; procedure FindTNVED; function cnvDate2Text(Sender : TObject; Var B: PAnsiChar; Var L: Long; Var CharSet: Smallint; Data : Pointer) : Boolean; //function EraseSpecialParaWithHyperlinks(aHLDocID: TDocID; aParaStyleID: Integer): Boolean; function ReplaceHyperLinks(aSearchHLDocID: TDocID; aReplaceHLDocID: TDocID): Boolean; //function ReplaceHyperLinksInStyle(aSearchHLDocID: TDocID; // aReplaceHLDocID: TDocID; // aParaStyleID: Integer): Boolean; end; Type PPointer = ^Pointer; PPChar = ^PAnsiChar; function GetNumberFromStr(aStr : AnsiString) : Longint; //function GetNearSaturday : TStDate; implementation {$INCLUDE ProjectDefine.inc} uses StrUtils, Dialogs, vtDialogs, Forms, Controls, StdCtrls, //l3Date, StrShop, IniShop, l3DateSt, l3MinMax, l3DatLst, l3Chars, l3String, l3Interfaces, l3Languages, evExcept, evOp, evOpProc, evIntf, evSearch, evInternalInterfaces, evdStyles, evEditor, k2Base, k2Tags, //m4DBTools, daDataProvider, DT_Const, dt_AttrSchema, DT_Link, DT_Dict, DT_Active, DT_Doc, DT_SrchQueries, D_GetAbo, D_DocInf, arSearch, SrchWin, DictsSup, evFacadTextSource, evFacadeCursor,//evFacade, DocIntf, DocAttrIntf, DocAttrToolsIntf , Dt_Alarm, dt_DictTypes, dt_DictConst, nevBase ; type TButtonControlHack = class(TButtonControl) public property ClicksDisabled; end; { function GetNearSaturday : TStDate; begin Result := CurrentDate + 7 - Ord(l3Date.DayOfWeek(CurrentDate)) - 1; If Result = CurrentDate then Result := CurrentDate + 7; //если сегодня суббота то возвращаем следущую end; } (* //вариант, который берет только первое число ло точки "4.1.1" = 4 function GetNumberFromStr(aStr : AnsiString) : Longint; {Ищет число в строке. Используется при простановке номера Sub'a} var IB,IE : Integer; begin IB:=1; Result := -1; While (IB <= Length(aStr)) and not (aStr[IB] in cc_Digits) do Inc(IB); If (IB > Length(aStr)) then Exit; IE := Succ(IB); While (IE <= Length(aStr)) and (aStr[IE] in cc_Digits) do Inc(IE); try Result := StrToInt(Copy(aStr,IB,IE-IB)); except end; end; *) //вариант, который берет все цифры "4.1.1" = 411 function GetNumberFromStr(aStr : AnsiString) : Longint; {Ищет число в строке. Используется при простановке номера Sub'a} var lStr : ShortString; I : Integer; begin lStr := ''; Result := 0; for I := 1 to Length(aStr) do begin if aStr[I] in cc_Digits then lStr := lStr + aStr[I] else if aStr[I] <> '.' then Break; end; TryStrToInt(lStr, Result); end; constructor IDocSpecial.Create(aDocWnd : TCustomEditorWindow); begin Inherited Create; fDocWnd := aDocWnd; end; procedure IDocSpecial.SetAbolished; var S : AnsiString; S1, S2 : AnsiString; Pack : InevOp; VLControlLog : Boolean; lWarnID : Integer; l_DefaultStyleID : Long; lActIntRec : TActiveIntervalRec; lInd : Integer; lStartDate : TSTDate; lExpDate : TSTDate; l_AlarmRec : TAlarmRec; begin with fDocWnd as TDocEditorWindow do begin with (Document.AttrManager.GetDocAttribute(atJurLogRecords) as ILogDocAttributeTool) do begin if not HasDocThisLogRec(acIncluded) then begin If vtMessageDlg(l3CStr(@sidNotIncludedWarning), mtWarning, [mbYes, mbNo], 0, mbNo, mbNo) <> mrYes then Exit; end; if HasDocThisLogRec(acAbolished) then begin vtMessageDlg(l3CStr(@sidEWJurUnpower), mtWarning); Exit; end; end; with TGetAbolishDataDlg.Create(fDocWnd) do try if Showmodal = mrOK then begin VLControlLog := lstNameStr.Current = 8; S := lstNameStr.Items[lstNameStr.Current]; If VLControlLog then SetVLControlPrim else begin {Записать в ЮЖ утратил силу с текущей датой} {---GlobalHTServer.LogBook[FDocFam].PutLogRecSet(DocID, acNoAction);} //Active with (Document.AttrManager.GetDocAttribute(atActiveIntervals) as IActiveIntervalsAttributeTool) do begin lInd := GetLastIntervalIndex; if (lstNameStr.Current in [18..21]) then begin if lInd >= 0 then Delete(lInd); AddRec(maxActiveDate, maxActiveDate); end else begin If edtExpDate.IsEmpty then lExpDate := minActiveDate else lExpDate := Pred(edtExpDate.StDate); if lInd >= 0 then CloseInterval(lInd, lExpDate) else AddRec(minActiveDate, lExpDate); end end; {!Abolished} if not (lstNameStr.Current in [18..21]) then (Document.AttrManager.GetDocAttribute(atJurLogRecords) as ILogDocAttributeTool) .AddAction(acAbolished, DateTimeToStDate(IniRec.NextVersionDate)); //Document.DocData.AddLogRec(acAbolished, DateTimeToStDate(IniRec.NextVersionDate)); S2 := ANSIUpperCase(S) + #0; //S := ' (' + ANSIUpperCase(S) + ')'; S := ' (' + S + ')'; //FullName If StrPos(FullNameMEdit.Buffer.S, @S2[1]) = nil then begin FullNameMEdit.GoToBottom; FullNameMEdit.InsertBuf(l3PCharLen(S)); end; //warning case lstNameStr.Current of 0..3 : lWarnID := 2; //утратил силу 4..7 : lWarnID := 3; //прекратил действие // 8 снято с контроля // 9 подписан Президентом РФ 11,17 : lWarnID := 19; //не действует, не применяется 12..15 : lWarnID := 31; //отменен 16 : lWarnID := 12; //действие приостановлено 18..21 : lWarnID := 4; //не вступил в силу else lWarnID := 0; end; if lWarnID > 0 then with (Document.AttrManager.GetDocAttribute(atWarnings) as IDictAttributeTool) do begin DeleteAll; AddRec(lWarnID); end; // устанавливаем аларм для "не вступил в силу" if (lstNameStr.Current in [18..21]) then begin {with l_AlarmRec do begin RecID := 0; Start := DateTimeToStDate(vtGetNearestDayOfWeek(Monday, False)); l3StringToArray(Comment, 1000, 'проверить публикацию'); end;} (Document.AttrManager.GetDocAttribute(atAlarms) as IAlarmAttributeTool).AddRec(DateTimeToStDate(vtGetNearestDayOfWeek(Monday, False)), l3PCharLen('проверить публикацию')); end; //in Spr if ((Document.Spravka <> nil) and Document.Spravka.TextSource.Document.IsValid) or (IsNewDoc and (cbUserType.ItemIndex in [0,1])) and not (lstNameStr.Current in [18..21]) then with SprTextEditor.DocEditor do begin Pack := StartOp(ev_ocUser+100); try GoToBottom; //MoveLeafCursor(ev_ocBottomRight); InsertBuf(cc_EOLStr); evInsertFrom(SprTextEditor.DocEditor, memoTextStr.TextSource); finally Pack := nil; {FinishOp;} end; end; end; //VLControlLog //in Doc if (evGetNettoCharCount(memoTextStr.TextSource) > 0) and not (lstNameStr.Current in [18..21]) then begin with DocTextEditor.DocEditor do begin Pack := StartOp(ev_ocUser+100); try GotoTop; try repeat with CurText do if (l3RTrimLen(S, SLen) <> 0) then break; until not MoveLeafCursor(ev_ocParaDown, true); if MoveLeafCursor(ev_ocParaDown, True) and (TextPara.Style.ID <> ev_saChangesInfo) then MoveLeafCursor(ev_ocParaUp, True); MoveLeafCursor(ev_ocParaEnd); InsertBuf(cc_EOLStr); except end; InsertBuf(cc_EOLStr); l_DefaultStyleID := TextSource.Processor.DefaultStyle; try TextSource.Processor.DefaultStyle := ev_saTxtComment; evInsertFrom(DocTextEditor.DocEditor, memoTextStr.TextSource); finally TextSource.Processor.DefaultStyle := l_DefaultStyleID; end; finally Pack := nil; {FinishOp;} end; end; end; end; finally Free; end; end; end; procedure IDocSpecial.SetMoJNotReg; var S : AnsiString; S1, S2 : AnsiString; lCurItemList : Tl3StringDataList; lInd : Integer; lRec : TDNDictRec; lWarnID : integer; begin With fDocWnd as TDocEditorWindow do begin if not (Document.AttrManager.GetDocAttribute(atJurLogRecords) as ILogDocAttributeTool).HasDocThisLogRec(acIncluded) then begin If vtMessageDlg(l3CStr(@sidNotIncludedWarning), mtWarning, [mbYes, mbNo], 0, mbNo, mbNo) <> mrYes then Exit; end; if (Document.AttrManager.GetDocAttribute(atJurLogRecords) as ILogDocAttributeTool).HasDocThisLogRec(acAbolished) then begin vtMessageDlg(l3CStr(@sidEWJurUnpower), mtWarning); Exit; end; {!Abolished} (Document.AttrManager.GetDocAttribute(atJurLogRecords) as ILogDocAttributeTool).HasDocThisLogRec(acAbolished,DateTimeToStDate(IniRec.NextVersionDate)); S := ' (не действует)'; S2 := ANSIUpperCase(S) + #0; If StrPos(FullNameMEdit.Buffer.S, @S2[1]) = nil then begin FullNameMEdit.GoToBottom; FullNameMEdit.InsertBuf(l3PCharLen(S)); end; {MojnotReg} l3FillChar(lRec, SizeOf(lRec)); lRec.ID := cUndefDictID; lRec.Typ := dnMU; (Document.AttrManager.GetDocAttribute(atDateNums) as IDateNumDocAttributeTool).AddRec(dnMU, 0, cc_UnAssignedStr); lWarnID := 6; (Document.AttrManager.GetDocAttribute(atWarnings) as IDictAttributeTool).AddRec(lWarnID); end; end; procedure IDocSpecial.SetVChanged; const lWarnNum : Integer = 12; begin With fDocWnd.Document.AttrManager do begin with (GetDocAttribute(atJurLogRecords) as ILogDocAttributeTool) do if not HasDocThisLogRec(acIncluded) then begin if vtMessageDlg(l3CStr(@sidNotIncludedWarning), mtWarning, [mbYes, mbNo], 0, mbNo, mbNo) <> mrYes then Exit; end else AddLogRecOnce(acChanged, DateTimeToStDate(IniRec.NextVersionDate), DateTimeToStDate(IniRec.NextVersionDate)); with GetDocAttribute(atWarnings) as IListDocAttribute do if (Count > 0) and (Handle[0] = lWarnNum) then Delete(0); end; end; procedure IDocSpecial.SetVLControl; begin With fDocWnd as TDocEditorWindow do begin if not (Document.AttrManager.GetDocAttribute(atJurLogRecords) as ILogDocAttributeTool).HasDocThisLogRec(acIncluded) then begin If vtMessageDlg(l3CStr(@sidNotIncludedWarning), mtWarning, [mbYes, mbNo], 0, mbNo, mbNo) <> mrYes then Exit; end; end; SetVLControlPrim; end; procedure IDocSpecial.SetVLControlPrim; begin (fDocWnd.Document.AttrManager.GetDocAttribute(atJurLogRecords) as ILogDocAttributeTool).AddLogRecOnce(acLControl, 0, DateTimeToStDate(IniRec.NextVersionDate)); end; procedure IDocSpecial.SetAnonced; begin (fDocWnd.Document.AttrManager.GetDocAttribute(atJurLogRecords) as ILogDocAttributeTool).AddLogRecOnce(acAnonced, 0, DateTimeToStDate(IniRec.NextVersionDate)); end; function IDocSpecial.cbfGetSelectStr(Sender : TObject; Var B: PAnsiChar; Var L: Long; Var CharSet: Smallint; Data : Pointer) : Boolean; begin PString(Data)^ := l3ArrayToString(B[0], L); if (CharSet = CP_OEM) or (CharSet = CP_OEMLite) then OemToCharBuff(@PString(Data)^[1], @PString(Data)^[1], L); Result := False; end; procedure IDocSpecial.SelectTextAction(aActionProc : TSrchByTextProc); var AnalizeStr : AnsiString;//PAnsiChar; SavePersBlock : Boolean; SaveReadOnly : Boolean; l_Query : TdtQuery; begin With fDocWnd do begin if CurEditor.Selection.Collapsed then begin AnalizeStr := CurEditor.Range.AsString; end else begin AnalizeStr := ''; //Nil; if CurEditor.Selection <> nil then SavePersBlock := CurEditor.Selection.Persistent else SavePersBlock := False; SaveReadOnly := CurEditor.ReadOnly; with CurEditor do begin if Selection <> nil then Selection.Persistent := True; ReadOnly := False; TextBufConvert(cbfGetSelectStr, @AnalizeStr); {GetSelectBlockString} if Selection <> nil then Selection.Persistent := SavePersBlock; ReadOnly := SaveReadOnly; end; end; if Length(AnalizeStr) = 0 then Exit; l_Query := nil; try try Screen.Cursor:=crHourGlass; l_Query := aActionProc(AnalizeStr); if (l_Query <> nil) and (not l_Query.IsEmpty) then With TSearchWin.Create(Application.MainForm) do begin Family := DocFamily; DocList.Query := l_Query; end else begin {aSrchServ.Free;} ShowMessage(sidNoSuchDoc); end; finally Screen.Cursor := crDefault; end; finally l3Free(l_Query); end; end; end; procedure IDocSpecial.ParseSelectTextAndSearch; function lSrchFunc(const aSrchStr : AnsiString): TdtQuery; begin Result := SQText2Query(aSrchStr); end; var lAction : Tl3FreeAction; begin lAction := L3LocalStub(@lSrchFunc); try SelectTextAction(TSrchByTextProc(lAction)); finally l3FreeFA(lAction); end; end; procedure IDocSpecial.SearchBySelectText(aIndexKind : TIndexType); function lSrchProc(const aSrchStr : AnsiString): TdtQuery; var l_Q : TdtQuery; begin l_Q := TdtTextQuery.Create(aSrchStr, aIndexKind); if (aIndexKind = itDictEntry) then begin // здесь раньше был вот такой код: //if (lSrchServRef <> nil) and (aIndexKind = itDictEntry) then // lSrchServRef.DocTypeFilter := lSrchServRef.DocTypeFilter + [dtDictEntry]; // // необходимо понять, как это проверить и что вообще с этим делать, т.к. сейчас // фильтры реализуются с помощью дополнительной query и не знают про умолчания end; Result := l_Q; end; var lAction : Tl3FreeAction; begin lAction := L3LocalStub(@lSrchProc); try SelectTextAction(TSrchByTextProc(lAction)); finally l3FreeFA(lAction); end; end; procedure IDocSpecial.AnalyseTextForParam(const aAnalizeStr : AnsiString = ''); function AnalyseOne(var aStr : Tl3PCharLen) : Boolean; var lStr : AnsiString; begin Result := False; lStr := l3PCharLen2String(aStr, GlobalDataProvider.BaseLanguage[(fDocWnd as TDocEditorWindow).DocFamily].AnsiCodePage); // копируем с коррекцией кодировки l3ReplaceNonReadable(PAnsiChar(lStr), Length(lStr)); Trim(lStr); fDocWnd.Document.Analyse(lStr); end; var lStr : AnsiString; begin with fDocWnd as TDocEditorWindow do begin Screen.Cursor := crHourGlass; try //Document.SaveAttributes(0); if (aAnalizeStr = '') and evCursorInSel(CurEditor) then begin CurEditor.SelectWholeParas; CurEditor.TextBufConvertF(evL2CB(@AnalyseOne)); end else begin if aAnalizeStr <> '' then lStr := aAnalizeStr else if CurEditor.CurText.SLen > 0 then begin lStr := l3PCharLen2String(CurEditor.CurText, GlobalDataProvider.BaseLanguage[DocFamily].AnsiCodePage); with CurEditor.TextPara.Style do if ID <> ev_saTxtHeader1 then ID := ev_saTxtHeader1; end else Exit; fDocWnd.Document.Analyse(lStr); // собственно, анализ if not Assigned(FullNameMEdit.Buffer.S) or (FullNameMEdit.Buffer.S[0] = #0) then begin l3ReplaceNonReadable(PAnsiChar(lStr), Length(lStr)); Trim(lStr); evGetUndoBuffer(FullNameMEdit.TextSource).Disabled := true; try FullNameMEdit.Buffer := l3PCharLen(lStr, GlobalDataProvider.BaseLanguage[DocFamily].AnsiCodePage); finally evGetUndoBuffer(FullNameMEdit.TextSource).Disabled := false; end; FullNameMEdit.Modified := True; end; end; with Document do if ((Spravka <> nil) and not Spravka.TextSource.Document.IsValid) or (IsNewDoc and (cbUserType.ItemIndex in [0,1])) then LoadSpr else if ((Spravka <> nil) and Spravka.TextSource.Document.IsValid and (evGetNettoCharCount(Spravka.TextSource) = 0)) then GenerateSpr; finally Screen.Cursor := Cursor; end; end; end; procedure IDocSpecial.ShowDocInfo; begin With fDocWnd do begin With TShowDocInfoDlg.Create(fDocWnd) do try lblDocSize.Caption := Format(lblDocSize.Caption, [evGetNettoCharCount(CurEditor.TextSource)]); ShowModal; finally Free; end; end; end; procedure IDocSpecial.FindTNVED; Var Searcher : TarHLinkTNVEDSearcher; Replacer : TarHLinkTNVEDReplacer; SFlags : TevSearchOptionSet; begin SFlags := [{ev_soGlobal,} ev_soConfirm, ev_soReplaceAll]; Searcher := TarHLinkTNVEDSearcher.Create(fDocWnd); Try Replacer := TarHLinkTNVEDReplacer.Create(fDocWnd); Try {Replacer.Editor := FEditor;} Searcher.Options := SFlags; Replacer.Options := SFlags; //Replacer.OnFinishReplace := fDocWnd.RefReplacerFinishReplace; try fDocWnd.CurEditor.Find(Searcher, Replacer, SFlags); except on EevSearchFailed do vtMessageDlg(l3CStr(Searcher.NotFoundMessage), mtWarning); end;{try..finally} finally l3Free(Replacer); end; finally l3Free(Searcher); end; end; Function IDocSpecial.cnvDate2Text(Sender : TObject; Var B: PAnsiChar; Var L: Long; Var CharSet: Smallint; Data : Pointer) : Boolean; Var I, TI : Integer; {D, M ,Y : Integer;} S : String[4]; ResStr : String[30]; Procedure GetNumeric; begin {SkipSpace;} While (I <= L) and Not (B[I] in ['0'..'9']) do Inc(I); If (I > L) then Abort; S:=''; While (I <= L) and (B[I] in ['0'..'9']) do begin S:=S+B[I]; Inc(I); end; If (I > L) then Abort; end; begin Try I:=0; GetNumeric; ResStr:=S+' '; GetNumeric; TI:=StrToInt(S); If TI > 12 then Abort; ResStr:=ResStr+GetMonthNameR(TI)+' '; Try GetNumeric; S := IntToStr(ExpandYear(StrToInt(S))); ResStr:=ResStr + S + ' г.'; except end; PShortString(Data)^:=ANSILowerCase(ResStr); B:=PAnsiChar(Data)+1; L:=Length(ResStr); except B:=Nil; end; Result:=True; end; function IDocSpecial.ReplaceHyperLinks(aSearchHLDocID: TDocID; aReplaceHLDocID: TDocID): Boolean; var lSrchEngine : TTextSearchDlg; begin lSrchEngine := TTextSearchDlg.Create(nil); try lSrchEngine.ReplaceReferences((fDocWnd as TDocEditorWindow).DocTextEditor.DocEditor, aSearchHLDocID, aReplaceHLDocID); finally lSrchEngine.Free; end; end; (* type TidsHyperlinkSearcher = class(TevHyperlinkSearcher) private f_StyleID: Integer; protected public function DoCheckText(const aPara : Tk2AtomR; aText : Tl3CustomString; const aSel : TevPair; out theSel : TevPair): Bool; override; public property StyleID: Integer read f_StyleID write f_StyleID; end; TidsDeleteParaReplacer = class(TevBaseReplacer) private protected function ReplaceFunc(const Container : InevOp; Block : TevBlock): Bool; override; public end; { TddHyperlinkSearcher } function TidsHyperlinkSearcher.DoCheckText(const aPara : Tk2AtomR; aText : Tl3CustomString; const aSel : TevPair; out theSel : TevPair): Bool; begin Result:= false; if inherited DoCheckText(aPara, aText, aSel, theSel) then begin with aPara.rAtom(k2_tiStyle) do if IsValid and (AsLong = f_StyleID) then begin theSel.rStart := 0; theSel.rFinish := aText.Len; Result := true; end; end;//inherited DoCheckText end; { TidsHyperlinkReplacer } function TidsDeleteParaReplacer.ReplaceFunc(const Container: InevOp; Block: TevBlock): Bool; var l_Block : TevBlock; l_Block1 : TevBlock; begin // В текущей реализации удаляется только текст абзаца. Block.GetSolidBottomChildBlock(l_Block); try l_Block.GetParentBlock(l_Block1); try evDeleteBlock(l_Block1, Container); finally l3Free(l_Block1); end;//try..finally finally l3Free(l_Block); end;//try..finally // evDeleteBlock(Block, Container); Result := True; //IevOpInsertString(Block).DoIt(nil, Container, true, [misfDirect]); end; function IDocSpecial.EraseSpecialParaWithHyperlinks(aHLDocID: TDocID; aParaStyleID: Integer): Boolean; var l_HLSearcher: TidsHyperlinkSearcher; l_HLReplacer: TidsDeleteParaReplacer; l_A: TevAddress; begin l_HLSearcher:= TidsHyperlinkSearcher.Create(nil); try l_HLSearcher.Options:= l_HLSearcher.Options+[ev_soReplace, ev_soReplaceAll]; l_A.DocID:= aHLDocID; l_A.SubID:= -1; l_HLSearcher.SearchHyperAddress:= l_A; l_HLSearcher.StyleID:= aParaStyleID; l_HLReplacer:= TidsDeleteParaReplacer.Create(nil); try l_HLReplacer.Options:= l_HLSearcher.Options; try (fDocWnd as TDocEditorWindow).DocEditor.Find(l_HLSearcher, l_HLReplacer, l_HLSearcher.Options); Result:= True; except Result:= False; end; finally l3Free(l_HLReplacer); end; finally l3Free(l_HLSearcher); end; end; function IDocSpecial.ReplaceHyperLinksInStyle(aSearchHLDocID: TDocID; aReplaceHLDocID: TDocID; aParaStyleID: Integer): Boolean; var l_HLSearcher: TidsHyperlinkSearcher; l_HLReplacer: TidsDeleteParaReplacer; begin Abort; //! l_HLSearcher:= TidsHyperlinkSearcher.Create(nil); try l_HLSearcher.Options:= l_HLSearcher.Options+[ev_soReplace, ev_soReplaceAll]; l_HLSearcher.SearchHyperAddress:= TevAddress_C(aSearchHLDocID, -1); l_HLSearcher.StyleID:= aParaStyleID; l_HLReplacer:= TidsDeleteParaReplacer.Create(nil); try l_HLReplacer.Options:= l_HLSearcher.Options; try (fDocWnd as TDocEditorWindow).DocEditor.Find(l_HLSearcher, l_HLReplacer, l_HLSearcher.Options); Result:= True; except Result:= False; end; finally l3Free(l_HLReplacer); end; finally l3Free(l_HLSearcher); end; end; *) end.
// ********************************************************************** // // Copyright (c) 2001 MT Tools. // // All Rights Reserved // // MT_DORB is based in part on the product DORB, // written by Shadrin Victor // // See Readme.txt for contact information // // ********************************************************************** unit map_int; interface uses orbtypes; type ILongInterfaceMap = interface ['{61252F5A-4D23-11d4-9D27-204C4F4F5020}'] procedure Put(Key: _ulong; Item: IUnknown); function Get(Key: _ulong): IUnknown; procedure clear(); procedure erase(Key: _ulong); procedure Delete(Index: Integer); function count(): integer; function IndexOf(Item: IUnknown): integer; function Items(Index: integer): IUnknown; property Item[Key: _ulong]: IUnknown read Get write Put; default; end; ILongObjectMap = interface ['{49481980-CA85-4F61-BF8D-F731299BFD02}'] procedure Put(Key: long; Item: TObject); function Get(Key: long): TObject; procedure clear(); procedure erase(Key: long); procedure Delete(Index: Integer); function count(): integer; function IndexOf(Item: TObject): integer; function Items(Index: integer): TObject; property Item[Key: long]: TObject read Get write Put; default; end; IInterfaceLongMap = interface ['{61252F5B-4D23-11d4-9D27-204C4F4F5020}'] procedure Put(Key: IUnknown;Item: long); function Get(Key: IUnknown): long; function IndexOf(Key: IUnknown): integer; procedure erase(Key: IUnknown); property Item[Key: IUnknown]: long read Get write Put; default; end; TInterfaceInterfaceMapCompare = function(const Item1, Item2: IInterface): boolean; IInterfaceInterfaceMap = interface ['{61252F5C-4D23-11d4-9D27-204C4F4F5020}'] procedure Put(Key: IUnknown;Item: IUnknown); function Get(Key: IUnknown): IUnknown; function IndexOf(Key: IUnknown): integer; procedure Delete(Index: Integer); property Item[Key: IUnknown]: IUnknown read Get write Put; default; procedure erase(Key: IUnknown); function Count: integer; function Second(Index: Integer): IUnknown; function Find(Key: IInterface): IInterface; overload; procedure SetCompareFunc(AFunc: TInterfaceInterfaceMapCompare); procedure clear(); end; IInterfaceStack = interface ['{22F20EEF-A3C8-4A74-93D8-96345AF0FC2E}'] function Count: integer; function Peek: IInterface; function Pop: IInterface; procedure Push(const AIntf: IInterface); procedure Lock; procedure Unlock; end; IStringInterfaceMap = interface ['{4D921A6A-210C-46C9-8206-9497EBCACA14}'] procedure Put(Key: AnsiString; const Item: IInterface); function Get(Key: AnsiString): IInterface; procedure Clear(); procedure Erase(const Key: AnsiString); procedure Delete(Index: Integer); function Count(): Integer; function IndexOf(const Item: IInterface): AnsiString; function Items(Index: integer): IInterface; procedure Lock; procedure Unlock; property Item[Key: AnsiString]: IInterface read Get write Put; default; end; implementation end.
{ ESM 2 JSON exporter. } unit esm2json_exporter; var json_output: TStringList; json_filecount: integer; // Called before processing // You can remove it if script doesn't require initialization code function Initialize: integer; begin Result := 0; json_output := TStringList.Create; // PrintElementTypes(); // PrintVarTypes(); end; procedure PrintVarTypes; begin AddMessage(''); AddMessage('varEmpty: ' + IntToStr(varEmpty)); AddMessage('varNull: ' + IntToStr(varNull)); AddMessage('varSmallint: ' + IntToStr(varSmallint)); AddMessage('varInteger: ' + IntToStr(varInteger)); AddMessage('varSingle: ' + IntToStr(varSingle)); AddMessage('varDouble: ' + IntToStr(varDouble)); AddMessage('varCurrency: ' + IntToStr(varCurrency)); AddMessage('varDate: ' + IntToStr(varDate)); AddMessage('varOleStr: ' + IntToStr(varOleStr)); AddMessage('varDispatch: ' + IntToStr(varDispatch)); AddMessage('varError: ' + IntToStr(varError)); AddMessage('varBoolean: ' + IntToStr(varBoolean)); AddMessage('varVariant: ' + IntToStr(varVariant)); AddMessage('varUnknown: ' + IntToStr(varUnknown)); AddMessage('varShortInt: ' + IntToStr(varShortInt)); AddMessage('varByte: ' + IntToStr(varByte)); AddMessage('varWord: ' + IntToStr(varWord)); AddMessage('varLongWord: ' + IntToStr(varLongWord)); AddMessage('varInt64: ' + IntToStr(varInt64)); AddMessage('varStrArg: ' + IntToStr(varStrArg)); AddMessage('varString: ' + IntToStr(varString)); AddMessage('varAny: ' + IntToStr(varAny)); AddMessage(''); end; procedure PrintElementTypes; begin AddMessage(''); AddMessage('DEBUG: Constants:'); AddMessage('etFile: ' + IntToStr(etFile)); AddMessage('etMainRecord: ' + IntToStr(etMainRecord)); AddMessage('etGroupRecord: ' + IntToStr(etGroupRecord)); AddMessage('etSubRecord: ' + IntToStr(etSubRecord)); AddMessage('etSubRecordStruct: ' + IntToStr(etSubRecordStruct)); AddMessage('etSubRecordArray: ' + IntToStr(etSubRecordArray)); AddMessage('etSubRecordUnion: ' + IntToStr(etSubRecordUnion)); AddMessage('etArray: ' + IntToStr(etArray)); AddMessage('etStruct: ' + IntToStr(etStruct)); AddMessage('etValue: ' + IntToStr(etValue)); AddMessage('etFlag: ' + IntToStr(etFlag)); AddMessage('etStringListTerminator: ' + IntToStr(etStringListTerminator)); AddMessage('etUnion: ' + IntToStr(etUnion)); AddMessage('etStructChapter: ' + IntToStr(etStructChapter)); AddMessage(''); end; function IsReference(e: IInterface): boolean; var sig: string; begin sig := Signature(e); if ( (sig = 'ACHR') Or (sig = 'REFR') Or (sig = 'ACRE') ) then begin Result := True; end else begin Result := False; end; end; function GetFormIDLabel(e: IInterface; formid: Cardinal): string; var name_string: string; base_formID: Cardinal; base_record, target_record: IInterface; begin target_record := RecordByFormID(GetFile(e), formid, True); name_string := EditorID(target_record); if ( (name_string = '') And (IsReference(target_record)) ) then begin name_string := '(' + Signature(target_record) + ')'; // base_formID := GetElementNativeValues(target_record, 'Name - Base'); // AddMessage('DEBUG: base_formID=' + IntToHex(base_formID, 8)); // base_record := RecordByFormID(GetFile(e), base_formID, True); // if (Assigned(base_record)) then // begin // name_string := 'BASE(' + EditorID(base_record) + ')'; // end; end; Result := '"' + name_string + ':' + IntToHex(formid, 8) + 'H"'; end; function ProcessChild(e: IInterface; prefix: string; postfix: string): integer; var element: IInterface; native_type, element_count, element_index, child_count: integer; element_name, type_string, element_path, element_edit_value, prefix2, postfix2: string; native_value: Variant; parent_type, element_type: TwbElementType; stringlist_length: integer; begin prefix2 := ' '; parent_type := ElementType(e); if ((parent_type = etArray) Or (parent_type = etSubRecordArray)) then begin // json_output.append(prefix + '['); stringlist_length := json_output.Count; json_output[stringlist_length-1] := json_output[stringlist_length-1] + ' ['; end else begin // json_output.append(prefix + '{'); stringlist_length := json_output.Count; // NOTE: stringlist_length = 0 will only happen at start of file, so above no need to check above if (stringlist_length = 0) then begin json_output.append('{'); end else begin json_output[stringlist_length-1] := json_output[stringlist_length-1] + ' {'; end; end; element_count := ElementCount(e); for element_index := 0 to element_count-1 do begin postfix2 := ''; if (element_index <> element_count-1) then postfix2 := ','; element := ElementByIndex(e, element_index); element_name := Name(element); element_path := Path(element); child_count := ElementCount(element); element_type := ElementType(element); element_edit_value := '"' + GetEditValue(element) + '"'; native_value := GetNativeValue(element); native_type := VarType(native_value); type_string := ''; // DEBUGGING // type_string := '[' + IntToStr(element_type) + ']'; // if ( (element_type = etValue) or (element_type = etFlag) or (element_type = etSubRecord)) then if (child_count = 0) then begin // AddMessage('DEBUG: element_path=' + element_path); if (Pos('Unused', element_path) = 0) then begin // if (element_type = etFlag) then element_edit_value := IntToHex(native_value, 8) + '!!!'; // if (VarType(native_value) = varLongWord) then element_edit_value := IntToHex(native_value, 8); if (native_type = 258) then begin element_edit_value := StringReplace(native_value,'\','\\', [rfReplaceAll]); element_edit_value := StringReplace(element_edit_value,'"','\"', [rfReplaceAll]); element_edit_value := StringReplace(element_edit_value, #13#10, '\r\n', [rfReplaceAll]); element_edit_value := StringReplace(element_edit_value, #10, '\n', [rfReplaceAll]); element_edit_value := '"' + element_edit_value + '"' end else if (native_type = varDouble) then begin element_edit_value := FloatToStrF(native_value, 2, 15, 15); end else if (native_type = varBoolean) then begin if (native_value) then begin element_edit_value := 'true'; end else begin element_edit_value := 'false'; end; end else if (native_type = varLongWord) then begin element_edit_value := '"' + IntToHex(native_value, 8) + 'H"'; end else if (native_type = varWord) then begin element_edit_value := '"' + IntToHex(native_value, 4) + 'H"'; end else if (varByte = varLongWord) then begin element_edit_value := '"' + IntToHex(native_value, 2) + 'H"'; end; // Display as: "EDID:FormID" if (Pos('INFO \ Choices \ TCLT - Choice', element_path) <> 0) then element_edit_value := GetFormIDLabel(e, native_value); if (Pos('QSTI - Quest', element_path) <> 0) then element_edit_value := GetFormIDLabel(e, native_value); if (Pos('AI Packages \ PKID - AI Package', element_path) <> 0) then element_edit_value := GetFormIDLabel(e, native_value); if (Pos('\ SPLO - Spell', element_path) <> 0) then element_edit_value := GetFormIDLabel(e, native_value); if (Pos('\ SNAM - Open sound', element_path) <> 0) then element_edit_value := GetFormIDLabel(e, native_value); if (Pos('\ QNAM - Close sound', element_path) <> 0) then element_edit_value := GetFormIDLabel(e, native_value); if (Pos('CNTO - Item \ Item', element_path) <> 0) then element_edit_value := GetFormIDLabel(e, native_value); if (Pos('Weather Type \ Weather', element_path) <> 0) then element_edit_value := GetFormIDLabel(e, native_value); if (Pos('\ Door', element_path) <> 0) then element_edit_value := GetFormIDLabel(e, native_value); if (Pos('\ NAME - Base', element_path) <> 0) then element_edit_value := GetFormIDLabel(e, native_value); if (Pos('SCRI - Script', element_path) <> 0) then element_edit_value := GetFormIDLabel(e, native_value); if (Pos('ENAM - Enchantment', element_path) <> 0) then element_edit_value := GetFormIDLabel(e, native_value); if (Pos('DATA - IDLE animation', element_path) <> 0) then element_edit_value := GetFormIDLabel(e, native_value); if (Pos('ANAM - Enchantment Points', element_path) <> 0) then element_edit_value := IntToStr(native_value); if (Pos('Weather Type \ Chance', element_path) <> 0) then element_edit_value := IntToStr(native_value); if (Pos('CNTO - Item \ Count', element_path) <> 0) then element_edit_value := IntToStr(native_value); if ( (Pos('EFIT - EFIT \ Type', element_path) <> 0) And (native_type <> 8209) ) then element_edit_value := '"' + GetEditValue(element) + ':' + IntToStr(native_value) + '"'; if (Pos('Flags', element_name) <> 0) then element_edit_value := '"' + IntToHex(native_value, 8) + 'H"'; if (CompareText('CELL \ DATA - Flags', element_path) = 0) then element_edit_value := '"' + IntToHex(native_value, 2) + 'H"'; if (Pos('\ Value', element_path) <> 0) then element_edit_value := IntToStr(native_value); if (Pos('Data Size', element_path) <> 0) then element_edit_value := IntToStr(native_value); if (Pos('\ Damage', element_path) <> 0) then element_edit_value := IntToStr(native_value); if (Pos('\ Armor', element_path) <> 0) then element_edit_value := IntToStr(native_value); if (Pos('\ Health', element_path) <> 0) then element_edit_value := IntToStr(native_value); if (Pos('EFID - Magic effect name', element_path) <> 0) then element_edit_value := '"' + GetEditValue(element) + '"'; if (Pos('Magic effect name', element_path) <> 0) then element_edit_value := '"' + GetEditValue(element) + '"'; if (CompareText('ENIT - ENIT \ Flags', element_path) = 0) then element_edit_value := '"' + IntToHex(native_value, 2) + 'H"'; if (Pos('EFIT - EFIT \ Magnitude', element_path) <> 0) then element_edit_value := IntToStr(native_value); if (Pos('EFIT - EFIT \ Area', element_path) <> 0) then element_edit_value := IntToStr(native_value); if (Pos('EFIT - EFIT \ Duration', element_path) <> 0) then element_edit_value := IntToStr(native_value); // if (Pos('EFIT - EFIT \ Type', element_path) <> 0) then element_edit_value := '"' + GetEditValue(element) + ':' + IntToStr(native_value) + '"'; if (Pos('EFIT - EFIT \ Actor Value', element_path) <> 0) then element_edit_value := '"' + GetEditValue(element) + ':' + IntToStr(native_value) + '"'; if (Pos('SCIT - Script effect data \ Script effect', element_path) <> 0) then element_edit_value := GetFormIDLabel(e, native_value); if (Pos('SCIT - Script effect data \ Magic school', element_path) <> 0) then element_edit_value := '"' + GetEditValue(element) + ':' + IntToStr(native_value) + '"'; if (Pos('SCIT - Script effect data \ Visual effect name', element_path) <> 0) then element_edit_value := '"' + GetEditValue(element) + ':' + IntToStr(native_value) + '"'; if (Pos('INFO \ Conditions \ CTDA - Condition \ Function', element_path) <> 0) then element_edit_value := '"' + GetEditValue(element) + ':' + IntToStr(native_value) + '"'; //if (Pos('INFO \ Conditions \ CTDA - Condition \ Parameter', element_path) <> 0) then element_edit_value := '"' + GetEditValue(element) + '"'; if (Pos('Primary Attribute', element_path) <> 0) then element_edit_value := '"' + GetEditValue(element) + ':' + IntToStr(native_value) + '"'; if (Pos('Major Skill', element_path) <> 0) then element_edit_value := '"' + GetEditValue(element) + ':' + IntToStr(native_value) + '"'; if (Pos('Specialization', element_path) <> 0) then element_edit_value := '"' + GetEditValue(element) + ':' + IntToStr(native_value) + '"'; if (Pos('Teaches', element_path) <> 0) then element_edit_value := '"' + GetEditValue(element) + ':' + IntToStr(native_value) + '"'; if (Pos('Skill Boost \ Skill', element_path) <> 0) then element_edit_value := '"' + GetEditValue(element) + ':' + IntToStr(native_value) + '"'; if (Pos('Skill Boost \ Boost', element_path) <> 0) then element_edit_value := IntToStr(native_value); if (Pos('RACE \ ATTR - Base Attributes', element_path) <> 0) then element_edit_value := IntToStr(native_value); if (Pos('Body Data \ Parts \ Part \ INDX - Index', element_path) <> 0) then element_edit_value := '"' + GetEditValue(element) + ':' + IntToStr(native_value) + '"'; if (Pos('Face Data \ Parts \ Part \ INDX - Index', element_path) <> 0) then element_edit_value := '"' + GetEditValue(element) + ':' + IntToStr(native_value) + '"'; if (Pos('QUST \ DATA - General \ Priority', element_path) <> 0) then element_edit_value := IntToStr(native_value); if (Pos('Stage \ INDX - Stage index', element_path) <> 0) then element_edit_value := IntToStr(native_value); if (Pos('SCHR - Basic Script Data \ RefCount', element_path) <> 0) then element_edit_value := IntToStr(native_value); if (Pos('SCHR - Basic Script Data \ CompiledSize', element_path) <> 0) then element_edit_value := IntToStr(native_value); if (Pos('SCHR - Basic Script Data \ VariableCount', element_path) <> 0) then element_edit_value := IntToStr(native_value); if (Pos('SCHR - Basic Script Data \ Type', element_path) <> 0) then element_edit_value := '"' + GetEditValue(element) + ':' + IntToStr(native_value) + '"'; if (Pos('SCRO - Global Reference', element_path) <> 0) then element_edit_value := GetFormIDLabel(e, native_value); if (Pos(' \ DATA - Point Count', element_path) <> 0) then element_edit_value := IntToStr(native_value); if (Pos(' \ Connections', element_path) <> 0) then element_edit_value := IntToStr(native_value); if (Pos('PGRP - Points \ Point ', element_path) <> 0) then element_edit_value := IntToStr(native_value); if (Pos(' Color \ Red', element_path) <> 0) then element_edit_value := IntToStr(native_value); if (Pos(' Color \ Green', element_path) <> 0) then element_edit_value := IntToStr(native_value); if (Pos(' Color \ Blue', element_path) <> 0) then element_edit_value := IntToStr(native_value); if (Pos('\ XCMT - Music', element_path) <> 0) then element_edit_value := '"' + GetEditValue(element) + ':' + IntToStr(native_value) + '"'; if (Pos('XCLL - Lighting \ Directional Rotation XY', element_path) <> 0) then element_edit_value := IntToStr(native_value); if (Pos('XCLL - Lighting \ Directional Rotation Z', element_path) <> 0) then element_edit_value := IntToStr(native_value); end; // AddMessage('DEBUG: VarType=' + VarToStr(VarType(native_value))); json_output.append(prefix + prefix2 + type_string + '"' + element_name + '": ' + element_edit_value + postfix2); end // if child_count <> 0 else begin if ( (parent_type <> etSubRecordArray) And (parent_type <> etArray) )then begin if (Pos('Flags', element_path) <> 0) then begin element_edit_value := '"' + IntToHex(native_value, 8) + 'H"'; if (CompareText('ENIT - ENIT \ Flags', element_path) = 0) then element_edit_value := '"' + IntToHex(native_value, 2) + 'H"'; if (CompareText('CELL \ DATA - Flags', element_path) = 0) then element_edit_value := '"' + IntToHex(native_value, 2) + 'H"'; json_output.append(prefix + prefix2 + type_string + '"' + element_name + '": ' + element_edit_value ); end else begin // AddMessage('TEST'); json_output.append(prefix + prefix2 + type_string + '"' + element_name + '":'); end; end; end; // if (Assigned(element_type)) then AddMessage('DEBUG: ElementType: ' + IntToStr(element_type)); if (child_count > 0) then ProcessChild(element, prefix + prefix2, postfix2); end; if ((parent_type = etArray) Or (parent_type = etSubRecordArray)) then begin json_output.append(prefix + ']' + postfix); end else begin json_output.append(prefix + '}' + postfix); end; end; // called for every record selected in xEdit function Process(e: IInterface): integer; var element, parent: IInterface; string_offset, element_count, element_index, child_count: integer; element_filename, element_path, element_edit_value, prefix: string; sig, x_string, parent_path, parent_basename: string; parent_type: TwbElementType; begin Result := 0; prefix := ' '; // AddMessage('Processing: ' + Name(e)); parent := GetContainer(e); element_filename := IntToHex(GetLoadOrderFormID(e),8) + '.json'; while (Assigned(parent)) do begin parent_type := ElementType(parent); parent_basename := BaseName(parent); // AddMessage('DEBUG: Container: [' + BaseName(parent) + ']: Type:' + IntToStr(parent_type) ); if (parent_type = etGroupRecord) then begin // 1. If basename starts with 'GRUP Cell ...' parent_path := parent_basename; if (Pos('GRUP Topic Children',parent_basename) = 1) then begin string_offset := Pos('[DIAL:', parent_basename) + 6; parent_path := copy(parent_basename, string_offset, 8); end else if (Pos('GRUP Cell',parent_basename) = 1) then begin // 2. Then If '...Children of [' Then record CELL:<FormID> if (Pos('GRUP Cell Children',parent_basename) = 1) then begin // Cell FORMID string_offset := Pos('[CELL:', parent_basename) + 6; parent_path := copy(parent_basename, string_offset, 8); // parent_path := IntToHex(GetLoadOrderFormID(e),8); end // 3. Else If '...Persistent Children' Then record 'Persistent' else if (Pos('GRUP Cell Persistent',parent_basename) = 1) then begin parent_path := 'Persistent'; end // 4. Else If '...Temporary...' Then ... else if (Pos('GRUP Cell Temporary',parent_basename) = 1) then begin parent_path := 'Temporary'; end // 5. Else If '...Visible...' Then ... else if (Pos('GRUP Cell Visible',parent_basename) = 1) then begin parent_path := 'Visible When Distant'; end; end // 6. Else if starts with 'GRUP Interior Cell ' ... else if (Pos('GRUP Interior Cell',parent_basename) = 1) then begin if (Pos('GRUP Interior Cell Sub-Block',parent_basename) = 1) then begin string_offset := Length(parent_basename); x_string := copy(parent_basename, 29, string_offset); parent_path := 'Sub-Block ' + x_string; end else if (Pos('GRUP Interior Cell Block',parent_basename) = 1) then begin string_offset := Length(parent_basename); x_string := copy(parent_basename, 25, string_offset); parent_path := 'Block ' + x_string end; end // 7. Else if starts with 'GRUP Exterior Cell ' ... else if (Pos('GRUP Exterior Cell',parent_basename) = 1) then begin if (Pos('GRUP Exterior Cell Sub-Block',parent_basename) = 1) then begin string_offset := Length(parent_basename); x_string := copy(parent_basename, 29, string_offset); parent_path := 'Sub-Block ' + x_string; end else if (Pos('GRUP Exterior Cell Block',parent_basename) = 1) then begin string_offset := Length(parent_basename); x_string := copy(parent_basename, 25, string_offset); parent_path := 'Block ' + x_string end; end // 8. Else if starts with 'GRUP World Children ' ... else if (Pos('GRUP World Children',parent_basename) = 1) then begin // worldspace FORMID string_offset := Pos('[WRLD:', parent_basename) + 6; parent_path := copy(parent_basename, string_offset, 8); end // 9. Else if starts with 'GRUP Top "' ... else if (Pos('GRUP Top ',parent_basename) = 1) then begin sig := Signature(e); if ( (sig = 'INFO') Or (CompareText(sig, 'LAND')=0) Or (CompareText(sig, 'PGRD')=0) Or (IsReference(e)) ) then begin parent_path := copy(parent_basename, 11, 4); end else begin parent_path := sig; end; end; end // Not GroupRecord else if (parent_type = etFile) then begin parent_path := parent_basename; end; element_path := parent_path + '\' + element_path; parent := GetContainer(parent); end; // AddMessage('DEBUG: composed path: ' + element_path); // AddMessage(''); // processing code goes here json_filecount := json_filecount + 1; if (json_filecount mod 100 = 0) then AddMessage('INFO: ' + IntToStr(json_filecount) + ' files written...'); // json_output := TStringList.Create; ProcessChild(e, '', ''); ForceDirectories(element_path); json_output.SaveToFile(element_path + element_filename); // json_output.Free; json_output.Clear; // AddMessage(''); end; // Called after processing // You can remove it if script doesn't require finalization code function Finalize: integer; begin AddMessage('Script Complete. ' + IntToStr(json_filecount) + ' json files written.'); json_output.Free; Result := 0; end; end.
{ Unit : verslab.pas Description : A TCustomLabel derivative that displays Win32 VersionInfo data Version : 1.02, 1 July 1997 Status : Freeware Contact : Marc Evans, marc@leviathn.demon.co.uk History: v1.01 : fixed bug stopping LangCharSet from actually doing anything at all on a non-UK system. v1.02 : Fixed resource leak bug. (surely there can't be any more? It's only 6K!) } unit verslab; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; const {The order of this array must be the same as the VersionResources enum type as that is used for the index lookup} VersionLookup: array[0..8, 0..1] of string = ( ('CompanyName', 'Company Name:'), ('FileDescription', 'File Description:'), ('FileVersion', 'File Version:'), ('InternalName', 'Internal Name:'), ('LegalCopyright', 'Legal Copyright:'), ('OriginalFilename', 'Original Filename:'), ('ProductName', 'Product Name:'), ('ProductVersion', 'Product Version:'), ('Comments', 'Comments:')); type TVersionResources = (vrCompanyName, vrFileDescription, vrFileVersion, vrInternalName, vrLegalCopyright, vrOriginalFilename, vrProductName, vrProductVersion, vrComments); type TVersionLabel = class(TCustomLabel) private { Private declarations } FVersionResource: TVersionResources; FInfoPrefix: string; FShowInfoPrefix: boolean; FVersionResourceKey: string; FLangCharset: string; procedure SetupInfoPrefix; procedure SetupResourceKey; procedure SetupCaption(CaptionBool: Boolean); protected { Protected declarations } procedure SetInfoPrefix(Value: String); function GetInfoPrefix: string; procedure SetVersionResource(Value: TVersionResources); procedure SetShowInfoPrefix(Value: boolean); procedure SetVersionResourceKey(Value: string); procedure SetLangCharset(Value: string); public { Public declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; function GetInfo(WithCaption: Boolean): string; published { Published declarations } property VersionResource: TVersionResources read FVersionResource write SetVersionResource; property VersionResourceKey: string read FVersionResourceKey write SetVersionResourceKey; property InfoPrefix: String read GetInfoPrefix write SetInfoPrefix; property ShowInfoPrefix: boolean read FShowInfoPrefix write SetShowInfoPrefix; property LangCharset: string read FLangCharset write SetLangCharset; property WordWrap; property Align; property Color; property Font; property AutoSize; property Alignment; property ParentFont; end; procedure Register; implementation procedure Register; begin RegisterComponents('FFS Common', [TVersionLabel]); end; constructor TVersionLabel.Create(AOwner: TComponent); begin inherited Create(AOwner); WordWrap := false; Autosize := true; ShowInfoPrefix := true; LangCharset :='040904E4'; {040904E4 is US prefix I think} VersionResource := vrFileVersion; end; destructor TVersionLabel.Destroy; begin inherited Destroy; end; procedure TVersionLabel.SetVersionResource(Value: TVersionResources); begin FVersionResource := Value; SetupResourceKey; SetupInfoPrefix; end; procedure TVersionLabel.SetupInfoPrefix; var s: string; begin s := VersionLookup[Integer(Self.VersionResource), 1]; InfoPrefix := s; end; procedure TVersionLabel.SetupResourceKey; var s: string; begin s := VersionLookup[Integer(Self.VersionResource), 0]; VersionResourceKey := s; end; function TVersionLabel.GetInfo(WithCaption: Boolean): string; var dump, s: dword; vallen: dword; buffer, VersionValue: pchar; VersionPointer: pchar; begin if csDesigning in Self.ComponentState then result := '< No design info >' else begin s := GetFileVersionInfoSize(pchar(Application.Exename), dump); if s = 0 then begin Result := '< No Data Available >'; end else begin buffer := StrAlloc(s+1); GetFileVersionInfo(Pchar(Application.Exename), 0, s, buffer); if VerQueryValue(buffer, pchar('\\StringFileInfo\\'+FLangCharSet+'\\'+ VersionResourceKey), pointer(VersionPointer), vallen) then begin if (Vallen > 1) then begin VersionValue := StrAlloc(vallen+1); StrLCopy(VersionValue, VersionPointer, vallen); Result := VersionValue; StrDispose(VersionValue); end else Result := 'No Version Info'; end else result := 'Error retrieving version info'; StrDispose(Buffer); end; end; if ((WithCaption) and (ShowInfoPrefix)) then Result := InfoPrefix+' '+Result; end; procedure TVersionLabel.SetInfoPrefix(Value: String); begin if FInfoPrefix = Value then exit; FInfoPrefix := Value; {The caption needs to be recalculated everytime the prefix is changed, otherwise the detaults override the user specified one} SetupCaption(True); end; procedure TVersionLabel.SetVersionResourceKey(Value: string); begin if FVersionResourceKey = Value then exit; FVersionResourceKey := Value; InfoPrefix := Value; end; function TVersionLabel.GetInfoPrefix: string; begin result := FInfoPrefix; end; procedure TVersionLabel.SetShowInfoPrefix(Value: boolean); begin if FShowInfoPrefix = value then exit; FShowInfoPrefix := Value; SetupCaption(True); end; procedure TVersionLabel.SetLangCharset(Value: string); begin if FLangCharSet = Value then exit; FLangCharSet := Value; SetupCaption(True); end; procedure TVersionLabel.SetupCaption(CaptionBool: Boolean); begin Caption := GetInfo(CaptionBool); end; end.
(* * Copyright (c) 2010-2020, Alexandru Ciobanu (alex+git@ciobanu.org) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of this library nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *) {$INCLUDE '..\TZDBPK\Version.inc'} unit TZCAPI; interface type /// <summary>Time zone enumerator procedure.</summary> /// <param name="Data">A data object provided by the consumer code.</param> /// <param name="Name">The name of the currently enumerated time zone.</param> /// <returns>Consmer must return <c>True</c> to interrupt the enumeraton process.</returns> TZ_EnumProc = function(Data: Pointer; Name: PChar): Boolean; stdcall; /// <summary>A <c>Pointer</c> to a <see cref="TZCAPI|TZ_Instance"/> stucture.</summary> PTZ_Instance = ^TZ_Instance; /// <summary>An opaque structure that identifies a time zone object.</summary> TZ_Instance = record FTZName: PChar; FTZObject: Pointer; end; /// <summary>A <c>Pointer</c> to a <see cref="TZCAPI|TZ_Time"/> type.</summary> PTZ_Time = ^TZ_Time; /// <summary>An <c>Int64</c> representing the C/UNIX time format.</summary> TZ_Time = Int64; /// <summary>A somewhat generic type used for most API methods in this library.</summary> /// <remarks>All negative values of this type signify an error. See <c>ERROR_*</c> constants for reference. /// Zero and the positive spectrum of values is function dependant. Each function will provide appropriate documentation.</remarks> TZ_Result = Integer; const /// <summary>The local time is in the Standard year period.</summary> LOCAL_TIME_STANDARD = 1; /// <summary>The local time is in the DST year period.</summary> LOCAL_TIME_DAYLIGHT = 2; /// <summary>The local time is in DST -> Standard year period.</summary> LOCAL_TIME_AMBIGUOUS = 3; /// <summary>The local time is in the Standard -> DST year period.</summary> LOCAL_TIME_INVALID = 4; /// <summary>A generic error. Source or cause unknwown.</summary> ERROR_UNKNOWN = -1; /// <summary>An argument passed to the function was invalid.</summary> ERROR_INVALID_ARG = -2; /// <summary>The time zone instance passed to the function was detected as being disposed.</summary> ERROR_INST_DISPOSED = -3; /// <summary>The local time value passed to the function was invalid in the given time zone.</summary> ERROR_INVALID_LOCAL_TIME = -4; /// <summary>Lists all known/supported time zone names.</summary> /// <param name="Data">User provided data that is passed along to <paramref name="EnumProc"/>.</param> /// <param name="IncludeAliases">Pass <c>True</c> to include time zone aliases into the list.</param> /// <param name="EnumProc">The enumerator procedure called for each item in the list.</param> /// <returns><c>True</c> is returned if the enumeration process was interrupted by the consumer. /// <c>False</c> is returned otherwise.</returns> function TZ_EnumTimeZones(IncludeAliases: Boolean; Data: Pointer; EnumProc: TZ_EnumProc): Boolean; stdcall; /// <summary>Looks up a time zone object by the given <paramref name="Name"/>.</summary> /// <param name="Name">The name time zone name to lookup. A <c>nil</c> value will be ignored.</param> /// <returns>A <c>Pointer</c> to a data structure containing the time zone object. Should be treated as an opaque /// <c>Pointer</c> by consumers. A <c>nil</c> value is returned if the time zone cannot be looked up.</returns> function TZ_InitInstance(Name: PChar): PTZ_Instance; stdcall; /// <summary>Releases a previously acquired instance.</summary> /// <param name="Instance">The time zone instance.</param> /// <returns>A zero or a positive value means success. See <c>ERROR_*</c> constants for possile errors (if the value is negative).</returns> function TZ_ReleaseInstance(Instance: PTZ_Instance): TZ_Result; stdcall; /// <summary>Generates an abbreviation string for the given local time.</summary> /// <param name="Instance">The time zone instance.</param> /// <param name="Time">The local time (C format).</param> /// <param name="ForceDaylight">Specify a <c>True</c> value if ambiguous periods should be treated as DST.</param> /// <param name="Abbrev">The output string parameter. Should be allocated.</param> /// <param name="AbbrevLen">The number of characters that <paramref name="Abbrev"/> can hold (excluding trailing \0).</param> /// <returns>The length of the actual name. If the value is negative, then an error occured. /// See <c>ERROR_*</c> constants for possile errors.</returns> /// <remarks>It is important to note that the consumer must specify an allocated memory block pointed by <paramref name="Abbrev"/>. /// The <paramref name="AbbrevLen"/> parameter must contain the number of bytes allocated. This method will fill this memory /// with the actual abbreviation and return the actual length of the abbreviation. There may be cases when the passed memory block /// is smaller than the actual length of the abbreviation. In those cases, only the part that will fit will be copied into the /// provided memory block.</remarks> function TZ_GetAbbreviation(Instance: PTZ_Instance; Time: TZ_Time; ForceDaylight: Boolean; Abbrev: PChar; AbbrevLen: Integer): TZ_Result; stdcall; /// <summary>Generates a diplay name for the given local time.</summary> /// <param name="Instance">The time zone instance.</param> /// <param name="Time">The local time (C format).</param> /// <param name="ForceDaylight">Specify a <c>True</c> value if ambiguous periods should be treated as DST.</param> /// <param name="DispName">The output string parameter. Should be allocated.</param> /// <param name="DispNameLen">The number of characters that <paramref name="DispName"/> can hold (excluding trailing \0).</param> /// <returns>The length of the actual name. If the value is negative, then an error occured. /// See <c>ERROR_*</c> constants for possile errors.</returns> /// <remarks>It is important to note that the consumer must specify an allocated memory block pointed by <paramref name="DispName"/>. /// The <paramref name="DispNameLen"/> parameter must contain the number of bytes allocated. This method will fill this memory /// with the actual name and return the actual length of the name. There may be cases when the passed memory block /// is smaller than the actual length of the name. In those cases, only the part that will fit will be copied into the /// provided memory block.</remarks> function TZ_GetDisplayName(Instance: PTZ_Instance; Time: TZ_Time; ForceDaylight: Boolean; DispName: PChar; DispNameLen: Integer): TZ_Result; stdcall; /// <summary>Returns the type of the local time.</summary> /// <param name="Instance">The time zone instance.</param> /// <param name="Time">The local time.</param> /// <returns>A zero or a positive result means success. See <c>LOCAL_TIME_*</c> constants for possible types. /// See <c>ERROR_*</c> constants for possile errors (if the value is negative).</returns> function TZ_GetLocalTimeType(Instance: PTZ_Instance; Time: TZ_Time): TZ_Result; stdcall; /// <summary>Returns the UTC offset of the given local time.</summary> /// <param name="Instance">The time zone instance.</param> /// <param name="Time">The local time.</param> /// <param name="ForceDaylight">Specify a <c>True</c> value if ambiguous periods should be treated as DST.</param> /// <param name="TimeType">An output parameter to which the UTC offset if copied.</param> /// <returns>A zero or a positive value means success. See <c>ERROR_*</c> constants for possile errors (if the value is negative).</returns> function TZ_GetUtcOffset(Instance: PTZ_Instance; Time: TZ_Time; ForceDaylight: Boolean; Offset: PInteger): TZ_Result; stdcall; /// <summary>Converts an UTC time to a local time.</summary> /// <param name="Instance">The time zone instance.</param> /// <param name="UtcTime">The UTC time to be converted.</param> /// <param name="LocalTime">The output parameter to hold the converted local time.</param> /// <returns>A zero or a positive value means success. See <c>ERROR_*</c> constants for possile errors (if the value is negative).</returns> function TZ_UtcToLocal(Instance: PTZ_Instance; UtcTime: TZ_Time; LocalTime: PTZ_Time): TZ_Result; stdcall; /// <summary>Converts a local time to UTC time.</summary> /// <param name="Instance">The time zone instance.</param> /// <param name="LocalTime">The local time to be converted.</param> /// <param name="ForceDaylight">Specify a <c>True</c> value if ambiguous periods should be treated as DST.</param> /// <param name="UtcTime">The output parameter to hold the converted UTC time.</param> /// <returns>A zero or a positive value means success. See <c>ERROR_*</c> constants for possile errors (if the value is negative).</returns> function TZ_LocalToUtc(Instance: PTZ_Instance; LocalTime: TZ_Time; ForceDaylight: Boolean; UtcTime: PTZ_Time): TZ_Result; stdcall; implementation uses SysUtils, DateUtils, Types, {$IFDEF DELPHI}TimeSpan,{$ENDIF} TZDB; const SUCCESS = 1; function TZ_EnumTimeZones(IncludeAliases: Boolean; Data: Pointer; EnumProc: TZ_EnumProc): Boolean; var I: Integer; LArray: {$IFDEF SUPPORTS_TARRAY}TArray<string>{$ELSE}TStringDynArray{$ENDIF}; LName: String; begin Result := false; if @EnumProc = nil then Exit; LArray := TBundledTimeZone.KnownTimeZones(IncludeAliases); { Iterate over all known records. } for I := 0 to Length(LArray) - 1 do begin LName := LArray[I]; if EnumProc(Data, PChar(LName)) then begin { If the enum proc returns true, stop iterating. } Result := true; Break; end; end; end; function TZ_InitInstance(Name: PChar): PTZ_Instance; stdcall; var LObject: TBundledTimeZone; begin if (Name = nil) then Exit(nil); { In case of any inner exception, do not leak it outside. } try LObject := TBundledTimeZone.GetTimeZone(Name); except Exit(nil); end; { Set result } New(Result); Result^.FTZObject := LObject; Result.FTZName := PChar(LObject.ID); end; function TZ_ReleaseInstance(Instance: PTZ_Instance): TZ_Result; begin { Verify parameters } if Instance = nil then Exit(ERROR_INVALID_ARG); if Instance^.FTZObject = nil then Exit(ERROR_INST_DISPOSED); { In case of any inner exception, do not leak it outside. } Instance^.FTZObject := nil; Dispose(Instance); Result := SUCCESS; end; function TZ_GetAbbreviation(Instance: PTZ_Instance; Time: TZ_Time; ForceDaylight: Boolean; Abbrev: PChar; AbbrevLen: Integer): Integer; var LValue: string; begin { Verify parameters } if (Instance = nil) or (Abbrev = nil) or (AbbrevLen < 1)then Exit(ERROR_INVALID_ARG); if Instance^.FTZObject = nil then Exit(ERROR_INST_DISPOSED); { Get the value we need } try LValue := TBundledTimeZone(Instance^.FTZObject).GetAbbreviation(UnixToDateTime(Time), ForceDaylight); except on ELocalTimeInvalid do Exit(ERROR_INVALID_LOCAL_TIME); on Exception do Exit(ERROR_UNKNOWN); end; { Init the result } StrLCopy(Abbrev, PChar(LValue), AbbrevLen); { Return the actual length of the name } Result := Length(LValue); end; function TZ_GetDisplayName(Instance: PTZ_Instance; Time: TZ_Time; ForceDaylight: Boolean; DispName: PChar; DispNameLen: Integer): TZ_Result; var LValue: string; begin { Verify parameters } if (Instance = nil) or (DispName = nil) or (DispNameLen < 1)then Exit(ERROR_INVALID_ARG); if Instance^.FTZObject = nil then Exit(ERROR_INST_DISPOSED); { Get the value we need } try LValue := TBundledTimeZone(Instance^.FTZObject).GetDisplayName(UnixToDateTime(Time), ForceDaylight); except on ELocalTimeInvalid do Exit(ERROR_INVALID_LOCAL_TIME); on Exception do Exit(ERROR_UNKNOWN); end; { Init the result } StrLCopy(DispName, PChar(LValue), DispNameLen); { Return the actual length of the name } Result := Length(LValue); end; function TZ_GetLocalTimeType(Instance: PTZ_Instance; Time: TZ_Time): TZ_Result; var LValue: TLocalTimeType; begin { Verify parameters } if Instance = nil then Exit(ERROR_INVALID_ARG); if Instance^.FTZObject = nil then Exit(ERROR_INST_DISPOSED); { Get the value we need } try LValue := TBundledTimeZone(Instance^.FTZObject).GetLocalTimeType(UnixToDateTime(Time)); except on ELocalTimeInvalid do Exit(ERROR_INVALID_LOCAL_TIME); on Exception do Exit(ERROR_UNKNOWN); end; { Get the value } case LValue of lttStandard: Result := LOCAL_TIME_STANDARD; lttDaylight: Result := LOCAL_TIME_DAYLIGHT; lttAmbiguous: Result := LOCAL_TIME_AMBIGUOUS; lttInvalid: Result := LOCAL_TIME_INVALID; else Result := ERROR_UNKNOWN; end; end; function TZ_GetUtcOffset(Instance: PTZ_Instance; Time: TZ_Time; ForceDaylight: Boolean; Offset: PInteger): TZ_Result; var LValue: {$IFDEF DELPHI}TTimeSpan{$ELSE}Int64{$ENDIF}; begin { Verify parameters } if Instance = nil then Exit(ERROR_INVALID_ARG); if Instance^.FTZObject = nil then Exit(ERROR_INST_DISPOSED); { Get the value we need } try LValue := TBundledTimeZone(Instance^.FTZObject).GetUtcOffset(UnixToDateTime(Time), ForceDaylight); { Transform into milliseconds } Offset^ := {$IFDEF DELPHI}Round(LValue.TotalSeconds){$ELSE}LValue{$ENDIF} * 1000; except on ELocalTimeInvalid do Exit(ERROR_INVALID_LOCAL_TIME); on Exception do Exit(ERROR_UNKNOWN); end; Result := SUCCESS; end; function TZ_UtcToLocal(Instance: PTZ_Instance; UtcTime: TZ_Time; LocalTime: PTZ_Time): TZ_Result; stdcall; begin { Get the value we need } try LocalTime^ := DateTimeToUnix(TBundledTimeZone(Instance^.FTZObject).ToLocalTime(UnixToDateTime(UtcTime))); except Exit(ERROR_UNKNOWN); end; Result := SUCCESS; end; function TZ_LocalToUtc(Instance: PTZ_Instance; LocalTime: TZ_Time; ForceDaylight: Boolean; UtcTime: PTZ_Time): TZ_Result; begin { Verify parameters } if Instance = nil then Exit(ERROR_INVALID_ARG); if Instance^.FTZObject = nil then Exit(ERROR_INST_DISPOSED); { Get the value we need } try UtcTime^ := DateTimeToUnix(TBundledTimeZone(Instance^.FTZObject).ToUniversalTime(UnixToDateTime(LocalTime), ForceDaylight)); except on ELocalTimeInvalid do Exit(ERROR_INVALID_LOCAL_TIME); on Exception do Exit(ERROR_UNKNOWN); end; Result := SUCCESS; end; end.
unit kwSetActivePage; {* *Формат:* ID_вкладки окно_редактора:перейти_на_вкладку *Описание:* Делает активной вкладку с номером ID_вкладки. *Примечания:* Константы с номерами вкладок находятся в файле: [code] w:\archi\source\projects\Archi\TestSet\Dictionary\ArchiControls.script" [code] } // Модуль: "w:\archi\source\projects\Archi\Archi_Insider_Test_Support\kwSetActivePage.pas" // Стереотип: "ScriptKeyword" // Элемент модели: "TkwSetActivePage" MUID: (4EAFC7190370) {$Include w:\archi\source\projects\Archi\arDefine.inc} interface {$If Defined(nsTest) AND Defined(InsiderTest) AND NOT Defined(NoScripts)} uses l3IntfUses , tfwRegisterableWord , tfwScriptingInterfaces ; type TkwSetActivePage = class(TtfwRegisterableWord) {* *Формат:* ID_вкладки окно_редактора:перейти_на_вкладку *Описание:* Делает активной вкладку с номером ID_вкладки. *Примечания:* Константы с номерами вкладок находятся в файле: [code] w:\archi\source\projects\Archi\TestSet\Dictionary\ArchiControls.script" [code] } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; end;//TkwSetActivePage {$IfEnd} // Defined(nsTest) AND Defined(InsiderTest) AND NOT Defined(NoScripts) implementation {$If Defined(nsTest) AND Defined(InsiderTest) AND NOT Defined(NoScripts)} uses l3ImplUses , arArchiTestsAdapter //#UC START# *4EAFC7190370impl_uses* //#UC END# *4EAFC7190370impl_uses* ; class function TkwSetActivePage.GetWordNameForRegister: AnsiString; begin Result := 'окно_редактора:перейти_на_вкладку'; end;//TkwSetActivePage.GetWordNameForRegister procedure TkwSetActivePage.DoDoIt(const aCtx: TtfwContext); //#UC START# *4DAEEDE10285_4EAFC7190370_var* //#UC END# *4DAEEDE10285_4EAFC7190370_var* begin //#UC START# *4DAEEDE10285_4EAFC7190370_impl* if aCtx.rEngine.IsTopInt then AcSetActivePage(aCtx.rEngine.PopInt) else Assert(False, 'Не задан номер вкладки!'); //#UC END# *4DAEEDE10285_4EAFC7190370_impl* end;//TkwSetActivePage.DoDoIt initialization TkwSetActivePage.RegisterInEngine; {* Регистрация TkwSetActivePage } {$IfEnd} // Defined(nsTest) AND Defined(InsiderTest) AND NOT Defined(NoScripts) end.
unit DrawForm; interface uses Windows, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Types, DBTables, DB, Grids, DBGrids, ExtCtrls, StdCtrls, DBCtrls, DBClient; type TForm1 = class(TForm) DataSource1: TDataSource; DBGrid1: TDBGrid; cds: TClientDataSet; cdsSpeciesNo: TFloatField; cdsCategory: TStringField; cdsCommon_Name: TStringField; cdsSpeciesName: TStringField; cdsLengthcm: TFloatField; cdsLength_In: TFloatField; cdsNotes: TMemoField; cdsGraphic: TGraphicField; procedure DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure FormCreate(Sender: TObject); procedure Table1NotesGetText(Sender: TField; var Text: String; DisplayText: Boolean); procedure Table1NotesSetText(Sender: TField; const Text: String); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); var Picture: TPicture; OutRect: TRect; PictWidth: Integer; begin // default output rectangle OutRect := Rect; if Column.Field = cdsCommon_Name then begin // draw the image Picture := TPicture.Create; try Picture.Assign(cdsGraphic); PictWidth := (Rect.Bottom - Rect.Top) * 2; OutRect.Right := Rect.Left + PictWidth; DBGrid1.Canvas.StretchDraw (OutRect, Picture.Graphic); finally Picture.Free; end; // reset output rectangle, leaving space for the graphic OutRect := Rect; OutRect.Left := OutRect.Left + PictWidth; end; // red font color if length > 100 if (Column.Field = cdsLengthcm) and (cdsLengthcm.AsInteger > 100) then DBGrid1.Canvas.Font.Color := clRed; // default drawing DBGrid1.DefaultDrawDataCell (OutRect, Column.Field, State); end; procedure TForm1.FormCreate(Sender: TObject); begin cds.Active := True; end; procedure TForm1.Table1NotesGetText(Sender: TField; var Text: String; DisplayText: Boolean); begin Text := Trim (Sender.AsString); end; procedure TForm1.Table1NotesSetText(Sender: TField; const Text: String); begin Sender.AsString := Text; end; end.
unit uMain; interface { Copyright 2020 Dmitriy Sosnovich, dmitriy@sosnovich.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. @version 1.0 with using of the Python4Delphi Component(https://github.com/pyscripter/python4delphi) } uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, PythonEngine, Vcl.StdCtrls, VarPyth, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, cxProgressBar, uTags, uConsts; type TfMain = class(TForm) btnStart: TButton; Log: TMemo; lblInstructions: TLabel; pbProgress: TcxProgressBar; procedure btnStartClick(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormCreate(Sender: TObject); private PythonEngine: TPythonEngine; columns_xpath: Variant; columns_name: Variant; procedure PrepareColumnsNamesByXmlVersion(const aVersion:variant); procedure Start; procedure ProcessDonorCsv; procedure ProcessCbuCsv; procedure CreatePythonEngine; procedure DestroyPythonEngine; procedure iterateOverDonors(const aFile: Variant; const aDonors: variant); procedure iterateOverCbus(const aFile: Variant; const aCbus: variant); procedure AttribsProcess(const aTag,aDonors_row:variant); public { Public declarations } end; var fMain: TfMain; implementation {$R *.dfm} procedure TfMain.AttribsProcess(const aTag, aDonors_row: variant); begin if (aTag.attrib <> None) then begin if (VarIsTrue(aTag.attrib.get(cBANK_ATTRIB_WMDA) <> None)) then aDonors_row.append(UTF8Encode(Trim(VarPythonAsString(aTag.attrib[cBANK_ATTRIB_WMDA])))) else aDonors_row.append(UTF8Encode(cEmptyAttr)); if (VarIsTrue(aTag.attrib.get(cBANK_ATTRIB_EMDIS) <> None)) then aDonors_row.append(UTF8Encode(Trim(VarPythonAsString(aTag.attrib[cBANK_ATTRIB_EMDIS])))) else aDonors_row.append(UTF8Encode(cEmptyAttr)); end; end; procedure TfMain.btnStartClick(Sender: TObject); begin Start; end; procedure TfMain.CreatePythonEngine; begin PythonEngine := TPythonEngine.Create(nil); with PythonEngine do begin AutoLoad := False; DllName := cPythonDll; DllPath := cPythonInstalledDir; APIVersion := 1013; RegVersion := '3.9'; UseLastKnownVersion := False; PyFlags := [pfOptimize]; end; MaskFPUExceptions(true); PythonEngine.LoadDLL; end; procedure TfMain.DestroyPythonEngine; begin if (Assigned(PythonEngine)) then begin PythonEngine.Finalize; FreeAndNil(PythonEngine); end; end; procedure TfMain.FormCreate(Sender: TObject); begin if (not FileExists(cPythonDllFullPath)) then begin raise Exception.Create('Python39.dll not found.'); Application.Terminate; end; CreatePythonEngine; columns_xpath := BuiltinModule.list(VarPythonCreate(cTagsXPathList)); columns_name := BuiltinModule.list(VarPythonCreate(cHeadersList)); //BANK_MANUF_ID and BANK_DISTRIB_ID have in version 2.2. attributes, so there is two more values one for the EMDIS other for WMDA, //but values are from the one tag. So, there is an exception for these two tags if ((len(columns_xpath)- 2) <> len(columns_name) ) then begin raise Exception.Create('Count of the tags xpath and header are not the same! columns_xpath:' + IntToStr(len(columns_xpath)) + ' ,columns_name' + IntToStr(len(columns_name)) + ' '); Application.Terminate; end; end; procedure TfMain.FormDestroy(Sender: TObject); begin DestroyPythonEngine; end; procedure TfMain.iterateOverCbus(const aFile: Variant; const aCBUs: Variant); var cbu: variant; tag: variant; tag_name: Variant; donor_row: Variant; final_list: Variant; begin final_list := BuiltinModule.list(); pbProgress.Properties.Max := len(aCBUs); for cbu in VarPyIterate(aCBUs) do begin donor_row := BuiltinModule.list(); for tag_name in VarPyIterate(columns_xpath) do begin tag := cbu.find(UTF8Encode(cXPathStart + tag_name)); if (tag <> None) then begin if (tag.text <> None) then begin donor_row.append(UTF8Encode(Trim(VarPythonAsString(tag.text.strip())))) ; if (tag.tag = cBANK_MANUF_ID ) or (tag.tag = cBANK_DISTRIB_ID) then begin AttribsProcess(VarPythonCreate(tag),VarPythonCreate(donor_row)) end; end else if (tag.tag = cBANK_MANUF_ID ) or (tag.tag = cBANK_DISTRIB_ID) then begin AttribsProcess(VarPythonCreate(tag),VarPythonCreate(donor_row)) end else donor_row.append(UTF8Encode(cEmptyTag)) end else donor_row.append(UTF8Encode(EmptyStr)) end; final_list.append(BuiltinModule.str(BuiltinModule.str(cCSVDelimiter).join(donor_row)) + VarPythonEval(cPythonNewStringExpression)); pbProgress.Position := pbProgress.Position + 1; Application.ProcessMessages; if (len(final_list) > 10000) then begin log.Lines.Add('10000'); Application.ProcessMessages; aFile.writelines(final_list); final_list.clear() end; end; if (len(final_list) > 0) then begin log.Lines.Add(VarPythonAsString(len(final_list))); Application.ProcessMessages; aFile.writelines(final_list); final_list.clear() end; end; procedure TfMain.iterateOverDonors(const aFile: Variant; const aDonors: variant); var donor: variant; tag: variant; tag_name: Variant; donor_row: Variant; final_list: Variant; begin pbProgress.Properties.Max := len(aDonors); final_list := BuiltinModule.list(); for donor in VarPyIterate(aDonors) do begin donor_row := BuiltinModule.list(); for tag_name in VarPyIterate(columns_xpath) do begin tag := donor.find(UTF8Encode(cXPathStart + tag_name)); if (tag <> None) then begin if (tag.text <> None) then donor_row.append(UTF8Encode(Trim(VarPythonAsString(tag.text.strip())))) else donor_row.append(UTF8Encode(cEmptyTag)) end else donor_row.append(UTF8Encode(EmptyStr)) end; final_list.append(BuiltinModule.str(BuiltinModule.str(cCSVDelimiter).join(donor_row)) + VarPythonEval(cPythonNewStringExpression)); pbProgress.Position := pbProgress.Position + 1; Application.ProcessMessages; if (len(final_list) > 10000) then begin log.Lines.Add('10000'); Application.ProcessMessages; aFile.writelines(final_list); final_list.clear() end; end; if (len(final_list) > 0) then begin log.Lines.Add(VarPythonAsString(len(final_list))); Application.ProcessMessages; aFile.writelines(final_list); final_list.clear() end; end; procedure TfMain.PrepareColumnsNamesByXmlVersion(const aVersion:variant); begin if (aVersion = cv2_1) then columns_name.extend(BuiltinModule.list(VarPythonCreate((cBanksManDistr21)))) else if (aVersion = cv2_2) then columns_name.extend(BuiltinModule.list(VarPythonCreate((cBanksManDistr22)))) else columns_name.extend(BuiltinModule.list(VarPythonCreate((cBanksManDistr21)))); end; procedure TfMain.ProcessCbuCsv; var pd: variant; df: Variant; datetime: Variant; os: Variant; begin pd := Import(cPandasLib); datetime := Import(cDateTimeLib); os := Import(cOsLib); df := pd.read_csv(UTF8Encode(cOutFull), UTF8Encode(cCSVDelimiter)); df := df.dropna(1, UTF8Encode('all')); df.to_csv(UTF8Encode(format(cDropped, ['C', datetime.datetime.now().strftime('%y%m%d%H%M%S')]))); os.remove(cOutFull) end; procedure TfMain.ProcessDonorCsv; var pd: variant; df: Variant; datetime: Variant; os: Variant; begin pd := Import(cPandasLib); datetime := Import(cDateTimeLib); os := Import(cOsLib); df := pd.read_csv(UTF8Encode(cOutFull), UTF8Encode(cCSVDelimiter)); df := df.dropna(1, UTF8Encode('all')); df.index.name := UTF8Encode(cRowId); df.to_csv(UTF8Encode(format(cDropped, ['D', datetime.datetime.now().strftime('%y%m%d%H%M%S')]))); os.remove(cOutFull) end; procedure TfMain.Start; var et: variant; tree: variant; root: Variant; inventory: variant; os: variant; version: variant; dlg: TOpenDialog; file_open: Variant; begin et := Import(cElementTreeLib); os := Import(cOsLib); dlg := TOpenDialog.Create(nil); try if (dlg.Execute) then begin tree := et.parse(Utf8Encode(dlg.FileName)); root := tree.getroot(); version := root.find(cINVENTORY).attrib[cVersionAttrib]; PrepareColumnsNamesByXmlVersion(VarPythonCreate(version)); try for inventory in VarPyIterate(root.findall(cInventoryTag)) do begin try if (not VarIsTrue(os.path.exists(cOutFolder))) then os.mkdir(cOutFolder); if (VarIsTrue(os.path.exists(cOutFull))) then os.remove(cOutFull); try if (len(inventory.findall(cDonorTag)) > 0) then begin file_open := BuiltinModule.open(cOutFull, 'w+'); try file_open.write(BuiltinModule.str(BuiltinModule.str(cCSVDelimiter).join(columns_name)) + VarPythonEval(cPythonNewStringExpression)); pbProgress.Position := 0; iterateOverDonors(VarPythonCreate(file_open), VarPythonCreate(inventory.findall(cDonorTag))); finally file_open.close(); ProcessDonorCsv; end; end; if (len(inventory.findall(cCBUTag)) > 0) then begin file_open := BuiltinModule.open(cOutFull, 'w+'); try file_open.write(BuiltinModule.str(BuiltinModule.str(cCSVDelimiter).join(columns_name)) + VarPythonEval(cPythonNewStringExpression)); pbProgress.Position := 0; iterateOverCbus(VarPythonCreate(file_open), VarPythonCreate(inventory.findall(cCBUTag))); finally file_open.close(); ProcessCbuCsv; end; end; finally end; except on EPyStopIteration do begin end; end; end; except on EPyStopIteration do begin end; end; end; finally dlg.free; end; end; end.
unit umpgSelectableStringList; interface uses Classes; type TmpgSelectableStringList = class(TObject) private FItems : TStrings; FMultiSelect: Boolean; FnItemIndex: integer; FOnChange: TNotifyEvent; FSelected : TStrings; function GetSelCount: Integer; function GetSelected(Index: Integer): Boolean; function GetText: string; procedure SetItemIndex(const Value: integer); procedure SetItems(const Value: TStrings); procedure SetSelected(Index: Integer; const Value: Boolean); procedure SetText(const Value: string); procedure SetMultiSelect(const Value: Boolean); public constructor Create; destructor Destroy; override; procedure Clear; procedure SelectAll; procedure UnSelectAll; property ItemIndex : integer read FnItemIndex write SetItemIndex; property Items: TStrings read FItems write SetItems; property MultiSelect: Boolean read FMultiSelect write SetMultiSelect; property OnChange : TNotifyEvent read FOnChange write FOnChange; property SelCount: Integer read GetSelCount; property Selected[Index: Integer]: Boolean read GetSelected write SetSelected; property Text : string read GetText write SetText; end; implementation { TmpgSelectableStringList } procedure TmpgSelectableStringList.Clear; begin FnItemIndex := -1; FItems.Clear; FSelected.Clear; end; constructor TmpgSelectableStringList.Create; begin inherited; FItems := TStringList.Create; FSelected := TStringList.Create; end; destructor TmpgSelectableStringList.Destroy; begin FItems.Free; FSelected.Free; inherited; end; function TmpgSelectableStringList.GetSelCount: Integer; begin result := FSelected.Count; end; function TmpgSelectableStringList.GetSelected(Index: Integer): Boolean; begin result := (FSelected.IndexOf(FItems[Index]) > -1); end; function TmpgSelectableStringList.GetText: string; begin if (FnItemIndex < 0) then result := '' else result := FItems[FnItemIndex]; end; procedure TmpgSelectableStringList.SetText(const Value: string); begin ItemIndex := FItems.IndexOf(Value); if (ItemIndex = -1) then FnItemIndex := FItems.Add(Value); end; procedure TmpgSelectableStringList.SelectAll; begin FSelected.Clear; FSelected.Assign(FItems); end; procedure TmpgSelectableStringList.SetItemIndex(const Value: integer); begin if (FnItemIndex <> Value) then begin FnItemIndex := Value; if Assigned(FOnChange) then FOnChange(Self); end; end; procedure TmpgSelectableStringList.SetItems(const Value: TStrings); begin FItems := Value; end; procedure TmpgSelectableStringList.SetSelected(Index: Integer; const Value: Boolean); var iIndex : integer; begin if FMultiSelect then begin iIndex := FSelected.IndexOf(FItems[Index]); if Value then if (iIndex = -1) then FSelected.Add(FItems[Index]) else if (iIndex >= 0) then FSelected.Delete(FSelected.IndexOf(FItems[Index])); end else begin FSelected.Clear; if (Value) then FSelected.Add(FItems[Index]); end; if not (Value) or (FSelected.Count = 0) then FnItemIndex := -1 else if (Value) and (FSelected.Count >= 0) then FnItemIndex := Index; end; procedure TmpgSelectableStringList.SetMultiSelect(const Value: Boolean); begin if (FMultiSelect <> Value) then FMultiSelect := Value; end; procedure TmpgSelectableStringList.UnSelectAll; begin FSelected.Clear; end; end.
unit Win95FileViewers; // Copyright (c) 1996 Jorge Romero Gomez, Merchise. interface uses Windows, ShellGUID; const // FileViewerShowInfo Flags FVSIF_RECT = $00000001; FVSIF_PINNED = $00000002; FVSIF_NEWFAILED = $08000000; FVSIF_NEWFILE = $80000000; FVSIF_CANVIEWIT = $40000000; type PFileViewerShowInfo = ^TFileViewerShowInfo; TFileViewerShowInfo = record Size : dword; Owner : HWND; Show : integer; Flags : dword; Rect : TRect; UnkRel : IUnknown; NewFile : array[0..MAX_PATH] of char;//TOleChar; end; type IFileViewerSite = class( IUnknown ) public constructor Create( aWinHandle : HWND ); public function QueryInterface( const iid : TIID; var obj) : HRESULT; override; stdcall; function AddRef : longint; override; stdcall; function Release : longint; override; stdcall; public function SetPinnedWindow( aWinHandle : HWND ) : HRESULT; virtual; stdcall; function GetPinnedWindow( var aWinHandle : HWND ) : HRESULT; virtual; stdcall; public WinHandle : HWND; private RefCount : integer; end; type IFileViewer = class( IUnknown) public function ShowInitialize( ViewerSite : IFileViewerSite ) : HRESULT; virtual; stdcall; abstract; function Show( ShowInfo : PFileViewerShowInfo) : HRESULT; virtual; stdcall; abstract; function PrintTo( Driver : pchar; SuppressUI : BOOL) : HRESULT; virtual; stdcall; abstract; end; function GetFileViewer( const aFileName : string; aSite : IFileViewerSite ) : IFileViewer; function AssociatedViewer( const ext : string; var ClassId : TCLSID ) : boolean; function ViewerLoader( ClassId : TCLSID) : IPersistFile; function CreateFileViewer( ClassId : TCLSID; const aFileName : string; aSite : IFileViewerSite ) : IFileViewer; const qvTryQuickViewOnly = 0; qvTryQuickViewFirst = 1; qvTryQuickViewPlusOnly = 2; var QuickViewPreference : integer = qvTryQuickViewOnly; QuickViewPlusInstalled : boolean; implementation uses SysUtils, RegUtils, OLEUtils; function AssociatedViewer( const ext : string; var ClassId : TCLSID ) : boolean; var CLSID : TRegistryKey; hk : HKEY; i : integer; procedure TryViewer; begin i := 0; while RegEnumKey( hk, i, CLSID, sizeof(CLSID)) = ERROR_SUCCESS do inc( i ); if i > 0 then begin try ClassId := StrToCLSID( CLSID ); Result := true; except on EBadCLSID do Result := false; end; end; RegCloseKey( hk ); end; begin Result := false; if (QuickViewPreference < qvTryQuickViewPlusOnly) and (RegOpenKey( HKEY_CLASSES_ROOT, pchar('QuickView.Original\' + ext), hk) = ERROR_SUCCESS) then TryViewer; if (not Result) and ((QuickViewPreference <> qvTryQuickViewOnly) or (not QuickViewPlusInstalled)) and (RegOpenKey( HKEY_CLASSES_ROOT, pchar('QuickView\' + ext), hk) = ERROR_SUCCESS) then TryViewer; end; function CreateSuitableViewer( const aFileName : string; aSite : IFileViewerSite ) : IFileViewer; var ClassId : TCLSID; CLSID : TRegistryKey; hk : HKEY; i : integer; procedure TryViewers; begin i := 0; while (RegEnumKey( hk, i, CLSID, sizeof(CLSID)) = ERROR_SUCCESS) and (Result = nil) do begin inc( i ); try ClassId := StrToCLSID( CLSID ); Result := CreateFileViewer( ClassId, aFileName, aSite ); except on EBadCLSID do Result := nil; end; end; RegCloseKey( hk ); end; begin Result := nil; if (QuickViewPreference < qvTryQuickViewPlusOnly) and (RegOpenKey( HKEY_CLASSES_ROOT, 'QuickView.Original\*', hk) = ERROR_SUCCESS) then TryViewers; if (Result = nil) and ((QuickViewPreference <> qvTryQuickViewOnly) or (not QuickViewPlusInstalled)) and (RegOpenKey( HKEY_CLASSES_ROOT, 'QuickView\*', hk) = ERROR_SUCCESS) then TryViewers; end; function ViewerLoader( ClassId : TCLSID ) : IPersistFile; begin if CoCreateInstance( ClassId, nil, CLSCTX_INPROC_SERVER, IID_IPersistFile, Result ) <> NO_ERROR then Result := nil; end; function CreateFileViewer( ClassId : TCLSID; const aFileName : string; aSite : IFileViewerSite ) : IFileViewer; var PersistFile : IPersistFile; WideStr : POleStr; begin PersistFile := ViewerLoader( ClassId ); if PersistFile <> nil then begin GetMem( WideStr, (length( aFileName ) + 1) * sizeof( TOleChar ) ); StringToWideChar( aFileName, WideStr, length( aFileName ) + 1 ); if (PersistFile.Load( WideStr, STGM_READ or STGM_SHARE_DENY_NONE ) = NO_ERROR) and (PersistFile.QueryInterface( IID_IFileViewer, Result ) = NO_ERROR) then begin if Result.ShowInitialize( aSite ) <> NO_ERROR then begin Result.Release; Result := nil; end; end else Result := nil; PersistFile.Release; FreeMem( WideStr ); end else Result := nil; end; function GetFileViewer( const aFileName : string; aSite : IFileViewerSite ) : IFileViewer; var Ext : string; ClassId : TCLSID; begin Ext := ExtractFileExt( aFileName ); if AssociatedViewer( Ext, ClassId ) then Result := CreateFileViewer( ClassId, aFileName, aSite) else Result := CreateSuitableViewer( aFileName, aSite ); end; // IFileViewerSite constructor IFileViewerSite.Create( aWinHandle : HWND ); begin WinHandle := aWinHandle; end; function IFileViewerSite.QueryInterface( const iid : TIID; var obj) : HRESULT; begin Result := E_NOTIMPL; end; function IFileViewerSite.AddRef : longint; begin inc( RefCount ); Result := RefCount; end; function IFileViewerSite.Release : longint; begin dec( RefCount ); Result := RefCount; if RefCount = 0 then Free; end; function IFileViewerSite.SetPinnedWindow( aWinHandle : HWND ) : HRESULT; begin WinHandle := aWinHandle; Result := NO_ERROR; end; function IFileViewerSite.GetPinnedWindow( var aWinHandle : HWND ) : HRESULT; begin aWinHandle := WinHandle; Result := NO_ERROR; end; var hk : HKEY; QvpDll : string; initialization if RegOpenKey( HKEY_LOCAL_MACHINE, 'Software\Inso\Quick View Plus', hk ) = ERROR_SUCCESS then begin QvpDll := GetRegValue( hk, 'APIDLL' ); QuickViewPlusInstalled := (QvpDll <> '') and FileExists( QvpDll ); RegCloseKey( hk ); end else QuickViewPlusInstalled := false; end.
unit f2LinkParser; interface uses jclStringLists, RegExpr, d2dTypes, d2dFont, d2dFormattedText, furqContext; function OutTextWithLinks(const aStr: string; const aTAT: Id2dTextAddingTool; const aContext: TFURQContext; const aActions: IJclStringList = nil): string; implementation uses SysUtils, furqTypes, furqBase; const gLinkRegEx: TRegExpr = nil; function GetLinkRegEx: TRegExpr; begin if gLinkRegEx = nil then begin gLinkRegEx := TRegExpr.Create; gLinkRegEx.Expression := '\[\[([^[\]]+?)\]\]'; end; Result := gLinkRegEx; end; function OutTextWithLinks(const aStr: string; const aTAT: Id2dTextAddingTool; const aContext: TFURQContext; const aActions: IJclStringList = nil): string; var l_Start: Integer; l_AData: IFURQActionData; l_Loc: string; l_Params: IJclStringList; l_AM: TFURQActionModifier; l_ActionID: string; l_LIdx: Integer; l_LinkTarget: string; l_LinkTxt: string; l_Pos: Integer; l_RE: TRegExpr; l_SubStr: string; begin Result := ''; l_RE := GetLinkRegEx; if l_RE.Exec(aStr) then begin l_Start := 1; repeat if l_RE.MatchPos[0] > l_Start then begin l_SubStr := Copy(aStr, l_Start, l_RE.MatchPos[0] - l_Start); aTAT.AddText(l_SubStr); Result := Result + l_SubStr; end; l_Pos := Pos('|', l_RE.Match[1]); if l_Pos = 0 then begin l_LinkTxt := l_RE.Match[1]; l_LinkTarget := Trim(l_LinkTxt); if l_LinkTxt[1] in ['!', '%'] then Delete(l_LinkTxt, 1, 1); // удаляем модификаторы, если они присутствуют в упрощённой ссылке end else begin l_LinkTxt := Copy(l_RE.Match[1], 1, l_Pos-1); l_LinkTarget := Copy(l_RE.Match[1], l_Pos+1, MaxInt); end; l_Params := JclStringList; ParseLocAndParams(l_LinkTarget, l_Loc, l_Params, l_AM); l_LIdx := aContext.Code.Labels.IndexOf(l_Loc); if l_LIdx = -1 then begin aTAT.AddLink(l_LinkTxt, ''); Result := Result + l_LinkTxt; end else begin l_AData := TFURQActionData.Create(l_LIdx, l_Params, l_AM); l_ActionID := aContext.AddAction(l_AData, aActions); aTAT.AddLink(l_LinkTxt, l_ActionID); Result := Result + l_LinkTxt; end; l_Start := l_RE.MatchPos[0] + l_RE.MatchLen[0]; until not l_RE.ExecNext; if l_Start <= Length(aStr) then begin l_SubStr := Copy(aStr, l_Start, MaxInt); aTAT.AddText(l_SubStr); Result := Result + l_SubStr; end; end else begin aTAT.AddText(aStr); Result := aStr; end; end; initialization // nope finalization FreeAndNil(gLinkRegEx); end.
unit MoabTutorial; interface uses SysUtils, Tasks; const tidTask_ClusterMoab = 'MoabTutorial'; tidTask_Moab_MainHeadquarter = 'MoabMainHq'; tidTask_Moab_SelectProduct = 'MoabSelProduct'; tidTask_Moab_PharmaTutorial = 'MoabPharmaTutorial'; procedure RegisterTasks; implementation uses Kernel, ClusterTask, HeadquarterTasks, FoodStore, Tutorial, CommonTasks, BasicAccounts, StdAccounts, StdFluids, FacIds; // Register Moab Tutorial Tasks procedure RegisterTasks; begin with TMetaClusterTask.Create( tidTask_ClusterMoab, 'Moab Cluster Tutorial', '', // No description tidTask_Tutorial, // None 10, TClusterTask) do begin Priority := tprHighest - 1; ClusterName := 'Moab'; Register(tidClassFamily_Tasks); end; {// Main Headquarter with TMetaHeadquarterTask.Create( tidTask_MainHeadquarter, tidTask_Moab_MainHeadquarter, tidTask_ClusterMoab) do begin Priority := tprNormal - 1; Register(tidClassFamily_Tasks); end;} // Select Product Task with TMetaTask.Create( tidTask_SelectProduct, tidTask_Moab_SelectProduct, tidTask_ClusterMoab) do begin Priority := tprNormal - 2; Register(tidClassFamily_Tasks); end; CommonTasks.AssembleTutorialBranch( 'Gas', tidTask_Moab_SelectProduct, 'Moab', tidTask_BuildGenWarehouse, tidFluid_Gasoline, tidTask_BuildGasStation, 'Refinery', tidTask_BuildRefinery, tidTask_Moab_MainHeadquarter, tidTask_ClusterMoab, accIdx_GasStation, FID_GasStation, FID_Refinery, 0.667); CommonTasks.AssembleTutorialBranch( 'Clothes', tidTask_Moab_SelectProduct, 'Moab', tidTask_BuildGenWarehouse, tidFluid_Clothes, tidTask_BuildClotheStore, 'ClothesLic', tidTask_BuildClotheInd, tidTask_Moab_MainHeadquarter, tidTask_ClusterMoab, accIdx_ClothesStore, FID_ClotheStore, FID_Clothes, 0.1665); CommonTasks.AssembleTutorialBranch( 'HHA', tidTask_Moab_SelectProduct, 'Moab', tidTask_BuildGenWarehouse, tidFluid_HouseHoldingAppliances, tidTask_BuildHHAStore, 'HHALic', tidTask_BuildHHAInd, tidTask_Moab_MainHeadquarter, tidTask_ClusterMoab, accIdx_HHAStore, FID_HHAStore, FID_Household, 0.1665); end; end.
unit MapCustom; interface uses Engine; type TMapCustom = class(TObject) private FHeight: Integer; FWidth: Integer; function GetHeight: Integer; function GetWidth: Integer; public constructor Create; procedure Clear; virtual; abstract; procedure Render; virtual; abstract; property Width: Integer read GetWidth; property Height: Integer read GetHeight; end; implementation { TMapCustom } constructor TMapCustom.Create; begin FHeight := MAP_HEIGHT; FWidth := MAP_WIDTH; end; function TMapCustom.GetHeight: Integer; begin Result := FHeight; end; function TMapCustom.GetWidth: Integer; begin Result := FWidth; end; end.
program squareroot(input, output); var number : real; function squareroot(val : real) : real; const EPSILON = 1E-6; var root : real; begin if val = 0 then squareroot := 0 else begin root := 1; repeat root := (val / root + root) / 2 until abs(val / sqr(root) - 1) < EPSILON; squareroot := root end; end; begin read(number); writeln(squareroot(number) : 5 : 2) end.
unit UEndereco; interface uses Rest.client,REST.Types, System.SysUtils, System.JSON, Rest.Json; type TEndereco = class private FLogradouro: String; FBairro: String; FCep: String; FNumero: String; FComplemento: String; Flocalidade: String; FPais: String; FUf: String; FIdCliente: Integer; procedure SetBairro(const Value: String); procedure SetCep(const Value: String); procedure SetLocalidade(const Value: String); procedure SetComplemento(const Value: String); procedure SetUF(const Value: String); procedure SetLogradouro(const Value: String); procedure SetNumero(const Value: String); procedure SetPais(const Value: String); procedure SetIdCliente(const Value: Integer); public constructor Create; destructor Destroy; override; property IdCliente:Integer read FIdCliente write SetIdCliente; property Cep: String read FCep write SetCep; property Logradouro: String read FLogradouro write SetLogradouro; property Numero: String read FNumero write SetNumero; property Complemento: String read FComplemento write SetComplemento; property Bairro: String read FBairro write SetBairro; property Localidade: String read Flocalidade write SetLocalidade; property Uf: String read FUf write SetUF; property Pais: String read FPais write SetPais; function GetCep(CEP:String): TJSONObject; function ValidaCep(Cep:String): Boolean; const URL_BASE_CEP = 'https://viacep.com.br/ws/'; const COMPRIMENTO_CEP = 8; end; implementation { TEndereco } constructor TEndereco.Create; begin FLogradouro := ''; FBairro := ''; FComplemento := ''; FLocalidade := ''; FUf := ''; FCep := ''; end; destructor TEndereco.Destroy; begin inherited; end; function TEndereco.GetCep(CEP: String): TJSONObject; var Cliente : TRESTClient; Requisicao: TRESTRequest; Resposta : TRESTResponse; begin Cliente := TRESTClient.Create(nil); Requisicao := TRESTRequest.Create(nil); Resposta := TRESTResponse.Create(nil); try Cliente.BaseURL := URL_BASE_CEP; Requisicao.Client := Cliente; Requisicao.Response := Resposta; Requisicao.Resource := '{CEP}'; Requisicao.ResourceSuffix := 'json'; Requisicao.Method := rmGet; Requisicao.Params.AddUrlSegment('CEP',CEP); Requisicao.Execute; Result := TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes( Utf8ToAnsi(RawByteString(Resposta.JSONText))), 0) as TJSONObject finally Cliente.Free; Requisicao.Free; Resposta.Free; end; end; procedure TEndereco.SetBairro(const Value: String); begin FBairro := Value; end; procedure TEndereco.SetCep(const Value: String); var oEndereco: TEndereco; begin if not ValidaCep(Value) then exit; FCep := Value; try oEndereco := TJSON.JsonToObject<TEndereco>(GetCep(FCep)); if not Assigned(oEndereco) then raise Exception.Create('CEP inválido.'); FLogradouro := oEndereco.Logradouro; FComplemento:= oEndereco.Complemento; FBairro := oEndereco.Bairro; FLocalidade := oEndereco.Localidade; FUf := oEndereco.Uf; finally FreeAndNil(oEndereco); end; end; procedure TEndereco.SetLocalidade(const Value: String); begin Flocalidade := Value; end; procedure TEndereco.SetComplemento(const Value: String); begin FComplemento := Value; end; procedure TEndereco.SetUF(const Value: String); begin FUf := Value; end; procedure TEndereco.SetIdCliente(const Value: Integer); begin FIdCliente := Value; end; procedure TEndereco.SetLogradouro(const Value: String); begin FLogradouro := Value; end; procedure TEndereco.SetNumero(const Value: String); begin FNumero := Value; end; procedure TEndereco.SetPais(const Value: String); begin FPais := Value; end; function TEndereco.ValidaCep(Cep:String): Boolean; begin Result := True; if (Cep.Trim.Length <> COMPRIMENTO_CEP) or (cep.IsEmpty) then Result := False; end; end.
unit InternetSecurityManager; interface uses Windows, ActiveX, URLMon2; type TInternetSecurityManager = class(TInterfacedObject, IInternetSecurityManager) private function SetSecuritySite(pSite : IInternetSecurityMgrSite) : HRESULT; stdcall; function GetSecuritySite(out ppSite : IInternetSecurityMgrSite) : HRESULT; stdcall; function MapUrlToZone(pwszUrl : PWideChar; out pdwZone : DWORD; dwFlags : DWORD) : HRESULT; stdcall; function GetSecurityId(pwszUrl : PWideChar; pbSecurityId : PByte; var pcbSecurityId : DWORD; dwReserved : DWORD) : HRESULT; stdcall; function ProcessUrlAction(pwszUrl : PWideChar; dwAction : DWORD; pPolicy : PByte; cbPolicy : DWORD; pContext : PByte; cbContext : DWORD; dwFlags : DWORD; dwReserved : DWORD) : HRESULT; stdcall; function QueryCustomPolicy(pwszUrl : PWideChar; guidKey : PGUID; out ppPolicy : PByte; out pcbPolicy : DWORD; pContext : PByte; cbContext : DWORD; dwReserved : DWORD) : HRESULT; stdcall; function SetZoneMapping(dwZone : DWORD; lpszPattern : PWideChar; dwFlags : DWORD) : HRESULT; stdcall; function GetZoneMappings(dwZone : DWORD; out ppenumString : IEnumString; dwFlags : DWORD) : HRESULT; stdcall; end; implementation function TInternetSecurityManager.SetSecuritySite(pSite : IInternetSecurityMgrSite) : HRESULT; stdcall; begin Result := INET_E_DEFAULT_ACTION; end; function TInternetSecurityManager.GetSecuritySite(out ppSite : IInternetSecurityMgrSite) : HRESULT; stdcall; begin Result := INET_E_DEFAULT_ACTION; end; function TInternetSecurityManager.MapUrlToZone(pwszUrl : PWideChar; out pdwZone : DWORD; dwFlags : DWORD) : HRESULT; stdcall; begin Result := INET_E_DEFAULT_ACTION; end; function TInternetSecurityManager.GetSecurityId(pwszUrl : PWideChar; pbSecurityId : PByte; var pcbSecurityId : DWORD; dwReserved : DWORD) : HRESULT; stdcall; begin Result := INET_E_DEFAULT_ACTION; end; function TInternetSecurityManager.ProcessUrlAction(pwszUrl : PWideChar; dwAction : DWORD; pPolicy : PByte; cbPolicy : DWORD; pContext : PByte; cbContext : DWORD; dwFlags : DWORD; dwReserved : DWORD) : HRESULT; stdcall; begin if cbPolicy >= sizeof(DWORD) then begin PDWORD(pPolicy)^ := URLPOLICY_ALLOW; Result := S_OK; end else Result := E_OUTOFMEMORY; end; function TInternetSecurityManager.QueryCustomPolicy(pwszUrl : PWideChar; guidKey : PGUID; out ppPolicy : PByte; out pcbPolicy : DWORD; pContext : PByte; cbContext : DWORD; dwReserved : DWORD) : HRESULT; stdcall; begin Result := INET_E_DEFAULT_ACTION; end; function TInternetSecurityManager.SetZoneMapping(dwZone : DWORD; lpszPattern : PWideChar; dwFlags : DWORD) : HRESULT; stdcall; begin Result := INET_E_DEFAULT_ACTION; end; function TInternetSecurityManager.GetZoneMappings(dwZone : DWORD; out ppenumString : IEnumString; dwFlags : DWORD) : HRESULT; stdcall; begin Result := INET_E_DEFAULT_ACTION; end; end.
unit umain; {$mode objfpc}{$H+} interface uses Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, Buttons, StdCtrls, acs_file, acs_audio, EditBtn,acs_classes,acs_mixer; type { TfMain } TfMain = class(TForm) bOpen: TBitBtn; Mixer1: TACSMixer; AudioIn1: TACSAudioIn; FileOut1: TACSFileOut; bRecord: TBitBtn; bStop: TBitBtn; cbRecordSource: TComboBox; Label1: TLabel; procedure FormCreate(Sender: TObject); procedure bOpenClick(Sender: TObject); procedure bRecordClick(Sender: TObject); procedure bStopClick(Sender: TObject); procedure cbRecordSourceChange(Sender: TObject); private { private declarations } public { public declarations } end; var fMain: TfMain; implementation { TfMain } procedure TfMain.FormCreate(Sender: TObject); var i : Integer; begin for i := 0 to Mixer1.Channelcount-1 do if Mixer1.IsRecordable(i) then cbRecordSource.Items.Add(Mixer1.ChannelName[i]); cbRecordSource.Text := Mixer1.ChannelName[Mixer1.RecordSource]; end; procedure TfMain.bOpenClick(Sender: TObject); begin FileOut1.Open; if FileExists(FileOut1.FileName) then FileOut1.FileMode := foAppend; end; procedure TfMain.bRecordClick(Sender: TObject); begin FileOut1.Run; end; procedure TfMain.bStopClick(Sender: TObject); begin FileOut1.Stop; end; procedure TfMain.cbRecordSourceChange(Sender: TObject); var i : Integer; begin for i := 0 to Mixer1.Channelcount-1 do if Mixer1.ChannelName[i] = cbRecordSource.Text then Mixer1.RecordSource := i; end; initialization {$I umain.lrs} end.
unit SceneAbout; interface uses DGLE, DGLE_Types, Engine, SceneCustom, SceneManager, Button; type TSceneAbout = class(TSceneCustom) private BackButton: TButton; public constructor Create; destructor Destroy; override; procedure Render(); override; procedure Update(); override; end; implementation uses SceneEngine; { TAbout } constructor TSceneAbout.Create; begin inherited Create('About.jpg'); BackButton := TButton.Create; BackButton.Caption := 'Назад'; BackButton.Width := BUTTON_WIDTH; BackButton.Height := BUTTON_HEIGHT; BackButton.Top := SCREEN_HEIGHT - BUTTON_HEIGHT - 10; BackButton.Left := SCREEN_WIDTH - BUTTON_WIDTH - 10; BackButton.FontColorOver := ColorYellow(); BackButton.FontColorDefault := ColorGrey(); BackButton.FontColorSellected := ColorOrange(); BackButton.Sellected := True; end; destructor TSceneAbout.Destroy; begin BackButton.Free; inherited; end; procedure TSceneAbout.Render; begin inherited; BackButton.Render; end; procedure TSceneAbout.Update; begin BackButton.Update; if BackButton.Click then begin SceneMan.Scene := SceneMenu; end; end; end.
program letters; var i : char; begin for i := 'a' to 'z' do begin write(i, ' '); end; writeln() end.
unit Model.CadastroEmpresa; interface uses Common.ENum, FireDAC.Comp.Client, Dialogs; type TCadastroEmpresa = class private FID: Integer; FCPFCNPJ: System.String; FTipoDoc: String; FNome: System.String; FAlias: System.string; FSUFRAMA: System.String; FCRT: System.String; FCNAE: System.String; FStatus: System.Boolean; FLog: String; FAcao: TAcao; public property ID: Integer read FID write FID; property CPFCNPJ: String read FCPFCNPJ write FCPFCNPJ; property TipoDoc: String read FTipoDoc write FTipoDoc; property Nome: String read FNome write FNome; property Alias: String read FAlias write FAlias; property SUFRAMA: String read FSUFRAMA write FSUFRAMA; property CRT: String read FCRT write FCRT; property CNAE: String read FCNAE write FCNAE; property Status: Boolean read FStatus write FStatus; property Log: String read FLog write FLog; property Acao: TAcao read FAcao write FAcao; function GetID(): Integer; function Localizar(aParam: array of variant): TFDQuery; function Gravar(): Boolean; end; implementation { TCadastroEmpresa } uses DAO.CadastroEmpresa, Common.Utils; function TCadastroEmpresa.GetID: Integer; var cadastrosDAO : TCadastroEmpresaDAO; begin try cadastrosDAO := TCadastroEmpresaDAO.Create; Result := cadastrosDAO.GetId(); finally cadastrosDAO.Free; end; end; function TCadastroEmpresa.Gravar: Boolean; var cadastrosDAO: TCadastroEmpresaDAO; begin try cadastrosDAO := TCadastroEmpresaDAO.Create; case FAcao of tacIncluir: Result := cadastrosDAO.Insert(Self); tacAlterar: Result := cadastrosDAO.Update(Self); tacExcluir: Result := cadastrosDAO.Delete(Self); end; finally cadastrosDAO.Free; end; end; function TCadastroEmpresa.Localizar(aParam: array of variant): TFDQuery; var cadastrosDAO : TCadastroEmpresaDAO; begin try cadastrosDAO := TCadastroEmpresaDAO.Create; Result := cadastrosDAO.lOCALIZAR(aParam); finally cadastrosDAO.Free; end; end; end.
unit MFichas.Model.Empresa; interface uses System.SysUtils, MFichas.Model.Empresa.Interfaces, MFichas.Model.Entidade.EMPRESA, MFichas.Model.Conexao.Interfaces, MFichas.Model.Conexao.Factory, ORMBR.Container.ObjectSet.Interfaces, ORMBR.Container.ObjectSet, ORMBR.Container.DataSet.Interfaces, ORMBR.Container.FDMemTable, FireDAC.Comp.Client; type TModelEmpresa = class(TInterfacedObject, iModelEmpresa, iModelEmpresaMetodos) private FFDMemTable: TFDMemTable; FConn : iModelConexaoSQL; FDAO : iContainerObjectSet<TEMPRESA>; FDAODataSet: iContainerDataSet<TEMPRESA>; constructor Create; public destructor Destroy; override; class function New: iModelEmpresa; function Metodos : iModelEmpresaMetodos; function DAO : iContainerObjectSet<TEMPRESA>; function DAODataSet: iContainerDataSet<TEMPRESA>; //METODOS function BuscarModel: iModelEmpresaMetodosBuscarModel; function EditarView : iModelEmpresaMetodosEditarView; function BuscarView : iModelEmpresaMetodosBuscarView; function &End : iModelEmpresa; end; implementation { TModelEmpresa } uses MFichas.Model.Empresa.Metodos.Buscar.Model, MFichas.Model.Empresa.Metodos.Buscar.View, MFichas.Model.Empresa.Metodos.Editar.View; function TModelEmpresa.&End: iModelEmpresa; begin Result := Self; end; function TModelEmpresa.BuscarModel: iModelEmpresaMetodosBuscarModel; begin Result := TModelEmpresaMetodosBuscarModel.New(Self); end; function TModelEmpresa.BuscarView: iModelEmpresaMetodosBuscarView; begin Result := TModelEmpresaMetodosBuscarView.New(Self); end; constructor TModelEmpresa.Create; begin FFDMemTable := TFDMemTable.Create(nil); FConn := TModelConexaoFactory.New.ConexaoSQL; FDAO := TContainerObjectSet<TEMPRESA>.Create(FConn.Conn); FDAODataSet := TContainerFDMemTable<TEMPRESA>.Create(FConn.Conn, FFDMemTable); end; function TModelEmpresa.DAO: iContainerObjectSet<TEMPRESA>; begin Result := FDAO; end; function TModelEmpresa.DAODataSet: iContainerDataSet<TEMPRESA>; begin Result := FDAODataSet; end; destructor TModelEmpresa.Destroy; begin {$IFDEF MSWINDOWS} FreeAndNil(FFDMemTable); {$ELSE} FFDMemTable.Free; FFDMemTable.DisposeOf; {$ENDIF} inherited; end; function TModelEmpresa.EditarView: iModelEmpresaMetodosEditarView; begin Result := TModelEmpresaMetodosEditarView.New(Self); end; function TModelEmpresa.Metodos: iModelEmpresaMetodos; begin Result := Self; end; class function TModelEmpresa.New: iModelEmpresa; begin Result := Self.Create; 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 frmMaterializedViewDetail; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Menus, cxLookAndFeelPainters, cxGraphics, cxCheckBox, cxGroupBox, cxRadioGroup, cxLabel, cxMemo, cxRichEdit, cxMaskEdit, cxDropDownEdit, cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox, cxContainer, cxEdit, cxTextEdit, StdCtrls, jpeg, ExtCtrls, cxPC, cxControls, cxButtons, cxSpinEdit, cxCalendar, cxTimeEdit, cxImageComboBox, OraMaterializedView, GenelDM; type TMaterializedViewDetailFrm = class(TForm) pc: TcxPageControl; tsView: TcxTabSheet; tsProperties: TcxTabSheet; tsDDL: TcxTabSheet; redtDDL: TcxRichEdit; cxGroupBox1: TcxGroupBox; cxLabel1: TcxLabel; cxLabel2: TcxLabel; cboxMethod: TcxComboBox; cbWhen: TcxComboBox; tedtOnThisTime: TcxTimeEdit; dedtOnThisDate: TcxDateEdit; cxLabel7: TcxLabel; cbType: TcxComboBox; tsStorage: TcxTabSheet; cxGroupBox2: TcxGroupBox; cxLabel17: TcxLabel; cbBuiltType: TcxComboBox; chkParalel: TcxCheckBox; edtParalelDegree: TcxMaskEdit; chkAllowUpdates: TcxCheckBox; chkPrebuiltOption: TcxCheckBox; chkEnableRowMovement: TcxCheckBox; chkEnableQueryRewrite: TcxCheckBox; cboxPrebuiltOption: TcxComboBox; cxGroupBox3: TcxGroupBox; chkUsingIndex: TcxCheckBox; cxLabel4: TcxLabel; chkStartOn: TcxCheckBox; chkNext: TcxCheckBox; tedtOnNextTime: TcxTimeEdit; dedtOnNextDate: TcxDateEdit; chkCompress: TcxCheckBox; chkUseRollbackSegment: TcxCheckBox; cxGroupBox4: TcxGroupBox; rgLocation: TcxRadioGroup; cxLabel5: TcxLabel; edtRollbackSegmentName: TcxTextEdit; lcbUsingIndex: TcxLookupComboBox; cxGroupBox5: TcxGroupBox; Label2: TLabel; Label1: TLabel; edtViewName: TcxTextEdit; lcViewSchema: TcxLookupComboBox; edtSQLQuery: TcxRichEdit; cxLabel3: TcxLabel; btnTestSQL: TcxButton; Bevel1: TBevel; cxGroupBox6: TcxGroupBox; gbStorageClause: TcxGroupBox; Label11: TLabel; Label12: TLabel; Label13: TLabel; Label14: TLabel; Label5: TLabel; Label6: TLabel; Label16: TLabel; Label17: TLabel; edtInitialExtend: TcxMaskEdit; edtNextExtend: TcxMaskEdit; edtMinExtents: TcxMaskEdit; edtMaxExtents: TcxMaskEdit; edtPctIncrease: TcxMaskEdit; edtFreeList: TcxMaskEdit; edtFreeGroup: TcxMaskEdit; cbBufferPool: TcxImageComboBox; gbStorage: TcxGroupBox; Label7: TLabel; Label8: TLabel; Label9: TLabel; Label10: TLabel; Label15: TLabel; edtPercentFree: TcxMaskEdit; edtPercentUsed: TcxMaskEdit; edtInitialTrans: TcxMaskEdit; edtMaxTrans: TcxMaskEdit; lcTablespace: TcxLookupComboBox; rgCache: TcxRadioGroup; rgLogging: TcxRadioGroup; cxGroupBox7: TcxGroupBox; btnExecute: TcxButton; btnCancel: TcxButton; procedure btnCancelClick(Sender: TObject); procedure pcPageChanging(Sender: TObject; NewPage: TcxTabSheet; var AllowChange: Boolean); procedure btnExecuteClick(Sender: TObject); procedure btnTestSQLClick(Sender: TObject); procedure cboxPropertiesChange(Sender: TObject); private { Private declarations } FMaterializedView: TMaterializedView; procedure SetProperties; function SetViewDetail: boolean; public { Public declarations } function Init(AMaterializedView : TMaterializedView): boolean; end; var MaterializedViewDetailFrm: TMaterializedViewDetailFrm; implementation uses Util, frmSchemaBrowser, oraStorage, VisualOptions; {$R *.dfm} function TMaterializedViewDetailFrm.Init(AMaterializedView : TMaterializedView): boolean; begin MaterializedViewDetailFrm := TMaterializedViewDetailFrm.Create(Application); Self := MaterializedViewDetailFrm; DMGenel.ChangeLanguage(self); ChangeVisualGUI(self); FMaterializedView := TMaterializedView.Create; FMaterializedView := AMaterializedView; dmGenel.ReLoad(FMaterializedView.OraSession); lcViewSchema.Text := FMaterializedView.OWNER; SetProperties; pc.ActivePage := tsView; ShowModal; result := ModalResult = mrOk; Free; end; procedure TMaterializedViewDetailFrm.btnCancelClick(Sender: TObject); begin close; end; procedure TMaterializedViewDetailFrm.SetProperties; begin gbStorage.Enabled := not chkPrebuiltOption.Checked; gbStorageClause.Enabled := not chkPrebuiltOption.Checked; rgCache.Enabled := not chkPrebuiltOption.Checked; rgLogging.Enabled := not chkPrebuiltOption.Checked; cbWhen.Enabled := cboxMethod.ItemIndex <> 3; chkStartOn.Enabled := cboxMethod.ItemIndex <> 3; tedtOnThisTime.Enabled := (cboxMethod.ItemIndex <> 3) and (chkStartOn.Checked); dedtOnThisDate.Enabled := (cboxMethod.ItemIndex <> 3) and (chkStartOn.Checked); chkNext.Enabled := cboxMethod.ItemIndex <> 3; tedtOnNextTime.Enabled := (cboxMethod.ItemIndex <> 3) and (chkNext.Checked); dedtOnNextDate.Enabled := (cboxMethod.ItemIndex <> 3) and (chkNext.Checked); cbType.Enabled := cboxMethod.ItemIndex <> 3; chkUseRollbackSegment.Enabled := cboxMethod.ItemIndex <> 3; rgLocation.Enabled := cboxMethod.ItemIndex <> 3; cboxPrebuiltOption.Enabled := chkPrebuiltOption.Checked; lcbUsingIndex.Enabled := chkUsingIndex.Checked; edtRollbackSegmentName.Enabled := (not chkUseRollbackSegment.Checked) and (cboxMethod.ItemIndex <> 3); edtParalelDegree.Enabled := chkParalel.Checked; end; procedure TMaterializedViewDetailFrm.cboxPropertiesChange( Sender: TObject); begin SetProperties; end; function TMaterializedViewDetailFrm.SetViewDetail: boolean; begin result := true; if edtViewName.Text = '' then begin MessageDlg('MaterializedView Name must be specified', mtWarning, [mbOk], 0); result := false; exit; end; if lcViewSchema.Text = '' then begin MessageDlg('Schema Name must be specified', mtWarning, [mbOk], 0); result := false; exit; end; if edtSQLQuery.Text = '' then begin MessageDlg('SQL Query must be specified', mtWarning, [mbOk], 0); result := false; exit; end; with FMaterializedView do begin OWNER := lcViewSchema.Text; NAME := edtViewName.Text; SQL_QUERY := edtSQLQuery.Text; MODE := TMVRefreshMode(cboxMethod.ItemIndex); WHEN := TMVWhenMethods(cbWhen.ItemIndex); START_TIME := ''; START_DATE := ''; if chkStartOn.Checked then begin START_TIME := tedtOnThisTime.Text; START_DATE := dedtOnThisDate.Text; end; NEXT_TIME := ''; NEXT_DATE := ''; if chkNext.Checked then begin NEXT_TIME := tedtOnNextTime.Text; NEXT_DATE := dedtOnNextDate.Text; end; REFRESH_TYPE := TMVRefreshType(cbType.ItemIndex); if chkParalel.Checked then PARALLEL := edtParalelDegree.Text else PARALLEL := '0'; ALLOW_UPDATES := chkAllowUpdates.Checked; if chkPrebuiltOption.Checked then PREBUILT_OPTION := cboxPrebuiltOption.Text else PREBUILT_OPTION := ''; ENABLE_ROW_MOVEMENT := chkEnableRowMovement.Checked; ENABLE_QUERY_REWRITE := chkEnableQueryRewrite.Checked; COMPRESS := chkCompress.Checked; BUILT_TYPE := TMVBuiltType(cbBuiltType.ItemIndex); if chkUsingIndex.Checked then INDEX_TABLESPACE := lcbUsingIndex.Text else INDEX_TABLESPACE := ''; USE_DEFAULT_ROLLBACK_SEGMENT := chkUseRollbackSegment.Checked; ROLLBACK_SEGMENT_LOCATION := TMVSegmentLocation(rgLocation.ItemIndex); if chkUseRollbackSegment.Checked then ROLLBACK_SEGMENT_NAME := '' else ROLLBACK_SEGMENT_NAME := edtRollbackSegmentName.Text; CACHE := rgCache.ItemIndex = 0; LOGGING := TLoggingType(rgLogging.ItemIndex); with PhsicalAttributes do begin PercentFree:= edtPercentFree.Text; PercentUsed:= edtPercentUsed.Text; InitialTrans:= edtInitialTrans.Text; MaxTrans:= edtMaxTrans.Text; Tablespace:= lcTablespace.Text; InitialExtent:=edtInitialExtend.Text; NextExtent:= edtNextExtend.Text; MinExtent:= edtMinExtents.Text; MaxExtent:= edtMaxExtents.Text; PctIncrease:= edtPctIncrease.Text; BufferPool:= TBufferPool(cbBufferPool.ItemIndex); FreeLists:= edtFreeList.Text; FreeGroups:= edtFreeGroup.Text; end; end; //with end; procedure TMaterializedViewDetailFrm.pcPageChanging(Sender: TObject; NewPage: TcxTabSheet; var AllowChange: Boolean); begin if NewPage = tsDDL then begin if not SetViewDetail then AllowChange := false else redtDDL.Text := FMaterializedView.GetDDL; CodeColors(self, 'Default', redtDDL, false); end; end; procedure TMaterializedViewDetailFrm.btnExecuteClick(Sender: TObject); begin if not SetViewDetail then exit; redtDDL.Text := FMaterializedView.GetDDL; if FMaterializedView.CreateView(redtDDL.Text) then ModalResult := mrOK; end; procedure TMaterializedViewDetailFrm.btnTestSQLClick(Sender: TObject); begin if edtSQLQuery.Text = '' then begin MessageDlg('Enter a query first.', mtWarning, [mbOk], 0); exit; end; if not ExpectResultSet(edtSQLQuery.Text) then begin MessageDlg('Syntax error in query.', mtWarning, [mbOk], 0); exit; end; FMaterializedView.ValidateQuery(edtSQLQuery.Text); end; end.
unit GuiHelpers_DB; interface uses typex, systemx, stringx, classes, controls, storageenginetypes, extctrls, stdctrls, variants, vcl.comctrls; procedure SyncRowSetTocomboBox(rs: TSERowSet; cb: TComboBox; sField: string); procedure SyncRowSetToListView(rs: TSERowSet; lv: TListView); procedure SyncRowSetToListViewFilterColumns(rs: TSERowSet; lv: TListView); implementation uses guihelpers, sysutils; procedure SyncRowSetTocomboBox(rs: TSERowSet; cb: TComboBox; sField: string); begin cb.Items.BeginUpdate; try cb.Items.Clear; rs.First; while not rs.EOF do begin cb.Items.Add(vartostr(rs[sfield])); rs.Next; end; finally cb.Items.EndUpdate; end; end; procedure SyncRowSetToListViewFilterColumns(rs: TSERowSet; lv: TListView); var t: ni; cx: ni; idx: ni; v: variant; ci: ni; begin cx := rs.rowcount; idx := 0; lv.items.BeginUpdate; try SyncListView(lv, rs.rowcount, lv.Columns.count); while cx > 0 do begin lv.items[idx].Caption := inttostr(idx); for t:= 0 to rs.fieldcount-1 do begin ci := IndexOfListColumn(lv, rs.FieldDefs[t].sName)-1; if ci >=0 then begin v := rs.Values[t,idx]; lv.Items[idx].SubItems[ci] := vartostrex(v); end; end; dec(cx); inc(idx); end; finally lv.items.EndUpdate; end; end; procedure SyncRowSetToListView(rs: TSERowSet; lv: TListView); var t: ni; cx: ni; idx: ni; v: variant; begin cx := rs.rowcount; idx := 0; lv.items.BeginUpdate; try SyncListView(lv, rs.rowcount, rs.FieldCount); while cx > 0 do begin lv.items[idx].Caption := inttostr(idx); for t:= 0 to rs.fieldcount-1 do begin v := rs.Values[t,idx]; lv.Items[idx].SubItems[t] := vartostrex(v); if idx = 0 then lv.columns[t+1].Caption := rs.fields[t].sName; end; dec(cx); inc(idx); end; finally lv.items.EndUpdate; end; end; end.
unit VSMRestClientParamHeaderDto; interface type TVSMRestClientParamHeaderDto = class private FValor: String; FNome: String; procedure SetNome(const Value: String); procedure SetValor(const Value: String); public constructor create(nome, valor: string); published property nome: String read FNome write SetNome; property valor: String read FValor write SetValor; end; implementation { TVSMRestClientParamHeaderDto } constructor TVSMRestClientParamHeaderDto.create(nome, valor: string); begin Self.nome := nome; Self.valor := valor; end; procedure TVSMRestClientParamHeaderDto.SetNome(const Value: String); begin FNome := Value; end; procedure TVSMRestClientParamHeaderDto.SetValor(const Value: String); begin FValor := Value; end; end.
unit vcmTabbedContainerFormDispatcherUtils; // Модуль: "w:\common\components\gui\Garant\VCM\implementation\Visual\ChromeLike\vcmTabbedContainerFormDispatcherUtils.pas" // Стереотип: "UtilityPack" // Элемент модели: "vcmTabbedContainerFormDispatcherUtils" MUID: (558163840015) {$Include w:\common\components\gui\Garant\VCM\vcmDefine.inc} interface {$If NOT Defined(NoVCM) AND NOT Defined(NoVGScene) AND NOT Defined(NoTabs)} uses l3IntfUses , vcmTabbedContainerForm , l3ProtoDataContainer , l3Memory , l3Types , l3Interfaces , l3Core , l3Except , Classes ; type TvcmContainerLockCountItem = {$IfDef XE4}record{$Else}object{$EndIf} public rContainer: TvcmTabbedContainerForm; rLockCount: Integer; public function EQ(const anOther: TvcmContainerLockCountItem): Boolean; end;//TvcmContainerLockCountItem _ItemType_ = TvcmContainerLockCountItem; _l3RecordWithEQList_Parent_ = Tl3ProtoDataContainer; {$Define l3Items_IsProto} {$Include w:\common\components\rtl\Garant\L3\l3RecordWithEQList.imp.pas} TvcmContainersLockCountList = class(_l3RecordWithEQList_) private procedure ChangeLockCount(aContainer: TvcmTabbedContainerForm; aDelta: Integer); public function IsContainerLocked(aContainer: TvcmTabbedContainerForm): Boolean; procedure LockContainer(aContainer: TvcmTabbedContainerForm); procedure UnlockContainer(aContainer: TvcmTabbedContainerForm); end;//TvcmContainersLockCountList function TvcmContainerLockCountItem_C(aContainer: TvcmTabbedContainerForm): TvcmContainerLockCountItem; {$IfEnd} // NOT Defined(NoVCM) AND NOT Defined(NoVGScene) AND NOT Defined(NoTabs) implementation {$If NOT Defined(NoVCM) AND NOT Defined(NoVGScene) AND NOT Defined(NoTabs)} uses l3ImplUses , l3Base , l3MinMax , RTLConsts , SysUtils //#UC START# *558163840015impl_uses* //#UC END# *558163840015impl_uses* ; function TvcmContainerLockCountItem_C(aContainer: TvcmTabbedContainerForm): TvcmContainerLockCountItem; //#UC START# *55824F260248_55824ED3027A_var* //#UC END# *55824F260248_55824ED3027A_var* begin System.FillChar(Result, SizeOf(Result), 0); //#UC START# *55824F260248_55824ED3027A_impl* Result.rContainer := aContainer; //#UC END# *55824F260248_55824ED3027A_impl* end;//TvcmContainerLockCountItem_C function TvcmContainerLockCountItem.EQ(const anOther: TvcmContainerLockCountItem): Boolean; //#UC START# *55824F0F01C2_55824ED3027A_var* //#UC END# *55824F0F01C2_55824ED3027A_var* begin //#UC START# *55824F0F01C2_55824ED3027A_impl* Result := anOther.rContainer = rContainer; //#UC END# *55824F0F01C2_55824ED3027A_impl* end;//TvcmContainerLockCountItem.EQ function CompareExistingItems(const CI: CompareItemsRec): Integer; forward; {$If Defined(l3Items_NeedsAssignItem) AND NOT Defined(l3Items_NoSort)} procedure AssignItem(const aTo: _ItemType_; const aFrom: _ItemType_); //#UC START# *47B2C42A0163_55815E1A0227_var* //#UC END# *47B2C42A0163_55815E1A0227_var* begin //#UC START# *47B2C42A0163_55815E1A0227_impl* Assert(False); //#UC END# *47B2C42A0163_55815E1A0227_impl* end;//AssignItem {$IfEnd} // Defined(l3Items_NeedsAssignItem) AND NOT Defined(l3Items_NoSort) function CompareExistingItems(const CI: CompareItemsRec): Integer; {* Сравнивает два существующих элемента. } //#UC START# *47B99D4503A2_55815E1A0227_var* //#UC END# *47B99D4503A2_55815E1A0227_var* begin //#UC START# *47B99D4503A2_55815E1A0227_impl* Result := -1; //#UC END# *47B99D4503A2_55815E1A0227_impl* end;//CompareExistingItems type _Instance_R_ = TvcmContainersLockCountList; {$Include w:\common\components\rtl\Garant\L3\l3RecordWithEQList.imp.pas} function TvcmContainersLockCountList.IsContainerLocked(aContainer: TvcmTabbedContainerForm): Boolean; //#UC START# *5582543B0147_55815E1A0227_var* var l_Item: TvcmContainerLockCountItem; l_Index: Integer; //#UC END# *5582543B0147_55815E1A0227_var* begin //#UC START# *5582543B0147_55815E1A0227_impl* l_Item := TvcmContainerLockCountItem_C(aContainer); l_Index := IndexOf(l_Item); Result := (l_Index <> -1) and (Items[l_Index].rLockCount > 0); //#UC END# *5582543B0147_55815E1A0227_impl* end;//TvcmContainersLockCountList.IsContainerLocked procedure TvcmContainersLockCountList.LockContainer(aContainer: TvcmTabbedContainerForm); //#UC START# *558254440303_55815E1A0227_var* //#UC END# *558254440303_55815E1A0227_var* begin //#UC START# *558254440303_55815E1A0227_impl* ChangeLockCount(aContainer, 1); //#UC END# *558254440303_55815E1A0227_impl* end;//TvcmContainersLockCountList.LockContainer procedure TvcmContainersLockCountList.UnlockContainer(aContainer: TvcmTabbedContainerForm); //#UC START# *558254500372_55815E1A0227_var* //#UC END# *558254500372_55815E1A0227_var* begin //#UC START# *558254500372_55815E1A0227_impl* ChangeLockCount(aContainer, -1); //#UC END# *558254500372_55815E1A0227_impl* end;//TvcmContainersLockCountList.UnlockContainer procedure TvcmContainersLockCountList.ChangeLockCount(aContainer: TvcmTabbedContainerForm; aDelta: Integer); //#UC START# *558259BC02E8_55815E1A0227_var* var l_Index: Integer; l_Item: TvcmContainerLockCountItem; //#UC END# *558259BC02E8_55815E1A0227_var* begin //#UC START# *558259BC02E8_55815E1A0227_impl* l_Item := TvcmContainerLockCountItem_C(aContainer); l_Index := IndexOf(l_Item); if (l_Index <> -1) then begin if ((Items[l_Index].rLockCount + aDelta) = 0) then Delete(l_Index) else begin l_Item.rLockCount := Items[l_Index].rLockCount + aDelta; Items[l_Index] := l_Item; end; end else if (aDelta > 0) then begin Inc(l_Item.rLockCount, aDelta); Add(l_Item); end; //#UC END# *558259BC02E8_55815E1A0227_impl* end;//TvcmContainersLockCountList.ChangeLockCount {$IfEnd} // NOT Defined(NoVCM) AND NOT Defined(NoVGScene) AND NOT Defined(NoTabs) end.
unit ObjdsDemoForm; interface uses MdDsList, MdDsCustom, TypInfo, DB, Classes, SysUtils; type TMdObjDataSet = class(TMdListDataSet) private PropList: PPropList; nProps: Integer; FObjClass: TPersistentClass; ObjClone: TPersistent; FChangeToClone: Boolean; procedure SetObjClass(const Value: TPersistentClass); function GetObjects(I: Integer): TPersistent; procedure SetChangeToClone(const Value: Boolean); protected procedure InternalInitFieldDefs; override; procedure InternalClose; override; procedure InternalInsert; override; procedure InternalPost; override; procedure InternalCancel; override; procedure InternalEdit; override; procedure SetFieldData(Field: TField; Buffer: Pointer); override; function GetCanModify: Boolean; override; procedure InternalPreOpen; override; public function GetFieldData(Field: TField; Buffer: Pointer): Boolean; override; property Objects [I: Integer]: TPersistent read GetObjects; function Add: TPersistent; published property ObjClass: TPersistentClass read FObjClass write SetObjClass; property ChangesToClone: Boolean read FChangeToClone write SetChangeToClone default False; end; procedure DoClone (SourceObj: TPersistent; TargetObj: TPersistent); forward; procedure Register; implementation uses Dialogs, Windows, Forms, Controls; procedure Register; begin RegisterComponents ('Md', [TMdObjDataSet]); end; // generic object cloning (RTTI-based) procedure DoClone (SourceObj: TPersistent; TargetObj: TPersistent); var nProps, i: Integer; PropList: PPropList; Value: Variant; begin // get list of properties nProps := GetTypeData(SourceObj.ClassInfo)^.PropCount; GetMem(PropList, nProps * SizeOf(Pointer)); GetPropInfos (SourceObj.ClassInfo, PropList); // shortcut: use varaints... (must fix this) for i := 0 to nProps - 1 do begin Value := GetPropValue (SourceObj, PropList [i].Name); SetPropValue (TargetObj, PropList [i].Name, Value); end; FreeMem (PropList); end; //////////////////////// // File Handling Support procedure TMdObjDataSet.InternalInitFieldDefs; var i: Integer; begin if FObjClass = nil then raise Exception.Create ('TMdObjDataSet: Unassigned class'); // field definitions FieldDefs.Clear; nProps := GetTypeData(fObjClass.ClassInfo)^.PropCount; GetMem(PropList, nProps * SizeOf(Pointer)); GetPropInfos (fObjClass.ClassInfo, PropList); for i := 0 to nProps - 1 do case PropList [i].PropType^.Kind of tkInteger, tkEnumeration, tkSet: FieldDefs.Add (PropList [i].Name, ftInteger, 0); tkChar: FieldDefs.Add (PropList [i].Name, ftFixedChar, 0); tkFloat: FieldDefs.Add (PropList [i].Name, ftFloat, 0); tkString, tkLString: FieldDefs.Add (PropList [i].Name, ftString, 50); // TODO: fix size // tkClass, tkMethod, tkWChar tkWString: FieldDefs.Add (PropList [i].Name, ftWideString, 50); // TODO: fix size // tkVariant, tkArray, tkRecord, tkInterface, tkInt64, tkDynArray end; end; procedure TMdObjDataSet.InternalPost; begin if FChangeToClone and Assigned (ObjClone) then DoClone (ObjClone, TPersistent (fList [fCurrentRecord])); end; procedure TMdObjDataSet.InternalCancel; begin if not FChangeToClone and Assigned (ObjClone) then DoClone (ObjClone, TPersistent(fList [fCurrentRecord])); end; function TMdObjDataSet.GetFieldData ( Field: TField; Buffer: Pointer): Boolean; var Obj: TPersistent; TypeInfo: PTypeInfo; IntValue: Integer; FlValue: Double; begin if FList.Count = 0 then begin Result := False; exit; end; if FChangeToClone and Assigned (ObjClone) and (State = dsEdit) and (PInteger(ActiveBuffer)^ = fCurrentRecord) then Obj:= ObjClone else Obj := fList [PInteger(ActiveBuffer)^] as TPersistent; TypeInfo := PropList [Field.FieldNo-1]^.PropType^; case TypeInfo.Kind of tkInteger, tkChar, tkWChar, tkClass, tkEnumeration, tkSet: begin IntValue := GetOrdProp(Obj, PropList [Field.FieldNo-1]); Move (IntValue, Buffer^, sizeof (Integer)); end; tkFloat: begin FlValue := GetFloatProp(Obj, PropList [Field.FieldNo-1]); Move (FlValue, Buffer^, sizeof (Double)); end; tkString, tkLString, tkWString: StrCopy (Buffer, pchar(GetStrProp(Obj, PropList [Field.FieldNo-1]))); end; Result := True; end; // III: Move data from field to record buffer procedure TMdObjDataSet.SetFieldData(Field: TField; Buffer: Pointer); var Obj: TPersistent; TypeInfo: PTypeInfo; IntValue: Integer; FlValue: Double; begin if FList.Count = 0 then Exit; if FChangeToClone and Assigned (ObjClone) then Obj:= ObjClone else Obj := fList [PInteger(ActiveBuffer)^] as TPersistent; TypeInfo := PropList [Field.FieldNo-1]^.PropType^; case TypeInfo.Kind of tkInteger, tkChar, tkWChar, tkClass, tkEnumeration, tkSet: begin Move (Buffer^, IntValue, sizeof (Integer)); SetOrdProp(Obj, PropList [Field.FieldNo-1], IntValue); end; tkFloat: begin Move (Buffer^, FlValue, sizeof (Double)); SetFloatProp(Obj, PropList [Field.FieldNo-1], FlValue); end; tkString, tkLString, tkWString: SetStrProp(Obj, PropList [Field.FieldNo-1], pchar(Buffer)); end; SetModified (True); end; procedure TMdObjDataSet.InternalInsert; begin // insert at the end only (Why reverse? Clears the buffers!) Add; Last; // TODO: add clone object support end; procedure TMdObjDataSet.InternalEdit; begin DoClone (fList [FCurrentRecord] as TPersistent, ObjClone); end; function TMdObjDataSet.GetCanModify: Boolean; begin Result := True; // read-write end; procedure TMdObjDataSet.SetObjClass(const Value: TPersistentClass); begin FObjClass := Value; end; function TMdObjDataSet.GetObjects(i: Integer): TPersistent; begin if i < fList.Count then Result := fList [i] as TPersistent else Result := nil; // or raise exception end; function TMdObjDataSet.Add: TPersistent; begin if not Active then Open; Result := fObjClass.Create; fList.Add (Result); end; procedure TMdObjDataSet.InternalPreOpen; begin inherited; ObjClone := FObjClass.Create; end; procedure TMdObjDataSet.InternalClose; begin inherited; ObjClone.Free; ObjClone := nil; end; procedure TMdObjDataSet.SetChangeToClone(const Value: Boolean); begin if not Active then FChangeToClone := Value else raise Exception.Create ('Cannot change style for an open dataset'); end; end.
unit udmAtualizacoes; interface uses Windows, System.UITypes,Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, udmPadrao, IBC, DB, MemDS, DBAccess; type TdmAtualizacoes = class(TdmPadrao) qryManutencaoID: TIntegerField; qryManutencaoNOME: TStringField; qryManutencaoVERSAO: TIntegerField; qryManutencaoARQUIVO: TBlobField; qryLocalizacaoID: TIntegerField; qryLocalizacaoNOME: TStringField; qryLocalizacaoVERSAO: TIntegerField; qryLocalizacaoARQUIVO: TBlobField; private FID: Integer; FNome: string; procedure MontaSQLBusca(DataSet: TDataSet = nil); override; procedure MontaSQLRefresh; override; public property ID: Integer read FID write FID; property Nome: string read FNome write FNome; function LocalizarNome(DataSet: TDataSet = nil): Boolean; end; const SQL_DEFAULT = ' SELECT * FROM ATUALIZACOES'; var dmAtualizacoes: TdmAtualizacoes; implementation {$R *.dfm} { TdmAtualizacoes } function TdmAtualizacoes.LocalizarNome(DataSet: TDataSet): Boolean; begin if DataSet = nil then DataSet := qryLocalizacao; with (DataSet as TIBCQuery) do begin Close; SQL.Clear; SQL.Add(SQL_DEFAULT); Open; Result := not IsEmpty; end; end; procedure TdmAtualizacoes.MontaSQLBusca(DataSet: TDataSet); begin inherited; with (DataSet as TIBCQuery) do begin SQL.Clear; SQL.Add(SQL_DEFAULT); SQL.Add('WHERE UPPER(NOME) = UPPER(:NOME)'); Params[0].AsString := FNome; end; end; procedure TdmAtualizacoes.MontaSQLRefresh; begin inherited; with qryManutencao do begin SQL.Clear; SQL.Add(SQL_DEFAULT); end; end; end.
unit UDssAbout; { Copyright 2012 Document Storage Systems, Inc.      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. } interface uses Windows, SysUtils, Classes, Graphics, Forms, Controls, StdCtrls, ExtCtrls, Dialogs, jpeg; type PVerTranslation = ^TVerTranslation; TVerTranslation = record Language : Word; CharSet : Word; end; type TDSSAboutDlg = class(TForm) Panel1: TPanel; lblCopyright: TLabel; lblCompany: TLabel; btnOk: TButton; Bevel1: TBevel; Memo1: TMemo; lblWebAddress: TLabel; lblCNTVersion: TLabel; Image1: TImage; procedure FormShow(Sender: TObject); procedure lblWebAddressClick(Sender: TObject); private public end; var DSSAboutDlg: TDSSAboutDlg; function FileVersionGet(const sgFileName: string) : string; implementation {$R *.DFM} uses shellAPI, DateUtils; function FileVersionGet(const sgFileName: string) : string; var infoSize: DWORD; verBuf: pointer; verSize: UINT; wnd: UINT; FixedFileInfo : PVSFixedFileInfo; begin infoSize := GetFileVersioninfoSize(PChar(sgFileName), wnd); result := ''; if infoSize <> 0 then begin GetMem(verBuf, infoSize); try if GetFileVersionInfo(PChar(sgFileName), wnd, infoSize, verBuf) then begin VerQueryValue(verBuf, '\', Pointer(FixedFileInfo), verSize); result := IntToStr(FixedFileInfo.dwFileVersionMS div $10000) + '.' + IntToStr(FixedFileInfo.dwFileVersionMS and $0FFFF) + '.' + IntToStr(FixedFileInfo.dwFileVersionLS div $10000) + '.' + IntToStr(FixedFileInfo.dwFileVersionLS and $0FFFF); end; finally FreeMem(verBuf); end; end; end; procedure TDSSAboutDlg.FormShow(Sender: TObject); var Memstat: TMemoryStatus; MyVerInfo: TOSVersionInfo; OSystem: string; sInternalName : string; ret: string; begin //ProgramIcon.Picture.Assign(Application.Icon); // Version info MyVerInfo.dwOSVersionInfoSize :=SizeOf(TOSVersionInfo); GetVersionEx(MyVerInfo); // Memory Info Memstat.dwLength := SizeOf(TMemoryStatus); GlobalMemoryStatus(MemStat); // Text lblCompany.Caption := 'Patient Search Tool'; //lblAppName.Caption := '';//'Patient Search Tool'; ret := FileVersionGet('DSSPatientRecordSearch.dll'); lblCNTVersion.Caption := 'Version: ' + ret; lblCopyright.Caption := 'Copyright ' + chr(169) + ' 2011-'+ IntToStr(YearOf(Now)) + ', DSS Inc.'; OSystem := OSystem + ' ' + InttoStr(MyVerInfo.dwmajorVersion) + '.' + InttoStr(MyVerInfo.dwminorVersion) + ' build(' + InttoStr(MyVerInfo.dwBuildNumber) + ')'; //labelOS.Caption := OSystem; //labelMemory.Caption := 'Memory Available: ' + IntToStr(Round(MemStat.dwTotalPhys/1024)) + ' KB'; end; procedure TDSSAboutDlg.lblWebAddressClick(Sender: TObject); var TempString : array[0..79] of char; begin StrPCopy(TempString,lblWebAddress.Caption); ShellExecute(0, Nil, TempString, Nil, Nil, SW_NORMAL); end; end.
{ Subroutine SST_W_C_ASSIGN (V, EXP) * * Write a complete assignment statement. This may actually expand out into * several statements. The assignment variable is specified by VAR. * EXP is the descriptor for the assignment value expression. } module sst_w_c_ASSIGN; define sst_w_c_assign; %include 'sst_w_c.ins.pas'; procedure sst_w_c_assign ( {write complete assignment statement} in v: sst_var_t; {descriptor for variable to assign to} in exp: sst_exp_t); {descriptor for assignment value expression} var dt_p, dt2_p: sst_dtype_p_t; {scratch pointers to data type descriptors} dtp_p: sst_dtype_p_t; {pointer to pointed-to data type} i: sys_int_machine_t; {scratch integer} acnt: sys_int_machine_t; {number of times to take address of expression} token: string_var32_t; {for number conversion} type_cast: boolean; {TRUE if need to type-cast expression} armode: array_k_t; {array symbol interpret mode for expression} label cast, normal; begin token.max := sizeof(token.str); {init local var string} type_cast := false; {init to don't explicitly type-cast exp} armode := array_pnt_first_k; {init to how C views array symbols} dt_p := v.dtype_p; {resolve base data type of variable} while dt_p^.dtype = sst_dtype_copy_k do dt_p := dt_p^.copy_dtype_p; if dt_p^.dtype = sst_dtype_array_k then begin { * The data type of the assignment variable is ARRAY. The C language * can not handle array assignments with an assignment statement. * We will call an intrinsic function that copies memory. The form is: * * memcpy (V, EXP, SIZE); * * where V is the assignement array variable, EXP is the assignment expression, * and SIZE is the number of memory units to copy. If the arrays are strings, * then the end of V must be cleared to blanks when EXP is smaller than V. * This is done with the statement: * * memset (V+START, ' ', N); } sst_w_c_armode_push (array_whole_k); {array identifiers represent whole array} sst_w_c_declare (decl_string_k); {make sure MEMCPY and MEMSET declared} dt2_p := exp.dtype_p; {resolve base data type of expression} while dt2_p^.dtype = sst_dtype_copy_k do dt2_p := dt2_p^.copy_dtype_p; i := min(dt_p^.size_used, dt2_p^.size_used); {number of mem units to copy} if i > 0 then begin {there is something to copy ?} sst_w_c_sment_start; sst_w.appendn^ ('memcpy (', 8); sst_w_c_var (v, 0); sst_w.appendn^ (',', 1); sst_w.delimit^; acnt := 0; {init to pass source expression as is} if dt2_p^.dtype <> sst_dtype_array_k then begin {source not an array ?} acnt := 1; {pass address of source expression} end; sst_w_c_exp (exp, acnt, nil, enclose_no_k); sst_w.appendn^ (',', 1); sst_w.delimit^; string_f_int (token, i); {make number of addresses to copy} sst_w.append^ (token); sst_w.appendn^ (')', 1); sst_w_c_sment_end; end; {done with code to copy the data} if {string, needs padding with blanks ?} (dt_p^.ar_string) and {data type is a string of characters ?} (i < dt_p^.size_used) {not whole string got set ?} then begin sst_w_c_sment_start; sst_w.appendn^ ('memset (', 8); sst_w_c_var (v, 0); if i > 0 then begin sst_w.delimit^; sst_w.appendn^ ('+', 1); sst_w.delimit^; sst_w.append^ (token); end; sst_w.appendn^ (',', 1); sst_w.delimit^; sst_w.appendn^ (''' '',', 4); sst_w.delimit^; string_f_int (token, dt_p^.size_used - i); {number of chars to clear} sst_w.append^ (token); sst_w.appendn^ (')', 1); sst_w_c_sment_end; end; {done handling padding string with blanks} sst_w_c_armode_pop; {restore old array name interpret mode} return; end; {done with data type is ARRAY} { * Check for an assignment of one string pointer to another where the * string lengths differ. The front end allows this. The C compiler also * does, but will issue a warning. In that case explicitly type-cast * the expression to the data type of the assignment variable. } if dt_p^.dtype <> sst_dtype_pnt_k then goto normal; dtp_p := dt_p^.pnt_dtype_p; {resolve base pointed-to data type} if dtp_p = nil then goto normal; {assigning to a NIL pointer ?} while dtp_p^.dtype = sst_dtype_copy_k do dtp_p := dtp_p^.copy_dtype_p; if dtp_p^.dtype <> sst_dtype_array_k then goto normal; if not dtp_p^.ar_string then goto normal; { * The assignment variable is a pointer to a string. * Now check the expression to see whether it is pointing to a different size * string. } dt2_p := exp.dtype_p; {resolve expression's base data type} while dt2_p^.dtype = sst_dtype_copy_k do dt2_p := dt2_p^.copy_dtype_p; if dt2_p^.dtype <> sst_dtype_pnt_k then goto normal; dt2_p := dt2_p^.pnt_dtype_p; {get pointed-to data type} if dt2_p = nil then goto cast; while dt2_p^.dtype = sst_dtype_copy_k do dt2_p := dt2_p^.copy_dtype_p; if dt2_p^.dtype <> sst_dtype_array_k then goto normal; if not dt2_p^.ar_string then goto normal; if dt2_p^.ar_ind_n = dtp_p^.ar_ind_n then goto normal; {string lengths match} cast: {jump here if need to type-cast expression} type_cast := true; normal: {skip to here if not need to type-cast exp} sst_w_c_sment_start; {start a new statement} sst_w_c_armode_push (array_whole_k); {array assign vars are the arrays} sst_w_c_var (v, 0); {write variable being assigned to} sst_w_c_armode_pop; sst_w.delimit^; sst_w.appendn^ ('=', 1); {write assignment operator} sst_w.delimit^; if type_cast then begin {need to write explicit type-cast} token.len := 0; sst_w.appendn^ ('(', 1); sst_w_c_dtype_simple (v.dtype_p^, token, false); {write desired data type} sst_w.appendn^ (')', 1); armode := array_pnt_whole_k; {preven additional automatic type-casting} end; sst_w_c_armode_push (armode); {set array symbol interpretation mode} sst_w_c_exp (exp, 0, nil, enclose_no_k); {write expression for assignment value} sst_w_c_armode_pop; {restore array symbol interpretation mode} sst_w_c_sment_end; {finish this statement} end;
unit GX_ProcedureListOptions; interface uses Types, Classes, Graphics, Controls, Forms, ExtCtrls, StdCtrls, GX_BaseForm; type TProcedureListOptions = class(TObject) private FAlignmentChanged: Boolean; FDialogFont: TFont; FCodeViewFont: TFont; FCodeViewAlignment: TAlign; FBoundsRect: TRect; FSortOnColumn: Integer; FCodeViewVisible: Boolean; FSearchAll: Boolean; FCodeViewWidth, FCodeViewHeight: Integer; FOptions: TProcedureListOptions; FObjectNameVisible: Boolean; FSearchClassName: Boolean; procedure SetBoundsRect(const AValue: TRect); public property AlignmentChanged: Boolean read FAlignmentChanged write FAlignmentChanged; property DialogFont: TFont read FDialogFont write FDialogFont; property CodeViewFont: TFont read FCodeViewFont write FCodeViewFont; property CodeViewAlignment: TAlign read FCodeViewAlignment write FCodeViewAlignment; property CodeViewVisible: Boolean read FCodeViewVisible write FCodeViewVisible; property CodeViewHeight: Integer read FCodeViewHeight write FCodeViewHeight; property CodeViewWidth: Integer read FCodeViewWidth write FCodeViewWidth; property BoundsRect: TRect read FBoundsRect write SetBoundsRect; property SortOnColumn: Integer read FSortOnColumn write FSortOnColumn; property SearchAll: Boolean read FSearchAll write FSearchAll; property SearchClassName: Boolean read FSearchClassName write FSearchClassName; property Options: TProcedureListOptions read FOptions write FOptions; property ObjectNameVisible: Boolean read FObjectNameVisible write FObjectNameVisible; procedure LoadSettings(const ConfigurationKey: string); procedure SaveSettings(const ConfigurationKey: string); constructor Create; destructor Destroy; override; end; TfmProcedureListOptions = class(TfmBaseForm) btnOK: TButton; btnCancel: TButton; gbCodeView: TGroupBox; cbCVDock: TComboBox; lblDock: TLabel; pnlCVFont: TPanel; btnChangeCodeViewFont: TButton; gbDialog: TGroupBox; pnlDialogFont: TPanel; btnChgDialogFont: TButton; chkShowCodeView: TCheckBox; chkShowObjectName: TCheckBox; chkMatchAnywhere: TCheckBox; chkMatchClass: TCheckBox; procedure btnChgDialogFontClick(Sender: TObject); procedure btnChangeCodeViewFontClick(Sender: TObject); procedure cbCVDockChange(Sender: TObject); procedure FormShow(Sender: TObject); procedure btnOKClick(Sender: TObject); private FOptions: TProcedureListOptions; procedure SetCodeViewAlignment(Value: TAlign); function GetCodeViewAlignment: TAlign; public property Options: TProcedureListOptions read FOptions write FOptions; end; implementation {$R *.dfm} uses SysUtils, Dialogs, GX_ConfigurationInfo, GX_GenericUtils; const CodeViewFontKey = 'CodeViewFont'; DialogFontKey = 'DialogFont'; constructor TProcedureListOptions.Create; begin FDialogFont := TFont.Create; FCodeViewFont := TFont.Create; FCodeViewFont.Name := 'Courier New'; FCodeViewFont.Size := 8; AlignmentChanged := False; ObjectNameVisible := True; SortOnColumn := 1; end; destructor TProcedureListOptions.Destroy; begin FreeAndNil(FDialogFont); FreeAndNil(FCodeViewFont); inherited; end; procedure TProcedureListOptions.LoadSettings(const ConfigurationKey: string); function GetCodeViewAlignment(Value: string): TAlign; begin if Value = 'Top' then Result := alTop else if Value = 'Right' then Result := alRight else if Value = 'Left' then Result := alLeft else Result := alBottom; end; var Settings: TGExpertsSettings; ExpSettings: TExpertSettings; begin // Do not localize any of the following lines ExpSettings := nil; Settings := TGExpertsSettings.Create(ConfigInfo.GExpertsIdeRootRegistryKey); try ExpSettings := Settings.CreateExpertSettings(ConfigurationKey); FBoundsRect := ExpSettings.ReadBounds(Bounds(317, 279, 550, 500)); FCodeViewVisible := ExpSettings.ReadBool('ShowProcedureBody', False); FCodeViewWidth := ExpSettings.ReadInteger('ProcedureWidth', 292); FCodeViewHeight := ExpSettings.ReadInteger('ProcedureHeight', 100); FCodeViewAlignment := GetCodeViewAlignment(ExpSettings.ReadString('ProcedureAlignment', 'Right')); FAlignmentChanged := ExpSettings.ReadBool('AlignmentChanged', False); FSortOnColumn := ExpSettings.ReadInteger('SortColumn', FSortOnColumn); ExpSettings.LoadFont(DialogFontKey, FDialogFont); ExpSettings.LoadFont(CodeViewFontKey, FCodeViewFont); FSearchAll := ExpSettings.ReadBool('SearchAll', True); FSearchClassName := ExpSettings.ReadBool('SearchClassName', True); FObjectNameVisible := ExpSettings.ReadBool('ShowObjectName', True); finally FreeAndNil(ExpSettings); FreeAndNil(Settings); end; end; procedure TProcedureListOptions.SaveSettings(const ConfigurationKey: string); function GetAlignmentString(Value: TAlign): string; begin case Value of alTop: Result := 'Top'; alLeft: Result := 'Left'; alRight: Result := 'Right'; alBottom: Result := 'Bottom'; else Result := 'Right'; end; end; var GxSettings: TGExpertsSettings; Settings: TExpertSettings; begin // Do not localize any of the following lines Settings := nil; GxSettings := TGExpertsSettings.Create(ConfigInfo.GExpertsIdeRootRegistryKey); try Settings := GxSettings.CreateExpertSettings(ConfigurationKey); Settings.WriteBool('SearchAll', FSearchAll); Settings.WriteBool('SearchClassName', FSearchClassName); Settings.WriteBounds(BoundsRect); Settings.WriteInteger('SortColumn', FSortOnColumn); Settings.WriteInteger('ProcedureWidth', FCodeViewWidth); Settings.WriteInteger('ProcedureHeight', FCodeViewHeight); Settings.WriteString('ProcedureAlignment', GetAlignmentString(FCodeViewAlignment)); Settings.SaveFont(DialogFontKey, FDialogFont); Settings.SaveFont(CodeViewFontKey, FCodeViewFont); Settings.WriteBool('ShowProcedureBody', FCodeViewVisible); Settings.WriteBool('AlignmentChanged', FAlignmentChanged); Settings.WriteBool('ShowObjectName', FObjectNameVisible); finally FreeAndNil(Settings); FreeAndNil(GxSettings); end; end; procedure TProcedureListOptions.SetBoundsRect(const AValue: TRect); begin FBoundsRect := AValue; end; procedure TfmProcedureListOptions.btnChgDialogFontClick(Sender: TObject); begin with TFontDialog.Create(nil) do try Font.Assign(pnlDialogFont.Font); if Execute then pnlDialogFont.Font.Assign(Font); finally Free; end; end; procedure TfmProcedureListOptions.btnChangeCodeViewFontClick(Sender: TObject); begin with TFontDialog.Create(nil) do try Options := Options + [fdFixedPitchOnly]; // Only show fixed font for source code Font.Assign(pnlCVFont.Font); if Execute then pnlCVFont.Font.Assign(Font); finally Free; end; end; function TfmProcedureListOptions.GetCodeViewAlignment: TAlign; var sDock: string; begin sDock := cbCVDock.Items[cbCVDock.ItemIndex]; if sDock = 'Top' then Result := alTop else if sDock = 'Right' then Result := alRight else if sDock = 'Left' then Result := alLeft else Result := alBottom; end; procedure TfmProcedureListOptions.SetCodeViewAlignment(Value: TAlign); begin case Value of alTop: cbCVDock.ItemIndex := cbCVDock.Items.IndexOf('Top'); alLeft: cbCVDock.ItemIndex := cbCVDock.Items.IndexOf('Left'); alRight: cbCVDock.ItemIndex := cbCVDock.Items.IndexOf('Right'); alBottom: cbCVDock.ItemIndex := cbCVDock.Items.IndexOf('Bottom'); else cbCVDock.ItemIndex := cbCVDock.Items.IndexOf('Right'); end; end; procedure TfmProcedureListOptions.cbCVDockChange(Sender: TObject); begin FOptions.AlignmentChanged := True; end; procedure TfmProcedureListOptions.FormShow(Sender: TObject); begin FOptions.AlignmentChanged := False; chkShowCodeView.Checked := FOptions.CodeViewVisible; chkShowObjectName.Checked := FOptions.ObjectNameVisible; SetCodeViewAlignment(FOptions.CodeViewAlignment); pnlDialogFont.Font.Assign(FOptions.DialogFont); pnlCVFont.Font.Assign(FOptions.CodeViewFont); chkMatchAnywhere.Checked := FOptions.SearchAll; chkMatchClass.Checked := FOptions.SearchClassName; end; procedure TfmProcedureListOptions.btnOKClick(Sender: TObject); begin FOptions.CodeViewVisible := chkShowCodeView.Checked; FOptions.ObjectNameVisible := chkShowObjectName.Checked; FOptions.CodeViewAlignment := GetCodeViewAlignment; FOptions.DialogFont.Assign(pnlDialogFont.Font); FOptions.CodeViewFont.Assign(pnlCVFont.Font); FOptions.SearchAll := chkMatchAnywhere.Checked; FOptions.SearchClassName := chkMatchClass.Checked; end; end.
unit UCustomCells; interface uses System.SysUtils, System.Types, System.UITypes, DateUtils, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.TMSNativeUIBaseControl, FMX.TMSNativeUITableView, FMX.TMSNativeUITableViewMail, iOSApi.Foundation, FMX.TMSNativeUITextView, FMX.TMSNativeUILabel, FMX.TMSNativeUIView, FMX.TMSNativeUIButton; type TForm907 = class(TForm) TMSFMXNativeUITableViewMail1: TTMSFMXNativeUITableViewMail; TMSFMXNativeUIView1: TTMSFMXNativeUIView; TMSFMXNativeUILabel1: TTMSFMXNativeUILabel; TMSFMXNativeUILabel2: TTMSFMXNativeUILabel; lblTitle: TTMSFMXNativeUILabel; lblSender: TTMSFMXNativeUILabel; TMSFMXNativeUILabel3: TTMSFMXNativeUILabel; lblDesc: TTMSFMXNativeUITextView; TMSFMXNativeUIButton1: TTMSFMXNativeUIButton; TMSFMXNativeUIView2: TTMSFMXNativeUIView; procedure FormCreate(Sender: TObject); procedure TMSFMXNativeUIButton1Click(Sender: TObject); procedure TMSFMXNativeUITableViewMail1GetItemFilterText(Sender: TObject; ASection, ARow: Integer; var AText: string); procedure TMSFMXNativeUITableViewMail1ItemSelect(Sender: TObject; ASection, ARow: Integer); private activemit: TTMSFMXNativeUITableViewMailItem; { Private declarations } public { Public declarations } end; var Form907: TForm907; implementation {$R *.fmx} procedure TForm907.FormCreate(Sender: TObject); var s: TTMSFMXNativeUITableViewMailSection; mit: TTMSFMXNativeUITableViewMailItem; I: Integer; senderlist: TStringList; titles: TStringList; descriptions: TStringList; str: String; begin if IsIpad then begin TMSFMXNativeUITableViewMail1.DetailView := TMSFMXNativeUIView2; TMSFMXNativeUITableViewMail1.Align := TAlignLayout.alLeft; TMSFMXNativeUITableViewMail1.Width := 320; TMSFMXNativeUIView2.Visible := True; end; senderlist := TStringList.Create; senderlist.Add('Steve Balmer'); senderlist.Add('Tim Cook'); senderlist.Add('Anders Ohlsson'); senderlist.Add('David I'); senderlist.Add('Marco Cantu'); senderlist.Add('John Porter'); titles := TStringList.Create; titles.Add('Take a look at the new Rad Studio XE4 !'); titles.Add('Appointment'); titles.Add('Order confirmation'); titles.Add('New event taking place'); descriptions := TStringList.Create; str := 'RAD Studio is the app development suite for companies who need'+ 'to create true native apps for PCs, tablets, and smartphones and get them to market fast. '+ 'Manage one codebase, one team, and one schedule without sacrificing performance. True native apps give you more '+ 'control, tighter security, and a better user experience.'; descriptions.Add(str); str := 'A remarkably slim design that still makes room for a larger display and a faster chip.'+ ' Ultrafast wireless that doesn’t sacrifice battery life. And all-new headphones designed to s'+ 'ound great and fit comfortably. So much went into this iPhone. So you could get even more out of it.'; descriptions.Add(str); str := 'Mail (also known as Mail.app or Apple Mail) is an email program included with Apple Inc.'+ ' Mac OS X operating system. Originally developed by NeXT as NeXTMail, a part of their NeXTSTEP '+ 'operating system, it was adapted to become OS X Mail application following Apple acquisition of NeXT.'; descriptions.Add(str); str := 'A business model describes the rationale of how an organization creates, delivers, and captures value[1] (economic, social, cultural, or other forms of value).'+ ' The process of business model construction is part of business strategy'; descriptions.Add(str); s := TTMSFMXNativeUITableViewMailSection(TMSFMXNativeUITableViewMail1.Sections.Add); TMSFMXNativeUITableViewMail1.BeginUpdate; for I := 0 to 99 do begin mit := TTMSFMXNativeUITableViewMailItem(s.Items.Add); mit.Date := Incday(Now, -Random(100)); mit.Title := titles[Random(titles.Count)]; mit.Description := descriptions[Random(descriptions.Count)]; mit.Sender := senderlist[Random(senderlist.Count)]; mit.Unread := I < 3; if not isIPad then begin mit.SubDetailView := TMSFMXNativeUIView1; mit.AccessoryType := atTableViewCellAccessoryDisclosureIndicator; end else mit.DetailView := TMSFMXNativeUIView1; end; TMSFMXNativeUITableViewMail1.EndUpdate; senderlist.Free; titles.Free; descriptions.Free; end; procedure TForm907.TMSFMXNativeUIButton1Click(Sender: TObject); begin activemit.Unread := True; TMSFMXNativeUITableViewMail1.HideDetailView; end; procedure TForm907.TMSFMXNativeUITableViewMail1GetItemFilterText( Sender: TObject; ASection, ARow: Integer; var AText: string); var mit: TTMSFMXNativeUITableViewMailItem; begin mit := TMSFMXNativeUITableViewMail1.Sections[ASection].Items[ARow] as TTMSFMXNativeUITableViewMailItem; if Assigned(mit) then AText := mit.Sender + ' ' + mit.Title + ' ' + mit.Description; end; procedure TForm907.TMSFMXNativeUITableViewMail1ItemSelect(Sender: TObject; ASection, ARow: Integer); begin TMSFMXNativeUIButton1.Visible := not TMSFMXNativeUITableViewMail1.IsFiltering; activemit := TMSFMXNativeUITableViewMail1.Sections[ASection].Items[ARow] as TTMSFMXNativeUITableViewMailItem; activemit.Unread := False; lblTitle.Text := activemit.Title; lblSender.Text := activemit.Sender; lblDesc.Text := activemit.Description; end; end.
unit k2TagFilter; { Библиотека "K-2" } { Автор: Люлин А.В. © } { Модуль: k2TagFilter - } { Начат: 14.05.2004 20:28 } { $Id: k2TagFilter.pas,v 1.10 2014/03/27 14:20:07 lulin Exp $ } // $Log: k2TagFilter.pas,v $ // Revision 1.10 2014/03/27 14:20:07 lulin // - переходим от интерфейсов к объектам. // // Revision 1.9 2013/10/18 14:11:33 lulin // - потихоньку избавляемся от использования идентификаторов типов тегов. // // Revision 1.8 2011/07/07 15:43:38 lulin // {RequestLink:271190917}. // // Revision 1.7 2006/04/11 17:55:28 lulin // - оптимизируем при помощи вынесения строк (по следам того как Вован наиграл в фильтрах 20% производительности). // // Revision 1.6 2006/01/30 16:36:34 lulin // - cleanup. // // Revision 1.5 2005/06/22 16:18:33 lulin // - cleanup. // // Revision 1.4 2005/02/01 12:48:04 lulin // - bug fix: на кривой структуре документа падал фильтр, отрезающий блоки - соответственно нельзя было вставить ГК в ГК в качестве комментария. // // Revision 1.3 2004/11/26 08:00:02 lulin // - bug fix: не закрывались пропускаемые параграфы. // // Revision 1.2 2004/10/12 15:30:32 lulin // - bug fix: при вставке из буфера обмена не учитывались блоки и соответственно вставлялись не комментарии (CQ OIT5-10223). // // Revision 1.1 2004/05/14 16:58:51 law // - new units: k2TagTerminator, k2TagFilter. // {$Include k2Define.inc } interface uses l3Types, l3Variant, k2Types, k2TagTerminator, k2Prim, k2Base ; type Tk2TagFilterOpenMode = (k2_tfomOpen, k2_tfomClose, k2_tfomAdd); Tk2TagFilter = class(Tk2TagTerminator) {* Фильтр тегов. } private // property fields f_SkipLevel : Long; f_TagFromSkippedChild : Long; protected // internal fields f_TagSkipLevel : Long; protected // internal methods function NeedTranslateChildToNext: Boolean; virtual; {-} function NeedTranslateChildToNextPrim(anOpenMode : Tk2TagFilterOpenMode): Boolean; virtual; {-} procedure DoCloseStructure(NeedUndo: Boolean); virtual; {-вызывается на закрывающуюся скобку} procedure DoStartTag(TagID: Long); virtual; {-} procedure DoStartChild(TypeID: Tk2Type); virtual; {-} procedure DoAddAtomEx(AtomIndex: Long; const Value: Tk2Variant); virtual; {-} procedure CloseStructure(NeedUndo: Boolean); override; {-} public // public methods procedure StartTag(TagID: Long); override; {-} procedure StartChild(TypeID: Tl3VariantDef); override; {-} procedure AddAtomEx(AtomIndex: Long; const Value: Tk2Variant); override; {-} procedure StartSkipTags; {* - начать пропускать дочерние теги. } procedure IncSkipTags; {-} procedure DecSkipTags; {-} public //public properties property SkipLevel: Long read f_SkipLevel; {* - текущий уровень пропускаемого тега. } end;//Tk2TagFilter {* Пропускает через себя все теги. } implementation uses SysUtils, k2Strings ; // start class Tk2TagFilter procedure Tk2TagFilter.StartTag(TagID: Long); {override;} {-} var l_NeedTranslate : Boolean; begin l_NeedTranslate := (f_TagFromSkippedChild = 0) AND NeedTranslateChildToNextPrim(k2_tfomOpen); inherited; if (f_TagFromSkippedChild = 0) then begin if l_NeedTranslate then begin if (SkipLevel = 0) then begin if (f_TagSkipLevel <> Pred(CurrentStartLevel)) then DoStartTag(TagID) else Inc(f_SkipLevel); end else Inc(f_SkipLevel); end//NeedTranslateChildToNext else Inc(f_TagFromSkippedChild); end//f_TagFromSkippedChild = 0 else Inc(f_TagFromSkippedChild); end; procedure Tk2TagFilter.StartChild(TypeID: Tl3VariantDef); {override;} {-} begin inherited; if (f_TagFromSkippedChild = 0) then begin if (SkipLevel = 0) then begin if (f_TagSkipLevel <> CurrentStartLevel) then DoStartChild(Tk2Type(TypeID)); end else Inc(f_SkipLevel); end//f_TagFromSkippedChild = 0 else Inc(f_TagFromSkippedChild); end; procedure Tk2TagFilter.CloseStructure(NeedUndo: Boolean); {override;} {-вызывается на закрывающуюся скобку} begin if (f_TagFromSkippedChild = 0) then begin if NeedTranslateChildToNextPrim(k2_tfomClose) then begin if (SkipLevel = 0) then begin if (Pred(f_TagSkipLevel) <> CurrentStartLevel) then DoCloseStructure(NeedUndo) else f_TagSkipLevel := 0; // - сбрасываем признак фильтрации end else Dec(f_SkipLevel); //inherited; end;//NeedTranslateChildToNext end//f_TagFromSkippedChild = 0 else Dec(f_TagFromSkippedChild); inherited; end; procedure Tk2TagFilter.AddAtomEx(AtomIndex: Long; const Value: Tk2Variant); {override;} {-} begin if (SkipLevel = 0) AND (f_TagSkipLevel <> CurrentStartLevel) then DoAddAtomEx(AtomIndex, Value); end; procedure Tk2TagFilter.StartSkipTags; {-} begin if (SkipLevel = 0) then f_SkipLevel := 1; end; procedure Tk2TagFilter.IncSkipTags; {-} begin Inc(f_SkipLevel); end; procedure Tk2TagFilter.DecSkipTags; {-} procedure RaiseBadSkipLevel; begin//RaiseBadSkipLevel raise Exception.Create(k2_errBadSkipLevel); end;//RaiseBadSkipLevel begin if (f_SkipLevel = 0) then RaiseBadSkipLevel; Dec(f_SkipLevel); end; function Tk2TagFilter.NeedTranslateChildToNext: Boolean; {-} begin Result := true; end; function Tk2TagFilter.NeedTranslateChildToNextPrim(anOpenMode : Tk2TagFilterOpenMode): Boolean; //virtual; {-} begin Result := NeedTranslateChildToNext; end; procedure Tk2TagFilter.DoCloseStructure(NeedUndo: Boolean); //virtual; {-вызывается на закрывающуюся скобку} begin if (Generator <> nil) then Generator.Finish(NeedUndo); end; procedure Tk2TagFilter.DoStartTag(TagID: Long); //virtual; {-} begin if (Generator <> nil) then Generator.StartTag(TagID); end; procedure Tk2TagFilter.DoStartChild(TypeID: Tk2Type); //virtual; {-} begin if (Generator <> nil) AND NeedTranslateChildToNextPrim(k2_tfomOpen) then Generator.StartChild(TypeID); end; procedure Tk2TagFilter.DoAddAtomEx(AtomIndex: Long; const Value: Tk2Variant); //virtual; {-} begin if (Generator <> nil) AND (f_TagFromSkippedChild = 0) AND NeedTranslateChildToNextPrim(k2_tfomOpen) then Generator.AddAtomEx(AtomIndex, Value); end; end.
// handles reading and writing of the code formatter settings to an ini file or // any other implementation of the IConfigReader and IConfigWriter interface // Original Author: Thomas Mueller (http://www.dummzeuch.de) unit GX_CodeFormatterConfigHandler; {$I GX_CondDefine.inc} interface uses Windows, SysUtils, Classes, IniFiles, GX_CodeFormatterSettings, GX_CodeFormatterTypes; const FORMATTER_CONFIG_PREFIX = 'FormatterSettings-'; type IConfigReader = interface //FI:W523 - we don't need a GUID function ReadBool(const _Name: string; _Default: Boolean): Boolean; function ReadInteger(const _Name: string; _Default: Integer): Integer; function ReadString(const _Name, _Default: string): string; procedure ReadStrings(const _Section: string; const _List: TStrings); end; type IConfigWriter = interface //FI:W523 - we don't need a GUID procedure WriteBool(const _Name: string; _Value: Boolean); procedure WriteInteger(const _Name: string; _Value: Integer); procedure WriteString(const _Name: string; const _Value: string); procedure WriteStrings(const _Section: string; const _List: TStrings); end; type TIniFileWrapper = class(TInterfacedObject, IConfigReader, IConfigWriter) protected FIni: TCustomIniFile; protected // implementation of IConfigReader function ReadBool(const _Name: string; _Default: Boolean): Boolean; function ReadInteger(const _Name: string; _Default: Integer): Integer; function ReadString(const _Name, _Default: string): string; procedure ReadStrings(const _Section: string; const _List: TStrings); protected // implementatio of IConfigWriter procedure WriteBool(const _Name: string; _Value: Boolean); procedure WriteInteger(const _Name: string; _Value: Integer); procedure WriteString(const _Name: string; const _Value: string); procedure WriteStrings(const _Section: string; const _List: TStrings); public constructor Create(_IniFile: TCustomIniFile); end; type TCodeFormatterConfigHandler = class public class procedure WriteSettings(_Writer: IConfigWriter; _Settings: TCodeFormatterSettings); class procedure ReadSettings(_Reader: IConfigReader; _Settings: TCodeFormatterSettings); class procedure ExportToFile(const _Filename: string; _Settings: TCodeFormatterSettings); class procedure ImportFromFile(const _Filename: string; _Settings: TCodeFormatterSettings); class procedure GetDefaultsList(_Defaults: TStrings); class function GetDefaultConfig(const _Name: string; _Settings: TCodeFormatterSettings): Boolean; end; implementation { TIniFileWrapper } constructor TIniFileWrapper.Create(_IniFile: TCustomIniFile); begin inherited Create; FIni := _IniFile; end; function TIniFileWrapper.ReadBool(const _Name: string; _Default: Boolean): Boolean; begin Result := FIni.ReadBool('settings', _Name, _Default) end; function TIniFileWrapper.ReadInteger(const _Name: string; _Default: Integer): Integer; begin Result := FIni.ReadInteger('settings', _Name, _Default) end; function TIniFileWrapper.ReadString(const _Name, _Default: string): string; begin Result := FIni.ReadString('settings', _Name, _Default) end; procedure TIniFileWrapper.ReadStrings(const _Section: string; const _List: TStrings); var Cnt: Integer; i: Integer; s: string; begin _List.Clear; Cnt := FIni.ReadInteger(_Section, 'Count', 0); for i := 0 to Cnt - 1 do begin s := FIni.ReadString(_Section, Format('Item%.4d', [i]), ''); if s <> '' then _List.Add(s); end; end; procedure TIniFileWrapper.WriteBool(const _Name: string; _Value: Boolean); begin FIni.WriteInteger('settings', _Name, Ord(_Value)); end; procedure TIniFileWrapper.WriteInteger(const _Name: string; _Value: Integer); begin FIni.WriteInteger('settings', _Name, _Value); end; procedure TIniFileWrapper.WriteString(const _Name, _Value: string); begin FIni.WriteString('settings', _Name, _Value); end; procedure TIniFileWrapper.WriteStrings(const _Section: string; const _List: TStrings); var i: Integer; begin FIni.WriteInteger(_Section, 'Count', _List.Count); for i := 0 to _List.Count - 1 do begin FIni.WriteString(_Section, Format('Items%.4d', [i]), _List[i]); end; end; { TCodeFormatterConfigHandler } class procedure TCodeFormatterConfigHandler.ReadSettings(_Reader: IConfigReader; _Settings: TCodeFormatterSettings); function ReadSpaceSet(const _Name: string; _Default: TSpaceSet): TSpaceSet; begin Result := IntToSpaceSet(_Reader.ReadInteger(_Name, SpaceSetToInt(_Default))); end; var ES: TCodeFormatterEngineSettings; cps: set of TConfigPrecedenceEnum; cp: TConfigPrecedenceEnum; begin _Settings.UseCapitalizationFile := _Reader.ReadBool('UseCapitalizationFile', False); _Settings.CapitalizationFile := _Reader.ReadString('CapitalizationFile', ''); _Settings.CapNames.Clear; if _Settings.UseCapitalizationFile and (_Settings.CapitalizationFile <> '') and FileExists(_Settings.CapitalizationFile) then _Settings.CapNames.LoadFromFile(_Settings.CapitalizationFile) else _Reader.ReadStrings('Capitalization', _Settings.CapNames); _Settings.ConfigPrecedence[1] := IntToConfigPrecedence(_Reader.ReadInteger('Precedence1', Ord(cpDirective))); _Settings.ConfigPrecedence[2] := IntToConfigPrecedence(_Reader.ReadInteger('Precedence2', Ord(cpIniFile))); _Settings.ConfigPrecedence[3] := IntToConfigPrecedence(_Reader.ReadInteger('Precedence3', Ord(cpMyConfig))); // make sure the setting is valid cps := [cpDirective, cpIniFile, cpMyConfig]; Exclude(cps, _Settings.ConfigPrecedence[1]); if not (_Settings.ConfigPrecedence[2] in cps) then begin _Settings.ConfigPrecedence[2] := _Settings.ConfigPrecedence[3]; if not (_Settings.ConfigPrecedence[2] in cps) then begin for cp := Low(TConfigPrecedenceEnum) to High(TConfigPrecedenceEnum) do begin if cp in cps then begin _Settings.ConfigPrecedence[2] := cp; Break; end; end; end; end; Exclude(cps, _Settings.ConfigPrecedence[2]); if not (_Settings.ConfigPrecedence[3] in cps) then begin for cp := Low(TConfigPrecedenceEnum) to High(TConfigPrecedenceEnum) do begin if cp in cps then begin _Settings.ConfigPrecedence[3] := cp; Break; end; end; end; ES := _Settings.Settings; ES.SpaceOperators := ReadSpaceSet('SpaceOperators', ES.SpaceOperators); ES.SpaceColon := ReadSpaceSet('SpaceColon', ES.SpaceColon); ES.SpaceSemiColon := ReadSpaceSet('SpaceSemiColon', ES.SpaceSemiColon); ES.SpaceComma := ReadSpaceSet('SpaceComma', ES.SpaceComma); ES.SpaceLeftBr := ReadSpaceSet('SpaceLeftBr', ES.SpaceLeftBr); ES.SpaceRightBr := ReadSpaceSet('SpaceRightBr', ES.SpaceRightBr); ES.SpaceLeftHook := ReadSpaceSet('SpaceLeftHook', ES.SpaceLeftHook); ES.SpaceRightHook := ReadSpaceSet('SpaceRightHook', ES.SpaceRightHook); ES.SpaceEqualOper := ReadSpaceSet('SpaceEqualOper', ES.SpaceEqualOper); ES.UpperCompDirectives := _Reader.ReadBool('UpperCompDirectives', ES.UpperCompDirectives); //: Boolean; ES.UpperNumbers := _Reader.ReadBool('UpperNumbers', ES.UpperNumbers); //: Boolean; ES.ReservedCase := TCase(_Reader.ReadInteger('ReservedCase', Ord(ES.ReservedCase))); //: TCase; ES.StandDirectivesCase := TCase(_Reader.ReadInteger('StandDirectivesCase', Ord(ES.StandDirectivesCase))); //: TCase; ES.IdentifiersCase := TCase(_Reader.ReadInteger('IdentifiersCase', Ord(ES.IdentifiersCase))); // TCase ES.ChangeIndent := _Reader.ReadBool('ChangeIndent', ES.ChangeIndent); //: Boolean; ES.NoIndentElseIf := _Reader.ReadBool('NoIndentElseIf', ES.NoIndentElseIf); //: Boolean; ES.IndentBegin := _Reader.ReadBool('IndentBegin', ES.IndentBegin); //: Boolean; ES.IndentTry := _Reader.ReadBool('IndentTry', ES.IndentTry); //: Boolean; ES.IndentTryElse := _Reader.ReadBool('IndentTryElse', ES.IndentTryElse); //: Boolean; ES.IndentCaseElse := _Reader.ReadBool('IndentCaseElse', ES.IndentCaseElse); //: Boolean; ES.IndentComments := _Reader.ReadBool('IndentComments', ES.IndentComments); //: Boolean; ES.IndentCompDirectives := _Reader.ReadBool('IndentCompDirectives', ES.IndentCompDirectives); //: Boolean; ES.BlankProc := _Reader.ReadBool('BlankProc', ES.BlankProc); //: Boolean; ES.BlankSubProc := _Reader.ReadBool('BlankSubProc', ES.BlankSubProc); //: Boolean; ES.RemoveDoubleBlank := _Reader.ReadBool('RemoveDoubleBlank', ES.RemoveDoubleBlank); //: Boolean; ES.SpacePerIndent := _Reader.ReadInteger('SpacePerIndent', ES.SpacePerIndent); //: Integer; ES.FeedRoundBegin := TFeedBegin(_Reader.ReadInteger('FeedRoundBegin', Ord(ES.FeedRoundBegin))); ES.FeedRoundTry := TFeedBegin(_Reader.ReadInteger('FeedRoundTry', Ord(ES.FeedRoundTry))); ES.FeedBeforeEnd := _Reader.ReadBool('FeedBeforeEnd', ES.FeedBeforeEnd); //: Boolean; ES.FeedAfterThen := _Reader.ReadBool('FeedAfterThen', ES.FeedAfterThen); //: Boolean; ES.ExceptSingle := _Reader.ReadBool('ExceptSingle', ES.ExceptSingle); //: Boolean; ES.FeedAfterVar := _Reader.ReadBool('FeedAfterVar', ES.FeedAfterVar); //: Boolean; ES.FeedEachUnit := _Reader.ReadBool('FeedEachUnit', ES.FeedEachUnit); //: Boolean; ES.NoFeedBeforeThen := _Reader.ReadBool('NoFeedBeforeThen', ES.NoFeedBeforeThen); //: Boolean; ES.FeedElseIf := _Reader.ReadBool('FeedElseIf', ES.FeedElseIf); //: Boolean; ES.FillNewWords := IntToCapfileMode(_Reader.ReadInteger('FillNewWords', CapfileModeToInt(ES.FillNewWords))); ES.FeedAfterSemiColon := _Reader.ReadBool('FeedAfterSemiColon', ES.FeedAfterSemiColon); //: Boolean; ES.StartCommentOut := _Reader.ReadString('StartCommentOut', ES.StartCommentOut); ES.EndCommentOut := _Reader.ReadString('EndCommentOut', ES.EndCommentOut); ES.CommentFunction := _Reader.ReadBool('CommentFunction', ES.CommentFunction); //: Boolean; ES.CommentUnit := _Reader.ReadBool('CommentUnit', ES.CommentUnit); //: Boolean; ES.WrapLines := _Reader.ReadBool('WrapLines', ES.WrapLines); //: Boolean; ES.WrapPosition := _Reader.ReadInteger('WrapPosition', ES.WrapPosition); //: Byte; ES.AlignCommentPos := _Reader.ReadInteger('AlignCommentPos', ES.AlignCommentPos); //: Byte; ES.AlignComments := _Reader.ReadBool('AlignComments', ES.AlignComments); //: Boolean; ES.AlignVarPos := _Reader.ReadInteger('AlignVarPos', ES.AlignVarPos); //: Byte; ES.AlignVar := _Reader.ReadBool('AlignVar', ES.AlignVar); //: Boolean; _Settings.Settings := ES; end; class procedure TCodeFormatterConfigHandler.WriteSettings(_Writer: IConfigWriter; _Settings: TCodeFormatterSettings); procedure WriteSpaceSet(const _Name: string; _Value: TSpaceSet); begin _Writer.WriteInteger(_Name, SpaceSetToInt(_Value)); end; begin WriteSpaceSet('SpaceOperators', _Settings.SpaceOperators); WriteSpaceSet('SpaceColon', _Settings.SpaceColon); WriteSpaceSet('SpaceSemiColon', _Settings.SpaceSemiColon); WriteSpaceSet('SpaceComma', _Settings.SpaceComma); WriteSpaceSet('SpaceLeftBr', _Settings.SpaceLeftBr); WriteSpaceSet('SpaceRightBr', _Settings.SpaceRightBr); WriteSpaceSet('SpaceLeftHook', _Settings.SpaceLeftHook); WriteSpaceSet('SpaceRightHook', _Settings.SpaceRightHook); WriteSpaceSet('SpaceEqualOper', _Settings.SpaceEqualOper); _Writer.WriteBool('UpperCompDirectives', _Settings.UpperCompDirectives); //: Boolean; _Writer.WriteBool('UpperNumbers', _Settings.UpperNumbers); //: Boolean; _Writer.WriteInteger('ReservedCase', Ord(_Settings.ReservedCase)); //: TCase; _Writer.WriteInteger('StandDirectivesCase', Ord(_Settings.StandDirectivesCase)); //: TCase; _Writer.WriteInteger('IdentifiersCase', Ord(_Settings.IdentifiersCase)); _Writer.WriteBool('ChangeIndent', _Settings.ChangeIndent); //: Boolean; _Writer.WriteBool('NoIndentElseIf', _Settings.NoIndentElseIf); //: Boolean; _Writer.WriteBool('IndentBegin', _Settings.IndentBegin); //: Boolean; _Writer.WriteBool('IndentTry', _Settings.IndentTry); //: Boolean; _Writer.WriteBool('IndentTryElse', _Settings.IndentTryElse); //: Boolean; _Writer.WriteBool('IndentCaseElse', _Settings.IndentCaseElse); //: Boolean; _Writer.WriteBool('IndentComments', _Settings.IndentComments); //: Boolean; _Writer.WriteBool('IndentCompDirectives', _Settings.IndentCompDirectives); //: Boolean; _Writer.WriteBool('BlankProc', _Settings.BlankProc); //: Boolean; _Writer.WriteBool('BlankSubProc', _Settings.BlankSubProc); //: Boolean; _Writer.WriteBool('RemoveDoubleBlank', _Settings.RemoveDoubleBlank); //: Boolean; _Writer.WriteInteger('SpacePerIndent', _Settings.SpacePerIndent); //: Integer; _Writer.WriteInteger('FeedRoundBegin', Ord(_Settings.FeedRoundBegin)); //: TFeedBegin; _Writer.WriteInteger('FeedRoundTry', Ord(_Settings.FeedRoundTry)); //: TFeedBegin; _Writer.WriteBool('FeedBeforeEnd', _Settings.FeedBeforeEnd); //: Boolean; _Writer.WriteBool('FeedAfterThen', _Settings.FeedAfterThen); //: Boolean; _Writer.WriteBool('ExceptSingle', _Settings.ExceptSingle); //: Boolean; _Writer.WriteBool('FeedAfterVar', _Settings.FeedAfterVar); //: Boolean; _Writer.WriteBool('FeedEachUnit', _Settings.FeedEachUnit); //: Boolean; _Writer.WriteBool('NoFeedBeforeThen', _Settings.NoFeedBeforeThen); //: Boolean; _Writer.WriteBool('FeedElseIf', _Settings.FeedElseIf); //: Boolean; _Writer.WriteInteger('FillNewWords', CapfileModeToInt(_Settings.FillNewWords)); _Writer.WriteBool('FeedAfterSemiColon', _Settings.FeedAfterSemiColon); //: Boolean; _Writer.WriteString('StartCommentOut', string(_Settings.StartCommentOut)); //: TCommentArray; _Writer.WriteString('EndCommentOut', string(_Settings.EndCommentOut)); //: TCommentArray; _Writer.WriteBool('CommentFunction', _Settings.CommentFunction); //: Boolean; _Writer.WriteBool('CommentUnit', _Settings.CommentUnit); //: Boolean; _Writer.WriteBool('WrapLines', _Settings.WrapLines); //: Boolean; _Writer.WriteInteger('WrapPosition', _Settings.WrapPosition); //: Byte; _Writer.WriteInteger('AlignCommentPos', _Settings.AlignCommentPos); //: Byte; _Writer.WriteBool('AlignComments', _Settings.AlignComments); //: Boolean; _Writer.WriteInteger('AlignVarPos', _Settings.AlignVarPos); //: Byte; _Writer.WriteBool('AlignVar', _Settings.AlignVar); //: Boolean; _Writer.WriteInteger('Precedence1', Ord(_Settings.ConfigPrecedence[1])); _Writer.WriteInteger('Precedence2', Ord(_Settings.ConfigPrecedence[2])); _Writer.WriteInteger('Precedence3', Ord(_Settings.ConfigPrecedence[3])); _Writer.WriteBool('UseCapitalizationFile', _Settings.UseCapitalizationFile); _Writer.WriteString('CapitalizationFile', string(_Settings.CapitalizationFile)); if _Settings.UseCapitalizationFile and (_Settings.CapitalizationFile <> '') then begin try _Settings.CapNames.SaveToFile(string(_Settings.CapitalizationFile)); except //FI:W501 // ignore, file might be readonly end; end else _Writer.WriteStrings('Capitalization', _Settings.CapNames); end; class procedure TCodeFormatterConfigHandler.ExportToFile(const _Filename: string; _Settings: TCodeFormatterSettings); var Writer: IConfigWriter; Ini: TMemIniFile; begin Ini := TMemIniFile.Create(_Filename); try Writer := TIniFileWrapper.Create(Ini); WriteSettings(Writer, _Settings); Ini.UpdateFile; finally Ini.Free; end; end; function GetModulePath: string; begin Result := ExtractFilePath(GetModuleName(HInstance)); end; class function TCodeFormatterConfigHandler.GetDefaultConfig(const _Name: string; _Settings: TCodeFormatterSettings): Boolean; var FileName: string; begin FileName := GetModulePath + FORMATTER_CONFIG_PREFIX + _Name + '.ini'; Result := FileExists(FileName); if Result then ImportFromFile(FileName, _Settings); end; class procedure TCodeFormatterConfigHandler.GetDefaultsList(_Defaults: TStrings); var Path: string; sr: TSearchRec; s: string; begin Path := GetModulePath; if 0 = FindFirst(Path + FORMATTER_CONFIG_PREFIX + '*.ini', faAnyFile, sr) then begin try repeat s := ChangeFileExt(sr.Name, ''); Delete(s, 1, Length(FORMATTER_CONFIG_PREFIX)); _Defaults.Add(s); until 0 <> FindNext(sr); finally FindClose(sr); end; end; end; class procedure TCodeFormatterConfigHandler.ImportFromFile(const _Filename: string; _Settings: TCodeFormatterSettings); var Reader: IConfigReader; Ini: TMemIniFile; begin Ini := TMemIniFile.Create(_Filename); try Reader := TIniFileWrapper.Create(Ini); ReadSettings(Reader, _Settings); finally Ini.Free; end; end; end.
unit xInetScanner; interface uses SysUtils, Classes, WinInet, Contnrs, StrUtils, EmbeddedWB, Windows, SHDocVw, MSHTML; type TxInetAccessType = (atDirect, atPreconfig, atPreconfigWithNoAutoProxy, atProxy); TxInetConnectionFlagsType = (cfAsync, cfFromCache, cfOffline); TxInetConnectionFlags = set of TxInetConnectionFlagsType; TxSearchForType = (sfSWF, sfGIF, sfEXE); TxURLType = (utHTML, utGIF, utCSS, utUnknown, utSWF); const X_DEF_PROXYBYPASS = '<local>'; X_SWF_SEARCH_ATTR = 'getflashplayer'; type TxURL = class; TxInetScanner = class; TxOnFindURL = procedure (Sender: TObject; AURL: TxURL) of object; TxURLScanThread = class(TThread) private FScanner: TxInetScanner; FURL: TxURL; FWithParse: Boolean; procedure Parse; public constructor Create(CreateSuspended: Boolean); procedure Execute; override; destructor Destroy; override; end; TxInetConnectionParams = class(TPersistent) private FScanner: TxInetScanner; FAccessType: TxInetAccessType; FAgent: string; FProxyPort: Integer; FProxyName: string; FProxyBypass: string; FFlags: TxInetConnectionFlags; procedure SetAccessType(const Value: TxInetAccessType); public constructor Create(AScanner: TxInetScanner); virtual; published property AccessType: TxInetAccessType read FAccessType write SetAccessType default atPreconfig; property Agent: string read FAgent write FAgent; property Flags: TxInetConnectionFlags read FFlags write FFlags default []; property ProxyName: string read FProxyName write FProxyName; property ProxyPort: Integer read FProxyPort write FProxyPort default 8080; property ProxyBypass: string read FProxyBypass write FProxyBypass; end; TxURL = class(TPersistent) private FScanner: TxInetScanner; FURLName: string; FHandle: HINTERNET; FData: string; FSize: Cardinal; FURLs: TObjectList; FURLFileName: string; FURLFullPath: string; FLevel: Cardinal; FParentURL: TxURL; FURLType: TxURLType; FURLTypeText: string; FRecvBytes: Cardinal; FDownloading: Boolean; FParsing: Boolean; FScanThread: TxURLScanThread; FOnEndDownload: TNotifyEvent; FOnStartParse: TNotifyEvent; FOnEndParse: TNotifyEvent; FOnStartDownload: TNotifyEvent; FOnSuspendScan: TNotifyEvent; FOnResumeScan: TNotifyEvent; FDownloaded: Boolean; procedure SetURLName(const Value: string); function GetURL(AIndex: Integer): TxURL; function GetURLsCount: Integer; procedure SetURLType(const AType: string); public function AddURL(const AURLName: string): TxURL; function AsString: string; constructor Create(AScanner: TxInetScanner); virtual; destructor Destroy; override; procedure Download(AWithParse: Boolean = False; ACreateThread: Boolean = False); procedure GetURLInfo; procedure Open; procedure Close; procedure Parse(AWB: TEmbeddedWB); procedure SuspendScan; procedure ResumeScan; procedure SaveToFile(const AFileName: string); property Size: Cardinal read FSize; property Level: Cardinal read FLevel; property Downloading: Boolean read FDownloading; property Parsing: Boolean read FParsing; property RecvBytes: Cardinal read FRecvBytes; property ParentURL: TxURL read FParentURL; property URLs[AIndex: Integer]: TxURL read GetURL; property URLFileName: string read FURLFileName; property URLType: TxURLType read FURLType; property URLTypeText: string read FURLTypeText; property URLFullPath: string read FURLFullPath; published property URLName: string read FURLName write SetURLName; property URLsCount: Integer read GetURLsCount; property OnStartDownload: TNotifyEvent read FOnStartDownload write FOnStartDownload; property OnEndDownload: TNotifyEvent read FOnEndDownload write FOnEndDownload; property OnStartParse: TNotifyEvent read FOnStartParse write FOnStartParse; property OnEndParse: TNotifyEvent read FOnEndParse write FOnEndParse; property OnResumeScan: TNotifyEvent read FOnResumeScan write FOnResumeScan; property OnSuspendScan: TNotifyEvent read FOnSuspendScan write FOnSuspendScan; end; TxInetScanner = class(TComponent) private FURLs: TList; FSession: HINTERNET; FConnected: Boolean; FConnection: TxInetConnectionParams; FStartURL: TxURL; FSearchFor: TxSearchForType; FOnFindURL: TxOnFindURL; FScanDepth: Cardinal; FAllowExtRefs: Boolean; FOnEndScan: TNotifyEvent; FOnStartScan: TNotifyEvent; FOnSuspendScan: TNotifyEvent; FOnResumeScan: TNotifyEvent; FWB: TEmbeddedWB; FDownloaded: Boolean; FFrameList: TList; FDoc: IHTMLDocument2; procedure SetConnected(const Value: Boolean); procedure SetConnection(const Value: TxInetConnectionParams); procedure SetStartURL(const Value: TxURL); function GetURL(AIndex: Integer): TxURL; function GetURLsCount: Integer; procedure DoStartScan(Sender: TObject); procedure DoEndScan(Sender: TObject); procedure DocumentComplete(Sender: TObject; const pDisp: IDispatch; var URL: OleVariant); { Private declarations } protected procedure Loaded; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Scan; procedure Resume; procedure Suspend; function IndexOfURL(const AURLName: string): Integer; procedure URLsClear; property URLsCount: Integer read GetURLsCount; property URLs[AIndex: Integer]: TxURL read GetURL; property WB: TEmbeddedWB read FWB write FWB; published property AllowExtRefs: Boolean read FAllowExtRefs write FAllowExtRefs default False; property Connected: Boolean read FConnected write SetConnected default False; property Connection: TxInetConnectionParams read FConnection write SetConnection; property ScanDepth: Cardinal read FScanDepth write FScanDepth default 1; property SearchFor: TxSearchForType read FSearchFor write FSearchFor default sfSWF; property StartURL: TxURL read FStartURL write SetStartURL; property OnFindURL: TxOnFindURL read FOnFindURL write FOnFindURL; property OnStartScan: TNotifyEvent read FOnStartScan write FOnStartScan; property OnEndScan: TNotifyEvent read FOnEndScan write FOnEndScan; property OnResumeScan: TNotifyEvent read FOnResumeScan write FOnResumeScan; property OnSuspendScan: TNotifyEvent read FOnSuspendScan write FOnSuspendScan; end; implementation uses Controls, Forms, {ssStrUtil,} dialogs; { TxInetConnectionParams } //============================================================================================== constructor TxInetConnectionParams.Create(AScanner: TxInetScanner); begin FScanner := AScanner; FAccessType := atPreconfig; FProxyBypass := X_DEF_PROXYBYPASS; FAgent := ':-)'; FProxyPort := 8080; end; //============================================================================================== procedure TxInetConnectionParams.SetAccessType( const Value: TxInetAccessType); begin FAccessType := Value; end; { TxInetScanner } //============================================================================================== constructor TxInetScanner.Create(AOwner: TComponent); begin inherited; FConnection := TxInetConnectionParams.Create(Self); FURLs := TList.Create; FStartURL := TxURL.Create(Self); with FStartURL do begin FLevel := 0; OnStartDownload := Self.DoStartScan; OnEndParse := Self.DoEndScan; end; FSearchFor := sfSWF; FScanDepth := 1; FWB := TEmbeddedWB.Create(nil); with FWB do begin FWB.Height := 0; if not (csDesigning in ComponentState) then ParentWindow := (Self.Owner as TWinControl).Handle; // then FWB.ParentWindow := GetDesktopWindow; FWB.Hide; OnDocumentComplete := Self.DocumentComplete; DownloadOptions := [DLCTL_NO_DLACTIVEXCTLS, DLCTL_NO_RUNACTIVEXCTLS, DLCTL_SILENT, DLCTL_PRAGMA_NO_CACHE]; end; FFrameList := TList.Create; end; //============================================================================================== destructor TxInetScanner.Destroy; begin if Connected then Connected := False; // FWB.ParentWindow := 0; FFrameList.Free; FWB.Free; FURLs.Free; FStartURL.Free; FConnection.Free; inherited; end; //============================================================================================== procedure TxURL.Download(AWithParse: Boolean = False; ACreateThread: Boolean = False); begin if FHandle = nil then Exit; if Assigned(OnStartDownload) then OnStartDownload(Self); FDownloading := True; FDownloaded := False; if ACreateThread then begin FScanThread := TxURLScanThread.Create(True); with FScanThread do begin FreeOnTerminate := True; FScanner := Self.FScanner; FWithParse := AWithParse; FURL := Self; Resume; end; end else begin FScanner.FWB.Navigate(FURLFullPath); repeat Application.ProcessMessages; until FScanner.FDownloaded; FDownloading := False; if Assigned(OnEndDownload) then OnEndDownload(Self); if AWithParse then Parse(FScanner.FWB); end; end; //============================================================================================== procedure TxInetScanner.DocumentComplete(Sender: TObject; const pDisp: IDispatch; var URL: OleVariant); begin if (pDisp as IWebBrowser) = (Sender as TWebBrowser).DefaultInterface then FDownloaded := True else begin // FFrameList.Add(Pointer((pDisp as IWebBrowser).Document as IHTMLDocument2)); FDoc := (pDisp as IWebBrowser).Document as IHTMLDocument2; end; end; //============================================================================================== procedure TxInetScanner.DoEndScan(Sender: TObject); begin if Assigned(FOnEndScan) then FOnEndScan(Self); end; //============================================================================================== procedure TxInetScanner.DoStartScan(Sender: TObject); begin if Assigned(FOnStartScan) then FOnStartScan(Self); end; //============================================================================================== function TxInetScanner.GetURL(AIndex: Integer): TxURL; begin Result := TxURL(FURLs[AIndex]); end; //============================================================================================== function TxInetScanner.GetURLsCount: Integer; begin Result := FURLs.Count; end; //============================================================================================== function TxInetScanner.IndexOfURL(const AURLName: string): Integer; var i: Integer; begin Result := -1; for i := 0 to FURLs.Count - 1 do if TxURL(FURLs[i]).URLName = AURLName then begin Result := i; Exit; end; end; //============================================================================================== procedure TxInetScanner.Loaded; begin inherited; end; //============================================================================================== procedure TxInetScanner.Resume; var i: Integer; begin for i := 0 to FURLs.Count - 1 do TxURL(FURLs[i]).ResumeScan; FStartURL.ResumeScan; if Assigned(FOnResumeScan) then FOnResumeScan(Self); end; //============================================================================================== procedure TxInetScanner.Scan; begin URLsClear; FFrameList.Clear; StartURL.Download(True, False); // repeat until not StartURL.Downloading; // StartURL.Parse; end; //============================================================================================== procedure TxInetScanner.SetConnected(const Value: Boolean); var FAccessType, FFlags: Integer; begin if FConnected = Value then Exit; FConnected := Value; if Value then begin case FConnection.AccessType of atDirect: FAccessType := INTERNET_OPEN_TYPE_DIRECT; atPreconfig: FAccessType := INTERNET_OPEN_TYPE_PRECONFIG; atPreconfigWithNoAutoProxy: FAccessType := INTERNET_OPEN_TYPE_PRECONFIG_WITH_NO_AUTOPROXY; atProxy: FAccessType := INTERNET_OPEN_TYPE_PROXY; end; FFlags := 0; if cfAsync in FConnection.Flags then FFlags := FFlags or INTERNET_FLAG_ASYNC; if cfFromCache in FConnection.Flags then FFlags := FFlags or INTERNET_FLAG_FROM_CACHE; if cfOffline in FConnection.Flags then FFlags := FFlags or INTERNET_FLAG_OFFLINE; FSession := InternetOpen(PChar(FConnection.Agent), FAccessType, PChar(FConnection.ProxyName + ':' + IntToStr(FConnection.ProxyPort)), PChar(FConnection.ProxyBypass), FFlags); if FSession = nil then begin FConnected := False; raise Exception.Create('Could not connect to Internet!'); Exit; end; FStartURL.Open; if FStartURL.FHandle = nil then begin FConnected := False; InternetCloseHandle(FSession); raise Exception.CreateFmt('Could not open URL: %s !', [FStartURL.URLName]); Exit; end; end else begin FStartURL.Close; InternetCloseHandle(FSession); end; end; //============================================================================================== procedure TxInetScanner.SetConnection(const Value: TxInetConnectionParams); begin FConnection := Value; end; //============================================================================================== procedure TxInetScanner.SetStartURL(const Value: TxURL); begin FStartURL.Assign(Value); if Connected then Connected := False; end; //============================================================================================== procedure TxInetScanner.Suspend; var i: Integer; begin for i := 0 to FURLs.Count - 1 do TxURL(FURLs[i]).SuspendScan; FStartURL.SuspendScan; if Assigned(FOnSuspendScan) then FOnSuspendScan(Self); end; //============================================================================================== procedure TxInetScanner.URLsClear; begin { for i := 0 to FURLs.Count - 1 do begin if TxURL(FURLs[i]).Level = 0 then TxURL(FURLs[0]).FURLs.Clear; end;} FStartURL.FURLs.Clear; FURLs.Clear; end; { TxURL } //============================================================================================== constructor TxURL.Create(AScanner: TxInetScanner); begin FScanner := AScanner; FURLs := TObjectList.Create(True); end; //============================================================================================== procedure TxURL.SetURLName(const Value: string); begin FURLName := Value; if (Pos('://', FURLName) = 0) and (Value[1] <> '/') and (PosEx_('www', FURLName) = 0) then FURLName := '/' + FURLName; FURLFileName := ExtractWord(WordCount(Value, ['/']), Value, ['/']); if (FURLName[1] = '/') and (Self <> FScanner.StartURL) then FURLFullPath := FScanner.StartURL.FURLFullPath + FURLName else if Pos('://', FURLName) = 0 then FURLFullPath := 'http://' + FURLName else FURLFullPath := FURLName; if FURLFullPath[Length(FURLFullPath)] = '/' then System.Delete(FURLFullPath, Length(FURLFullPath), 1); FURLName := Value; end; //============================================================================================== procedure TxURL.Open; begin FHandle := InternetOpenUrl(FScanner.FSession, PChar(FURLFullPath), nil, 0, 0, 0); end; //============================================================================================== procedure TxURL.Close; begin if Assigned(FHandle) then begin FData := ''; InternetCloseHandle(FHandle); end; end; //============================================================================================== function TxURL.AsString: string; begin Result := FData; end; //============================================================================================== procedure TxURL.SaveToFile(const AFileName: string); var F: TextFile; begin AssignFile(F, AFileName); Rewrite(F); Write(F, FData); CloseFile(F); end; //============================================================================================== procedure TxURL.Parse; var FOffs, j, i: Integer; FExt, FRes: string; FURL: TxURL; FExtSkip: Boolean; IHTML, IFrame: IHTMLDocument2; ICol: IHTMLElementCollection; IItem: IHTMLElement; IWnd: IHTMLWindow2; // IFrame: IHTMLWindow2; OV: OleVariant; s: string; begin if AWB = nil then Exit; AWB.ControlInterface.Document.QueryInterface(IID_IHTMLDOCUMENT2, IHTML); IHTML.all.tags('html').QueryInterface(IHTMLElementCollection, ICol); if ICol.length = 0 then Exit; ICol.item(0, 0).QueryInterface(IHTMLElement, IItem); FData := IItem.innerHTML; if FData = '' then Exit; FParsing := True; if Assigned(FOnStartParse) then FOnStartParse(Self); case FScanner.SearchFor of sfSWF: FExt := '.swf'; sfGIF: FExt := '.gif'; sfEXE: FExt := '.exe'; end; { FOffs := PosEx_(FExt, FData); while FOffs > 0 do begin i := 1; FRes := FExt; while not (FData[FOffs - i] in ['=', '"', ' ']) do begin if Pos('http://', LowerCase(FRes)) = 1 then Break; FRes := FData[FOffs - i] + FRes; Inc(i); end; FRes := DelChars(FRes, ['''', '+']); FURL := AddURL(FRes); if FURL <> nil then begin FURL.GetURLInfo; if Assigned(FScanner.OnFindURL) then FScanner.OnFindURL(FScanner, FURL); end; FOffs := PosEx_(FExt, FData, FOffs + 1); end;} try for i := 0 to IHTML.embeds.length - 1 do begin IHTML.embeds.item(i, 0).QueryInterface(IHTMLElement, IItem); if PosEx_(X_SWF_SEARCH_ATTR, IItem.getAttribute('pluginspage', 0)) > 0 then begin FRes := IItem.getAttribute('src', 0); FURL := AddURL(FRes); if FURL <> nil then begin FURL.GetURLInfo; if Assigned(FScanner.OnFindURL) then FScanner.OnFindURL(FScanner, FURL); end; end; end; except on e:exception do showmessage(e.Message); end; //executing frames for j := 0 to FScanner.FFrameList.Count do begin // IFrame := IHTMLDocument2(FScanner.FFrameList[j]); IFrame := FScanner.FDoc; showmessage(iframe.body.innerHTML); for i := 0 to IFrame.embeds.length - 1 do begin IFrame.embeds.item(i, 0).QueryInterface(IHTMLElement, IItem); if PosEx_(X_SWF_SEARCH_ATTR, IItem.getAttribute('pluginspage', 0)) > 0 then begin FRes := IItem.getAttribute('src', 0); FURL := AddURL(FRes); if FURL <> nil then begin FURL.GetURLInfo; if Assigned(FScanner.OnFindURL) then FScanner.OnFindURL(FScanner, FURL); end; end; end; end; { FOffs := PosEx_('<iframe', FData); while FOffs > 0 do begin i := 8; FRes := ''; while not (FData[FOffs + i] in ['>']) do begin FRes := FRes + FData[FOffs + i]; Inc(i); end; j := PosEx_('src=', FRes); if j > 0 then begin FRes := Copy(FRes, j, Length(FRes) - j + 1); FRes := ExtractWord(1, FRes, [' ', #13, #10]); System.Delete(FRes, 1, 4); FRes := DelChars(FRes, ['''', '"']); // if FRes[1] in ['"', ''''] then System.Delete(FRes, 1, 1); // if FRes[Length(FRes)] in ['"', ''''] then System.Delete(FRes, Length(FRes), 1); FURL := AddURL(FRes); if FURL <> nil then begin FURL.GetURLInfo; if Assigned(FScanner.OnFindURL) then FScanner.OnFindURL(FScanner, FURL); FURL.Open; FURL.Download(True); // repeat until not FURL.Downloading; // FURL.Parse; end; end; FOffs := PosEx_('<iframe', FData, FOffs + 1); end; //executing java-scripts FOffs := PosEx_('language=JavaScript', FData); while FOffs > 0 do begin i := 20; FRes := ''; while not (FData[FOffs + i] in ['>']) do begin FRes := FRes + FData[FOffs + i]; Inc(i); end; j := PosEx_('src=', FRes); if j > 0 then begin FRes := Copy(FRes, j, Length(FRes) - j + 1); FRes := ExtractWord(1, FRes, [' ', #13, #10]); System.Delete(FRes, 1, 4); FRes := DelChars(FRes, ['''', '"']); // if FRes[1]='"' then System.Delete(FRes, 1, 1); // if FRes[Length(FRes)]='"' then System.Delete(FRes, Length(FRes), 1); FURL := AddURL(FRes); if FURL <> nil then begin FURL.GetURLInfo; if Assigned(FScanner.OnFindURL) then FScanner.OnFindURL(FScanner, FURL); FURL.Open; FURL.Download(True); // repeat until not FURL.Downloading; // FURL.Parse; end; end; FOffs := PosEx_('language=JavaScript', FData, FOffs + 1); end; if Self.Level < FScanner.ScanDepth - 1 then begin FExt := 'href="'; FOffs := PosEx_(FExt, FData); while FOffs > 0 do begin i := 6; FRes := ''; while not (FData[FOffs + i] in ['"']) do begin FRes := FRes + FData[FOffs + i]; Inc(i); end; FExtSkip := (FRes = '') or (not FScanner.AllowExtRefs and (Pos('://', LowerCase(FRes)) > 0) and (Pos(LowerCase(FScanner.StartURL.URLName), LowerCase(FRes)) = 0)) or (FRes[1] = '?'); if not FExtSkip then begin FURL := AddURL(FRes); if FURL <> nil then begin FURL.GetURLInfo; if Assigned(FScanner.OnFindURL) then FScanner.OnFindURL(FScanner, FURL); if FURL.URLType = utHTML then begin FURL.Open; FURL.Download(True); // repeat until not FURL.Downloading; // FURL.Parse; end; end; end; FOffs := PosEx_(FExt, FData, FOffs + 1); end; end;} FParsing := False; if Assigned(FOnEndParse) then FOnEndParse(Self); end; //============================================================================================== function TxURL.GetURL(AIndex: Integer): TxURL; begin Result := TxURL(FURLs[AIndex]); end; //============================================================================================== destructor TxURL.Destroy; begin FURLs.Clear; FURLs.Free; inherited; end; //============================================================================================== function TxURL.AddURL(const AURLName: string): TxURL; begin if FScanner.IndexOfURL(AURLName) <> -1 then begin Result := nil; Exit; end; Result := TxURL.Create(Self.FScanner); with Result do begin URLName := AURLName; FParentURL := Self; FLevel := Self.FLevel + 1; end; if Result.URLFullPath = FScanner.StartURL.URLFullPath then begin FreeAndNil(Result); Exit; end; FURLs.Add(Result); FScanner.FURLs.Add(Result); end; //============================================================================================== function TxURL.GetURLsCount: Integer; begin Result := FURLs.Count; end; //============================================================================================== procedure TxURL.GetURLInfo; var FConnect, FRequest: HINTERNET; FURLC: TURLComponents; FHostName, FURLPath: array[1..INTERNET_MAX_PATH_LENGTH] of Char; FBuffSize, FIndex: Cardinal; FBuff: string; begin if FScanner.FSession = nil then Exit; SetURLType(''); FillChar(FURLC, SizeOf(TURLComponents), 0); with FURLC do begin dwStructSize := SizeOf(TURLComponents); lpszScheme := nil; dwSchemeLength := 0; lpSzExtraInfo := nil; dwExtraInfoLength := 0; lpSzHostName := @FHostName[1]; dwHostNameLength := INTERNET_MAX_PATH_LENGTH; lpszUrlPath := @FURLPath[1]; dwUrlPathLength := INTERNET_MAX_PATH_LENGTH; end; InternetCrackUrl(PChar(FURLFullPath), 0, ICU_ESCAPE, FURLC); FConnect := InternetConnect(FScanner.FSession, FURLC.lpszHostName, FURLC.nPort, nil, nil, INTERNET_SERVICE_HTTP, 0, 0); if Assigned(FConnect) then try FRequest := HttpOpenRequest(FConnect, PChar('HEAD'), PChar(StringReplace(FURLC.lpszUrlPath, '/', '//', [rfReplaceAll])), nil, nil, nil, INTERNET_FLAG_RELOAD, 0); if Assigned(FRequest) then try if HttpSendRequest(FRequest, nil, 0, FURLC.lpszExtraInfo, FURLC.dwExtraInfoLength) then begin FBuffSize := 1024; FIndex := 0; SetLength(FBuff, FBuffSize); if HttpQueryInfo(FRequest, HTTP_QUERY_CONTENT_TYPE, @FBuff[1], FBuffSize, FIndex) then begin SetLength(FBuff, FBuffSize); SetURLType(FBuff); end; if FURLType <> utHTML then begin FBuffSize := 1024; FIndex := 0; SetLength(FBuff, FBuffSize); if HttpQueryInfo(FRequest, HTTP_QUERY_CONTENT_LENGTH, @FBuff[1], FBuffSize, FIndex) then begin SetLength(FBuff, FBuffSize); FSize := StrToInt(FBuff); end; end; end; finally InternetCloseHandle(FRequest); end; finally InternetCloseHandle(FConnect); end; end; //============================================================================================== procedure TxURL.SetURLType(const AType: string); begin FURLTypeText := AType; FURLType := utUnknown; if Pos('.swf', LowerCase(FURLName)) > 0 then FURLType := utSWF else if Pos('text/html', AType) = 1 then FURLType := utHTML else if Pos('image/gif', AType) = 1 then FURLType := utGIF else if Pos('application/x-shockwave-flash', AType) = 1 then FURLType := utSWF else if AType = 'text/css' then FURLType := utCSS; end; { TxScanThread } //============================================================================================== constructor TxURLScanThread.Create(CreateSuspended: Boolean); begin inherited Create(CreateSuspended); end; //============================================================================================== destructor TxURLScanThread.Destroy; begin inherited; end; //============================================================================================== procedure TxURLScanThread.Execute; const BuffSize = 1024; var FBuff: string; FAcceptedLen: Cardinal; IHTML: IHTMLDocument2; ICol: IHTMLElementCollection; IItem: IHTMLElement; f: string; begin FURL.FData := ''; if FWithParse then begin // FWB.ParentWindow := FWnd; FURL.FScanner.FWB.Navigate(FURL.FURLFullPath); repeat Application.ProcessMessages; until FURL.FScanner.FDownloaded; end else begin repeat SetLength(FBuff, BuffSize); InternetReadFile(FURL.FHandle, @FBuff[1], BuffSize, FAcceptedLen); SetLength(FBuff, FAcceptedLen); FURL.FRecvBytes := FURL.FRecvBytes + FAcceptedLen; FURL.FData := FURL.FData + FBuff; until FAcceptedLen = 0; end; FURL.FDownloading := False; if Assigned(FURL.OnEndDownload) then FURL.OnEndDownload(FURL); if FWithParse then begin Synchronize(Parse); end; Terminate; end; //============================================================================================== procedure TxURL.ResumeScan; begin if FParsing or FDownloading then begin if Assigned(FOnResumeScan) then FOnResumeScan(Self); if FScanThread.Suspended then FScanThread.Resume; end; end; //============================================================================================== procedure TxURL.SuspendScan; begin if FParsing or FDownloading then begin if Assigned(FOnSuspendScan) then FOnSuspendScan(Self); if not FScanThread.Suspended then FScanThread.Suspend; end; end; //============================================================================================== procedure TxURLScanThread.Parse; begin FURL.Parse(FURL.FScanner.FWB); end; end.
unit idlParser; { Unit which parses idl (interface description language) files into a TIDLList struct. Copyright (C) 2012 Joost van der Sluis/CNOC joost@cnoc.nl 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. } {$mode objfpc}{$H+} interface uses Classes, SysUtils,contnrs; type TMemberType=(mtFunc,mtAttribute,mtConst); TParamInOutType=(piNormal,piOut,piIn,piInOut); { TIDLMemberParameter } TIDLMemberParameter = class private FParamInOutType: TParamInOutType; FParamName: string; FParamType: string; FParamTypeUnsigned: boolean; public property ParamType : string read FParamType write FParamType; property ParamTypeUnsigned: boolean read FParamTypeUnsigned write FParamTypeUnsigned; property ParamName: string read FParamName write FParamName; property ParamInOutType: TParamInOutType read FParamInOutType write FParamInOutType; end; TIDLMemberParameterList = class(TObjectList); { TIDLMember } TIDLMember = class private FMemberName: string; FMemberReadonly: boolean; FMemberType: TMemberType; FParams: TIDLMemberParameterList; FReturnType: string; FConstValue: string; FReturnTypeUnsigned: boolean; public constructor Create; virtual; destructor Destroy; override; property MemberType : TMemberType read FMemberType write FMemberType; property ReturnType : string read FReturnType write FReturnType; property ReturnTypeUnsigned: boolean read FReturnTypeUnsigned write FReturnTypeUnsigned; property MemberName: string read FMemberName write FMemberName; property MemberReadonly: boolean read FMemberReadonly write FMemberReadonly; property Params: TIDLMemberParameterList read FParams; property ConstValue: string read FConstValue write FConstValue; end; TIDLMemberList = class(TObjectList); TIDL = class private FInterfaceName: string; FInterfaceType: string; Fmembers: TIDLMemberList; FUUID: string; public constructor Create; virtual; destructor Destroy; override; property InterfaceName: string read FInterfaceName write FInterfaceName; property InterfaceType: string read FInterfaceType write FInterfaceType; property UUID: string read FUUID write FUUID; property members: TIDLMemberList read Fmembers; end; TIDLList = class(TObjectList); procedure ParseFile(const AnIdlList: TIDLList; const IDLtext: tstrings); implementation const idlInterface = 'interface'; idlUUID = 'uuid'; idlattribute = 'attribute'; idlconst = 'const'; idlreadonly = 'readonly'; idlInterfaceEnd = ';'; idlUnsigned = 'unsigned'; idlMemberEnd = ';'; idlInterfaceTypeSeparator = ':'; idlInterfaceBlockStart = '{'; idlInterfaceBlockEnd = '}'; idlStartMultiLineComment = '/*'; idlEndMultiLineComment = '*/'; idlStartExtension = '%{'; idlEndExtension = '%}'; idlStartSingleLineComment = '//'; idlEndSingleLineComment = #10; idlStartIDLAttributesBlock = '['; idlEndIDLAttributesBlock = ']'; idlStartUUID = '('; idlEndUUID = ')'; idlSeparateFuncParams = ','; idlStartFuncParams = '('; idlEndFuncParams = ')'; idlParamIn = 'in'; idlParamOut = 'out'; idlConstAssign = '='; procedure ParseFile(const AnIdlList: TIDLList; const IDLtext: tstrings); type TParseState = (psBegin, psMultiLineComment, psSingleLineComment, psInterface, psInterfaceType, psInterfaceBlock, psInterfaceBlockFuncName, psInterfaceBlockFuncParams, psInterfaceBlockFuncParamName, psInterfaceAfterFuncParams, psParamAttributeBlock, psConstValue, psIDLAttributes, psSearchUUID, psUUID, psExtension, psWord); var PriorState: TParseState; ParseState: TParseState; IDLString: string; pCurrent: pchar; AWord: string; LineNr: integer; pWordStart: pchar; wordchars: set of char; UUIDAttribute: string; CurrentIDL: TIDL; CurrentIDLMember: TIDLMember; CurrentIDLMemberParam: TIDLMemberParameter; IsAttribute, IsReadonly: boolean; IsConst: boolean; IsParamIn, IsParamOut: boolean; IsUnsigned: boolean; function CheckChar(const ACheckForString: string; ASetParseState: TParseState): boolean; begin result := false; if CompareChar(pCurrent^,ACheckForString[1], length(ACheckForString))=0 then begin ParseState := ASetParseState; inc(pcurrent,length(ACheckForString)); result := True; end; end; function CheckChar(const ACheckForString: string; ASetParseState, ASetPriorParseState: TParseState): boolean; begin result := CheckChar(ACheckForString, ASetParseState); if result then PriorState:=ASetPriorParseState; end; function CheckStartWord(ASetParseState, ASetPriorParseState: TParseState; AllowMinus: boolean = false): boolean; begin result := false; wordchars:=['a'..'z','A'..'Z','0'..'9','_']; if AllowMinus then include(wordchars,'-'); if pCurrent^ in wordchars then begin pWordStart:=pCurrent; PriorState:=ASetPriorParseState; ParseState := ASetParseState; inc(pcurrent); result := True; end; end; function CheckEndWord(ASetParseState: TParseState): boolean; var i: integer; begin result := false; if not (pCurrent^ in wordchars) then begin i := pCurrent-pWordStart; SetLength(AWord,i); move(pWordStart^,AWord[1],i); if PriorState = psInterface then CurrentIDL.InterfaceName:=AWord else if PriorState = psInterfaceType then CurrentIDL.InterfaceType:=AWord else if PriorState = psSearchUUID then UUIDAttribute:=AWord else if PriorState = psInterfaceBlockFuncName then CurrentIDLMember.MemberName:=AWord else if PriorState = psInterfaceBlockFuncParamName then CurrentIDLMemberParam.ParamName:=AWord; ParseState := ASetParseState; result := True; end; end; function CheckStartConst: boolean; begin result := CheckChar(idlConstAssign,psConstValue); if Result then begin pWordStart:=pCurrent; ParseState := psConstValue; inc(pcurrent); end; end; function CheckEndConst: boolean; var i: integer; begin result := CheckChar(idlMemberEnd,psInterfaceBlock); if result then begin i := pCurrent-pWordStart-1; SetLength(AWord,i); move(pWordStart^,AWord[1],i); CurrentIDLMember.ConstValue:=AWord; ParseState := psInterfaceBlock; inc(pcurrent); end; end; function CheckInterfaceStart: boolean; begin result := CheckChar(idlInterface, psInterface); if result then begin CurrentIDL := TIDL.Create; AnIdlList.Add(CurrentIDL); CurrentIDL.UUID:=UUIDAttribute; UUIDAttribute:=''; end; end; function CheckFuncStart: boolean; begin result := CheckStartWord(psWord, psInterfaceBlockFuncName); if result then begin CurrentIDLMember := TIDLMember.Create; if Isconst then CurrentIDLMember.MemberType:=mtConst else if IsAttribute then CurrentIDLMember.MemberType:=mtAttribute else CurrentIDLMember.MemberType:=mtFunc; CurrentIDLMember.MemberReadonly:=IsReadonly; IsAttribute:=false; IsConst:=false; IsReadonly:=false; CurrentIDL.members.Add(CurrentIDLMember); end; end; function CheckParamStart: boolean; begin result := CheckStartWord(psWord, psInterfaceBlockFuncParamName); if result then begin CurrentIDLMemberParam := TIDLMemberParameter.Create; if IsParamIn and IsParamOut then CurrentIDLMemberParam.ParamInOutType:=piInOut else if IsParamIn then CurrentIDLMemberParam.ParamInOutType:=piIn else if IsParamOut then CurrentIDLMemberParam.ParamInOutType:=piOut else CurrentIDLMemberParam.ParamInOutType:=piNormal; IsParamIn:=false; IsParamOut:=false; CurrentIDLMember.Params.Add(CurrentIDLMemberParam); end; end; function CheckAttributeStart: boolean; begin result := CheckChar(idlattribute, psInterfaceBlock); if result then IsAttribute := True; end; function CheckConstStart: boolean; begin result := CheckChar(idlconst, psInterfaceBlock); if result then IsConst := True; end; function CheckUnsigned: boolean; begin result := CheckChar(idlUnsigned, ParseState); if result then IsUnsigned := True; end; function CheckAttributeReadOnly: boolean; begin result := CheckChar(idlreadonly, psInterfaceBlock); if result then IsReadonly := True; end; function CheckParamIn: boolean; begin result := CheckChar(idlParamIn, psInterfaceBlockFuncParams); if result then IsParamIn := True; end; function CheckParamOut: boolean; begin result := CheckChar(idlParamOut, psInterfaceBlockFuncParams); if result then IsParamOut := True; end; begin LineNr := 0; ParseState:=psBegin; IDLString:=IDLtext.Text; if length(IDLString)=0 then Exit; IsAttribute:=false; IsReadonly:=false; IsUnsigned:=false; IsConst:=false; IsParamIn:=false; IsParamOut:=false; UUIDAttribute:=''; pCurrent:=@IDLString[1]; while pCurrent^ <> #0 do begin case ParseState of psBegin: begin if not (CheckChar(idlStartMultiLineComment,psMultiLineComment,ParseState) or CheckChar(idlStartExtension,psExtension,ParseState) or CheckInterfaceStart or CheckChar(idlStartIDLAttributesBlock,psIDLAttributes,ParseState) or CheckChar(idlInterface,psInterface)) then inc(pCurrent); end; psMultiLineComment: begin if not (CheckChar(idlEndMultiLineComment,PriorState)) then inc(pCurrent); end; psExtension: begin if not (CheckChar(idlEndExtension,PriorState)) then inc(pCurrent); end; psSingleLineComment: begin if not (CheckChar(idlEndSingleLineComment,PriorState)) then inc(pCurrent); end; psParamAttributeBlock: begin if not (CheckChar(idlEndIDLAttributesBlock,PriorState)) then inc(pCurrent); end; psIDLAttributes: begin if not (CheckChar(idlEndIDLAttributesBlock,psBegin) or CheckChar(idlUUID, psSearchUUID)) then inc(pCurrent); end; psSearchUUID: begin if not (CheckChar(idlStartUUID,psUUID) or CheckChar(idlEndUUID, psIDLAttributes)) then inc(pCurrent); end; psUUID: begin if not CheckStartWord(psWord,psSearchUUID,true) then inc(pCurrent); end; psInterface, psInterfaceType: begin if not (CheckStartWord(psWord,ParseState) or CheckChar(idlInterfaceBlockStart,psInterfaceBlock,ParseState) or CheckChar(idlStartMultiLineComment,psMultiLineComment,ParseState) or CheckChar(idlStartSingleLineComment,psSingleLineComment,ParseState) or CheckChar(idlStartExtension,psExtension,ParseState) or CheckChar(idlInterfaceTypeSeparator, psInterfaceType) or CheckChar(idlInterfaceEnd, psBegin)) then inc(pCurrent); end; psInterfaceBlock: begin if not (CheckChar(idlInterfaceBlockEnd,psInterface) or CheckChar(idlStartMultiLineComment,psMultiLineComment,ParseState) or CheckChar(idlStartExtension,psExtension,ParseState) or CheckChar(idlStartSingleLineComment,psSingleLineComment,ParseState) or CheckChar(idlStartIDLAttributesBlock,psParamAttributeBlock,ParseState) or CheckAttributeStart or CheckAttributeReadOnly or CheckConstStart or CheckUnsigned or CheckFuncStart) then inc(pCurrent) end; psInterfaceBlockFuncName: begin if CurrentIDLMember.ReturnType = '' then begin CurrentIDLMember.ReturnType:=aword; CurrentIDLMember.ReturnTypeUnsigned := IsUnsigned; IsUnsigned:=false; end; if not (CheckStartWord(psWord, psInterfaceBlockFuncName) or CheckChar(idlStartFuncParams,psInterfaceBlockFuncParams) or CheckChar(idlMemberEnd,psInterfaceBlock) or CheckStartConst or CheckChar(idlStartMultiLineComment,psMultiLineComment,ParseState)) then inc(pCurrent) end; psInterfaceBlockFuncParams: begin if not (CheckChar(idlStartMultiLineComment,psMultiLineComment,ParseState) or CheckChar(idlStartIDLAttributesBlock,psParamAttributeBlock,ParseState) or CheckParamIn or CheckParamOut or CheckUnsigned or CheckParamStart or CheckChar(idlEndFuncParams,psInterfaceAfterFuncParams)) then inc(pCurrent) end; psInterfaceAfterFuncParams: begin // voor een definitie als: 'nsIDOMNode setNamedItem(in nsIDOMNode arg) raises(DOMException);' // negeer in dat geval alles na de parameters if not (CheckChar(idlStartMultiLineComment,psMultiLineComment,ParseState) or CheckChar(idlMemberEnd,psInterfaceBlock)) then inc(pCurrent) end; psInterfaceBlockFuncParamName: begin if CurrentIDLMemberParam.ParamType = '' then begin CurrentIDLMemberParam.ParamType:=aword; CurrentIDLMemberParam.ParamTypeUnsigned := IsUnsigned; IsUnsigned:=false; end; if not (CheckStartWord(psWord, psInterfaceBlockFuncParamName) or CheckChar(idlStartMultiLineComment,psMultiLineComment,ParseState) or CheckChar(idlSeparateFuncParams,psInterfaceBlockFuncParams) or CheckChar(idlEndFuncParams,psInterfaceAfterFuncParams)) then inc(pCurrent) end; psConstValue: begin if not (CheckChar(idlStartMultiLineComment,psMultiLineComment,ParseState) or CheckChar(idlStartSingleLineComment,psSingleLineComment,ParseState) or CheckEndConst) then inc(pCurrent) end; psWord: begin if not CheckEndWord(PriorState) then inc(pCurrent); end; end; end; end; { TIDLMember } constructor TIDLMember.Create; begin FParams := TIDLMemberParameterList.create; end; destructor TIDLMember.Destroy; begin FParams.Free; inherited Destroy; end; { TIDL } constructor TIDL.Create; begin Fmembers := TIDLMemberList.create; end; destructor TIDL.Destroy; begin Fmembers.free; inherited Destroy; end; end.
{$Define dyn_unzip32} unit Unzip; { Copyright (c) 2004 headcrash industries. All rights reserved. Author: Gerke Preussner <j3rky@gerke-preussner.de> Updated for Delphi 4 by Alexey Torgashin <atorg@yandex.ru> This file belongs to the InfoZIP UnZip for Delphi Wrapper. Please read the license agreement in the readme.txt that comes with this package. Latest updates can be found at http://www.gerke-preussner.de } interface {* ======================== enums ======================== *} //////////////////// // callback returns //////////////////// type EDllPassword = Longint; EDllPrint = Longint; EDllReplace = Longint; EDllService = Longint; EGrepCmd = Longint; const IZ_PW_ENTERED = 0; // got some PWD string, use/try it IZ_PW_NONE = 1; IZ_PW_CANCEL = -1; // no password available (for this entry) IZ_PW_CANCELALL = -2; // no password, skip any further PWD request IZ_PW_ERROR = 5; // failure (no mem, no tty, ... IDM_REPLACE_NO = 100; // skip this file IDM_REPLACE_TEXT = 101; // open replace dialog? IDM_REPLACE_YES = 102; // overwrite this file IDM_REPLACE_ALL = 103; // always overwrite files IDM_REPLACE_NONE = 104; // never overwrite files IDM_REPLACE_RENAME = 105; // auto rename file IDM_REPLACE_HELP = 106; UZ_ST_CONTINUE = 0; // continue unpacking UZ_ST_BREAK = 1; // cancel unpacking //////////////////// // parameters //////////////////// UZ_GREP_NORMAL = 0; // case insensitive substring search UZ_GREP_NORMALC = 1; // case sensitive substring search UZ_GREP_WORDS = 2; // case insensitive search for whole words UZ_GREP_WORDSC = 3; // case sensitive search for whole words {* ======================== prototypes ======================== *} //////////////////// // callback //////////////////// type DLLMESSAGE = procedure (ucsize, csiz, cfactor, mo, dy, yr, hh, mm: Longword; c: Byte; fname, meth: PChar; crc: Longword; fCrypt: Byte); stdcall; DLLPASSWORD = function (pwbuf: PChar; size: Longint; m, efn: PChar): EDllPassword; stdcall; DLLPRNT = function (buffer: PChar; size: Longword): EDllPrint; stdcall; DLLREPLACE = function (filename: PChar): EDllReplace; stdcall; DLLSERVICE = function (efn: PChar; details: Longword): EDllService; stdcall; DLLSND = procedure; stdcall; {* ======================== structs ======================== *} //////////////////// // USERFUNCTIONS //////////////////// USERFUNCTIONS = packed record print: DLLPRNT; // print callback routine sound: DLLSND; // sound callback routine replace: DLLREPLACE; // replace callback routine password: DLLPASSWORD; // password callback routine SendApplicationMessage: DLLMESSAGE; // message callback routine ServCallBk: DLLSERVICE; // service callback routine TotalSizeComp: Longword; // result: total size of archive TotalSize: Longword; // result: total size of files in the archive CompFactor: Longword; // result: compression factor NumMembers: Longword; // result: number of files in the archive cchComment: Word; // result: length of comment end; //////////////////// // DCL //////////////////// DCL = packed record ExtractOnlyNewer: Longint; // 1 - extract only newer SpaceToUnderscore: Longint; // 1 - convert space to underscore PromptToOverwrite: Longint; // 1 - prompt before overwrite fQuiet: Longint; // 0 - return all messages, 1 = fewer messages, 2 = no messages ncflag: Longint; // 1 - write to stdout ntflag: Longint; // 1 - test zip file nvflag: Longint; // 1 - give a verbose listing nfflag: Longint; // 1 - freshen existing files only nzflag: Longint; // 1 - display a zip file comment ndflag: Longint; // >0 - recreate directories, <2 - skip "../" noflag: Longint; // 1 - over-write all files naflag: Longint; // 1 - convert CR to CRLF nZIflag: Longint; // 1 - verbose zip info C_flag: Longint; // 0 - case sensitive, 1 - case insensitive fPrivilege: Longint; // 1 - ACL, 2 - priv lpszZipFN: PChar; // archive name lpszExtractDir: PChar; // target directory, NULL - current directory end; //////////////////// // UzpBuffer //////////////////// UzpBuffer = packed record strlength: Longword; // length of buffer strptr: PChar; // buffer end; //////////////////// // _version_type //////////////////// _version_type = packed record major: Byte; // major version number minor: Byte; // minor version number patchlevel: Byte; // patch level not_used: Byte; end; //////////////////// // UzpVer //////////////////// UzpVer = packed record structlen: Longword; // length of the struct being passed flag: Longword; // bit 0: is_beta bit 1: uses_zlib betalevel: PChar; // e.g., "g BETA" or "" date: PChar; // e.g., "4 Sep 95" (beta) or "4 September 1995" zlib_version: PChar; // e.g., "0.95" or NULL unzip: _version_type; zipinfo: _version_type; os2dll: _version_type; windll: _version_type; end; PUzpVer = ^UzpVer; //////////////////// // UzpVer2 //////////////////// UzpVer2 = packed record structlen: Longword; // length of the struct being passed flag: Longword; // bit 0: is_beta bit 1: uses_zlib betalevel: array[0..9] of Char; // e.g., "g BETA" or "" date: array[0..19] of Char; // e.g., "4 Sep 95" (beta) or "4 September 1995" zlib_version: array[0..9] of Char; // e.g., "0.95" or NULL unzip: _version_type; zipinfo: _version_type; os2dll: _version_type; windll: _version_type; end; {* ======================== functions ======================== *} //////////////////// // imports //////////////////// {$IFNDEF dyn_unzip32} procedure UzpFreeMemBuffer (var UzpBuffer); stdcall; function UzpVersion: PUzpVer; stdcall; procedure UzpVersion2 (var version: UzpVer2); stdcall; function Wiz_Grep (archive, fname, pattern: PChar; cmd: EGrepCmd; skipbin: Longbool; var ufunc: USERFUNCTIONS): Longint; stdcall; function Wiz_Init (var pG: Pointer; var ufunc: USERFUNCTIONS): LongBool; stdcall; procedure Wiz_NoPrinting (noprint: Longbool); stdcall; function Wiz_SetOpts (var pG: Pointer; var c: DCL): Longbool; stdcall; function Wiz_SingleEntryUnzip (ifnc: Longint; var ifnv: PChar; xfnc: Longint; var xfnv: PChar; var c: DCL; var ufunc: USERFUNCTIONS): Longint; stdcall; function Wiz_Unzip (var pG: Pointer; ifnc: Longint; var ifnv: PChar; xfnc: Longint; var xfnv: PChar): Longint; stdcall; function Wiz_UnzipToMemory (zip, fname: PChar; var ufunc: USERFUNCTIONS; var retstr: UzpBuffer): Longint; stdcall; function Wiz_Validate (archive: PChar; AllCodes: Longint): Longint; stdcall; {$ELSE} PROCUzpFreeMemBuffer = procedure (var UzpBuffer); stdcall; PROCUzpVersion = function: PUzpVer; stdcall; PROCUzpVersion2 = procedure (var version: UzpVer2); stdcall; PROCWiz_Grep = function (archive, fname, pattern: PChar; cmd: EGrepCmd; skipbin: Longbool; var ufunc: USERFUNCTIONS): Longint; stdcall; PROCWiz_Init = function (var pG: Pointer; var ufunc: USERFUNCTIONS): Longbool; stdcall; PROCWiz_NoPrinting = procedure (noprint: Longbool); stdcall; PROCWiz_SetOpts = function (var pG: Pointer; var c: DCL): LongBool; stdcall; PROCWiz_SingleEntryUnzip = function (ifnc: Longint; var ifnv: PChar; xfnc: Longint; var xfnv: PChar; var c: DCL; var ufunc: USERFUNCTIONS): Longint; stdcall; PROCWiz_Unzip = function (var pG: Pointer; ifnc: Longint; var ifnv: PChar; xfnc: Longint; var xfnv: PChar): Longint; stdcall; PROCWiz_UnzipToMemory = function (zip, fname: PChar; var ufunc: USERFUNCTIONS; var retstr: UzpBuffer): Longint; stdcall; PROCWiz_Validate = function (archive: PChar; AllCodes: Longint): Longint; stdcall; {$ENDIF} //////////////////// // tools //////////////////// function Wiz_ErrorToStr (code: Longint): String; {* ======================== consts ======================== *} const //////////////////// // return codes //////////////////// PK_OK = 0; // no error PK_COOL = 0; // no error PK_WARN = 1; // warning error PK_ERR = 2; // error in zipfile PK_BADERR = 3; // severe error in zipfile PK_MEM = 4; // insufficient memory (during initialization) PK_MEM2 = 5; // insufficient memory (password failure) PK_MEM3 = 6; // insufficient memory (file decompression) PK_MEM4 = 7; // insufficient memory (memory decompression) PK_MEM5 = 8; // insufficient memory (not yet used) PK_NOZIP = 9; // zipfile not found PK_PARAM = 10; // bad or illegal parameters specified PK_FIND = 11; // no files found PK_DISK = 50; // disk full PK_EOF = 51; // unexpected EOF IZ_CTRLC = 80; // user hit ^C to terminate IZ_UNSUP = 81; // no files found: all unsup. compr/encrypt. IZ_BADPWD = 82; // wrong password //////////////////// // version flags //////////////////// UZ_VERFLAG_ISBETA = 1; // this version is a beta UZ_VERFLAG_USESZLIB = 2; // this version uses ZLib //////////////////// // misc //////////////////// UNZIP32 = 'unzip32.dll'; implementation {* ======================== imports ======================== *} {$IFNDEF dyn_unzip32} procedure UzpFreeMemBuffer (var UzpBuffer); external UNZIP32 name 'UzpFreeMemBuffer'; function UzpVersion: PUzpVer; external UNZIP32 name 'UzpVersion'; procedure UzpVersion2 (var version: UzpVer2); external UNZIP32 name 'UzpVersion2'; function Wiz_Grep (archive, fname, pattern: PChar; cmd: EGrepCmd; SkipBin: Longbool; var ufunc: USERFUNCTIONS): Longint; external UNZIP32 name 'Wiz_Grep'; function Wiz_Init (var pG: Pointer; var ufunc: USERFUNCTIONS): Longbool; external UNZIP32 name 'Wiz_Init'; procedure Wiz_NoPrinting (noprint: Longbool); external UNZIP32 name 'Wiz_NoPrinting'; function Wiz_SetOpts (var pG: Pointer; var c: DCL): LongBool; external UNZIP32 name 'Wiz_SetOpts'; function Wiz_SingleEntryUnzip (ifnc: Longint; var ifnv: PChar; xfnc: Longint; var xfnv: PChar; var c: DCL; var ufunc: USERFUNCTIONS): Longint; external UNZIP32 name 'Wiz_SingleEntryUnzip'; function Wiz_Unzip (var pG: Pointer; ifnc: Longint; var ifnv: PChar; xfnc: Longint; var xfnv: PChar): Longint; external UNZIP32 name 'Wiz_Unzip'; function Wiz_UnzipToMemory (zip, fname: PChar; var ufunc: USERFUNCTIONS; var retstr: UzpBuffer): Longint; external UNZIP32 name 'Wiz_UnzipToMemory'; function Wiz_Validate (archive: PChar; AllCodes: Longint): Longint; external UNZIP32 name 'Wiz_Validate'; {$ENDIF} {* ======================== tools ======================== *} function Wiz_ErrorToStr (code: Longint): String; begin case code of PK_OK: Result := 'Operation completed successfully'; PK_WARN: Result := 'Warnings occurred on one or more files'; PK_ERR: Result := 'Errors occurred on one or more files'; PK_BADERR: Result := 'Sever error in archive'; PK_MEM, PK_MEM2, PK_MEM3, PK_MEM4, PK_MEM5: Result := 'Insufficient memory'; PK_NOZIP: Result := 'Archive not found'; PK_PARAM: Result := 'Bad or illegal parameters specified'; PK_FIND: Result := 'No files found'; PK_DISK: Result := 'Disk full'; PK_EOF: Result := 'Unexpected end of file'; IZ_CTRLC: Result := 'Canceled by user'; IZ_UNSUP: Result := 'No files found: All unsupported'; IZ_BADPWD: Result := 'No files found: Bad password'; else Result := 'Unknown error'; end; end; end.
unit LocalOrdersFrame; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, ComCtrls, ToolWin, LocalOrdersUnit, Menus, ActnList, ImgList, Buttons; type TFrameLocalOrders = class(TFrame) toolbarLocOrders: TToolBar; tbLoadList: TToolButton; tbSaveList: TToolButton; tbApply: TToolButton; panRight: TPanel; lvOrdersList: TListView; Splitter1: TSplitter; gbInfo: TGroupBox; gbReply: TGroupBox; gbText: TGroupBox; memoText: TMemo; memoReply: TMemo; lbFromText: TLabel; lbToText: TLabel; lbFrom: TLabel; lbTo: TLabel; gbList: TGroupBox; ActionList1: TActionList; actNew: TAction; actApply: TAction; pmLocOrdersList: TPopupMenu; actListLoad: TAction; actListSave: TAction; mNewItem: TMenuItem; mApply: TMenuItem; btnSelectReply: TButton; bbtnSignOn: TBitBtn; ilSignOnIcons: TImageList; ToolButton1: TToolButton; ToolButton2: TToolButton; procedure actNewExecute(Sender: TObject); procedure lvOrdersListChange(Sender: TObject; Item: TListItem; Change: TItemChange); procedure btnSignOnClick(Sender: TObject); private { Private declarations } ItemsList: TLocOrderList; SelectedItem: TLocOrderItem; procedure ReadSelectedItem(); procedure WriteSelectedItem(); procedure RefreshItemsList(SelectedOnly: boolean = false); procedure NewItem(); procedure LoadList(); procedure SaveList(); public { Public declarations } constructor Create(AOwner: TComponent); override; destructor Destroy(); override; end; implementation uses Main, MainFunc; const iIconSign: integer = 1; const iIconUnSign: integer = 0; const sCaptSign: string = 'Подписать'; const sCaptUnSign: string = 'Отменить'; {$R *.dfm} //=========================================== constructor TFrameLocalOrders.Create(AOwner: TComponent); begin inherited Create(AOwner); self.Align:=alClient; if not Assigned(ItemsList) then ItemsList:=TLocOrderList.Create(); self.LoadList(); end; destructor TFrameLocalOrders.Destroy(); begin ItemsList.Free(); inherited Destroy(); end; //=========================================== // List operations //=========================================== procedure TFrameLocalOrders.RefreshItemsList(SelectedOnly: boolean = false); var Item: TLocOrderItem; tn: TListItem; i: integer; begin if SelectedOnly then begin if not Assigned(SelectedItem) then Exit; for i:=0 to lvOrdersList.Items.Count-1 do begin Item:=TLocOrderItem(lvOrdersList.Items[i].Data); if Item=SelectedItem then begin tn:=lvOrdersList.Items[i]; tn.SubItems.Clear(); if Item.Signed then tn.Caption:='S' else tn.Caption:=''; tn.SubItems.Add(Item.From); Exit; end; end; Exit; end; lvOrdersList.Items.Clear(); ItemsList.Sort(); for i:=0 to ItemsList.Count-1 do begin Item:=TLocOrderItem(ItemsList[i]); tn:=lvOrdersList.Items.Add(); //tn.Caption:=''; if Item.Signed then tn.Caption:='S'; tn.SubItems.Add(Item.From); tn.Data:=Item; if Item=SelectedItem then begin tn.Selected:=true; tn.Focused:=true; end; end; end; procedure TFrameLocalOrders.LoadList(); begin lvOrdersList.Items.Clear(); SelectedItem:=nil; ItemsList.Clear(); ItemsList.LoadList(); RefreshItemsList(); end; procedure TFrameLocalOrders.SaveList(); begin ItemsList.SaveList(); end; procedure TFrameLocalOrders.NewItem(); var Item: TLocOrderItem; tn: TListItem; i: integer; begin Item:=TLocOrderItem.Create(); Item.Dest:='кому-то'; Item.Author:=conf['UserName']; Item.Timestamp:=Now(); self.ItemsList.Add(Item); tn:=lvOrdersList.Items.Add(); tn.Data:=Item; self.SelectedItem:=Item; ReadSelectedItem(); end; procedure TFrameLocalOrders.ReadSelectedItem(); var Item: TLocOrderItem; Avail: boolean; i: integer; s: string; Image: TBitmap; begin if not Assigned(self.SelectedItem) then Exit; Item:=self.SelectedItem; // Set availability Avail:=(conf['UserName']=Item.Author); memoText.Enabled:=Avail; memoReply.Enabled:=Avail; lbFrom.Caption:=Item.From; lbTo.Caption:=Item.Dest; memoText.Text:=Item.Text; memoReply.Text:=Item.Reply; if Item.Signed then i:=iIconUnSign else i:=iIconSign; if Item.Signed then s:=sCaptUnSign else s:=sCaptSign; Image:=bbtnSignOn.Glyph; ilSignOnIcons.GetBitmap(i, Image); bbtnSignOn.Glyph:=Image; bbtnSignOn.Caption:=s; //lbPeriod.Caption:=''+DateTimeToStr(Item.BeginDate)+' - '+DateTimeToStr(Item.EndDate); //TextEditor.RawText:=Item.Text; //TextEditor.LoadFromFile(self.MsgBoardList.FileName+'.data\'+IntToStr(Item.ID)+'.rtf'); end; procedure TFrameLocalOrders.WriteSelectedItem(); begin if not Assigned(self.SelectedItem) then Exit; //self.SelectedMBItem.Author:=glUserName; self.SelectedItem.Text:=memoText.Text; //TextEditor.SaveToFile(self.MsgBoardList.FileName+'.data\'+IntToStr(self.SelectedMBItem.ID)+'.rtf'); self.SelectedItem.Reply:=memoReply.Text; //if TextEditor.Lines.Count>0 then self.SelectedMBItem.Desc:=TextEditor.Lines[0]; RefreshItemsList(true); end; //=========================================== // Action handlers //=========================================== procedure TFrameLocalOrders.actNewExecute(Sender: TObject); begin if Sender = actNew then begin self.NewItem(); end else if Sender = actApply then begin self.WriteSelectedItem(); end else if Sender = actListLoad then begin self.LoadList(); end else if Sender = actListSave then begin self.SaveList(); end; end; procedure TFrameLocalOrders.lvOrdersListChange(Sender: TObject; Item: TListItem; Change: TItemChange); var AItem: TLocOrderItem; begin if not Assigned(Item) then Exit; if not Assigned(Item.Data) then Exit; AItem:=TLocOrderItem(Item.Data); if AItem=SelectedItem then Exit; WriteSelectedItem(); SelectedItem:=AItem; ReadSelectedItem() end; procedure TFrameLocalOrders.btnSignOnClick(Sender: TObject); var i: integer; s: string; Image: TBitmap; begin if not Assigned(self.SelectedItem) then Exit; if self.SelectedItem.Signed = false then begin self.SelectedItem.Signed:=true; i:=iIconUnSign; s:=sCaptUnSign; end else begin self.SelectedItem.Signed:=false; i:=iIconSign; s:=sCaptSign; end; Image:=bbtnSignOn.Glyph; ilSignOnIcons.GetBitmap(i, Image); bbtnSignOn.Glyph:=Image; bbtnSignOn.Caption:=s; WriteSelectedItem(); end; end.
{ Subroutine SST_SCOPE_OLD * * Set the parent of the current scope as the new current scope. } module sst_SCOPE_OLD; define sst_scope_old; %include 'sst2.ins.pas'; procedure sst_scope_old; {pop back to parent scope} begin sst_scope_p := sst_scope_p^.parent_p; sst_names_p := sst_scope_p; end;
unit DataObjectOptimizationsResponseUnit; interface uses REST.Json.Types, GenericParametersUnit, DataObjectUnit; type TDataObjectOptimizationsResponse = class(TGenericParameters) private [JSONName('optimizations')] FOptimizations: TArray<TDataObject>; public property Optimizations: TArray<TDataObject> read FOptimizations write FOptimizations; end; implementation end.
module AVLTREE ; (**************************************************************) (* *) (* Portierung des AVLTREE Moduls nach Pascal *) (* Soll funktionieren fuer beliebige AVL-Baeume *) (* Key- und Datendefinition kommt "von aussen" *) (* *) (* Bernd Oppolzer - 07.2018 *) (* *) (**************************************************************) (*$A+ *) (**************************************************************) type PTR_AVLNODE = -> AVLNODE ; AVLNODE = record MAGIC : CHAR ( 8 ) ; // always 'AVLNODEX' PVORG : PTR_AVLNODE ; // Vorgaenger PLN : PTR_AVLNODE ; // linker Nachfolger PRN : PTR_AVLNODE ; // rechter Nachfolger BALANCE : INTEGER ; // balance lt. Wirth KEY : VOIDPTR ; // Schluessel KEYLEN : INTEGER ; // Keylen if deep copy OBJ : VOIDPTR ; // eigentliche Info OBJLEN : INTEGER ; // Objlen if deep copy end ; PTR_AVLLINK = -> AVLLINK ; AVLLINK = record // only used for avlprint ZEICHNEN : CHAR ; // storage for character NEXT : PTR_AVLLINK ; // to print the tree PREV : PTR_AVLLINK ; // linkage lines end ; PTR_AVLC = -> AVLC_ENTRY ; AVLC_ENTRY = record MAGIC : CHAR ( 8 ) ; // always 'AVLCACHE' CNAME : CHAR ( 8 ) ; // Name of Cache COUNT : INTEGER ; // Nbr of entries PTREE : PTR_AVLNODE ; // ptr to tree end ; local function AVLSRCH_INTERN ( SKEY : VOIDPTR ; // look SKEYLEN : INTEGER ; // for var POBJ : VOIDPTR ; // comments var POBJLEN : VOIDPTR ; // at var GEFUNDEN : BOOLEAN ; // function var PP : PTR_AVLNODE ; // AVLSRCH var HCHANGED : BOOLEAN ; // below EINFUEGEN : BOOLEAN ; // MODUS : CHAR ; // function AVLCOMP // look ( X1 : VOIDPTR ; // for L1 : INTEGER ; // comments X2 : VOIDPTR ; // at L2 : INTEGER ) // function : INTEGER ) // AVLSRCH : PTR_AVLNODE ; // below (********************************************************************) (* *) (* Suchfunktion im AVL-Baum (fuegt auch ein, falls noetig) *) (* *) (* SKEY = Zeiger auf Suchargument fuer Suche und ggf. Einfg. *) (* SKEYLEN = deep copy, wenn skeylen > 0 - dann wird der Key *) (* beim Einfuegen in den AVL-Baum kopiert (ALLOC) *) (* ansonsten wird nur der Pointer gespeichert *) (* POBJ = pointer to OBJ is returned from tree node *) (* POBJLEN = pointer to OBJLEN field is returned from tree node *) (* GEFUNDEN = if true then found, otherwise inserted or NIL ret. *) (* PP = actual AVL-tree, may be changed on return *) (* HCHANGED = init with false, may change during recursion *) (* EINFUEGEN = set to true, if insert on not found condition *) (* MODUS = type of search (= search or > search) *) (* AVLCOMP = Vergleichsfunktion fuer Suchargumente, muss *) (* Werte zurueckgeben wie memcmp (1, -1, 0) *) (* *) (* The AVL tree may be used to record pointers only; in this *) (* case KEYLEN and OBJLEN are zero. Or it may be use to record *) (* the contents as well. In this case, SKEYLEN should be *) (* specified as a positive value. On insert, the key value *) (* is copied into the AVL tree (using ALLOC and MEMCPY), *) (* and on free, the storage is freed. *) (* *) (* Same goes for POBJ and POBJLEN, but AVLSRCH does not do *) (* anything to the OBJ fields; it simply returns their *) (* addresses and leaves it up to the caller to enter *) (* the values and the length there. When freeing the tree, *) (* the obj values are freed by AVLFREE, if objlen *) (* contains a nonzero value. *) (* *) (* The AVLCOMP function gets the lengths of the two operands *) (* as parameters, but with a pointer-only AVL tree, the *) (* length parameters will be zero, and the AVLCOMP is *) (* supposed to know the length in this case, anyway, and *) (* to do the comparison correctly (maybe constant length). *) (* *) (********************************************************************) var P1 : PTR_AVLNODE ; P2 : PTR_AVLNODE ; P : PTR_AVLNODE ; PX : PTR_AVLNODE ; PRES : PTR_AVLNODE ; PVORG_SAVE : PTR_AVLNODE ; begin (* AVLSRCH_INTERN *) P := PP ; if P = NIL then begin GEFUNDEN := FALSE ; /************************************************************/ /* Der Knoten existiert noch nicht, der gesuchte Schluessel */ /* wurde also nicht gefunden. */ /************************************************************/ if EINFUEGEN then begin /************************************************************/ /* Es wird ein neuer Knoten mit diesem Schluessel angelegt */ /* und in den Baum eingefuegt. */ /************************************************************/ P := ALLOC ( SIZEOF ( AVLNODE ) ) ; with P -> do begin MAGIC := 'AVLNODEX' ; PVORG := NIL ; PLN := NIL ; PRN := NIL ; BALANCE := 0 ; KEY := NIL ; KEYLEN := 0 ; OBJ := NIL ; OBJLEN := 0 ; end (* with *) ; if SKEYLEN > 0 then begin /************************************************************/ /* deep copy */ /************************************************************/ P -> . KEY := ALLOC ( SKEYLEN ) ; MEMCPY ( P -> . KEY , SKEY , SKEYLEN ) ; P -> . KEYLEN := SKEYLEN ; end (* then *) else P -> . KEY := SKEY ; HCHANGED := TRUE ; PRES := P ; POBJ := ADDR ( PRES -> . OBJ ) ; POBJLEN := ADDR ( PRES -> . OBJLEN ) ; end (* then *) else begin PRES := NIL ; POBJ := NIL ; POBJLEN := NIL ; end (* else *) ; PP := P ; AVLSRCH_INTERN := PRES ; return ; end (* then *) ; if AVLCOMP ( SKEY , SKEYLEN , P -> . KEY , P -> . KEYLEN ) < 0 then begin /************************************************************/ /* Der gesuchte Schluessel ist kleiner als der Schluessel */ /* des aktuellen Knotens. Es wird also im linken Teilbaum */ /* weitergesucht (rekursiver Aufruf). Nachdem das passiert */ /* ist, wird geprueft, ob sich der linke Teilbaum durch ein */ /* eventuelles Einfuegen verlaengert hat. */ /************************************************************/ if P -> . PLN = NIL then /***********************************************************/ /* new in 02.2020: */ /* if modus = '>', data is not returned */ /* instead the key of the found entry (which may be */ /* greater than the requested key) is returned in the */ /* pobj fields. Another request is needed to retrieve */ /* the data. */ /***********************************************************/ if MODUS = '>' then begin GEFUNDEN := TRUE ; PRES := P ; POBJ := ADDR ( PRES -> . KEY ) ; POBJLEN := ADDR ( PRES -> . KEYLEN ) ; if EINFUEGEN then HCHANGED := FALSE ; PP := P ; AVLSRCH_INTERN := PRES ; return end (* then *) ; PRES := AVLSRCH_INTERN ( SKEY , SKEYLEN , POBJ , POBJLEN , GEFUNDEN , P -> . PLN , HCHANGED , EINFUEGEN , MODUS , AVLCOMP ) ; if EINFUEGEN and HCHANGED then begin PVORG_SAVE := P -> . PVORG ; /**************************************************/ /* Falls der linke Teilbaum laenger geworden ist: */ /**************************************************/ case P -> . BALANCE of 1 : begin /********************************************/ /* bisher war der rechte Teilbaum laenger */ /********************************************/ P -> . BALANCE := 0 ; HCHANGED := FALSE ; end (* tag/ca *) ; 0 : begin /*********************************************/ /* bisher waren beide Teilbaeume gleich lang */ /*********************************************/ P -> . BALANCE := - 1 ; end (* tag/ca *) ; otherwise begin /***************************************************/ /* Der linke Teilbaum war ohnehin schon laenger. */ /* Jetzt muss der Baum umorganisiert werden! */ /* Zunaechst wird geprueft, ob beim linken Nach- */ /* folger der linke Teilbaum laenger ist (Fall A) */ /* oder der rechte (Fall B). Danach werden die */ /* Verbindungszeiger neu gesetzt. */ /***************************************************/ P1 := P -> . PLN ; if P1 -> . BALANCE = - 1 then begin /************************************/ /* Fall A */ /************************************/ PX := P1 -> . PRN ; P -> . PLN := PX ; if PX <> NIL then PX -> . PVORG := P ; P1 -> . PRN := P ; P -> . PVORG := P1 ; P -> . BALANCE := 0 ; P := P1 ; end (* then *) else begin /************************************/ /* Fall B */ /************************************/ P2 := P1 -> . PRN ; PX := P2 -> . PLN ; P1 -> . PRN := PX ; if PX <> NIL then PX -> . PVORG := P1 ; P2 -> . PLN := P1 ; P1 -> . PVORG := P2 ; PX := P2 -> . PRN ; P -> . PLN := PX ; if PX <> NIL then PX -> . PVORG := P ; P2 -> . PRN := P ; P -> . PVORG := P2 ; if P2 -> . BALANCE = - 1 then P -> . BALANCE := 1 else P -> . BALANCE := 0 ; if P2 -> . BALANCE = 1 then P1 -> . BALANCE := - 1 else P1 -> . BALANCE := 0 ; P := P2 ; end (* else *) ; P -> . BALANCE := 0 ; HCHANGED := FALSE ; end (* otherw *) end (* case *) ; if P -> . PLN <> NIL then P -> . PLN -> . PVORG := P ; P -> . PVORG := PVORG_SAVE ; end (* then *) end (* then *) else if AVLCOMP ( SKEY , SKEYLEN , P -> . KEY , P -> . KEYLEN ) > 0 then begin /************************************************************/ /* Der gesuchte Schluessel ist groesser als der Schluessel */ /* des aktuellen Knotens. Es wird also im rechten Teilbaum */ /* weitergesucht (rekursiver Aufruf). Nachdem das passiert */ /* ist, wird geprueft ob sich der rechte Teilbaum durch ein */ /* eventuelles Einfuegen verlaengert hat. */ /************************************************************/ PRES := AVLSRCH_INTERN ( SKEY , SKEYLEN , POBJ , POBJLEN , GEFUNDEN , P -> . PRN , HCHANGED , EINFUEGEN , MODUS , AVLCOMP ) ; if EINFUEGEN and HCHANGED then begin PVORG_SAVE := P -> . PVORG ; /***************************************************/ /* Falls der rechte Teilbaum laenger geworden ist: */ /***************************************************/ case P -> . BALANCE of - 1 : begin /********************************************/ /* bisher war der linke Teilbaum laenger */ /********************************************/ P -> . BALANCE := 0 ; HCHANGED := FALSE ; end (* tag/ca *) ; 0 : begin /*********************************************/ /* bisher waren beide Teilbaeume gleich lang */ /*********************************************/ P -> . BALANCE := 1 ; end (* tag/ca *) ; otherwise begin /***************************************************/ /* Der rechte Teilbaum war ohnehin schon laenger. */ /* Jetzt muss der Baum umorganisiert werden! */ /* Zunaechst wird geprueft, ob beim rechten Nach- */ /* folger der rechte Teilbaum laenger ist (Fall A) */ /* oder der linke (Fall B). Danach werden die */ /* Verbindungszeiger neu gesetzt. */ /***************************************************/ P1 := P -> . PRN ; if P1 -> . BALANCE = 1 then begin /************************************/ /* Fall A */ /************************************/ PX := P1 -> . PLN ; P -> . PRN := PX ; if PX <> NIL then PX -> . PVORG := P ; P1 -> . PLN := P ; P -> . PVORG := P1 ; P -> . BALANCE := 0 ; P := P1 ; end (* then *) else begin /************************************/ /* Fall B */ /************************************/ P2 := P1 -> . PLN ; PX := P2 -> . PRN ; P1 -> . PLN := PX ; if PX <> NIL then PX -> . PVORG := P1 ; P2 -> . PRN := P1 ; P1 -> . PVORG := P2 ; PX := P2 -> . PLN ; P -> . PRN := PX ; if PX <> NIL then PX -> . PVORG := P ; P2 -> . PLN := P ; P -> . PVORG := P2 ; if P2 -> . BALANCE = 1 then P -> . BALANCE := - 1 else P -> . BALANCE := 0 ; if P2 -> . BALANCE = - 1 then P1 -> . BALANCE := 1 else P1 -> . BALANCE := 0 ; P := P2 ; end (* else *) ; P -> . BALANCE := 0 ; HCHANGED := FALSE ; end (* otherw *) end (* case *) ; if P -> . PRN <> NIL then P -> . PRN -> . PVORG := P ; P -> . PVORG := PVORG_SAVE ; end (* then *) end (* then *) else begin GEFUNDEN := TRUE ; /***********************************************************/ /* Schluessel gefunden, diesen Knoten zurueckgeben */ /***********************************************************/ PRES := P ; POBJ := ADDR ( PRES -> . OBJ ) ; POBJLEN := ADDR ( PRES -> . OBJLEN ) ; if EINFUEGEN then HCHANGED := FALSE ; end (* else *) ; PP := P ; AVLSRCH_INTERN := PRES ; end (* AVLSRCH_INTERN *) ; function AVLSRCH ( SKEY : VOIDPTR ; // ptr to key SKEYLEN : INTEGER ; // keylen (if deep copy) var POBJ : VOIDPTR ; // ptr to obj ptr var POBJLEN : VOIDPTR ; // ptr to objlen field var GEFUNDEN : BOOLEAN ; // true if found var PP : PTR_AVLNODE ; // tree pointer var HCHANGED : BOOLEAN ; // height changed EINFUEGEN : BOOLEAN ; // if insert then true function AVLCOMP // passed as parameter: ( X1 : VOIDPTR ; // compare func for L1 : INTEGER ; // nodes in avl tree X2 : VOIDPTR ; // integer return values L2 : INTEGER ) // like memcmp : INTEGER ) : PTR_AVLNODE ; begin (* AVLSRCH *) if PP <> NIL then if PP -> . MAGIC <> 'AVLNODEX' then begin WRITELN ( '+++ AVLSRCH: parameter PP invalid (MAGIC field not ok)' ) ; EXIT ( 2001 ) ; end (* then *) ; AVLSRCH := AVLSRCH_INTERN ( SKEY , SKEYLEN , POBJ , POBJLEN , GEFUNDEN , PP , HCHANGED , EINFUEGEN , '=' , AVLCOMP ) ; end (* AVLSRCH *) ; function AVLSRCHX ( SKEY : VOIDPTR ; // ptr to key SKEYLEN : INTEGER ; // keylen (if deep copy) var POBJ : VOIDPTR ; // ptr to obj ptr var POBJLEN : VOIDPTR ; // ptr to objlen field var GEFUNDEN : BOOLEAN ; // true if found var PP : PTR_AVLNODE ; // tree pointer var HCHANGED : BOOLEAN ; // height changed EINFUEGEN : BOOLEAN ; // if insert then true MODUS : CHAR ; // = or > (type of search) function AVLCOMP // passed as parameter: ( X1 : VOIDPTR ; // compare func for L1 : INTEGER ; // nodes in avl tree X2 : VOIDPTR ; // integer return values L2 : INTEGER ) // like memcmp : INTEGER ) : PTR_AVLNODE ; begin (* AVLSRCHX *) if PP <> NIL then if PP -> . MAGIC <> 'AVLNODEX' then begin WRITELN ( '+++ AVLSRCH: parameter PP invalid (MAGIC field not ok)' ) ; EXIT ( 2001 ) ; end (* then *) ; AVLSRCHX := AVLSRCH_INTERN ( SKEY , SKEYLEN , POBJ , POBJLEN , GEFUNDEN , PP , HCHANGED , EINFUEGEN , MODUS , AVLCOMP ) ; end (* AVLSRCHX *) ; function AVLGET ( MODUS : CHAR ; // mode = F(irst), N(ext) START : PTR_AVLNODE ; // starting position var RESULT : PTR_AVLNODE ; // new position var PKEY : VOIDPTR ; // pointer to key var KEYLEN : INTEGER ; // keylen var POBJ : VOIDPTR ; // pointer to obj var OBJLEN : INTEGER ) // objlen : INTEGER ; // zero, if OK (********************************************************************) (* *) (* suche nachfolger im baum: *) (* *) (* vorwaerts: *) (* *) (* wenn rechter nachfolger da, *) (* gehe dorthin, und *) (* dann immer linker nachfolger, bis keiner mehr da ist. *) (* fertig *) (* *) (* wenn kein rechter nachfolger da: *) (* wenn kein vorgaenger da: ende der iteration *) (* wenn vorgaenger da: *) (* ist aktueller knoten linker nachfolger des vorgaengers? *) (* ja: vorgaenger nehmen und fertig. *) (* nein: weiter mit vorgaenger *) (* *) (* rueckwaerts: *) (* *) (* wenn linker nachfolger da, *) (* gehe dorthin, und *) (* dann immer rechter nachfolger, bis keiner mehr da ist. *) (* fertig *) (* *) (* wenn kein linker nachfolger da: *) (* wenn kein vorgaenger da: ende der iteration *) (* wenn vorgaenger da: *) (* ist aktueller knoten rechter nachfolger des vorgaengers? *) (* ja: vorgaenger nehmen und fertig. *) (* nein: weiter mit vorgaenger *) (* *) (* erster und letzter ist einfach: *) (* *) (* nach oben und dann ganz links oder ganz rechts runter *) (* *) (*------------------------------------------------------------------*) (* *) (* Die folgende Funktion navigiert auf dem Baum; *) (* dabei kann wie ueblich first, last, next, previous *) (* mitgegeben werden (F,L,N,P). *) (* *) (* Fuer start muss irgendein Knoten des Baums mitgegeben *) (* werden (bei F und L geht es am schnellsten mit dem *) (* root-Knoten, aber alle anderen gehen auch). Bei N und P *) (* wird der jeweils naechste bzw. vorhergehende zurueck- *) (* gegeben, ansonsten der erste bzw. letzte ueberhaupt. *) (* *) (*------------------------------------------------------------------*) (* *) (* erstellt 12.2009 - OPP *) (* *) (********************************************************************) var RES : PTR_AVLNODE ; P : PTR_AVLNODE ; RC : INTEGER ; RESCHECK : PTR_AVLNODE ; CHECK_RESULT : BOOLEAN ; begin (* AVLGET *) RES := NIL ; PKEY := NIL ; POBJ := NIL ; KEYLEN := - 1 ; OBJLEN := - 1 ; CHECK_RESULT := FALSE ; RC := 0 ; if START = NIL then RC := 2 else if START -> . MAGIC <> 'AVLNODEX' then begin WRITELN ( '+++ AVLGET: parameter START invalid (MAGIC field not ok)' ) ; EXIT ( 2001 ) ; end (* then *) ; if RC = 0 then begin while START -> . PVORG <> NIL do START := START -> . PVORG ; if MODUS = 'N' then begin if RESULT = NIL then MODUS := 'F' else CHECK_RESULT := TRUE end (* then *) ; if MODUS = 'P' then begin if RESULT = NIL then MODUS := 'L' else CHECK_RESULT := TRUE end (* then *) end (* then *) ; if CHECK_RESULT then begin if RESULT -> . MAGIC <> 'AVLNODEX' then begin WRITELN ( '+++ AVLGET: parameter RESULT invalid (MAGIC field not ok)' ) ; EXIT ( 2001 ) ; end (* then *) ; RESCHECK := RESULT ; while RESCHECK -> . PVORG <> NIL do RESCHECK := RESCHECK -> . PVORG ; if RESCHECK <> START then RC := 3 end (* then *) ; case MODUS of 'F' : if RC = 0 then begin while START -> . PLN <> NIL do START := START -> . PLN ; RES := START ; end (* then *) ; 'L' : if RC = 0 then begin while START -> . PRN <> NIL do START := START -> . PRN ; RES := START ; end (* then *) ; 'N' : if RC = 0 then begin P := RESULT -> . PRN ; if P <> NIL then begin while P -> . PLN <> NIL do P := P -> . PLN ; RES := P ; end (* then *) else begin P := RESULT ; while TRUE do begin if P -> . PVORG = NIL then begin RC := 1 ; break ; end (* then *) ; if P = P -> . PVORG -> . PLN then begin RES := P -> . PVORG ; break ; end (* then *) ; P := P -> . PVORG ; end (* while *) end (* else *) end (* then *) ; 'P' : if RC = 0 then begin P := RESULT -> . PLN ; if P <> NIL then begin while P -> . PRN <> NIL do P := P -> . PRN ; RES := P ; end (* then *) else begin P := RESULT ; while TRUE do begin if P -> . PVORG = NIL then begin RC := 1 ; break ; end (* then *) ; if P = P -> . PVORG -> . PRN then begin RES := P -> . PVORG ; break ; end (* then *) ; P := P -> . PVORG ; end (* while *) end (* else *) end (* then *) ; otherwise begin RC := - 1 ; end (* otherw *) end (* case *) ; RESULT := RES ; if RES <> NIL then begin PKEY := RES -> . KEY ; KEYLEN := RES -> . KEYLEN ; POBJ := RES -> . OBJ ; OBJLEN := RES -> . OBJLEN ; end (* then *) ; AVLGET := RC ; end (* AVLGET *) ; procedure AVLPRINT ( P : PTR_AVLNODE ; // tree to print var AUSGFILE : TEXT ; // output file EINRUECK : INTEGER ; // indentation count PV : PTR_AVLLINK ; // nil on top level call RICHTUNG : CHAR ; // blank on top level call procedure AVLPKEY // passed as parameter: ( var F : TEXT ; // procedure to print P : VOIDPTR ) ) ; // one key value (********************************************************************) (* *) (* Drucken AVL-Baum *) (* *) (* P = Zeiger auf AVL-Baum *) (* AUSGFILE = Textfile, auf den gedruckt werden soll *) (* EINRUECK = Anzahl Einrueckzeichen pro Ebene *) (* AVLPKEY = Prozedur zum Drucken eines Knotens *) (* PV = Verbindungsinformation, bei Top Level NIL mitgeben *) (* RICHTUNG = Teilbauminfo, bei Top Level Blank mitgeben *) (* *) (********************************************************************) const SW = '-' ; SS = '|' ; var I : INTEGER ; VN : AVLLINK ; PVL : PTR_AVLLINK ; static PVFIRST : PTR_AVLLINK ; begin (* AVLPRINT *) if P <> NIL then begin /*********************************************/ /* Rechten Teilbaum ausgeben. Dazu */ /* Verbindungsstruktur an die */ /* verkettete Liste dranhaengen */ /*********************************************/ if PV <> NIL then PV -> . NEXT := ADDR ( VN ) else PVFIRST := ADDR ( VN ) ; VN . PREV := PV ; VN . ZEICHNEN := 'N' ; VN . NEXT := NIL ; AVLPRINT ( P -> . PRN , AUSGFILE , EINRUECK , ADDR ( VN ) , 'R' , AVLPKEY ) ; /*********************************************************/ /* Schreiben der Key-Information und evtl. not- */ /* wendiger Verbindungszeichen */ /*********************************************************/ if PV <> NIL then begin WRITE ( AUSGFILE , ' ' : EINRUECK ) ; PVL := PVFIRST ; while PVL <> PV do begin if PVL -> . ZEICHNEN = 'J' then WRITE ( AUSGFILE , SS : EINRUECK ) else WRITE ( AUSGFILE , ' ' : EINRUECK ) ; PVL := PVL -> . NEXT end (* while *) end (* then *) ; //************************************************************ // if (p -> pvorg <> NIL) // printf ("%05d/", p -> pvorg -> key); // else // printf (" NIL/"); //************************************************************ AVLPKEY ( AUSGFILE , P -> . KEY ) ; if PV <> NIL then if RICHTUNG = 'R' then PV -> . ZEICHNEN := 'J' else PV -> . ZEICHNEN := 'N' ; if P -> . PLN <> NIL then VN . ZEICHNEN := 'J' else VN . ZEICHNEN := 'N' ; if ( P -> . PRN <> NIL ) or ( P -> . PLN <> NIL ) then begin /********************************************************/ /* Falls es Nachfolge-Knoten gibt, horizontale */ /* Verbindungszeichen ausgeben */ /********************************************************/ WRITE ( AUSGFILE , ' ' ) ; for I := 1 to EINRUECK - 2 do WRITE ( AUSGFILE , SW ) ; WRITE ( AUSGFILE , SS ) ; end (* then *) ; WRITELN ( AUSGFILE ) ; /*******************************************************/ /* Verbindungszeichen ausgeben */ /*******************************************************/ if FALSE then begin VN . NEXT := NIL ; WRITE ( AUSGFILE , ' ' : EINRUECK ) ; PVL := PVFIRST ; while PVL <> PV do begin if PVL -> . ZEICHNEN = 'J' then WRITE ( AUSGFILE , SS : EINRUECK ) else WRITE ( AUSGFILE , ' ' : EINRUECK ) ; PVL := PVL -> . NEXT end (* while *) ; WRITELN ( AUSGFILE ) ; end (* then *) ; /*********************************/ /* Linken Teilbaum ausgeben */ /*********************************/ AVLPRINT ( P -> . PLN , AUSGFILE , EINRUECK , ADDR ( VN ) , 'L' , AVLPKEY ) end (* then *) end (* AVLPRINT *) ; procedure AVLFREE ( P : PTR_AVLNODE ) ; begin (* AVLFREE *) if P <> NIL then begin AVLFREE ( P -> . PLN ) ; AVLFREE ( P -> . PRN ) ; if P -> . KEYLEN > 0 then if P -> . KEY <> NIL then FREE ( P -> . KEY ) ; if P -> . OBJLEN > 0 then if P -> . OBJ <> NIL then FREE ( P -> . OBJ ) ; FREE ( P ) ; end (* then *) end (* AVLFREE *) ; function AVLCACHE ( FUNKCODE : CHAR ( 8 ) ; // Funktionscode PHANDLE : VOIDPTR ; // Cachehandle var SEQKEY : VOIDPTR ; // seq. Keyposition, var PKEY : VOIDPTR ; // Zeiger auf Key var LKEY : INTEGER ; // Laenge Key var PDAT : VOIDPTR ; // Zeiger auf Daten var LDAT : INTEGER ) // Laenge Daten : INTEGER ; (********************************************************************) (* *) (* Create and manage Cache Areas using AVL-Trees *) (* *) (* FUNKCODE = function code, see below *) (* PHANDLE = Cache Handle (once the cache has been created) *) (* SEQKEY = used when processing a cache sequentially *) (* PKEY = pointer to cache key *) (* LKEY = length of cache key *) (* PDAT = pointer to cache data *) (* LDAT = length of cache data *) (* *) (* Function CREATE (also used to locate existing cache): *) (* *) (* PKEY points to 8 byte cache name *) (* LKEY is not used *) (* *) (* if successful, PDAT returns cache handle *) (* LDAT returns 20 (= current sizeof cache handle) *) (* function result is zero, when (empty) cache is created *) (* 4, when existing cache has been located, *) (* other return codes are errors *) (* *) (* Function GET: *) (* *) (* PHANDLE: handle for cache (returned by CREATE) *) (* PKEY / LKEY: identifies key *) (* PDAT / LDAT: to return the data, if key found *) (* *) (* function result is zero, when data is found *) (* and 8, if data is not found; *) (* 20, if phandle is NIL or invalid *) (* *) (* Function PUT: *) (* *) (* PHANDLE: handle for cache (returned by CREATE) *) (* PKEY / LKEY: identifies key *) (* PDAT / LDAT: identifies data *) (* *) (* function result is zero, when data is inserted into *) (* cache, and 4, when data is replaced (freed and inserted); *) (* 20, if phandle is NIL or invalid *) (* *) (* Function GFIRST: *) (* *) (* PHANDLE: handle for cache (returned by CREATE) *) (* SEQKEY: stores the cache reading position between calls *) (* PKEY / LKEY: to return the key, if entry found *) (* PDAT / LDAT: to return the data, if entry found *) (* *) (* function result is zero, when data is found *) (* and 8, if data is not found (empty cache) *) (* 20, if phandle is NIL or invalid *) (* *) (* Function GNEXT: *) (* *) (* PHANDLE: handle for cache (returned by CREATE) *) (* SEQKEY: stores the cache reading position between calls *) (* PKEY / LKEY: to return the key, if entry found *) (* PDAT / LDAT: to return the data, if entry found *) (* *) (* function result is zero, when data is found *) (* and 8, if data is not found (no next cache entry) *) (* 20, if phandle is NIL or invalid *) (* *) (* note: calling GNEXT with a SEQKEY of NIL is the same *) (* as calling GFIRST *) (* *) (* Function TRACE: *) (* *) (* PHANDLE: handle for cache (returned by CREATE) *) (* PKEY: should be NIL or point to an 8 byte cache name *) (* all other parameters have no meaning *) (* *) (* the cache is printed; the key and data is treated *) (* as characters strings of the stored length *) (* *) (* function result is zero, when data is found *) (* and 8, if data is not found (empty cache) *) (* 20, if phandle is NIL or invalid *) (* *) (********************************************************************) type PVOIDPTR = -> VOIDPTR ; var CMDX : INTEGER ; RC : INTEGER ; I : INTEGER ; PCACHENAME : -> CHAR ( 8 ) ; PPAVLC : -> PTR_AVLC ; PAVLC : PTR_AVLC ; POBJ : PVOIDPTR ; POBJLEN : -> INTEGER ; PKEYNEU : PVOIDPTR ; LKEYNEU : -> INTEGER ; PLEN : -> INTEGER ; PRES : VOIDPTR ; GEFUNDEN : BOOLEAN ; HCHANGED : BOOLEAN ; PBAUMX : VOIDPTR ; RCFOUND : INTEGER ; PKEY_LOCAL : VOIDPTR ; LKEY_LOCAL : INTEGER ; PDAT_LOCAL : VOIDPTR ; LDAT_LOCAL : INTEGER ; SEQKEY_LOCAL : VOIDPTR ; PC254 : -> CHAR ( 254 ) ; static PCACHEDIR : VOIDPTR ; const COMMAND_COUNT = 10 ; COMMANDS : array [ 1 .. COMMAND_COUNT ] of CHAR ( 8 ) = ( 'CREATE' , 'GET' , 'PUT' , 'GFIRST' , 'GNEXT' , 'TRACE' , 'DELETE' , 'SHOWALL' , 'START' , 'CLEAR' ) ; function DIRCOMP ( X1 : VOIDPTR ; L1 : INTEGER ; X2 : VOIDPTR ; L2 : INTEGER ) : INTEGER ; //**************************************************************** // compare function for AVL tree key values (here: char (8) keys) // this function is passed as a parameter to avlsrch //**************************************************************** var S1 : CHAR ( 8 ) ; SP1 : -> CHAR ( 8 ) ; S2 : CHAR ( 8 ) ; SP2 : -> CHAR ( 8 ) ; begin (* DIRCOMP *) //********************************************** // this coding simply to avoid warning message // about parameters not used :-) //********************************************** if FALSE then if L1 <> L2 then begin L1 := 8 ; L2 := 8 end (* then *) ; SP1 := X1 ; SP2 := X2 ; S1 := SP1 -> ; S2 := SP2 -> ; if S1 > S2 then DIRCOMP := 1 else if S1 < S2 then DIRCOMP := - 1 else DIRCOMP := 0 ; end (* DIRCOMP *) ; function CACHECOMP ( X1 : VOIDPTR ; L1 : INTEGER ; X2 : VOIDPTR ; L2 : INTEGER ) : INTEGER ; //**************************************************************** // compare function for AVL tree key values // here: arbitrary structures of varying length // this function is passed as a parameter to avlsrch //**************************************************************** begin (* CACHECOMP *) if L1 > L2 then CACHECOMP := 1 else if L1 < L2 then CACHECOMP := - 1 else CACHECOMP := MEMCMP ( X1 , X2 , L1 ) ; end (* CACHECOMP *) ; begin (* AVLCACHE *) CMDX := 0 ; for I := 1 to COMMAND_COUNT do if FUNKCODE = COMMANDS [ I ] then begin CMDX := I ; break end (* then *) ; case CMDX of 1 : begin // CREATE (or LOCATE) PDAT := NIL ; LDAT := 0 ; PCACHENAME := PKEY ; HCHANGED := FALSE ; PRES := AVLSRCH ( PCACHENAME , 8 , PPAVLC , PLEN , GEFUNDEN , PCACHEDIR , HCHANGED , TRUE , DIRCOMP ) ; if PRES = NIL then RC := 12 else begin if GEFUNDEN then begin PAVLC := PPAVLC -> ; RC := 4 end (* then *) else begin RC := 0 ; PPAVLC -> := ALLOC ( SIZEOF ( AVLC_ENTRY ) ) ; PAVLC := PPAVLC -> ; with PAVLC -> do begin MAGIC := 'AVLCACHE' ; CNAME := PCACHENAME -> ; COUNT := 0 ; PTREE := NIL ; end (* with *) ; PLEN -> := SIZEOF ( AVLC_ENTRY ) ; end (* else *) ; PDAT := PAVLC ; LDAT := PLEN -> ; end (* else *) end (* tag/ca *) ; 2 : begin repeat // GET - one time loop PAVLC := PHANDLE ; //************************************************************ // check handle and return if handle nok //************************************************************ if PAVLC = NIL then begin RC := 20 ; break end (* then *) ; if PAVLC -> . MAGIC <> 'AVLCACHE' then begin RC := 20 ; break end (* then *) ; //************************************************************ // search for key and return data if found //************************************************************ PBAUMX := PAVLC -> . PTREE ; HCHANGED := FALSE ; PRES := AVLSRCH ( PKEY , LKEY , POBJ , POBJLEN , GEFUNDEN , PBAUMX , HCHANGED , FALSE , CACHECOMP ) ; if not GEFUNDEN then begin PDAT := NIL ; LDAT := 0 ; RC := 8 ; end (* then *) else begin PDAT := POBJ -> ; LDAT := POBJLEN -> ; RC := 0 ; end (* else *) until TRUE end (* tag/ca *) ; 3 : begin repeat // PUT - one time loop PAVLC := PHANDLE ; //************************************************************ // check handle and return if handle nok //************************************************************ if PAVLC = NIL then begin RC := 20 ; break end (* then *) ; if PAVLC -> . MAGIC <> 'AVLCACHE' then begin RC := 20 ; break end (* then *) ; //************************************************************ // search for key and insert if notfound //************************************************************ PBAUMX := PAVLC -> . PTREE ; HCHANGED := FALSE ; PRES := AVLSRCH ( PKEY , LKEY , POBJ , POBJLEN , GEFUNDEN , PBAUMX , HCHANGED , TRUE , CACHECOMP ) ; if not GEFUNDEN then begin //************************************************************ // insert data if notfound //************************************************************ PAVLC -> . COUNT := PAVLC -> . COUNT + 1 ; POBJ -> := ALLOC ( LDAT ) ; POBJLEN -> := LDAT ; MEMCPY ( POBJ -> , PDAT , LDAT ) ; PAVLC -> . PTREE := PBAUMX ; RC := 0 ; end (* then *) else begin //************************************************************ // replace data if notfound //************************************************************ FREE ( POBJ -> ) ; POBJ -> := ALLOC ( LDAT ) ; POBJLEN -> := LDAT ; MEMCPY ( POBJ -> , PDAT , LDAT ) ; RC := 4 ; end (* else *) until TRUE end (* tag/ca *) ; 4 : begin repeat // GFIRST - one time loop PAVLC := PHANDLE ; //************************************************************ // check handle and return if handle nok //************************************************************ if PAVLC = NIL then begin RC := 20 ; break end (* then *) ; if PAVLC -> . MAGIC <> 'AVLCACHE' then begin RC := 20 ; break end (* then *) ; //************************************************************ // search for first key using AVLGET / F //************************************************************ PBAUMX := PAVLC -> . PTREE ; RCFOUND := AVLGET ( 'F' , PBAUMX , SEQKEY , PKEY , LKEY , PDAT , LDAT ) ; if RCFOUND <> 0 then begin PKEY := NIL ; LKEY := 0 ; PDAT := NIL ; LDAT := 0 ; RC := 8 ; end (* then *) else begin RC := 0 ; end (* else *) until TRUE end (* tag/ca *) ; 5 : begin repeat // GNEXT - one time loop PAVLC := PHANDLE ; //************************************************************ // check handle and return if handle nok //************************************************************ if PAVLC = NIL then begin RC := 20 ; break end (* then *) ; if PAVLC -> . MAGIC <> 'AVLCACHE' then begin RC := 20 ; break end (* then *) ; //************************************************************ // search for next key using AVLGET / N //************************************************************ PBAUMX := PAVLC -> . PTREE ; RCFOUND := AVLGET ( 'N' , PBAUMX , SEQKEY , PKEY , LKEY , PDAT , LDAT ) ; if RCFOUND <> 0 then begin PKEY := NIL ; LKEY := 0 ; PDAT := NIL ; LDAT := 0 ; RC := 8 ; end (* then *) else begin RC := 0 ; end (* else *) until TRUE end (* tag/ca *) ; 6 : begin repeat // TRACE - one time loop PAVLC := PHANDLE ; //************************************************************ // check handle and return if handle nok //************************************************************ if PAVLC = NIL then begin RC := 20 ; break end (* then *) ; if PAVLC -> . MAGIC <> 'AVLCACHE' then begin RC := 20 ; break end (* then *) ; //************************************************************ // output the whole cache using AVLGET //************************************************************ WRITELN ; PC254 := PKEY ; if PC254 <> NIL then WRITELN ( 'Print CACHE - Cachename = ' , SUBSTR ( PC254 -> , 1 , 8 ) ) else WRITELN ( 'Print CACHE - Cachename = *unknown*' ) ; WRITELN ( 'Number of entries = ' , PAVLC -> . COUNT : 1 ) ; WRITELN ( '----------------------------------------' ) ; RC := 8 ; SEQKEY_LOCAL := NIL ; PBAUMX := PAVLC -> . PTREE ; while TRUE do begin RCFOUND := AVLGET ( 'N' , PBAUMX , SEQKEY_LOCAL , PKEY_LOCAL , LKEY_LOCAL , PDAT_LOCAL , LDAT_LOCAL ) ; if RCFOUND <> 0 then break ; WRITELN ; PC254 := PKEY_LOCAL ; WRITELN ( 'key: ' , SUBSTR ( PC254 -> , 1 , LKEY_LOCAL ) ) ; PC254 := PDAT_LOCAL ; WRITELN ( 'dat: ' , SUBSTR ( PC254 -> , 1 , LDAT_LOCAL ) ) ; RC := 0 ; end (* while *) ; WRITELN ; until TRUE end (* tag/ca *) ; 7 : begin end (* tag/ca *) ; 8 : begin end (* tag/ca *) ; 9 : begin repeat // START - one time loop PAVLC := PHANDLE ; //************************************************************ // check handle and return if handle nok //************************************************************ if PAVLC = NIL then begin RC := 20 ; break end (* then *) ; if PAVLC -> . MAGIC <> 'AVLCACHE' then begin RC := 20 ; break end (* then *) ; //************************************************************ // search for key and return data if found //************************************************************ PBAUMX := PAVLC -> . PTREE ; HCHANGED := FALSE ; PRES := AVLSRCHX ( PKEY , LKEY , PKEYNEU , LKEYNEU , GEFUNDEN , PBAUMX , HCHANGED , FALSE , '>' , CACHECOMP ) ; if not GEFUNDEN then begin PDAT := NIL ; LDAT := 0 ; RC := 8 ; end (* then *) else begin PKEY := PKEYNEU -> ; LKEY := LKEYNEU -> ; PRES := AVLSRCHX ( PKEY , LKEY , POBJ , POBJLEN , GEFUNDEN , PBAUMX , HCHANGED , FALSE , '=' , CACHECOMP ) ; PDAT := POBJ -> ; LDAT := POBJLEN -> ; RC := 0 ; end (* else *) until TRUE end (* tag/ca *) ; 10 : begin repeat // START - one time loop PAVLC := PHANDLE ; //************************************************************ // check handle and return if handle nok //************************************************************ if PAVLC = NIL then begin RC := 20 ; break end (* then *) ; if PAVLC -> . MAGIC <> 'AVLCACHE' then begin RC := 20 ; break end (* then *) ; //************************************************************ // search for key and return data if found //************************************************************ PBAUMX := PAVLC -> . PTREE ; AVLFREE ( PBAUMX ) ; PAVLC -> . PTREE := NIL ; PAVLC -> . COUNT := 0 ; until TRUE end (* tag/ca *) ; otherwise begin end (* otherw *) end (* case *) ; AVLCACHE := RC ; end (* AVLCACHE *) ; begin (* HAUPTPROGRAMM *) end (* HAUPTPROGRAMM *) .
{ *************************************************************************** } { } { This file is part of the XPde project } { } { Copyright (c) 2002 Jose Leon Serna <ttm@xpde.com> } { } { 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 2 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; see the file COPYING. If not, write to } { the Free Software Foundation, Inc., 59 Temple Place - Suite 330, } { Boston, MA 02111-1307, USA. } { } { *************************************************************************** } unit uXPColorSelector; interface uses SysUtils, Types, Classes, QGraphics, QControls, QForms, QDialogs, uXPColorDialog, uGraphics; type TXPColorSelector = class(TGraphicControl) private FColor: TColor; FDown: boolean; FOnChange: TNotifyEvent; procedure SetColor(const Value: TColor); procedure SetDown(const Value: boolean); procedure SetOnChange(const Value: TNotifyEvent); { Private declarations } protected { Protected declarations } procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; public { Public declarations } procedure Paint;override; constructor Create(AOwner:TComponent);override; destructor Destroy;override; published { Published declarations } property Color: TColor read FColor write SetColor; property Down: boolean read FDown write SetDown; property OnChange:TNotifyEvent read FOnChange write SetOnChange; end; procedure Register; implementation procedure Register; begin RegisterComponents('XPde', [TXPColorSelector]); end; { TXPColorSelector } constructor TXPColorSelector.Create(AOwner: TComponent); begin inherited; FColor:=clNone; width:=75; height:=21; end; destructor TXPColorSelector.Destroy; begin inherited; end; procedure TXPColorSelector.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited; Down:=true; SetCaptureControl(self); end; procedure TXPColorSelector.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var p: TPoint; mr: TModalResult; begin inherited; Down:=false; SetCaptureControl(nil); with TXPColorDialog.create(application) do begin selectedColor:=FColor; p.x:=self.boundsrect.left; p.y:=self.boundsrect.bottom; p:=self.parent.ClientToScreen(p); if (p.y+height)>screen.height then begin p.x:=self.boundsrect.left; p.y:=self.BoundsRect.Top; p:=self.parent.ClientToScreen(p); p.y:=p.y-height; end; if (p.x+width)>screen.width then begin p.x:=screen.width-width; end; left:=p.x; top:=p.y; try mr:=showmodal; if mr=mrOk then self.Color:=selectedcolor; if mr=mrAll then begin with TColorDialog.create(application) do begin try color:=self.color; if execute then begin self.color:=color; end; finally free; end; end; end; finally free; end; end; end; procedure TXPColorSelector.Paint; var x,y:integer; d: integer; begin canvas.brush.color:=clButton; r3d(canvas,clientrect,false,not FDown,true); d:=0; if FDown then d:=1; canvas.pen.color:=clBlack; canvas.brush.color:=FColor; canvas.rectangle(rect(4+d,4+d,clientrect.right-15+d,clientrect.bottom-4+d)); canvas.pen.color:=clBtnShadow; canvas.moveto(clientrect.right-12+d,4+d); canvas.lineto(clientrect.right-12+d,clientrect.bottom-5+d); canvas.pen.color:=clBtnHighLight; canvas.moveto(clientrect.right-11+d,4+d); canvas.lineto(clientrect.right-11+d,clientrect.bottom-5+d); x:=(clientrect.right-9)+d; y:=((height-3) div 2)+d; canvas.Pen.Color:=clBlack; with Canvas do begin moveto(x,y); lineto(x+4,y); moveto(x+1,y+1); lineto(x+3,y+1); moveto(x+2,y+2); lineto(x+2,y+2); end; end; procedure TXPColorSelector.SetColor(const Value: TColor); begin if FColor<>Value then begin FColor := Value; paint; if assigned(FonChange) then FOnChange(self); end; end; procedure TXPColorSelector.SetDown(const Value: boolean); begin if FDown<>Value then begin FDown := Value; paint; end; end; procedure TXPColorSelector.SetOnChange(const Value: TNotifyEvent); begin FOnChange := Value; end; end.
unit http_helpers; interface uses System.JSON, http_intf; function badRequest(const AError: TJSONObject): IHttpResponse; function serverError: IHttpResponse; function OK(const Value: TJSONObject): IHttpResponse; implementation function badRequest(const AError: TJSONObject): IHttpResponse; begin result := THttpResponse.New.statusCode(400).body(AError); end; function serverError: IHttpResponse; begin result := THttpResponse.New.statusCode(500) // .body(TJSONObject.Create.AddPair('error', 'Internal Server Error')); end; function OK(const Value: TJSONObject): IHttpResponse; begin result := THttpResponse.New.statusCode(200).body(Value); end; end.
unit uDBImages; interface uses Windows, Messages, Classes, Controls, Graphics, DB, DBCtrls, Forms; type TImageType = (itUnknown, itBitmap, itJPG, itICO, itPNG); TImageTypes = set of TImageType; TpDBImage = class(TCustomControl) private FDataLink: TFieldDataLink; FPicture: TPicture; FBorderStyle: TBorderStyle; FAutoDisplay: Boolean; FStretch: Boolean; FCenter: Boolean; FPictureLoaded: Boolean; FQuickDraw: Boolean; FImageType: TImageType; procedure DataChange(Sender: TObject); function GetDataField: string; function GetDataSource: TDataSource; function GetField: TField; function GetReadOnly: Boolean; procedure PictureChanged(Sender: TObject); procedure SetAutoDisplay(Value: Boolean); procedure SetBorderStyle(Value: TBorderStyle); procedure SetCenter(Value: Boolean); procedure SetDataField(const Value: string); procedure SetDataSource(Value: TDataSource); procedure SetPicture(Value: TPicture); procedure SetReadOnly(Value: Boolean); procedure SetStretch(Value: Boolean); procedure UpdateData(Sender: TObject); procedure CMGetDataLink(var Message: TMessage); message CM_GETDATALINK; procedure CMEnter(var Message: TCMEnter); message CM_ENTER; procedure CMExit(var Message: TCMExit); message CM_EXIT; procedure CMTextChanged(var Message: TMessage); message CM_TEXTCHANGED; procedure WMLButtonDown(var Message: TWMLButtonDown); message WM_LBUTTONDOWN; procedure WMLButtonDblClk(var Message: TWMLButtonDblClk); message WM_LBUTTONDBLCLK; procedure WMCut(var Message: TMessage); message WM_CUT; procedure WMCopy(var Message: TMessage); message WM_COPY; procedure WMPaste(var Message: TMessage); message WM_PASTE; procedure WMSize(var Message: TMessage); message WM_SIZE; protected procedure CreateParams(var Params: TCreateParams); override; function GetPalette: HPALETTE; override; procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure KeyPress(var Key: Char); override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure Paint; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure CopyToClipboard; procedure CutToClipboard; function ExecuteAction(Action: TBasicAction): Boolean; override; procedure LoadPicture(DrawPicture: TPicture = nil); procedure PasteFromClipboard; function UpdateAction(Action: TBasicAction): Boolean; override; function GetImageType: TImageType; property Field: TField read GetField; property Picture: TPicture read FPicture write SetPicture; published property Align; property Anchors; property AutoDisplay: Boolean read FAutoDisplay write SetAutoDisplay default True; property BorderStyle: TBorderStyle read FBorderStyle write SetBorderStyle default bsSingle; property Center: Boolean read FCenter write SetCenter default True; property Color; property Constraints; property Ctl3D; property DataField: string read GetDataField write SetDataField; property DataSource: TDataSource read GetDataSource write SetDataSource; property DragCursor; property DragKind; property DragMode; property Enabled; property Font; property ParentColor default False; property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupMenu; property ReadOnly: Boolean read GetReadOnly write SetReadOnly default False; property QuickDraw: Boolean read FQuickDraw write FQuickDraw default True; property ShowHint; property Stretch: Boolean read FStretch write SetStretch default False; property TabOrder; property TabStop default True; property Visible; property OnClick; property OnContextPopup; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDock; property OnEndDrag; property OnEnter; property OnExit; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDock; property OnStartDrag; end; function TypeImageInStream(Stream: TStream): TImageType; procedure Register; implementation uses Clipbrd, Vcl.Imaging.Jpeg, Types, Vcl.Imaging.pngimage; type TSign = array [0 .. 2] of Char; TCursorOrIcon = packed record Reserved: Word; wType: Word; Count: Word; end; const rc3_StockIcon = 0; rc3_Icon = 1; function TypeImageInStream(Stream: TStream): TImageType; const // JpegSign:TSign=('я', 'Ш', 'я', 'а', #0, #16, 'J', 'F', 'I', 'F'); JpegSign: TSign = (#255, #216, #255); PNGSign: TSign = (#137, #80, #73); var OldPos: integer; sign: TSign; CI: TCursorOrIcon; begin Result := itUnknown; OldPos := Stream.Position; try Stream.Position := 0; Stream.ReadBuffer(sign[0], 3); if (sign[0] = 'B') and (sign[1] = 'M') then Result := itBitmap else if JpegSign = sign then Result := itJPG else if PNGSign = sign then Result := itPNG else begin Stream.Position := 0; Stream.ReadBuffer(CI, SizeOf(CI)); if (CI.wType in [rc3_StockIcon, rc3_Icon]) then Result := itICO end; finally Stream.Position := OldPos; end; end; constructor TpDBImage.Create(AOwner: TComponent); begin inherited Create(AOwner); ControlStyle := ControlStyle + [csOpaque, csReplicatable]; if not NewStyleControls then ControlStyle := ControlStyle + [csFramed]; Width := 105; Height := 105; TabStop := True; ParentColor := False; FPicture := TPicture.Create; FPicture.OnChange := PictureChanged; FBorderStyle := bsSingle; FAutoDisplay := True; FCenter := True; FDataLink := TFieldDataLink.Create; FDataLink.Control := Self; FDataLink.OnDataChange := DataChange; FDataLink.OnUpdateData := UpdateData; FQuickDraw := True; end; destructor TpDBImage.Destroy; begin FPicture.Free; FDataLink.Free; FDataLink := nil; inherited Destroy; end; function TpDBImage.GetDataSource: TDataSource; begin Result := FDataLink.DataSource; end; procedure TpDBImage.SetDataSource(Value: TDataSource); begin if not(FDataLink.DataSourceFixed and (csLoading in ComponentState)) then FDataLink.DataSource := Value; if Value <> nil then Value.FreeNotification(Self); end; function TpDBImage.GetDataField: string; begin Result := FDataLink.FieldName; end; procedure TpDBImage.SetDataField(const Value: string); begin FDataLink.FieldName := Value; end; function TpDBImage.GetReadOnly: Boolean; begin Result := FDataLink.ReadOnly; end; procedure TpDBImage.SetReadOnly(Value: Boolean); begin FDataLink.ReadOnly := Value; end; function TpDBImage.GetField: TField; begin Result := FDataLink.Field; end; function TpDBImage.GetPalette: HPALETTE; begin Result := 0; if FPicture.Graphic is TBitmap then Result := TBitmap(FPicture.Graphic).Palette; end; procedure TpDBImage.SetAutoDisplay(Value: Boolean); begin if FAutoDisplay <> Value then begin FAutoDisplay := Value; if Value then LoadPicture; end; end; procedure TpDBImage.SetBorderStyle(Value: TBorderStyle); begin if FBorderStyle <> Value then begin FBorderStyle := Value; RecreateWnd; end; end; procedure TpDBImage.SetCenter(Value: Boolean); begin if FCenter <> Value then begin FCenter := Value; Invalidate; end; end; procedure TpDBImage.SetPicture(Value: TPicture); begin FPicture.Assign(Value); end; procedure TpDBImage.SetStretch(Value: Boolean); begin if FStretch <> Value then begin FStretch := Value; Invalidate; end; end; function TpDBImage.GetImageType: TImageType; begin Result := FImageType end; procedure TpDBImage.Paint; var Size: TSize; R: TRect; S: string; DrawPict: TPicture; Form: TCustomForm; Pal: HPALETTE; proporciaImage: double; proporciaSelf: double; stretchRect: TRect; delta: integer; begin with Canvas do begin Brush.Style := bsSolid; Brush.Color := Color; if FPictureLoaded or (csPaintCopy in ControlState) then begin DrawPict := TPicture.Create; Pal := 0; try if (csPaintCopy in ControlState) and Assigned(FDataLink.Field) and FDataLink.Field.IsBlob then begin // FPictureLoaded:=False; LoadPicture(DrawPict); // DrawPict.Assign(FDataLink.Field); if DrawPict.Graphic is TBitmap then DrawPict.Bitmap.IgnorePalette := QuickDraw; end else begin DrawPict.Assign(Picture); if Focused and (DrawPict.Graphic <> nil) and (DrawPict.Graphic.Palette <> 0) then begin { Control has focus, so realize the bitmap palette in foreground } Pal := SelectPalette(Handle, DrawPict.Graphic.Palette, False); RealizePalette(Handle); end; end; if Stretch then if (DrawPict.Graphic = nil) or DrawPict.Graphic.Empty then FillRect(ClientRect) else begin stretchRect := ClientRect; if DrawPict.Graphic.Width <> 0 then proporciaImage := DrawPict.Graphic.Height / DrawPict.Graphic.Width else proporciaImage := 0; if Width <> 0 then proporciaSelf := (stretchRect.Bottom - stretchRect.Top) / (stretchRect.Right - stretchRect.Left) else proporciaSelf := 0; if (proporciaSelf <> 0) and (proporciaImage <> 0) then begin if proporciaSelf > proporciaImage then begin // За счет высоты stretchRect.Bottom := stretchRect.Top + Trunc((stretchRect.Right - stretchRect.Left) * proporciaImage); delta := ((ClientRect.Bottom - ClientRect.Top) - (stretchRect.Bottom - stretchRect.Top)) div 2; Inc(stretchRect.Top, delta); Inc(stretchRect.Bottom, delta); FillRect(Rect(ClientRect.Left, ClientRect.Top, ClientRect.Right, stretchRect.Top)); FillRect(Rect(ClientRect.Left, stretchRect.Bottom, ClientRect.Right, ClientRect.Bottom)); end else begin // За счет ширины stretchRect.Right := stretchRect.Left + Trunc(1 / (proporciaImage / (stretchRect.Bottom - stretchRect.Top))); delta := ((ClientRect.Right - ClientRect.Left) - (stretchRect.Right - stretchRect.Left)) div 2; Inc(stretchRect.Right, delta); Inc(stretchRect.Left, delta); FillRect(Rect(ClientRect.Left, ClientRect.Top, stretchRect.Left, ClientRect.Bottom)); FillRect(Rect(stretchRect.Right, ClientRect.Top, ClientRect.Right, ClientRect.Bottom)); end; end; StretchDraw(stretchRect, DrawPict.Graphic) // StretchDraw(ClientRect, DrawPict.Graphic) end else begin SetRect(R, 0, 0, DrawPict.Width, DrawPict.Height); if Center then OffsetRect(R, (ClientWidth - DrawPict.Width) div 2, (ClientHeight - DrawPict.Height) div 2); StretchDraw(R, DrawPict.Graphic); ExcludeClipRect(Handle, R.Left, R.Top, R.Right, R.Bottom); FillRect(ClientRect); SelectClipRgn(Handle, 0); end; finally if Pal <> 0 then SelectPalette(Handle, Pal, True); DrawPict.Free; end; end else begin Font := Self.Font; if FDataLink.Field <> nil then S := FDataLink.Field.DisplayLabel else S := Name; S := '(' + S + ')'; Size := TextExtent(S); R := ClientRect; TextRect(R, (R.Right - Size.cx) div 2, (R.Bottom - Size.cy) div 2, S); end; Form := GetParentForm(Self); if (Form <> nil) and (Form.ActiveControl = Self) and not(csDesigning in ComponentState) and not(csPaintCopy in ControlState) then begin Brush.Color := clWindowFrame; FrameRect(ClientRect); end; end; end; procedure TpDBImage.PictureChanged(Sender: TObject); begin if FPictureLoaded then FDataLink.Modified; FPictureLoaded := True; Invalidate; end; procedure TpDBImage.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if (Operation = opRemove) and (FDataLink <> nil) and (AComponent = DataSource) then DataSource := nil; end; procedure TpDBImage.LoadPicture(DrawPicture: TPicture = nil); var StreamValue: TMemoryStream; Jpg: TJPEGImage; png : TPngImage; Ic: TIcon; Reload: Boolean; begin if not Assigned(FDataLink.Field) then begin FImageType := itUnknown; Exit; end; Reload := DrawPicture <> nil; if not Reload then begin DrawPicture := Picture; end; if (not FPictureLoaded or Reload) and FDataLink.Field.IsBlob then begin if (not FDataLink.Field.IsBlob and FDataLink.Field.IsNull) or (TBlobField(FDataLink.Field).BlobSize = 0) then DrawPicture.Assign(FDataLink.Field) else begin begin StreamValue := TMemoryStream.Create; try TBlobField(FDataLink.Field).SaveToStream(StreamValue); StreamValue.Position := 0; case TypeImageInStream(StreamValue) of itBitmap: begin FImageType := itBitmap; DrawPicture.Assign(FDataLink.Field); end; itJPG: begin FImageType := itJPG; Jpg := TJPEGImage.Create; try Jpg.LoadFromStream(StreamValue); DrawPicture.Assign(Jpg) finally Jpg.Free; end; end; itICO: begin FImageType := itICO; Ic := TIcon.Create; try Ic.LoadFromStream(StreamValue); DrawPicture.Assign(Ic) finally Ic.Free; end end; itPNG: begin FImageType := itPNG; png := TPngImage.Create; try png.LoadFromStream(StreamValue); DrawPicture.Assign(png) finally png.Free; end; end; end; // case finally StreamValue.Free; end; end; end; end; end; procedure TpDBImage.DataChange(Sender: TObject); begin Picture.Graphic := nil; FPictureLoaded := False; if FAutoDisplay then LoadPicture; end; procedure TpDBImage.UpdateData(Sender: TObject); begin if Picture.Graphic is TBitmap then FDataLink.Field.Assign(Picture.Graphic) else FDataLink.Field.Clear; end; procedure TpDBImage.CopyToClipboard; begin if Picture.Graphic <> nil then Clipboard.Assign(Picture); end; procedure TpDBImage.CutToClipboard; begin if Picture.Graphic <> nil then if FDataLink.Edit then begin CopyToClipboard; Picture.Graphic := nil; end; end; procedure TpDBImage.PasteFromClipboard; begin if Clipboard.HasFormat(CF_BITMAP) and FDataLink.Edit then Picture.Bitmap.Assign(Clipboard); end; procedure TpDBImage.CreateParams(var Params: TCreateParams); begin inherited CreateParams(Params); with Params do begin if FBorderStyle = bsSingle then if NewStyleControls and Ctl3D then ExStyle := ExStyle or WS_EX_CLIENTEDGE else Style := Style or WS_BORDER; WindowClass.Style := WindowClass.Style and not(CS_HREDRAW or CS_VREDRAW); end; end; procedure TpDBImage.KeyDown(var Key: Word; Shift: TShiftState); begin inherited KeyDown(Key, Shift); case Key of VK_INSERT: if ssShift in Shift then PasteFromClipboard else if ssCtrl in Shift then CopyToClipboard; VK_DELETE: if ssShift in Shift then CutToClipboard; end; end; procedure TpDBImage.KeyPress(var Key: Char); begin inherited KeyPress(Key); case Key of ^X: CutToClipboard; ^C: CopyToClipboard; ^V: PasteFromClipboard; #13: LoadPicture; #27: FDataLink.Reset; end; end; procedure TpDBImage.CMGetDataLink(var Message: TMessage); begin Message.Result := integer(FDataLink); end; procedure TpDBImage.CMEnter(var Message: TCMEnter); begin Invalidate; { Draw the focus marker } inherited; end; procedure TpDBImage.CMExit(var Message: TCMExit); begin try if Assigned(DataSource) and Assigned(DataSource.DataSet) and (DataSource.DataSet.State in [dsInsert, dsEdit]) then FDataLink.UpdateRecord; except SetFocus; raise; end; Invalidate; { Erase the focus marker } inherited; end; procedure TpDBImage.CMTextChanged(var Message: TMessage); begin inherited; if not FPictureLoaded then Invalidate; end; procedure TpDBImage.WMLButtonDown(var Message: TWMLButtonDown); begin if TabStop and CanFocus then SetFocus; inherited; end; procedure TpDBImage.WMLButtonDblClk(var Message: TWMLButtonDblClk); begin LoadPicture; inherited; end; procedure TpDBImage.WMCut(var Message: TMessage); begin CutToClipboard; end; procedure TpDBImage.WMCopy(var Message: TMessage); begin CopyToClipboard; end; procedure TpDBImage.WMPaste(var Message: TMessage); begin PasteFromClipboard; end; procedure TpDBImage.WMSize(var Message: TMessage); begin inherited; Invalidate; end; function TpDBImage.ExecuteAction(Action: TBasicAction): Boolean; begin Result := inherited ExecuteAction(Action) or (FDataLink <> nil) and FDataLink.ExecuteAction(Action); end; function TpDBImage.UpdateAction(Action: TBasicAction): Boolean; begin Result := inherited UpdateAction(Action) or (FDataLink <> nil) and FDataLink.UpdateAction(Action); end; procedure Register; begin RegisterComponents('Data Controls', [TpDBImage]); end; end.
unit MdiChilds.FmLatinValidator; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, MdiChilds.CustomDialog, JvComponentBase, JvDragDrop, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.ComCtrls, ActionHandler, MdiChilds.ProgressForm, ComObj; type TFmLatinValidator = class(TFmProcess) pcMain: TPageControl; tsFiles: TTabSheet; lvFiles: TListView; JvDragDrop: TJvDragDrop; OpenDialog: TOpenDialog; procedure JvDragDropDrop(Sender: TObject; Pos: TPoint; Value: TStrings); private procedure AnalizeFile(AFileName: string); procedure AnalizeCell(Cell: OleVariant); function isValidWord(Word: string): Boolean; function HasLatin(Word: string): Boolean; function HasCyr(Word: string): Boolean; protected procedure DoOk(Sender: TObject; ProgressForm: TFmProgress; var ShowMessage: Boolean); override; public { Public declarations } end; TLatinValidatorActionHandler = class(TAbstractActionHandler) public procedure ExecuteAction(UserData: Pointer = nil); override; end; var FmLatinValidator: TFmLatinValidator; implementation {$R *.dfm} procedure TFmLatinValidator.AnalizeCell(Cell: OleVariant); var Value: string; // Words: TArray<String>; I: Integer; NewWord: String; // J: Integer; begin Value := Cell.Value; NewWord := ''; I := 1; // [' ', #9, '/', ',', ':', ';', '-', '=', '(', ')', '<', '>', '«', '»', '•', '·', '.', '–', '"', ''''] while (I <= Length(Value)) do begin if (I < Length(Value)) and not(CharInSet(Value[I], [' ', #9, '/', ',', ':', ';', '-', '=', '(', ')', '<', '>', '«', '»', '•', '·', '.', '–', '"', ''''])) then NewWord := NewWord + Value[I] else begin if not isValidWord(NewWord) then begin Cell.Characters[I - Length(NewWord), Length(NewWord)].Font.ColorIndex := 5; end; NewWord := ''; end; Inc(I); end; for I := 1 to Length(Value) do if CharInSet(Value[I], ['A' .. 'Z', 'a' .. 'z']) then Cell.Characters[I, 1].Font.ColorIndex := 3; end; procedure TFmLatinValidator.AnalizeFile(AFileName: string); const xlCellTypeLastCell = $0000000B; var ExlApp, Sheet: OleVariant; I, j, r, c: Integer; WB: OleVariant; begin ExlApp := CreateOleObject('Excel.Application'); try ExlApp.Visible := false; ExlApp.DisplayAlerts := false; WB := ExlApp.Workbooks.Open(AFileName); Sheet := WB.WorkSheets[1]; Sheet.Cells.SpecialCells(xlCellTypeLastCell, EmptyParam).Activate; r := ExlApp.ActiveCell.Row; c := ExlApp.ActiveCell.Column; for I := 1 to r do for j := 1 to c do AnalizeCell(Sheet.Cells[I, j]); WB.SaveAs(AFileName); finally Sheet := Unassigned; WB.Close; WB := Unassigned; ExlApp.Quit; ExlApp := Unassigned; end; end; procedure TFmLatinValidator.DoOk(Sender: TObject; ProgressForm: TFmProgress; var ShowMessage: Boolean); var I: Integer; begin ShowMessage := True; ProgressForm.InitPB(lvFiles.Items.Count - 1); ProgressForm.Show; for I := 0 to lvFiles.Items.Count - 1 do begin ProgressForm.StepIt(lvFiles.Items[I].Caption); lvFiles.Items[I].SubItems[0] := 'Èäåò àíàëèç....'; try AnalizeFile(lvFiles.Items[I].Caption); except lvFiles.Items[I].SubItems[0] := 'Îøèáêà'; end; lvFiles.Items[I].SubItems[0] := 'Îáðàáîòàí'; if not ProgressForm.InProcess then Break; end; end; function TFmLatinValidator.HasCyr(Word: string): Boolean; const Rus = '¨ÉÖÓÊÅÍÃØÙÇÕÚÔÛÂÀÏÐÎËÄÆÝß×ÑÌÈÒÜÁÞàáâãä叿çèéêëìíîïðñòóôõö÷øùüûúýþÿ'; var I: Integer; begin Result := false; for I := 1 to Length(Word) do if Pos(Word[I], Rus) > 0 then begin Exit(True); end; end; function TFmLatinValidator.HasLatin(Word: string): Boolean; var I: Integer; begin Result := false; for I := 1 to Length(Word) do if CharInSet(Word[I], ['A' .. 'Z', 'a' .. 'z']) then begin Exit(True); end; end; function TFmLatinValidator.isValidWord(Word: string): Boolean; var // I: Integer; A, B: Boolean; begin // if cbUseDictionary.Checked and (FDict.IndexOf(Word) <> -1) then // Exit(True); Result := True; if Word = '' then Exit; A := HasLatin(Word); B := HasCyr(Word); if A and B then Exit(false) else // if A and not B then // FDict.Add(Word); end; procedure TFmLatinValidator.JvDragDropDrop(Sender: TObject; Pos: TPoint; Value: TStrings); var I: Integer; Item: TListItem; begin lvFiles.Clear; for I := 0 to Value.Count - 1 do begin Item := lvFiles.Items.Add; Item.Caption := Value[I]; Item.Checked := True; Item.SubItems.Add('Îæèäàíèå'); end; end; { TLatinValidatorActionHandler } procedure TLatinValidatorActionHandler.ExecuteAction; begin TFmLatinValidator.Create(Application).Show; end; begin ActionHandlerManager.RegisterActionHandler('Ïðîâåðêà íà ëàòèíèöó Excel', hkDefault, TLatinValidatorActionHandler); end.
unit kwArchiNewDocument; {* *Формат:* Создать *Описание:* Создание документа из файла. Имя файла совпадает с названием теста, но используется расширение evd. *Пример:* [code] Создать [code] *Результат:* Создает документ из файла Название_теста.evd *Примечания:* В скриптах напрямую практически не используется, так как есть более удобные функции в файле: [code] w:\archi\source\projects\Archi\TestSet\Dictionary\MainFormUtils.script" [code] } // Модуль: "w:\archi\source\projects\Archi\Archi_Insider_Test_Support\kwArchiNewDocument.pas" // Стереотип: "ScriptKeyword" // Элемент модели: "TkwArchiNewDocument" MUID: (4E0A095C0324) {$Include w:\archi\source\projects\Archi\arDefine.inc} interface {$If Defined(nsTest) AND Defined(InsiderTest) AND NOT Defined(NoScripts)} uses l3IntfUses , kwCreateNewFile , tfwScriptingInterfaces ; type TkwArchiNewDocument = class(TkwCreateNewFile) {* *Формат:* Создать *Описание:* Создание документа из файла. Имя файла совпадает с названием теста, но используется расширение evd. *Пример:* [code] Создать [code] *Результат:* Создает документ из файла Название_теста.evd *Примечания:* В скриптах напрямую практически не используется, так как есть более удобные функции в файле: [code] w:\archi\source\projects\Archi\TestSet\Dictionary\MainFormUtils.script" [code] } protected function DoWithFileName(const aCtx: TtfwContext): AnsiString; override; class function GetWordNameForRegister: AnsiString; override; end;//TkwArchiNewDocument {$IfEnd} // Defined(nsTest) AND Defined(InsiderTest) AND NOT Defined(NoScripts) implementation {$If Defined(nsTest) AND Defined(InsiderTest) AND NOT Defined(NoScripts)} uses l3ImplUses , SysUtils , arArchiTestsAdapter , dt_Types //#UC START# *4E0A095C0324impl_uses* //#UC END# *4E0A095C0324impl_uses* ; function TkwArchiNewDocument.DoWithFileName(const aCtx: TtfwContext): AnsiString; //#UC START# *52BD79600196_4E0A095C0324_var* //#UC END# *52BD79600196_4E0A095C0324_var* begin //#UC START# *52BD79600196_4E0A095C0324_impl* Result := ChangeFileExt(aCtx.rStreamFactory.Filename, '.evd'); Result := ExtractFileName(Result); Result := aCtx.rCaller.ResolveInputFilePath(Result); //#UC END# *52BD79600196_4E0A095C0324_impl* end;//TkwArchiNewDocument.DoWithFileName class function TkwArchiNewDocument.GetWordNameForRegister: AnsiString; begin Result := 'Создать'; end;//TkwArchiNewDocument.GetWordNameForRegister initialization TkwArchiNewDocument.RegisterInEngine; {* Регистрация TkwArchiNewDocument } {$IfEnd} // Defined(nsTest) AND Defined(InsiderTest) AND NOT Defined(NoScripts) end.
unit PrimMain_Form; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "View" // Модуль: "w:/garant6x/implementation/Garant/GbaNemesis/View/PrimMain_Form.pas" // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<VCMMainForm::Class>> F1 Базовые определения предметной области::F1 Application Template::View::PrimF1::PrimMain // // Главная форма. Общая для всех приложений F1 // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface uses l3StringIDEx, l3MessageID, MainPrim_Form, vcmExternalInterfaces {a}, vcmInterfaces {a}, vcmEntityForm {a} ; var { Локализуемые строки Local } str_MayExit : Tl3MessageID = (rS : -1; rLocalized : false; rKey : 'MayExit'; rValue : 'Вы уверены, что хотите закрыть систему %s?'); { 'Вы уверены, что хотите закрыть систему %s?' } str_ApplicationName : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'ApplicationName'; rValue : 'ГАРАНТ'); { 'ГАРАНТ' } str_MayExit_CheckCaption : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'MayExit_CheckCaption'; rValue : 'Всегда выходить без подтверждения'); { undefined } str_MayExit_SettingsCaption : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'MayExit_SettingsCaption'; rValue : 'Выход из системы'); { undefined } str_MayExit_LongHint : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'MayExit_LongHint'; rValue : 'Подтверждение при выходе из системы'); { undefined } type TPrimMainForm = {form} class(TMainPrimForm) {* Главная форма. Общая для всех приложений F1 } protected // overridden protected methods {$If not defined(NoVCM)} procedure DoInit(aFromHistory: Boolean); override; {* Инициализация формы. Для перекрытия в потомках } {$IfEnd} //not NoVCM function NeedTerminateOnExit: Boolean; override; function AskMayExit: Boolean; override; procedure DoShow; override; procedure ActivateDefKeyboardLayout; override; end;//TPrimMainForm implementation uses DataAdapter, Forms, F1Like_FormDefinitions_Controls, Dialogs, StdRes {a} ; var { Варианты выбора для диалога MayExit } str_MayExit_Choice_Exit : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'MayExit_Choice_Exit'; rValue : 'Выйти'); { 'Выйти' } str_MayExit_Choice_Stay : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'MayExit_Choice_Stay'; rValue : 'Продолжить работу'); { 'Продолжить работу' } // start class TPrimMainForm {$If not defined(NoVCM)} procedure TPrimMainForm.DoInit(aFromHistory: Boolean); //#UC START# *49803F5503AA_4A92BD85004D_var* //#UC END# *49803F5503AA_4A92BD85004D_var* begin //#UC START# *49803F5503AA_4A92BD85004D_impl* inherited; //#UC END# *49803F5503AA_4A92BD85004D_impl* end;//TPrimMainForm.DoInit {$IfEnd} //not NoVCM function TPrimMainForm.NeedTerminateOnExit: Boolean; //#UC START# *4ADDD31E0091_4A92BD85004D_var* //#UC END# *4ADDD31E0091_4A92BD85004D_var* begin //#UC START# *4ADDD31E0091_4A92BD85004D_impl* {$IfNDef nsWithoutLogin} Result := not defDataAdapter.Authorization.IsServerAlive; {$Else nsWithoutLogin} Result := false; {$EndIf nsWithoutLogin} //#UC END# *4ADDD31E0091_4A92BD85004D_impl* end;//TPrimMainForm.NeedTerminateOnExit function TPrimMainForm.AskMayExit: Boolean; //#UC START# *4ADDD5A30139_4A92BD85004D_var* //#UC END# *4ADDD5A30139_4A92BD85004D_var* begin //#UC START# *4ADDD5A30139_4A92BD85004D_impl* Result := Ask(str_MayExit, [str_ApplicationName.AsCStr]); //#UC END# *4ADDD5A30139_4A92BD85004D_impl* end;//TPrimMainForm.AskMayExit procedure TPrimMainForm.DoShow; //#UC START# *4B321D1301DD_4A92BD85004D_var* //#UC END# *4B321D1301DD_4A92BD85004D_var* begin //#UC START# *4B321D1301DD_4A92BD85004D_impl* inherited; //#UC END# *4B321D1301DD_4A92BD85004D_impl* end;//TPrimMainForm.DoShow procedure TPrimMainForm.ActivateDefKeyboardLayout; //#UC START# *4F71FA8102BF_4A92BD85004D_var* //#UC END# *4F71FA8102BF_4A92BD85004D_var* begin //#UC START# *4F71FA8102BF_4A92BD85004D_impl* inherited; defDataAdapter.ActivateDefKeyboardLayout; //#UC END# *4F71FA8102BF_4A92BD85004D_impl* end;//TPrimMainForm.ActivateDefKeyboardLayout initialization // Инициализация str_MayExit_Choice_Exit str_MayExit_Choice_Exit.Init; // Инициализация str_MayExit_Choice_Stay str_MayExit_Choice_Stay.Init; // Инициализация str_MayExit str_MayExit.Init; str_MayExit.AddChoice(str_MayExit_Choice_Exit); str_MayExit.AddChoice(str_MayExit_Choice_Stay); str_MayExit.AddDefaultChoice(str_MayExit_Choice_Exit); str_MayExit.SetDlgType(mtConfirmation); str_MayExit.SetNeedCheck(true); str_MayExit.SetCheckCaption(str_MayExit_CheckCaption); str_MayExit.SetSettingsCaption(str_MayExit_SettingsCaption); str_MayExit.SetLongHint(str_MayExit_LongHint); // Инициализация str_ApplicationName str_ApplicationName.Init; // Инициализация str_MayExit_CheckCaption str_MayExit_CheckCaption.Init; // Инициализация str_MayExit_SettingsCaption str_MayExit_SettingsCaption.Init; // Инициализация str_MayExit_LongHint str_MayExit_LongHint.Init; end.
unit ControleContainerTO; interface uses Classes, DateUtils, SysUtils; type TOperacao = (Entrada, Saida); type TStatus = (Digitado, Pago, Cancelado, Baixado, ComSaida); type TFormaPgamento = (AVista, Faturado); {type TLocalizacao = class(Tpersistent) private FAndar: integer; FNumero: integer; FApartamento: integer; FRua: string; public property Rua: string read FRua write FRua; property Numero: integer read FNumero write FNumero; property Andar: integer read FAndar write FAndar; property Apartamento: integer read FApartamento write FApartamento; end;} type TControleContainer = class private FAndar: integer; FNumero: integer; FApartamento: integer; FRua: string; FCliente: string; FCliente_: string; FProduto: string; FDataSaida: TDateTime; FDataEntrada: TDateTime; FOperacao: integer; FStatus: TStatus; FNroTicket: integer; FOperador: string; FObservacao: string; //FLocalizacao: TLocalizacao; FDataMovimentacao: TDateTime; FTipoServico: integer; FPeriodo: integer; FVlrPeriodo: real; FVlrCalculado: real; FVlrAPagar: real; FVlrTransbordo: real; FTara: real; FVeiculo: string; FContainer: string; FMotorista: string; FFormaPgamento: TFormaPgamento; FPeriodoEmHoras: integer; FCarenciaPeriodo: integer; iHoraPermanencia: integer; iMinutoPermanencia: integer; FTransbordoEmHoras: integer; FCarenciaTransbordo: integer; FFilOrig: string; FID: Integer; FIntervaloEmHoras: integer; FCarenciaIntervalo: integer; FVlrIntervalo: real; FNMCliente: string; FNMProduto: string; FCaluladoIntervalo: Boolean; FCaluladoPeriodo: Boolean; FCaluladoTransbordo: Boolean; FArmador: string; FSituacao: string; FMovimentacao: string; FTransportador: string; FTipo: string; FLacres: string; FCodAvarias: string; FCodViagem: string; FViagem: string; FNavio: string; FImportador: string; FPorto: string; FReserva: string; FCodigo_Imo: string; FCarreta: string; FRefCliente: string; FTipoAduaneiro: string; FMaxCross: string; FDataAlteracao: TDateTime; FFilial_OS: string; FN_OS: Integer; function GetVlrAPagar: real; function GetHorasPermanencia: string; function GetCalculado: real; //funcoes utess function ArredInter(nValor: Double; iCasaDec: Integer): Double; function Eleva(Base, Expoente: Double): Double; public constructor Create; destructor Destroy; override; property Rua: string read FRua write FRua; property Numero: integer read FNumero write FNumero; property Andar: integer read FAndar write FAndar; property Apartamento: integer read FApartamento write FApartamento; property ID: Integer read FID write FID; property Operacao: Integer read FOperacao write FOperacao; property Cliente: string read FCliente write FCliente; property Cliente_: string read FCliente_ write FCliente_; property Produto: string read FProduto write FProduto; property DataEntrada: TDateTime read FDataEntrada write FDataEntrada; property DataSaida: TDateTime read FDataSaida write FDataSaida; property DataMovimentacao: TDateTime read FDataMovimentacao write FDataMovimentacao; property DataAlteracao: TDateTime read FDataAlteracao write FDataAlteracao; property Status: TStatus read FStatus write FStatus; property FilOrig: string read FFilOrig write FFilOrig; property NroTicket: integer read FNroTicket write FNroTicket; property Observacao: string read FObservacao write FObservacao; //property Localizacao: TLocalizacao read FLocalizacao write FLocalizacao; property Operador: string read FOperador write FOperador; property FormaPgamento: TFormaPgamento read FFormaPgamento write FFormaPgamento; property Veiculo: string read FVeiculo write FVeiculo; property Motorista: string read FMotorista write FMotorista; property Container: string read FContainer write FContainer; property TipoServico: integer read FTipoServico write FTipoServico; property Tara: real read FTara write FTara; property HorasPermanencia: string read GetHorasPermanencia; property Periodo: integer read FPeriodo write FPeriodo; // novos campos incluido por Francisco , RA T&D nº 7183 data 21/11/2011 property Transportador: string read FTransportador write FTransportador; property Armador: string read FArmador write FArmador; property Navio: string read FNavio write FNavio; property Movimentacao: string read FMovimentacao write FMovimentacao; property Importador: string read FImportador write FImportador; property Situacao: string read FSituacao write FSItuacao; property Tipo: string read FTipo write FTipo; property CodAvarias: string read FCodAvarias write FCodAvarias; property CodViagem: string read FCodViagem write FCodViagem; property Lacres: string read FLacres write FLacres; property Viagem: string read FViagem write FViagem; property Porto: string read FPorto write FPorto; property Carreta: string read FCarreta write FCarreta; property Codigo_Imo: string read FCodigo_Imo write FCodigo_Imo; property MaxCross: string read FMaxCross write FMaxCross; property Reserva: string read FReserva write FReserva; property RefCliente: string read FRefCliente write FRefCliente; property TipoAduaneiro: string read FTipoAduaneiro write FTipoAduaneiro; property VlrCalculado: real read GetCalculado; property VlrAPagar: real read GetVlrAPagar write FVlrAPagar; property Filial_OS: string read FFilial_OS write FFilial_OS; property N_OS: Integer read FN_OS write FN_OS; //propriedades que deve ser TRUE calculo envolver cada um property CalculadoTransbordo: Boolean read FCaluladoTransbordo; property CalculadoIntervalo: Boolean read FCaluladoIntervalo; property CalculadoPeriodo: Boolean read FCaluladoPeriodo; //valores fixo ->vem cadastro property VlrPeriodo: real read FVlrPeriodo write FVlrPeriodo; property PeriodoEmHoras: integer read FPeriodoEmHoras write FPeriodoEmHoras; property CarenciaPeriodo: integer read FCarenciaPeriodo write FCarenciaPeriodo; property VlrTransbordo: real read FVlrTransbordo write FVlrTransbordo; property TransbordoEmHoras: integer read FTransbordoEmHoras write FTransbordoEmHoras; property CarenciaTransbordo: integer read FCarenciaTransbordo write FCarenciaTransbordo; property VlrIntervalo: real read FVlrIntervalo write FVlrIntervalo; property IntervaloEmHoras: integer read FIntervaloEmHoras write FIntervaloEmHoras; property CarenciaIntervalo: integer read FCarenciaIntervalo write FCarenciaIntervalo; property NMCliente: string read FNMCliente write FNMCliente; property NMProduto: string read FNMProduto write FNMProduto; //funcoes utess function IntToEnumerado(var ok: boolean; const s: integer; const AInteger: array of integer; const AEnumerados: array of variant): variant; function StrToEnumerado(var ok: boolean; const s: string; const AString: array of string; const AEnumerados: array of variant): variant; function EnumeradoToStr(const t: variant; const AString: array of string; const AEnumerados: array of variant): variant; function EnumeradoToInt(const t: variant; const AInteger: array of Integer; const AEnumerados: array of variant): variant; function OperacaoToInt(const t: TOperacao): Integer; function IntToOperacao(const t: integer): TOperacao; function StatusToStr(const t: TStatus): string; function StrToStatus(const s: string): TStatus; function FormaPgamentoToInt(const t: TFormaPgamento): Integer; function IntToFormaPgamento(const t: integer): TFormaPgamento; procedure Prepare; end; implementation { TControleContainer } constructor TControleContainer.Create; begin {if not Assigned(FLocalizacao) then FLocalizacao := TLocalizacao.Create;} inherited; end; function TControleContainer.EnumeradoToInt(const t: variant; const AInteger: array of Integer; const AEnumerados: array of variant): variant; var i : integer; begin result := ''; for i := Low(AEnumerados) to High(AEnumerados) do if t = AEnumerados[i] then result := AInteger[i]; end; function TControleContainer.EnumeradoToStr(const t: variant; const AString: array of string; const AEnumerados: array of variant): variant; var i : integer; begin result := ''; for i := Low(AEnumerados) to High(AEnumerados) do if t = AEnumerados[i] then result := AString[i]; end; function TControleContainer.FormaPgamentoToInt(const t: TFormaPgamento): Integer; begin result := EnumeradoToInt(t, [0, 1], [AVista, Faturado]); end; function TControleContainer.GetCalculado: real; var xIntervalo : integer; xExcedePeriodo : integer; xExcedeArred : integer; xIntervaloArred : real; xVlrIntervalo_1 : real; begin xIntervalo := 0; xExcedePeriodo := 0; xExcedeArred := 0; xIntervaloArred := 0; xVlrIntervalo_1 := 0; Result := 0; FPeriodo := 0; if (iHoraPermanencia < FPeriodoEmHoras) then begin if ((iHoraPermanencia = FTransbordoEmHoras) and (iMinutoPermanencia <= FCarenciaTransbordo)) or (iHoraPermanencia < FTransbordoEmHoras) then begin FCaluladoTransbordo := True; FCaluladoPeriodo := False; FCaluladoIntervalo := False; Result := FVlrTransbordo; end else begin FCaluladoTransbordo := False; FCaluladoPeriodo := True; FCaluladoIntervalo := False; FPeriodo := 1; Result := FVlrPeriodo; end; end; if (iHoraPermanencia = FPeriodoEmHoras) then begin xVlrIntervalo_1 := 0; if (iMinutoPermanencia <= FCarenciaPeriodo) then FPeriodo := 1 else if FVlrIntervalo > 0 then begin FPeriodo := 1; xVlrIntervalo_1 := FVlrIntervalo; end else FPeriodo := 2; FCaluladoTransbordo := False; FCaluladoPeriodo := True; FCaluladoIntervalo := False; Result := FVlrPeriodo * FPeriodo + xVlrIntervalo_1; end; if (iHoraPermanencia > FPeriodoEmHoras) then begin try FPeriodo := iHoraPermanencia div FPeriodoEmHoras; except FPeriodo := 0; end; if FPeriodo = 0 then FPeriodo := 1; if FVlrIntervalo > 0 then begin if FPeriodo > 1 then begin xExcedePeriodo := (iHoraPermanencia - FPeriodoEmHoras); xIntervalo := xExcedePeriodo div IntervaloEmHoras; FPeriodo := 1; end else begin xExcedePeriodo := iHoraPermanencia mod FPeriodoEmHoras; xIntervalo := xExcedePeriodo div IntervaloEmHoras; end; if (xExcedePeriodo mod IntervaloEmHoras = 0) then xExcedeArred := 0 else xExcedeArred := xExcedePeriodo; xExcedeArred := xExcedeArred mod 10; xIntervaloArred := ArredInter((xExcedeArred / 10), 0); xIntervalo := xIntervalo + StrToInt(FloatToStr((xIntervaloArred))); if (iMinutoPermanencia > FCarenciaIntervalo) and (xIntervalo > 0) then xIntervalo := xIntervalo; // + 1 FCaluladoTransbordo := False; FCaluladoPeriodo := True; FCaluladoIntervalo := True; FPeriodo := FPeriodo + xIntervalo; Result := FVlrPeriodo + (FVlrIntervalo * xIntervalo); end else begin if (iMinutoPermanencia > FCarenciaPeriodo) then FPeriodo := FPeriodo + 1; FCaluladoTransbordo := False; FCaluladoPeriodo := True; FCaluladoIntervalo := False; Result := FVlrPeriodo * FPeriodo; end; end; FVlrCalculado := Result; end; function TControleContainer.GetHorasPermanencia: string; begin if FDataSaida < FDataEntrada then begin raise Exception.Create('DaraHora de Saída não pode ser menor doque Entrada!'); iHoraPermanencia := 0; iMinutoPermanencia := 0 end; iHoraPermanencia := MinutesBetween(FDataEntrada, FDataSaida) div 60; iMinutoPermanencia := MinutesBetween(FDataEntrada, FDataSaida) mod 60; Result := FormatFloat('00', iHoraPermanencia) + ':' + FormatFloat('00', iMinutoPermanencia); //HoursBetween(DateOf(aDataEntrada), DateOf(aDataSaida)); end; function TControleContainer.GetVlrAPagar: real; begin if (FVlrAPagar <> FVlrCalculado) and (FVlrAPagar > 0) then Result := FVlrAPagar else Result := FVlrCalculado; end; function TControleContainer.IntToEnumerado(var ok: boolean; const s: integer; const AInteger: array of integer; const AEnumerados: array of variant): variant; var i : integer; begin result := -1; for i := Low(AInteger) to High(AInteger) do if (s = AInteger[i]) then result := AEnumerados[i]; ok := result <> -1; if not ok then result := AEnumerados[0]; end; function TControleContainer.IntToFormaPgamento(const t: integer): TFormaPgamento; var ok : boolean; begin result := IntToEnumerado(ok, t, [0, 1], [AVista, Faturado]); end; function TControleContainer.IntToOperacao(const t: integer): TOperacao; var ok : boolean; begin result := IntToEnumerado(ok, t, [0, 1], [Entrada, Saida]); end; function TControleContainer.OperacaoToInt(const t: TOperacao): Integer; begin result := EnumeradoToInt(t, [0, 1], [Entrada, Saida]); end; procedure TControleContainer.Prepare; begin //FCliente := ''; FProduto := ''; FDataSaida := 0; FDataEntrada := 0; FOperacao := 0; FStatus := Digitado; FNroTicket := 0; FOperador := ''; FObservacao := ''; FRua := ''; FNumero := 0; FAndar := 0; FApartamento :=0; {FLocalizacao.Rua := ''; FLocalizacao.Numero := 0; FLocalizacao.Andar := 0; FLocalizacao.Apartamento := 0;} FDataMovimentacao := 0; FTipoServico := 0; FPeriodo := 0; FVlrPeriodo := 0; FVlrCalculado := 0; FVlrAPagar := 0; FVlrTransbordo := 0; FTara := 0; FVeiculo := ''; FContainer := ''; FMotorista := ''; FFormaPgamento := Faturado; FPeriodoEmHoras := 0; FCarenciaPeriodo := 0; iHoraPermanencia := 0; iMinutoPermanencia := 0; FTransbordoEmHoras := 0; FCarenciaTransbordo := 0; FFilOrig := ''; FID := 0; FImportador := ''; FTransportador := ''; FMovimentacao := ''; FArmador := ''; FNavio := ''; FSituacao := ''; FCodAvarias := ''; FCodViagem := ''; FPorto := ''; FCarreta := ''; FCodigo_Imo := ''; FReserva := ''; FRefCliente := ''; FTipoAduaneiro := ''; FMaxCross := ''; FDataAlteracao := 0; FN_OS := 0; FFilial_OS := ''; FCliente_ := ''; end; function TControleContainer.StatusToStr(const t: TStatus): string; begin result := EnumeradoToStr(t, ['DG', 'PG', 'CA', 'BX', 'CS'], [Digitado, Pago, Cancelado, Baixado, ComSaida]); end; function TControleContainer.StrToEnumerado(var ok: boolean; const s: string; const AString: array of string; const AEnumerados: array of variant): variant; var i : integer; begin result := -1; for i := Low(AString) to High(AString) do if AnsiSameText(s, AString[i]) then result := AEnumerados[i]; ok := result <> -1; if not ok then result := AEnumerados[0]; end; function TControleContainer.StrToStatus(const s: string): TStatus; var ok : boolean; begin result := StrToEnumerado(ok, s, ['DG', 'PG', 'CA', 'BX', 'CS'], [Digitado, Pago, Cancelado, Baixado, ComSaida]); end; function TControleContainer.Eleva(Base, Expoente: Double): Double; begin if Expoente = 0 then Result := 1 else Result := Exp(Expoente * Ln(Base)); end; function TControleContainer.ArredInter(nValor: Double; iCasaDec: Integer): Double; var rNovoValor : Real; begin rNovoValor := nValor * Eleva(10, iCasaDec); if (rNovoValor - Int(rNovoValor)) >= 0.1 then rNovoValor := Int(rNovoValor) + 1 else rNovoValor := Int(rNovoValor); Result := rNovoValor / Eleva(10, iCasaDec); end; destructor TControleContainer.Destroy; begin //FLocalizacao.Free; inherited; end; end.
(*============================================================================== Программа : Система ведения договоров Модуль : Авторы : Смотрин А.А. Назначение : ==============================================================================*) unit SWIFT_UUtils; //////////////////////////////////////////////////////////////////////////////// interface/////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// uses Db, SysUtils, synautil; //////////////////////////////////////////////////////////////////////////////// type SubjectSWIFTInfo = packed record siName : String; siAddr : String; siSWIFT : String; siBIC : String; siUNN : String; siINN : String; siCorrAcc : String; end; FAccInfo = packed record PayID : Integer; Acc : String; AccCurr : Integer; BIC_Code : String; Swift_Code : String; Address : String; BankName : String; end; const cEditableFields: array [0..1] of string = ( 'CONFDET.FIA.70E.FIAN', 'CONFDET.70E' ); const SWIFT_MrkRefId = 30001; // сообщение отправлено cMessagesLinkKind = 70000; // тип связи сделки с сообщением cMessagesLinkByRefKind = 70001; // связь сообщения с сообщением по референсу cMessagesToMessagesLinkKind = 70003; // связь сообщения с родительским сообщением PaySystems: array[0..1] of String = ('SWIFT', 'TELEX'); // платежные системы ItemPathName = 'Внешнеэкономические операции'; // Ветка в НСИ cnSwiftItemPath = 'Архив swift сообщений'; // Ветка архива SWIFT сообщений в НСИ const cnSWIFTMsgText = 'MsgText'; cnSWIFTType = 'SWIFTType'; cnSWIFTMandatoryFields = 'SWIFTMandatoryFields'; cnSWIFTMandatoryFieldsPlainText = 'SWIFTMandatoryFieldsPlainText'; const {символы, допустимые в использовании SWIFT} SWIFTPermissible=['A'..'Z','a'..'z','0'..'9','/','-','?',':','(',')','.',#44,#39,'+',' ']; (* //сохранить сообщение в SWIFTMSGARCHIVE function AddToSwiftArch(const aDirection: Integer; aPaySys: Integer; aFileName: String; aMsgText: String; iTemplId: Integer; aSender: String; aReciever : String; aRef20: String; aRef21: String; aValueDate: TDateTime; aDate_op: TDateTime; iUSERID:Integer): Integer; //удаляет из строки кавычки и двойные кавычки function CopyNotQuote(str: String): String; //дополнительное преобразование строки для исходящих сообщений function CopySwiftAdd(const str: String): String; //замена/дополнение '.' на ',' в строке function ReplacePointStr(str: String): String; *) //Проверка на наличие слэша '/' в первой и последней позиции поля; на наличие двух последовательных слэшей '//' в поле //Применимо в основном для :20: и :21: поля function CheckingForSlashes(const StrValid: string; const FieldName: string): string; (* //Проверка поля на допустимую длину и наличие кириллических символов function ValidLineSWIFT(const StrValid: string; const ValidLength: Integer; const FieldName: string): string; function IsValidDate(Y, M, D: Word): Boolean; // Возвращает информацию о финансовой организации для МР) // необходима, что бы наименования банка соответствовали международному справочнику function GetBankInfoForMR(const ID: Integer; const sBIC, sSW: String; const bR: Boolean = False): SubjectSWIFTInfo; //////////////////////////////////////////////////////////////////////////////// // Возвращает информацию о субъекте function GetSubjectInfoSwift(const SID: Integer; const bRUS: Boolean = False; const IsFullAddress: Boolean = False): SubjectSWIFTInfo; // Возвращает информацию о клиенте function GetClientInfoSwift(const CLID: Integer; const bRUS: Boolean = False; const IsFullAddress: Boolean = False): SubjectSWIFTInfo; // Возвращает информацию о внешнем счете function GetFAccInfo(const Acc: String; const Curr: Integer; const B: String = ''; const S: String=''): FAccInfo; // Возвращает информацию о счете function GetAccInfo(const cAcc: String; const Curr: Integer; const BICCode: String; const SwiftCode: String): FAccInfo; //////////////////////////////////////////////////////////////////////////////// // Возвращает True если установлен признак STP function GetSTPforBIC(const sBIC: String): Boolean; // Возвращает True если установлен признак STP function GetSTPforSWIFT(const sSWIFT: String): Boolean; // Возвращает True если установлен признак BKE function GetBKEforBIC(const sBIC: String): Boolean; // Возвращает True если установлен признак BKE function GetBKEforSWIFT(const sSWIFT: String): Boolean; //Возвращает код клиринговой системы function GetClearingCode(const sBIC: String): String; *) // Возвращает True если SWIFT код сществует справочнике function ValidateSWIFT(aSWIFT: String): Boolean; (* //определение признака по корсчету и атрибуту function IsCorrAccIDForAtrRefID(const iAccId: Integer; const sRefid: String): Boolean; function GetIsFullAddrr(const iAccID: Integer): Boolean; // синхронизация родителей swift сообщений procedure LinkParentEntities(aEntID: Integer; aSwiftMsgEntID: Integer; aActID: Integer); // ИД текущего пользователя function GetRegUserID: Integer; function GetRegFuncID: Integer; *) //////////////////////////////////////////////////////////////////////////////// type TSWIFTBuilder = class(TStringBuilder) private FMaxLineLength: Integer; public procedure AfterConstruction; override; public function AppendSWIFTLine(const aValue: string): TSWIFTBuilder; overload; function AppendSWIFTLine(const aValue: string; const Args: array of const): TSWIFTBuilder; overload; function AppendLineFmt(const aValue: string; const Args: array of const): TSWIFTBuilder; end; // function StrRightPad(const str: String; ForceLength: Integer; const strPad: String): String; function GetBetweenEx(const PairBegin, PairEnd, Value: string): string; function Contains(const aNumber: Integer; const aValues: array of Integer): Boolean; // function iff(expr: Boolean; Val1, Val2: Variant): Variant; {возвращает признак наличия в строке недопустимые для S.W.I.F.T. символов} function IsSWIFTPermissible(const str: String; out strError: String): Boolean; // Проверяет необходимость авторизации данного типа SWIFT сообщения // по соответсвию маске заданной в НСИ //function IsNeedAuth(aType: Integer): Boolean; //////////////////////////////////////////////////////////////////////////////// implementation////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// (* uses DateUtil, SYS_UStr, SYS_uDllInit, Sys_uDbTools, API_uSwiftTrans, SVD_UApiClientUtils, SVD_UAPIAccUtils, API_uAppSettings, EXP_USubjects; *) function Contains(const aNumber: Integer; const aValues: array of Integer): Boolean; var Index: Integer; begin Result := False; for Index := Low(aValues) to High(aValues) do if aNumber = aValues[Index] then Exit(True); end; function GetBetweenEx(const PairBegin, PairEnd, Value: string): string; var n: integer; x: integer; s: string; lenBegin: integer; lenEnd: integer; str: string; max: integer; begin lenBegin := Length(PairBegin); lenEnd := Length(PairEnd); n := Length(Value); if (Value = PairBegin + PairEnd) then begin Result := '';//nothing between exit; end; if (n < lenBegin + lenEnd) then begin Result := Value; exit; end; s := SeparateRight(Value, PairBegin); if (s = Value) then begin Result := ''; exit; end; n := Pos(PairEnd, s); if (n = 0) then begin Result := ''; exit; end; Result := ''; x := 1; max := Length(s) - lenEnd + 1; for n := 1 to max do begin str := copy(s, n, lenEnd); if (str = PairEnd) then begin Dec(x); if (x <= 0) then Break; end; str := copy(s, n, lenBegin); if (str = PairBegin) then Inc(x); Result := Result + s[n]; end; end; (* //сохранить сообщение в SWIFTMSGARCHIVE function AddToSwiftArch(const aDirection: Integer; aPaySys: Integer; aFileName: String; aMsgText: String; iTemplId: Integer; aSender: String; aReciever : String; aRef20: String; aRef21: String; aValueDate: TDateTime; aDate_op: TDateTime; iUSERID:Integer): Integer; var vMsgText: String; begin with TMyQuery.Create(nil) do try SQL.Text := 'Insert Into SWIFTMSGARCHIVE (SWIFTMSGID, DIRECTION, FILENAME, MSGTYPE, SENDER, RECIEVER, REFERENCE20, REFERENCE21,'#13 +'MSGTEXT, PROCESSTIME, VALUEDATE, OPERDATE, PAYSYS, USERID)'#13 +'values (SEQSWIFTMsgID.Nextval, :DIRECTION, :FILENAME, :MSGTYPE, :SENDER, :RECIEVER, :REFERENCE20, :REFERENCE21,'#13 +':MSGTEXT, :PROCESSTIME, :VALUEDATE, :OPERDATE, :PAYSYS, :USERID) RETURNING SWIFTMSGID INTO :RESULT'; ParamByName('DIRECTION').AsString := IntToStr(aDIRECTION); ParamByName('FILENAME').AsString := aFileName; ParamByName('MSGTYPE').AsInteger := iTemplId; ParamByName('SENDER').AsString := aSender; if (ParamByName('SENDER').AsString='') then ParamByName('SENDER').AsString := CurrContext.GetVal(['REGISTRY','COMMON','BANK','SWIFT_CODE']); ParamByName('RECIEVER').AsString := trim(copy(Subst(aReciever,''#39'',' '),1,15));; ParamByName('REFERENCE20').AsString := trim(copy(Subst(aRef20,''#39'',' '),1,16)); ParamByName('REFERENCE21').AsString := trim(copy(Subst(aRef21,''#39'',' '),1,16)); vMsgText := Subst(aMsgText,''#$D#$A'','~'); vMsgText := Subst(vMsgText,''#39'',' '); vMsgText := trim(Subst(vMsgText,''#34'',' ')); ParamByName('MSGTEXT').AsWideString := vMsgText; if (ParamByName('MSGTEXT').AsString='') then ParamByName('MSGTEXT').AsString := '???'; ParamByName('PROCESSTIME').AsDateTime := now; ParamByName('VALUEDATE').AsDateTime := aValueDate; if (ParamByName('VALUEDATE').AsDateTime=0) then ParamByName('VALUEDATE').Clear; ParamByName('OPERDATE').AsDateTime := aDate_op; if (ParamByName('OPERDATE').AsDateTime=0) then ParamByName('OPERDATE').Clear; if (aPaySys=0) then ParamByName('PAYSYS').AsInteger := 1 else ParamByName('PAYSYS').AsInteger := 0; ParamByName('USERID').AsInteger := iUSERID; ParamByName('RESULT').ParamType := ptOutput; ParamByName('RESULT').DataType := ftInteger; ExecSQL; Result := ParamByName('RESULT').AsInteger; finally Free; end; end; ////удаляет из строки кавычки и двойные кавычки function CopyNotQuote(str: String): String; var i: Integer; begin Result:=''; for i:=1 to Length(str) do begin if not(str[i] in [#39,'"']) then begin Result := Result+ str[i]; end; end; end; //дополнительное преобразование строки для исходящих сообщений function CopySwiftAdd(const str: String): String; var s: String; begin if (str>'') then begin if IsTrans(str) then begin s := StrSWIFTTransliteration(str, 0, stRUR6); Result := CopySWIFT(s, 1, length(s), [#39]); end else begin Result := CopySWIFT(str, 1, length(str)); end; end; end; //замена/дополнение '.' на ',' в строке function ReplacePointStr(str: String): String; var PDof: PChar; begin //str := Abs(str); PDof := AnsiStrScan(PChar(str),'.'); if Assigned (PDof) then PDof^ := ',' else str := str + ','; if str = ',' then str := '0,'; Result := str; end; *) function CheckingForSlashes(const StrValid: string; const FieldName: string): string; var sErr: string; var eStrValid: string; begin if Pos(':SEME//', StrValid) > 0 then eStrValid := SeparateRight(StrValid, ':SEME//'); //значение не должно начинаться со слэша if (eStrValid > '') and (Copy(eStrValid,1,1) = '/') then sErr := sErr + #13 + 'поле ' + FieldName + ' не должно начинаться со слэша "/"'; //заканчиваться слэшем if (eStrValid > '') and (Copy(eStrValid, length(eStrValid), 1)='/') then sErr := sErr + #13 + 'поле ' + FieldName + ' не должно заканчиваться слэшем "/"'; //содержать внутри двойной слэш if (eStrValid > '') and Assigned(AnsiStrPos(PChar(eStrValid), PChar('//'))) then sErr := sErr + #13 + 'поле ' + FieldName + ' не должно содержать внутри двойной слэш "//"'; Result := sErr; end; (* function ValidLineSWIFT(const StrValid: string; const ValidLength: Integer; const FieldName: string): string; var sErr: string; begin if (length(StrValid) > ValidLength) then sErr := sErr+#13+Format('%s'#$9'%s - длина (%d) ==> допустимая длина (%d)',[FieldName, StrValid, length(StrValid), ValidLength]); if IsTrans(StrValid) then sErr := sErr+#13+Format('%s'#$9'%s ==> недопустимые символы',[FieldName, StrValid]); Result := sErr; end; function IsValidDate(Y, M, D: Word): Boolean; begin Result := (Y >= 1) and (Y <= 9999) and (M >= 1) and (M <= 12) and (D >= 1) and (D <= DaysPerMonth(Y, M)); end; //------------------------------------------------------------------------------ // Возвращает информацию о финансовой организации для МР) // необходима, что бы наименования банка соответствовали международному справочнику function GetBankInfoForMR(const ID: Integer; const sBIC, sSW: String; const bR: Boolean = False): SubjectSWIFTInfo; begin //по SWIFT-коду if (sSW>'') then begin Result.siSWIFT := sSW; try with GetFBankSwiftInfo(sSW) do begin Result.siBIC := BIC; Result.siCorrAcc := CorrAcc; if bR then begin if (Name>'') then Result.siName := Name else Result.siName := NameInt; if (Address>'') then Result.siAddr := Address else Result.siAddr := IntAddress; end else begin if (NameInt>'') then Result.siName := NameInt else Result.siName := Name; if (IntAddress>'') then Result.siAddr := IntAddress else Result.siAddr := Address; end; end; Exit; except on E: ENoRecordFound do begin try with GetSubjectSwiftInfo(sSW) do begin Result.siBIC := BIC; Result.siCorrAcc := CorrAcc; if bR then begin if (SubjectName>'') then Result.siName := SubjectName else Result.siName := InternationalName; if (Domicile>'') then Result.siAddr := Domicile else Result.siAddr := InternationalDomicile; end else begin if (InternationalName>'') then Result.siName := InternationalName else Result.siName := SubjectName; if (InternationalDomicile>'') then Result.siAddr := InternationalDomicile else Result.siAddr := Domicile; end; end; Exit; except on E: ENoRecordFound do begin end; end; end; end; end; //по BIC-коду if (sBIC>'') then begin Result.siBIC := sBIC; try with GetFBankBICInfo(sBIC) do begin Result.siSWIFT := SWIFT; Result.siCorrAcc := CorrAcc; if bR then begin if (Name>'') then Result.siName := Name else Result.siName := NameInt; if (Address>'') then Result.siAddr := Address else Result.siAddr := IntAddress; end else begin if (NameInt>'') then Result.siName := NameInt else Result.siName := Name; if (IntAddress>'') then Result.siAddr := IntAddress else Result.siAddr := Address; end; end; except on E: ENoRecordFound do begin try with GetSubjectBicInfo(sBIC) do begin Result.siSWIFT := SWIFT; Result.siCorrAcc := CorrAcc; if bR then begin if (SubjectName>'') then Result.siName := SubjectName else Result.siName := InternationalName; if (Domicile>'') then Result.siAddr := Domicile else Result.siAddr := InternationalDomicile; end else begin if (InternationalName>'') then Result.siName := InternationalName else Result.siName := SubjectName; if (InternationalDomicile>'') then Result.siAddr := InternationalDomicile else Result.siAddr := Domicile; end; end; except on E: ENoRecordFound do begin end; end; end; end; end; //по ИД субъекта if (ID>0) then begin try with GetSubjectInfo(ID) do begin Result.siBIC := BIC; Result.siSWIFT := SWIFT; Result.siCorrAcc := CorrAcc; if bR then begin if (SubjectName>'') then Result.siName := SubjectName else Result.siName := InternationalName; if (Domicile>'') then Result.siAddr := Domicile else Result.siAddr := InternationalDomicile; end else begin if (InternationalName>'') then Result.siName := InternationalName else Result.siName := SubjectName; if (InternationalDomicile>'') then Result.siAddr := InternationalDomicile else Result.siAddr := Domicile; end; end; except end; end; end; //------------------------------------------------------------------------------ function GetSubjectInfoSwift(const SID: Integer; const bRUS: Boolean = False; const IsFullAddress: Boolean = False): SubjectSWIFTInfo; begin FillChar(Result, SizeOf(Result), 0); with Result do begin if (SID>0) then begin try with GetSubjectInfo(SID) do begin Result.siINN := INN; Result.siUNN := UNN; Result.siSWIFT := SWIFT; Result.siBIC := BIC; Result.siCorrAcc := CorrAcc; if (bRUS) then begin if (SubjectName>'') then Result.siName := SubjectName else if (InternationalName>'') then Result.siName := InternationalName; if (Domicile>'') then begin Result.siAddr := Domicile; if IsFullAddress then Result.siAddr := Result.siAddr + ' ' + DomicileExt; end else if (InternationalDomicile>'') then begin Result.siAddr := InternationalDomicile; if IsFullAddress then begin Result.siAddr := Result.siAddr + ' ' + InternationalDomicileExt; end; end; end else begin if (InternationalName>'') then Result.siName := InternationalName else if (SubjectName>'') then Result.siName := SubjectName; if (InternationalDomicile>'') then begin Result.siAddr := InternationalDomicile; if IsFullAddress then Result.siAddr := Result.siAddr + ' ' + InternationalDomicileExt; end else if (Domicile>'') then begin Result.siAddr := Domicile; if IsFullAddress then begin Result.siAddr := Result.siAddr + ' ' + DomicileExt; end; end; end; end; except end; end; end; end; // Возвращает информацию о клиенте function GetClientInfoSwift(const CLID: Integer; const bRUS: Boolean = False; const IsFullAddress: Boolean = False): SubjectSWIFTInfo; begin FillChar(Result, SizeOf(Result), 0); with Result do begin if (CLID>0) then begin with GetClientInfo(CLID) do begin Result.siSWIFT := ''; Result.siBIC := ''; Result.siCorrAcc := ''; Result.siINN := INN; Result.siUNN := UNN; if (bRUS) then begin if (SWIFT_RusName>'') then Result.siName := SWIFT_RusName else if (SWIFT_Name>'') then Result.siName := SWIFT_Name else if (ShortName>'') then Result.siName := ShortName else Result.siName := Name; if (SWIFT_RusAddress>'') then Result.siAddr := SWIFT_RusAddress else if (SWIFT_Address>'') then Result.siAddr := SWIFT_Address else Result.siAddr := Address; end else begin if (SWIFT_Name>'') then Result.siName := SWIFT_Name else if (SWIFT_RusName>'') then Result.siName := SWIFT_RusName else if (ShortName>'') then Result.siName := ShortName else Result.siName := Name; if (SWIFT_Address>'') then Result.siAddr := SWIFT_Address else if (SWIFT_RusAddress>'') then Result.siAddr := SWIFT_RusAddress else Result.siAddr := Address; end; end; end; end; end; function GetFAccInfo(const Acc: String; const Curr: Integer; const B: String = ''; const S: String=''): FAccInfo; begin FillChar(Result, SizeOf(Result), 0); if (Acc='') then Exit; if (Curr=0) then Exit; with TMyQuery.Create(nil) do try SQL.Text:= 'select PR.*, CR.ISO, CR.CURRNAME ' +'from VPAYMENTREQS PR, CURRENCIES CR ' +'WHERE PR.CURRID=CR.CURRID and PR.ACC=:ACC and PR.CURRID=:CURR'; if (B<>'') and (S<>'') then begin SQL.Add(' and PR.BIC=:BIC and PR.SWIFT=:SWIFT'); ParamByName('BIC').AsString:=B; ParamByName('SWIFT').AsString:=S; end; ParamByName('ACC').AsString:=Acc; ParamByName('CURR').AsInteger:=Curr; Active:=True; if not(EOF) then begin with Result do begin Acc:=Acc; AccCurr:=Curr; PayID:=FieldByName('PAYREQID').AsInteger; BIC_Code:=FieldByName('BIC').AsString; Swift_Code:=FieldByName('SWIFT').AsString; Address:=FieldByName('ADDRESS').AsString; BankName:=FieldByName('BANKNAME').AsString; end; end else begin raise ENoRecordFound.Create(Format('AccInfoById: Внешний счет не найден (%s %d).', [Acc, Curr])); end; finally Free; end; end; function GetAccInfo(const cAcc: String; const Curr: Integer; const BICCode: String; const SwiftCode: String): FAccInfo; begin try with GetFAccInfo(cAcc, Curr, BICCode, SwiftCode) do begin Result.Acc := cAcc; Result.AccCurr := Curr; Result.BIC_Code := BICCode; Result.Swift_Code := SwiftCode; Result.Address := Address; Result.BankName := BankName; end; except on E: ENoRecordFound do begin with LocalAccInfo(cAcc, Curr, 1) do begin Result.Acc := Copy(cAcc, 1, 4)+' '+Copy(cAcc,5, Length(cAcc)-5)+' '+Copy(cAcc,Length(cAcc),1); Result.AccCurr := Curr; Result.BIC_Code := CurrContext.GetVal(['REGISTRY','COMMON','BANK','BANKID']); Result.Swift_Code := SwiftCode; with GetSubjectInfo(1) do begin Result.BankName := SubjectName; Result.Address := Domicile; end; if (Result.BankName='') then Result.BankName := CurrContext.GetVal(['REGISTRY','COMMON','BANK','BANKNAME']); if (Result.Address='') then Result.Address := CurrContext.GetVal(['REGISTRY','COMMON','BANK','ADDRESS']); end; end; end; end; //------------------------------------------------------------------------------ // Возвращает True если установлен признак STP function GetSTPforBIC(const sBIC: String): Boolean; begin if (sBIC>'') then begin with TMyQuery.Create(nil) do try SQL.Text := Format( 'select nvl(to_number(Is_SWIFT_STP.AttrValue),0) as "Is_SWIFT_STP"'+ ' from SUBJFINANCEREQS S,'+ ' (select SubjectID, AttrValue from PaySysNAttrs where (AttrRefID = ''STP'') and (PaySys=2)) Is_SWIFT_STP'+ ' where S.BIC = ''%s'''+ ' and Is_SWIFT_STP.SubjectID(+) = S.SUBJECTID',[sBIC]); Active := True; Result:=(Fields[0].AsInteger=1); finally Free; end; end else begin Result := False; end; end; //------------------------------------------------------------------------------ // Возвращает True если установлен признак STP function GetSTPforSWIFT(const sSWIFT: String): Boolean; begin if (sSWIFT>'') then begin with TMyQuery.Create(nil) do try SQL.Text := Format( 'select nvl(to_number(Is_SWIFT_STP.AttrValue),0) as "Is_SWIFT_STP"'+ ' from SUBJFINANCEREQS S,'+ ' (select SubjectID, AttrValue from PaySysNAttrs where (AttrRefID = ''STP'') and (PaySys=2)) Is_SWIFT_STP'+ ' where S.SWIFTCODE = ''%s'''+ ' and Is_SWIFT_STP.SubjectID(+) = S.SUBJECTID',[sSWIFT]); Active := True; Result:=(Fields[0].AsInteger=1); finally Free; end; end else begin Result := False; end; end; //------------------------------------------------------------------------------ // Возвращает True если установлен признак BKE function GetBKEforBIC(const sBIC: String): Boolean; begin if (sBIC>'') then begin with TMyQuery.Create(nil) do try SQL.Text := Format( 'select nvl(to_number(Is_SWIFT_BKE.AttrValue),0) as "Is_SWIFT_BKE"'+ ' from SUBJFINANCEREQS S,'+ ' (select SubjectID, AttrValue from PaySysNAttrs where (AttrRefID = ''BKE'') and (PaySys=2)) Is_SWIFT_BKE'+ ' where S.BIC = ''%s'''+ ' and Is_SWIFT_BKE.SubjectID(+) = S.SUBJECTID',[sBIC]); Active := True; Result:=(Fields[0].AsInteger=1); finally Free; end; end else begin Result := False; end; end; //------------------------------------------------------------------------------ // Возвращает True если установлен признак BKE function GetBKEforSWIFT(const sSWIFT: String): Boolean; begin if (sSWIFT>'') then begin with TMyQuery.Create(nil) do try SQL.Text := Format( 'select nvl(to_number(Is_SWIFT_BKE.AttrValue),0) as "Is_SWIFT_BKE"'+ ' from SUBJFINANCEREQS S,'+ ' (select SubjectID, AttrValue from PaySysNAttrs where (AttrRefID = ''BKE'') and (PaySys=2)) Is_SWIFT_BKE'+ ' where S.SWIFTCODE = ''%s'''+ ' and Is_SWIFT_BKE.SubjectID(+) = S.SUBJECTID',[sSWIFT]); Active := True; Result:=(Fields[0].AsInteger=1); finally Free; end; end else begin Result := False; end; end; //Возвращает код клиринговой системы function GetClearingCode(const sBIC: String): String; const aClearingCode: array[0..9] of String = ('RU','AT','AU','BL','CC','ES','IT','NZ','PT','SW'); var i: Integer; bClearingCode: Boolean; begin bClearingCode := False; for i:=0 to High(aClearingCode) do begin if (Copy(sBIC,1,2)=aClearingCode[i]) then begin bClearingCode := True; break; end; end; if not (bClearingCode) then begin try i := GetSubjectBicInfo(sBIC).StateID; except i := 0; end; if (i>0) then begin with TMyQuery.Create(nil) do try SQL.Text := Format('select CLEARINGSYSCODE from STATES where STATEID=%d',[i]); Active:=True; if not(EOF) then begin Result := Fields[0].AsString; end; finally Free; end; end; end; end; *) // Возвращает True если SWIFT код сществует справочнике function ValidateSWIFT(aSWIFT: String): Boolean; begin Result := True; end; (* //определение признака по корсчету и атрибуту function IsCorrAccIDForAtrRefID(const iAccId: Integer; const sRefid: String): Boolean; begin Result := False; if (iAccId=0) then Exit; if (sRefid='') then Exit; with TMyQuery.Create(nil) do try SQL.Text:= 'select max(T.CONFORMATTRVALUE) from ACC2ACCCONFORMATTRS T, ACC2ACCCONFORMITIES A ' +'where A.ACCID=:ACCID and A.ACC2ACCCONFID=T.ACC2ACCCONFID and T.ACCATTRREFID=:REFID'; ParamByName('ACCID').AsInteger:=iAccId; ParamByName('REFID').AsString:=sRefid; Active:=True; Result:=(Trim(Fields[0].AsString)='1'); finally Free; end end; function GetIsFullAddrr(const iAccID: Integer): Boolean; begin Result := False; if (iAccId=0) then Exit; with TMyQuery.Create(nil) do try SQL.Text:= 'select A.ATTRVALUE ' +'from SUBJECTS S, SUBJSATTRS A, ACCOUNTS T, SUBJ2CLIENTLINKS L ' +'where S.SUBJECTID=A.SUBJECTID and A.ATTRREFID=''APPLYTHEFULLADDRESS''' +' and T.ACCID=:ACCID and T.CLIENTID=L.CLIENTID and L.SUBJECTID=S.SUBJECTID'; ParamByName('ACCID').AsInteger:=iAccId; Active:=True; Result:=(Trim(Fields[0].AsString)='1'); finally Free; end end; procedure LinkParentEntities(aEntID: Integer; aSwiftMsgEntID: Integer; aActID: Integer); const SQLText = 'insert into ENTITIES_E2E '#13#10 + ' select E2E.TOPENTITYID, '#13#10 + ' :NewEntID, '#13#10 + ' :ActID, '#13#10 + ' :LinkKindID, '#13#10 + ' SEQENTLINKID.NEXTVAL '#13#10 + ' from ENTITIES_E2E E2E, ENTITIES E '#13#10 + ' where E2E.SUBENTITYID = :EntID '#13#10 + ' and E.ENTITYID = E2E.TOPENTITYID '#13#10 + ' and E.ENTREFID not like ''70%'' '#13#10 + ' and not exists (select 1 from ENTITIES_E2E E2E2 '#13#10 + ' where E2E2.TOPENTITYID = E2E.TOPENTITYID '#13#10 + ' and E2E2.SUBENTITYID = :NewEntID '#13#10 + ' and E2E2.LINKKIND = :LinkKindID)'; SQLExtension = ' and exists (select 1 from ENTITIES E2 '#13#10 + ' where E2.ENTITYID = :NewEntID '#13#10 + ' and E2.ENTREFID like ''70%'')'; begin with TMyQuery.Create() do try // связь между aSwiftMsgEntID(sub) и родителем aEntID(top) ExecQuery(SQLText, [aSwiftMsgEntID, aActID, cMessagesLinkKind, aEntID]); // связь между aEntID(sub) и родителем aSwiftMsgEntID(top) ExecQuery(SQLText + SQLExtension, [aEntID, aActID, cMessagesLinkKind, aSwiftMsgEntID]); finally Free; end; end; //------------------------------------------------------------------------------ function GetRegUserID: Integer; begin Result := CurrContext.GetValDef(['CFG', 'USERID'], 0); end; //------------------------------------------------------------------------------ function GetRegFuncID: Integer; begin Result := CurrContext.GetValDef(['CFG', 'FUNCID'], 0); end; *) //////////////////////////////////////////////////////////////////////////////// { TSWIFTBuilder } procedure TSWIFTBuilder.AfterConstruction; begin inherited; FMaxLineLength := 35; end; function TSWIFTBuilder.AppendSWIFTLine(const aValue: string): TSWIFTBuilder; begin Append(WrapText(aValue, FMaxLineLength)); AppendLine; Result := Self; end; function TSWIFTBuilder.AppendLineFmt(const aValue: string; const Args: array of const): TSWIFTBuilder; begin AppendLine(SysUtils.Format(aValue, Args)); Result := Self; end; function TSWIFTBuilder.AppendSWIFTLine(const aValue: string; const Args: array of const): TSWIFTBuilder; begin AppendSWIFTLine(SysUtils.Format(aValue, Args)); Result := Self; end; function StrRightPad(const str: String; ForceLength: Integer; const strPad: String): String; begin Result:=str; while (Length(Result) < ForceLength) do Result:=Result+strPad; Delete(Result, ForceLength+1, Length(Result)-ForceLength); end; function iff(expr: Boolean; Val1, Val2: Variant): Variant; begin if expr then Result := Val1 else Result := Val2; end; function IsSWIFTPermissible(const str: String; out strError: String): Boolean; var i: Integer; begin Result:=False; for i:=1 to Length(str) do begin if not (str[i] in SWIFTPermissible) then begin Result:=True; strError := strError + str[i]; end; end; end; end.//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
unit MdiChilds.ImportFromExcel.MatKeys; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, MdiChilds.ImportFromExcel, Vcl.StdCtrls, Vcl.ExtCtrls, ActionHandler, MdiChilds.ProgressForm, GsDocument, Parsers.Excel, Parsers.Abstract, Parsers.Excel.Tools; type TFmImportFromExcelKeys = class(TFmImportFromExcel) edtDoc: TLabeledEdit; btnOpenDoc: TButton; OpenDialogDoc: TOpenDialog; procedure btnOpenDocClick(Sender: TObject); private { Private declarations } protected procedure DoOk(Sender: TObject; ProgressForm: TFmProgress; var ShowMessage: Boolean); override; procedure ReadSettings(); override; procedure WriteSettings(); override; public { Public declarations } end; TImportKeysActionHandler = class(TAbstractActionHandler) public procedure ExecuteAction(UserData: Pointer = nil); override; end; TExcelKeyRow = class(TExcelRowWrapper) end; TExcelKeysParser = class(TExcelParser<TGsDocument, TExcelKeyRow>) private FDocument: TGsDocument; FList: TStringList; procedure EnumPositions(); protected function DoGetDocument: TGsDocument; override; procedure DoParseSheet(AExcelSheet: TExcelSheet; ADocument: TGsDocument); override; procedure DoParseRow(AExcelRow: TExcelKeyRow; ARowIndex: Integer; ADocument: TGsDocument); override; public constructor Create(ADocument: TGsDocument); destructor Destroy; override; end; var FmImportFromExcelKeys: TFmImportFromExcelKeys; implementation {$R *.dfm} procedure TFmImportFromExcelKeys.btnOpenDocClick(Sender: TObject); begin if OpenDialogDoc.Execute then edtDoc.Text := OpenDialogDoc.FileName; end; { TImportKeysActionHandler } procedure TImportKeysActionHandler.ExecuteAction; begin TFmImportFromExcelKeys.Create(Application).Show; end; procedure TFmImportFromExcelKeys.DoOk(Sender: TObject; ProgressForm: TFmProgress; var ShowMessage: Boolean); var Parser: TExcelKeysParser; D: TGsDocument; begin Assert(edtDoc.Text <> '', 'Необходимо задать документ'); D := TGsDocument.Create; try D.LoadFromFile(edtDoc.Text); Parser := TExcelKeysParser.Create(D); try Parser.ParseDoc(edtSourceFile.Text, cbSheetName.Text); finally Parser.Free; end; finally D.Free end; end; { TExcelKeysParser } constructor TExcelKeysParser.Create(ADocument: TGsDocument); begin inherited Create; FDocument := ADocument; FList := TStringList.Create; EnumPositions; end; destructor TExcelKeysParser.Destroy; begin FList.Free; inherited; end; function TExcelKeysParser.DoGetDocument: TGsDocument; begin Result := nil; end; procedure TExcelKeysParser.DoParseRow(AExcelRow: TExcelKeyRow; ARowIndex: Integer; ADocument: TGsDocument); var Row: TGsRow; Index: Integer; a: string; begin // if TParserTools.IsDefaultMaterialCode(AExcelRow.Values[1]) then begin Index := FList.IndexOf(AExcelRow.Values[0]); if Index <> -1 then begin Row := TGsRow(FList.Objects[Index]); Row.Attributes[Ord(eaCode2001)] := Unassigned; a := Trim(StringReplace(AExcelRow.Values[6], 'ТССЦ-', '', [])); a := Trim(StringReplace(a, 'ФССЦ-', '', [])); Row.Attributes[Ord(eaCode2001)] := a; // Row.Attributes[Ord(eaCodeOKPD2)] := AExcelRow.Values[2]; end; end; end; procedure TExcelKeysParser.DoParseSheet(AExcelSheet: TExcelSheet; ADocument: TGsDocument); begin inherited; ADocument := TGsDocument.Create; try ADocument.Assign(FDocument); ADocument.SaveToFile(ChangeFileExt(FDocument.FileName, '.xml')); finally ADocument.Free end; end; procedure TExcelKeysParser.EnumPositions; var L: TList; I: Integer; begin Assert(FDocument <> nil, 'Не задан документ'); L := TList.Create; try FDocument.Chapters.EnumItems(L, TGsRow, True); for I := 0 to L.Count - 1 do begin FList.AddObject(TGsRow(L[I]).Number(True), L[I]); TGsRow(L[I]).Attributes[Ord(eaCode2001)] := Unassigned; end; finally L.Free; end; end; procedure TFmImportFromExcelKeys.ReadSettings; begin // end; procedure TFmImportFromExcelKeys.WriteSettings; begin // end; begin {$IFDEF DEBUG} ActionHandlerManager.RegisterActionHandler('Импорт ключей для материалов', hkDefault, TImportKeysActionHandler); {$ENDIF} end.
unit GeocodingActionsUnit; interface uses SysUtils, BaseActionUnit, CommonTypesUnit, BulkGeocodingRequestUnit, GeocodingUnit, EnumsUnit, DirectionPathPointUnit, GeocodingAddressUnit; type TGeocodingActions = class(TBaseAction) private function ParseXml(XmlString: String): TGeocodingList; public /// <summary> /// Forward geocoding is the process of converting place name information into latitude and longitude values /// </summary> function ForwardGeocodeAddress(Address: String; out ErrorString: String): TGeocoding; /// <summary> /// Forward geocoding is the process of converting place name information into latitude and longitude values /// </summary> function ForwardGeocodeAddresses(Addresses: TAddressInfoArray; out ErrorString: String): TGeocodingList; /// <summary> /// With the reverse geocoding you can retrieve an address name from a geographical location point (latitude, longitude). /// Using this method, you can get the nearest locations to a specific address name. /// You can also get the larger scale objects (such as street addresses, places, /// neighbourhoods, county, state or country) which include a specified address. /// </summary> function ReverseGeocodeAddress(Location: TDirectionPathPoint; out ErrorString: String): TGeocodingList; /// <summary> /// Single address geocoding refers to the process of getting a geographic address by address name sent with HTTP GET data. /// </summary> function GetSingleAddress(Pk: integer; out ErrorString: String): TGeocodingAddress; /// <summary> /// This example refers to the process of getting all addresses. /// </summary> function GetAddresses(out ErrorString: String): TGeocodingAddressList; overload; /// <summary> /// This example refers to the process of getting a limited number of the addresses. The limitation parameters are: offset and limit. /// </summary> function GetAddresses(Limit, Offset: integer; out ErrorString: String): TGeocodingAddressList; overload; /// <summary> /// This example refers to the process of getting all addresses containing a specified zip code. /// </summary> function GetZipCodes(ZipCode: String; out ErrorString: String): TGeocodingAddressList; overload; /// <summary> /// This example refers to the process of getting a limited number of addresses containing a specified zip code. /// </summary> function GetZipCodes(ZipCode: String; Limit, Offset: integer; out ErrorString: String): TGeocodingAddressList; overload; /// <summary> /// This example refers to the process of getting all addresses containing a specified zip code and house number. /// </summary> function GetZipCodeAndHouseNumber(ZipCode: String; HouseNumber: String; out ErrorString: String): TGeocodingAddressList; overload; /// <summary> /// This example refers to the process of getting a limited number of addresses containing a specified zip code and house number. /// </summary> function GetZipCodeAndHouseNumber(ZipCode: String; HouseNumber: String; Limit, Offset: integer; out ErrorString: String): TGeocodingAddressList; overload; end; implementation { TGeocodingActions } uses Xml.XMLDoc, Xml.XMLIntf, SettingsUnit, GenericParametersUnit, UtilsUnit, NullableBasicTypesUnit; { TGeocodingActions } function TGeocodingActions.ForwardGeocodeAddress(Address: String; out ErrorString: String): TGeocoding; var Request: TGenericParameters; XmlString: TSimpleString; Parsed: TGeocodingList; begin Result := nil; Request := TGenericParameters.Create; try Request.AddParameter('addresses', Address); Request.AddParameter('format', TFormatDescription[TFormatEnum.Xml]); XmlString := FConnection.Post(TSettings.EndPoints.Geocoding, Request, TSimpleString, ErrorString) as TSimpleString; try if (XmlString <> nil) then begin Parsed := ParseXml(XmlString.Value); try if (Parsed.Count > 0) then begin if (Parsed[0].Type_.IsNotNull) and (Parsed[0].Type_.Value = 'invalid') then begin ErrorString := 'Forward Geocode Address fault'; Exit; end; Result := Parsed[0]; Parsed.OwnsObjects := False; Parsed.Remove(Result); Parsed.OwnsObjects := True; end; finally FreeAndNil(Parsed); end; end; finally FreeAndNil(XmlString); end; if (Result = nil) and (ErrorString = EmptyStr) then ErrorString := 'Forward Geocode Address fault'; finally FreeAndNil(Request); end; end; function TGeocodingActions.GetAddresses( out ErrorString: String): TGeocodingAddressList; var Request: TGenericParameters; Url: String; begin Request := TGenericParameters.Create; try Url := Format('%s/', [TSettings.EndPoints.RapidAddressSearch]); Result := FConnection.Get(Url, Request, TGeocodingAddressList, ErrorString) as TGeocodingAddressList; if (Result = nil) and (ErrorString = EmptyStr) then ErrorString := 'Get Addresses fault'; finally FreeAndNil(Request); end; end; function TGeocodingActions.GetZipCodes(ZipCode: String; out ErrorString: String): TGeocodingAddressList; var Request: TGenericParameters; Url: String; begin Request := TGenericParameters.Create; try Url := Format('%s/zipcode/%s/', [TSettings.EndPoints.RapidAddressSearch, ZipCode]); Result := FConnection.Get(Url, Request, TGeocodingAddressList, ErrorString) as TGeocodingAddressList; if (Result = nil) and (ErrorString = EmptyStr) then ErrorString := 'Get Zip Codes fault'; finally FreeAndNil(Request); end; end; function TGeocodingActions.ForwardGeocodeAddresses(Addresses: TAddressInfoArray; out ErrorString: String): TGeocodingList; var Request: TBulkGeocodingRequest; XmlString: TSimpleString; List: TGeocodingList; i: integer; IsInvalid: boolean; begin Result := TGeocodingList.Create; Request := TBulkGeocodingRequest.Create; try for i := 0 to High(Addresses) do Request.AddAddress(Addresses[i]); XmlString := FConnection.Post(TSettings.EndPoints.BulkGeocoding, Request, TSimpleString, ErrorString) as TSimpleString; try if (XmlString <> nil) then begin try List := ParseXml(XmlString.Value); try if (List.Count > 0) then begin IsInvalid := True; for i := 0 to List.Count - 1 do if (List[0].Type_.IsNotNull) and (List[0].Type_.Value <> 'invalid') then begin IsInvalid := False; Break; end; if IsInvalid then Exit; List.OwnsObjects := False; Result.AddRange(List); end; finally FreeAndNil(List); end; except ErrorString := XmlString.Value; Exit; end; end; finally FreeAndNil(XmlString); end; if (Result = nil) and (ErrorString = EmptyStr) then ErrorString := 'Forward Geocode Addresses fault'; finally FreeAndNil(Request); end; end; function TGeocodingActions.GetAddresses(Limit, Offset: integer; out ErrorString: String): TGeocodingAddressList; var Request: TGenericParameters; Url: String; begin Request := TGenericParameters.Create; try Url := Format('%s/%d/%d/', [TSettings.EndPoints.RapidAddressSearch, Offset, Limit]); Result := FConnection.Get(Url, Request, TGeocodingAddressList, ErrorString) as TGeocodingAddressList; if (Result = nil) and (ErrorString = EmptyStr) then ErrorString := 'Get Addresses fault'; finally FreeAndNil(Request); end; end; function TGeocodingActions.GetSingleAddress(Pk: integer; out ErrorString: String): TGeocodingAddress; var Request: TGenericParameters; Url: String; begin Request := TGenericParameters.Create; try Url := Format('%s/%d/', [TSettings.EndPoints.RapidAddressSearch, Pk]); Result := FConnection.Get(Url, Request, TGeocodingAddress, ErrorString) as TGeocodingAddress; if (Result = nil) and (ErrorString = EmptyStr) then ErrorString := 'Get Single Address fault'; finally FreeAndNil(Request); end; end; function TGeocodingActions.GetZipCodeAndHouseNumber(ZipCode, HouseNumber: String; Limit, Offset: integer; out ErrorString: String): TGeocodingAddressList; var Request: TGenericParameters; Url: String; begin Request := TGenericParameters.Create; try Url := Format('%s/service/%s/%s/%d/%d/', [TSettings.EndPoints.RapidAddressSearch, ZipCode, HouseNumber, Offset, Limit]); Result := FConnection.Get(Url, Request, TGeocodingAddressList, ErrorString) as TGeocodingAddressList; if (Result = nil) and (ErrorString = EmptyStr) then ErrorString := 'Get Zip Code And House Number fault'; finally FreeAndNil(Request); end; end; function TGeocodingActions.GetZipCodes(ZipCode: String; Limit, Offset: integer; out ErrorString: String): TGeocodingAddressList; var Request: TGenericParameters; Url: String; begin Request := TGenericParameters.Create; try Url := Format('%s/zipcode/%s/%d/%d/', [TSettings.EndPoints.RapidAddressSearch, ZipCode, Offset, Limit]); Result := FConnection.Get(Url, Request, TGeocodingAddressList, ErrorString) as TGeocodingAddressList; if (Result = nil) and (ErrorString = EmptyStr) then ErrorString := 'Get Zip Codes fault'; finally FreeAndNil(Request); end; end; function TGeocodingActions.ParseXml(XmlString: String): TGeocodingList; var Doc: IXMLDocument; Node, DestinationNode: IXmlNode; Item: TGeocoding; i: integer; begin Result := TGeocodingList.Create; Doc := TXMLDocument.Create(nil); try Doc.LoadFromXML(XmlString); Node := Doc.ChildNodes.FindNode('destinations'); if (Node = nil) then Exit; for i := 0 to Node.ChildNodes.Count - 1 do begin if (Node.ChildNodes[i].NodeName <> 'destination') then Continue; DestinationNode := Node.ChildNodes[i]; Item := TGeocoding.Create; if DestinationNode.HasAttribute('destination') then Item.Destination := DestinationNode.Attributes['destination']; if DestinationNode.HasAttribute('lat') then Item.Latitude := TUtils.StrToFloat(DestinationNode.Attributes['lat']); if DestinationNode.HasAttribute('lng') then Item.Longitude := TUtils.StrToFloat(DestinationNode.Attributes['lng']); if DestinationNode.HasAttribute('confidence') then Item.SetConfidenceAsString(DestinationNode.Attributes['confidence']); if DestinationNode.HasAttribute('type') then Item.Type_ := DestinationNode.Attributes['type']; if DestinationNode.HasAttribute('original') then Item.Original := DestinationNode.Attributes['original']; Result.Add(Item); end; finally Doc := nil; end; end; function TGeocodingActions.GetZipCodeAndHouseNumber(ZipCode, HouseNumber: String; out ErrorString: String): TGeocodingAddressList; var Request: TGenericParameters; Url: String; begin Request := TGenericParameters.Create; try Url := Format('%s/service/%s/%s/', [TSettings.EndPoints.RapidAddressSearch, ZipCode, HouseNumber]); Result := FConnection.Get(Url, Request, TGeocodingAddressList, ErrorString) as TGeocodingAddressList; if (Result = nil) and (ErrorString = EmptyStr) then ErrorString := 'Get Zip Code And House Number fault'; finally FreeAndNil(Request); end; end; function TGeocodingActions.ReverseGeocodeAddress( Location: TDirectionPathPoint; out ErrorString: String): TGeocodingList; var Request: TGenericParameters; LocationParam: String; XmlString: TSimpleString; List: TGeocodingList; i: integer; IsInvalid: boolean; begin Result := TGeocodingList.Create; Request := TGenericParameters.Create; try LocationParam := TUtils.FloatToStrDot(Location.Latitude.Value) + ',' + TUtils.FloatToStrDot(Location.Longitude.Value); Request.AddParameter('addresses', LocationParam); Request.AddParameter('format', TFormatDescription[TFormatEnum.Xml]); XmlString := FConnection.Post(TSettings.EndPoints.Geocoding, Request, TSimpleString, ErrorString) as TSimpleString; try if (XmlString <> nil) then begin List := ParseXml(XmlString.Value); try if (List.Count > 0) then begin IsInvalid := True; for i := 0 to List.Count - 1 do if (List[0].Type_.IsNotNull) and (List[0].Type_.Value <> 'invalid') then begin IsInvalid := False; Break; end; if IsInvalid then Exit; List.OwnsObjects := False; Result.AddRange(List); end; finally FreeAndNil(List); end; end; finally FreeAndNil(XmlString); end; if (Result = nil) and (ErrorString = EmptyStr) then ErrorString := 'Reverse Geocode Address fault'; finally FreeAndNil(Request); end; end; end.
{ Subroutine SST_R_PAS_LIT_STRING (STR) * * Process the LIT_STRING syntax. The string represented by this syntax * is returned in STR. } module sst_r_pas_LIT_STRING; define sst_r_pas_lit_string; %include 'sst_r_pas.ins.pas'; procedure sst_r_pas_lit_string ( {read LIT_STRING syntax and return string} in out str: univ string_var_arg_t); {returned string} var tag: sys_int_machine_t; {syntax tag ID} str_h: syo_string_t; {handle to string associated with TAG} val: sst_var_value_t; {value of ASCII character number} label str_loop; { ************************************************ * * Local subroutine QUOTED_STRING (S) * * Append the string characters from the syntax QUOTED_STRING_CHARS to the * string S. } procedure quoted_string ( in out s: univ string_var_arg_t); {string to append new characters to} var tag: sys_int_machine_t; {syntax tag ID} str_h: syo_string_t; {handle to string associated with TAG} token: string_var8192_t; {scratch string for extracting characters} label quoted_loop; begin token.max := sizeof(token.str); {init local var string} syo_level_down; {down into QUOTED_STRING_CHARS syntax} quoted_loop: syo_get_tag_msg (tag, str_h, 'sst_pas_read', 'constant_bad', nil, 0); case tag of 1: begin {chunk of raw characters} syo_get_tag_string (str_h, token); {get raw string characters} string_append (s, token); {add characters to output string} end; 2: begin {double quote, interpret as literal quote} string_append1 (s, ''''); end; syo_tag_end_k: begin {done reading quoted string} syo_level_up; {back up from QUOTED_STRING_CHARS syntax} return; end; otherwise syo_error_tag_unexp (tag, str_h); end; {done with TAG cases} goto quoted_loop; {back and read next chunk of string} end; { ************************************************ * * Start of main routine. } begin syo_level_down; {down into LIT_STRING syntax} str.len := 0; {init accumulated string to empty} str_loop: {back here each new part of quoted string} syo_get_tag_msg (tag, str_h, 'sst_pas_read', 'constant_bad', nil, 0); case tag of 1: begin {quoted string characters} quoted_string (str); {append characters from this quoted part} goto str_loop; {back for next part of this string} end; 2: begin {ASCII character value in ()} sst_r_pas_exp_eval (val); {get value of ASCII character} if val.dtype <> sst_dtype_int_k then begin {expression was not an integer ?} syo_error (str_h, 'sst_pas_read', 'exp_not_int', nil, 0); end; string_append1 (str, chr(val.int_val)); {append this character to output string} goto str_loop; {back for next part of this string} end; syo_tag_end_k: begin {hit end of string, STR all set} end; otherwise syo_error_tag_unexp (tag, str_h); end; syo_level_up; {up from LIT_STRING syntax} end;
unit wwWorms; interface Uses Types, wwClasses, wwTypes, wwMinds; type TwwTarget = class (TwwThing) private f_Power: Integer; FPower: Integer; public constructor Create(aWorld: TwwWorld); reintroduce; procedure Ressurect; override; property Power: Integer read FPower; end; TwwWorm = class (TwwThing) private f_Mind: TwwMind; f_MindCenter: TwwMindCenter; FTarget: TwwThing; FFavorite: TwwFavoriteType; FStopTurns: Integer; FTargetCount: Integer; procedure FindTarget; protected function GetDefaultLenght: Integer; function GetDefaultLength: Integer; override; procedure Think; override; procedure WhileStop; override; public constructor Create(aWorld: TwwWorld; aMindCenter: TwwMindCenter; aVariety: Integer); reintroduce; procedure Die; override; function Eat(const aPOint: TPoint): Boolean; override; function IsNeck(const aPoint: TPoint): Boolean; procedure Ressurect; override; function ToHead(A: TPoint): TwwDirection; function ToTail(A: TPoint): TwwDirection; function ToNeck: TwwDirection; property Favorite: TwwFavoriteType read FFavorite write FFavorite; property Target: TwwThing read FTarget write FTarget; property Mind: TwwMind read f_Mind; property TargetCount: Integer read FTargetCount; end; implementation Uses Math, wwUtils; const MinWormLength = 5; TargetsVarieties : array[0..1] of Integer = (0, 1); TargetName : array[0..1] of String = ('Apple', 'Orange'); TargetPower : array[0..1] of Integer = (5, 3); MaxStopTurns = 3; { TwwWorm } { *********************************** TwwWorm ************************************ } constructor TwwWorm.Create(aWorld: TwwWorld; aMindCenter: TwwMindCenter; aVariety: Integer); begin inherited Create(aWorld, MinWormLength); Caption:= 'Worm'; Entity:= weLive; f_MindCenter:= aMindCenter; Variety:= aVariety; end; function TwwWorm.Eat(const aPOint: TPoint): Boolean; var l_T: TwwThing; begin // Проверить, является ли данная точка нашей целью Result:= False; l_T:= World.ThingAt(aPoint); if (l_T <> nil) and (l_T.Entity = weNotLive) then begin Enlarge(TwwTarget(Target).Power); Inc(FTargetCount); Target.Die; //Target:= nil; Result:= True; end (* if Equal(aPoint, Target.Head.Position) then begin Enlarge(TwwTarget(Target).Power); Inc(FTargetCount); Target.Die; Target:= nil; Result:= True; end else begin l_T:= World.ThingAt(aPoint); Result:= (l_T = nil) or (l_T.Entity = weNotLive); end; *) end; function TwwWorm.GetDefaultLenght: Integer; begin Result := MinWormLength; end; function TwwWorm.GetDefaultLength: Integer; begin Result:= MinWormLength; end; function TwwWorm.IsNeck(const aPoint: TPoint): Boolean; begin if Length > 1 then Result:= IsMe(aPoint) and Equal(Points[1].Position, aPoint) else Result:= False; end; procedure TwwWorm.Ressurect; var i: Integer; {$IFNDEF Delphi7} l_P: TPoint; {$ENDIF} begin inherited; f_Mind:= f_MindCenter.RandomMind; if f_Mind <> nil then begin Caption:= f_Mind.Caption; Target:= f_Mind.FindTarget(Self) ; end; Head.Value:= ws_HeadL; for i:= 1 to Length-2 do begin Points[i].Position:= Head.Position; {$IFDEF Delphi7} Points[i].Position.X:= Head.Position.X{ - i}; {$ELSE} l_P:= Points[i].Position; l_P.X:= Head.Position.X; Points[i].Position:= l_P; {$ENDIF} Points[i].Value:= ws_BodyH; end; Tail.Position:= Head.Position; {$IFDEF Delphi7} Tail.Position.X:= Head.Position.X{ - i}; {$ELSE} l_P:= Points[i].Position; l_P.X:= Tail.Position.X; Tail.Position:= l_P; {$ENDIF} Tail.Value:= ws_TailL; FTargetCount:= 0; end; procedure TwwWorm.Think; begin if f_Mind <> nil then Direction:= f_Mind.Think(Self) else Direction:= dtNone; if Direction <> dtStop then FStopTurns:= 0; end; function TwwWorm.ToHead(A: TPoint): TwwDirection; var l_Index: Integer; begin Result:= dtStop; l_Index:= PointIndex(A); if (l_Index > 0) then Result:= CalcDir(A, Points[Pred(l_Index)].Position, ftVertical) end; function TwwWorm.ToTail(A: TPoint): TwwDirection; var l_IndexA, l_Tail: Integer; begin Result:= dtStop; l_IndexA:= PointIndex(A); if (l_IndexA <> -1) and (l_IndexA < Length) then begin while Equal(A, Tail.Position) do begin Dec(l_IndexA); A:= Points[l_IndexA].Position; end; while IsTurn(A, Points[Succ(l_IndexA)].Position) do begin Dec(l_IndexA); A:= Points[l_IndexA].Position; end; Result:= CalcDir(A, Points[Succ(l_IndexA)].Position, ftVertical) end; end; function TwwWorm.ToNeck: TwwDirection; begin Result:= CalcDir(Head.Position, Points[1].Position, ftVertical) end; procedure TwwWorm.WhileStop; begin Enlarge(-5); Inc(FStopTurns); if FStopTurns > MaxStopTurns then Die; end; procedure TwwWorm.FindTarget; begin if f_Mind <> nil then Target:= f_Mind.FindTarget(Self) as TwwTarget; end; { TwwTarget } { ********************************** TwwTarget *********************************** } constructor TwwTarget.Create(aWorld: TwwWorld); begin inherited Create(aWorld, 1); Caption:= 'Target'; Entity:= weNotLive; end; procedure TwwTarget.Ressurect; begin inherited; Variety:= RandomFrom(TargetsVarieties); Head.Value:= ws_Target; Caption:= TargetName[Variety]; FPower:= TargetPower[Variety]; end; procedure TwwWorm.Die; begin inherited; if f_Mind <> nil then f_Mind.PostMorten(Self); end; end.
unit nsLogEventData; // Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\Logging\nsLogEventData.pas" // Стереотип: "SimpleClass" // Элемент модели: "TnsLogEventData" MUID: (55B760CE036A) {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface uses l3IntfUses , l3SimpleObject , LoggingWrapperInterfaces , LoggingUnit , BaseTypesUnit ; type TnsLogEventData = class(Tl3SimpleObject, InsLogEventData) private f_LogEventData: ILogEventData; f_AsString: AnsiString; private procedure ToLog(const aData: AnsiString); protected procedure AddDate(const aData: TDate); procedure AddObject(const aData: IUnknown); procedure AddString(aData: PAnsiChar); procedure AddULong(aData: Longword); function AsLogEventData: ILogEventData; function AsString: AnsiString; procedure Cleanup; override; {* Функция очистки полей объекта. } procedure InitFields; override; public class function Make: InsLogEventData; reintroduce; end;//TnsLogEventData implementation uses l3ImplUses , DataAdapter , bsConvert , DateUtils , SysUtils //#UC START# *55B760CE036Aimpl_uses* //#UC END# *55B760CE036Aimpl_uses* ; class function TnsLogEventData.Make: InsLogEventData; var l_Inst : TnsLogEventData; begin l_Inst := Create; try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//TnsLogEventData.Make procedure TnsLogEventData.ToLog(const aData: AnsiString); //#UC START# *55BA419F0230_55B760CE036A_var* //#UC END# *55BA419F0230_55B760CE036A_var* begin //#UC START# *55BA419F0230_55B760CE036A_impl* f_AsString := f_AsString + '[' + aData + ']'; //#UC END# *55BA419F0230_55B760CE036A_impl* end;//TnsLogEventData.ToLog procedure TnsLogEventData.AddDate(const aData: TDate); //#UC START# *55B75F7202BE_55B760CE036A_var* //#UC END# *55B75F7202BE_55B760CE036A_var* begin //#UC START# *55B75F7202BE_55B760CE036A_impl* ToLog(DateToStr(bsAdapterToBusiness(aData))); f_LogEventData.AddDate(aData); //#UC END# *55B75F7202BE_55B760CE036A_impl* end;//TnsLogEventData.AddDate procedure TnsLogEventData.AddObject(const aData: IUnknown); //#UC START# *55B75FA00176_55B760CE036A_var* //#UC END# *55B75FA00176_55B760CE036A_var* begin //#UC START# *55B75FA00176_55B760CE036A_impl* ToLog('obj'); f_LogEventData.AddObject(aData); //#UC END# *55B75FA00176_55B760CE036A_impl* end;//TnsLogEventData.AddObject procedure TnsLogEventData.AddString(aData: PAnsiChar); //#UC START# *55B75FBE02BE_55B760CE036A_var* //#UC END# *55B75FBE02BE_55B760CE036A_var* begin //#UC START# *55B75FBE02BE_55B760CE036A_impl* ToLog(aData); f_LogEventData.AddString(aData); //#UC END# *55B75FBE02BE_55B760CE036A_impl* end;//TnsLogEventData.AddString procedure TnsLogEventData.AddULong(aData: Longword); //#UC START# *55B75FD7031E_55B760CE036A_var* //#UC END# *55B75FD7031E_55B760CE036A_var* begin //#UC START# *55B75FD7031E_55B760CE036A_impl* ToLog(IntToStr(aData)); f_LogEventData.AddULong(aData); //#UC END# *55B75FD7031E_55B760CE036A_impl* end;//TnsLogEventData.AddULong function TnsLogEventData.AsLogEventData: ILogEventData; //#UC START# *55B76037036D_55B760CE036A_var* //#UC END# *55B76037036D_55B760CE036A_var* begin //#UC START# *55B76037036D_55B760CE036A_impl* Result := f_LogEventData; //#UC END# *55B76037036D_55B760CE036A_impl* end;//TnsLogEventData.AsLogEventData function TnsLogEventData.AsString: AnsiString; //#UC START# *55BA030300BA_55B760CE036A_var* //#UC END# *55BA030300BA_55B760CE036A_var* begin //#UC START# *55BA030300BA_55B760CE036A_impl* Result := f_AsString; //#UC END# *55BA030300BA_55B760CE036A_impl* end;//TnsLogEventData.AsString procedure TnsLogEventData.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_55B760CE036A_var* //#UC END# *479731C50290_55B760CE036A_var* begin //#UC START# *479731C50290_55B760CE036A_impl* f_LogEventData := nil; inherited; //#UC END# *479731C50290_55B760CE036A_impl* end;//TnsLogEventData.Cleanup procedure TnsLogEventData.InitFields; //#UC START# *47A042E100E2_55B760CE036A_var* //#UC END# *47A042E100E2_55B760CE036A_var* begin //#UC START# *47A042E100E2_55B760CE036A_impl* inherited; f_LogEventData := DefDataAdapter.NativeAdapter.MakeLogEventData; f_AsString := ''; //#UC END# *47A042E100E2_55B760CE036A_impl* end;//TnsLogEventData.InitFields end.
unit tanqueDao; interface uses Tanque, DB, DM, IBQuery, IBDataBase, Classes; type T_TanqueDao = class(TObject) private F_Qr: TIBQuery; F_Lista: TList; public constructor Create(db: TIBDataBase); destructor Destroy(); function NewID(): Integer; function incluir(tanque: T_Tanque): Integer; procedure atualizar(tanque: T_Tanque); procedure remover(tanque: T_Tanque); overload; procedure remover(tanque_id: Integer); overload; function listarTudo(): TList; function get(id: Integer): T_Tanque; end; implementation const SQL_ID = 'SELECT GEN_ID( TANQUE_ID_GEN, 1 ) AS ID FROM RDB$DATABASE; '; SQL_INCLUIR = 'INSERT INTO TANQUE(Id, Capacidade_Litros, Quantidade_Litros, TipoCombustivel_Id) '#13#10 + 'VALUES( :id , :capacidade_litros , :quantidade_litros , :tipocombustivel_id ) '; SQL_ATUALIZAR = 'UPDATE TANQUE '#13#10 + 'SET '#13#10 + ' capacidade_litros = :capacidade_litros , '#13#10 + ' quantidade_litros = :quantidade_litros , '#13#10 + ' tipocombustivel_id = :tipocombustivel_id '#13#10 + 'WHERE Id = :id '#13#10; SQL_EXCLUIR = 'DELETE FROM TANQUE WHERE Id = :id '; SQL_LISTARTUDO = 'SELECT * FROM TANQUE '; SQL_GET = 'SELECT * FROM TANQUE WHERE ID = :id '; constructor T_TanqueDao.Create(db: TIBDataBase); begin F_Qr := TIBQuery.Create(db); F_Qr.Database := db; F_QR.Transaction := db.DefaultTransaction; F_Lista := TList.Create(); end; destructor T_TanqueDao.Destroy(); begin F_Lista.Free(); end; function T_TanqueDao.NewID(): Integer; var id: Integer; begin F_Qr.Active := False; F_Qr.SQL.Clear(); F_Qr.SQL.Text := SQL_ID; F_Qr.Open(); result := F_Qr.FieldByName('Id').AsInteger; F_Qr.Active := False; end; function T_TanqueDao.incluir(tanque: T_Tanque): Integer; var id: Integer; begin id := NewID(); F_QR.Active := False; F_QR.SQL.Clear(); F_Qr.SQL.Text := SQL_INCLUIR; F_Qr.ParamByName('id').Value := id; F_Qr.ParamByName('capacidade_litros').Value := tanque.Capacidade_Litros; F_Qr.ParamByName('quantidade_litros').Value := tanque.Quantidade_Litros; F_Qr.ParamByName('tipocombustivel_id').Value := tanque.TipoCombustivel_Id; F_QR.Prepare(); F_Qr.ExecSQL(); tanque.Id := id; end; procedure T_TanqueDao.atualizar(tanque: T_Tanque); begin F_Qr.SQL.Text := SQL_ATUALIZAR; F_Qr.ParamByName('id').Value := tanque.id; F_Qr.ParamByName('capacidade_litros').Value := tanque.Capacidade_Litros; F_Qr.ParamByName('quantidade_litros').Value := tanque.Quantidade_Litros; F_Qr.ParamByName('tipocombustivel_id').Value := tanque.TipoCombustivel_Id; F_Qr.ExecSQL(); end; procedure T_TanqueDao.remover(tanque: T_Tanque); begin F_Qr.SQL.Text := SQL_EXCLUIR; F_Qr.ParamByName('id').Value := tanque.Id; F_Qr.Delete(); end; procedure T_TanqueDao.remover(tanque_id: Integer); begin F_Qr.SQL.Text := SQL_EXCLUIR; F_Qr.ParamByName('id').Value := tanque_id; F_Qr.Delete(); end; function T_TanqueDao.listarTudo(): TList; var a: T_Tanque; begin F_Qr.SQL.Text := SQL_LISTARTUDO; F_Qr.Open(); F_Lista.Clear(); result := TList.Create(); if result = nil then result := F_Lista.Create(); F_Qr.First(); while not F_Qr.Eof do begin result.Add( T_Tanque.Create( F_Qr.FieldByName('Id').AsInteger, F_Qr.FieldByName('Capacidade_Litros').AsFloat, F_Qr.FieldByName('Quantidade_Litros').AsFloat, F_Qr.FieldByName('TipoCombustivel_Id').AsInteger) ); F_Qr.Next(); end; if F_Qr.Active then F_Qr.Close(); end; function T_TanqueDao.get(id: Integer): T_Tanque; var a: T_Tanque; begin F_Qr.SQL.Text := SQL_GET; F_Qr.ParamByName('id').Value := id; F_Qr.Open(); result := nil; if not F_Qr.Eof then begin result := T_Tanque.Create( F_Qr.FieldByName('Id').AsInteger, F_Qr.FieldByName('Capacidade_Litros').AsFloat, F_Qr.FieldByName('Quantidade_Litros').AsFloat, F_Qr.FieldByName('TipoCombustivel_Id').AsInteger); end; if F_Qr.Active then F_Qr.Close(); end; end.
unit BaseSearchContainerKeywordsPack; {* Набор слов словаря для доступа к экземплярам контролов формы BaseSearchContainer } // Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\View\BaseSearch\Forms\BaseSearchContainerKeywordsPack.pas" // Стереотип: "ScriptKeywordsPack" // Элемент модели: "BaseSearchContainerKeywordsPack" MUID: (4D7A458300CB_Pack) {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL)} uses l3IntfUses ; {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL) implementation {$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL)} uses l3ImplUses , BaseSearchContainer_Form , tfwPropertyLike , vtPanel , tfwScriptingInterfaces , TypInfo , tfwTypeInfo , vtLabel , ExtCtrls , tfwControlString , kwBynameControlPush , TtfwClassRef_Proxy , SysUtils , TtfwTypeRegistrator_Proxy , tfwScriptingTypes //#UC START# *4D7A458300CB_Packimpl_uses* //#UC END# *4D7A458300CB_Packimpl_uses* ; type TkwBaseSearchContainerFormChildZone = {final} class(TtfwPropertyLike) {* Слово скрипта .TBaseSearchContainerForm.ChildZone } private function ChildZone(const aCtx: TtfwContext; aBaseSearchContainerForm: TBaseSearchContainerForm): TvtPanel; {* Реализация слова скрипта .TBaseSearchContainerForm.ChildZone } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwBaseSearchContainerFormChildZone TkwBaseSearchContainerFormPnHeader = {final} class(TtfwPropertyLike) {* Слово скрипта .TBaseSearchContainerForm.pnHeader } private function pnHeader(const aCtx: TtfwContext; aBaseSearchContainerForm: TBaseSearchContainerForm): TvtPanel; {* Реализация слова скрипта .TBaseSearchContainerForm.pnHeader } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwBaseSearchContainerFormPnHeader TkwBaseSearchContainerFormLbHeader = {final} class(TtfwPropertyLike) {* Слово скрипта .TBaseSearchContainerForm.lbHeader } private function lbHeader(const aCtx: TtfwContext; aBaseSearchContainerForm: TBaseSearchContainerForm): TvtLabel; {* Реализация слова скрипта .TBaseSearchContainerForm.lbHeader } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwBaseSearchContainerFormLbHeader TkwBaseSearchContainerFormPbHeader = {final} class(TtfwPropertyLike) {* Слово скрипта .TBaseSearchContainerForm.pbHeader } private function pbHeader(const aCtx: TtfwContext; aBaseSearchContainerForm: TBaseSearchContainerForm): TPaintBox; {* Реализация слова скрипта .TBaseSearchContainerForm.pbHeader } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwBaseSearchContainerFormPbHeader TkwBaseSearchContainerFormParentZone = {final} class(TtfwPropertyLike) {* Слово скрипта .TBaseSearchContainerForm.ParentZone } private function ParentZone(const aCtx: TtfwContext; aBaseSearchContainerForm: TBaseSearchContainerForm): TvtPanel; {* Реализация слова скрипта .TBaseSearchContainerForm.ParentZone } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwBaseSearchContainerFormParentZone Tkw_Form_BaseSearchContainer = {final} class(TtfwControlString) {* Слово словаря для идентификатора формы BaseSearchContainer ---- *Пример использования*: [code]форма::BaseSearchContainer TryFocus ASSERT[code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_Form_BaseSearchContainer Tkw_BaseSearchContainer_Control_ChildZone = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола ChildZone ---- *Пример использования*: [code]контрол::ChildZone TryFocus ASSERT[code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_BaseSearchContainer_Control_ChildZone Tkw_BaseSearchContainer_Control_ChildZone_Push = {final} class(TkwBynameControlPush) {* Слово словаря для контрола ChildZone ---- *Пример использования*: [code]контрол::ChildZone:push pop:control:SetFocus ASSERT[code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_BaseSearchContainer_Control_ChildZone_Push Tkw_BaseSearchContainer_Control_pnHeader = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола pnHeader ---- *Пример использования*: [code]контрол::pnHeader TryFocus ASSERT[code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_BaseSearchContainer_Control_pnHeader Tkw_BaseSearchContainer_Control_pnHeader_Push = {final} class(TkwBynameControlPush) {* Слово словаря для контрола pnHeader ---- *Пример использования*: [code]контрол::pnHeader:push pop:control:SetFocus ASSERT[code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_BaseSearchContainer_Control_pnHeader_Push Tkw_BaseSearchContainer_Control_lbHeader = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола lbHeader ---- *Пример использования*: [code]контрол::lbHeader TryFocus ASSERT[code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_BaseSearchContainer_Control_lbHeader Tkw_BaseSearchContainer_Control_lbHeader_Push = {final} class(TkwBynameControlPush) {* Слово словаря для контрола lbHeader ---- *Пример использования*: [code]контрол::lbHeader:push pop:control:SetFocus ASSERT[code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_BaseSearchContainer_Control_lbHeader_Push Tkw_BaseSearchContainer_Control_pbHeader = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола pbHeader ---- *Пример использования*: [code]контрол::pbHeader TryFocus ASSERT[code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_BaseSearchContainer_Control_pbHeader Tkw_BaseSearchContainer_Control_pbHeader_Push = {final} class(TkwBynameControlPush) {* Слово словаря для контрола pbHeader ---- *Пример использования*: [code]контрол::pbHeader:push pop:control:SetFocus ASSERT[code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_BaseSearchContainer_Control_pbHeader_Push Tkw_BaseSearchContainer_Control_ParentZone = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола ParentZone ---- *Пример использования*: [code]контрол::ParentZone TryFocus ASSERT[code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_BaseSearchContainer_Control_ParentZone Tkw_BaseSearchContainer_Control_ParentZone_Push = {final} class(TkwBynameControlPush) {* Слово словаря для контрола ParentZone ---- *Пример использования*: [code]контрол::ParentZone:push pop:control:SetFocus ASSERT[code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_BaseSearchContainer_Control_ParentZone_Push function TkwBaseSearchContainerFormChildZone.ChildZone(const aCtx: TtfwContext; aBaseSearchContainerForm: TBaseSearchContainerForm): TvtPanel; {* Реализация слова скрипта .TBaseSearchContainerForm.ChildZone } begin Result := aBaseSearchContainerForm.ChildZone; end;//TkwBaseSearchContainerFormChildZone.ChildZone class function TkwBaseSearchContainerFormChildZone.GetWordNameForRegister: AnsiString; begin Result := '.TBaseSearchContainerForm.ChildZone'; end;//TkwBaseSearchContainerFormChildZone.GetWordNameForRegister function TkwBaseSearchContainerFormChildZone.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtPanel); end;//TkwBaseSearchContainerFormChildZone.GetResultTypeInfo function TkwBaseSearchContainerFormChildZone.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwBaseSearchContainerFormChildZone.GetAllParamsCount function TkwBaseSearchContainerFormChildZone.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TBaseSearchContainerForm)]); end;//TkwBaseSearchContainerFormChildZone.ParamsTypes procedure TkwBaseSearchContainerFormChildZone.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству ChildZone', aCtx); end;//TkwBaseSearchContainerFormChildZone.SetValuePrim procedure TkwBaseSearchContainerFormChildZone.DoDoIt(const aCtx: TtfwContext); var l_aBaseSearchContainerForm: TBaseSearchContainerForm; begin try l_aBaseSearchContainerForm := TBaseSearchContainerForm(aCtx.rEngine.PopObjAs(TBaseSearchContainerForm)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aBaseSearchContainerForm: TBaseSearchContainerForm : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(ChildZone(aCtx, l_aBaseSearchContainerForm)); end;//TkwBaseSearchContainerFormChildZone.DoDoIt function TkwBaseSearchContainerFormPnHeader.pnHeader(const aCtx: TtfwContext; aBaseSearchContainerForm: TBaseSearchContainerForm): TvtPanel; {* Реализация слова скрипта .TBaseSearchContainerForm.pnHeader } begin Result := aBaseSearchContainerForm.pnHeader; end;//TkwBaseSearchContainerFormPnHeader.pnHeader class function TkwBaseSearchContainerFormPnHeader.GetWordNameForRegister: AnsiString; begin Result := '.TBaseSearchContainerForm.pnHeader'; end;//TkwBaseSearchContainerFormPnHeader.GetWordNameForRegister function TkwBaseSearchContainerFormPnHeader.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtPanel); end;//TkwBaseSearchContainerFormPnHeader.GetResultTypeInfo function TkwBaseSearchContainerFormPnHeader.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwBaseSearchContainerFormPnHeader.GetAllParamsCount function TkwBaseSearchContainerFormPnHeader.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TBaseSearchContainerForm)]); end;//TkwBaseSearchContainerFormPnHeader.ParamsTypes procedure TkwBaseSearchContainerFormPnHeader.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству pnHeader', aCtx); end;//TkwBaseSearchContainerFormPnHeader.SetValuePrim procedure TkwBaseSearchContainerFormPnHeader.DoDoIt(const aCtx: TtfwContext); var l_aBaseSearchContainerForm: TBaseSearchContainerForm; begin try l_aBaseSearchContainerForm := TBaseSearchContainerForm(aCtx.rEngine.PopObjAs(TBaseSearchContainerForm)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aBaseSearchContainerForm: TBaseSearchContainerForm : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(pnHeader(aCtx, l_aBaseSearchContainerForm)); end;//TkwBaseSearchContainerFormPnHeader.DoDoIt function TkwBaseSearchContainerFormLbHeader.lbHeader(const aCtx: TtfwContext; aBaseSearchContainerForm: TBaseSearchContainerForm): TvtLabel; {* Реализация слова скрипта .TBaseSearchContainerForm.lbHeader } begin Result := aBaseSearchContainerForm.lbHeader; end;//TkwBaseSearchContainerFormLbHeader.lbHeader class function TkwBaseSearchContainerFormLbHeader.GetWordNameForRegister: AnsiString; begin Result := '.TBaseSearchContainerForm.lbHeader'; end;//TkwBaseSearchContainerFormLbHeader.GetWordNameForRegister function TkwBaseSearchContainerFormLbHeader.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtLabel); end;//TkwBaseSearchContainerFormLbHeader.GetResultTypeInfo function TkwBaseSearchContainerFormLbHeader.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwBaseSearchContainerFormLbHeader.GetAllParamsCount function TkwBaseSearchContainerFormLbHeader.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TBaseSearchContainerForm)]); end;//TkwBaseSearchContainerFormLbHeader.ParamsTypes procedure TkwBaseSearchContainerFormLbHeader.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству lbHeader', aCtx); end;//TkwBaseSearchContainerFormLbHeader.SetValuePrim procedure TkwBaseSearchContainerFormLbHeader.DoDoIt(const aCtx: TtfwContext); var l_aBaseSearchContainerForm: TBaseSearchContainerForm; begin try l_aBaseSearchContainerForm := TBaseSearchContainerForm(aCtx.rEngine.PopObjAs(TBaseSearchContainerForm)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aBaseSearchContainerForm: TBaseSearchContainerForm : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(lbHeader(aCtx, l_aBaseSearchContainerForm)); end;//TkwBaseSearchContainerFormLbHeader.DoDoIt function TkwBaseSearchContainerFormPbHeader.pbHeader(const aCtx: TtfwContext; aBaseSearchContainerForm: TBaseSearchContainerForm): TPaintBox; {* Реализация слова скрипта .TBaseSearchContainerForm.pbHeader } begin Result := aBaseSearchContainerForm.pbHeader; end;//TkwBaseSearchContainerFormPbHeader.pbHeader class function TkwBaseSearchContainerFormPbHeader.GetWordNameForRegister: AnsiString; begin Result := '.TBaseSearchContainerForm.pbHeader'; end;//TkwBaseSearchContainerFormPbHeader.GetWordNameForRegister function TkwBaseSearchContainerFormPbHeader.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TPaintBox); end;//TkwBaseSearchContainerFormPbHeader.GetResultTypeInfo function TkwBaseSearchContainerFormPbHeader.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwBaseSearchContainerFormPbHeader.GetAllParamsCount function TkwBaseSearchContainerFormPbHeader.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TBaseSearchContainerForm)]); end;//TkwBaseSearchContainerFormPbHeader.ParamsTypes procedure TkwBaseSearchContainerFormPbHeader.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству pbHeader', aCtx); end;//TkwBaseSearchContainerFormPbHeader.SetValuePrim procedure TkwBaseSearchContainerFormPbHeader.DoDoIt(const aCtx: TtfwContext); var l_aBaseSearchContainerForm: TBaseSearchContainerForm; begin try l_aBaseSearchContainerForm := TBaseSearchContainerForm(aCtx.rEngine.PopObjAs(TBaseSearchContainerForm)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aBaseSearchContainerForm: TBaseSearchContainerForm : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(pbHeader(aCtx, l_aBaseSearchContainerForm)); end;//TkwBaseSearchContainerFormPbHeader.DoDoIt function TkwBaseSearchContainerFormParentZone.ParentZone(const aCtx: TtfwContext; aBaseSearchContainerForm: TBaseSearchContainerForm): TvtPanel; {* Реализация слова скрипта .TBaseSearchContainerForm.ParentZone } begin Result := aBaseSearchContainerForm.ParentZone; end;//TkwBaseSearchContainerFormParentZone.ParentZone class function TkwBaseSearchContainerFormParentZone.GetWordNameForRegister: AnsiString; begin Result := '.TBaseSearchContainerForm.ParentZone'; end;//TkwBaseSearchContainerFormParentZone.GetWordNameForRegister function TkwBaseSearchContainerFormParentZone.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtPanel); end;//TkwBaseSearchContainerFormParentZone.GetResultTypeInfo function TkwBaseSearchContainerFormParentZone.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwBaseSearchContainerFormParentZone.GetAllParamsCount function TkwBaseSearchContainerFormParentZone.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TBaseSearchContainerForm)]); end;//TkwBaseSearchContainerFormParentZone.ParamsTypes procedure TkwBaseSearchContainerFormParentZone.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству ParentZone', aCtx); end;//TkwBaseSearchContainerFormParentZone.SetValuePrim procedure TkwBaseSearchContainerFormParentZone.DoDoIt(const aCtx: TtfwContext); var l_aBaseSearchContainerForm: TBaseSearchContainerForm; begin try l_aBaseSearchContainerForm := TBaseSearchContainerForm(aCtx.rEngine.PopObjAs(TBaseSearchContainerForm)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aBaseSearchContainerForm: TBaseSearchContainerForm : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(ParentZone(aCtx, l_aBaseSearchContainerForm)); end;//TkwBaseSearchContainerFormParentZone.DoDoIt function Tkw_Form_BaseSearchContainer.GetString: AnsiString; begin Result := 'BaseSearchContainerForm'; end;//Tkw_Form_BaseSearchContainer.GetString class procedure Tkw_Form_BaseSearchContainer.RegisterInEngine; begin inherited; TtfwClassRef.Register(TBaseSearchContainerForm); end;//Tkw_Form_BaseSearchContainer.RegisterInEngine class function Tkw_Form_BaseSearchContainer.GetWordNameForRegister: AnsiString; begin Result := 'форма::BaseSearchContainer'; end;//Tkw_Form_BaseSearchContainer.GetWordNameForRegister function Tkw_BaseSearchContainer_Control_ChildZone.GetString: AnsiString; begin Result := 'ChildZone'; end;//Tkw_BaseSearchContainer_Control_ChildZone.GetString class procedure Tkw_BaseSearchContainer_Control_ChildZone.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtPanel); end;//Tkw_BaseSearchContainer_Control_ChildZone.RegisterInEngine class function Tkw_BaseSearchContainer_Control_ChildZone.GetWordNameForRegister: AnsiString; begin Result := 'контрол::ChildZone'; end;//Tkw_BaseSearchContainer_Control_ChildZone.GetWordNameForRegister procedure Tkw_BaseSearchContainer_Control_ChildZone_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('ChildZone'); inherited; end;//Tkw_BaseSearchContainer_Control_ChildZone_Push.DoDoIt class function Tkw_BaseSearchContainer_Control_ChildZone_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::ChildZone:push'; end;//Tkw_BaseSearchContainer_Control_ChildZone_Push.GetWordNameForRegister function Tkw_BaseSearchContainer_Control_pnHeader.GetString: AnsiString; begin Result := 'pnHeader'; end;//Tkw_BaseSearchContainer_Control_pnHeader.GetString class procedure Tkw_BaseSearchContainer_Control_pnHeader.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtPanel); end;//Tkw_BaseSearchContainer_Control_pnHeader.RegisterInEngine class function Tkw_BaseSearchContainer_Control_pnHeader.GetWordNameForRegister: AnsiString; begin Result := 'контрол::pnHeader'; end;//Tkw_BaseSearchContainer_Control_pnHeader.GetWordNameForRegister procedure Tkw_BaseSearchContainer_Control_pnHeader_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('pnHeader'); inherited; end;//Tkw_BaseSearchContainer_Control_pnHeader_Push.DoDoIt class function Tkw_BaseSearchContainer_Control_pnHeader_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::pnHeader:push'; end;//Tkw_BaseSearchContainer_Control_pnHeader_Push.GetWordNameForRegister function Tkw_BaseSearchContainer_Control_lbHeader.GetString: AnsiString; begin Result := 'lbHeader'; end;//Tkw_BaseSearchContainer_Control_lbHeader.GetString class procedure Tkw_BaseSearchContainer_Control_lbHeader.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtLabel); end;//Tkw_BaseSearchContainer_Control_lbHeader.RegisterInEngine class function Tkw_BaseSearchContainer_Control_lbHeader.GetWordNameForRegister: AnsiString; begin Result := 'контрол::lbHeader'; end;//Tkw_BaseSearchContainer_Control_lbHeader.GetWordNameForRegister procedure Tkw_BaseSearchContainer_Control_lbHeader_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('lbHeader'); inherited; end;//Tkw_BaseSearchContainer_Control_lbHeader_Push.DoDoIt class function Tkw_BaseSearchContainer_Control_lbHeader_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::lbHeader:push'; end;//Tkw_BaseSearchContainer_Control_lbHeader_Push.GetWordNameForRegister function Tkw_BaseSearchContainer_Control_pbHeader.GetString: AnsiString; begin Result := 'pbHeader'; end;//Tkw_BaseSearchContainer_Control_pbHeader.GetString class procedure Tkw_BaseSearchContainer_Control_pbHeader.RegisterInEngine; begin inherited; TtfwClassRef.Register(TPaintBox); end;//Tkw_BaseSearchContainer_Control_pbHeader.RegisterInEngine class function Tkw_BaseSearchContainer_Control_pbHeader.GetWordNameForRegister: AnsiString; begin Result := 'контрол::pbHeader'; end;//Tkw_BaseSearchContainer_Control_pbHeader.GetWordNameForRegister procedure Tkw_BaseSearchContainer_Control_pbHeader_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('pbHeader'); inherited; end;//Tkw_BaseSearchContainer_Control_pbHeader_Push.DoDoIt class function Tkw_BaseSearchContainer_Control_pbHeader_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::pbHeader:push'; end;//Tkw_BaseSearchContainer_Control_pbHeader_Push.GetWordNameForRegister function Tkw_BaseSearchContainer_Control_ParentZone.GetString: AnsiString; begin Result := 'ParentZone'; end;//Tkw_BaseSearchContainer_Control_ParentZone.GetString class procedure Tkw_BaseSearchContainer_Control_ParentZone.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtPanel); end;//Tkw_BaseSearchContainer_Control_ParentZone.RegisterInEngine class function Tkw_BaseSearchContainer_Control_ParentZone.GetWordNameForRegister: AnsiString; begin Result := 'контрол::ParentZone'; end;//Tkw_BaseSearchContainer_Control_ParentZone.GetWordNameForRegister procedure Tkw_BaseSearchContainer_Control_ParentZone_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('ParentZone'); inherited; end;//Tkw_BaseSearchContainer_Control_ParentZone_Push.DoDoIt class function Tkw_BaseSearchContainer_Control_ParentZone_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::ParentZone:push'; end;//Tkw_BaseSearchContainer_Control_ParentZone_Push.GetWordNameForRegister initialization TkwBaseSearchContainerFormChildZone.RegisterInEngine; {* Регистрация BaseSearchContainerForm_ChildZone } TkwBaseSearchContainerFormPnHeader.RegisterInEngine; {* Регистрация BaseSearchContainerForm_pnHeader } TkwBaseSearchContainerFormLbHeader.RegisterInEngine; {* Регистрация BaseSearchContainerForm_lbHeader } TkwBaseSearchContainerFormPbHeader.RegisterInEngine; {* Регистрация BaseSearchContainerForm_pbHeader } TkwBaseSearchContainerFormParentZone.RegisterInEngine; {* Регистрация BaseSearchContainerForm_ParentZone } Tkw_Form_BaseSearchContainer.RegisterInEngine; {* Регистрация Tkw_Form_BaseSearchContainer } Tkw_BaseSearchContainer_Control_ChildZone.RegisterInEngine; {* Регистрация Tkw_BaseSearchContainer_Control_ChildZone } Tkw_BaseSearchContainer_Control_ChildZone_Push.RegisterInEngine; {* Регистрация Tkw_BaseSearchContainer_Control_ChildZone_Push } Tkw_BaseSearchContainer_Control_pnHeader.RegisterInEngine; {* Регистрация Tkw_BaseSearchContainer_Control_pnHeader } Tkw_BaseSearchContainer_Control_pnHeader_Push.RegisterInEngine; {* Регистрация Tkw_BaseSearchContainer_Control_pnHeader_Push } Tkw_BaseSearchContainer_Control_lbHeader.RegisterInEngine; {* Регистрация Tkw_BaseSearchContainer_Control_lbHeader } Tkw_BaseSearchContainer_Control_lbHeader_Push.RegisterInEngine; {* Регистрация Tkw_BaseSearchContainer_Control_lbHeader_Push } Tkw_BaseSearchContainer_Control_pbHeader.RegisterInEngine; {* Регистрация Tkw_BaseSearchContainer_Control_pbHeader } Tkw_BaseSearchContainer_Control_pbHeader_Push.RegisterInEngine; {* Регистрация Tkw_BaseSearchContainer_Control_pbHeader_Push } Tkw_BaseSearchContainer_Control_ParentZone.RegisterInEngine; {* Регистрация Tkw_BaseSearchContainer_Control_ParentZone } Tkw_BaseSearchContainer_Control_ParentZone_Push.RegisterInEngine; {* Регистрация Tkw_BaseSearchContainer_Control_ParentZone_Push } TtfwTypeRegistrator.RegisterType(TypeInfo(TBaseSearchContainerForm)); {* Регистрация типа TBaseSearchContainerForm } TtfwTypeRegistrator.RegisterType(TypeInfo(TvtPanel)); {* Регистрация типа TvtPanel } TtfwTypeRegistrator.RegisterType(TypeInfo(TvtLabel)); {* Регистрация типа TvtLabel } TtfwTypeRegistrator.RegisterType(TypeInfo(TPaintBox)); {* Регистрация типа TPaintBox } {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL) end.
unit udmHorasAtendimento; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, udmPadrao, DBAccess, IBC, DB, MemDS; type TdmHorasAtendimento = class(TdmPadrao) qryManutencaoCGC: TStringField; qryManutencaoTREINAMENTO: TStringField; qryManutencaoDESENVOLVIMENTO: TStringField; qryManutencaoVLR_TREINAMENTO: TFloatField; qryManutencaoVLR_DESENVOLVIMENTO: TFloatField; qryManutencaoSITUACAO: TIntegerField; qryManutencaoOPERADOR: TStringField; qryManutencaoDT_ALTERACAO: TDateTimeField; qryManutencaoVLR_MENSAL: TFloatField; qryManutencaoOBS: TBlobField; qryManutencaoMES_CONTRATO: TStringField; qryManutencaoDIA_VENCTO: TIntegerField; qryManutencaoVLR_INI_MENSAL: TFloatField; qryManutencaoVRL_MAQ_EXEDENTE: TFloatField; qryManutencaoQTD_MAQ_INICIAL: TIntegerField; qryManutencaoQTD_MAQ_EXEDENTE: TIntegerField; qryManutencaoDT_INI_CONTRATO: TDateTimeField; qryManutencaoDT_ALTER_CONTRATO: TDateTimeField; qryLocalizacaoCGC: TStringField; qryLocalizacaoTREINAMENTO: TStringField; qryLocalizacaoDESENVOLVIMENTO: TStringField; qryLocalizacaoVLR_TREINAMENTO: TFloatField; qryLocalizacaoVLR_DESENVOLVIMENTO: TFloatField; qryLocalizacaoSITUACAO: TIntegerField; qryLocalizacaoOPERADOR: TStringField; qryLocalizacaoDT_ALTERACAO: TDateTimeField; qryLocalizacaoNM_CLIENTE: TStringField; qryLocalizacaoVLR_MENSAL: TFloatField; qryLocalizacaoOBS: TBlobField; qryLocalizacaoMES_CONTRATO: TStringField; qryLocalizacaoDIA_VENCTO: TIntegerField; qryLocalizacaoVLR_INI_MENSAL: TFloatField; qryLocalizacaoVRL_MAQ_EXEDENTE: TFloatField; qryLocalizacaoQTD_MAQ_INICIAL: TIntegerField; qryLocalizacaoQTD_MAQ_EXEDENTE: TIntegerField; qryLocalizacaoDT_INI_CONTRATO: TDateTimeField; qryLocalizacaoDT_ALTER_CONTRATO: TDateTimeField; qryManutencaoNM_CLIENTE: TStringField; qryManutencaoEMITE_NFSE: TStringField; qryLocalizacaoEMITE_NFSE: TStringField; procedure DataModuleDestroy(Sender: TObject); procedure qryManutencaoCalcFields(DataSet: TDataSet); private { Private declarations } sCod_Cliente: string; function GetCliente: string; procedure SetCliente(const Value: string); function GetC_SQL_DEFAUT: string; public { Public declarations } procedure MontaSQLBusca(DataSet: TDataSet = nil); override; procedure MontaSQLRefresh; override; property Cliente: string read GetCliente write SetCliente; property SQLDefault: string read GetC_SQL_DEFAUT; end; const C_SQL_DEFAUT = ' SELECT H.CGC, '+ ' H.TREINAMENTO, '+ ' H.DESENVOLVIMENTO, '+ ' H.VLR_TREINAMENTO, '+ ' H.VLR_DESENVOLVIMENTO, '+ ' H.MES_CONTRATO, '+ ' H.DIA_VENCTO, '+ ' H.OBS, '+ ' H.VLR_MENSAL, '+ ' H.OPERADOR, '+ ' H.DT_ALTERACAO, '+ ' H.SITUACAO, '+ ' H.VLR_INI_MENSAL, '+ ' H.VRL_MAQ_EXEDENTE, '+ ' H.QTD_MAQ_INICIAL, '+ ' H.QTD_MAQ_EXEDENTE, '+ ' H.DT_INI_CONTRATO, '+ ' H.DT_ALTER_CONTRATO, '+ ' H.EMITE_NFSE, ' + ' CLI.NOME AS NM_CLIENTE '+ ' FROM STWSACTHRS AS H '+ ' LEFT JOIN STWOPETCLI CLI ON CLI.CGC = H.CGC '; var dmHorasAtendimento: TdmHorasAtendimento; implementation uses udmCliente, udmPrincipal; {$R *.dfm} function TdmHorasAtendimento.GetC_SQL_DEFAUT: string; begin Result := C_SQL_DEFAUT; end; procedure TdmHorasAtendimento.DataModuleDestroy(Sender: TObject); begin inherited; dmHorasAtendimento := nil; end; function TdmHorasAtendimento.GetCliente: string; begin Result := sCod_Cliente; end; procedure TdmHorasAtendimento.MontaSQLBusca(DataSet: TDataSet); begin inherited; with (DataSet as TibcQuery) do begin SQL.Clear; // SQL.Add('SELECT * FROM STWSACTHRS'); SQL.Add(C_SQL_DEFAUT); SQL.Add('WHERE CGC = :CGC'); SQL.Add('ORDER BY CGC'); Params[0].AsString := sCod_Cliente; end; end; procedure TdmHorasAtendimento.MontaSQLRefresh; begin inherited; with qryManutencao do begin SQL.Clear; SQL.Add(C_SQL_DEFAUT); // SQL.Add('SELECT H.* FROM STWSACTHRS H'); // SQL.Add('LEFT JOIN STWOPETCLI C ON C.CGC = H.CGC'); // SQL.Add('ORDER BY C.NOME'); end; end; procedure TdmHorasAtendimento.SetCliente(const Value: string); begin sCod_Cliente := Value; end; procedure TdmHorasAtendimento.qryManutencaoCalcFields(DataSet: TDataSet); begin if not UtilizaCalculados then exit; if (DataSet as TibcQuery).State in [dsInsert, dsEdit] then exit; if not Assigned(dmCliente) then dmCliente := TdmCliente.Create(Application); dmCliente.UtilizaCalculados := False; dmCliente.Cod_Cliente := (DataSet as TibcQuery).FieldByName('CGC').AsString; if dmCliente.Localizar then (DataSet as TibcQuery).FieldByName('NM_CLIENTE').AsString := dmCliente.qryLocalizacaoNOME.AsString; // dmodClientes.UtilizaCalculados := True; end; end.
unit GX_Experts; {$I GX_CondDefine.inc} interface uses Classes, Graphics, Forms, ActnList, Menus, GX_Actions, GX_ConfigurationInfo, GX_BaseExpert; type TGX_Expert = class(TGX_BaseExpert) private FShortCut: TShortCut; FAction: IGxAction; procedure ActionOnUpdate(Sender: TObject); protected procedure SetShortCut(Value: TShortCut); override; function GetShortCut: TShortCut; override; function GetExpertIndex: Integer; procedure SetFormIcon(Form: TForm); procedure SetActive(New: Boolean); override; procedure UpdateAction(Action: TCustomAction); virtual; // Defaults to False function HasSubmenuItems: Boolean; virtual; // you usually don't need to override this procedure LoadActiveAndShortCut(Settings: TGExpertsSettings); override; // you usually don't need to override this procedure SaveActiveAndShortCut(Settings: TGExpertsSettings); override; public constructor Create; virtual; destructor Destroy; override; // Information functions that need to be overriden // by each expert to provide required registration // information. // Caption of a menu item entry. // Defaults to GetName (we don't want any abstract methods), // but descendants should override this method. function GetActionCaption: string; virtual; // Determine if the expert action is enabled function GetActionEnabled: Boolean; virtual; // Name of action to be created for expert; by default, // the action name is constructed from the expert's name. function GetActionName: string; // Name to be displayed for the expert in the GExperts // *configuration* dialog; this is a different entry than // the action caption (GetActionCaption) but by default // it calls GetActionCaption and removes any Hotkey characters and '...' // This is probably OK for most experts. function GetDisplayName: string; override; // Defaults to True function HasMenuItem: Boolean; virtual; // Defaults to False function HasDesignerMenuItem: Boolean; virtual; procedure DoCreateSubMenuItems(MenuItem: TMenuItem); procedure CreateSubMenuItems(MenuItem: TMenuItem); virtual; // procedure Execute(Sender: TObject); virtual; // declared in TGX_BaseExpert // Do any delayed setup after the IDE is done initializing procedure AfterIDEInitialized; virtual; // Update the action state procedure DoUpdateAction; // Calls HasMenuItem function CanHaveShortCut: boolean; override; // Index of expert; used to determine a "historic" // menu item order in the GExperts menu item. property ExpertIndex: Integer read GetExpertIndex; // Keyboard shortcut associated with the expert property ShortCut: TShortCut read GetShortCut write SetShortCut; end; TGX_ExpertClass = class of TGX_Expert; var GX_ExpertList: TList = nil; ExpertIndexLookup: TStringList = nil; procedure RegisterGX_Expert(AClass: TGX_ExpertClass); function GetGX_ExpertClassByIndex(const Index: Integer): TGX_ExpertClass; implementation uses {$IFOPT D+} GX_DbugIntf, {$ENDIF} SysUtils, Dialogs, GX_MenuActions, GX_MessageBox, GX_IconMessageBox, GX_GxUtils, GX_OtaUtils, GX_GenericUtils; { TGX_Expert } procedure TGX_Expert.ActionOnUpdate(Sender: TObject); begin DoUpdateAction; end; // Note: Don't call LoadSettings in Create. This is done for you // when the expert is created. See TGExperts.InstallAddIn. constructor TGX_Expert.Create; begin inherited Create; // Don't set Active to True. // Instead override IsDefaultActive and let LoadSettings do it FShortCut := GetDefaultShortCut; end; procedure TGX_Expert.CreateSubMenuItems(MenuItem: TMenuItem); begin // Override to create any submenu items in the main menu end; destructor TGX_Expert.Destroy; begin // Set active to False, this makes it possible to handle all creation and // destruction inside SetActive Active := False; inherited Destroy; end; function TGX_Expert.GetActionName: string; begin // Default action name from expert name; do not localize. Result := 'GX_' + GetName + 'Action'; end; function TGX_Expert.GetExpertIndex: Integer; var Index: Integer; begin Result := MaxInt - 10000; if ExpertIndexLookup.Find(ClassName, Index) then Result := Integer(ExpertIndexLookup.Objects[Index]); end; function TGX_Expert.HasMenuItem: Boolean; begin Result := True; end; function TGX_Expert.HasSubmenuItems: Boolean; begin Result := False; end; const ShortCutIdent = 'ExpertShortcuts'; // Do not localize. EnabledIdent = 'EnabledExperts'; // Do not localize. procedure TGX_Expert.LoadActiveAndShortCut(Settings: TGExpertsSettings); begin // Do not put these two Settings.xxx lines in InternalLoadSettings, // since a descendant might forget to call 'inherited' ShortCut := Settings.ReadInteger(ShortCutIdent, GetName, ShortCut); Active := Settings.ReadBool(EnabledIdent, GetName, IsDefaultActive); end; procedure TGX_Expert.SaveActiveAndShortCut(Settings: TGExpertsSettings); begin // Do not put these two Settings.xxx lines in InternalSaveSettings, // since a descendant might forget to call 'inherited' Settings.WriteBool(EnabledIdent, GetName, Active); Settings.WriteInteger(ShortCutIdent, GetName, ShortCut); end; procedure TGX_Expert.SetActive(New: Boolean); begin if New = FActive then Exit; FActive := New; if HasMenuItem then begin if New and not IsStandAlone then FAction := GXMenuActionManager.RequestMenuExpertAction(Self) else FAction := nil; end; if Assigned(FAction) then FAction.OnUpdate := ActionOnUpdate; end; function TGX_Expert.GetShortCut: TShortCut; begin Result := FShortCut; end; procedure TGX_Expert.SetShortCut(Value: TShortCut); begin FShortCut := Value; if Assigned(FAction) then FAction.ShortCut := FShortCut; end; { Globals } function GetGX_ExpertClass(const ClassName: string): TGX_ExpertClass; var i: Integer; begin Assert(GX_ExpertList <> nil, 'Uses clauses are out of order. GX_ExpertList is nil!'); for i := 0 to GX_ExpertList.Count - 1 do begin Result := GX_ExpertList[i]; if Result.ClassNameIs(ClassName) then Exit; end; Result := nil; end; function GetGX_ExpertClassByIndex(const Index: Integer): TGX_ExpertClass; begin Result := nil; if (Index >= 0) and (Index <= GX_ExpertList.Count - 1) then Result := GX_ExpertList[Index]; end; procedure RegisterGX_Expert(AClass: TGX_ExpertClass); var ExpertClassName: string; begin ExpertClassName := AClass.ClassName; {$IFOPT D+} SendDebug('Registering expert: ' + ExpertClassName); {$ENDIF D+} if GetGX_ExpertClass(ExpertClassName) <> nil then begin Assert(False, 'Duplicate call to RegisterGX_Expert for ' + ExpertClassName); Exit; end; GX_ExpertList.Add(AClass); end; procedure InitExpertIndexLookup; const OldExpertOrder: array [0..29] of string = ( 'TProcedureExpert', 'TExpertManagerExpert', 'TGrepDlgExpert', 'TGrepExpert', 'TMsgExpExpert', 'TBackupExpert', 'TTabExpert', 'TCleanExpert', 'TClipExpert', 'TFilesExpert', 'TClassExpert', 'TSourceExportExpert', 'TCodeLibExpert', 'TASCIIExpert', 'TPEExpert', 'TReplaceCompExpert', 'TGridExpert', 'TShortCutExpert', 'TDependExpert', 'TLayoutExpert', 'TToDoExpert', 'TCodeProofreaderExpert', 'TProjOptionSetsExpert', 'TCompsToCodeExpert', 'TCompRenameExpert', 'TCopyComponentNamesExpert', 'TGxMenusForEditorExperts', 'TMacroLibExpert', 'TOpenFileExpert', 'TFindCompRefWizard' ); var i: Integer; begin Assert(not Assigned(ExpertIndexLookup)); ExpertIndexLookup := TStringList.Create; for i := Low(OldExpertOrder) to High(OldExpertOrder) do ExpertIndexLookup.AddObject(OldExpertOrder[i], TObject(i)); ExpertIndexLookup.Sorted := True; end; procedure TGX_Expert.SetFormIcon(Form: TForm); var bmp: TBitmap; begin Assert(Assigned(Form)); bmp := GetBitmap; if Assigned(bmp) then ConvertBitmapToIcon(bmp, Form.Icon); end; function TGX_Expert.HasDesignerMenuItem: Boolean; begin Result := False; end; function TGX_Expert.GetActionCaption: string; begin Result := GetName; end; function TGX_Expert.GetActionEnabled: Boolean; begin Result := FAction.GetEnabled; end; procedure TGX_Expert.DoCreateSubMenuItems(MenuItem: TMenuItem); begin if HasSubMenuItems then if Assigned(MenuItem) then CreateSubMenuItems(MenuItem); end; procedure TGX_Expert.DoUpdateAction; begin UpdateAction(FAction.GetAction); end; function TGX_Expert.GetDisplayName: string; begin Result := StringReplace(GetActionCaption, '...', '', [rfReplaceAll]); Result := StripHotkey(Result); end; function TGX_Expert.CanHaveShortCut: boolean; begin Result := HasMenuItem; end; {$IFDEF GX_BCB} class function TGX_Expert.GetName: string; begin Result := ClassName; end; {$ENDIF} procedure TGX_Expert.UpdateAction(Action: TCustomAction); begin // Update Enabled, Visible, Caption, etc. end; procedure TGX_Expert.AfterIDEInitialized; begin // Do any delayed setup here that needs some later-created IDE items end; initialization GX_ExpertList := TList.Create; InitExpertIndexLookup; finalization FreeAndNil(GX_ExpertList); FreeAndNil(ExpertIndexLookup); end.
unit TestTelematicsSamplesUnit; interface uses TestFramework, Classes, SysUtils, BaseTestOnlineExamplesUnit; type TTestTelematicsSamples = class(TTestOnlineExamples) private published procedure GetAllVendors; procedure GetVendor; procedure SearchVendors; procedure CompareVendors; end; implementation uses VehicleUnit, VendorUnit, EnumsUnit, NullableBasicTypesUnit, CommonTypesUnit; procedure TTestTelematicsSamples.GetVendor; var ErrorString: String; VendorId: integer; Vendor: TVendor; begin VendorId := 153; Vendor := FRoute4MeManager.Telematics.Get(VendorId, ErrorString); try CheckEquals(EmptyStr, ErrorString); CheckNotNull(Vendor); finally FreeAndNil(Vendor); end; VendorId := -123; Vendor := FRoute4MeManager.Telematics.Get(VendorId, ErrorString); try CheckNotEquals(EmptyStr, ErrorString); CheckNull(Vendor); finally FreeAndNil(Vendor); end; end; procedure TTestTelematicsSamples.CompareVendors; var ErrorString: String; VendorIds: TStringArray; Vendors: TVendorList; begin SetLength(VendorIds, 3); VendorIds[0] := '55'; VendorIds[1] := '56'; VendorIds[2] := '57'; Vendors := FRoute4MeManager.Telematics.Compare(VendorIds, ErrorString); try CheckEquals(EmptyStr, ErrorString); CheckNotNull(Vendors); CheckEquals(3, Vendors.Count); finally FreeAndNil(Vendors); end; SetLength(VendorIds, 1); VendorIds[0] := '55'; Vendors := FRoute4MeManager.Telematics.Compare(VendorIds, ErrorString); try CheckEquals(EmptyStr, ErrorString); CheckNotNull(Vendors); CheckEquals(1, Vendors.Count); finally FreeAndNil(Vendors); end; SetLength(VendorIds, 1); VendorIds[0] := '-123'; Vendors := FRoute4MeManager.Telematics.Compare(VendorIds, ErrorString); try CheckNotEquals(EmptyStr, ErrorString); CheckNotNull(Vendors); CheckEquals(0, Vendors.Count); finally FreeAndNil(Vendors); end; SetLength(VendorIds, 2); VendorIds[0] := '55'; VendorIds[1] := '-123'; Vendors := FRoute4MeManager.Telematics.Compare(VendorIds, ErrorString); try CheckEquals(EmptyStr, ErrorString); CheckNotNull(Vendors); CheckEquals(1, Vendors.Count); finally FreeAndNil(Vendors); end; end; procedure TTestTelematicsSamples.GetAllVendors; var ErrorString: String; Vendors: TVendorList; begin Vendors := FRoute4MeManager.Telematics.Get(ErrorString); try CheckEquals(EmptyStr, ErrorString); CheckNotNull(Vendors); CheckTrue(Vendors.Count > 0); finally FreeAndNil(Vendors); end; end; procedure TTestTelematicsSamples.SearchVendors; var ErrorString: String; Vendors: TVendorList; Size: NullableVendorSizeType; IsIntegrated: NullableBoolean; Feature, Country, Search: NullableString; Page: NullableInteger; PerPage: NullableInteger; begin Size := TVendorSizeType.vsGlobal; IsIntegrated := True; Feature := 'Satellite'; Country := 'GB'; Search := NullableString.Null; Page := 1; PerPage := 15; Vendors := FRoute4MeManager.Telematics.Search(Size, IsIntegrated, Feature, Country, Search, Page, PerPage, ErrorString); try CheckEquals(EmptyStr, ErrorString); CheckNotNull(Vendors); CheckTrue(Vendors.Count > 0); finally FreeAndNil(Vendors); end; Size := TVendorSizeType.vsRegional; IsIntegrated := True; Feature := 'Satellite'; Country := 'AU'; Search := NullableString.Null; Page := 1; PerPage := 15; Vendors := FRoute4MeManager.Telematics.Search(Size, IsIntegrated, Feature, Country, Search, Page, PerPage, ErrorString); try CheckNotEquals(EmptyStr, ErrorString); CheckNotNull(Vendors); CheckTrue(Vendors.Count = 0); finally FreeAndNil(Vendors); end; Size := NullableVendorSizeType.Null; IsIntegrated := NullableBoolean.Null; Feature := 'Satellite'; Country := NullableString.Null; Search := NullableString.Null; Page := NullableInteger.Null; PerPage := NullableInteger.Null; Vendors := FRoute4MeManager.Telematics.Search(Size, IsIntegrated, Feature, Country, Search, Page, PerPage, ErrorString); try CheckEquals(EmptyStr, ErrorString); CheckNotNull(Vendors); CheckTrue(Vendors.Count > 0); finally FreeAndNil(Vendors); end; end; initialization RegisterTest('Examples\Online\Telematics\', TTestTelematicsSamples.Suite); end.
{!DOCTOPIC}{ TimeUtils module } {!DOCREF} { @method: var TimeUtils = TObjTime; @desc: Miscellaneous time related functions } {!DOCREF} { @method: function TimeUtils.Time(Offset:Double=0): Double; @desc: Return the time in seconds since the unix-epoch, as double. [code=pascal]...[/code] @keywords: TimeUtils, TimeUtils.Time, Time } function TObjTime.Time(Offset:UInt32=0): Double; begin Result := exp_TimeSinceEpoch(Offset); end; {!DOCREF} { @method: function TimeUtils.Format(FormatString:String; UnixTime:Double): String; @desc: Return the time as a formatted string [code=pascal]...[/code] @keywords: TimeUtils, TimeUtils.Format, Format } function TObjTime.Format(FormatString:String; UnixTime:Double): String; begin Result := exp_FormatEpochTime(FormatString, UnixTime); end; {!DOCREF} { @method: function TimeUtils.ToDateTime(UnixTime:Double): TDateTime; @desc: Converts Unix time in to TDateTime represntation. [code=pascal]...[/code] @keywords: TimeUtils, TimeUtils.EpochToDateTime, EpochToDateTime } function TObjTime.ToDateTime(UnixTime:Double): TDateTime; begin Result := exp_EpochToTime(UnixTime); end; {!DOCREF} { @method: procedure TimeUtils.Mark(var Timer:Double); @desc: Marks current time, used to with `TimeUtils.Ellapsed()` to get time ellapsed since marked. } procedure TObjTime.Mark(var Timer:Double); begin Timer := MarkTime(); end; {!DOCREF} { @method: procedure TimeUtils.Ellapsed(Timer:Double; usec:Boolean=False): Double; @desc: Returns the time in `ms` since `TimeUtils.Mark()` was called, if `usec = true` then it returns μs. } function TObjTime.Ellapsed(Timer:Double; usec:Boolean=False): Double; begin case usec of False: Result := Round((MarkTime() - Timer), 5); True: Result := Round((MarkTime() - Timer) * 1000, 5); end; end; {!DOCREF} { @method: procedure TimeUtils.Wait(ms:Double); @desc: High precision `Wait()` function. Should atleast beat the precition of the internal `Wait()`. } procedure TObjTime.Wait(ms:Double); begin ms := MarkTime() + ms - 0.002; while (MarkTime() < ms) do Continue; end;
unit DmdConnection; interface uses System.SysUtils, System.Classes, IdCoderMIME, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.FB, FireDAC.Phys.FBDef, FireDAC.VCLUI.Wait, Data.DB, FireDAC.Comp.Client, Data.SqlExpr; type TDMConection = class(TDataModule) FDConnection: TFDConnection; procedure DataModuleCreate(Sender: TObject); private { Private declarations } public { Public declarations } end; var DMConection: TDMConection; implementation uses System.IniFiles, Vcl.Forms, Vcl.Dialogs, uUtilPadrao; {%CLASSGROUP 'Vcl.Controls.TControl'} {$R *.dfm} procedure TDMConection.DataModuleCreate(Sender: TObject); var ArquivoIni, BancoDados, DriverName, UserName, PassWord : String; LocalServer : Integer; Configuracoes : TIniFile; Decoder64: TIdDecoderMIME; Encoder64: TIdEncoderMIME; begin Decoder64 := TIdDecoderMIME.Create(nil); ArquivoIni := ExtractFilePath(Application.ExeName) + '\Config.ini'; if not FileExists(ArquivoIni) then begin MessageDlg('Arquivo config.ini não encontrado!', mtInformation,[mbOK],0); Exit; end; Configuracoes := TIniFile.Create(ArquivoINI); try BancoDados := Configuracoes.ReadString('SSFacil', 'DATABASE', DriverName); DriverName := Configuracoes.ReadString('SSFacil', 'DriverName', DriverName); UserName := Configuracoes.ReadString('SSFacil', 'UserName', UserName); PassWord := Decoder64.DecodeString(Configuracoes.ReadString('SSFacil', 'PASSWORD', '')); finally Configuracoes.Free; Decoder64.Free; end; try FDConnection.Connected := False; FDConnection.Params.Clear; FDConnection.DriverName := 'FB'; FDConnection.Params.Values['DriveId'] := 'FB'; FDConnection.Params.Values['DataBase'] := BancoDados; FDConnection.Params.Values['User_Name'] := UserName; FDConnection.Params.Values['Password'] := PassWord; FDConnection.Connected := True; uUtilPadrao.vCaminhoBanco := BancoDados; except on E : Exception do begin raise Exception.Create('Erro ao conectar o Banco de dados ' + #13 + 'Mensagem: ' + e.Message + #13 + 'Classe: ' + e.ClassName + #13 + 'Banco de Dados: ' + BancoDados + #13 + 'Usuário: ' + UserName); end; end; end; end.
unit LocaleMessages; interface type TLocaleMessages = ( c_ApplicationTitle , c_Publisher // Common , c_CommonErrorMessage , c_CommonFileNotFound , c_CommonNotEmptyValueRequired , c_CommonUnableStartProcess , c_CommonUnexpectedException , c_CommonUnrecognisedParameterValue // Garant , c_GarantCannotCreateFolder , c_GarantCheckCopyResults , c_GarantCheckOperationFailed , c_GarantCheckUpdateInstallation , c_GarantCreateShortcutsOnDesktop , c_GarantCurrentUser , c_GarantEtalonSettingsFolderAbsent , c_GarantInstallUpdate , c_GarantOperationAborted , c_GarantOperationFailed , c_GarantRegistryOperationFailed , c_GarantSettingsCopyOperation , c_GarantSettingsExportOperation , c_GarantSettingsRestoreOperation , c_GarantSettingsRevertOperation , c_GarantSettingsSaveOperation , c_GarantUpdateLocalCache , c_GarantUnableGetDesktopPath , c_GarantVersionClient , c_GarantVersionDesktop , c_GarantVersionMobile , c_GarantVersionNetware , c_GarantVersionSuperMobile , c_GarantVersionUnknown , c_GarantVersionWorking , c_GarantWarningMessage // Garant: FolderNotExist , c_GarantFolderNotExistFormContinueButtonCaption , c_GarantFolderNotExistFormFolderNotExist , c_GarantFolderNotExistFormFolderNotExistButtonCaption , c_GarantFolderNotExistFormFolderNotExistFormLabelCaption , c_GarantFolderNotExistFormMainPanelLabelCaption , c_GarantFolderNotExistFormSkipButtonCaption // Garant: SelectInstallFolderForm , c_GarantSelectInstallFolderFormCancelButtonCaption , c_GarantSelectInstallFolderFormContinueButtonCaption , c_GarantSelectInstallFolderFormFirstRunClientProduct , c_GarantSelectInstallFolderFormFirstRunDesktopProduct , c_GarantSelectInstallFolderFormFirstRunMobileProduct , c_GarantSelectInstallFolderFormFirstRunNetwareProduct , c_GarantSelectInstallFolderFormFirstRunSuperMobileProduct , c_GarantSelectInstallFolderFormFirstRunUnknownProduct , c_GarantSelectInstallFolderFormFirstRunWorkingProduct , c_GarantSelectInstallFolderFormMainPanelSecondLabelCaption , c_GarantSelectInstallFolderFormNotEnoughFreeSpaceInFolder , c_GarantSelectInstallFolderFormResetDefaultFolderButtonCaption , c_GarantSelectInstallFolderFormSelectInstallFolderButtonCaption , c_GarantSelectInstallFolderFormSelectInstallFolderFormLabelCaption , c_GarantSelectInstallFolderFormUnableCreateFolder , c_GarantSelectInstallFolderFormUnableSelectFolder , c_GarantSelectInstallFolderFormUnwritableFolder // Garant: WaitMessageForm , c_GarantWaitMessageFormOperationInProgress // GarantCleaner , c_GarantCleanerDeleteAborted , c_GarantCleanerDeleteFailed , c_GarantCleanerErrorMessage , c_GarantCleanerProductUninstalled , c_GarantCleanerSubInfo , c_GarantCleanerUninstallProduct // Mini , c_MiniUseCreateStorageFile , c_MiniUseMultiFileEncoderCaption , c_MiniUseMultiFileEncoderSelectFolder , c_MiniUseMultiFileEncoderText , c_MiniUseMultiFileEncoding , c_MiniUseStatusSavedCaption , c_MiniUseStatusSavedText , c_MiniUseStatusSavedSuccessfullyCaption , c_MiniUseStatusSavedSuccessfullyText , c_MiniUseStorageCreatedCaption , c_MiniUseStorageCreatedText , c_MiniUseStorageFileFull , c_MiniUseStorageUnsupportedIntegerSize // Logo , c_LogoLoading // Protection , c_ProtectionFailure ); procedure SetCurrentLocale(const a_LocaleValue: string); function GetCurrentLocaleMessage(const a_LocaleMessages: TLocaleMessages): string; procedure SetLocaleApplicationTitle; implementation uses SysUtils, Forms; var g_LocaleMessagesArray: array [TLocaleMessages] of record r_Current: PChar; // r_English: PChar; r_Russian: PChar; end = ( ( r_Current: nil // c_ApplicationTitle ; r_English: 'GARANT aero' ; r_Russian: 'ГАРАНТ аэро' ) , ( r_Current: nil // c_Publisher ; r_English: 'SIE "GARANT-SERVICE-UNIVERSITY" LLC' ; r_Russian: 'ООО НПП "ГАРАНТ-СЕРВИС-УНИВЕРСИТЕТ"' ) // Common , ( r_Current: nil // c_CommonErrorMessage ; r_English: '%s'#13#13'Cannot continue working with system.'#13#13'Install product again from installation disk or'#13'apply to your servicing organization.' ; r_Russian: '%s'#13#13'Дальнейшая работа невозможна.'#13#13'Попробуйте заново установить продукт с дистрибутива или'#13'обратитесь в обслуживающую Вас организацию.' ) , ( r_Current: nil // c_CommonFileNotFound ; r_English: 'Cannot find file "%s" (it was possibly deleted or corrupted).' ; r_Russian: 'Не могу найти файл "%s" (возможно он был удален или поврежден).' ) , ( r_Current: nil // c_CommonNotEmptyValueRequired ; r_English: 'Parameter value "\[%s]\%s" in file "%s" cannot be empty.' ; r_Russian: 'Значение параметра "\[%s]\%s" в файле "%s" не может быть пустым.' ) , ( r_Current: nil // c_CommonUnableStartProcess ; r_English: 'Cannot start process: "%s".' ; r_Russian: 'Не могу стартовать процесс: "%s".' ) , ( r_Current: nil // c_CommonUnexpectedException ; r_English: 'Unexpected program error, exception:'#13'%s.' ; r_Russian: 'Непредвиденная ошибка программы, исключение:'#13'%s.' ) , ( r_Current: nil // c_CommonUnrecognisedParameterValue ; r_English: 'Unknown parameter value "%s=%s".' ; r_Russian: 'Неизвестное значение параметра "%s=%s".' ) // Garant , ( r_Current: nil // c_GarantCannotCreateFolder ; r_English: 'Cannot create folder "%s".' ; r_Russian: 'Не могу создать папку "%s".' ) , ( r_Current: nil // c_GarantCheckCopyResults ; r_English: 'Checking copy results' ; r_Russian: 'Проверка результатов копирования' ) , ( r_Current: nil // c_GarantCheckOperationFailed ; r_English: 'Checking operation "%s" failed.'#13#13'File "%s" content not equal'#13'to file "%s" content.' ; r_Russian: 'Проверка операции "%s" закончилась неудачей.'#13#13'Содержимое файла "%s" не совпадает'#13'с содержимым файла "%s".' ) , ( r_Current: nil // c_GarantCheckUpdateInstallation ; r_English: 'Checking update results <%s>' ; r_Russian: 'Проверка установки обновления <%s>' ) , ( r_Current: nil // c_GarantCreateShortcutsOnDesktop ; r_English: 'Do you want to create shortcuts on your desktop?' ; r_Russian: 'Произвести создание необходимых ярлыков на вашем рабочем столе?' ) , ( r_Current: nil // c_GarantCurrentUser ; r_English: 'Current User' ; r_Russian: 'Текущий Пользователь' ) , ( r_Current: nil // c_GarantEtalonSettingsFolderAbsent ; r_English: 'Default settings folder for user "%s" is absent.' ; r_Russian: 'Каталог эталонных настроек пользователя "%s" отсутствует.' ) , ( r_Current: nil // c_GarantInstallUpdate ; r_English: 'Updating <%s>' ; r_Russian: 'Установка обновления <%s>' ) , ( r_Current: nil // c_GarantOperationAborted ; r_English: 'Operation "%s" was interrupted.' ; r_Russian: 'Операция "%s" была прервана.' ) , ( r_Current: nil // c_GarantOperationFailed ; r_English: 'Operation "%s" was failed.' ; r_Russian: 'Операция "%s" закончилась неудачей.' ) , ( r_Current: nil // c_GarantRegistryOperationFailed ; r_English: 'Unable to do necessary operation with registry.' ; r_Russian: 'Невозможно произвести необходимые операции с реестром.' ) , ( r_Current: nil // c_GarantSettingsCopyOperation ; r_English: 'Installation default user settings' ; r_Russian: 'Установка эталонных настроек пользователя' ) , ( r_Current: nil // c_GarantSettingsExportOperation ; r_English: 'Export user settings' ; r_Russian: 'Экспорт настроек пользователя' ) , ( r_Current: nil // c_GarantSettingsRestoreOperation ; r_English: 'Restoration saved user settings' ; r_Russian: 'Восстановление сохраненных настроек пользователя' ) , ( r_Current: nil // c_GarantSettingsRevertOperation ; r_English: 'Undo installation default user settings' ; r_Russian: 'Откат установки эталонных настроек пользователя' ) , ( r_Current: nil // c_GarantSettingsSaveOperation ; r_English: 'Saving current user settings' ; r_Russian: 'Сохранение текущих настроек пользователя' ) , ( r_Current: nil // c_GarantUpdateLocalCache ; r_English: 'Update data cache' ; r_Russian: 'Обновление кешированных данных' ) , ( r_Current: nil // c_GarantUnableGetDesktopPath ; r_English: 'Unable get path to desktop folder.' ; r_Russian: 'Не могу получить путь к каталогу рабочего стола.' ) , ( r_Current: nil // c_GarantVersionClient ; r_English: 'Client' ; r_Russian: 'Клиент' ) , ( r_Current: nil // c_GarantVersionDesktop ; r_English: 'Local' ; r_Russian: 'Локальная' ) , ( r_Current: nil // c_GarantVersionMobile ; r_English: 'Mobile' ; r_Russian: 'Мобильная' ) , ( r_Current: nil // c_GarantVersionNetware ; r_English: 'FileServer' ; r_Russian: 'ФайлСервер' ) , ( r_Current: nil // c_GarantVersionSuperMobile ; r_English: 'Mobile Online' ; r_Russian: 'Мобильная Онлайн' ) , ( r_Current: nil // c_GarantVersionUnknown ; r_English: 'Unknown' ; r_Russian: 'Неизвестная' ) , ( r_Current: nil // c_GarantVersionWorking ; r_English: 'Working' ; r_Russian: 'Рабочая' ) , ( r_Current: nil // c_GarantWarningMessage ; r_English: '%s'#13#13'After OK pressed prorgram will launch with default settings.'#13#13'Previous settings was saved.'#13'If you want to repair it -'#13'please apply to your servicing organization:' ; r_Russian: '%s'#13#13'После нажатия ОК программа запустится с настройками по умолчанию.'#13#13'Настройки предыдущей версии сохранены.'#13'В случае, если они представляют для Вас ценность -'#13'пожалуйста, обратитесь в обслуживающую Вас организацию:' ) // Garant: FolderNotExist , ( r_Current: nil // c_GarantFolderNotExistFormContinueButtonCaption ; r_English: 'Continue' ; r_Russian: 'Продолжить' ) , ( r_Current: nil // c_GarantFolderNotExistFormFolderNotExist ; r_English: 'Folder not exist!'#13'You have to select exist folder.' ; r_Russian: 'Указанный каталог не существует!'#13'Вы должны указать существующий каталог.' ) , ( r_Current: nil // c_GarantFolderNotExistFormFolderNotExistButtonCaption ; r_English: 'Select...' ; r_Russian: 'Выберите...' ) , ( r_Current: nil // c_GarantFolderNotExistFormFolderNotExistFormLabelCaption ; r_English: 'Folder not exist' ; r_Russian: 'Папка не существует' ) , ( r_Current: nil // c_GarantFolderNotExistFormMainPanelLabelCaption ; r_English: 'Select replace folder:' ; r_Russian: 'Укажите папку для замены:' ) , ( r_Current: nil // c_GarantFolderNotExistFormSkipButtonCaption ; r_English: 'Skip' ; r_Russian: 'Пропустить' ) // Garant: SelectInstallFolderForm , ( r_Current: nil // c_GarantSelectInstallFolderFormCancelButtonCaption ; r_English: 'Cancel' ; r_Russian: 'Отмена' ) , ( r_Current: nil // c_GarantSelectInstallFolderFormContinueButtonCaption ; r_English: 'Continue' ; r_Russian: 'Начать работу' ) , ( r_Current: nil // c_GarantSelectInstallFolderFormFirstRunClientProduct ; r_English: 'This is the first launch of client version.' ; r_Russian: 'Вы впервые запустили клиентскую версию продукта.' ) , ( r_Current: nil // c_GarantSelectInstallFolderFormFirstRunDesktopProduct ; r_English: 'This is the first launch of local version.' ; r_Russian: 'Вы впервые запустили локальную версию продукта.' ) , ( r_Current: nil // c_GarantSelectInstallFolderFormFirstRunMobileProduct ; r_English: 'This is the first launch of mobile version.' ; r_Russian: 'Вы впервые запустили мобильную версию продукта.' ) , ( r_Current: nil // c_GarantSelectInstallFolderFormFirstRunNetwareProduct ; r_English: 'This is the first launch of file-server version.' ; r_Russian: 'Вы впервые запустили файл-серверную версию продукта.' ) , ( r_Current: nil // c_GarantSelectInstallFolderFormFirstRunSuperMobileProduct ; r_English: 'This is the first launch of mobile-online version.' ; r_Russian: 'Вы впервые запустили мобильную онлайн версию продукта.' ) , ( r_Current: nil // c_GarantSelectInstallFolderFormFirstRunUnknownProduct ; r_English: 'This is the first launch of program.' ; r_Russian: 'Вы впервые запустили продукт.' ) , ( r_Current: nil // c_GarantSelectInstallFolderFormFirstRunWorkingProduct ; r_English: 'This is the first launch of CD or DVD version.' ; r_Russian: 'Вы впервые запустили рабочую версию продукта.' ) , ( r_Current: nil // c_GarantSelectInstallFolderFormMainPanelSecondLabelCaption ; r_English: 'Select personal settings folder:' ; r_Russian: 'Укажите папку для Ваших личных настроек:' ) , ( r_Current: nil // c_GarantSelectInstallFolderFormNotEnoughFreeSpaceInFolder ; r_English: 'Not enough free space in selected folder.' ; r_Russian: 'В указанной папке недостаточно свободного места.' ) , ( r_Current: nil // c_GarantSelectInstallFolderFormResetDefaultFolderButtonCaption ; r_English: 'Return to default folder' ; r_Russian: 'Вернуться к папке по умолчанию' ) , ( r_Current: nil // c_GarantSelectInstallFolderFormSelectInstallFolderButtonCaption ; r_English: 'Select...' ; r_Russian: 'Выберите...' ) , ( r_Current: nil // c_GarantSelectInstallFolderFormSelectInstallFolderFormLabelCaption ; r_English: 'Select installation folder' ; r_Russian: 'Выберите папку для установки' ) , ( r_Current: nil // c_GarantSelectInstallFolderFormUnableCreateFolder ; r_English: 'Cannot create folder. Select other folder to store settings.' ; r_Russian: 'Ошибка создания папки, возможно, не хватает прав или указан неверный путь. Выберите другую папку для сохранения настроек.' ) , ( r_Current: nil // c_GarantSelectInstallFolderFormUnableSelectFolder ; r_English: 'This folder cannot be used, because it is installation folder or one of its subfolders.' ; r_Russian: 'Указанная папка не может быть выбрана, т.к. она указывает на каталог или подкаталог дистрибутива.' ) , ( r_Current: nil // c_GarantSelectInstallFolderFormUnwritableFolder ; r_English: 'This folder is write-protected.' ; r_Russian: 'В указанной папке отсутствуют права на запись.' ) // Garant: WaitMessageForm , ( r_Current: nil // c_GarantWaitMessageFormOperationInProgress ; r_English: #13#10'Processing operation "%s".'#13#10#13#10'Wait, please...' ; r_Russian: #13#10'Идет операция "%s".'#13#10#13#10'Пожалуйста, подождите...' ) // GarantCleaner , ( r_Current: nil // c_GarantCleanerDeleteAborted ; r_English: 'Deleting folder "%s" was interrupted.' ; r_Russian: 'Операция удаления каталога "%s" была прервана.' ) , ( r_Current: nil // c_GarantCleanerDeleteFailed ; r_English: 'Deleting folder "%s" was failed.' ; r_Russian: 'Операция удаления каталога "%s" закончилась неудачей.' ) , ( r_Current: nil // c_GarantCleanerErrorMessage ; r_English: '%s'#13#13'Deleting program will not further proceed.' ; r_Russian: '%s'#13#13'Дальнейшая работа программы удаления невозможна.' ) , ( r_Current: nil // c_GarantCleanerProductUninstalled ; r_English: '"%s" uninstalled successfully.' ; r_Russian: '"%s" успешно удален.' ) , ( r_Current: nil // c_GarantCleanerSubInfo ; r_English: 'current settings remove' ; r_Russian: 'удаление текущих настроек' ) , ( r_Current: nil // c_GarantCleanerUninstallProduct ; r_English: 'Do you want to uninstall "%s"?' ; r_Russian: 'Вы действительно хотите удалить "%s"?' ) // Mini , ( r_Current: nil // c_MiniUseCreateStorageFile ; r_English: 'Create STORAGE file' ; r_Russian: 'Создание файла ХРАНИЛИЩА' ) , ( r_Current: nil // c_MiniUseMultiFileEncoderCaption ; r_English: 'GARANT system update' ; r_Russian: 'Обновление системы ГАРАНТ' ) , ( r_Current: nil // c_MiniUseMultiFileEncoderSelectFolder ; r_English: 'Select folder for the status of installation saving:' ; r_Russian: 'Выберите папку для сохранения статуса установки:' ) , ( r_Current: nil // c_MiniUseMultiFileEncoderText ; r_English: 'Save the status of installation?'#13#13'(this functionality is for GARANT support engineers only)' ; r_Russian: 'Сохранить статус установки?'#13#13'(данная функциональность предназначена только для специалистов по сервисному обслуживанию системы ГАРАНТ)' ) , ( r_Current: nil // c_MiniUseMultiFileEncoding ; r_English: 'Saving the status of installation' ; r_Russian: 'Сохранение статуса установки' ) , ( r_Current: nil // c_MiniUseStatusSavedCaption ; r_English: 'GARANT system update' ; r_Russian: 'Обновление системы ГАРАНТ' ) , ( r_Current: nil // c_MiniUseStatusSavedText ; r_English: 'The status of installation is saved.' ; r_Russian: 'Статус установки сохранен.' ) , ( r_Current: nil // c_MiniUseStatusSavedSuccessfullyCaption ; r_English: 'GARANT system update' ; r_Russian: 'Обновление системы ГАРАНТ' ) , ( r_Current: nil // c_MiniUseStatusSavedSuccessfullyText ; r_English: 'The status of installation is successfully saved.' ; r_Russian: 'Статус установки успешно сохранен.' ) , ( r_Current: nil // c_MiniUseStorageCreatedCaption ; r_English: 'GARANT system update' ; r_Russian: 'Обновление системы ГАРАНТ' ) , ( r_Current: nil // c_MiniUseStorageCreatedText ; r_English: 'The STORAGE creation is successfully finished.' ; r_Russian: 'Создание ХРАНИЛИЩА успешно завершено.' ) , ( r_Current: nil // c_MiniUseStorageFileFull ; r_English: 'The STORAGE file full!' ; r_Russian: 'В файле ХРАНИЛИЩА недостаточно свободного места!' ) , ( r_Current: nil // c_MiniUseStorageUnsupportedIntegerSize ; r_English: 'Unsupported size of "integer" type!' ; r_Russian: 'Не поддерживаемый размер типа "integer"!' ) // Logo , ( r_Current: nil // c_LogoLoading ; r_English: 'Loading...' ; r_Russian: 'Идет загрузка...' ) // Protection , ( r_Current: nil // c_ProtectionFailure ; r_English: 'Protection failure: %d' ; r_Russian: 'Ошибка защиты: %d' ) ); procedure SetCurrentLocale(const a_LocaleValue: string); const c_English = 1; c_Russian = 2; c_Default = c_English; // function GetLanguage(const a_LocaleValue: string): Word; begin Result := c_Default; // if (StrLIComp(PChar(a_LocaleValue), PChar('en'), 2) = 0) then Result := c_English else if (StrLIComp(PChar(a_LocaleValue), PChar('ru'), 2) = 0) then Result := c_Russian; end; // var l_Index: TLocaleMessages; l_Language: Word; begin l_Language := GetLanguage(a_LocaleValue); // for l_Index := Low(g_LocaleMessagesArray) to High(g_LocaleMessagesArray) do case l_Language of c_English: g_LocaleMessagesArray[l_Index].r_Current := g_LocaleMessagesArray[l_Index].r_English; c_Russian: g_LocaleMessagesArray[l_Index].r_Current := g_LocaleMessagesArray[l_Index].r_Russian; else g_LocaleMessagesArray[l_Index].r_Current := g_LocaleMessagesArray[l_Index].r_English; end; end; function GetCurrentLocaleMessage(const a_LocaleMessages: TLocaleMessages): string; begin Result := g_LocaleMessagesArray[a_LocaleMessages].r_Current; end; procedure SetLocaleApplicationTitle; begin Application.Title := GetCurrentLocaleMessage(c_ApplicationTitle); end; initialization SetCurrentLocale('$(UserDefaultLocale)'); // First initialization as User Default Locale (== English now) end.
{ Clever Internet Suite Copyright (C) 2013 Clever Components All Rights Reserved www.CleverComponents.com } unit clServerGuard; interface {$I clVer.inc} uses {$IFNDEF DELPHIXE2} Classes, Contnrs, SyncObjs, Windows, {$ELSE} System.Classes, System.Contnrs, System.SyncObjs, Winapi.Windows, {$ENDIF} clUtils; type TclGuardConnectionLimit = class(TPersistent) private FMax: Integer; FPeriod: Integer; public constructor Create; procedure Assign(Source: TPersistent); override; published property Max: Integer read FMax write FMax default 6; property Period: Integer read FPeriod write FPeriod default 60000; end; TclGuardLoginDelay = class(TPersistent) private FMax: Integer; FIncrement: Integer; FMin: Integer; FIsIncremental: Boolean; FIsRandom: Boolean; public constructor Create; procedure Assign(Source: TPersistent); override; published property Min: Integer read FMin write FMin default 10; property Max: Integer read FMax write FMax default 5000; property Increment: Integer read FIncrement write FIncrement default 1000; property IsIncremental: Boolean read FIsIncremental write FIsIncremental default True; property IsRandom: Boolean read FIsRandom write FIsRandom default True; end; TclGuardConnectionInfo = class private FIP: string; FPort: Integer; FTime: Integer; FAttempts: Integer; public constructor Create(const AIP: string; APort, ATime: Integer); function NewAttempt: Integer; property IP: string read FIP; property Port: Integer read FPort; property Time: Integer read FTime; property Attempts: Integer read FAttempts; end; TclGuardUserInfo = class(TclGuardConnectionInfo) private FUserName: string; FDelay: Integer; public constructor Create(const AUserName, AIP: string; APort, ATime: Integer); property UserName: string read FUserName; property Delay: Integer read FDelay write FDelay; end; TclGuardConnectionInfoList = class private FList: TObjectList; function GetCount: Integer; protected function GetItem(Index: Integer): TclGuardConnectionInfo; public constructor Create; destructor Destroy; override; procedure Add(AItem: TclGuardConnectionInfo); procedure Delete(Index: Integer); procedure Clear; property Items[Index: Integer]: TclGuardConnectionInfo read GetItem; default; property Count: Integer read GetCount; end; TclGuardUserInfoList = class(TclGuardConnectionInfoList) private function GetItem(Index: Integer): TclGuardUserInfo; public property Items[Index: Integer]: TclGuardUserInfo read GetItem; default; end; TclGuardConnectionEvent = procedure(Sender: TObject; const AIP: string; APort: Integer; ATime: Integer) of object; TclGuardCanConnectEvent = procedure(Sender: TObject; const AIP: string; APort: Integer; ATime: Integer; var Allowed, Handled: Boolean) of object; TclGuardUserEvent = procedure(Sender: TObject; const AUserName, AIP: string; APort: Integer; ATime: Integer) of object; TclGuardGetDelayEvent = procedure(Sender: TObject; AUser: TclGuardUserInfo; var ADelay: Integer; var Handled: Boolean) of object; TclGuardCanLoginEvent = procedure(Sender: TObject; const AUserName, AIP: string; APort: Integer; ATime: Integer; var Allowed, Handled: Boolean) of object; TclServerGuard = class(TComponent) private FOnCanConnect: TclGuardCanConnectEvent; FOnAddUser: TclGuardUserEvent; FOnAllowConnection: TclGuardConnectionEvent; FOnRemoveConnection: TclGuardConnectionEvent; FOnBlockConnection: TclGuardConnectionEvent; FOnLockUser: TclGuardUserEvent; FOnCanLogin: TclGuardCanLoginEvent; FOnAddConnection: TclGuardConnectionEvent; FOnGetDelay: TclGuardGetDelayEvent; FOnRemoveUser: TclGuardUserEvent; FUsers: TclGuardUserInfoList; FConnections: TclGuardConnectionInfoList; FEnableLoginCheck: Boolean; FEnableConnectCheck: Boolean; FAllowWhiteListOnly: Boolean; FLockedUsers: TStrings; FBlackIPList: TStrings; FWhiteIPList: TStrings; FLoginDelay: TclGuardLoginDelay; FConnectionLimit: TclGuardConnectionLimit; FAccessor: TCriticalSection; procedure SetLockedUsers(const Value: TStrings); procedure SetBlackIPList(const Value: TStrings); procedure SetWhiteIPList(const Value: TStrings); procedure SetLoginDelay(const Value: TclGuardLoginDelay); procedure SetConnectionLimit(const Value: TclGuardConnectionLimit); function GetWildcardIP(const AIP: string): string; function GetLoginDelay(AUser: TclGuardUserInfo): Integer; protected procedure DoAllowConnection(const AIP: string; APort: Integer; ATime: Integer); procedure DoBlockConnection(const AIP: string; APort: Integer; ATime: Integer); procedure DoAddConnection(const AIP: string; APort: Integer; ATime: Integer); procedure DoRemoveConnection(const AIP: string; APort: Integer; ATime: Integer); procedure DoCanConnect(const AIP: string; APort: Integer; ATime: Integer; var Allowed, Handled: Boolean); procedure DoLockUser(const AUserName, AIP: string; APort: Integer; ATime: Integer); procedure DoAddUser(const AUserName, AIP: string; APort: Integer; ATime: Integer); procedure DoRemoveUser(const AUserName, AIP: string; APort: Integer; ATime: Integer); procedure DoGetDelay(AUser: TclGuardUserInfo; var ADelay: Integer; var Handled: Boolean); procedure DoCanLogin(const AUserName, AIP: string; APort: Integer; ATime: Integer; var Allowed, Handled: Boolean); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function Connect(const AIP: string; APort: Integer): Boolean; virtual; function Login(const AUserName: string; AIsAuthorized: Boolean; const AIP: string; APort: Integer): Boolean; virtual; procedure Reset; virtual; function IsBlackListed(const AIP: string; APort, ATime: Integer): Boolean; function IsWhiteListed(const AIP: string; APort, ATime: Integer): Boolean; function IsLockedUser(const AUserName, AIP: string; APort, ATime: Integer): Boolean; property Users: TclGuardUserInfoList read FUsers; property Connections: TclGuardConnectionInfoList read FConnections; published property ConnectionLimit: TclGuardConnectionLimit read FConnectionLimit write SetConnectionLimit; property LoginDelay: TclGuardLoginDelay read FLoginDelay write SetLoginDelay; property WhiteIPList: TStrings read FWhiteIPList write SetWhiteIPList; property BlackIPList: TStrings read FBlackIPList write SetBlackIPList; property LockedUsers: TStrings read FLockedUsers write SetLockedUsers; property AllowWhiteListOnly: Boolean read FAllowWhiteListOnly write FAllowWhiteListOnly default False; property EnableConnectCheck: Boolean read FEnableConnectCheck write FEnableConnectCheck default True; property EnableLoginCheck: Boolean read FEnableLoginCheck write FEnableLoginCheck default True; property OnAllowConnection: TclGuardConnectionEvent read FOnAllowConnection write FOnAllowConnection; property OnBlockConnection: TclGuardConnectionEvent read FOnBlockConnection write FOnBlockConnection; property OnAddConnection: TclGuardConnectionEvent read FOnAddConnection write FOnAddConnection; property OnRemoveConnection: TclGuardConnectionEvent read FOnRemoveConnection write FOnRemoveConnection; property OnCanConnect: TclGuardCanConnectEvent read FOnCanConnect write FOnCanConnect; property OnLockUser: TclGuardUserEvent read FOnLockUser write FOnLockUser; property OnAddUser: TclGuardUserEvent read FOnAddUser write FOnAddUser; property OnRemoveUser: TclGuardUserEvent read FOnRemoveUser write FOnRemoveUser; property OnGetDelay: TclGuardGetDelayEvent read FOnGetDelay write FOnGetDelay; property OnCanLogin: TclGuardCanLoginEvent read FOnCanLogin write FOnCanLogin; end; implementation { TclServerGuard } function TclServerGuard.Connect(const AIP: string; APort: Integer): Boolean; var i: Integer; currentTime: Integer; handled: Boolean; conn, info: TclGuardConnectionInfo; begin if (not EnableConnectCheck) then begin Result := True; Exit; end; FAccessor.Enter(); try currentTime := Integer(GetTickCount()); Result := False; handled := False; DoCanConnect(AIP, APort, currentTime, Result, handled); if handled then begin Exit; end; if (AIP = '') then begin DoBlockConnection(AIP, APort, currentTime); Result := False; Exit; end; if IsBlackListed(AIP, APort, currentTime) then begin Result := False; Exit; end; if IsWhiteListed(AIP, APort, currentTime) then begin Result := True; Exit; end else if AllowWhiteListOnly then begin Result := False; Exit; end; conn := nil; for i := Connections.Count - 1 downto 0 do begin info := Connections[i]; if ((currentTime - info.Time) < ConnectionLimit.Period) then begin if (info.IP = AIP) then begin conn := info; end; end else begin Connections.Delete(i); DoRemoveConnection(AIP, APort, currentTime); end; end; if (conn = nil) then begin conn := TclGuardConnectionInfo.Create(AIP, APort, currentTime); Connections.Add(conn); DoAddConnection(AIP, APort, currentTime); end; Result := conn.NewAttempt() <= ConnectionLimit.Max; if Result then begin DoAllowConnection(AIP, APort, currentTime); end else begin DoBlockConnection(AIP, APort, currentTime); end; finally FAccessor.Leave(); end; end; constructor TclServerGuard.Create(AOwner: TComponent); begin inherited Create(AOwner); FAccessor := TCriticalSection.Create(); FConnectionLimit := TclGuardConnectionLimit.Create(); FLoginDelay := TclGuardLoginDelay.Create(); FConnections := TclGuardConnectionInfoList.Create(); FUsers := TclGuardUserInfoList.Create(); FWhiteIPList := TStringList.Create(); FBlackIPList := TStringList.Create(); FLockedUsers := TStringList.Create(); FEnableConnectCheck := True; FEnableLoginCheck := True; Randomize(); end; destructor TclServerGuard.Destroy; begin FLockedUsers.Free(); FBlackIPList.Free(); FWhiteIPList.Free(); FUsers.Free(); FConnections.Free(); FLoginDelay.Free(); FConnectionLimit.Free(); FAccessor.Free(); inherited Destroy(); end; procedure TclServerGuard.DoAddConnection(const AIP: string; APort, ATime: Integer); begin if Assigned(OnAddConnection) then begin OnAddConnection(Self, AIP, APort, ATime); end; end; procedure TclServerGuard.DoAddUser(const AUserName, AIP: string; APort, ATime: Integer); begin if Assigned(OnAddUser) then begin OnAddUser(Self, AUserName, AIP, APort, ATime); end; end; procedure TclServerGuard.DoAllowConnection(const AIP: string; APort, ATime: Integer); begin if Assigned(OnAllowConnection) then begin OnAllowConnection(Self, AIP, APort, ATime); end; end; procedure TclServerGuard.DoBlockConnection(const AIP: string; APort, ATime: Integer); begin if Assigned(OnBlockConnection) then begin OnBlockConnection(Self, AIP, APort, ATime); end; end; procedure TclServerGuard.DoCanConnect(const AIP: string; APort, ATime: Integer; var Allowed, Handled: Boolean); begin if Assigned(OnCanConnect) then begin OnCanConnect(Self, AIP, APort, ATime, Allowed, Handled); end; end; procedure TclServerGuard.DoCanLogin(const AUserName, AIP: string; APort, ATime: Integer; var Allowed, Handled: Boolean); begin if Assigned(OnCanLogin) then begin OnCanLogin(Self, AUserName, AIP, APort, ATime, Allowed, Handled); end; end; procedure TclServerGuard.DoGetDelay(AUser: TclGuardUserInfo; var ADelay: Integer; var Handled: Boolean); begin if Assigned(OnGetDelay) then begin OnGetDelay(Self, AUser, ADelay, Handled); end; end; procedure TclServerGuard.DoLockUser(const AUserName, AIP: string; APort, ATime: Integer); begin if Assigned(OnLockUser) then begin OnLockUser(Self, AUserName, AIP, APort, ATime); end; end; procedure TclServerGuard.DoRemoveConnection(const AIP: string; APort, ATime: Integer); begin if Assigned(OnRemoveConnection) then begin OnRemoveConnection(Self, AIP, APort, ATime); end; end; procedure TclServerGuard.DoRemoveUser(const AUserName, AIP: string; APort, ATime: Integer); begin if Assigned(OnRemoveUser) then begin OnRemoveUser(Self, AUserName, AIP, APort, ATime); end; end; function TclServerGuard.GetLoginDelay(AUser: TclGuardUserInfo): Integer; var range: Integer; handled: Boolean; begin Result := 0; handled := False; DoGetDelay(AUser, Result, handled); if handled then begin AUser.Delay := Result; Exit; end; Result := 0; if LoginDelay.IsRandom and (LoginDelay.Min < LoginDelay.Max) then begin range := LoginDelay.Max - LoginDelay.Min; Result := Random(range) + LoginDelay.Min; end; if LoginDelay.IsIncremental then begin Result := Result + AUser.Delay + LoginDelay.Increment; end; AUser.Delay := Result; end; function TclServerGuard.GetWildcardIP(const AIP: string): string; var ind: Integer; begin Result := AIP; if (Result = '') then Exit; ind := RTextPos('.', AIP); if (ind > 0) then begin Result := Copy(Result, 1, ind - 1) + '.*'; end; end; function TclServerGuard.IsBlackListed(const AIP: string; APort, ATime: Integer): Boolean; begin Result := (BlackIPList.IndexOf(AIP) > -1) or (BlackIPList.IndexOf(GetWildcardIP(AIP)) > -1); if Result then begin DoBlockConnection(AIP, APort, ATime); end; end; function TclServerGuard.IsLockedUser(const AUserName, AIP: string; APort, ATime: Integer): Boolean; begin Result := LockedUsers.IndexOf(AUserName) > -1; if Result then begin DoLockUser(AUserName, AIP, APort, ATime); end; end; function TclServerGuard.IsWhiteListed(const AIP: string; APort, ATime: Integer): Boolean; begin Result := (WhiteIPList.IndexOf(AIP) > -1) or (WhiteIPList.IndexOf(GetWildcardIP(AIP)) > -1); if Result then begin DoAllowConnection(AIP, APort, ATime); end; end; function TclServerGuard.Login(const AUserName: string; AIsAuthorized: Boolean; const AIP: string; APort: Integer): Boolean; var i: Integer; currentTime, delay: Integer; handled: Boolean; user, info: TclGuardUserInfo; begin if (not EnableLoginCheck) then begin Result := AIsAuthorized; Exit; end; currentTime := Loword(GetTickCount()); FAccessor.Enter(); try Result := False; handled := False; DoCanLogin(AUserName, AIP, APort, currentTime, Result, handled); if handled then begin Exit; end; if IsBlackListed(AIP, APort, currentTime) then begin Result := False; Exit; end; if IsLockedUser(AUserName, AIP, APort, currentTime) then begin Result := False; Exit; end; user := nil; for i := Users.Count - 1 downto 0 do begin info := Users[i]; if (info.UserName = AUserName) and (info.IP = AIP) then begin if AIsAuthorized then begin Users.Delete(i); DoRemoveUser(AUserName, AIP, APort, currentTime); end else begin user := info; end; end; end; if AIsAuthorized then begin Result := True; Exit; end; if (user = nil) then begin user := TclGuardUserInfo.Create(AUserName, AIP, APort, currentTime); Users.Add(user); DoAddUser(AUserName, AIP, APort, currentTime); end; delay := GetLoginDelay(user); finally FAccessor.Leave(); end; if (delay > 0) then begin Sleep(delay); end; Result := AIsAuthorized; end; procedure TclServerGuard.Reset; begin Connections.Clear(); Users.Clear(); end; procedure TclServerGuard.SetBlackIPList(const Value: TStrings); begin FBlackIPList.Assign(Value); end; procedure TclServerGuard.SetConnectionLimit(const Value: TclGuardConnectionLimit); begin FConnectionLimit.Assign(Value); end; procedure TclServerGuard.SetLockedUsers(const Value: TStrings); begin FLockedUsers.Assign(Value); end; procedure TclServerGuard.SetLoginDelay(const Value: TclGuardLoginDelay); begin FLoginDelay.Assign(Value); end; procedure TclServerGuard.SetWhiteIPList(const Value: TStrings); begin FWhiteIPList.Assign(Value); end; { TclGuardConnectionLimit } procedure TclGuardConnectionLimit.Assign(Source: TPersistent); var Src: TclGuardConnectionLimit; begin if (Source is TclGuardConnectionLimit) then begin Src := (Source as TclGuardConnectionLimit); Max := Src.Max; Period := Src.Period; end else begin inherited Assign(Source); end; end; constructor TclGuardConnectionLimit.Create; begin inherited Create(); FMax := 6; FPeriod := 60000; end; { TclGuardLoginDelay } procedure TclGuardLoginDelay.Assign(Source: TPersistent); var Src: TclGuardLoginDelay; begin if (Source is TclGuardLoginDelay) then begin Src := (Source as TclGuardLoginDelay); FMin := Src.Min; FMax := Src.Max; FIncrement := Src.Increment; FIsIncremental := Src.IsIncremental; FIsRandom := Src.IsRandom; end else begin inherited Assign(Source); end; end; constructor TclGuardLoginDelay.Create; begin inherited Create(); FMin := 10; FMax := 5000; FIncrement := 1000; FIsIncremental := True; FIsRandom := True; end; { TclGuardConnectionInfo } constructor TclGuardConnectionInfo.Create(const AIP: string; APort, ATime: Integer); begin inherited Create(); FIP := AIP; FPort := APort; FTime := ATime; FAttempts := 0; end; function TclGuardConnectionInfo.NewAttempt: Integer; begin Inc(FAttempts); Result := FAttempts; end; { TclGuardUserInfo } constructor TclGuardUserInfo.Create(const AUserName, AIP: string; APort, ATime: Integer); begin inherited Create(AIP, APort, ATime); FUserName := AUserName; FDelay := 0; end; { TclGuardConnectionInfoList } procedure TclGuardConnectionInfoList.Add(AItem: TclGuardConnectionInfo); begin FList.Add(AItem); end; procedure TclGuardConnectionInfoList.Clear; begin FList.Clear(); end; constructor TclGuardConnectionInfoList.Create; begin inherited Create(); FList := TObjectList.Create(True); end; procedure TclGuardConnectionInfoList.Delete(Index: Integer); begin FList.Delete(Index); end; destructor TclGuardConnectionInfoList.Destroy; begin FList.Free(); inherited Destroy(); end; function TclGuardConnectionInfoList.GetCount: Integer; begin Result := FList.Count; end; function TclGuardConnectionInfoList.GetItem(Index: Integer): TclGuardConnectionInfo; begin Result := TclGuardConnectionInfo(FList[Index]); end; { TclGuardUserInfoList } function TclGuardUserInfoList.GetItem(Index: Integer): TclGuardUserInfo; begin Result := TclGuardUserInfo(inherited GetItem(Index)); end; end.
unit uSounds; interface uses // Delphi units Classes, // Third-party Bass, // Own units UCommon; type TChannelType = (ctUnknown, ctStream, ctMusic); TSound = class(THODObject) private FC: Byte; FChannelType: TChannelType; FTmpList, FSoundsList: TStringList; FChannel: array[0..7] of DWORD; FVolume: ShortInt; procedure SetVolume(const Value: ShortInt); function GetVolume: ShortInt; public //** Конструктор. constructor Create; destructor Destroy; override; property Volume: ShortInt read GetVolume write SetVolume; function PlayClick(N: Byte = 3): Boolean; function Play(const SoundID: Integer): Boolean; overload; function Play(const FileName: string): Boolean; overload; procedure Stop(); end; var Sound: TSound; implementation uses uMain, uLog, uIni, uAdvStr, uUtils, SysUtils, uVars, uBox; { TSound } constructor TSound.Create; var BassInfo: BASS_INFO; I: Integer; begin Volume := 50; BASS_Init(1, 44100, BASS_DEVICE_3D, 0, nil); BASS_Start; BASS_GetInfo(BassInfo); FSoundsList := TStringList.Create; FTmpList := TStringList.Create; FTmpList.LoadFromFile(Path + '\Data\Sounds.ini'); for i := 0 to FTmpList.Count - 1 do if (Trim(FTmpList[i]) <> '') then FSoundsList.Append(Trim(FTmpList[i])); FTmpList.Free; Log.Log('Запуск звукового движка.', True); Log.Log('Загрузка: загружено звуков: ' + IntToStr(FSoundsList.Count) + '.', True); Volume := Ini.Read('Sound', 'Volume', 75); end; destructor TSound.Destroy; begin Stop(); FSoundsList.Free; Log.Log('Остановка звукового движка.', True); Ini.Write('Sound', 'Volume', Volume); inherited; end; function TSound.GetVolume: ShortInt; begin if (FVolume > 100) then FVolume := 100; if (FVolume < 0) then FVolume := 0; Result := FVolume; end; function TSound.Play(const FileName: string): Boolean; begin Result := False; if (Volume <= 0) then Exit; FChannel[FC] := BASS_StreamCreateFile(False, PChar(FileName), 0, 0, 0); if (FChannel[FC] <> 0) then begin FChannelType := ctStream; BASS_ChannelSetAttribute(FChannel[FC], BASS_ATTRIB_VOL, Volume / 100); BASS_ChannelPlay(FChannel[FC], False); end; Result := FChannel[FC] <> 0; Inc(FC); if (FC > High(FChannel)) then FC := 0; end; function TSound.Play(const SoundID: Integer): Boolean; begin Result := SoundID <> 0; if not Result then Exit; AdvStr.AdvString := FSoundsList[SoundID - 1]; Result := Play(Trim(AdvStr.IniValue('='))); end; function TSound.PlayClick(N: Byte): Boolean; begin Result := Play(N + 61); end; procedure TSound.SetVolume(const Value: ShortInt); begin FVolume := Value; if (FVolume > 100) then FVolume := 100; if (FVolume < 0) then FVolume := 0; end; procedure TSound.Stop; var I: Byte; begin for I := 0 to High(FChannel) do BASS_ChannelStop(FChannel[I]); end; initialization Sound := TSound.Create; finalization Sound.Free; end.