text stringlengths 14 6.51M |
|---|
{**********************************************************************}
{* Иллюстрация к книге "OpenGL в проектах Delphi" *}
{* Краснов М.В. softgl@chat.ru *}
{**********************************************************************}
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
OpenGL;
type
TfrmGL = class(TForm)
procedure FormCreate(Sender: TObject);
procedure FormPaint(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
hrc: HGLRC;
aVertex : Array [0..63, 0..1] of GLFloat;
aColors : Array [0..63, 0..2] of GLFloat;
procedure Init;
end;
var
frmGL: TfrmGL;
implementation
{$R *.DFM}
procedure glVertexPointer (size: GLint; atype: GLenum;
stride: GLsizei; data: pointer); stdcall; external OpenGL32;
procedure glColorPointer (size: GLint; atype: GLenum; stride: GLsizei;
data: pointer); stdcall; external OpenGL32;
procedure glDrawArrays (mode: GLenum; first: GLint; count: GLsizei);
stdcall; external OpenGL32;
procedure glEnableClientState (aarray: GLenum); stdcall; external OpenGL32;
procedure glDisableClientState (aarray: GLenum); stdcall; external OpenGL32;
const
GL_VERTEX_ARRAY = $8074;
GL_COLOR_ARRAY = $8076;
procedure TfrmGL.Init;
var
i : 0..63;
begin
For i := 0 to 63 do begin
aVertex[i][0] := ClientWidth / 450 * sin (0.1 * i);
aVertex[i][1] := ClientHeight / 450 * cos (0.1 * i);
aColors[i][0] := 0.75 - 0.01 * i;
aColors[i][1] := 0.85 - 0.02 * i;
aColors[i][1] := 0.85 - 0.02 * i;
end;
end;
{=======================================================================
Перерисовка окна}
procedure TfrmGL.FormPaint(Sender: TObject);
begin
wglMakeCurrent(Canvas.Handle, hrc);
glViewPort (0, 0, ClientWidth, ClientHeight);
Init;
glClearColor (0.5, 0.5, 0.75, 1.0);
glClear (GL_COLOR_BUFFER_BIT);
glVertexPointer(2, GL_FLOAT, 0, @aVertex);
glColorPointer(3, GL_FLOAT, 0, @aColors);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
glDrawArrays(GL_POLYGON, 0, 64);
glDisableClientState(GL_COLOR_ARRAY);
glDisableClientState(GL_VERTEX_ARRAY);
SwapBuffers(Canvas.Handle); // содержимое буфера - на экран
wglMakeCurrent(0, 0);
end;
{=======================================================================
Формат пикселя}
procedure SetDCPixelFormat (hdc : HDC);
var
pfd : TPixelFormatDescriptor;
nPixelFormat : Integer;
begin
FillChar (pfd, SizeOf (pfd), 0);
pfd.dwFlags := PFD_DRAW_TO_WINDOW or PFD_SUPPORT_OPENGL or PFD_DOUBLEBUFFER;
nPixelFormat := ChoosePixelFormat (hdc, @pfd);
SetPixelFormat (hdc, nPixelFormat, @pfd);
end;
{=======================================================================
Создание формы}
procedure TfrmGL.FormCreate(Sender: TObject);
begin
SetDCPixelFormat(Canvas.Handle);
hrc := wglCreateContext(Canvas.Handle);
end;
{=======================================================================
Конец работы приложения}
procedure TfrmGL.FormDestroy(Sender: TObject);
begin
wglDeleteContext(hrc);
end;
end.
|
unit BTMemory_x86_64;
{ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Memory DLL loading code
* ------------------------
*
* Original C Code
* Memory DLL loading code
* Version 0.0.4
*
* Copyright (c) 2004-2015 by Joachim Bauch / mail@joachim-bauch.de
* http://www.joachim-bauch.de
*
* The contents of this file are subject to the Mozilla Public 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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is MemoryModule.c
*
* The Initial Developer of the Original Code is Joachim Bauch.
*
* Portions created by Joachim Bauch are Copyright (C) 2004-2015
* Joachim Bauch. All Rights Reserved.
*
* ================== MemoryModule "Conversion to Delphi" ==================
*
* Copyright (c) 2015 by Fr0sT / https://github.com/Fr0sT-Brutal
*
* Initially based on the code by:
* Copyright (c) 2005 - 2006 by Martin Offenwanger / coder@dsplayer.de / http://www.dsplayer.de
* Carlo Pasolini / cdpasop@hotmail.it / http://pasotech.altervista.org
*
* NOTE
* This code is Delphi translation of original C code taken from https://github.com/fancycode/MemoryModule
* (commit dc173ca from Mar 1, 2015).
* Resource loading and exe loading, custom functions, user data not implemented yet.
* Tested under RAD Studio XE2 and XE6 32/64-bit, Lazarus 32-bit
* }
interface
uses
Winapi.Windows, System.SysUtils;
type
TMemoryModule = Pointer;
{ ++++++++++++++++++++++++++++++++++++++++++++++++++
*** Memory DLL loading functions Declaration ***
-------------------------------------------------- }
_BT_MEMORY_MODULE = packed record
headers: PImageNtHeaders;
codeBase: Pointer;
modules: Pointer;
numModules: Integer;
initialized: boolean;
end;
{$EXTERNALSYM _BT_MEMORY_MODULE}
BT_MEMORY_MODULE = _BT_MEMORY_MODULE;
{$EXTERNALSYM BT_MEMORY_MODULE}
PUInt64 = ^UInt64;
{ +++++++++++++++++++++++++++++++++++
*** SectionFinalization Flags ***
----------------------------------- }
TSFFlag = Byte;
const
SF_NOFIN = $0; // no SectionFinalization
{$EXTERNALSYM SF_NOFIN}
SF_PROTECT = $1; // SectionFinalization with VirtualProtect
{$EXTERNALSYM SF_PROTECT}
SF_DISCARD = $10; // SectionFinalization with Discard
{$EXTERNALSYM SF_DISCARD}
SF_BOTH = $11; // FIN_PROTECT + FIN_DISCARD
{$EXTERNALSYM SF_BOTH}
// return value is nil if function fails
function MemoryLoadLibary(data: Pointer): TMemoryModule; stdcall;
// return value is nil if function fails
function MemoryGetProcAddress(module: TMemoryModule; const name: PAnsiChar): Pointer; stdcall;
// free module
procedure MemoryFreeLibrary(module: TMemoryModule); stdcall;
implementation
{ ++++++++++++++++++++++++++++++++++++++++
*** Missing Windows API Definitions ***
---------------------------------------- }
{$IF NOT DECLARED(IMAGE_BASE_RELOCATION)}
type
{$ALIGN 4}
IMAGE_BASE_RELOCATION = record
VirtualAddress: DWORD;
SizeOfBlock: DWORD;
end;
{$ALIGN ON}
PIMAGE_BASE_RELOCATION = ^IMAGE_BASE_RELOCATION;
{$IFEND}
// Types that are declared in Pascal-style (ex.: PImageOptionalHeader); redeclaring them in C-style
{$IF NOT DECLARED(PIMAGE_DATA_DIRECTORY)}
type PIMAGE_DATA_DIRECTORY = ^IMAGE_DATA_DIRECTORY;
{$IFEND}
{$IF NOT DECLARED(PIMAGE_SECTION_HEADER)}
type PIMAGE_SECTION_HEADER = ^IMAGE_SECTION_HEADER;
{$IFEND}
{$IF NOT DECLARED(PIMAGE_EXPORT_DIRECTORY)}
type PIMAGE_EXPORT_DIRECTORY = ^IMAGE_EXPORT_DIRECTORY;
{$IFEND}
{$IF NOT DECLARED(PIMAGE_DOS_HEADER)}
type PIMAGE_DOS_HEADER = ^IMAGE_DOS_HEADER;
{$IFEND}
{$IF NOT DECLARED(PIMAGE_NT_HEADERS)}
type PIMAGE_NT_HEADERS = ^IMAGE_NT_HEADERS;
{$IFEND}
{$IF NOT DECLARED(PUINT_PTR)}
type PUINT_PTR = ^UINT_PTR;
{$IFEND}
// Missing constants
const
IMAGE_SIZEOF_BASE_RELOCATION = 8;
IMAGE_REL_BASED_ABSOLUTE = 0;
IMAGE_REL_BASED_HIGHLOW = 3;
IMAGE_REL_BASED_DIR64 = 10;
IMAGE_SIZEOF_SHORT_NAME = 8;
// Things that are incorrectly defined at least up to XE6 (miss x64 mapping)
{$IFDEF CPUX64}
type
PIMAGE_TLS_DIRECTORY = PIMAGE_TLS_DIRECTORY64;
const
IMAGE_ORDINAL_FLAG = IMAGE_ORDINAL_FLAG64;
{$ENDIF}
type
{ +++++++++++++++++++++++++++++++++++++++++++++++
*** Internal MemoryModule Type Definition ***
----------------------------------------------- }
TMemoryModuleRec = record
headers: PIMAGE_NT_HEADERS;
codeBase: Pointer;
modules: array of HMODULE;
numModules: Integer;
initialized: Boolean;
isRelocated: Boolean;
pageSize: DWORD;
end;
PMemoryModule = ^TMemoryModuleRec;
TDllEntryProc = function(hinstDLL: HINST; fdwReason: DWORD; lpReserved: Pointer): BOOL; stdcall;
TSectionFinalizeData = record
address: Pointer;
alignedAddress: Pointer;
size: DWORD;
characteristics: DWORD;
last: Boolean;
end;
// Explicitly export these functions to allow hooking of their origins
function GetProcAddress_Internal(hModule: HMODULE; lpProcName: LPCSTR): FARPROC; stdcall; external kernel32 name 'GetProcAddress';
function LoadLibraryA_Internal(lpLibFileName: LPCSTR): HMODULE; stdcall; external kernel32 name 'LoadLibraryA';
function FreeLibrary_Internal(hLibModule: HMODULE): BOOL; stdcall; external kernel32 name 'FreeLibrary';
// Just an imitation to allow using try-except block. DO NOT try to handle this
// like "on E do ..." !
procedure Abort;
begin
raise TObject.Create;
end;
// Copy from SysUtils to get rid of this unit
function StrComp(const Str1, Str2: PAnsiChar): Integer;
var
P1, P2: PAnsiChar;
begin
P1 := Str1;
P2 := Str2;
while True do
begin
if (P1^ <> P2^) or (P1^ = #0) then
Exit(Ord(P1^) - Ord(P2^));
Inc(P1);
Inc(P2);
end;
end;
{ +++++++++++++++++++++++++++++++++++++++++++++++++++++
*** Missing WinAPI macros ***
----------------------------------------------------- }
{$IF NOT DECLARED(IMAGE_ORDINAL)}
// #define IMAGE_ORDINAL64(Ordinal) (Ordinal & 0xffff)
// #define IMAGE_ORDINAL32(Ordinal) (Ordinal & 0xffff)
function IMAGE_ORDINAL(Ordinal: NativeUInt): Word; inline;
begin
Result := Ordinal and $FFFF;
end;
{$IFEND}
{$IF NOT DECLARED(IMAGE_SNAP_BY_ORDINAL)}
// IMAGE_SNAP_BY_ORDINAL64(Ordinal) ((Ordinal & IMAGE_ORDINAL_FLAG64) != 0)
// IMAGE_SNAP_BY_ORDINAL32(Ordinal) ((Ordinal & IMAGE_ORDINAL_FLAG32) != 0)
function IMAGE_SNAP_BY_ORDINAL(Ordinal: NativeUInt): Boolean; inline;
begin
Result := ((Ordinal and IMAGE_ORDINAL_FLAG) <> 0);
end;
{$IFEND}
{ +++++++++++++++++++++++++++++++++++++++++++++++++++++
*** Helper functions ***
----------------------------------------------------- }
function GET_HEADER_DICTIONARY(module: PMemoryModule; idx: Integer): PIMAGE_DATA_DIRECTORY;
begin
Result := PIMAGE_DATA_DIRECTORY(@(module.headers.OptionalHeader.DataDirectory[idx]));
end;
function ALIGN_DOWN(address: Pointer; alignment: DWORD): Pointer;
begin
Result := Pointer(UIntPtr(address) and not (alignment - 1));
end;
function CopySections(data: Pointer; old_headers: PIMAGE_NT_HEADERS; module: PMemoryModule): Boolean;
var
i, size: Integer;
codebase: Pointer;
dest: Pointer;
section: PIMAGE_SECTION_HEADER;
begin
codebase := module.codeBase;
section := PIMAGE_SECTION_HEADER(IMAGE_FIRST_SECTION(module.headers{$IFNDEF FPC}^{$ENDIF}));
for i := 0 to module.headers.FileHeader.NumberOfSections - 1 do
begin
// section doesn't contain data in the dll itself, but may define
// uninitialized data
if section.SizeOfRawData = 0 then
begin
size := old_headers.OptionalHeader.SectionAlignment;
if size > 0 then
begin
dest := VirtualAlloc(PByte(codebase) + section.VirtualAddress,
size,
MEM_COMMIT,
PAGE_READWRITE);
if dest = nil then
Exit(False);
// Always use position from file to support alignments smaller
// than page size.
dest := PByte(codebase) + section.VirtualAddress;
section.Misc.PhysicalAddress := DWORD(dest);
ZeroMemory(dest, size);
end;
// section is empty
Inc(section);
Continue;
end; // if
// commit memory block and copy data from dll
dest := VirtualAlloc(PByte(codebase) + section.VirtualAddress,
section.SizeOfRawData,
MEM_COMMIT,
PAGE_READWRITE);
if dest = nil then
Exit(False);
// Always use position from file to support alignments smaller
// than page size.
dest := PByte(codebase) + section.VirtualAddress;
CopyMemory(dest, PByte(data) + section.PointerToRawData, section.SizeOfRawData);
section.Misc.PhysicalAddress := DWORD(dest);
Inc(section);
end; // for
Result := True;
end;
// Protection flags for memory pages (Executable, Readable, Writeable)
const
ProtectionFlags: array[Boolean, Boolean, Boolean] of DWORD =
(
(
// not executable
(PAGE_NOACCESS, PAGE_WRITECOPY),
(PAGE_READONLY, PAGE_READWRITE)
),
(
// executable
(PAGE_EXECUTE, PAGE_EXECUTE_WRITECOPY),
(PAGE_EXECUTE_READ, PAGE_EXECUTE_READWRITE)
)
);
function GetRealSectionSize(module: PMemoryModule; section: PIMAGE_SECTION_HEADER): DWORD;
begin
Result := section.SizeOfRawData;
if Result = 0 then
if (section.Characteristics and IMAGE_SCN_CNT_INITIALIZED_DATA) <> 0 then
Result := module.headers.OptionalHeader.SizeOfInitializedData
else if (section.Characteristics and IMAGE_SCN_CNT_UNINITIALIZED_DATA) <> 0 then
Result := module.headers.OptionalHeader.SizeOfUninitializedData;
end;
function FinalizeSection(module: PMemoryModule; const sectionData: TSectionFinalizeData): Boolean;
var
protect, oldProtect: DWORD;
executable, readable, writeable: Boolean;
begin
if sectionData.size = 0 then
Exit(True);
if (sectionData.characteristics and IMAGE_SCN_MEM_DISCARDABLE) <> 0 then
begin
// section is not needed any more and can safely be freed
if (sectionData.address = sectionData.alignedAddress) and
( sectionData.last or
(module.headers.OptionalHeader.SectionAlignment = module.pageSize) or
(sectionData.size mod module.pageSize = 0)
) then
// Only allowed to decommit whole pages
VirtualFree(sectionData.address, sectionData.size, MEM_DECOMMIT);
Exit(True);
end;
// determine protection flags based on characteristics
executable := (sectionData.characteristics and IMAGE_SCN_MEM_EXECUTE) <> 0;
readable := (sectionData.characteristics and IMAGE_SCN_MEM_READ) <> 0;
writeable := (sectionData.characteristics and IMAGE_SCN_MEM_WRITE) <> 0;
protect := ProtectionFlags[executable][readable][writeable];
if (sectionData.characteristics and IMAGE_SCN_MEM_NOT_CACHED) <> 0 then
protect := protect or PAGE_NOCACHE;
// change memory access flags
Result := VirtualProtect(sectionData.address, sectionData.size, protect, oldProtect);
end;
function FinalizeSections(module: PMemoryModule): Boolean;
var
i: Integer;
section: PIMAGE_SECTION_HEADER;
imageOffset: UIntPtr;
sectionData: TSectionFinalizeData;
sectionAddress, alignedAddress: Pointer;
sectionSize: DWORD;
begin
section := PIMAGE_SECTION_HEADER(IMAGE_FIRST_SECTION(module.headers{$IFNDEF FPC}^{$ENDIF}));
{$IFDEF CPUX64}
imageOffset := (NativeUInt(module.codeBase) and $ffffffff00000000);
{$ELSE}
imageOffset := 0;
{$ENDIF}
sectionData.address := Pointer(UIntPtr(section.Misc.PhysicalAddress) or imageOffset);
sectionData.alignedAddress := ALIGN_DOWN(sectionData.address, module.pageSize);
sectionData.size := GetRealSectionSize(module, section);
sectionData.characteristics := section.Characteristics;
sectionData.last := False;
Inc(section);
// loop through all sections and change access flags
for i := 1 to module.headers.FileHeader.NumberOfSections - 1 do
begin
sectionAddress := Pointer(UIntPtr(section.Misc.PhysicalAddress) or imageOffset);
alignedAddress := ALIGN_DOWN(sectionData.address, module.pageSize);
sectionSize := GetRealSectionSize(module, section);
// Combine access flags of all sections that share a page
// TODO(fancycode): We currently share flags of a trailing large section
// with the page of a first small section. This should be optimized.
if (sectionData.alignedAddress = alignedAddress) or
(PByte(sectionData.address) + sectionData.size > PByte(alignedAddress)) then
begin
// Section shares page with previous
if (section.Characteristics and IMAGE_SCN_MEM_DISCARDABLE = 0) or
(sectionData.Characteristics and IMAGE_SCN_MEM_DISCARDABLE = 0) then
sectionData.characteristics := (sectionData.characteristics or section.Characteristics) and not IMAGE_SCN_MEM_DISCARDABLE
else
sectionData.characteristics := sectionData.characteristics or section.Characteristics;
sectionData.size := PByte(sectionAddress) + sectionSize - PByte(sectionData.address);
Inc(section);
Continue;
end;
if not FinalizeSection(module, sectionData) then
Exit(False);
sectionData.address := sectionAddress;
sectionData.alignedAddress := alignedAddress;
sectionData.size := sectionSize;
sectionData.characteristics := section.Characteristics;
Inc(section);
end; // for
sectionData.last := True;
if not FinalizeSection(module, sectionData) then
Exit(False);
Result := True;
end;
function ExecuteTLS(module: PMemoryModule): Boolean;
var
codeBase: Pointer;
directory: PIMAGE_DATA_DIRECTORY;
tls: PIMAGE_TLS_DIRECTORY;
callback: PPointer; // =^PIMAGE_TLS_CALLBACK;
cb: Pointer;
// TLS callback pointers are VA's (ImageBase included) so if the module resides at
// the other ImageBage they become invalid. This routine relocates them to the
// actual ImageBase.
// The case seem to happen with DLLs only and they rarely use TLS callbacks.
// Moreover, they probably don't work at all when using DLL dynamically which is
// the case in our code.
function FixPtr(OldPtr: Pointer): Pointer;
begin
Result := Pointer(NativeInt(OldPtr) - module.headers.OptionalHeader.ImageBase + NativeInt(codeBase));
end;
begin
Result := True;
codeBase := module.codeBase;
directory := GET_HEADER_DICTIONARY(module, IMAGE_DIRECTORY_ENTRY_TLS);
if directory.VirtualAddress = 0 then
Exit;
tls := PIMAGE_TLS_DIRECTORY(PByte(codeBase) + directory.VirtualAddress);
// Delphi syntax is quite awkward when dealing with proc pointers so we have to
// use casts to untyped pointers
callback := Pointer(tls.AddressOfCallBacks);
if callback <> nil then
begin
callback := FixPtr(callback);
while callback^ <> nil do
begin
PIMAGE_TLS_CALLBACK(FixPtr(callback^))(codeBase, DLL_PROCESS_ATTACH, nil);
Inc(callback);
end;
end;
end;
function PerformBaseRelocation(module: PMemoryModule; delta: NativeInt): Boolean;
var
i: Cardinal;
codebase: Pointer;
directory: PIMAGE_DATA_DIRECTORY;
relocation: PIMAGE_BASE_RELOCATION;
dest: Pointer;
relInfo: ^UInt16;
patchAddrHL: PDWORD;
{$IFDEF CPUX64}
patchAddr64: PULONGLONG;
{$ENDIF}
relType, offset: Integer;
begin
codebase := module.codeBase;
directory := GET_HEADER_DICTIONARY(module, IMAGE_DIRECTORY_ENTRY_BASERELOC);
if directory.Size = 0 then
Exit(delta = 0);
relocation := PIMAGE_BASE_RELOCATION(PByte(codebase) + directory.VirtualAddress);
while relocation.VirtualAddress > 0 do
begin
dest := Pointer(PByte(codebase) + relocation.VirtualAddress);
relInfo := Pointer(PByte(relocation) + IMAGE_SIZEOF_BASE_RELOCATION);
for i := 0 to Trunc(((relocation.SizeOfBlock - IMAGE_SIZEOF_BASE_RELOCATION) / 2)) - 1 do
begin
// the upper 4 bits define the type of relocation
relType := relInfo^ shr 12;
// the lower 12 bits define the offset
offset := relInfo^ and $FFF;
case relType of
IMAGE_REL_BASED_ABSOLUTE:
// skip relocation
;
IMAGE_REL_BASED_HIGHLOW:
begin
// change complete 32 bit address
patchAddrHL := Pointer(PByte(dest) + offset);
Inc(patchAddrHL^, delta);
end;
{$IFDEF CPUX64}
IMAGE_REL_BASED_DIR64:
begin
patchAddr64 := Pointer(PByte(dest) + offset);
Inc(patchAddr64^, delta);
end;
{$ENDIF}
end;
Inc(relInfo);
end; // for
// advance to next relocation block
relocation := PIMAGE_BASE_RELOCATION(PByte(relocation) + relocation.SizeOfBlock);
end; // while
Result := True;
end;
function BuildImportTable(module: PMemoryModule): Boolean; stdcall;
var
codebase: Pointer;
directory: PIMAGE_DATA_DIRECTORY;
importDesc: PIMAGE_IMPORT_DESCRIPTOR;
thunkRef: PUINT_PTR;
funcRef: ^FARPROC;
handle: HMODULE;
thunkData: PIMAGE_IMPORT_BY_NAME;
begin
codebase := module.codeBase;
Result := True;
directory := GET_HEADER_DICTIONARY(module, IMAGE_DIRECTORY_ENTRY_IMPORT);
if directory.Size = 0 then
Exit(True);
importDesc := PIMAGE_IMPORT_DESCRIPTOR(PByte(codebase) + directory.VirtualAddress);
while (not IsBadReadPtr(importDesc, SizeOf(IMAGE_IMPORT_DESCRIPTOR))) and (importDesc.Name <> 0) do
begin
handle := LoadLibraryA_Internal(PAnsiChar(PByte(codebase) + importDesc.Name));
if handle = 0 then
begin
SetLastError(ERROR_MOD_NOT_FOUND);
Result := False;
Break;
end;
try
SetLength(module.modules, module.numModules + 1);
except
FreeLibrary_Internal(handle);
SetLastError(ERROR_OUTOFMEMORY);
Result := False;
Break;
end;
module.modules[module.numModules] := handle;
Inc(module.numModules);
if importDesc.OriginalFirstThunk <> 0 then
begin
thunkRef := Pointer(PByte(codebase) + importDesc.OriginalFirstThunk);
funcRef := Pointer(PByte(codebase) + importDesc.FirstThunk);
end
else
begin
// no hint table
thunkRef := Pointer(PByte(codebase) + importDesc.FirstThunk);
funcRef := Pointer(PByte(codebase) + importDesc.FirstThunk);
end;
while thunkRef^ <> 0 do
begin
if IMAGE_SNAP_BY_ORDINAL(thunkRef^) then
funcRef^ := GetProcAddress_Internal(handle, PAnsiChar(IMAGE_ORDINAL(thunkRef^)))
else
begin
thunkData := PIMAGE_IMPORT_BY_NAME(PByte(codebase) + thunkRef^);
funcRef^ := GetProcAddress_Internal(handle, PAnsiChar(@(thunkData.Name)));
end;
if funcRef^ = nil then
begin
Result := False;
Break;
end;
Inc(funcRef);
Inc(thunkRef);
end; // while
if not Result then
begin
FreeLibrary_Internal(handle);
SetLastError(ERROR_PROC_NOT_FOUND);
Break;
end;
Inc(importDesc);
end; // while
end;
{ +++++++++++++++++++++++++++++++++++++++++++++++++++++
*** Memory DLL loading functions Implementation ***
----------------------------------------------------- }
function MemoryLoadLibary(data: Pointer): TMemoryModule; stdcall;
var
dos_header: PIMAGE_DOS_HEADER;
old_header: PIMAGE_NT_HEADERS;
code, headers: Pointer;
locationdelta: NativeInt;
sysInfo: SYSTEM_INFO;
DllEntry: TDllEntryProc;
successfull: Boolean;
module: PMemoryModule;
begin
Result := nil; module := nil;
try
dos_header := PIMAGE_DOS_HEADER(data);
if (dos_header.e_magic <> IMAGE_DOS_SIGNATURE) then
begin
SetLastError(ERROR_BAD_EXE_FORMAT);
Exit;
end;
// old_header = (PIMAGE_NT_HEADERS)&((const unsigned char * )(data))[dos_header->e_lfanew];
old_header := PIMAGE_NT_HEADERS(PByte(data) + dos_header._lfanew);
if old_header.Signature <> IMAGE_NT_SIGNATURE then
begin
SetLastError(ERROR_BAD_EXE_FORMAT);
Exit;
end;
{$IFDEF CPUX64}
if old_header.FileHeader.Machine <> IMAGE_FILE_MACHINE_AMD64 then
{$ELSE}
if old_header.FileHeader.Machine <> IMAGE_FILE_MACHINE_I386 then
{$ENDIF}
begin
SetLastError(ERROR_BAD_EXE_FORMAT);
Exit;
end;
if (old_header.OptionalHeader.SectionAlignment and 1) <> 0 then
begin
// Only support section alignments that are a multiple of 2
SetLastError(ERROR_BAD_EXE_FORMAT);
Exit;
end;
// reserve memory for image of library
// XXX: is it correct to commit the complete memory region at once?
// calling DllEntry raises an exception if we don't...
code := VirtualAlloc(Pointer(old_header.OptionalHeader.ImageBase),
old_header.OptionalHeader.SizeOfImage,
MEM_RESERVE or MEM_COMMIT,
PAGE_READWRITE);
if code = nil then
begin
// try to allocate memory at arbitrary position
code := VirtualAlloc(nil,
old_header.OptionalHeader.SizeOfImage,
MEM_RESERVE or MEM_COMMIT,
PAGE_READWRITE);
if code = nil then
begin
SetLastError(ERROR_OUTOFMEMORY);
Exit;
end;
end;
module := PMemoryModule(HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, SizeOf(TMemoryModuleRec)));
if module = nil then
begin
VirtualFree(code, 0, MEM_RELEASE);
SetLastError(ERROR_OUTOFMEMORY);
Exit;
end;
// memory is zeroed by HeapAlloc
module.codeBase := code;
GetNativeSystemInfo({$IFDEF FPC}@{$ENDIF}sysInfo);
module.pageSize := sysInfo.dwPageSize;
// commit memory for headers
headers := VirtualAlloc(code,
old_header.OptionalHeader.SizeOfHeaders,
MEM_COMMIT,
PAGE_READWRITE);
// copy PE header to code
CopyMemory(headers, dos_header, old_header.OptionalHeader.SizeOfHeaders);
// result->headers = (PIMAGE_NT_HEADERS)&((const unsigned char *)(headers))[dos_header->e_lfanew];
module.headers := PIMAGE_NT_HEADERS(PByte(headers) + dos_header._lfanew);
// copy sections from DLL file block to new memory location
if not CopySections(data, old_header, module) then
Abort;
// adjust base address of imported data
locationdelta := NativeInt(code) - old_header.OptionalHeader.ImageBase;
if locationdelta <> 0 then
module.isRelocated := PerformBaseRelocation(module, locationdelta)
else
module.isRelocated := True;
// load required dlls and adjust function table of imports
if not BuildImportTable(module) then
Abort;
// mark memory pages depending on section headers and release
// sections that are marked as "discardable"
if not FinalizeSections(module) then
Abort;
// TLS callbacks are executed BEFORE the main loading
if not ExecuteTLS(module) then
Abort;
// get entry point of loaded library
if module.headers.OptionalHeader.AddressOfEntryPoint <> 0 then
begin
@DllEntry := Pointer(PByte(code) + module.headers.OptionalHeader.AddressOfEntryPoint);
// notify library about attaching to process
successfull := DllEntry(HINST(code), DLL_PROCESS_ATTACH, nil);
if not successfull then
begin
SetLastError(ERROR_DLL_INIT_FAILED);
Abort;
end;
module.initialized := True;
end;
Result := module;
except
// cleanup
MemoryFreeLibrary(module);
Exit;
end;
end;
function MemoryGetProcAddress(module: TMemoryModule; const name: PAnsiChar): Pointer; stdcall;
var
codebase: Pointer;
idx: Integer;
i: DWORD;
hiname: WORD;
nameRef: PDWORD;
ordinal: PWord;
exportDir: PIMAGE_EXPORT_DIRECTORY;
directory: PIMAGE_DATA_DIRECTORY;
temp: PDWORD;
mmodule: PMemoryModule;
begin
Result := nil;
mmodule := PMemoryModule(module);
codebase := mmodule.codeBase;
directory := GET_HEADER_DICTIONARY(mmodule, IMAGE_DIRECTORY_ENTRY_EXPORT);
// no export table found
if directory.Size = 0 then
begin
SetLastError(ERROR_PROC_NOT_FOUND);
Exit;
end;
exportDir := PIMAGE_EXPORT_DIRECTORY(PByte(codebase) + directory.VirtualAddress);
// DLL doesn't export anything modify by lihp
//if (exportDir.NumberOfNames = 0) or (exportDir.NumberOfFunctions = 0) then
if (exportDir.NumberOfNames = 0) and (exportDir.NumberOfFunctions = 0) then
begin
SetLastError(ERROR_PROC_NOT_FOUND);
Exit;
end;
// search function name in list of exported names
nameRef := Pointer(PByte(codebase) + exportDir.AddressOfNames);
ordinal := Pointer(PByte(codebase) + exportDir.AddressOfNameOrdinals);
hiname := ((Integer(name) shr 16) and $ffff);
idx := -1;
if ( hiname = 0) then
begin
idx := (Integer(name) and $ffff) - exportDir^.Base;
end
else
begin
for i := 0 to exportDir.NumberOfNames - 1 do
begin
if StrComp(name, PAnsiChar(PByte(codebase) + nameRef^)) = 0 then
begin
idx := ordinal^;
Break;
end;
Inc(nameRef);
Inc(ordinal);
end;
end;
// exported symbol not found
if (idx = -1) then
begin
SetLastError(ERROR_PROC_NOT_FOUND);
Exit;
end;
// name <-> ordinal number don't match
if (DWORD(idx) > exportDir.NumberOfFunctions) then
begin
SetLastError(ERROR_PROC_NOT_FOUND);
Exit;
end;
// AddressOfFunctions contains the RVAs to the "real" functions {}
temp := Pointer(PByte(codebase) + exportDir.AddressOfFunctions + idx*4);
Result := Pointer(PByte(codebase) + temp^);
end;
procedure MemoryFreeLibrary(module: TMemoryModule); stdcall;
var
i: Integer;
DllEntry: TDllEntryProc;
mmodule: PMemoryModule;
begin
if module = nil then Exit;
mmodule := PMemoryModule(module);
if mmodule.initialized then
begin
// notify library about detaching from process
@DllEntry := Pointer(PByte(mmodule.codeBase) + mmodule.headers.OptionalHeader.AddressOfEntryPoint);
DllEntry(HINST(mmodule.codeBase), DLL_PROCESS_DETACH, nil);
end;
if Length(mmodule.modules) <> 0 then
begin
// free previously opened libraries
for i := 0 to mmodule.numModules - 1 do
if mmodule.modules[i] <> 0 then
FreeLibrary_Internal(mmodule.modules[i]);
SetLength(mmodule.modules, 0);
end;
if mmodule.codeBase <> nil then
// release memory of library
VirtualFree(mmodule.codeBase, 0, MEM_RELEASE);
HeapFree(GetProcessHeap(), 0, mmodule);
end;
end.
|
unit MyRichEdit;
interface
uses
ComCtrls, Graphics,
Nodes, Repr;
type
TMyRichEdit =
class(TRichEdit)
protected
FRepr: TRepr;
FTree: TNode;
FFocus: TNode;
FLine: String;
FSelStart: Integer;
FSelLength: Integer;
procedure BuildLine;
procedure WriteNode(ANode: TNode);
public
procedure SetRepr(ARepr: Trepr);
procedure AddTree(ATree: TNode);
procedure ChangeFocus(AFocus: TNode);
end;
implementation
{ TMyRichEdit }
procedure TMyRichEdit.AddTree(ATree: TNode);
var
VLength: Integer;
begin
FTree := ATree;
FFocus := ATree;
BuildLine;
VLength := Length(Text);
Lines.Add(FLine);
SelStart := VLength + FSelStart;
SelLength := FSelLength;
end;
procedure TMyRichEdit.BuildLine;
begin
FLine := '';
WriteNode(FTree);
end;
procedure TMyRichEdit.ChangeFocus(AFocus: TNode);
var
VLength: Integer;
begin
FFocus := AFocus;
BuildLine;
with Lines do
if Count > 0
then Delete(Count - 1);
VLength := Length(Text);
Lines.Add(FLine);
SelStart := VLength + FSelStart;
SelLength := FSelLength;
with SelAttributes do
Style := [fsBold];
end;
procedure TMyRichEdit.SetRepr(ARepr: Trepr);
begin
FRepr := ARepr;
end;
procedure TMyRichEdit.WriteNode(ANode: TNode);
var
I: Integer;
begin
if ANode = FFocus
then FSelStart := Length(FLine);
with ANode do
if HasData
then FLine := FLine + GetData
else
begin
for I := 0 to GetNrOfSons - 1 do
begin
FLine := FLine + FRepr.Rep(ANode, I);
WriteNode(GetSon(I));
end;
FLine := FLine + FRepr.Rep(ANode, GetNrOfSons);
end;
if ANode = FFocus
then FSelLength := Length(FLine) - FSelStart;
end;
end.
|
unit TestSpaceBeforeBrackets;
{(*}
(*------------------------------------------------------------------------------
Delphi Code formatter source code
The Original Code is TestSpaceBeforeBrackets, released April 2007.
The Initial Developer of the Original Code is Anthony Steele.
Portions created by Anthony Steele are Copyright (C) 2007 Anthony Steele.
All Rights Reserved.
Contributor(s): Anthony Steele.
The contents of this file are subject to the Mozilla Public License Version 1.1
(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.mozilla.org/NPL/
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied.
See the License for the specific language governing rights and limitations
under the License.
Alternatively, the contents of this file may be used under the terms of
the GNU General Public License Version 2 or later (the "GPL")
See http://www.gnu.org/licenses/gpl.html
------------------------------------------------------------------------------*)
{*)}
{$I jcfGlobal.inc}
interface
uses
TestFrameWork, BaseTestProcess;
type
TTestSpaceBeforeBrackets = class(TBaseTestProcess)
private
fbSaveSpaceBeforeOpenBracketsInFunctionDeclaration: boolean;
fbSaveSpaceBeforeOpenBracketsInFunctionCall: boolean;
fbSaveSpaceBeforeOpenSquareBracketsInExpression: boolean;
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestSpaceBeforeBrackets_InBoth;
procedure TestSpaceBeforeBrackets_InCall;
procedure TestSpaceBeforeBrackets_InDecl;
procedure TestSpaceBeforeBrackets_Off;
procedure TestSpaceBeforeArray_Off;
procedure TestSpaceBeforeArray_On;
end;
implementation
uses JclStrings, JclAnsiStrings,
JcfSettings, SetSpaces, SingleSpaceBefore;
const
TEST_UNIT_IN = UNIT_HEADER +
'function foo(value: integer): integer;' + AnsiLineBreak +
'begin' + AnsiLineBreak +
' result := 1 + foo(1 + 1);' + AnsiLineBreak +
'end;' + AnsiLineBreak +
UNIT_FOOTER;
TEST_UNIT_OUT_BOTH = UNIT_HEADER +
'function foo (value: integer): integer;' + AnsiLineBreak +
'begin' + AnsiLineBreak +
' result := 1 + foo (1 + 1);' + AnsiLineBreak +
'end;' + AnsiLineBreak +
UNIT_FOOTER;
TEST_UNIT_OUT_HEADER = UNIT_HEADER +
'function foo (value: integer): integer;' + AnsiLineBreak +
'begin' + AnsiLineBreak +
' result := 1 + foo(1 + 1);' + AnsiLineBreak +
'end;' + AnsiLineBreak +
UNIT_FOOTER;
TEST_UNIT_OUT_CALL = UNIT_HEADER +
'function foo(value: integer): integer;' + AnsiLineBreak +
'begin' + AnsiLineBreak +
' result := 1 + foo (1 + 1);' + AnsiLineBreak +
'end;' + AnsiLineBreak +
UNIT_FOOTER;
procedure TTestSpaceBeforeBrackets.SetUp;
begin
inherited;
fbSaveSpaceBeforeOpenBracketsInFunctionDeclaration := JcfFormatSettings.Spaces.SpaceBeforeOpenBracketsInFunctionDeclaration;
fbSaveSpaceBeforeOpenBracketsInFunctionCall := JcfFormatSettings.Spaces.SpaceBeforeOpenBracketsInFunctionCall;
fbSaveSpaceBeforeOpenSquareBracketsInExpression := JcfFormatSettings.Spaces.SpaceBeforeOpenSquareBracketsInExpression;
end;
procedure TTestSpaceBeforeBrackets.TearDown;
begin
JcfFormatSettings.Spaces.SpaceBeforeOpenBracketsInFunctionDeclaration := fbSaveSpaceBeforeOpenBracketsInFunctionDeclaration;
JcfFormatSettings.Spaces.SpaceBeforeOpenBracketsInFunctionCall := fbSaveSpaceBeforeOpenBracketsInFunctionCall;
JcfFormatSettings.Spaces.SpaceBeforeOpenSquareBracketsInExpression := fbSaveSpaceBeforeOpenSquareBracketsInExpression;
end;
procedure TTestSpaceBeforeBrackets.TestSpaceBeforeBrackets_Off;
begin
JcfFormatSettings.Spaces.SpaceBeforeOpenBracketsInFunctionDeclaration := False;
JcfFormatSettings.Spaces.SpaceBeforeOpenBracketsInFunctionCall := False;
TestProcessResult(TSingleSpaceBefore, TEST_UNIT_IN, TEST_UNIT_IN);
end;
procedure TTestSpaceBeforeBrackets.TestSpaceBeforeBrackets_InDecl;
begin
JcfFormatSettings.Spaces.SpaceBeforeOpenBracketsInFunctionDeclaration := True;
JcfFormatSettings.Spaces.SpaceBeforeOpenBracketsInFunctionCall := False;
TestProcessResult(TSingleSpaceBefore, TEST_UNIT_IN, TEST_UNIT_OUT_HEADER);
end;
procedure TTestSpaceBeforeBrackets.TestSpaceBeforeBrackets_InCall;
begin
JcfFormatSettings.Spaces.SpaceBeforeOpenBracketsInFunctionDeclaration := False;
JcfFormatSettings.Spaces.SpaceBeforeOpenBracketsInFunctionCall := True;
TestProcessResult(TSingleSpaceBefore, TEST_UNIT_IN, TEST_UNIT_OUT_CALL);
end;
procedure TTestSpaceBeforeBrackets.TestSpaceBeforeBrackets_InBoth;
begin
JcfFormatSettings.Spaces.SpaceBeforeOpenBracketsInFunctionDeclaration := True;
JcfFormatSettings.Spaces.SpaceBeforeOpenBracketsInFunctionCall := True;
TestProcessResult(TSingleSpaceBefore, TEST_UNIT_IN, TEST_UNIT_OUT_BOTH);
end;
const
TEST_ARRAY_IN = UNIT_HEADER +
'function foo(value: integer): integer;' + AnsiLineBreak +
'begin' + AnsiLineBreak +
' result := 1 + bar[1];' + AnsiLineBreak +
'end;' + AnsiLineBreak +
UNIT_FOOTER;
TEST_ARRAY_OUT = UNIT_HEADER +
'function foo(value: integer): integer;' + AnsiLineBreak +
'begin' + AnsiLineBreak +
' result := 1 + bar [1];' + AnsiLineBreak +
'end;' + AnsiLineBreak +
UNIT_FOOTER;
procedure TTestSpaceBeforeBrackets.TestSpaceBeforeArray_Off;
begin
JcfFormatSettings.Spaces.SpaceBeforeOpenBracketsInFunctionDeclaration := False;
JcfFormatSettings.Spaces.SpaceBeforeOpenBracketsInFunctionCall := False;
JcfFormatSettings.Spaces.SpaceBeforeOpenSquareBracketsInExpression := False;
TestProcessResult(TSingleSpaceBefore, TEST_ARRAY_IN, TEST_ARRAY_IN);
end;
procedure TTestSpaceBeforeBrackets.TestSpaceBeforeArray_On;
begin
JcfFormatSettings.Spaces.SpaceBeforeOpenBracketsInFunctionDeclaration := False;
JcfFormatSettings.Spaces.SpaceBeforeOpenBracketsInFunctionCall := False;
JcfFormatSettings.Spaces.SpaceBeforeOpenSquareBracketsInExpression := True;
TestProcessResult(TSingleSpaceBefore, TEST_ARRAY_IN, TEST_ARRAY_OUT);
end;
initialization
TestFramework.RegisterTest('Processes', TTestSpaceBeforeBrackets.Suite);
end.
|
unit Form.Alert;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, ClipBrd;
procedure AlertCreate(const Sender: TForm; const Msg: String);
type
TfAlert = class(TForm)
gBorder: TGroupBox;
lMessage: TLabel;
tTransparent: TTimer;
iBG: TImage;
procedure tTransparentTimer(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure lMessageClick(Sender: TObject);
private
Waittime: integer;
alpha: integer;
public
{ Public declarations }
end;
var
fAlert: TfAlert;
implementation
{$R *.dfm}
procedure AlertCreate(const Sender: TForm; const Msg: String);
begin
if fAlert <> Nil then FreeAndNil(fAlert);
fAlert := TfAlert.Create(Sender);
try
fAlert.lMessage.Caption := Msg;
fAlert.ShowModal;
finally
FreeAndNil(fAlert);
end;
end;
procedure TfAlert.FormCreate(Sender: TObject);
begin
Waittime := 0;
alpha := 0;
end;
procedure TfAlert.lMessageClick(Sender: TObject);
begin
if lMessage.Caption[1] <> 'S' then Close;
end;
procedure TfAlert.tTransparentTimer(Sender: TObject);
begin
if Waittime = 0 then
begin
alpha := alpha + 1;
AlphaBlendValue := 255 - round(sqr(alpha) / (sqr(Length(lMessage.Caption)) / 80));
if AlphaBlendValue < 150 then Close;
end
else Waittime := Waittime - 1;
end;
end.
|
unit HardCodings;
interface
uses
Classes;
function HardCodedMap(AOwner: TComponent): TMetroMap;
implementation //===============================================================
function HardCodedMap(AOwner: TComponent): TMetroMap;
var
VMetroMap: TmetroMap;
VLine: TVisLine;
VBitmap: TBitmap;
begin
VMetroMap := TMetroMap.Create(AOwner);
// add some stations ---------------------------------------------------------
with VMetroMap do
begin
Add(TVisStationTransfer.Create('GAD', nil, 157, 388)); //Grande Arche de La Défense
Add(TVisStationStop .Create('ESP', nil, 181, 411)); //Esplanade de La Défense
Add(TVisStationStop .Create('PON', nil, 206, 436)); //Pont de Neuilly
Add(TVisStationStop .Create('LSA', nil, 231, 461)); //Les Sablons
Add(TVisStationTransfer.Create('PTT', nil, 259, 490)); //Porte Maillot
Add(TVisStationStop .Create('ARG', nil, 299, 530)); //Argentine
Add(TVisStationTransfer.Create('CDG', nil, 331, 562)); //Charles de Gaulle - Étoile
Add(TVisStationStop .Create('GEO', nil, 369, 600)); //George V
Add(TVisStationTransfer.Create('FRA', nil, 407, 638)); //Franklin D. Roosevelt
Add(TVisStationTransfer.Create('CEC', nil, 433, 664)); //Champs Élysées - Clémenceau
Add(TVisStationTransfer.Create('CON', nil, 457, 688)); //Concorde
Add(TVisStationStop .Create('TUI', nil, 514, 705)); //Tuileries
Add(TVisStationStop .Create('LOU', nil, 569, 705)); //Louvre
Add(TVisStationStop .Create('LOR', nil, 613, 705)); //Louvre - Rivoli
Add(TVisStationTransfer.Create('CHA', nil, 709, 705)); //Châtelet
Add(TVisStationTransfer.Create('HOT', nil, 763, 705)); //Hôtel de Ville
Add(TVisStationStop .Create('SAP', nil, 809, 751)); //Saint-Paul
Add(TVisStationTransfer.Create('BAS', nil, 866, 766)); //Bastille
Add(TVisStationTransfer.Create('GLY', nil, 907, 866)); //Gare de Lyon
Add(TVisStationTransfer.Create('REU', nil, 986, 844)); //Reuilly - Diderot
Add(TVisStationTransfer.Create('NAT', nil,1066, 800)); //Nation
Add(TVisStationStop .Create('PTZ', nil,1118, 816)); //Porte de Vincennes
Add(TVisStationStop .Create('SAM', nil,1158, 838)); //Saint-Mandé - Tourelle
Add(TVisStationStop .Create('BER', nil,1179, 859)); //Bérault
Add(TVisStationStop .Create('CHV', nil,1198, 878)); //Château de Vincennes
end;
// add some lines ------------------------------------------------------------
VLine := TVisLine.Create('L01', nil, clRed);
with VLine do
begin
Add(VMetroMap.GetStation('GAD'));
Add(VMetroMap.GetStation('ESP'));
Add(VMetroMap.GetStation('PON'));
Add(VMetroMap.GetStation('LSA'));
Add(VMetroMap.GetStation('PTT'));
Add(VMetroMap.GetStation('ARG'));
Add(VMetroMap.GetStation('CDG'));
Add(VMetroMap.GetStation('GEO'));
Add(VMetroMap.GetStation('FRA'));
Add(VMetroMap.GetStation('CEC'));
Add(VMetroMap.GetStation('CON'));
Add(TVisStationDummy.Create( 474, 705));
Add(VMetroMap.GetStation('TUI'));
Add(VMetroMap.GetStation('LOU'));
Add(VMetroMap.GetStation('LOR'));
Add(VMetroMap.GetStation('CHA'));
Add(VMetroMap.GetStation('HOT'));
Add(VMetroMap.GetStation('SAP'));
Add(TVisStationDummy.Create( 814, 757));
Add(TVisStationDummy.Create( 854, 757));
Add(TVisStationDummy.Create( 867, 769));
Add(VMetroMap.GetStation('BAS'));
Add(TVisStationDummy.Create( 867, 769));
Add(TVisStationDummy.Create( 904, 806));
Add(TVisStationDummy.Create( 904, 846));
Add(TVisStationDummy.Create( 916, 858));
Add(VMetroMap.GetStation('GLY'));
Add(TVisStationDummy.Create( 916, 858));
Add(TVisStationDummy.Create( 944, 886));
Add(VMetroMap.GetStation('REU'));
Add(TVisStationDummy.Create(1042, 788));
Add(TVisStationDummy.Create(1061, 805));
Add(VMetroMap.GetStation('NAT'));
Add(TVisStationDummy.Create(1061, 805));
Add(TVisStationDummy.Create(1071, 816));
Add(VMetroMap.GetStation('PTZ'));
Add(TVisStationDummy.Create(1136, 816));
Add(VMetroMap.GetStation('SAM'));
Add(VMetroMap.GetStation('BER'));
Add(VMetroMap.GetStation('CHV'));
end;
VMetroMap.Add(VLine);
// add some landmarks ----------------------------------------------------------
VBitmap := TBitmap.Create;
VBitmap.LoadFromFile('../Images/Landmarks/eiffel.bmp');
VMetroMap.Add(TVisLandmark.Create('eif', nil, 300, 738, VBitMap));
VBitmap := TBitmap.Create;
VBitmap.LoadFromFile('../Images/Landmarks/arcdetriomphe.bmp');
VMetroMap.Add(TVisLandmark.Create('arc', nil, 306, 490, VBitMap));
VBitmap := TBitmap.Create;
VBitmap.LoadFromFile('../Images/Landmarks/notredame.bmp');
VMetroMap.Add(TVisLandmark.Create('nod', nil, 704, 734, VBitMap));
VBitmap := TBitmap.Create;
VBitmap.LoadFromFile('../Images/Landmarks/defense.bmp');
VMetroMap.Add(TVisLandmark.Create('def', nil, 143, 319, VBitMap));
VBitmap := TBitmap.Create;
VBitmap.LoadFromFile('../Images/Landmarks/madeleine.bmp');
VMetroMap.Add(TVisLandmark.Create('mad', nil, 467, 590, VBitMap));
VBitmap := TBitmap.Create;
VBitmap.LoadFromFile('../Images/Landmarks/sacrecoeur.bmp');
VMetroMap.Add(TVisLandmark.Create('sac', nil, 675, 338, VBitMap));
VBitmap := TBitmap.Create;
VBitmap.LoadFromFile('../Images/Landmarks/invalides.bmp');
VMetroMap.Add(TVisLandmark.Create('inv', nil, 400, 745, VBitMap));
// add some text -------------------------------------------------------------
with VMetroMap do
begin
Add(TVisText.Create('PON', nil, 206, 436, 'Pont de Neuilly', tpNorthEast));
Add(TVisText.Create('ARG', nil, 299, 530, 'Argentine' , tpNorthEast));
Add(TVisText.Create('CON', nil, 457, 688, 'Concorde' , tpWest ));
Add(TVisText.Create('TUI', nil, 514, 705, 'Tuileries' , tpNorth ));
Add(TVisText.Create('SAP', nil, 809, 751, 'St-Paul' , tpSouthWest));
end;
Result := VMetroMap;
end;
end.
|
{*********************************************}
{ TeeBI Software Library }
{ Using TeeChart "Functions" as BI providers }
{ Copyright (c) 2015-2016 by Steema Software }
{ All Rights Reserved }
{*********************************************}
unit FMXBI.ChartFunctions;
{$DEFINE FMX}
interface
uses
System.Classes,
BI.DataItem,
{$IFDEF FMX}
FMXTee.Constants, FMXTee.Engine,
{$ELSE}
VCLTee.TeeConst, VCLTee.TeEngine,
{$ENDIF}
{$IFDEF FPC}
{$DEFINE TEEPRO} // <-- TeeChart Lite or Pro ?
{$ELSE}
{$IF TeeMsg_TeeChartPalette='TeeChart'}
{$DEFINE TEEPRO} // <-- TeeChart Lite or Pro ?
{$ENDIF}
{$ENDIF}
BI.Algorithm;
type
TDataFunction=class(TDataProviderNeeds)
private
FFunction : TTeeFunction;
FFunctionClass : TTeeFunctionClass;
procedure AddNeeds(const AFunctionClass:TTeeFunctionClass);
function CalcClass:TTeeFunctionClass;
function GetPeriod: Double;
function GetTeeFunction: TTeeFunction;
procedure SetPeriod(const Value: Double);
protected
function GetChildOwner: TComponent; override;
Procedure GetChildren(Proc:TGetChildProc; Root:TComponent); override;
procedure Load(const AData:TDataItem; const Children:Boolean); override;
procedure Loaded; override;
public
Constructor CreateFunction(const AOwner:TComponent; const AFunctionClass:TTeeFunctionClass); overload;
Constructor CreateFunction(const AOwner:TComponent; const AFunction:TTeeFunction); overload;
function FunctionTitle:String;
function IsFinancial:Boolean;
property FunctionClass:TTeeFunctionClass read CalcClass;
property TeeFunction:TTeeFunction read GetTeeFunction;
published
property Period:Double read GetPeriod write SetPeriod stored False;
end;
implementation
|
unit UzslEditors;
interface
Uses
Classes, SysUtils, Dialogs, DesignIntf, DesignEditors, Forms, VCLEditors;
Type
TFileNameProperty = class(TMPFileNameProperty)
public
Procedure Edit; override;
end;
TDBPropertyEditor = class(TStringProperty)
protected
Procedure GetNames(Strings: TStrings);virtual; abstract;
public
Procedure GetValues(Proc: TGetStrProc); override;
Function GetAttributes: TPropertyAttributes; override;
end;
TDatabaseNameProperty = class(TDBPropertyEditor)
protected
Procedure GetNames(Strings: TStrings); override;
end;
implementation
uses
UTableBox;
Procedure TFileNameProperty.Edit;
var
OpenDialog : TOpenDialog;
begin
OpenDialog := TOpenDialog.Create(Application);
try
OpenDialog.FileName := GetValue;
OpenDialog.Filter := 'Log Files (*.log)|*.log|All Files(*.*)|*.*';
OpenDialog.Options := OpenDialog.Options + [ofPathMustExist];
if OpenDialog.Execute then SetValue(OpenDialog.Filename);
finally
OpenDialog.Free;
end;
end;
//procedure Register;
//implementation
//uses
//UTableBox;
//procedure Register;
//begin
//RegisterPropertyEditor(TypeInfo(TDatabaseName), TTableBox,
//'DatabaseName', TDatabaseNameProperty );
//end;
{ TDBPropertyEditor }
function TDBPropertyEditor.GetAttributes: TPropertyAttributes;
begin
result := [paRevertable, paMultiselect, paValueList];
end;
procedure TDBPropertyEditor.GetValues(Proc: TGetStrProc);
var
I: Integer;
Strings: TStrings;
begin
Strings := TStringList.Create;
try
GetNames(Strings);
for I := 0 to Strings.Count - 1 do Proc(Strings[I]);
finally
Strings.Free;
end;
end;
{ TDatabaseNameProperty }
procedure TDatabaseNameProperty.GetNames(Strings: TStrings);
begin
if Assigned(Session) then
Session.GetDatabaseNames(Strings);
end;
end.
|
unit frmMenuUnit;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, FireDAC.Stan.Intf, FireDAC.Stan.Option,
FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf,
FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, FireDAC.UI.Intf,
FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Phys, FireDAC.Phys.MSAcc,
FireDAC.Phys.MSAccDef, FireDAC.VCLUI.Wait, Data.DB, FireDAC.Comp.UI,
FireDAC.Comp.Client, FireDAC.Comp.DataSet, Vcl.Grids, Vcl.DBGrids,
Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Buttons, gridOperUnit;
type
TfrmMenu = class(TForm)
grboxAdd: TGroupBox;
btnAdd: TSpeedButton;
btnClearAddForm: TSpeedButton;
lbleditDishName: TLabeledEdit;
grboxSearch: TGroupBox;
btnSearch: TSpeedButton;
btnDelete: TSpeedButton;
lbleditSearch: TLabeledEdit;
DBGrid1: TDBGrid;
lbleditPrice: TLabeledEdit;
lbleditDescription: TLabeledEdit;
gboxEdit: TGroupBox;
btnUpdate: TSpeedButton;
btnClearEditPanel: TSpeedButton;
lbleditDish: TLabeledEdit;
lbleditCenaEdit: TLabeledEdit;
lbleditDescr: TLabeledEdit;
FDConnection1: TFDConnection;
FDQuery1: TFDQuery;
FDQuery2: TFDQuery;
DataSource1: TDataSource;
FDGUIxWaitCursor1: TFDGUIxWaitCursor;
procedure lbleditPriceKeyPress(Sender: TObject; var Key: Char);
procedure btnAddClick(Sender: TObject);
procedure btnClearAddFormClick(Sender: TObject);
procedure btnDeleteClick(Sender: TObject);
procedure btnClearEditPanelClick(Sender: TObject);
procedure lbleditSearchKeyPress(Sender: TObject; var Key: Char);
procedure btnSearchClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btnUpdateClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
frmMenu: TfrmMenu;
implementation
{$R *.dfm}
procedure TfrmMenu.btnAddClick(Sender: TObject);
begin
if string.IsNullOrEmpty(lbleditDishName.Text) then
ShowMessage('Моля въведете име!')
else if string.IsNullOrEmpty(lbleditPrice.Text) then
ShowMessage('Моля въведете цена!')
else if string.IsNullOrEmpty(lbleditDescription.Text) then
ShowMessage('Моля въведете описание!')
else begin
FDQuery1.SQL.Text :=
'INSERT INTO qstia(ime, cena, opisanie) VALUES(:ime, :cena, :opisanie)';
FDQuery1.ParamByName('ime').Value := lbleditDishName.Text;
FDQuery1.ParamByName('cena').Value := StrToFloat(lbleditPrice.Text);
FDQuery1.ParamByName('opisanie').Value := lbleditDescription.Text;
FDQuery1.ExecSQL;
ShowMessage('Ястието е добавено!');
btnClearAddFormClick(Sender);
end;
end;
procedure TfrmMenu.btnClearAddFormClick(Sender: TObject);
begin
lbleditDishName.Clear;
lbleditPrice.Clear;
lbleditDescription.Clear;
end;
procedure TfrmMenu.btnClearEditPanelClick(Sender: TObject);
begin
lbleditDish.Clear;
lbleditCenaEdit.Clear;
lbleditDescr.Clear;
end;
procedure TfrmMenu.btnDeleteClick(Sender: TObject);
var
dishID: string;
begin
if MessageDlg('Наистина ли искате да се изтрие записът?',
mtCustom, [mbYes, mbNo], 0) = mrYes then begin
dishID := DBGrid1.DataSource.DataSet.FieldByName('qstia_id').AsString;
FDQuery1.SQL.Text := 'DELETE FROM qstia WHERE qstia_id = ' + dishID;
FDQuery1.ExecSQL;
DBGrid1.DataSource.DataSet.Refresh;
ShowMessage('Ястие номер ' + dishID + ' е изтрито!');
btnClearEditPanelClick(Sender);
gboxEdit.Visible := false;
btnDelete.Visible := false;
end;
end;
procedure TfrmMenu.btnSearchClick(Sender: TObject);
begin
if not string.IsNullOrEmpty(lbleditSearch.Text) then begin
FDQuery2.Active := false;
FDQuery2.SQL.Text := 'SELECT * FROM qstia WHERE qstia_Id=' +
lbleditSearch.Text;
FDQuery2.Active := true;
if not DBGrid1.DataSource.DataSet.IsEmpty then begin
SetGridColumnWidths(DBGrid1);
gboxEdit.Visible := true;
btnDelete.Visible := true;
end
else begin
gboxEdit.Visible := false;
btnDelete.Visible := false;
end;
end;
end;
procedure TfrmMenu.btnUpdateClick(Sender: TObject);
var
queryStr: string;
tr: boolean;
begin
tr := false;
queryStr := 'UPDATE qstia SET ';
//-------------------------------------------------------------------------------------
if not string.IsNullOrEmpty(lbleditDish.Text) then begin
queryStr := queryStr + 'ime=' + QuotedStr(lbleditDish.Text);
tr := true;
end;
//-------------------------------------------------------------------------------------
if not string.IsNullOrEmpty(lbleditCenaEdit.Text) then begin
if tr then
queryStr := queryStr + ', cena=' + QuotedStr(lbleditCenaEdit.Text)
else begin
queryStr := queryStr + 'cena=' + QuotedStr(lbleditCenaEdit.Text);
end;
tr := true;
end;
//-------------------------------------------------------------------------------------
if not string.IsNullOrEmpty(lbleditDescr.Text) then begin
if tr then
queryStr := queryStr + ', opisanie=' + QuotedStr(lbleditDescr.Text)
else
queryStr := queryStr + 'opisanie=' + QuotedStr(lbleditDescr.Text);
tr := true;
end;
//-------------------------------------------------------------------------------------
if tr then begin
queryStr := queryStr + ' WHERE qstia_id=' +
DBGrid1.DataSource.DataSet.FieldByName('qstia_id').AsString;
FDQuery1.SQL.Clear;
FDQuery1.ExecSQL(queryStr);
btnClearEditPanelClick(Sender);
DBGrid1.DataSource.DataSet.Refresh;
SetGridColumnWidths(DBGrid1);
ShowMessage('Данните са редактирани!');
end;
//-------------------------------------------------------------------------------------
end;
procedure TfrmMenu.FormClose(Sender: TObject; var Action: TCloseAction);
begin
btnClearEditPanelClick(Sender);
btnClearAddFormClick(Sender);
btnDelete.Visible := false;
gboxEdit.Visible := false;
lbleditSearch.Clear;
FDQuery2.Active := false; // clear dbgrid
end;
procedure TfrmMenu.lbleditPriceKeyPress(Sender: TObject; var Key: Char);
begin
if Key in ['0'..'9', '.', #8] = false then
Key := #0;
end;
procedure TfrmMenu.lbleditSearchKeyPress(Sender: TObject; var Key: Char);
begin
if Key = #13 then
btnSearchClick(Sender);
end;
end.
|
unit SIBAPI;
// SuperIB
// Copyright © 1999 David S. Becker
// dhbecker@jps.net
// www.jps.net/dhbecker/superib
{$I FIBPlus.inc}
interface
uses IB_Intf, SIBGlobals;
type
// data types used to interface with the InterBase API
SIB_PVoid = ^Pointer;
SIB_PPChar = ^PAnsiChar;
SIB_Long = LongInt;
SIB_PLong = ^SIB_Long;
SIB_UShort = Word;
SIB_DBHandle = SIB_PVoid;
SIB_PDBHandle = ^SIB_DBHandle;
SIB_Status = SIB_Long;
SIB_PStatus = ^SIB_Status;
SIB_PPStatus = ^SIB_PStatus;
SIB_StatusVector = array[0..19] of SIB_Status;
SIB_PStatusVector = ^SIB_StatusVector;
SIB_PPStatusVector = ^SIB_PStatusVector;
SIB_EventCallback = procedure(P: Pointer; Length: SIB_UShort; Updated: PAnsiChar); cdecl;
function SIB_Free(ClientLibrary:IIBClientLibrary;P: PAnsiChar): SIB_Long;
function SIB_QueEvents(ClientLibrary:IIBClientLibrary;Status: SIB_PStatusVector; DBHandle: SIB_PDBHandle; EventID: SIB_PLong;
Length: SIB_UShort;EventBuffer: PAnsiChar; Callback:
SIB_EventCallback; CallbackArg: Pointer
): SIB_Status;
function SIB_CancelEvents(ClientLibrary:IIBClientLibrary;Status: SIB_PStatusVector; DBHandle: SIB_DBHandle; EventID: SIB_PLong): SIB_Status;
procedure SIB_EventCounts(ClientLibrary:IIBClientLibrary;Status: SIB_PStatusVector; Length: SIB_UShort; EventBuffer, ResultBuffer: PAnsiChar);
implementation
uses IB_Externals, ibase;
//---------------------------------------------------------------------------
function SIB_QueEvents(ClientLibrary:IIBClientLibrary;Status: SIB_PStatusVector;
DBHandle: SIB_PDBHandle; EventID: SIB_PLong; Length: SIB_UShort;
EventBuffer: PAnsiChar; Callback: SIB_EventCallback; CallbackArg: Pointer): SIB_Status;
begin
with ClientLibrary do
Result := isc_que_events( PISC_STATUS( Status ), PISC_DB_HANDLE( DBHandle ),
PISC_LONG( EventID ),
Length, EventBuffer,
TISC_CALLBACK( Callback ), CallbackArg
);
Set8087CW(Default8087CW);
end;
//---------------------------------------------------------------------------
function SIB_CancelEvents(ClientLibrary:IIBClientLibrary;Status: SIB_PStatusVector; DBHandle: SIB_DBHandle; EventID: SIB_PLong): SIB_Status;
begin
with ClientLibrary do
Result := isc_cancel_events( PISC_STATUS( Status ), PISC_DB_HANDLE( DBHandle ), PISC_LONG( EventID ) );
Set8087CW(Default8087CW);
end;
//---------------------------------------------------------------------------
procedure SIB_EventCounts(ClientLibrary:IIBClientLibrary;Status: SIB_PStatusVector; Length: SIB_UShort; EventBuffer, ResultBuffer: PAnsiChar);
begin
ClientLibrary.isc_event_counts( PISC_STATUS( Status ), Length, EventBuffer, ResultBuffer );
Set8087CW(Default8087CW);
end;
//---------------------------------------------------------------------------
function SIB_Free(ClientLibrary:IIBClientLibrary;P: PAnsiChar): SIB_Long;
begin
with ClientLibrary do
if Assigned(P) then
Result := isc_free(P)
else
Result := 0 ;
Set8087CW(Default8087CW);
end;
end.
|
{
AD.A.P.T. Library
Copyright (C) 2014-2018, Simon J Stuart, All Rights Reserved
Original Source Location: https://github.com/LaKraven/ADAPT
Subject to original License: https://github.com/LaKraven/ADAPT/blob/master/LICENSE.md
}
unit ADAPT;
{$I ADAPT.inc}
{$IFDEF FPC}
{$IFNDEF ADAPT_SUPPRESS_VERSION_WARNING}
{.$IF FPC_VERSION < 3}
{.$ERROR 'FreePascal (FPC) 3.0 or above is required for the ADAPT.'}
{.$DEFINE ADAPT_WARNING_VERSION}
{.$IFEND FPC_VERSION}
{$ENDIF ADAPT_SUPPRESS_VERSION_WARNING}
{$ELSE}
{$IFNDEF ADAPT_SUPPRESS_VERSION_WARNING}
{$IFNDEF DELPHIXE2_UP}
{$MESSAGE WARN 'Delphi 2010 and XE are not regularly tested with the ADAPT. Please report any issues on https://github.com/LaKraven/ADAPT'}
{$DEFINE ADAPT_WARNING_VERSION}
{$ENDIF DELPHIXE2_UP}
{$ENDIF ADAPT_SUPPRESS_VERSION_WARNING}
{$ENDIF FPC}
{$IFDEF ADAPT_WARNING_VERSION}
{$MESSAGE HINT 'Define "ADAPT_SUPPRESS_VERSION_WARNING" in your project options to get rid of these messages'}
{$UNDEF ADAPT_WARNING_VERSION}
{$ENDIF ADAPT_WARNING_VERSION}
{$IFNDEF ADAPT_SUPPRESS_DEPRECATION_WARNING}
// Nothing deprecated to warn about at this moment
{$IFDEF ADAPT_WARNING_DEPRECATION}
{$MESSAGE HINT 'Define "ADAPT_SUPPRESS_DEPRECATION_WARNING" in your project options to get rid of these messages'}
{$ENDIF ADAPT_WARNING_DEPRECATION}
{$ENDIF ADAPT_SUPPRESS_DEPRECATION_WARNING}
interface
uses
{$IFDEF ADAPT_USE_EXPLICIT_UNIT_NAMES}
System.Classes, System.SysUtils,
{$ELSE}
Classes, SysUtils,
{$ENDIF ADAPT_USE_EXPLICIT_UNIT_NAMES}
ADAPT.Intf;
{$I ADAPT_RTTI.inc}
type
{ Class Forward Declarations }
TADObject = class;
TADPersistent = class;
TADAggregatedObject = class;
/// <summary><c>ADAPT Base Excpetion Type.</c></summary>
EADException = class abstract(Exception);
EADGenericsIterateException = class(EADException);
EADGenericsIterateDirectionUnknownException = class(EADGenericsIterateException);
EADGenericsRangeException = class(EADException);
EADGenericsParameterInvalidException = class(EADException);
EADGenericsCapacityLessThanCount = class(EADGenericsParameterInvalidException);
EADGenericsCompactorNilException = class(EADGenericsParameterInvalidException);
EADGenericsExpanderNilException = class(EADGenericsParameterInvalidException);
/// <summary><c>ADAPT Base Object Type.</c></summary>
/// <remarks><c>All Classes in ADAPT are Interfaced unless otherwise stated.</c></remarks>
TADObject = class abstract(TInterfacedObject, IADInterface)
private
function GetInstanceGUID: TGUID;
protected
FInstanceGUID: TGUID;
constructor Create; virtual;
public
property InstanceGUID: TGUID read GetInstanceGUID;
end;
/// <summary><c>ADAPT Base Persistent Type.</c></summary>
/// <remarks>
/// <para><c>All Classes in ADAPT are Interfaced unless otherwise stated.</c></para>
/// <para><c>There is no Reference Counting on Persistent Types.</c></para>
/// </remarks>
TADPersistent = class abstract(TInterfacedPersistent, IADInterface)
private
function GetInstanceGUID: TGUID;
protected
FInstanceGUID: TGUID;
constructor Create; virtual;
public
property InstanceGUID: TGUID read GetInstanceGUID;
end;
/// <summary><c>ADAPT Base Aggregated Object Type.</c></summary>
/// <remarks><c>All Classes in ADAPT are Interfaced unless otherwise stated.</c></remarks>
TADAggregatedObject = class abstract(TAggregatedObject, IADInterface)
private
function GetInstanceGUID: TGUID;
protected
FInstanceGUID: TGUID;
public
constructor Create(const Controller: IInterface); reintroduce; virtual;
property InstanceGUID: TGUID read GetInstanceGUID;
end;
TADObjectHolder<T: class> = class(TADObject, IADObjectHolder<T>)
private
FOwnership: TADOwnership;
FObject: T;
protected
// Getters
{ IADObjectOwner }
function GetOwnership: TADOwnership; virtual;
{ IADObjectHolder<T> }
function GetObject: T; virtual;
// Setters
{ IADObjectOwner }
procedure SetOwnership(const AOwnership: TADOwnership); virtual;
public
constructor Create(const AObject: T; const AOwnership: TADOwnership = oOwnsObjects); reintroduce; virtual;
destructor Destroy; override;
// Properties
{ IADObjectOwner }
property Ownership: TADOwnership read GetOwnership write SetOwnership;
{ IADObjectHolder<T> }
property HeldObject: T read GetObject;
end;
TADValueHolder<T> = class(TADObject, IADValueHolder<T>)
private
FValue: T;
protected
function GetValue: T; virtual;
public
constructor Create(const AValue: T); reintroduce;
property Value: T read GetValue;
end;
TADKeyValuePair<TKey, TValue> = class(TADObject, IADKeyValuePair<TKey, TValue>)
protected
FKey: TKey;
FValue: TValue;
// Getters
function GetKey: TKey;
function GetValue: TValue;
// Setters
procedure SetValue(const AValue: TValue);
public
constructor Create(const AKey: TKey; const AValue: TValue); reintroduce;
// Properties
property Key: TKey read GetKey;
property Value: TValue read GetValue write SetValue;
end;
const
{$IFDEF ADAPT_FLOAT_SINGLE}
/// <summary><c>Zero value for ADFloat values.</c></summary>
ADFLOAT_ZERO = 0.00;
{$ELSE}
{$IFDEF ADAPT_FLOAT_EXTENDED}
/// <summary><c>Zero value for ADFloat values.</c></summary>
ADFLOAT_ZERO = 0.00;
{$ELSE}
/// <summary><c>Zero value for ADFloat values.</c></summary>
ADFLOAT_ZERO = 0.00;
{$ENDIF ADAPT_FLOAT_DOUBLE}
{$ENDIF ADAPT_FLOAT_SINGLE}
implementation
{ TADObject }
constructor TADObject.Create;
begin
CreateGUID(FInstanceGUID);
end;
function TADObject.GetInstanceGUID: TGUID;
begin
Result := FInstanceGUID;
end;
{ TADPersistent }
constructor TADPersistent.Create;
begin
inherited Create;
CreateGUID(FInstanceGUID);
end;
function TADPersistent.GetInstanceGUID: TGUID;
begin
Result := FInstanceGUID;
end;
{ TADAggregatedObject }
constructor TADAggregatedObject.Create(const Controller: IInterface);
begin
inherited Create(Controller);
CreateGUID(FInstanceGUID);
end;
function TADAggregatedObject.GetInstanceGUID: TGUID;
begin
Result := FInstanceGUID;
end;
{ TADObjectHolder<T> }
constructor TADObjectHolder<T>.Create(const AObject: T; const AOwnership: TADOwnership);
begin
inherited Create;
FObject := AObject;
FOwnership := AOwnership;
end;
destructor TADObjectHolder<T>.Destroy;
begin
if FOwnership = oOwnsObjects then
FObject.{$IFDEF SUPPORTS_DISPOSEOF}DisposeOf{$ELSE}Free{$ENDIF SUPPORTS_DISPOSEOF};
inherited;
end;
function TADObjectHolder<T>.GetObject: T;
begin
Result := FObject;
end;
function TADObjectHolder<T>.GetOwnership: TADOwnership;
begin
Result := FOwnership;
end;
procedure TADObjectHolder<T>.SetOwnership(const AOwnership: TADOwnership);
begin
FOwnership := AOwnership;
end;
{ TADValueHolder<T> }
constructor TADValueHolder<T>.Create(const AValue: T);
begin
inherited Create;
FValue := AValue;
end;
function TADValueHolder<T>.GetValue: T;
begin
Result := FValue;
end;
{ TADKeyValuePair<TKey, TValue> }
constructor TADKeyValuePair<TKey, TValue>.Create(const AKey: TKey; const AValue: TValue);
begin
inherited Create;
FKey := AKey;
FValue := AValue;
end;
function TADKeyValuePair<TKey, TValue>.GetKey: TKey;
begin
Result := FKey;
end;
function TADKeyValuePair<TKey, TValue>.GetValue: TValue;
begin
Result := FValue;
end;
procedure TADKeyValuePair<TKey, TValue>.SetValue(const AValue: TValue);
begin
FValue := AValue;
end;
end.
|
unit uTesteShell;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Registry, LMDCustomComponent, LMDSysInfo, JamSelectionList,
ExtCtrls, ShellLink, JAMDialogs;
type
TForm19 = class(TForm)
Memo1: TMemo;
Panel1: TPanel;
Button2: TButton;
Button4: TButton;
Button1: TButton;
Button3: TButton;
Button5: TButton;
JamFileOperation1: TJamFileOperation;
Button6: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure Button4Click(Sender: TObject);
procedure Button5Click(Sender: TObject);
procedure Button6Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form19: TForm19;
implementation
uses ncgShell;
{$R *.dfm}
const
path_explorer = '\Software\Microsoft\Windows\CurrentVersion\Explorer';
function GetStartupKey(const aKey: HKEY = HKEY_CURRENT_USER; const aUser: Boolean = True) : String;
var
R : TRegistry;
S : String;
begin
R := TRegistry.Create;
try
R.RootKey := aKey;
if aUser then
S := '\User Shell Folders' else
S := '\Shell Folders';
if not R.OpenKeyReadOnly(path_explorer+S) then begin
Result := '';
Exit;
end;
if aKey = HKEY_CURRENT_USER then
Result := R.ReadString('Startup') else
Result := R.ReadString('Common Startup');
finally
R.Free;
end;
end;
procedure TForm19.Button1Click(Sender: TObject);
begin
ShowMessage(GetShellData(esfUserShellFolders, sdStartMenu, False, False));
end;
procedure TForm19.Button2Click(Sender: TObject);
begin
ChangeShellData(False);
end;
procedure TForm19.Button3Click(Sender: TObject);
begin
ChangeShellData(True);
end;
procedure TForm19.Button4Click(Sender: TObject);
var
J: TJamSelectionList;
S : String;
function Next: Boolean;
begin
S := J.FindNext;
Result := (S>'');
end;
begin
J := TJamSelectionList.Create(Self);
try
J.LoadFromIniFile('c:\meus programas\nexcafe\jamteste2.ini', 'Teste');
J.ResetFindNext;
while Next do Memo1.Lines.Add(S);
finally
J.Free;
end;
end;
procedure TForm19.Button5Click(Sender: TObject);
var J : TJamSelectionList;
S : String;
function Next: Boolean;
begin
S := J.FindNext;
Result := (S>'');
end;
begin
J := TJamSelectionList.Create(nil);
try
J.AddPathToSelection('c:\meus programas\nexcafe');
// while Next do Memo1.Lines.Add(S);
case J.IsPathSelected('c:\meus programas\nexcafe\Clientes.rar') of
ssChecked : ShowMessage('checked');
ssUnchecked : ShowMessage('unchecked');
ssUnused : ShowMessage('unused');
ssNone : ShowMessage('none');
ssGrayed : ShowMessage('grayed');
end;
finally
J.Free;
end;
end;
procedure TForm19.Button6Click(Sender: TObject);
begin
DelTree('c:\meus programas\nexcafe\dados_clientes\keyti', False);
end;
procedure TForm19.FormCreate(Sender: TObject);
begin
ForceDirectories(GetShellDir(sdPrograms, False, True));
ForceDirectories(GetShellDir(sdPrograms, True, True));
end;
end.
|
unit wavewrite;
{$mode delphi}
interface
uses
Classes, SysUtils, mmsystem, syncobjs;
type
TWaveHeader = record
RIFF,
filesize,
WAVE,
fmt,
fmtSize: UInt32;
waveFormat: PCMWAVEFORMAT;
data,
datasize: Uint32;
end;
TWaveRecorderAudioState = (asStartSilence, asAudioData, asSilence, asSilenceTresh);
{ TWaveRecorder }
TWaveRecorder = class
private
FFile: file;
FHeader: TWaveHeader;
FCanWrite: Boolean;
FCurrent: LPWAVEHDR;
FCurrentWritten: longword;
FLastTimestamp: longword;
FState: TWaveRecorderAudioState;
FSilenceDuration: Integer;
FCutStartSilence: Boolean;
function IsSilence(data: Pointer; size: Integer): Boolean;
public
constructor Create(filename: string; format: WAVEFORMATEX; CutStartSilence: Boolean = false);
destructor Destroy; override;
procedure Flush;
procedure WriteData(data: Pointer; size: Integer);
procedure WriteWaveHdr(data: LPWAVEHDR; Timestamp: longword);
procedure WritePartially(Timestamp: longword);
function IsSilent: Boolean;
end;
{ TSlowWriterThread }
TSlowWriterThread = class(TThread)
private
FRecorders: array of TWaveRecorder;
FCS: TCriticalSection;
protected
procedure Execute; override;
public
constructor Create;
destructor Destroy; override;
procedure RegisterRecorder(Rec: TWaveRecorder);
procedure UnregisterRecorder(Rec: TWaveRecorder);
end;
var
SlowWriterThread: TSlowWriterThread;
implementation
uses
winhooks;
{ TWaveRecorder }
function Encode4(const s: string): UInt32;
begin
PByteArray(@result)^[0]:=Ord(s[1]);
PByteArray(@result)^[1]:=Ord(s[2]);
PByteArray(@result)^[2]:=Ord(s[3]);
PByteArray(@result)^[3]:=Ord(s[4]);
end;
{ TSlowWriterThread }
procedure TSlowWriterThread.Execute;
var
i: Integer;
t: longword;
begin
while not Terminated do
begin
t:=GetTickCount;
fcs.Enter;
for i:=0 to Length(FRecorders)-1 do
FRecorders[i].WritePartially(t);
FCS.Leave;
Sleep(1000);
end;
end;
constructor TSlowWriterThread.Create;
begin
FCS:=TCriticalSection.Create;
Setlength(FRecorders, 0);
inherited Create(False);
end;
destructor TSlowWriterThread.Destroy;
begin
inherited Destroy;
end;
procedure TSlowWriterThread.RegisterRecorder(Rec: TWaveRecorder);
var
i: Integer;
begin
FCS.Enter;
i:=Length(FRecorders);
Setlength(FRecorders, i+1);
FRecorders[i]:=Rec;
FCS.Leave;
end;
procedure TSlowWriterThread.UnregisterRecorder(Rec: TWaveRecorder);
var
i: Integer;
begin
FCS.Enter;
for i:=0 to Length(FRecorders)-1 do
if FRecorders[i] = Rec then
begin
FRecorders[i]:=FRecorders[Length(FRecorders)-1];
Setlength(FRecorders, LEngth(FRecorders)-1);
Break;
end;
FCS.Leave;
end;
function TWaveRecorder.IsSilence(data: Pointer; size: Integer): Boolean;
var
i: Integer;
begin
Result:=True;
if FHeader.waveFormat.wf.wFormatTag = 3 then
begin
for i:=0 to (size div SizeOf(Single)) - 1 do
begin
// for float, we blindly assume 32 bit single
if abs((PSingle(@PByteArray(data)^[i * SizeOf(Single)]))^) > 0.00001 then
begin
Result:=False;
Exit;
end;
end;
end else
begin
// for integer streams, just test for zero
for i:=0 to size-1 do
if (PByteArray(data)^[i] <> 0) then
begin
Result:=False;
Exit;
end;
end;
end;
constructor TWaveRecorder.Create(filename: string; format: WAVEFORMATEX;
CutStartSilence: Boolean);
begin
Fillchar(FHeader, SizeOf(FHeader), #0);
FState:=asStartSilence;
FCutStartSilence:=CutStartSilence;
FHeader.datasize:=0;
FHeader.filesize:=sizeOf(FHeader)-8;
FHeader.RIFF:=Encode4('RIFF');
FHeader.WAVE:=Encode4('WAVE');
FHeader.fmt :=Encode4('fmt ');
FHeader.data:=Encode4('data');
FHeader.fmtSize:=sizeOf(FHeader.waveFormat);
FHeader.waveFormat.wf.wFormatTag:=format.wFormatTag;
FHeader.waveFormat.wf.nChannels:=format.nChannels;
FHeader.waveFormat.wf.nBlockAlign:=format.nBlockAlign;
FHeader.waveFormat.wf.nSamplesPerSec:=format.nSamplesPerSec;
FHeader.waveFormat.wf.nAvgBytesPerSec:=format.nAvgBytesPerSec;
FHeader.waveFormat.wBitsPerSample:=format.wBitsPerSample;
FCurrent:=nil;
Assignfile(FFile, filename);
{$I-}Rewrite(FFile,1);{$I+}
if ioresult = 0 then
begin
FCanWrite:=True;
Blockwrite(FFile, FHeader, SizeOf(FHeader));
end else
FCanWrite:=False;
if Assigned(SlowWriterThread) then
SlowWriterThread.RegisterRecorder(Self);
end;
destructor TWaveRecorder.Destroy;
begin
if Assigned(SlowWriterThread) then
SlowWriterThread.UnregisterRecorder(Self);
if FCanWrite then
begin
Flush;
Seek(FFile, 0);
Blockwrite(FFile, FHeader, SizeOf(FHeader));
Closefile(FFile);
end;
inherited Destroy;
end;
procedure TWaveRecorder.Flush;
begin
if not Assigned(FCurrent) then
Exit;
WriteData(@FCurrent^.lpData[FCurrentWritten], FCurrent^.dwBufferLength - FCurrentWritten);
FCurrent:=nil;
end;
procedure TWaveRecorder.WriteData(data: Pointer; size: Integer);
var
op: Integer;
begin
if FCanWrite and Assigned(data) then
begin
if IsSilence(data, size) then
begin
case FState of
asStartSilence:
begin
if FCutStartSilence then
Exit;
end;
asAudioData:
begin
FState:=asSilence;
FSilenceDuration:=size;
end;
asSilence:
begin
FSilenceDuration:=FSilenceDuration + size;
if FSilenceDuration >= FHeader.waveFormat.wf.nAvgBytesPerSec then
begin
FState:=asSilenceTresh;
end;
if FCutStartSilence then
Exit;
end;
asSilenceTresh:
begin
if FCutStartSilence then
Exit;
end;
end;
end else
begin
FState:=asAudioData;
end;
Inc(FHeader.filesize, size);
Inc(FHeader.datasize, size);
op:=FilePos(FFile);
Seek(FFile, 0);
Blockwrite(FFile, FHeader, SizeOf(FHeader));
Seek(FFile, op);
Blockwrite(FFile, data^, size);
end;
end;
procedure TWaveRecorder.WriteWaveHdr(data: LPWAVEHDR; Timestamp: longword);
begin
Flush;
// for short buffers we assume that they are properly filled and can be immediately written to file
if data^.dwBufferLength div FHeader.waveFormat.wf.nSamplesPerSec < 5 then
begin
WriteData(data^.lpData, data^.dwBufferLength);
Exit;
end;
// for longer buffers, we can try to write the buffer over time
FCurrent:=data;
FCurrentWritten:=0;
FLastTimestamp:=Timestamp;
end;
procedure TWaveRecorder.WritePartially(Timestamp: longword);
var
dataToWrite: longword;
begin
if not Assigned(FCurrent) then
Exit;
if Timestamp - FLastTimestamp >= 1000 then
begin
datatowrite:=((Timestamp - FLastTimestamp) * FHeader.waveFormat.wf.nAvgBytesPerSec) div 1000;
if datatowrite > FCurrent^.dwBufferLength - FCurrentWritten then
datatowrite:=FCurrent^.dwBufferLength - FCurrentWritten;
WriteData(@FCurrent^.lpData[FCurrentWritten], dataToWrite);
Inc(FCurrentWritten, dataToWrite);
if FCurrentWritten = FCurrent^.dwBufferLength then
FCurrent:=nil;
FLastTimestamp:=Timestamp;
end;
end;
function TWaveRecorder.IsSilent: Boolean;
begin
result:=FState = asSilenceTresh;
end;
initialization
SlowWriterThread:=nil;
end.
|
{$mode objfpc}{$H+}{$J-}
uses
SysUtils;
type
TGun = class
end;
TPlayer = class
Gun1, Gun2: TGun;
constructor Create;
destructor Destroy; override;
end;
constructor TPlayer.Create;
begin
inherited;
Gun1 := TGun.Create;
raise Exception.Create('Вызваем exception из constructor-а!');
Gun2 := TGun.Create;
end;
destructor TPlayer.Destroy;
begin
{ В данном случае в результате ошибки в constructor-е, у нас
может оказаться Gun1 <> nil и Gun2 = nil. Смиритесь.
В таком случае, FreeAndNil справится с задачей без каких-либо
дополнительных действий с нашей стороны, поскольку FreeAndNil проверяет
является ли экземпляр класса nil перед вызовом соответствующего destructor-а. }
FreeAndNil(Gun1);
FreeAndNil(Gun2);
inherited;
end;
begin
try
TPlayer.Create;
except
on E: Exception do
WriteLn('Ошибка ' + E.ClassName + ': ' + E.Message);
end;
end. |
unit Rx.Schedulers;
interface
uses Classes, Rx, Generics.Collections;
type
TCurrentThreadScheduler = class(TInterfacedObject, IScheduler, StdSchedulers.ICurrentThreadScheduler)
public
procedure Invoke(Action: IAction);
end;
TMainThreadScheduler = class(TInterfacedObject, IScheduler, StdSchedulers.IMainThreadScheduler)
public
procedure Invoke(Action: IAction);
end;
TAsyncTask = class(TThread)
type
TInput = TThreadedQueue<IAction>;
strict private
FInput: TInput;
protected
procedure Execute; override;
public
constructor Create(Input: TInput);
destructor Destroy; override;
end;
TJob = class(TThread)
strict private
FAction: IAction;
protected
procedure Execute; override;
public
constructor Create(Action: IAction);
destructor Destroy; override;
end;
TSeparateThreadScheduler = class(TInterfacedObject, IScheduler, StdSchedulers.ISeparateThreadScheduler)
strict private
FTask: TAsyncTask;
FJobQueue: TAsyncTask.TInput;
public
constructor Create;
destructor Destroy; override;
procedure Invoke(Action: IAction);
end;
TNewThreadScheduler = class(TInterfacedObject, IScheduler, StdSchedulers.INewThreadScheduler)
strict private
FJobs: TList<TJob>;
procedure RefreshJobs;
public
constructor Create;
destructor Destroy; override;
procedure Invoke(Action: IAction);
end;
TThreadPoolScheduler = class(TInterfacedObject, IScheduler, StdSchedulers.IThreadPoolScheduler)
type
tArrayOfTasks = array of TAsyncTask;
strict private
FTasks: tArrayOfTasks;
FJobQueue: TAsyncTask.TInput;
public
constructor Create(PoolSize: Integer);
destructor Destroy; override;
procedure Invoke(Action: IAction);
end;
implementation
{ TCurrentThreadScheduler }
procedure TCurrentThreadScheduler.Invoke(Action: IAction);
begin
Action.Emit;
end;
{ TMainThreadScheduler }
procedure TMainThreadScheduler.Invoke(Action: IAction);
begin
TThread.Synchronize(nil, procedure
begin
Action.Emit;
end
);
end;
{ TSeparateThreadScheduler }
constructor TSeparateThreadScheduler.Create;
begin
FJobQueue := TAsyncTask.TInput.Create;
FTask := TAsyncTask.Create(FJobQueue);
end;
destructor TSeparateThreadScheduler.Destroy;
begin
FJobQueue.DoShutDown;
FTask.WaitFor;
FTask.Free;
FJobQueue.Free;
inherited;
end;
procedure TSeparateThreadScheduler.Invoke(Action: IAction);
begin
FJobQueue.PushItem(Action)
end;
{ TNewThreadScheduler }
constructor TNewThreadScheduler.Create;
begin
FJobs := TList<TJob>.Create;
end;
destructor TNewThreadScheduler.Destroy;
var
Job: TJob;
begin
for Job in FJobs do begin
Job.WaitFor;
Job.Free;
end;
FJobs.Free;
inherited;
end;
procedure TNewThreadScheduler.Invoke(Action: IAction);
begin
RefreshJobs;
FJobs.Add(TJob.Create(Action))
end;
procedure TNewThreadScheduler.RefreshJobs;
var
I: Integer;
begin
for I := FJobs.Count-1 downto 0 do begin
if FJobs[I].Terminated then begin
FJobs[I].Free;
FJobs.Delete(I);
end;
end;
end;
{ TThreadPoolScheduler }
constructor TThreadPoolScheduler.Create(PoolSize: Integer);
var
I: Integer;
begin
FJobQueue := TAsyncTask.TInput.Create;
SetLength(FTasks, PoolSize);
for I := 0 to High(FTasks) do
FTasks[I] := TAsyncTask.Create(FJobQueue);
end;
destructor TThreadPoolScheduler.Destroy;
var
I: Integer;
begin
FJobQueue.DoShutDown;
for I := 0 to High(FTasks) do begin
FTasks[I].WaitFor;
FTasks[I].Free;
end;
FJobQueue.Free;
inherited;
end;
procedure TThreadPoolScheduler.Invoke(Action: IAction);
begin
FJobQueue.PushItem(Action)
end;
{ TAsyncTask }
constructor TAsyncTask.Create(Input: TInput);
begin
FInput := Input;
inherited Create(False);
end;
destructor TAsyncTask.Destroy;
begin
inherited;
end;
procedure TAsyncTask.Execute;
var
Action: IAction;
begin
while not FInput.ShutDown do begin
Action := FInput.PopItem;
try
if Assigned(Action) then
Action.Emit;
except
// raise off
end;
end
end;
{ TJob }
constructor TJob.Create(Action: IAction);
begin
FAction := Action;
inherited Create(False);
end;
destructor TJob.Destroy;
begin
FAction := nil;
inherited;
end;
procedure TJob.Execute;
begin
FAction.Emit;
end;
end.
|
{$A+,B-,D+,E-,F-,G+,I+,L+,N+,O-,P-,Q-,R-,S-,T-,V+,X+,Y+}
{$M 16384,0,0}
{
by Behdad Esfahbod
Algorithmic Problems Book
August '1999
Problem 19 O(N2) Dfs Method
}
program
BiConnectedComponents;
const
MaxN = 100;
var
N : Integer;
A : array [0 .. MaxN, 0 .. MaxN] of Integer;
M, B : array [1 .. MaxN] of Boolean;
S : array [1 .. MaxN] of Integer;
St : array [1 .. MaxN * MaxN] of Integer;
StNum : Integer;
BCCNum : Integer;
I, J, D, Time, Te : Integer;
F : Text;
procedure ReadInput;
begin
Assign(F, 'input.txt');
Reset(F);
Readln(F, N);
for I := 2 to N do
begin
for J := 1 to I - 1 do
begin
Read(F, A[I, J]); A[J, I] := A[I, J];
end;
Readln(F);
end;
Close(F);
Assign(F, 'output.txt');
ReWrite(F);
end;
function Dfs (V, P : Integer) : Integer;
var
I, L, T : Integer;
begin
M[V] := True;
Inc(Time);
S[V] := Time;
L := S[V];
for I := 1 to N do
if (A[I, V] = 1) then
if not M[I] then
begin
Inc(StNum);
St[StNum] := I * 256 + V;
T := Dfs(I, V);
if T = S[I] then
begin
FillChar(B, SizeOf(B), 0);
while St[StNum] <> I * 256 + V do
begin
B[St[StNum] mod 256] := True; B[St[StNum] div 256] := True;
Dec(StNum);
end;
for Te := 1 to N do
if B[Te] then
Write(F, Te , ' ');
Writeln(F);
Writeln(F, V, ' ', I);
Dec(StNum);
Inc(BCCNum, 2);
end;
if T < L then
L := T;
B[V] := True; B[I] := True;
end
else
if (I <> P) and (S[I] < L) then
L := S[I];
Dfs := L;
end;
procedure BiConnected;
begin
for I := 1 to N do
if not M[I] then
begin
Dfs(I, 0);
if STNum > 0 then
Inc(BCCNum);
StNum := 0;
end;
ReWrite(F);
FillChar(M, SizeOf(M), 0);
Writeln(F, BCCNum);
for I := 1 to N do
if not M[I] then
begin
Dfs(I, 0);
if STNum = 0 then
Continue;
Inc(BCCNum);
FillChar(B, SizeOf(B), 0);
while StNum > 0 do
begin
B[St[StNum] mod 256] := True; B[St[StNum] div 256] := True;
Dec(StNum);
end;
for Te := 1 to N do
if B[Te] then
Write(F, Te , ' ');
Writeln(F);
end;
end;
begin
ReadInput;
BiConnected;
Close(F);
end.
|
unit IdLogDebug;
interface
uses
Classes,
IdLogBase;
type
TIdLogDebugTarget = (ltFile, ltDebugOutput, ltEvent);
TIdLogDebug = class(TIdLogBase)
protected
procedure LogStatus(const AText: string); override;
procedure LogReceivedData(const AText: string; const AData: string); override;
procedure LogSentData(const AText: string; const AData: string); override;
public
published
end;
implementation
uses
IdGlobal;
{ TIdLogDebug }
procedure TIdLogDebug.LogReceivedData(const AText, AData: string);
begin
DebugOutput('Recv ' + AText + ': ' + AData); {Do not Localize}
end;
procedure TIdLogDebug.LogSentData(const AText, AData: string);
begin
DebugOutput('Sent ' + AText + ': ' + AData); {Do not Localize}
end;
procedure TIdLogDebug.LogStatus(const AText: string);
begin
DebugOutput('Stat ' + AText); {Do not Localize}
end;
end.
|
unit ncgShell;
interface
uses Windows, SysUtils, Classes, Registry, madKernel, Dialogs;
type
TnexShellDir = (sdDesktop, sdStartMenu, sdPrograms, sdStartup);
TnexExplorerShellfolder = (esfShellFolders, esfUserShellFolders);
function GetShellDir(aShellDir: TnexShellDir; aUser, aNexCafe: Boolean): String;
function GetShellData(aESF: TnexExplorerShellFolder; aShellDir: TnexShellDir; aUser, aNexCafe: Boolean): String;
procedure ChangeShellData(DesktopToNexCafe, MenuIniciarToNexCafe: Boolean);
function StartupSubFolder: String;
function StartMenuSubFolder: String;
function ProgramsSubFolder: String;
function GetWinBaseFolder(aShellDir: TnexShellDir; aUser: Boolean): String;
procedure DelTree(aFolder: String; aOnlyFolders: Boolean);
procedure StartExplorer(aForce: Boolean = False);
var
UserCommonStartupFolder,
UserStartupFolder,
CommonStartupFolder,
StartupFolder : String;
CurrentUserName : String;
const
ValueName : Array[TnexShellDir] of String = (
'Desktop', 'Start Menu', 'Programs', 'Startup');
implementation
uses ncShellStart, ncDebug, ncClassesBase;
const
path_Explorer = '\Software\Microsoft\Windows\CurrentVersion\Explorer';
BoolStr : Array[Boolean] of String = ('FALSE', 'TRUE');
function SysDrive: String;
begin
Result := Copy(CommonStartupFolder, 1, 3);
end;
procedure DelFolder(aFolder: String; SL: TStrings; aOnlyFolders: Boolean);
var
SR : TSearchRec;
S : String;
begin
SL.Add('@@@'+aFolder);
if FindFirst(aFolder+'\*.*', faAnyFile, SR)=0 then
try
repeat
if (SR.Name<>aFolder) and (SR.Name<>'.') and (SR.Name<>'..') then
if (SR.Attr and faDirectory) = faDirectory then
DelFolder(aFolder+'\'+SR.Name, SL, aOnlyFolders)
else
if not aOnlyFolders then begin
S := SR.Name;
Windows.DeleteFile(PChar(SR.Name));
SL.Add(aFolder+'\'+S);
end;
until FindNext(SR)<>0;
finally
FindClose(SR);
end;
end;
procedure DelTree(aFolder: String; aOnlyFolders: Boolean);
var
SL : TStrings;
I : Integer;
S : String;
begin
SL := TStringList.Create;
try
DelFolder(aFolder, SL, aOnlyFolders);
for I := SL.Count-1 downto 0 do begin
S := SL[I];
if Copy(S, 1, 3)<>'@@@' then begin
Windows.DeleteFile(PChar(S));
SL.Delete(I);
end;
end;
for I := SL.Count-1 downto 0 do begin
S := SL[I];
Delete(S, 1, 3);
RemoveDirectory(PChar(S));
end;
finally
SL.Free;
end;
end;
procedure FechaProc(ProcessID: Cardinal);
VAR ProcessHandle: THANDLE;
ExitCode: DWORD;
begin
ExitCode:= 0;
ProcessHandle:= OpenProcess(PROCESS_CREATE_THREAD OR
PROCESS_VM_OPERATION
OR PROCESS_VM_WRITE OR PROCESS_VM_READ OR
PROCESS_TERMINATE,
FALSE,ProcessID);
if (ProcessHandle > 0) then
BEGIN
GetExitCodeProcess(ProcessHandle, ExitCode);
TerminateProcess(ProcessHandle,ExitCode);
CloseHandle(ProcessHandle);
END;
end;
procedure StartExplorer(aForce: Boolean = False);
begin
if aForce or (Processes('explorer.exe').ItemCount=0) then
ShellStart('explorer.exe');
end;
procedure ChangeShellData(DesktopToNexCafe, MenuIniciarToNexCafe: Boolean);
var R: TRegistry; SD : TnexShellDir; S: String;
begin
DebugMsg('*** ChangeShellData - DesktopToNexCafe: ' + BoolStr[DesktopToNexCafe] + ' - MenuIniciarToNexCafe: ' + BoolStr[MenuIniciarToNexCafe]);
R := TRegistry.Create;
try
R.RootKey := HKEY_CURRENT_USER;
R.Access := KEY_ALL_ACCESS or KEY_WOW64_64KEY;
if R.OpenKey(path_Explorer+'\User Shell Folders', True) then
for SD := Low(TnexShellDir) to High(TnexShellDir) do
if SD<>sdStartup then
if SD=sdDesktop then
R.WriteExpandString(ValueName[SD], GetShellData(esfUserShellFolders, SD, True, DesktopToNexCafe)) else
R.WriteExpandString(ValueName[SD], GetShellData(esfUserShellFolders, SD, True, MenuIniciarToNexCafe));
R.CloseKey;
if R.OpenKey(path_Explorer+'\Shell Folders', True) then
for SD := Low(TnexShellDir) to High(TnexShellDir) do
if SD<>sdStartup then
if SD=sdDesktop then
R.WriteExpandString(ValueName[SD], GetShellData(esfShellFolders, SD, True, DesktopToNexCafe)) else
R.WriteExpandString(ValueName[SD], GetShellData(esfShellFolders, SD, True, MenuIniciarToNexCafe));
R.CloseKey;
R.RootKey := HKEY_LOCAL_MACHINE;
R.Access := KEY_ALL_ACCESS or KEY_WOW64_64KEY;
if R.OpenKey(path_Explorer+'\User Shell Folders', False) then
for SD := Low(TnexShellDir) to High(TnexShellDir) do
if SD<>sdStartup then begin
if Sd=sdDesktop then
S := GetShellData(esfUserShellFolders, SD, False, DesktopToNexCafe) else
S := GetShellData(esfUserShellFolders, SD, False, MenuIniciarToNexCafe);
R.WriteExpandString('Common ' + ValueName[SD], S);
end;
R.CloseKey;
if R.OpenKey(path_Explorer+'\Shell Folders', False) then
for SD := Low(TnexShellDir) to High(TnexShellDir) do
if SD<>sdStartup then begin
if SD=sdDesktop then
S := GetShellData(esfShellFolders, SD, False, DesktopToNexCafe) else
S := GetShellData(esfShellFolders, SD, False, MenuIniciarToNexCafe);
R.WriteExpandString('Common ' + ValueName[SD], S);
end;
R.CloseKey;
finally
R.Free;
end;
end;
function GetCurrentUserName:String;
var le:DWORD;
begin
le:=63;
SetLength(result,le);
if GetUsername(PChar(result),le) then
SetLength(result, le-1) else
result:='(erro)';
end;
function GetShellDirRegistry(const aShellDir: TnexShellDir; const aKey: HKEY = HKEY_CURRENT_USER; const aUser: Boolean = True) : String;
var
R : TRegistry;
S : String;
begin
R := TRegistry.Create;
try
R.RootKey := aKey;
if aUser then
S := '\User Shell Folders' else
S := '\Shell Folders';
if not R.OpenKeyReadOnly(path_explorer+S) then begin
Result := '';
Exit;
end;
if aKey = HKEY_CURRENT_USER then
Result := R.ReadString(ValueName[aShellDir]) else
Result := R.ReadString('Common '+ValueName[aShellDir]);
finally
R.Free;
end;
DebugMsg('GetShellDirRegistry - aUser: ' + BoolStr[aUser] + ' - Result: ' + Result);
end;
function AppShellFolder(aUser: Boolean; aZero: Boolean): String;
begin
Result := ExtractFilePath(ParamStr(0))+'Shell\';
if aZero then
Result := Result + 'Zero\'
else
if aUser then
Result := Result + 'User\' else
Result := Result + 'Common\';
end;
function GetWinBaseFolder(aShellDir: TnexShellDir; aUser: Boolean): String;
var I, C: Integer;
begin
if Win32MajorVersion>5 then begin
if aShellDir=sdDesktop then begin
if aUser then
Result := SysDrive + 'Users\'+CurrentUserName+'\' else
Result := SysDrive + 'Users\Public\';
end else begin
if aUser then
Result := StartupFolder else
Result := CommonStartupFolder;
C := 0;
for I := Length(Result) downto 1 do begin
if Result[I]='\' then Inc(C);
if C=3 then Break;
end;
Result := Copy(Result, 1, I);
end;
end else begin
if aUser then
Result := SysDrive+ 'Documents And Settings\'+CurrentUserName+'\' else
Result := SysDrive + 'Documents And Settings\All Users\';
end;
debugMsg('GetWinBaseFolder - aUser: ' + BoolStr[aUser]+ ' - Res: ' + Result);
end;
function GetUserWinBaseFolder(aShellDir: TnexShellDir; aUser: Boolean): String;
var I, C: Integer;
begin
if Win32MajorVersion>5 then begin
if aShellDir=sdDesktop then begin
if aUser then
Result := '%USERPROFILE%\' else
Result := '%PUBLIC%\';
end else begin
if aUser then
Result := UserStartupFolder else
Result := UserCommonStartupFolder;
C := 0;
for I := Length(Result) downto 1 do begin
if Result[I]='\' then Inc(C);
if C=3 then Break;
end;
Result := Copy(Result, 1, I);
end;
end else begin
if aUser then
Result := '%USERPROFILE%\' else
Result := '%ALLUSERSPROFILE%\';
end;
debugMsg('*** GetUserWinBaseFolder - aUser: ' + BoolStr[aUser]+ ' - Res: ' + Result);
end;
function GetShellDir(aShellDir: TnexShellDir; aUser, aNexCafe: Boolean): String;
begin
if aNexCafe then begin
case aShellDir of
sdDesktop: Result := AppShellFolder(aUser, False) + 'Desktop';
sdStartMenu: Result := AppShellFolder(aUser, gConfig.BloqMenuIniciar) + StartMenuSubFolder;
sdPrograms: Result := AppShellFolder(aUser, gConfig.BloqMenuIniciar) + ProgramsSubFolder;
end;
end else begin
case aShellDir of
sdDesktop: Result := GetWinBaseFolder(aShellDir, aUser) + 'Desktop';
sdStartMenu: Result := GetWinBaseFolder(aShellDir, aUser) + StartMenuSubFolder;
sdPrograms: Result := GetWinBasefolder(aShellDir, aUser) + ProgramsSubFolder;
end;
end;
DebugMsg('*** GetShellDir - aUser: ' + BoolStr[aUser] + ' - aNexCafe: ' + BoolStr[aNexCafe] + ' - Res: ' + Result);
end;
function GetShellData(aESF: TnexExplorerShellFolder; aShellDir: TnexShellDir; aUser, aNexCafe: Boolean): String;
begin
if aNexCafe then begin
Result := GetShellDir(aShellDir, aUser, True);
end else begin
if aESF=esfShellFolders then
Result := GetShellDir(aShellDir, aUser, False)
else
case aShellDir of
sdDesktop: Result := GetUserWinBaseFolder(aShellDir, aUser) + 'Desktop';
sdStartMenu: Result := GetUserWinBaseFolder(aShellDir, aUser) + StartMenuSubFolder;
sdPrograms: Result := GetUserWinBasefolder(aShellDir, aUser) + ProgramsSubFolder;
end;
end;
DebugMsg('*** GetShellData - aUser: ' + BoolStr[aUser] + ' - aNexCafe: ' + BoolStr[aNexCafe] + ' - Res: ' + Result);
end;
function StartupSubFolder: String;
var I, C: Integer;
begin
Result := '';
C := 0;
for I := Length(StartupFolder) downto 1 do begin
if StartupFolder[I]='\' then Inc(C);
if C=3 then Break;
Result := StartupFolder[I] + Result;
end;
end;
function StartMenuSubFolder: String;
begin
Result := StartupSubFolder;
Result := Copy(Result, 1, Pos('\', Result)-1);
end;
function ProgramsSubFolder: String;
var I : Integer;
begin
Result := StartupSubFolder;
for I := Length(Result) downto 1 do
if Result[I]='\' then begin
Result := Copy(Result, 1, I-1);
Exit;
end;
end;
initialization
StartupFolder := GetShellDirRegistry(sdStartup, HKEY_CURRENT_USER, False);
CommonStartupFolder := GetShellDirRegistry(sdStartup, HKEY_LOCAL_MACHINE, False);
UserStartupFolder := GetShellDirRegistry(sdStartup, HKEY_CURRENT_USER, True);
UserCommonStartupFolder := GetShellDirRegistry(sdStartup, HKEY_LOCAL_MACHINE, True);
CurrentUserName := GetCurrentUserName;
end.
|
{
"Socket Handle Pool" - Copyright (c) Danijel Tkalcec
@exclude
}
unit rtcSocketPool;
{$INCLUDE rtcDefs.inc}
interface
uses
rtcTrashcan,
Windows,
SysUtils,
Classes,
rtcSyncObjs,
rtcLog,
rtcThrPool;
procedure rtcEnterSocket;
procedure rtcLeaveSocket;
// Get socket (need to call rtcEnterSocket before & rtcLeaveSocket after)
function rtcGetSocket(sock:longword):TObject;
// Check socket (no need to call rtcEnterSocket and rtcLeaveSocket)
function rtcCheckSocket(sock:longword):TObject;
// Store socket (thread-safe)
procedure rtcStoreSocket(obj:TObject; sock:longword);
// Remove socket (thread-safe)
function rtcRemoveSocket(obj:TObject):boolean;
implementation
uses
memBinTree;
var
SockList:tBinTree;
CSHWND:TRtcCritSec;
procedure rtcStoreSocket(obj:TObject; sock:longword);
//var i:longword;
begin
CSHWND.Enter;
try
{i:=SockList.search(longword(Obj));
if i<>0 then // object in the list
begin
Log('Exception! Socket not removed.');
SockList.remove(longword(Obj));
end;
if SockList.isearch(sock)<>0 then
Log('Exception! Other object using same socket!');}
// add socket-to-object reference
SockList.insert(longword(Obj), Sock);
finally
CSHWND.Leave;
end;
end;
function rtcRemoveSocket(obj:TObject):boolean;
var
i:longword;
begin
Result:=False;
CSHWND.Enter;
try
i:=SockList.search(longword(Obj));
if i<>0 then // object in the list
begin
SockList.remove(longword(Obj));
Result:=True;
end;
finally
CSHWND.Leave;
end;
end;
procedure rtcEnterSocket;
begin
CSHWND.Enter;
end;
procedure rtcLeaveSocket;
begin
CSHWND.Leave;
end;
function rtcGetSocket(Sock:longword):TObject;
var
i:longword;
begin
i:=SockList.isearch(Sock);
if i<>0 then
Result:=TObject(i)
else
Result:=nil;
end;
function rtcCheckSocket(Sock:longword):TObject;
var
i:longword;
begin
CSHWND.Enter;
try
i:=SockList.isearch(Sock);
if i<>0 then
Result:=TObject(i)
else
Result:=nil;
finally
CSHWND.Leave;
end;
end;
initialization
CSHWND:=TRtcCritSec.Create;
SockList:=tBinTree.Create(256);
finalization
Garbage(SockList);
Garbage(CSHWND);
end.
|
unit constexpr_2;
interface
implementation
function Add(a, b: Int32): Int32; pure;
begin
Result := a + b;
end;
var G1, G2: Int32;
procedure Test;
begin
G1 := Add(1, 2);
G2 := Add(G1, 1);
end;
initialization
Test();
finalization
Assert(G1 = 3);
Assert(G2 = 4);
end. |
unit TMHtmlWindow;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, OleCtrls, SHDocVw, StdCtrls, JvGradient, ExtCtrls, TMStruct,
JvExControls;
type
THtmlWindow = class(TForm)
TopPanel: TPanel;
AboutHeader: TLabel;
JvGradient2: TJvGradient;
BottomPanel: TPanel;
CloseBtn: TButton;
WebBrowser: TWebBrowser;
Bevel1: TBevel;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure CloseBtnClick(Sender: TObject);
procedure WebBrowserBeforeNavigate2(Sender: TObject;
const pDisp: IDispatch; var URL, Flags, TargetFrameName, PostData,
Headers: OleVariant; var Cancel: WordBool);
procedure WebBrowserDocumentComplete(Sender: TObject;
const pDisp: IDispatch; var URL: OleVariant);
procedure FormShow(Sender: TObject);
procedure WebBrowserTitleChange(Sender: TObject;
const Text: WideString);
private
FSrc: String;
FHeader: String;
FHtmlActions: TStringList;
FHtmlWindowFlags: THtmlWindowFlags;
procedure SetSrc(const Value: String);
procedure SetHeader(const Value: String);
procedure SetHtmlWindowFlags(const Value: THtmlWindowFlags);
protected
procedure CreateParams(var Params: TCreateParams); override;
public
property Header: String read FHeader write SetHeader;
property Src: String read FSrc write SetSrc;
property HtmlActions: TStringList read FHtmlActions write FHtmlActions;
property HtmlWindowFlags: THtmlWindowFlags read FHtmlWindowFlags write SetHtmlWindowFlags;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure SetPosAndDimensions(ALeft, ATop, AWidth, AHeight: Integer);
end;
var
HtmlWindow: THtmlWindow;
implementation
uses
TMMsgs, JclStrings, TMMain;
{$R *.dfm}
var
HookID: THandle;
MouseHookEnabled: Boolean;
function MouseProc(nCode: Integer; wParam, lParam: Longint): Longint; stdcall;
var
szClassName: array[0..255] of Char;
const
ie_name = 'Internet Explorer_Server';
begin
case nCode < 0 of
True:
Result := CallNextHookEx(HookID, nCode, wParam, lParam)
else
case wParam of
WM_RBUTTONDOWN,
WM_RBUTTONUP:
begin
GetClassName(PMOUSEHOOKSTRUCT(lParam)^.HWND, szClassName, SizeOf(szClassName));
if (lstrcmp(@szClassName[0], @ie_name[1]) = 0) and MouseHookEnabled then
Result := HC_SKIP
else
Result := CallNextHookEx(HookID, nCode, wParam, lParam);
end
else
Result := CallNextHookEx(HookID, nCode, wParam, lParam);
end;
end;
end;
{ THtmlWindow }
procedure THtmlWindow.CloseBtnClick(Sender: TObject);
begin
Close;
end;
constructor THtmlWindow.Create(AOwner: TComponent);
begin
inherited;
{ Hook the window to prevent the TWebBrowser popup menu }
HookID := SetWindowsHookEx(WH_MOUSE, MouseProc, 0, GetCurrentThreadId());
end;
procedure THtmlWindow.CreateParams(var Params: TCreateParams);
begin
inherited;
if hwfAlwaysOnTop in HtmlWindowFlags then
Params.WndParent := GetDesktopWindow
else
Params.WndParent := Application.Handle;
end;
destructor THtmlWindow.Destroy;
begin
{ Unhook the window }
if HookID <> 0 then
UnHookWindowsHookEx(HookID);
{ Other de-inits }
HtmlWindow := nil;
inherited;
end;
procedure THtmlWindow.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
end;
procedure THtmlWindow.SetPosAndDimensions(ALeft, ATop, AWidth, AHeight: Integer);
begin
if AWidth > 0 then
ClientWidth := AWidth;
if AHeight > 0 then
begin
ClientHeight := AHeight;
if BottomPanel.Visible then
ClientHeight := ClientHeight + BottomPanel.Height;
if TopPanel.Visible then
ClientHeight := ClientHeight + TopPanel.Height;
end;
if ALeft >= 0 then
Left := ALeft
else if ALeft < 0 then
Left := Screen.Width + ALeft;
if ATop >= 0 then
Top := ATop
else if ATop < 0 then
Top := Screen.Height + ATop;
end;
procedure THtmlWindow.SetHeader(const Value: String);
begin
FHeader := Value;
AboutHeader.Caption := ' ' + Value;
end;
procedure THtmlWindow.SetHtmlWindowFlags(const Value: THtmlWindowFlags);
begin
FHtmlWindowFlags := Value;
{ Apply the flags }
if hwfMaximized in HtmlWindowFlags then
WindowState := wsMaximized
else
WindowState := wsNormal;
if hwfNoResize in HtmlWindowFlags then
BorderStyle := bsDialog
else
BorderStyle := bsSizeable;
MouseHookEnabled := not (hwfEnableContextMenu in HtmlWindowFlags);
BottomPanel.Visible := not (hwfNoCloseButton in HtmlWindowFlags);
TopPanel.Visible := not (hwfNoHeader in HtmlWindowFlags);
if hwfAlwaysOnTop in HtmlWindowFlags then
FormStyle := fsStayOnTop
else
FormStyle := fsNormal;
// SetWindowPos(Handle, HWND_TOPMOST, 0, 0, 0, 0,
// SWP_NOACTIVATE + SWP_NOSIZE + SWP_NOMOVE)
// else
// SetWindowPos(Handle, HWND_NOTOPMOST, 0, 0, 0, 0,
// SWP_NOACTIVATE + SWP_NOSIZE + SWP_NOMOVE);
end;
procedure THtmlWindow.SetSrc(const Value: String);
begin
FSrc := Value;
WebBrowser.Navigate(Value);
end;
procedure THtmlWindow.WebBrowserBeforeNavigate2(Sender: TObject;
const pDisp: IDispatch; var URL, Flags, TargetFrameName, PostData,
Headers: OleVariant; var Cancel: WordBool);
var
I: Integer;
begin
{ Intercept and handle action URLs }
if StrIPos('action:', Trim(URL)) = 1 then
begin
Cancel := True;
if HtmlActions.Find( Trim(StrAfter('action:', Trim(URL))), I) then
(HtmlActions.Objects[I] as TTMMultiAction).ExecuteAction
else
raise Exception.CreateFmt(SHtmlUnknownAction, [Trim(StrAfter('action:', Trim(URL)))]);
end;
if SameText('close:', Trim(URL)) then
begin
Cancel := True;
Close;
end;
end;
procedure THtmlWindow.WebBrowserDocumentComplete(Sender: TObject;
const pDisp: IDispatch; var URL: OleVariant);
begin
{ Apply some flags }
if hwfNoScrollbars in HtmlWindowFlags then
if not VarIsEmpty(WebBrowser.OleObject.Document) then
begin
WebBrowser.OleObject.Document.Body.Style.OverflowX := 'hidden';
WebBrowser.OleObject.Document.Body.Style.OverflowY := 'hidden';
end;
end;
procedure THtmlWindow.FormShow(Sender: TObject);
begin
if hwfAlwaysOnTop in HtmlWindowFlags then
ShowWindow(Application.Handle, SW_HIDE);
//Prevent application taskbar button from showing up
end;
procedure THtmlWindow.WebBrowserTitleChange(Sender: TObject;
const Text: WideString);
begin
Caption := Text;
end;
initialization
MouseHookEnabled := True;
end.
|
unit Test.Unicode;
interface
uses
Deltics.Smoketest;
type
Utils = class(TTest)
procedure IsHiSurrogateReturnsFalseForNonHiSurrogates;
procedure IsHiSurrogateReturnsTrueForHiSurrogates;
procedure IsLoSurrogateReturnsFalseForNonLoSurrogates;
procedure IsLoSurrogateReturnsTrueForLoSurrogates;
procedure CodepointToSurrogateEncodesValidSurrogatesCorrectly;
procedure CodepointToSurrogateRaisesEInvalidCodepointIfCodepointIsInvalid;
procedure CodepointToSurrogateRaisesEInvalidCodepointIfCodepointLiesInBMP;
procedure CodepointToSurrogateRaisesEInvalidCodepointIfCodepointIsReservedForSurrogates;
procedure CodepointToUtf8EncodesValidCodepointsCorrectly;
procedure SurrogatesToCodepointDecodesValidSurrogatesCorrectly;
procedure SurrogatesToCodepointRaisesEInvalidHiSurrogateIfHiSurrogateIsNotValid;
procedure SurrogatesToCodepointRaisesEInvalidLoSurrogateIfLoSurrogateIsNotValid;
procedure Utf16ToUtf8StringsEncodesValidStringCorrectly;
procedure Utf8ToCodepointEncodesValidUtf8Correctly;
procedure Utf8ToCodepointRaisesEInvalidEncodingIfByteIsNotAValidLeadByte;
procedure Utf8ToCodepointRaisesEInvalidEncodingIfContinuationByteIsInvalid;
procedure Utf8ToCodepointRaisesEInvalidEncodingIfFirstOfTwoContinuationBytesIsInvalid;
procedure Utf8ToCodepointRaisesEInvalidEncodingIfFirstOfThreeContinuationBytesIsInvalid;
procedure Utf8ToCodepointRaisesEInvalidEncodingIfSecondOfTwoContinuationBytesIsInvalid;
procedure Utf8ToCodepointRaisesEInvalidEncodingIfSecondOfThreeContinuationBytesIsInvalid;
procedure Utf8ToCodepointRaisesEInvalidEncodingIfThirdOfThreeContinuationBytesIsInvalid;
procedure Utf8ToCodepointRaisesEMoreDataIfOneRequiredContinuationByteOfOneIsNotAvailable;
procedure Utf8ToCodepointRaisesEMoreDataIfAtLeastOneRequiredContinuationByteOfTwoIsNotAvailable;
procedure Utf8ToCodepointRaisesEMoreDataIfAtLeastOneRequiredContinuationByteOfThreeIsNotAvailable;
procedure Utf8ToCodepointRaisesENoData;
procedure Utf8ToUtf16StringsEncodesValidStringCorrectly;
procedure Utf8ToCodepointYieldsEmptyArrayIfInputArrayIsEmpty;
procedure AnsiToWideToAnsi;
end;
implementation
uses
Deltics.Unicode;
{ Transcoding ------------------------------------------------------------------------------------ }
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
{ UnicodeUtils }
procedure Utils.AnsiToWideToAnsi;
var
c: AnsiChar;
w: WideChar;
o: AnsiChar;
begin
for o := #0 to #255 do
begin
w := Unicode.AnsiCharToWide(o);
c := Unicode.WideCharToAnsi(w);
Test('AnsiCharToWide -> WideCharToAnsi').Assert(c).Equals(o);
end;
end;
procedure Utils.CodepointToSurrogateEncodesValidSurrogatesCorrectly;
var
hi, lo: WideChar;
begin
Unicode.CodepointToSurrogates($10000, hi, lo);
Test('CodepointToSurrogates($10000).hi').Assert(hi).Equals(WideChar($d800));
Test('CodepointToSurrogates($10000).lo').Assert(lo).Equals(WideChar($dc00));
Unicode.CodepointToSurrogates($10437, hi, lo);
Test('CodepointToSurrogates($10437).hi').Assert(hi).Equals(WideChar($d801));
Test('CodepointToSurrogates($10437).lo').Assert(lo).Equals(WideChar($dc37));
Unicode.CodepointToSurrogates($24b62, hi, lo);
Test('CodepointToSurrogates($24b62).hi').Assert(hi).Equals(WideChar($d852));
Test('CodepointToSurrogates($24b62).lo').Assert(lo).Equals(WideChar($df62));
Unicode.CodepointToSurrogates($10ffff, hi, lo);
Test('CodepointToSurrogates($10ffff).hi').Assert(hi).Equals(WideChar($dbff));
Test('CodepointToSurrogates($10ffff).lo').Assert(lo).Equals(WideChar($dfff));
end;
procedure Utils.CodepointToSurrogateRaisesEInvalidCodepointIfCodepointIsInvalid;
var
hi, lo: WideChar;
begin
Test.Raises(EInvalidCodepoint, 'U+110000 is not a valid codepoint');
Unicode.CodepointToSurrogates($110000, hi, lo);
end;
procedure Utils.CodepointToSurrogateRaisesEInvalidCodepointIfCodepointIsReservedForSurrogates;
var
hi, lo: WideChar;
begin
Test.Raises(EInvalidCodepoint, 'The codepoint U+D800 is reserved for surrogate encoding');
Unicode.CodepointToSurrogates($d800, hi, lo);
end;
procedure Utils.CodepointToSurrogateRaisesEInvalidCodepointIfCodepointLiesInBMP;
var
hi, lo: WideChar;
begin
Test.Raises(EInvalidCodepoint, 'The codepoint U+00A9 is not in the Supplementary Plane');
Unicode.CodepointToSurrogates($00a9, hi, lo);
end;
procedure Utils.CodepointToUtf8EncodesValidCodepointsCorrectly;
var
utf8: Utf8Array;
begin
Unicode.CodepointToUtf8($0041, utf8);
if Test('CodepointToUtf8($0041).length').Assert(Length(utf8)).Equals(1).Passed then
Test('CodepointToUtf8($0041)[0]').Assert(utf8[0]).Equals(#$41);
Unicode.CodepointToUtf8($00a9, utf8);
if Test('CodepointToUtf8($00a9).length').Assert(Length(utf8)).Equals(2).Passed then
begin
Test('CodepointToUtf8($00a9)[0]').Assert(utf8[0]).Equals(#$c2);
Test('CodepointToUtf8($00a9)[1]').Assert(utf8[1]).Equals(#$a9);
end;
Unicode.CodepointToUtf8($d55c, utf8);
if Test('CodepointToUtf8($d55c).length').Assert(Length(utf8)).Equals(3).Passed then
begin
Test('CodepointToUtf8($d55c)[0]').Assert(utf8[0]).Equals(#$ed);
Test('CodepointToUtf8($d55c)[1]').Assert(utf8[1]).Equals(#$95);
Test('CodepointToUtf8($d55c)[1]').Assert(utf8[2]).Equals(#$9c);
end;
Unicode.CodepointToUtf8($10348, utf8);
if Test('CodepointToUtf8($10348).length').Assert(Length(utf8)).Equals(4).Passed then
begin
Test('CodepointToUtf8($10348)[0]').Assert(utf8[0]).Equals(#$f0);
Test('CodepointToUtf8($10348)[1]').Assert(utf8[1]).Equals(#$90);
Test('CodepointToUtf8($10348)[2]').Assert(utf8[2]).Equals(#$8d);
Test('CodepointToUtf8($10348)[3]').Assert(utf8[3]).Equals(#$88);
end;
end;
procedure Utils.IsHiSurrogateReturnsFalseForNonHiSurrogates;
begin
Test('IsHiSurrogate($0040)').Assert(Unicode.IsHiSurrogate(WideChar($0040))).IsFalse;
Test('IsHiSurrogate($d799)').Assert(Unicode.IsHiSurrogate(WideChar($d799))).IsFalse;
Test('IsHiSurrogate($dc00)').Assert(Unicode.IsHiSurrogate(WideChar($dc00))).IsFalse;
Test('IsHiSurrogate($fffe)').Assert(Unicode.IsHiSurrogate(WideChar($fffe))).IsFalse;
end;
procedure Utils.IsHiSurrogateReturnsTrueForHiSurrogates;
begin
Test('IsHiSurrogate($d800)').Assert(Unicode.IsHiSurrogate(WideChar($d800))).IsTrue;
Test('IsHiSurrogate($da00)').Assert(Unicode.IsHiSurrogate(WideChar($da00))).IsTrue;
Test('IsHiSurrogate($dbff)').Assert(Unicode.IsHiSurrogate(WideChar($dbff))).IsTrue;
end;
procedure Utils.IsLoSurrogateReturnsFalseForNonLoSurrogates;
begin
Test('IsLoSurrogate($0040)').Assert(Unicode.IsLoSurrogate(WideChar($0040))).IsFalse;
Test('IsLoSurrogate($dbff)').Assert(Unicode.IsLoSurrogate(WideChar($dbff))).IsFalse;
Test('IsLoSurrogate($e000)').Assert(Unicode.IsLoSurrogate(WideChar($e000))).IsFalse;
Test('IsLoSurrogate($fffe)').Assert(Unicode.IsLoSurrogate(WideChar($fffe))).IsFalse;
end;
procedure Utils.IsLoSurrogateReturnsTrueForLoSurrogates;
begin
Test('IsLoSurrogate($dc00)').Assert(Unicode.IsLoSurrogate(WideChar($dc00))).IsTrue;
Test('IsLoSurrogate($dd72)').Assert(Unicode.IsLoSurrogate(WideChar($dd72))).IsTrue;
Test('IsLoSurrogate($dcff)').Assert(Unicode.IsLoSurrogate(WideChar($dfff))).IsTrue;
end;
procedure Utils.SurrogatesToCodepointDecodesValidSurrogatesCorrectly;
var
sut: Codepoint;
begin
sut := Unicode.SurrogatesToCodepoint(#$d800, #$dc00);
Test('SurrogatesToCodepoint($d800, $dc00)').Assert(sut).Equals($10000);
sut := Unicode.SurrogatesToCodepoint(#$d801, #$dc37);
Test('SurrogatesToCodepoint($d801, $dc37)').Assert(sut).Equals($10437);
sut := Unicode.SurrogatesToCodepoint(#$d852, #$df62);
Test('SurrogatesToCodepoint($d852, $df62)').Assert(sut).Equals($24b62);
sut := Unicode.SurrogatesToCodepoint(#$dbff, #$dfff);
Test('SurrogatesToCodepoint($dbff, $dfff)').Assert(sut).Equals($10ffff);
end;
procedure Utils.SurrogatesToCodepointRaisesEInvalidHiSurrogateIfHiSurrogateIsNotValid;
begin
Test.Raises(EInvalidHiSurrogate);
Unicode.SurrogatesToCodepoint(#$df62, #$df62);
end;
procedure Utils.SurrogatesToCodepointRaisesEInvalidLoSurrogateIfLoSurrogateIsNotValid;
begin
Test.Raises(EInvalidLoSurrogate);
Unicode.SurrogatesToCodepoint(#$d852, #$d852);
end;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
procedure Utils.Utf16ToUtf8StringsEncodesValidStringCorrectly;
var
input: UnicodeString;
result: Utf8String;
expectedResult: Utf8String;
begin
input := '©2020??';
input[6] := #$d801;
input[7] := #$dc37;
expectedResult := '??2020????';
expectedResult[1] := Utf8Char($c2);
expectedResult[2] := Utf8Char($a9);
expectedResult[7] := Utf8Char($f0);
expectedResult[8] := Utf8Char($90);
expectedResult[9] := Utf8Char($90);
expectedResult[10] := Utf8Char($b7);
result := Unicode.Utf16ToUtf8(input);
Test('Utf16ToUtf8({input})', [input]).AssertUtf8(result).Equals(expectedResult);
end;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
procedure Utils.Utf8ToCodepointEncodesValidUtf8Correctly;
var
cp: Codepoint;
begin
cp := Unicode.Utf8ToCodepoint(Unicode.Utf8Array([#$41]));
Test('Utf8ToCodepoint([$41])').Assert(cp).Equals($41);
cp := Unicode.Utf8ToCodepoint(Unicode.Utf8Array([#$c2, #$a9]));
Test('Utf8ToCodepoint([$c2, $a9])').Assert(cp).Equals($a9);
cp := Unicode.Utf8ToCodepoint(Unicode.Utf8Array([#$ed, #$95, #$9c]));
Test('Utf8ToCodepoint([$ed, $95, $9c])').Assert(cp).Equals($d55c);
cp := Unicode.Utf8ToCodepoint(Unicode.Utf8Array([#$f0, #$90, #$8d, #$88]));
Test('Utf8ToCodepoint([$f0, $90, $8d, $88])').Assert(cp).Equals($10348);
end;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
procedure Utils.Utf8ToCodepointRaisesEInvalidEncodingIfByteIsNotAValidLeadByte;
begin
Test.Raises(EInvalidEncoding, '0xFF is not a valid byte in Utf8');
Unicode.Utf8ToCodepoint(Unicode.Utf8Array([#$ff]));
end;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
procedure Utils.Utf8ToCodepointRaisesEInvalidEncodingIfContinuationByteIsInvalid;
begin
Test.Raises(EInvalidEncoding, '0x20 is not a valid continuation byte');
Unicode.Utf8ToCodepoint(Unicode.Utf8Array([#$c2, #$20]));
end;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
procedure Utils.Utf8ToCodepointRaisesEInvalidEncodingIfFirstOfThreeContinuationBytesIsInvalid;
begin
Test.Raises(EInvalidEncoding, '0x20 is not a valid continuation byte');
Unicode.Utf8ToCodepoint(Unicode.Utf8Array([#$f0, #$20, #$8d, #$88]));
end;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
procedure Utils.Utf8ToCodepointRaisesEInvalidEncodingIfFirstOfTwoContinuationBytesIsInvalid;
begin
Test.Raises(EInvalidEncoding, '0x20 is not a valid continuation byte');
Unicode.Utf8ToCodepoint(Unicode.Utf8Array([#$ed, #$20, #$9c]));
end;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
procedure Utils.Utf8ToCodepointRaisesEInvalidEncodingIfSecondOfThreeContinuationBytesIsInvalid;
begin
Test.Raises(EInvalidEncoding, '0x20 is not a valid continuation byte');
Unicode.Utf8ToCodepoint(Unicode.Utf8Array([#$f0, #$90, #$20, #$88]));
end;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
procedure Utils.Utf8ToCodepointRaisesEInvalidEncodingIfSecondOfTwoContinuationBytesIsInvalid;
begin
Test.Raises(EInvalidEncoding, '0x20 is not a valid continuation byte');
Unicode.Utf8ToCodepoint(Unicode.Utf8Array([#$ed, #$95, #$20]));
end;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
procedure Utils.Utf8ToCodepointRaisesEInvalidEncodingIfThirdOfThreeContinuationBytesIsInvalid;
begin
Test.Raises(EInvalidEncoding, '0x20 is not a valid continuation byte');
Unicode.Utf8ToCodepoint(Unicode.Utf8Array([#$f0, #$90, #$8d, #$20]));
end;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
procedure Utils.Utf8ToCodepointRaisesEMoreDataIfAtLeastOneRequiredContinuationByteOfThreeIsNotAvailable;
begin
Test.Raises(EMoreData, '3 continuation bytes required, 2 available');
Unicode.Utf8ToCodepoint(Unicode.Utf8Array([#$f0, #$90, #$8d]));
end;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
procedure Utils.Utf8ToCodepointRaisesEMoreDataIfAtLeastOneRequiredContinuationByteOfTwoIsNotAvailable;
begin
Test.Raises(EMoreData, '2 continuation bytes required, 1 available');
Unicode.Utf8ToCodepoint(Unicode.Utf8Array([#$ed, #$95]));
end;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
procedure Utils.Utf8ToCodepointRaisesEMoreDataIfOneRequiredContinuationByteOfOneIsNotAvailable;
begin
Test.Raises(EMoreData, '1 continuation byte required, 0 available');
Unicode.Utf8ToCodepoint(Unicode.Utf8Array([#$c2]));
end;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
procedure Utils.Utf8ToCodepointRaisesENoData;
begin
Test.Raises(ENoData, 'No Utf8 characters available');
Unicode.Utf8ToCodepoint(Unicode.Utf8Array([]));
end;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
procedure Utils.Utf8ToUtf16StringsEncodesValidStringCorrectly;
var
input: Utf8String;
result: UnicodeString;
expectedResult: UnicodeString;
begin
expectedResult := '©2020??';
expectedResult[6] := #$d801;
expectedResult[7] := #$dc37;
input := '??2020????';
input[1] := Utf8Char($c2);
input[2] := Utf8Char($a9);
input[7] := Utf8Char($f0);
input[8] := Utf8Char($90);
input[9] := Utf8Char($90);
input[10] := Utf8Char($b7);
result := Unicode.Utf8ToUtf16(input);
Test('Utf8ToUtf16({input})', [input]).Assert(result).Equals(expectedResult);
end;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
procedure Utils.Utf8ToCodepointYieldsEmptyArrayIfInputArrayIsEmpty;
var
result: Utf8Array;
begin
result := Unicode.Utf8Array([]);
Test('Length(result)').Assert(Length(result)).Equals(0);
end;
end.
|
{------------------------------------------------------------------------------
This file is part of the MotifMASTER project. This software is
distributed under GPL (see gpl.txt for details).
This software 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.
Copyright (C) 1999-2007 D.Morozov (dvmorozov@mail.ru)
------------------------------------------------------------------------------}
unit ObjSavingStringList;
interface
uses
ComponentList, SelfCopied, SysUtils, Classes, SelfSaved, ClassInheritIDs;
type
TObjSavingStringList = class(TSelfCopiedCompList)
protected
class function GetPropHeaderRec: TPropHeaderRec; override;
class procedure ReadProperties(
const Reader: TReader;
const PropHeaderRec: TPropHeaderRec;
const AnObject: TSelfSavedComponent
); override;
class procedure WriteProperties(
const Writer: TWriter;
const AnObject: TSelfSavedComponent
); override;
public
function GetObjectIdentifier(const ObjNum: LongInt): string; virtual;
end;
implementation
function TObjSavingStringList.GetObjectIdentifier(const ObjNum: LongInt): string;
begin
Result := 'Object ' + IntToStr(ObjNum);
end;
class function TObjSavingStringList.GetPropHeaderRec: TPropHeaderRec;
begin
Result.ClassInheritID := OSSLClassInheritID;
Result.PropVersionNum := OSSLCurVerNum;
end;
class procedure TObjSavingStringList.ReadProperties(const Reader: TReader;
const PropHeaderRec: TPropHeaderRec;
const AnObject: TSelfSavedComponent);
begin
end;
class procedure TObjSavingStringList.WriteProperties(const Writer: TWriter;
const AnObject: TSelfSavedComponent);
begin
end;
initialization
RegisterClass(TObjSavingStringList);
end.
|
unit ClntMain;
{ This demo uses the IBLOCAL alias which is setup by the install program
when you install Delphi 5.0 if you have installed Local Interbase.
This example demonstrates how ClientDataSets can be used in a master-detail
application. This is the client application. You must compile and
run the Server application before running this program.
}
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ComCtrls, ExtCtrls, DBCtrls, ToolWin, Grids, DBGrids, StdCtrls, Mask, Db,
Buttons;
type
TClientForm = class(TForm)
Label2: TLabel;
MemberGrid: TDBGrid;
Label5: TLabel;
Label6: TLabel;
DescMemo: TDBMemo;
ProjectGrid: TDBGrid;
AddBtn: TButton;
DeleteBtn: TButton;
LeaderBtn: TButton;
ProductCombo: TDBComboBox;
Toolbar: TPanel;
DBNavigator1: TDBNavigator;
ApplyUpdatesBtn: TSpeedButton;
procedure MemberGridDrawColumnCell(Sender: TObject; const Rect: TRect;
DataCol: Integer; Column: TColumn; State: TGridDrawState);
procedure DeleteBtnClick(Sender: TObject);
procedure AddBtnClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure LeaderBtnClick(Sender: TObject);
procedure ApplyUpdatesBtnClick(Sender: TObject);
end;
var
ClientForm: TClientForm;
implementation
uses ClntDM;
{$R *.DFM}
{ Bold the leader in the member list. }
procedure TClientForm.MemberGridDrawColumnCell(Sender: TObject; const Rect: TRect;
DataCol: Integer; Column: TColumn; State: TGridDrawState);
begin
if DM.ProjectTEAM_LEADER.Value = DM.Emp_ProjEMP_NO.Value then
MemberGrid.Canvas.Font.Style := [fsBold];
MemberGrid.DefaultDrawColumnCell(Rect, DataCol, Column, State);
end;
procedure TClientForm.DeleteBtnClick(Sender: TObject);
begin
DM.Emp_Proj.Delete;
end;
procedure TClientForm.AddBtnClick(Sender: TObject);
begin
MemberGrid.SetFocus;
DM.Emp_Proj.Append;
MemberGrid.EditorMode := True;
end;
{ Set the column width to the width of the grid. }
procedure TClientForm.FormCreate(Sender: TObject);
begin
MemberGrid.Columns[0].Width := MemberGrid.ClientWidth - GetSystemMetrics(SM_CXVSCROLL);
end;
{ Set the team leader. }
procedure TClientForm.LeaderBtnClick(Sender: TObject);
var
NewLeader: Integer;
begin
NewLeader := DM.Emp_ProjEMP_NO.Value;
if not (DM.Project.State in dsEditModes) then
DM.Project.Edit;
DM.ProjectTEAM_LEADER.Value := NewLeader;
MemberGrid.Refresh;
end;
procedure TClientForm.ApplyUpdatesBtnClick(Sender: TObject);
begin
DM.ApplyUpdates;
end;
end.
|
(*
Name: UfrmVisualKeyboardExportBMPParams
Copyright: Copyright (C) SIL International.
Documentation:
Description:
Create Date: 23 Aug 2006
Modified Date: 18 May 2012
Authors: mcdurdin
Related Files:
Dependencies:
Bugs:
Todo:
Notes:
History: 23 Aug 2006 - mcdurdin - Initial refactor for new visual keyboard
22 Jan 2007 - mcdurdin - Rework to support pixel size for export
19 Nov 2007 - mcdurdin - I1157 - const string parameters
03 May 2011 - mcdurdin - I2890 - Record diagnostic data when encountering registry errors
18 May 2012 - mcdurdin - I3306 - V9.0 - Remove TntControls + Win9x support
*)
unit UfrmVisualKeyboardExportBMPParams; // I3306
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ImgList;
type
TfrmVisualKeyboardExportBMPParams = class(TForm)
gbOutputType: TGroupBox;
rbMulti: TRadioButton;
rbSingle: TRadioButton;
Label1: TLabel;
lblFileName: TLabel;
Label4: TLabel;
Label5: TLabel;
gbOptions: TGroupBox;
chkUnicode: TCheckBox;
chkANSI: TCheckBox;
cmdOK: TButton;
cmdCancel: TButton;
imglistKeys: TImageList;
gbSize: TGroupBox;
lblPixelWidth: TLabel;
editPixelWidth: TEdit;
procedure FormCreate(Sender: TObject);
procedure cmdOKClick(Sender: TObject);
private
function GetMultiFile: Boolean;
function GetOutputANSI: Boolean;
function GetOutputUnicode: Boolean;
procedure SetFileName(Value: string);
function GetPixelWidth: Integer;
public
property FileName: string write SetFileName;
property MultiFile: Boolean read GetMultiFile;
property OutputUnicode: Boolean read GetOutputUnicode;
property OutputANSI: Boolean read GetOutputANSI;
property PixelWidth: Integer read GetPixelWidth;
end;
implementation
{$R *.DFM}
uses
ErrorControlledRegistry,
RegistryKeys;
{ TfrmVisualKeyboardExportBMPParams }
function TfrmVisualKeyboardExportBMPParams.GetMultiFile: Boolean;
begin
Result := rbMulti.Checked;
end;
function TfrmVisualKeyboardExportBMPParams.GetOutputANSI: Boolean;
begin
Result := chkANSI.Checked;
end;
function TfrmVisualKeyboardExportBMPParams.GetOutputUnicode: Boolean;
begin
Result := chkUnicode.Checked;
end;
function TfrmVisualKeyboardExportBMPParams.GetPixelWidth: Integer;
begin
Result := StrToIntDef(editPixelWidth.Text, 720);
end;
procedure TfrmVisualKeyboardExportBMPParams.SetFileName(Value: string);
begin
lblFileName.Caption := ChangeFileExt(ExtractFileName(Value), '') + '_U_<shift>' +
ExtractFileExt(Value);
end;
procedure TfrmVisualKeyboardExportBMPParams.FormCreate(Sender: TObject);
var
b: Boolean;
begin
with TRegistryErrorControlled.Create do // I2890
try
RootKey := HKEY_CURRENT_USER;
if OpenKeyReadOnly(SRegKey_IDEVisualKeyboard) then
begin
if ValueExists(SRegValue_IDEVKbd_ExportBMPMulti)
then b := ReadString(SRegValue_IDEVKbd_ExportBMPMulti) = '1'
else b := False;
rbMulti.Checked := b;
rbSingle.Checked := not b;
chkANSI.Checked := not ValueExists(SRegValue_IDEVKbd_ExportBMPANSI) or
(ReadString(SRegValue_IDEVKbd_ExportBMPANSI) = '1');
chkUnicode.Checked := not ValueExists(SRegValue_IDEVKbd_ExportBMPUnicode) or
(ReadString(SRegValue_IDEVKbd_ExportBMPUnicode) = '1');
if ValueExists(SRegValue_IDEVKbd_ExportBMPPixelWidth) then
editPixelWidth.Text := IntToStr(ReadInteger(SRegValue_IDEVKbd_ExportBMPPixelWidth));
end;
finally
Free;
end;
end;
procedure TfrmVisualKeyboardExportBMPParams.cmdOKClick(Sender: TObject);
begin
with TRegistryErrorControlled.Create do // I2890
try
RootKey := HKEY_CURRENT_USER;
if OpenKey(SRegKey_IDEVisualKeyboard, True) then
begin
if rbMulti.Checked
then WriteString(SRegValue_IDEVKbd_ExportBMPMulti, '1')
else WriteString(SRegValue_IDEVKbd_ExportBMPMulti, '0');
if chkANSI.Checked
then WriteString(SRegValue_IDEVKbd_ExportBMPANSI, '1')
else WriteString(SRegValue_IDEVKbd_ExportBMPANSI, '0');
if chkUnicode.Checked
then WriteString(SRegValue_IDEVKbd_ExportBMPUnicode, '1')
else WriteString(SRegValue_IDEVKbd_ExportBMPUnicode, '0');
WriteInteger(SRegValue_IDEVKbd_ExportBMPPixelWidth, StrToIntDef(editPixelWidth.Text, 720));
end;
finally
Free;
end;
ModalResult := mrOk;
end;
end.
|
unit uEvent;
interface
uses
Soap.InvokeRegistry, System.Types, Soap.XSBuiltIns, Soap.encddecd,
System.IOUtils, FMX.Dialogs, FMX.Forms, Classes, SysUtils, System.UITypes,
System.Variants,
FMX.Graphics, Data.DB, Data.DbxSqlite, Data.SqlExpr;
type
TEvent = class(TCollectionItem)
public
public
Id: string;
IdAction: string;
EvName: string;
Description: string;
end;
TEventList = class(TCollection)
public
procedure AddAction(Id, IdAction, EvName, Description: string);
Procedure SaveEvent(Item: TEvent);
Procedure UpdateOrInsert(Item: TEvent);
function ConnectToDb: TSQLConnection;
Procedure LoadActions;
Procedure SelectByEventId(EventId: string);
end;
implementation
{ TactionList }
{ TactionList }
procedure TEventList.AddAction(Id, IdAction, EvName, Description: string);
var
Item: TEvent;
begin
Item := TEvent(self.Add);
Item.Id := Id;
Item.IdAction := IdAction;
Item.EvName := EvName;
Item.Description := Description;
end;
function TEventList.ConnectToDb: TSQLConnection;
var
ASQLConnection: TSQLConnection;
Path: string;
begin
ASQLConnection := TSQLConnection.Create(nil);
ASQLConnection.ConnectionName := 'SQLITECONNECTION';
ASQLConnection.DriverName := 'Sqlite';
ASQLConnection.LoginPrompt := false;
ASQLConnection.Params.Values['Host'] := 'localhost';
ASQLConnection.Params.Values['FailIfMissing'] := 'False';
ASQLConnection.Params.Values['ColumnMetaDataSupported'] := 'False';
Createdir(IncludeTrailingPathDelimiter(Tpath.GetSharedDocumentsPath) +
IncludeTrailingPathDelimiter('ExampleDb'));
Path := IncludeTrailingPathDelimiter(Tpath.GetSharedDocumentsPath) +
IncludeTrailingPathDelimiter('ExampleDb') + 'ExampleDb.db';
ASQLConnection.Params.Values['Database'] := Path;
ASQLConnection.Execute('CREATE TABLE if not exists Events(' + 'Id TEXT,' +
'IdAction TEXT,' + 'EvName TEXT,' + 'Description TEXT' + ');', nil);
ASQLConnection.Open;
result := ASQLConnection;
end;
procedure TEventList.LoadActions;
var
ASQLConnection: TSQLConnection;
ResImage: TResourceStream;
RS: TDataset;
Item: TEvent;
begin
ASQLConnection := ConnectToDb;
try
ASQLConnection.Execute
('select Id,IdAction,EvName,Description from Events', nil, RS);
while not RS.Eof do
begin
Item := TEvent(self.Add);
Item.Id := RS.FieldByName('Id').Value;
Item.IdAction := RS.FieldByName('IdAction').Value;
Item.EvName := RS.FieldByName('EvName').Value;
Item.Description := RS.FieldByName('Description').Value;
RS.Next;
end;
finally
Freeandnil(ASQLConnection);
end;
end;
procedure TEventList.SaveEvent(Item: TEvent);
var
i: integer;
DB: TSQLConnection;
Params: TParams;
query: string;
begin
query := 'INSERT INTO Events (Id,IdAction,EvName,Description) VALUES (:Id,:IdAction,:EvName,:Description)';
DB := ConnectToDb;
try
for i := 0 to self.Count - 1 do
begin
Params := TParams.Create;
Params.CreateParam(TFieldType.ftString, 'id', ptInput);
Params.ParamByName('id').AsString := TEvent(self.Items[i]).Id;
Params.CreateParam(TFieldType.ftString, 'IdAction', ptInput);
Params.ParamByName('IdAction').AsString := TEvent(self.Items[i]).IdAction;
Params.CreateParam(TFieldType.ftString, 'EvName', ptInput);
Params.ParamByName('EvName').AsString := TEvent(self.Items[i]).EvName;
Params.CreateParam(TFieldType.ftString, 'Description', ptInput);
Params.ParamByName('Description').AsString := TEvent(self.Items[i])
.Description;
DB.Execute(query, Params);
Freeandnil(Params);
end;
finally
Freeandnil(DB);
end;
end;
procedure TEventList.SelectByEventId(EventId: string);
var
ASQLConnection: TSQLConnection;
RS: TDataset;
i: integer;
Item: TEvent;
begin
i := 0;
ASQLConnection := ConnectToDb;
try
ASQLConnection.Execute
('select id,IdAction,EvName,Description from Events WHERE IdAction = "' +
EventId + '"', nil, RS);
while not RS.Eof do
begin
Item := TEvent(self.Add);
Item.Id := RS.FieldByName('Id').Value;
Item.IdAction := RS.FieldByName('IdAction').Value;
Item.EvName := RS.FieldByName('Evname').Value;
Item.Description := RS.FieldByName('Description').Value;
RS.Next;
end;
finally
Freeandnil(ASQLConnection);
end;
Freeandnil(RS);
end;
procedure TEventList.UpdateOrInsert(Item: TEvent);
const
cInsertQuery =
'UPDATE Events SET `id` =:id,`IdAction` =:IdAction,`EvName` =:EvName, `Description`= :Description WHERE id="%s"';
var
Image: TBitmap;
query: String;
querity: TSQLQuery;
connect: TSQLConnection;
Guid: TGUID;
begin
connect := ConnectToDb;
querity := TSQLQuery.Create(nil);
try
querity.SQLConnection := connect;
querity.SQL.Text := 'select Id from Events where Id = "' + Item.Id + '"';
querity.Open;
if not querity.Eof then
begin
query := Format(cInsertQuery, [Item.Id]);
querity.Params.CreateParam(TFieldType.ftString, 'Id', ptInput);
querity.Params.ParamByName('Id').AsString := Item.Id;
querity.Params.CreateParam(TFieldType.ftString, 'IdAction', ptInput);
querity.Params.ParamByName('IdAction').AsString := Item.IdAction;
querity.Params.CreateParam(TFieldType.ftString, 'EvName', ptInput);
querity.Params.ParamByName('EvName').AsString := Item.EvName;
querity.Params.CreateParam(TFieldType.ftString, 'Description', ptInput);
querity.Params.ParamByName('Description').AsString := Item.Description;
querity.SQL.Text := query;
querity.ExecSQL();
end
else
begin
CreateGUID(Guid);
query := 'INSERT INTO Events (Id,IdAction,EvName,Description) VALUES (:Id,:IdAction,:EvName,:Description)';
querity.Params.CreateParam(TFieldType.ftString, 'Id', ptInput);
querity.Params.ParamByName('Id').AsString := Item.Id;
querity.Params.CreateParam(TFieldType.ftString, 'IdAction', ptInput);
querity.Params.ParamByName('IdAction').AsString := Item.IdAction;
querity.Params.CreateParam(TFieldType.ftString, 'EvName', ptInput);
querity.Params.ParamByName('EvName').AsString := Item.EvName;
querity.Params.CreateParam(TFieldType.ftString, 'Description', ptInput);
querity.Params.ParamByName('Description').AsString := Item.Description;
querity.SQL.Text := query;
querity.ExecSQL();
end;
finally
Freeandnil(querity);
end;
Freeandnil(connect);
end;
{ TactionList }
end.
|
unit GridViewForm;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, cxGraphics,
cxLookAndFeels, cxLookAndFeelPainters, Vcl.Menus, Vcl.StdCtrls, cxButtons,
cxClasses, cxPropertiesStore, GridFrame, Vcl.ActnList, dxSkinsCore,
dxSkinBlack, dxSkinBlue, dxSkinBlueprint, dxSkinCaramel, dxSkinCoffee,
dxSkinDarkRoom, dxSkinDarkSide, dxSkinDevExpressDarkStyle,
dxSkinDevExpressStyle, dxSkinFoggy, dxSkinGlassOceans, dxSkinHighContrast,
dxSkiniMaginary, dxSkinLilian, dxSkinLiquidSky, dxSkinLondonLiquidSky,
dxSkinMcSkin, dxSkinMetropolis, dxSkinMetropolisDark, dxSkinMoneyTwins,
dxSkinOffice2007Black, dxSkinOffice2007Blue, dxSkinOffice2007Green,
dxSkinOffice2007Pink, dxSkinOffice2007Silver, dxSkinOffice2010Black,
dxSkinOffice2010Blue, dxSkinOffice2010Silver, dxSkinOffice2013DarkGray,
dxSkinOffice2013LightGray, dxSkinOffice2013White, dxSkinOffice2016Colorful,
dxSkinOffice2016Dark, dxSkinPumpkin, dxSkinSeven, dxSkinSevenClassic,
dxSkinSharp, dxSkinSharpPlus, dxSkinSilver, dxSkinSpringTime, dxSkinStardust,
dxSkinSummer2008, dxSkinTheAsphaltWorld, dxSkinsDefaultPainters,
dxSkinValentine, dxSkinVisualStudio2013Blue, dxSkinVisualStudio2013Dark,
dxSkinVisualStudio2013Light, dxSkinVS2010, dxSkinWhiteprint,
dxSkinXmas2008Blue, RootForm;
type
TMyMsgDlgBtn = (mmbOK, mmbCancel, mmbContinue);
TMyMsgDlgButtons = set of TMyMsgDlgBtn;
TfrmGridView = class(TfrmRoot)
pnlMain: TPanel;
cxbtnOK: TcxButton;
cxbtnCancel: TcxButton;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
FGridView: TfrmGrid;
FGridViewClass: TGridViewClass;
FOKAction: TAction;
procedure SetGridViewClass(const Value: TGridViewClass);
{ Private declarations }
public
constructor Create(AOwner: TComponent; const ACaption: string; MyMsgDlgButtons:
TMyMsgDlgButtons; AWidth: Cardinal = 0; AHeight: Cardinal = 0); reintroduce;
procedure AfterConstruction; override;
property GridView: TfrmGrid read FGridView;
property GridViewClass: TGridViewClass read FGridViewClass
write SetGridViewClass;
property OKAction: TAction read FOKAction write FOKAction;
{ Public declarations }
end;
implementation
{$R *.dfm}
constructor TfrmGridView.Create(AOwner: TComponent; const ACaption: string;
MyMsgDlgButtons: TMyMsgDlgButtons; AWidth: Cardinal = 0; AHeight: Cardinal
= 0);
begin
inherited Create(AOwner);
OKAction := nil;
Caption := ACaption;
// Если кнопка отмена нам не нужна
if not (mmbCancel in MyMsgDlgButtons) then
begin
cxbtnOk.Left := cxbtnCancel.Left;
cxbtnCancel.Visible := False;
end;
if mmbContinue in MyMsgDlgButtons then
begin
cxbtnOK.Caption := 'Продолжить'
end;
if AWidth > 0 then
Width := AWidth;
if AHeight > 0 then
Height := AHeight;
end;
procedure TfrmGridView.AfterConstruction;
begin
inherited;
// cxpsViewForm.RestoreFrom;
end;
procedure TfrmGridView.FormClose(Sender: TObject; var Action: TCloseAction);
begin
// cxpsViewForm.StoreTo();
if (ModalResult = mrOK) and (OKAction <> nil) and (OKAction.Enabled) then
try
// Пытаемся сохранить
OKAction.Execute;
except
Action := caNone;
raise;
end;
end;
procedure TfrmGridView.SetGridViewClass(const Value: TGridViewClass);
begin
if FGridViewClass = Value then
Exit;
FGridViewClass := Value;
FreeAndNil(FGridView);
FGridView := FGridViewClass.Create(nil);
FGridView.Place(pnlMain);
end;
end.
|
(* HashChaining: SWa, modified by MM, 2020-03-11 *)
(* ------------- *)
(* Fun with hashing and separate chaining. *)
(* ========================================================================= *)
UNIT HashChaining;
INTERFACE
CONST
MAX = 211;
TYPE
NodePtr = ^Node;
Node = RECORD
val: STRING;
count: INTEGER;
next: NodePtr;
END; (* Node *)
ListPtr = NodePtr;
HashTable = ARRAY [0 .. MAX - 1] OF ListPtr;
PROCEDURE Insert(VAR table: HashTable; val: STRING);
PROCEDURE InitHashTable(VAR table: HashTable);
FUNCTION Contains(table: HashTable; val: STRING): NodePtr;
FUNCTION GetHighestCount(table: HashTable): NodePtr;
IMPLEMENTATION
FUNCTION NewNode(val: STRING; next: NodePtr): NodePtr;
VAR
n: NodePtr;
BEGIN (* NewNode *)
New(n);
n^.val := val;
n^.count := 1;
n^.next := next;
NewNode := n;
END; (* NewNode *)
PROCEDURE InitHashTable(VAR table: HashTable);
VAR
i: INTEGER;
BEGIN (* InitHashTable *)
FOR i := Low(table) TO High(table) DO BEGIN
table[i] := NIL;
END; (* FOR *)
END; (* InitHashTable *)
FUNCTION GetHashCode(val: STRING): INTEGER;
BEGIN (* GetHashCode *)
IF (Length(val) = 0) THEN BEGIN
GetHashCode := 0;
END ELSE IF (Length(val) = 1) THEN BEGIN
GetHashCode := (Ord(val[1]) * 7 + 1) * 17;
END ELSE BEGIN
GetHashCode := (Ord(val[1]) * 7 + Ord(val[2]) + Length(val)) * 17;
END; (* IF *)
END; (* GetHashCode *)
PROCEDURE Insert(VAR table: HashTable; val: STRING);
VAR
hashcode: INTEGER;
n: NodePtr;
BEGIN (* Insert *)
hashcode := GetHashCode(val);
hashcode := hashcode MOD MAX;
// prepend new element at index hashcode if not already in list
n := Contains(table, val);
if n <> NIL THEN
Inc(n^.count)
else
table[hashcode] := NewNode(val, table[hashcode]);
END; (* Insert *)
FUNCTION Contains(table: HashTable; val: STRING): NodePtr;
VAR
hashcode: INTEGER;
n: NodePtr;
BEGIN (* Contains *)
hashcode := GetHashCode(val);
hashcode := hashcode MOD MAX;
n := table[hashcode];
WHILE ((n <> NIL) AND (n^.val <> val)) DO BEGIN
n := n^.next;
END; (* WHILE *)
Contains := n;
END; (* Contains *)
FUNCTION GetHighestCount(table: HashTable): NodePtr;
var n: NodePtr;
highest: NodePtr;
i: INTEGER;
BEGIN (* GetHighestCount *)
highest := table[0];
FOR i := 0 TO (MAX - 1) DO BEGIN
n := table[i];
WHILE n <> NIL DO BEGIN
IF highest = NIL THEN
highest := n
ELSE BEGIN
IF n^.count > highest^.count THEN
highest := n;
END; (* IF *)
n := n^.next;
END; (* WHILE *)
END; (* FOR *)
GetHighestCount := highest;
END; (* GetHighestCount *)
BEGIN (* HashChaining *)
END. (* HashChaining *)
|
unit BanksSearch;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BaseSearch, Data.DB, Vcl.StdCtrls,
Vcl.Grids, Vcl.DBGrids, RzDBGrid, Vcl.Mask, RzEdit, RzLabel,
Vcl.Imaging.pngimage, Vcl.ExtCtrls, RzPanel, RzButton;
type
TfrmBankSearch = class(TfrmBaseSearch)
private
{ Private declarations }
public
{ Public declarations }
protected
{ Public declarations }
procedure SearchList; override;
procedure SetReturn; override;
procedure Add; override;
procedure Cancel; override;
end;
var
frmBankSearch: TfrmBankSearch;
implementation
{$R *.dfm}
uses
AuxData, Bank;
procedure TfrmBankSearch.SearchList;
var
filter: string;
begin
inherited;
if Trim(edSearchKey.Text) <> '' then
filter := 'bank_name like ''*' + edSearchKey.Text + '*'''
else
filter := '';
grSearch.DataSource.DataSet.Filter := filter;
end;
procedure TfrmBankSearch.SetReturn;
begin
with grSearch.DataSource.DataSet do
begin
bnk.Id := FieldByName('bank_id').AsString;
bnk.BankName := FieldByName('bank_name').AsString;
bnk.BankCode := FieldByName('bank_code').AsString;
bnk.Branch := FieldByName('branch').AsString;
end;
end;
procedure TfrmBankSearch.Add;
begin
end;
procedure TfrmBankSearch.Cancel;
begin
bnk.Destroy;
end;
end.
|
unit CachedUp;
{ This demo uses the IBLOCAL alias which is setup by the install program
when you install Delphi and you have installed Local Interbase.
See the file ABOUT.TXT for a description of this demo. }
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
DBTables, DB, Grids, DBGrids, TypInfo, StdCtrls, Menus, ExtCtrls, DBCtrls,
Buttons;
type
TCacheDemoForm = class(TForm)
DBGrid1: TDBGrid;
MainMenu1: TMainMenu;
miAbout: TMenuItem;
DBNavigator1: TDBNavigator;
GroupBox1: TGroupBox;
UnmodifiedCB: TCheckBox;
ModifiedCB: TCheckBox;
InsertedCB: TCheckBox;
DeletedCB: TCheckBox;
Panel1: TPanel;
CachedUpdates: TCheckBox;
UseUpdateSQL: TCheckBox;
Panel2: TPanel;
ApplyUpdatesBtn: TButton;
CancelUpdatesBtn: TButton;
RevertRecordBtn: TButton;
ReExecuteButton: TButton;
procedure ApplyUpdatesBtnClick(Sender: TObject);
procedure ToggleUpdateMode(Sender: TObject);
procedure miAboutClick(Sender: TObject);
procedure CancelUpdatesBtnClick(Sender: TObject);
procedure RevertRecordBtnClick(Sender: TObject);
procedure UpdateRecordsToShow(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure ReExecuteButtonClick(Sender: TObject);
procedure UseUpdateSQLClick(Sender: TObject);
private
{ Private declarations }
FDataSet: TDBDataSet;
procedure SetControlStates(Enabled: Boolean);
public
{ Public declarations }
end;
var
CacheDemoForm: TCacheDemoForm;
implementation
{$R *.dfm}
uses
About, ErrForm, DataMod, Variants;
{ This method enables and disables controls when cached updates are
turned on and off }
procedure TCacheDemoForm.SetControlStates(Enabled: Boolean);
begin
ApplyUpdatesBtn.Enabled := Enabled;
CancelUpdatesBtn.Enabled := Enabled;
RevertRecordBtn.Enabled := Enabled;
UnmodifiedCB.Enabled := Enabled;
ModifiedCB.Enabled := Enabled;
InsertedCB.Enabled := Enabled;
DeletedCB.Enabled := Enabled;
UseUpdateSQL.Enabled := Enabled;
end;
procedure TCacheDemoForm.FormCreate(Sender: TObject);
begin
FDataSet := CacheData.CacheDS.DataSet as TDBDataSet;
FDataSet.CachedUpdates := CachedUpdates.Checked;
SetControlStates(FDataSet.CachedUpdates);
FDataSet.Open;
end;
procedure TCacheDemoForm.ToggleUpdateMode(Sender: TObject);
begin
{ Toggle the state of the CachedUpdates property }
FDataSet.CachedUpdates := not FDataSet.CachedUpdates;
{ Enable/Disable Controls }
SetControlStates(FDataSet.CachedUpdates);
end;
procedure TCacheDemoForm.miAboutClick(Sender: TObject);
begin
ShowAboutDialog;
end;
procedure TCacheDemoForm.ApplyUpdatesBtnClick(Sender: TObject);
begin
FDataSet.Database.ApplyUpdates([FDataSet]);
end;
procedure TCacheDemoForm.CancelUpdatesBtnClick(Sender: TObject);
begin
FDataSet.CancelUpdates;
end;
procedure TCacheDemoForm.RevertRecordBtnClick(Sender: TObject);
begin
FDataSet.RevertRecord;
end;
{ This event is triggered when the user checks or unchecks one
of the "Show Records" check boxes. It translates the states
of the checkboxes into a set value which is required by the
UpdateRecordTypes property of TDataSet. The UpdateRecordTypes
property controls what types of records are included in the
dataset. The default is to show only unmodified modified
and inserted records. To "undelete" a record, you would
check the Deleted checkbox, then position the grid to the
row you want to undelete and finally click the Revert Record
Button }
procedure TCacheDemoForm.UpdateRecordsToShow(Sender: TObject);
var
UpdRecTypes : TUpdateRecordTypes;
begin
UpdRecTypes := [];
if UnModifiedCB.Checked then
Include(UpdRecTypes, rtUnModified);
if ModifiedCB.Checked then
Include(UpdRecTypes, rtModified);
if InsertedCB.Checked then
Include(UpdRecTypes, rtInserted);
if DeletedCB.Checked then
Include(UpdRecTypes, rtDeleted);
FDataSet.UpdateRecordTypes := UpdRecTypes;
end;
procedure TCacheDemoForm.ReExecuteButtonClick(Sender: TObject);
begin
FDataSet.Close;
FDataSet.Open;
end;
procedure TCacheDemoForm.UseUpdateSQLClick(Sender: TObject);
begin
FDataSet.Close;
if UseUpdateSQL.Checked then
FDataSet.UpdateObject := CacheData.UpdateSQL
else
FDataSet.UpdateObject := nil;
FDataSet.Open;
end;
end.
|
PROGRAM Sorting;
var numComp, numAssign: longint;
type IntArray = array [1..100] of integer;
FUNCTION LT(a, b: integer): boolean;
BEGIN (* LT *)
Inc(numComp);
LT := a < b;
END; (* LT *)
PROCEDURE Swap(var a, b: integer);
var x: integer;
BEGIN (* Swap *)
x := a;
a := b;
b := x;
Inc(numAssign, 3);
END; (* Swap *)
PROCEDURE MergeSort(var arr: IntArray; lft, rgt: integer);
var i, j, k: integer;
m: IntArray;
BEGIN (* MergeSort *)
if lft < rgt then begin
i := lft;
j := lft + (rgt - lft) DIV 2;
for i := lft to rgt do begin
m[i] := arr[i];
end; (* FOR *)
MergeSort(m, lft, (rgt - lft)DIV 2 + lft - 1);
MergeSort(m, (rgt - lft)DIV 2 + lft, rgt);
i := lft;
j := lft + (rgt - lft)Div 2;
k := lft;
while k <= rgt do begin
if (j > rgt) OR LT(m[i], m[j]) then begin
if LT(m[i], m[j]) then begin
arr[k] := m[i];
Inc(i);
Inc(numAssign);
end else begin
arr[k] := m[j];
Inc(j);
Inc(numAssign);
end; (* IF *)
end; (* IF *)
Inc(k);
end; (* WHILE *)
end; (* IF *)
END; (* MergeSort *)
PROCEDURE CombSort(var arr: IntArray; lft, rgt: integer);
var h, i: integer;
isChanged: boolean;
BEGIN (* CombSort *)
h := (rgt - lft) DIV 2;
while h > 0 do begin
isChanged := TRUE;
while isChanged do begin
isChanged := FALSE;
for i := lft to rgt - h do begin
if LT(arr[i + h], arr[i]) then begin
Swap(arr[i], arr[i + h]);
isChanged := TRUE;
end; (* IF *)
end; (* FOR *)
end; (* WHILE *)
h := h * 10 DIV 13;
end; (* WHILE *)
END; (* CombSort *)
PROCEDURE SelectionSort(VAR arr: IntArray; lft, rgt: integer);
var i, j: integer;
minIndex: integer;
BEGIN (* SelectionSort *)
for i := lft to rgt - 1 do begin
minIndex := i;
for j := i + 1 to rgt do begin
if LT(arr[j], arr[minIndex]) then
minIndex := j;
end; (* FOR *)
if (i <> minIndex) then
Swap(arr[i], arr[minIndex]);
end; (* FOR *)
END; (* SelectionSort *)
PROCEDURE ShellSort(var arr: IntArray; lft, rgt: integer);
var i, j, h, t: integer;
BEGIN (* ShellSort *)
h := (rgt - lft) DIV 2;
while h > 0 do begin
for i := lft + h to rgt do begin
t := arr[i]; Inc(numAssign);
j := i - h;
while (j >= lft) AND LT(t, arr[j]) do begin
arr[j + h] := arr[j];
j := j - h; Inc(numAssign);
end; (* while *)
arr[j + h] := t;
end; (* for *)
h := h DIV 2;
end; (* while *)
END; (* ShellSort *)
PROCEDURE QuickSort(var arr: IntArray; lft, rgt: integer);
var p, i, j: integer;
BEGIN (* QuickSort *)
if lft < rgt then begin
p := arr[lft+(rgt-lft+1) DIV 2];
i := lft;
j := rgt;
repeat
while LT(arr[i], p) do Inc(i);
while LT(p, arr[j]) do Dec(j);
if i <= j then begin
if i <> j then
Swap(arr[i], arr[j]);
Inc(i);
Dec(j);
end; (* IF *)
until j < i;
QuickSort(arr, lft, j);
QuickSort(arr, i, rgt);
end; (* IF *)
END; (* QuickSort *)
PROCEDURE BubbleSort(VAR arr: IntArray; left, right: INTEGER);
VAR i: INTEGER;
isChanged: BOOLEAN;
BEGIN (* BubbleSort *)
isChanged := TRUE;
WHILE isChanged DO BEGIN
isChanged := FALSE;
FOR i := left TO right - 1 DO
IF LT(arr[i+1], arr[i]) THEN BEGIN
Swap(arr[i], arr[i+1]);
isCHanged := TRUE;
END; (* IF *)
END; (* WHILE *)
END; (* BubbleSort *)
PROCEDURE InsertionSort(VAR arr: IntArray; left, right: INTEGER);
VAR i, j, t: INTEGER;
BEGIN (* InsertionSort *)
FOR i := left + 1 TO right DO BEGIN
t := arr[i];
Inc(numAssign);
j := i - 1;
WHILE (j >= left) AND (LT(t, arr[j])) DO BEGIN
arr[j+1] := arr[j];
Inc(numAssign);
Dec(j);
END; (* WHILE *)
IF(j + 1) <> i THEN BEGIN
arr[j+1] := t;
Inc(numAssign);
END; (* IF *)
END; (* FOR *)
END; (* InsertionSort *)
var arr: IntArray;
i, j: integer;
BEGIN (* Sorting *)
numAssign := 0;
numComp := 0;
for i := 1 to 100 do begin
arr[i] := Random(100);
end;
for j := 1 to 100 do begin
Write(arr[j], ', ');
end;
WriteLn();
MergeSort(arr, 1, 100);
for j := 1 to 100 do begin
Write(arr[j], ', ');
end;
WriteLn();
WriteLn(numComp);
WriteLn(numAssign);
END. (* Sorting *) |
{$A+,B-,D+,E-,F-,G+,I+,L+,N+,O-,P-,Q-,R-,S-,T-,V+,X+,Y+}
{$M 1024,0,0}
{
by Behdad Esfahbod
Algorithmic Problems Book
September '1999
Problem 40 O(N3) Dynamic Method
}
program
WeightBoundedMinimumDistance;
const
MaxN = 100;
var
N, E, U, V, W : Integer;
G, D : array [0 .. MaxN, 1 .. MaxN] of Word;
P : array [0 .. MaxN, 1 .. MaxN] of Byte;
I, J, K, L : Integer;
F : Text;
procedure Solve;
begin
FillChar(D, SizeOf(D), 120);
D[0, V] := 0;
for K := 1 to N - 1 do
for I := 1 to N do
for J := 1 to N do
if (G[J, I] > 0) and (D[K, I] > D[K - 1, J] + G[J, I]) then
begin
D[K, I] := D[K - 1, J] + G[J, I];
P[K, I] := J;
end;
end;
procedure ReadInput;
begin
Assign(F, 'input.txt');
Reset(F);
Readln(F, N, E, U, V, W);
for I := 1 to E do
begin
Readln(F, J, K, L);
G[J, K] := L; G[K, J] := L;
end;
Close(F);
end;
procedure WriteOutput;
begin
Assign(F, 'output.txt');
ReWrite(F);
J := U;
for L := 1 to N do
if D[L, U] <= W then Break;
if L = N then
Writeln(F, 'No Solution')
else
for K := L downto 0 do
begin
Write(F, J, ' ');
J := P[K, J];
end;
Close(F);
end;
begin
ReadInput;
Solve;
WriteOutput;
end.
|
unit MediaProcessing.Drawer.RGB;
interface
uses SysUtils,Windows,Classes, MediaProcessing.Definitions,MediaProcessing.Global,Graphics;
type
TMediaProcessor_Drawer_Rgb=class (TMediaProcessor,IMediaProcessor_Drawer_Rgb)
private
FTextFont : TFontData;
protected
procedure SaveCustomProperties(const aWriter: IPropertiesWriter); override;
procedure LoadCustomProperties(const aReader: IPropertiesReader); override;
class function MetaInfo:TMediaProcessorInfo; override;
public
constructor Create; override;
destructor Destroy; override;
function HasCustomProperties: boolean; override;
procedure ShowCustomProperiesDialog;override;
end;
implementation
uses Controls,UITypes, uBaseClasses,MediaProcessing.Drawer.RGB.SettingsDialog;
type
PFontStylesBase = ^TFontStylesBase;
{ TMediaProcessor_Drawer_Rgb }
constructor TMediaProcessor_Drawer_Rgb.Create;
begin
inherited;
end;
destructor TMediaProcessor_Drawer_Rgb.Destroy;
begin
inherited;
end;
function TMediaProcessor_Drawer_Rgb.HasCustomProperties: boolean;
begin
result:=true;
end;
class function TMediaProcessor_Drawer_Rgb.MetaInfo: TMediaProcessorInfo;
begin
result.Clear;
result.TypeID:=IMediaProcessor_Drawer_Rgb;
result.Name:='Рисование';
result.Description:='Выполняет рисование различных примитивов повех видео';
result.SetInputStreamType(stRGB);
result.OutputStreamType:=stRGB;
result.ConsumingLevel:=0;
end;
procedure TMediaProcessor_Drawer_Rgb.LoadCustomProperties(const aReader: IPropertiesReader);
var
t: Integer;
begin
inherited;
ZeroMemory(@FTextFont,sizeof(FTextFont));
FTextFont.Height:=aReader.ReadInteger('TextFont.Font.Size', 10);
t:=aReader.ReadInteger('TextFont.Font.Style', 0);
FTextFont.Style:=PFontStylesBase(@t)^;
FTextFont.Name:=AnsiString(aReader.ReadString('TextFont.Font.Name', 'MS Sans Serif'));
FTextFont.Charset:=DEFAULT_CHARSET;
end;
procedure TMediaProcessor_Drawer_Rgb.SaveCustomProperties(const aWriter: IPropertiesWriter);
var
b: byte;
begin
inherited;
aWriter.WriteInteger('TextFont.Font.Size', FTextFont.Height);
b:=PByte(@FTextFont.Style)^;
aWriter.WriteInteger('TextFont.Font.Style', b);
aWriter.WriteString('TextFont.Font.Name', string(FTextFont.Name));
end;
procedure TMediaProcessor_Drawer_Rgb.ShowCustomProperiesDialog;
var
aDialog: TfmMediaProcessingSettingsRgb;
begin
aDialog:=TfmMediaProcessingSettingsRgb.Create(nil);
try
if aDialog.ShowModal=mrOK then
begin
end;
finally
aDialog.Free;
end;
end;
//initialization
// MediaProceccorFactory.RegisterMediaProcessor(TMediaProcessor_Drawer_Rgb);
end.
|
unit ActiveClientsSearch;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BaseSearch, Data.DB, RzButton,
Vcl.Grids, Vcl.DBGrids, RzDBGrid, Vcl.StdCtrls, Vcl.Mask, RzEdit, RzLabel,
Vcl.Imaging.pngimage, Vcl.ExtCtrls, RzPanel, ADODB;
type
TfrmActiveClientsSearch = class(TfrmBaseSearch)
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
procedure SearchList; override;
procedure SetReturn; override;
procedure Add; override;
procedure Cancel; override;
end;
var
frmActiveClientsSearch: TfrmActiveClientsSearch;
implementation
{$R *.dfm}
uses
ActiveClient, AppData;
procedure TfrmActiveClientsSearch.SearchList;
var
filter: string;
begin
if Trim(edSearchKey.Text) <> '' then
filter := 'name like ''*' + edSearchKey.Text + '*'''
else
filter := '';
grSearch.DataSource.DataSet.Filter := filter;
end;
procedure TfrmActiveClientsSearch.SetReturn;
begin
with grSearch.DataSource.DataSet do
begin
activeCln := TActiveClient.Create;
activeCln.Id := FieldByName('entity_id').AsString;
activeCln.Name := FieldByName('name').AsString;
end;
end;
procedure TfrmActiveClientsSearch.Add;
begin
end;
procedure TfrmActiveClientsSearch.Cancel;
begin
end;
procedure TfrmActiveClientsSearch.FormCreate(Sender: TObject);
begin
// set parameters
(grSearch.DataSource.DataSet as TADODataSet).Parameters.ParamByName('@filter_type').Value := 1;
(grSearch.DataSource.DataSet as TADODataSet).Parameters.ParamByName('@non_clients').Value := 0;
inherited;
end;
end.
|
{*******************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ }
{ Copyright (c) 1995-2002 Borland Software Corporation }
{ }
{*******************************************************}
unit CheckLst;
{$T-,H+,X+}
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls,
StdCtrls;
type
TCheckListBox = class(TCustomListBox)
private
FAllowGrayed: Boolean;
FFlat: Boolean;
FStandardItemHeight: Integer;
FOnClickCheck: TNotifyEvent;
FSaveStates: TList;
FHeaderColor: TColor;
FHeaderBackgroundColor: TColor;
procedure ResetItemHeight;
procedure DrawCheck(R: TRect; AState: TCheckBoxState; AEnabled: Boolean);
procedure SetChecked(Index: Integer; AChecked: Boolean);
function GetChecked(Index: Integer): Boolean;
procedure SetState(Index: Integer; AState: TCheckBoxState);
function GetState(Index: Integer): TCheckBoxState;
procedure ToggleClickCheck(Index: Integer);
procedure InvalidateCheck(Index: Integer);
function CreateWrapper(Index: Integer): TObject;
function ExtractWrapper(Index: Integer): TObject;
function GetWrapper(Index: Integer): TObject;
function HaveWrapper(Index: Integer): Boolean;
procedure SetFlat(Value: Boolean);
procedure CNDrawItem(var Message: TWMDrawItem); message CN_DRAWITEM;
procedure CMFontChanged(var Message: TMessage); message CM_FONTCHANGED;
procedure WMDestroy(var Msg : TWMDestroy);message WM_DESTROY;
function GetItemEnabled(Index: Integer): Boolean;
procedure SetItemEnabled(Index: Integer; const Value: Boolean);
function GetHeader(Index: Integer): Boolean;
procedure SetHeader(Index: Integer; const Value: Boolean);
procedure SetHeaderBackgroundColor(const Value: TColor);
procedure SetHeaderColor(const Value: TColor);
protected
procedure DrawItem(Index: Integer; Rect: TRect;
State: TOwnerDrawState); override;
function InternalGetItemData(Index: Integer): Longint; override;
procedure InternalSetItemData(Index: Integer; AData: Longint); override;
procedure SetItemData(Index: Integer; AData: LongInt); override;
function GetItemData(Index: Integer): LongInt; override;
procedure KeyPress(var Key: Char); override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer); override;
procedure ResetContent; override;
procedure DeleteString(Index: Integer); override;
procedure ClickCheck; dynamic;
procedure CreateParams(var Params: TCreateParams); override;
procedure CreateWnd; override;
procedure DestroyWnd; override;
function GetCheckWidth: Integer;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property Checked[Index: Integer]: Boolean read GetChecked write SetChecked;
property ItemEnabled[Index: Integer]: Boolean read GetItemEnabled write SetItemEnabled;
property State[Index: Integer]: TCheckBoxState read GetState write SetState;
property Header[Index: Integer]: Boolean read GetHeader write SetHeader;
published
property OnClickCheck: TNotifyEvent read FOnClickCheck write FOnClickCheck;
property Align;
property AllowGrayed: Boolean read FAllowGrayed write FAllowGrayed default False;
property Anchors;
property AutoComplete;
property BevelEdges;
property BevelInner;
property BevelOuter;
property BevelKind;
property BevelWidth;
property BiDiMode;
property BorderStyle;
property Color;
property Columns;
property Constraints;
property Ctl3D;
property DragCursor;
property DragKind;
property DragMode;
property Enabled;
property Flat: Boolean read FFlat write SetFlat default True;
//property ExtendedSelect;
property Font;
property HeaderColor: TColor read FHeaderColor write SetHeaderColor default clInfoText;
property HeaderBackgroundColor: TColor read FHeaderBackgroundColor write SetHeaderBackgroundColor default clInfoBk;
property ImeMode;
property ImeName;
property IntegralHeight;
property ItemHeight;
property Items;
//property MultiSelect;
property ParentBiDiMode;
property ParentColor;
property ParentCtl3D;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property Sorted;
property Style;
property TabOrder;
property TabStop;
property TabWidth;
property Visible;
property OnClick;
property OnContextPopup;
property OnData;
property OnDataFind;
property OnDataObject;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnDrawItem;
property OnEndDock;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnMeasureItem;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnStartDock;
property OnStartDrag;
end;
implementation
uses Consts, RTLConsts, Themes;
type
TCheckListBoxDataWrapper = class
private
FData: LongInt;
FState: TCheckBoxState;
FDisabled: Boolean;
FHeader: Boolean;
procedure SetChecked(Check: Boolean);
function GetChecked: Boolean;
public
class function GetDefaultState: TCheckBoxState;
property Checked: Boolean read GetChecked write SetChecked;
property State: TCheckBoxState read FState write FState;
property Disabled: Boolean read FDisabled write FDisabled;
property Header: Boolean read FHeader write FHeader;
end;
var
FCheckWidth, FCheckHeight: Integer;
procedure GetCheckSize;
begin
with TBitmap.Create do
try
Handle := LoadBitmap(0, PChar(OBM_CHECKBOXES));
FCheckWidth := Width div 4;
FCheckHeight := Height div 3;
finally
Free;
end;
end;
function MakeSaveState(State: TCheckBoxState; Disabled: Boolean): TObject;
begin
Result := TObject((Byte(State) shl 16) or Byte(Disabled));
end;
function GetSaveState(AObject: TObject): TCheckBoxState;
begin
Result := TCheckBoxState(Integer(AObject) shr 16);
end;
function GetSaveDisabled(AObject: TObject): Boolean;
begin
Result := Boolean(Integer(AObject) and $FF);
end;
{ TCheckListBoxDataWrapper }
procedure TCheckListBoxDataWrapper.SetChecked(Check: Boolean);
begin
if Check then FState := cbChecked else FState := cbUnchecked;
end;
function TCheckListBoxDataWrapper.GetChecked: Boolean;
begin
Result := FState = cbChecked;
end;
class function TCheckListBoxDataWrapper.GetDefaultState: TCheckBoxState;
begin
Result := cbUnchecked;
end;
{ TCheckListBox }
constructor TCheckListBox.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FFlat := True;
FHeaderColor := clInfoText;
FHeaderBackgroundColor := clInfoBk;
end;
destructor TCheckListBox.Destroy;
begin
FSaveStates.Free;
inherited;
end;
procedure TCheckListBox.CreateWnd;
var
I: Integer;
Wrapper: TCheckListBoxDataWrapper;
SaveState: TObject;
begin
inherited CreateWnd;
if FSaveStates <> nil then
begin
for I := 0 to FSaveStates.Count - 1 do
begin
Wrapper := TCheckListBoxDataWrapper(GetWrapper(I));
SaveState := FSaveStates[I];
Wrapper.FState := GetSaveState(SaveState);
Wrapper.FDisabled := GetSaveDisabled(SaveState);
end;
FreeAndNil(FSaveStates);
end;
ResetItemHeight;
end;
procedure TCheckListBox.DestroyWnd;
var
I: Integer;
begin
if Items.Count > 0 then
begin
FSaveStates := TList.Create;
for I := 0 to Items.Count - 1 do
FSaveStates.Add(MakeSaveState(State[I], not ItemEnabled[I]));
end;
inherited DestroyWnd;
end;
procedure TCheckListBox.CreateParams(var Params: TCreateParams);
begin
inherited;
with Params do
if Style and (LBS_OWNERDRAWFIXED or LBS_OWNERDRAWVARIABLE) = 0 then
Style := Style or LBS_OWNERDRAWFIXED;
end;
function TCheckListBox.GetCheckWidth: Integer;
begin
Result := FCheckWidth + 2;
end;
procedure TCheckListBox.CMFontChanged(var Message: TMessage);
begin
inherited;
ResetItemHeight;
end;
procedure TCheckListBox.ResetItemHeight;
begin
if HandleAllocated and (Style = lbStandard) then
begin
Canvas.Font := Font;
FStandardItemHeight := Canvas.TextHeight('Wg');
Perform(LB_SETITEMHEIGHT, 0, FStandardItemHeight);
end;
end;
procedure TCheckListBox.DrawItem(Index: Integer; Rect: TRect;
State: TOwnerDrawState);
var
R: TRect;
SaveEvent: TDrawItemEvent;
ACheckWidth: Integer;
Enable: Boolean;
begin
ACheckWidth := GetCheckWidth;
if Index < Items.Count then
begin
R := Rect;
Enable := Self.Enabled and GetItemEnabled(Index);
if not Header[Index] then
begin
if not UseRightToLeftAlignment then
begin
R.Right := Rect.Left;
R.Left := R.Right - ACheckWidth;
end
else
begin
R.Left := Rect.Right;
R.Right := R.Left + ACheckWidth;
end;
DrawCheck(R, GetState(Index), Enable);
end
else
begin
Canvas.Font.Color := HeaderColor;
Canvas.Brush.Color := HeaderBackgroundColor;
end;
if not Enable then
Canvas.Font.Color := clGrayText;
end;
if (Style = lbStandard) and Assigned(OnDrawItem) then
begin
{ Force lbStandard list to ignore OnDrawItem event. }
SaveEvent := OnDrawItem;
OnDrawItem := nil;
try
inherited;
finally
OnDrawItem := SaveEvent;
end;
end
else
inherited;
end;
procedure TCheckListBox.CNDrawItem(var Message: TWMDrawItem);
begin
if Items.Count = 0 then exit;
with Message.DrawItemStruct^ do
if not Header[itemID] then
if not UseRightToLeftAlignment then
rcItem.Left := rcItem.Left + GetCheckWidth
else
rcItem.Right := rcItem.Right - GetCheckWidth;
inherited;
end;
procedure TCheckListBox.DrawCheck(R: TRect; AState: TCheckBoxState; AEnabled: Boolean);
var
DrawState: Integer;
DrawRect: TRect;
OldBrushColor: TColor;
OldBrushStyle: TBrushStyle;
OldPenColor: TColor;
Rgn, SaveRgn: HRgn;
ElementDetails: TThemedElementDetails;
begin
SaveRgn := 0;
DrawRect.Left := R.Left + (R.Right - R.Left - FCheckWidth) div 2;
DrawRect.Top := R.Top + (R.Bottom - R.Top - FCheckHeight) div 2;
DrawRect.Right := DrawRect.Left + FCheckWidth;
DrawRect.Bottom := DrawRect.Top + FCheckHeight;
with Canvas do
begin
if Flat then
begin
{ Remember current clipping region }
SaveRgn := CreateRectRgn(0,0,0,0);
GetClipRgn(Handle, SaveRgn);
{ Clip 3d-style checkbox to prevent flicker }
with DrawRect do
Rgn := CreateRectRgn(Left + 2, Top + 2, Right - 2, Bottom - 2);
SelectClipRgn(Handle, Rgn);
DeleteObject(Rgn);
end;
if ThemeServices.ThemesEnabled then
begin
case AState of
cbChecked:
if AEnabled then
ElementDetails := ThemeServices.GetElementDetails(tbCheckBoxCheckedNormal)
else
ElementDetails := ThemeServices.GetElementDetails(tbCheckBoxCheckedDisabled);
cbUnchecked:
if AEnabled then
ElementDetails := ThemeServices.GetElementDetails(tbCheckBoxUncheckedNormal)
else
ElementDetails := ThemeServices.GetElementDetails(tbCheckBoxUncheckedDisabled)
else // cbGrayed
if AEnabled then
ElementDetails := ThemeServices.GetElementDetails(tbCheckBoxMixedNormal)
else
ElementDetails := ThemeServices.GetElementDetails(tbCheckBoxMixedDisabled);
end;
ThemeServices.DrawElement(Handle, ElementDetails, R);
end
else
begin
case AState of
cbChecked:
DrawState := DFCS_BUTTONCHECK or DFCS_CHECKED;
cbUnchecked:
DrawState := DFCS_BUTTONCHECK;
else // cbGrayed
DrawState := DFCS_BUTTON3STATE or DFCS_CHECKED;
end;
if not AEnabled then
DrawState := DrawState or DFCS_INACTIVE;
DrawFrameControl(Handle, DrawRect, DFC_BUTTON, DrawState);
end;
if Flat then
begin
SelectClipRgn(Handle, SaveRgn);
DeleteObject(SaveRgn);
{ Draw flat rectangle in-place of clipped 3d checkbox above }
OldBrushStyle := Brush.Style;
OldBrushColor := Brush.Color;
OldPenColor := Pen.Color;
Brush.Style := bsClear;
Pen.Color := clBtnShadow;
with DrawRect do
Rectangle(Left + 1, Top + 1, Right - 1, Bottom - 1);
Brush.Style := OldBrushStyle;
Brush.Color := OldBrushColor;
Pen.Color := OldPenColor;
end;
end;
end;
procedure TCheckListBox.SetChecked(Index: Integer; AChecked: Boolean);
begin
if AChecked <> GetChecked(Index) then
begin
TCheckListBoxDataWrapper(GetWrapper(Index)).SetChecked(AChecked);
InvalidateCheck(Index);
end;
end;
procedure TCheckListBox.SetItemEnabled(Index: Integer; const Value: Boolean);
begin
if Value <> GetItemEnabled(Index) then
begin
TCheckListBoxDataWrapper(GetWrapper(Index)).Disabled := not Value;
InvalidateCheck(Index);
end;
end;
procedure TCheckListBox.SetState(Index: Integer; AState: TCheckBoxState);
begin
if AState <> GetState(Index) then
begin
TCheckListBoxDataWrapper(GetWrapper(Index)).State := AState;
InvalidateCheck(Index);
end;
end;
procedure TCheckListBox.InvalidateCheck(Index: Integer);
var
R: TRect;
begin
if not Header[Index] then
begin
R := ItemRect(Index);
if not UseRightToLeftAlignment then
R.Right := R.Left + GetCheckWidth
else
R.Left := R.Right - GetCheckWidth;
InvalidateRect(Handle, @R, not (csOpaque in ControlStyle));
UpdateWindow(Handle);
end;
end;
function TCheckListBox.GetChecked(Index: Integer): Boolean;
begin
if HaveWrapper(Index) then
Result := TCheckListBoxDataWrapper(GetWrapper(Index)).GetChecked
else
Result := False;
end;
function TCheckListBox.GetItemEnabled(Index: Integer): Boolean;
begin
if HaveWrapper(Index) then
Result := not TCheckListBoxDataWrapper(GetWrapper(Index)).Disabled
else
Result := True;
end;
function TCheckListBox.GetState(Index: Integer): TCheckBoxState;
begin
if HaveWrapper(Index) then
Result := TCheckListBoxDataWrapper(GetWrapper(Index)).State
else
Result := TCheckListBoxDataWrapper.GetDefaultState;
end;
procedure TCheckListBox.KeyPress(var Key: Char);
begin
if (Key = ' ') then
ToggleClickCheck(ItemIndex);
inherited KeyPress(Key);
end;
procedure TCheckListBox.MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
var
Index: Integer;
begin
inherited;
if Button = mbLeft then
begin
Index := ItemAtPos(Point(X,Y),True);
if (Index <> -1) and GetItemEnabled(Index) then
if not UseRightToLeftAlignment then
begin
if X - ItemRect(Index).Left < GetCheckWidth then
ToggleClickCheck(Index)
end
else
begin
Dec(X, ItemRect(Index).Right - GetCheckWidth);
if (X > 0) and (X < GetCheckWidth) then
ToggleClickCheck(Index)
end;
end;
end;
procedure TCheckListBox.ToggleClickCheck;
var
State: TCheckBoxState;
begin
if (Index >= 0) and (Index < Items.Count) and GetItemEnabled(Index) then
begin
State := Self.State[Index];
case State of
cbUnchecked:
if AllowGrayed then State := cbGrayed else State := cbChecked;
cbChecked: State := cbUnchecked;
cbGrayed: State := cbChecked;
end;
Self.State[Index] := State;
ClickCheck;
end;
end;
procedure TCheckListBox.ClickCheck;
begin
if Assigned(FOnClickCheck) then FOnClickCheck(Self);
end;
function TCheckListBox.GetItemData(Index: Integer): LongInt;
begin
Result := 0;
if HaveWrapper(Index) then
Result := TCheckListBoxDataWrapper(GetWrapper(Index)).FData;
end;
function TCheckListBox.GetWrapper(Index: Integer): TObject;
begin
Result := ExtractWrapper(Index);
if Result = nil then
Result := CreateWrapper(Index);
end;
function TCheckListBox.ExtractWrapper(Index: Integer): TObject;
begin
Result := TCheckListBoxDataWrapper(inherited GetItemData(Index));
if LB_ERR = Integer(Result) then
raise EListError.CreateResFmt(@SListIndexError, [Index]);
if (Result <> nil) and (not (Result is TCheckListBoxDataWrapper)) then
Result := nil;
end;
function TCheckListBox.InternalGetItemData(Index: Integer): LongInt;
begin
Result := inherited GetItemData(Index);
end;
procedure TCheckListBox.InternalSetItemData(Index: Integer; AData: LongInt);
begin
inherited SetItemData(Index, AData);
end;
function TCheckListBox.CreateWrapper(Index: Integer): TObject;
begin
Result := TCheckListBoxDataWrapper.Create;
inherited SetItemData(Index, LongInt(Result));
end;
function TCheckListBox.HaveWrapper(Index: Integer): Boolean;
begin
Result := ExtractWrapper(Index) <> nil;
end;
procedure TCheckListBox.SetItemData(Index: Integer; AData: LongInt);
var
Wrapper: TCheckListBoxDataWrapper;
begin
if HaveWrapper(Index) or (AData <> 0) then
begin
Wrapper := TCheckListBoxDataWrapper(GetWrapper(Index));
Wrapper.FData := AData;
end;
end;
procedure TCheckListBox.ResetContent;
var
I: Integer;
begin
for I := 0 to Items.Count - 1 do
if HaveWrapper(I) then
GetWrapper(I).Free;
inherited;
end;
procedure TCheckListBox.DeleteString(Index: Integer);
begin
if HaveWrapper(Index) then
GetWrapper(Index).Free;
inherited;
end;
procedure TCheckListBox.SetFlat(Value: Boolean);
begin
if Value <> FFlat then
begin
FFlat := Value;
Invalidate;
end;
end;
procedure TCheckListBox.WMDestroy(var Msg: TWMDestroy);
var
i: Integer;
begin
for i := 0 to Items.Count -1 do
ExtractWrapper(i).Free;
inherited;
end;
function TCheckListBox.GetHeader(Index: Integer): Boolean;
begin
if HaveWrapper(Index) then
Result := TCheckListBoxDataWrapper(GetWrapper(Index)).Header
else
Result := False;
end;
procedure TCheckListBox.SetHeader(Index: Integer; const Value: Boolean);
begin
if Value <> GetHeader(Index) then
begin
TCheckListBoxDataWrapper(GetWrapper(Index)).Header := Value;
InvalidateCheck(Index);
end;
end;
procedure TCheckListBox.SetHeaderBackgroundColor(const Value: TColor);
begin
if Value <> HeaderBackgroundColor then
begin
FHeaderBackgroundColor := Value;
Invalidate;
end;
end;
procedure TCheckListBox.SetHeaderColor(const Value: TColor);
begin
if Value <> HeaderColor then
begin
FHeaderColor := Value;
Invalidate;
end;
end;
initialization
GetCheckSize;
end.
|
{$A+,B-,D+,E-,F-,G+,I+,L+,N+,O-,P-,Q+,R+,S+,T-,V+,X+,Y+}
{$M 1024,0,655360}
{
by Behdad Esfahbod
Algorithmic Problems Book
April '2000
Problem 74 Simulating
}
program
Mariage;
uses
Graph;
const
MaxN = 400;
MaxM = 400;
MaxK = 10000;
MaxT = 600;
dx : array [0 .. 4] of Integer = (0, 1, 0, -1, 0);
dy : array [0 .. 4] of Integer = (0, 0, 1, 0, -1);
Col : array [-1 .. 1] of Integer = (12, 10, 9);
type
TP = array [1 .. MaxK] of record X, Y, L : Integer end;
TR = array [0 .. MaxN + 1] of Integer;
var
M, N, P, T : Integer;
B : array [0 .. MaxM + 1] of ^ TR;
Ps : ^ TP;
Ans : array [-1 .. 1] of Integer;
Parvaneh : Boolean;
I, J, K, Time, D : Integer;
procedure ReadInput;
begin
Assign(Input, 'input.txt');
Reset(Input);
Readln(M, N, P, T);
Close(Input);
end;
procedure InitOutput;
var
grDriver: Integer;
grMode: Integer;
ErrCode: Integer;
begin
Assign(Output, 'output.txt');
Rewrite(Output);
grDriver := Detect;
InitGraph(grDriver, grMode,'');
end;
procedure CloseOutput;
begin
Close(Output);
Assign(Input, '');
Reset(Input);
Readln;
CloseGraph;
end;
procedure Simulate;
begin
New(Ps);
for I := 0 to M + 1 do
begin
GetMem(B[I], (N + 2) * SizeOf(B[I]^[0]));
FillChar(B[I]^, (N + 2) * SizeOf(B[I]^[0]), 127);
end;
for I := 1 to M do
for J := 1 to N do
B[I]^[J] := 0;
Randomize;
for K := 1 to P do
with Ps^[K] do
begin
X := Random(M) + 1;
Y := Random(N) + 1;
L := 0;
end;
for Time := 1 to T do
begin
for K := 1 to P do
with Ps^[K] do
begin
repeat
D := Random(5);
until B[X + dx[D]]^[Y + dy[D]] <= P;
Inc(X, dx[D]);
Inc(Y, dy[D]);
end;
FillChar(Ans, SizeOf(Ans), 0);
for I := 1 to M do
for J := 1 to N do
B[I]^[J] := 0;
for K := 1 to P do
with Ps^[K] do
Inc(B[X]^[Y], L);
Inc(B[1]^[1]);
if not Parvaneh and (B[M]^[N] > 0) then
begin
Parvaneh := True;
Col[0] := 11;
end;
if Parvaneh then
B[M]^[N] := -1;
for K := 1 to P do
with Ps^[K] do
begin
if B[X]^[Y] > 0 then L := 1 else
if B[X]^[Y] < 0 then L := -1 else
L := 0;
Inc(Ans[L]);
end;
Write(Time, ':');
K := 0;
for I := -1 to 1 do
begin
J := Trunc((Ans[I] / P) * 100 + 0.5);
Write(' ', J, '%');
SetColor(Col[I]);
J := Trunc(Ans[I] / P * 480 + 0.5);
if J <> 0 then
Line(Time, K, Time, K + J - 1);
Inc(K, J);
end;
Writeln;
end;
end;
begin
ReadInput;
InitOutput;
Simulate;
CloseOutput;
end.
|
{*******************************************************}
{ }
{ Delphi Visual Component Library }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit Vcl.PlatformDefaultStyleActnCtrls;
interface
uses Vcl.ActnMan, Vcl.ActnMenus, Vcl.ActnCtrls;
type
{$IF NOT DEFINED(CLR)}
{$HPPEMIT ''}
{$HPPEMIT '/* automatically link to platformstyleactnctrls.obj so that the property editors are registered */'}
{$HPPEMIT '#pragma link "Vcl.platformdefaultstyleactnctrls.obj"'}
{$HPPEMIT ''}
{$IFEND}
{ TPlatformDefaultStyleActionBars }
TPlatformDefaultStyleActionBars = class(TActionBarStyleEx)
public
function GetColorMapClass(ActionBar: TCustomActionBar): TCustomColorMapClass; override;
function GetControlClass(ActionBar: TCustomActionBar;
AnItem: TActionClientItem): TCustomActionControlClass; override;
function GetPopupClass(ActionBar: TCustomActionBar): TCustomPopupClass; override;
function GetAddRemoveItemClass(ActionBar: TCustomActionBar): TCustomAddRemoveItemClass; override;
function GetStyleName: string; override;
function GetScrollBtnClass: TCustomToolScrollBtnClass; override;
end;
var
PlatformDefaultStyle: TPlatformDefaultStyleActionBars;
implementation
uses
Vcl.ListActns, Vcl.ActnColorMaps, System.SysUtils, Vcl.Themes, Vcl.XPActnCtrls,
Vcl.StdActnMenus, Vcl.ThemedActnCtrls;
type
TActionControlStyle = (csStandard, csXPStyle, csThemed);
function GetActionControlStyle: TActionControlStyle;
begin
if TStyleManager.IsCustomStyleActive then
Result := csThemed
else if TOSVersion.Check(6) then
begin
if StyleServices.Theme[teMenu] <> 0 then
Result := csThemed
else
Result := csXPStyle;
end
else if TOSVersion.Check(5, 1) then
Result := csXPStyle
else
Result := csStandard;
end;
{ TPlatformDefaultStyleActionBars }
function TPlatformDefaultStyleActionBars.GetAddRemoveItemClass(
ActionBar: TCustomActionBar): TCustomAddRemoveItemClass;
begin
case GetActionControlStyle of
csStandard: Result := TStandardAddRemoveItem;
csXPStyle: Result := TXPStyleAddRemoveItem;
else
Result := TThemedAddRemoveItem;
end;
end;
function TPlatformDefaultStyleActionBars.GetColorMapClass(
ActionBar: TCustomActionBar): TCustomColorMapClass;
begin
case GetActionControlStyle of
csStandard: Result := TStandardColorMap;
csXPStyle: Result := TXPColorMap;
else
Result := TThemedColorMap;
end;
end;
function TPlatformDefaultStyleActionBars.GetControlClass(ActionBar: TCustomActionBar;
AnItem: TActionClientItem): TCustomActionControlClass;
begin
if ActionBar is TCustomActionToolBar then
begin
if AnItem.HasItems then
case GetActionControlStyle of
csStandard: Result := TStandardDropDownButton;
csXPStyle: Result := TXPStyleDropDownBtn;
else
Result := TThemedDropDownButton;
end
else
if (AnItem.Action is TStaticListAction) or
(AnItem.Action is TVirtualListAction) then
Result := TCustomComboControl
else
case GetActionControlStyle of
csStandard: Result := TStandardButtonControl;
csXPStyle: Result := TXPStyleButton;
else
Result := TThemedButtonControl;
end
end
else if ActionBar is TCustomActionMainMenuBar then
case GetActionControlStyle of
csStandard: Result := TStandardMenuButton;
csXPStyle: Result := TXPStyleMenuButton;
else
Result := TThemedMenuButton;
end
else if ActionBar is TCustomizeActionToolBar then
begin
with TCustomizeActionToolbar(ActionBar) do
if not Assigned(RootMenu) or
(AnItem.ParentItem <> TCustomizeActionToolBar(RootMenu).AdditionalItem) then
case GetActionControlStyle of
csStandard: Result := TStandardMenuItem;
csXPStyle: Result := TXPStyleMenuItem;
else
Result := TThemedMenuItem;
end
else
case GetActionControlStyle of
csStandard: Result := TStandardAddRemoveItem;
csXPStyle: Result := TXPStyleAddRemoveItem;
else
Result := TThemedAddRemoveItem;
end
end
else if ActionBar is TCustomActionPopupMenu then
case GetActionControlStyle of
csStandard: Result := TStandardMenuItem;
csXPStyle: Result := TXPStyleMenuItem;
else
Result := TThemedMenuItem;
end
else
case GetActionControlStyle of
csStandard: Result := TStandardButtonControl;
csXPStyle: Result := TXPStyleButton;
else
Result := TThemedButtonControl;
end
end;
function TPlatformDefaultStyleActionBars.GetPopupClass(ActionBar: TCustomActionBar): TCustomPopupClass;
begin
if ActionBar is TCustomActionToolBar then
case GetActionControlStyle of
csStandard: Result := TStandardCustomizePopup;
csXPStyle: Result := TXPStyleCustomizePopup;
else
Result := TThemedCustomizePopup;
end
else
case GetActionControlStyle of
csStandard: Result := TStandardMenuPopup;
csXPStyle: Result := TXPStylePopupMenu;
else
Result := TThemedPopupMenu;
end;
end;
function TPlatformDefaultStyleActionBars.GetScrollBtnClass: TCustomToolScrollBtnClass;
begin
case GetActionControlStyle of
csStandard: Result := TStandardToolScrollBtn;
csXPStyle: Result := TXPStyleToolScrollBtn;
else
Result := TThemedToolScrollBtn;
end;
end;
function TPlatformDefaultStyleActionBars.GetStyleName: string;
begin
Result := 'Platform Default'; { Do not localize }
end;
initialization
PlatformDefaultStyle := TPlatformDefaultStyleActionBars.Create;
DefaultActnBarStyle := PlatformDefaultStyle.GetStyleName;
RegisterActnBarStyle(PlatformDefaultStyle);
finalization
UnregisterActnBarStyle(PlatformDefaultStyle);
PlatformDefaultStyle.Free;
end.
|
unit uQrCodeGeneratorDemoFMX;
interface
uses
SysUtils,
IOUtils,
UITypes,
FMX.Dialogs,
FMX.Graphics,
QlpIQrCode,
QlpQrCode,
QlpIQrSegment,
QlpQrSegment,
QlpQrSegmentMode,
QlpBitBuffer,
QlpConverters,
QlpQRCodeGenLibTypes;
type
TQrCodeGeneratorDemoFMX = class sealed(TObject)
strict private
class procedure WriteQrCodeToFile(const AQrCode: IQrCode;
AScale, ABorder: Int32; const AFileName: String);
// Creates a single QR Code, then writes it to supported image formats and an SVG file.
class procedure DoBasicDemo();
// Creates a single QR Code, changes the colors (background and foreground) then writes it to supported image formats and an SVG file.
class procedure DoBasicDemoAndChangeColor();
// Creates a variety of QR Codes that exercise different features of the library, then writes each one to supported image formats and an SVG file.
class procedure DoVarietyDemo();
// Creates QR Codes with manually specified segments for better compactness, then writes each one to supported image formats and an SVG file.
class procedure DoSegmentDemo();
// Creates QR Codes with the same size and contents but different mask patterns, then writes each one to supported image formats and an SVG file.
class procedure DoMaskDemo();
public
class procedure RunAllDemos();
end;
implementation
uses
QrCodeGeneratorDemoFMXForm;
{ TQrCodeGeneratorDemo }
class procedure TQrCodeGeneratorDemoFMX.DoBasicDemo;
var
LText: String;
LErrCorLvl: TQrCode.TEcc;
LQrCode: IQrCode;
LEncoding: TEncoding;
begin
LEncoding := TEncoding.UTF8;
LText := 'Hello, world!'; // User-supplied Unicode text
LErrCorLvl := TQrCode.TEcc.eccLow; // Error correction level
// Make the QR Code symbol
LQrCode := TQrCode.EncodeText(LText, LErrCorLvl, LEncoding);
WriteQrCodeToFile(LQrCode, 10, 4, 'hello-world-QR');
end;
class procedure TQrCodeGeneratorDemoFMX.DoBasicDemoAndChangeColor;
var
LText: String;
LErrCorLvl: TQrCode.TEcc;
LQrCode: IQrCode;
LEncoding: TEncoding;
begin
LEncoding := TEncoding.UTF8;
LText := 'Hello, world!'; // User-supplied Unicode text
LErrCorLvl := TQrCode.TEcc.eccLow; // Error correction level
// Make the QR Code symbol
LQrCode := TQrCode.EncodeText(LText, LErrCorLvl, LEncoding);
LQrCode.BackgroundColor := TConverters.HTMLHexColorToQRCodeGenLibColor
('FFA500');
LQrCode.ForegroundColor := TConverters.HTMLHexColorToQRCodeGenLibColor
('000000');
WriteQrCodeToFile(LQrCode, 10, 4, 'hello-world-orange-background-QR');
end;
class procedure TQrCodeGeneratorDemoFMX.DoSegmentDemo;
const
// Kanji mode encoding (13 bits per character)
kanjiChars: array [0 .. 28] of Int32 = ($0035, $1002, $0FC0, $0AED, $0AD7,
$015C, $0147, $0129, $0059, $01BD, $018D, $018A, $0036, $0141, $0144, $0001,
$0000, $0249, $0240, $0249, $0000, $0104, $0105, $0113, $0115, $0000, $0208,
$01FF, $0008);
var
LSilver0, LSilver1, LGolden0, LGolden1, LGolden2, LMadoka: String;
LBitBuffer: TBitBuffer;
LEncoding: TEncoding;
LQrCode: IQrCode;
LSegs: TQRCodeGenLibGenericArray<IQrSegment>;
LCIdx: Int32;
begin
LEncoding := TEncoding.UTF8;
// Illustration "silver"
LSilver0 := 'THE SQUARE ROOT OF 2 IS 1.';
LSilver1 :=
'41421356237309504880168872420969807856967187537694807317667973799';
LQrCode := TQrCode.EncodeText(LSilver0 + LSilver1, TQrCode.TEcc.eccLow,
LEncoding);
WriteQrCodeToFile(LQrCode, 10, 3, 'sqrt2-monolithic-QR');
LSegs := TQRCodeGenLibGenericArray<IQrSegment>.Create
(TQrSegment.MakeAlphanumeric(LSilver0), TQrSegment.MakeNumeric(LSilver1));
LQrCode := TQrCode.EncodeSegments(LSegs, TQrCode.TEcc.eccLow);
WriteQrCodeToFile(LQrCode, 10, 3, 'sqrt2-segmented-QR');
// Illustration "golden"
LGolden0 := 'Golden ratio φ = 1.';
LGolden1 :=
'6180339887498948482045868343656381177203091798057628621354486227052604628189024497072072041893911374';
LGolden2 := '......';
LQrCode := TQrCode.EncodeText(LGolden0 + LGolden1 + LGolden2,
TQrCode.TEcc.eccLow, LEncoding);
WriteQrCodeToFile(LQrCode, 8, 5, 'phi-monolithic-QR');
LSegs := TQRCodeGenLibGenericArray<IQrSegment>.Create
(TQrSegment.MakeBytes(TConverters.ConvertStringToBytes(LGolden0, LEncoding)
), TQrSegment.MakeNumeric(LGolden1), TQrSegment.MakeAlphanumeric(LGolden2));
LQrCode := TQrCode.EncodeSegments(LSegs, TQrCode.TEcc.eccLow);
WriteQrCodeToFile(LQrCode, 8, 5, 'phi-segmented-QR');
// Illustration "Madoka": kanji, kana, Cyrillic, full-width Latin, Greek characters
LMadoka := '「魔法少女まどか☆マギカ」って、 ИАИ desu κα?';
LQrCode := TQrCode.EncodeText(LMadoka, TQrCode.TEcc.eccLow, LEncoding);
WriteQrCodeToFile(LQrCode, 9, 4, 'madoka-utf8-QR');
LBitBuffer := TBitBuffer.Create();
for LCIdx in kanjiChars do
begin
LBitBuffer.AppendBits(LCIdx, 13);
end;
LSegs := TQRCodeGenLibGenericArray<IQrSegment>.Create
(TQrSegment.Create(TQrSegmentMode.qsmKanji, System.Length(kanjiChars),
LBitBuffer.Data, LBitBuffer.bitLength) as IQrSegment);
LQrCode := TQrCode.EncodeSegments(LSegs, TQrCode.TEcc.eccLow);
WriteQrCodeToFile(LQrCode, 9, 4, 'madoka-kanji-QR');
end;
class procedure TQrCodeGeneratorDemoFMX.DoMaskDemo;
var
LQrCode: IQrCode;
LSegs: TQRCodeGenLibGenericArray<IQrSegment>;
LEncoding: TEncoding;
begin
LEncoding := TEncoding.UTF8;
// Project Nayuki URL
LSegs := TQrSegment.MakeSegments('https://www.nayuki.io/', LEncoding);
// Automatic mask
LQrCode := TQrCode.EncodeSegments(LSegs, TQrCode.TEcc.eccHigh,
TQrCode.MIN_VERSION, TQrCode.MAX_VERSION, -1, true);
WriteQrCodeToFile(LQrCode, 8, 6, 'project-nayuki-automask-QR');
// Force mask 3
LQrCode := TQrCode.EncodeSegments(LSegs, TQrCode.TEcc.eccHigh,
TQrCode.MIN_VERSION, TQrCode.MAX_VERSION, 3, true);
WriteQrCodeToFile(LQrCode, 8, 6, 'project-nayuki-mask3-QR');
// Chinese text as UTF-8
LSegs := TQrSegment.MakeSegments
('維基百科(Wikipedia,聆聽i/ˌwɪkᵻˈpiːdi.ə/)是一個自由內容、公開編輯且多語言的網路百科全書協作計畫',
LEncoding);
// Force mask 0
LQrCode := TQrCode.EncodeSegments(LSegs, TQrCode.TEcc.eccMedium,
TQrCode.MIN_VERSION, TQrCode.MAX_VERSION, 0, true);
WriteQrCodeToFile(LQrCode, 10, 3, 'unicode-mask0-QR');
// Force mask 1
LQrCode := TQrCode.EncodeSegments(LSegs, TQrCode.TEcc.eccMedium,
TQrCode.MIN_VERSION, TQrCode.MAX_VERSION, 1, true);
WriteQrCodeToFile(LQrCode, 10, 3, 'unicode-mask1-QR');
// Force mask 5
LQrCode := TQrCode.EncodeSegments(LSegs, TQrCode.TEcc.eccMedium,
TQrCode.MIN_VERSION, TQrCode.MAX_VERSION, 5, true);
WriteQrCodeToFile(LQrCode, 10, 3, 'unicode-mask5-QR');
// Force mask 7
LQrCode := TQrCode.EncodeSegments(LSegs, TQrCode.TEcc.eccMedium,
TQrCode.MIN_VERSION, TQrCode.MAX_VERSION, 7, true);
WriteQrCodeToFile(LQrCode, 10, 3, 'unicode-mask7-QR');
end;
class procedure TQrCodeGeneratorDemoFMX.DoVarietyDemo;
var
LQrCode: IQrCode;
LEncoding: TEncoding;
begin
LEncoding := TEncoding.UTF8;
// Numeric mode encoding (3.33 bits per digit)
LQrCode := TQrCode.EncodeText
('314159265358979323846264338327950288419716939937510',
TQrCode.TEcc.eccMedium, LEncoding);
WriteQrCodeToFile(LQrCode, 13, 1, 'pi-digits-QR');
// Alphanumeric mode encoding (5.5 bits per character)
LQrCode := TQrCode.EncodeText
('DOLLAR-AMOUNT:$39.87 PERCENTAGE:100.00% OPERATIONS:+-*/',
TQrCode.TEcc.eccHigh, LEncoding);
WriteQrCodeToFile(LQrCode, 10, 2, 'alphanumeric-QR');
// Unicode text as UTF-8
LQrCode := TQrCode.EncodeText('こんにちwa、世界! αβγδ', TQrCode.TEcc.eccQuartile,
LEncoding);
WriteQrCodeToFile(LQrCode, 10, 3, 'unicode-QR');
// Moderately large QR Code using longer text (from Lewis Carroll's Alice in Wonderland)
LQrCode := TQrCode.EncodeText
('Alice was beginning to get very tired of sitting by her sister on the bank, '
+ 'and of having nothing to do: once or twice she had peeped into the book her sister was reading, '
+ 'but it had no pictures or conversations in it, ''and what is the use of a book,'' thought Alice '
+ '''without pictures or conversations?'' So she was considering in her own mind (as well as she could, '
+ 'for the hot day made her feel very sleepy and stupid), whether the pleasure of making a '
+ 'daisy-chain would be worth the trouble of getting up and picking the daisies, when suddenly '
+ 'a White Rabbit with pink eyes ran close by her.',
TQrCode.TEcc.eccQuartile, LEncoding);
WriteQrCodeToFile(LQrCode, 6, 10, 'alice-wonderland-QR');
end;
class procedure TQrCodeGeneratorDemoFMX.RunAllDemos;
begin
QRCodeGeneratorFMXDemoForm.mmoLogger.Lines.Add('Started "DoBasicDemo"');
DoBasicDemo();
QRCodeGeneratorFMXDemoForm.mmoLogger.Lines.Add('Finished "DoBasicDemo"');
QRCodeGeneratorFMXDemoForm.mmoLogger.Lines.Add
('Started "DoBasicDemoAndChangeColor"');
DoBasicDemoAndChangeColor();
QRCodeGeneratorFMXDemoForm.mmoLogger.Lines.Add
('Finished "DoBasicDemoAndChangeColor"');
QRCodeGeneratorFMXDemoForm.mmoLogger.Lines.Add('Started "DoVarietyDemo"');
DoVarietyDemo();
QRCodeGeneratorFMXDemoForm.mmoLogger.Lines.Add('Finished "DoVarietyDemo"');
QRCodeGeneratorFMXDemoForm.mmoLogger.Lines.Add('Started "DoSegmentDemo"');
DoSegmentDemo();
QRCodeGeneratorFMXDemoForm.mmoLogger.Lines.Add('Finished "DoSegmentDemo"');
QRCodeGeneratorFMXDemoForm.mmoLogger.Lines.Add('Started "DoMaskDemo"');
DoMaskDemo();
QRCodeGeneratorFMXDemoForm.mmoLogger.Lines.Add('Finished "DoMaskDemo"');
QRCodeGeneratorFMXDemoForm.mmoLogger.Lines.Add(sLineBreak);
QRCodeGeneratorFMXDemoForm.mmoLogger.Lines.Add
('Finished Executing All Demos');
end;
class procedure TQrCodeGeneratorDemoFMX.WriteQrCodeToFile
(const AQrCode: IQrCode; AScale, ABorder: Int32; const AFileName: String);
const
FolderName: String = 'Assets';
var
LFilePath: String;
LBitmap: TQRCodeGenLibBitmap;
begin
LFilePath := TPath.Combine(TPath.GetSharedDocumentsPath, FolderName);
if not DirectoryExists(LFilePath) then
begin
if not ForceDirectories(LFilePath) then
begin
// break out since we cannot create our "Assets" directory.
ShowMessage(Format('Error creating our "%s" directory.', [LFilePath]));
Exit;
end;
end;
LFilePath := TPath.Combine(LFilePath, AFileName);
// create bmp
LBitmap := AQrCode.ToBitmapImage(AScale, ABorder);
try
try
{$IF DEFINED(MSWINDOWS) OR DEFINED(MACOS)}
// bmp is only supported on Windows and MACOS
// save bmp
LBitmap.SaveToFile(LFilePath + '.bmp');
{$ENDIF}
// save jpeg
LBitmap.SaveToFile(LFilePath + '.jpg');
// save png
LBitmap.SaveToFile(LFilePath + '.png');
AQrCode.ToSvgFile(ABorder, LFilePath + '.svg');
except
raise;
end;
finally
LBitmap.Free;
end;
end;
end.
|
{*******************************************************}
{ }
{ Borland Delphi Test Server }
{ }
{ Copyright (c) 2001 Borland Software Corporation }
{ }
{*******************************************************}
unit SvrLogColSettingsFrame;
interface
uses
SysUtils, Classes, QGraphics, QControls, QForms, QDialogs, SvrLogFrame,
QComCtrls, SvrLog;
type
TLogColSettingsFrame = class(TFrame)
lvColumns: TListView;
procedure FrameResize(Sender: TObject);
private
FLogFrame: TLogFrame;
procedure SetLogFrame(const Value: TLogFrame);
public
procedure UpdateColumns;
property LogFrame: TLogFrame read FLogFrame write SetLogFrame;
end;
implementation
{$R *.xfm}
{ TLogColumnsFrame }
procedure TLogColSettingsFrame.SetLogFrame(const Value: TLogFrame);
var
Item: TListItem;
I: Integer;
LogColumn: TLogColumn;
Positions: TLogColumnOrder;
begin
FLogFrame := Value;
FLogFrame.SynchColumnInfo;
FLogFrame.GetColumnOrder(Positions);
for I := Low(Positions) to High(Positions) do
begin
Item := lvColumns.Items.Add;
LogColumn := Positions[I];
Item.Caption := LogFrame.ColumnCaption[LogColumn];
Item.Checked := LogFrame.ColumnVisible[LogColumn];
Item.Data := Pointer(LogColumn);
end;
end;
procedure TLogColSettingsFrame.FrameResize(Sender: TObject);
begin
lvColumns.Columns[0].Width := lvColumns.ClientWidth;
end;
procedure TLogColSettingsFrame.UpdateColumns;
var
I: Integer;
Item: TListItem;
begin
for I := 0 to lvColumns.Items.Count - 1 do
begin
Item := lvColumns.Items[I];
LogFrame.ColumnVisible[TLogColumn(Item.Data)] := Item.Checked;
end;
LogFrame.RefreshColumns;
LogFrame.RefreshSubItems;
end;
end.
|
unit U_ListFunctions;
interface
uses U_Typeset;
function IsNumber(c : char) : boolean; // checks if c is a number
function IsUpper(c : char) : boolean; // checks if c is UPPERCASE
function IsLower(c : char) : boolean; // checks if c is lowercase
procedure PrintOut(s : PItem);
// What : prints the list out
procedure InsertEnd(prvek : string; var l : PItem);
// What : inserts a new element at the end
function FillList(var exact_react : longint; var number_elem : longint; var l : PItem; var ReactOnLeft : longint) : byte;
// What : fills list with input
// How : Reads stdin until SeekEoF, builds a string and when it find
// '=' or '+' it inserts it at the end of the list and starts a new one
procedure PrintStack(s : PStack);
// What : prints stack
procedure PushEnd(item : longint; var l : PStack);
// What : pushes a new element at the end of the stack
function PopEnd(var l : PStack) : longint;
// What : returns the latest element of the stack
implementation
{ Char procedures }
function IsNumber(c : char) : boolean;
begin
if( (c >= '0') AND (c <= '9') ) then IsNumber := true
else IsNumber := false;
end;
function IsUpper(c : char) : boolean;
begin
if( (c >= 'A') AND (c <= 'Z') ) then IsUpper := true
else IsUpper := false;
end;
function IsLower(c : char) : boolean;
begin
if( (c >= 'a') AND (c <= 'z') ) then IsLower := true
else IsLower := false;
end;
{ List procedures }
procedure PrintOut(s : PItem);
var i : PItem;
begin
i := s^.next;
while i <> nil do begin
write(i^.val, ' ');
i := i^.next;
end;
WriteLn;
end;
procedure InsertEnd(prvek : string; var l : PItem);
var i : Pitem;
begin
new(i);
i^.val := prvek;
i^.next := nil;
l^.next := i;
l := i;
end;
{ Start of parsing - makes the list with reactants }
function FillList(var exact_react : longint; var number_elem : longint; var l : PItem; var ReactOnLeft : longint) : byte;
var in_C : char;
s : string;
ReachedEnd,Empty,ReachedEquat : boolean;
begin
s := '';
ReachedEnd := false;
Empty := true;
ReachedEquat := false;
{ all the reactants }
while not seekEOF do begin
read(in_C);
{ one reactant }
While ((in_C <> '+') and (in_C <> '=' ) and (in_C <> '.' )) do begin
s := s + in_C;
if(isUpper(in_C)) then Inc(number_elem);
if seekEOF then begin ReachedEnd := true; break; end
else read(in_C);
end;
{ found the whole }
if(s <> '') then begin
InsertEnd(s,l);
Empty := false;
end;
if(in_C = '.' ) then ReachedEnd := true;
Inc(exact_react);
if(in_C = '=') then begin ReactOnLeft := exact_react; ReachedEquat := true; end;
if(ReachedEnd = true) then break;
s := '';
end;
if(empty) then FillList := 10 // empty equation !
else if((not(empty)) and (ReachedEquat = false)) then FillList := 12 // No '=' found !
else if(number_elem = 0) then FillList := 14 // No elements found !
else if((not(empty)) and (ReachedEquat = true)) then FillList := 20 // All is OK.
end;
{ Stack procedures }
procedure PrintStack(s : PStack);
var i : PStack;
begin
i := s^.next;
while i <> nil do begin
write(i^.val,' ');
i := i^.next;
end;
WriteLn;
end;
procedure PushEnd(item : longint; var l : PStack);
var i : PStack;
begin
new(i);
i^.next := nil;
i^.last := l;
i^.val := item;
l^.next := i;
l := i;
end;
function PopEnd(var l : PStack) : longint;
var tmp : PStack;
begin
PopEnd := l^.val;
if(l^.val <> -31000) then begin
tmp := l;
l^.last^.next := nil;
l := l^.last;
dispose(tmp);
end;
end;
end. |
{$I NEX.INC}
unit ncDMCaixa;
{
ResourceString: Dario 12/03/13
}
interface
uses
SysUtils, Classes, DB, nxdb, kbmMemTable, nxllTransport,
nxptBasePooledTransport, nxtwWinsockTransport, nxsdServerEngine,
nxreRemoteServerEngine, nxllComponent, ncCaixas,
uNexTransResourceStrings_PT, frxDBSet, frxExportPDF, frxClass, frxDesgn;
type
{TDadosCaixa = record
dcID : Integer;
dcAbertura : TDateTime;
dcFechamento : TDateTime;
dcSaldoInicial : Currency;
dcUsuario : String;
end;}
TDadosResFin = record
drfQtd : Integer;
drfValor : Currency;
end;
TdmCaixa = class(TDataModule)
nxSession: TnxSession;
nxDB: TnxDatabase;
nxRSE: TnxRemoteServerEngine;
nxTCPIP: TnxWinsockTransport;
dsQVC: TDataSource;
qVC: TnxQuery;
tProd: TnxTable;
tAuxME: TnxTable;
mtEst: TkbmMemTable;
mtEstSaldoInicial: TFloatField;
mtEstEntradas: TFloatField;
mtEstCompras: TFloatField;
mtEstSaidas: TFloatField;
mtEstVendas: TFloatField;
mtEstValorVendas: TCurrencyField;
mtEstSaldoFinal: TFloatField;
mtEstLucro: TCurrencyField;
dsTot: TDataSource;
dsEst: TDataSource;
mtTot: TkbmMemTable;
mtTotItem: TIntegerField;
mtTotDescricao: TStringField;
mtTotValor: TCurrencyField;
tProdID: TAutoIncField;
mtEstID: TIntegerField;
tProdCustoUnitario: TCurrencyField;
tProdNaoControlaEstoque: TBooleanField;
qRFFat: TnxQuery;
qDesc: TnxQuery;
qCanc: TnxQuery;
tCli: TnxTable;
qVCTotal: TCurrencyField;
qVCDesconto: TCurrencyField;
qVCTotFinal: TCurrencyField;
tAuxMESaldoFinal: TFloatField;
tCaixa: TnxTable;
tCaixaID: TAutoIncField;
tCaixaAberto: TBooleanField;
tCaixaUsuario: TStringField;
tCaixaAbertura: TDateTimeField;
tCaixaFechamento: TDateTimeField;
tCaixaTotalFinal: TCurrencyField;
tCaixaDescontos: TCurrencyField;
tCaixaCancelamentos: TCurrencyField;
tCaixaSaldoAnt: TCurrencyField;
tCaixaObs: TMemoField;
qFecha: TnxQuery;
PDFexp: TfrxPDFExport;
frdbCaixa: TfrxDBDataset;
frdbTot: TfrxDBDataset;
qVCQuant: TFloatField;
tCaixaSangria: TCurrencyField;
tCaixaSupr: TCurrencyField;
tCaixaReproc: TDateTimeField;
qCorr: TnxQuery;
qCorr2: TnxQuery;
tTran: TnxTable;
tITran: TnxTable;
mtEstFidResg: TFloatField;
tCaixaEstSessoesQtd: TIntegerField;
tCaixaEstSessoesTempo: TFloatField;
tCaixaEstUrls: TIntegerField;
tCaixaEstSyncOk: TBooleanField;
tCaixaEstBuscasEng: TMemoField;
tCaixaEstRes: TMemoField;
qCancQuant: TLargeintField;
qCancTotal: TCurrencyField;
qDescQuant: TLargeintField;
qDescTotal: TCurrencyField;
tCaixaSaldoF: TCurrencyField;
tCaixaQuebra: TCurrencyField;
frdbEst: TfrxDBDataset;
mtEstEntradasTot: TFloatField;
frdbTran: TfrxDBDataset;
tRepProd: TnxTable;
frdbProd: TfrxDBDataset;
qRepTran: TnxQuery;
qRepTranDataHora: TDateTimeField;
qRepTranFunc: TStringField;
qRepTranTotal: TCurrencyField;
qRepTranDesconto: TCurrencyField;
qRepTranTotLiq: TCurrencyField;
qRepTranPago: TCurrencyField;
qRepTranDebito: TCurrencyField;
qRepTranObs: TnxMemoField;
qRepTranCancelado: TBooleanField;
qRepTranCanceladoPor: TStringField;
qRepTranCanceladoEm: TDateTimeField;
qRepTranQtdTempo: TFloatField;
qRepTranCredValor: TBooleanField;
qRepTranFidResgate: TBooleanField;
qRepTranNomeTipo: TStringField;
qRepTranCancFid: TStringField;
tCaixaIDLivre: TStringField;
tUsuario: TnxTable;
tUsuarioUsername: TStringField;
tUsuarioNome: TStringField;
tUsuarioAdmin: TBooleanField;
repCaixa_pt: TfrxReport;
tCaixaNomeLoja: TStringField;
qPagEsp: TnxQuery;
tEsp: TnxTable;
tEspID: TWordField;
tEspNome: TStringField;
tEspImg: TWordField;
dsPagEsp: TDataSource;
frdbPagEsp: TfrxDBDataset;
qRFPag: TnxQuery;
qRFPagCredito: TCurrencyField;
qRFPagDebito: TCurrencyField;
qRFPagQtd: TLargeintField;
qRFPagCreditoUsado: TCurrencyField;
qRFPagPago: TCurrencyField;
qRFFatQtd: TLargeintField;
qRFFatTotLiq: TCurrencyField;
mtRF1: TkbmMemTable;
mtRF1Item: TIntegerField;
mtRF1Descricao: TStringField;
mtRF1Total: TCurrencyField;
dsRF1: TDataSource;
mtRF2: TkbmMemTable;
mtRF2Item: TIntegerField;
mtRF2Descricao: TStringField;
mtRF2Total: TCurrencyField;
dsRF2: TDataSource;
mtRF3: TkbmMemTable;
mtRF3Item: TIntegerField;
mtRF3Descricao: TStringField;
mtRF3Total: TCurrencyField;
dsRF3: TDataSource;
dbRF1: TfrxDBDataset;
dbRF2: TfrxDBDataset;
dbRF3: TfrxDBDataset;
mtRF1Bold: TBooleanField;
mtRF1Cor: TIntegerField;
mtRF2Bold: TBooleanField;
mtRF2Cor: TIntegerField;
mtRF3Bold: TBooleanField;
mtRF3Cor: TIntegerField;
mtObs: TkbmMemTable;
mtObsObs: TMemoField;
dbObs: TfrxDBDataset;
qRFPagTroco: TCurrencyField;
tAuxMEID: TUnsignedAutoIncField;
tAuxMETran: TLongWordField;
tAuxMEProduto: TLongWordField;
tAuxMEQuant: TFloatField;
tAuxMEUnitario: TCurrencyField;
tAuxMETotal: TCurrencyField;
tAuxMECustoU: TCurrencyField;
tAuxMEItem: TByteField;
tAuxMEDesconto: TCurrencyField;
tAuxMEDataHora: TDateTimeField;
tAuxMEEntrada: TBooleanField;
tAuxMEAjustaCusto: TBooleanField;
tAuxMEEstoqueAnt: TFloatField;
tAuxMECaixa: TIntegerField;
tAuxMENaoControlaEstoque: TBooleanField;
tAuxMEITran: TIntegerField;
tAuxMETipoTran: TByteField;
tAuxMEFidResgate: TBooleanField;
tITranID: TUnsignedAutoIncField;
tITranTran: TLongWordField;
tITranCaixa: TLongWordField;
tITranCaixaPag: TLongWordField;
tITranCliente: TLongWordField;
tITranSessao: TLongWordField;
tITranDataHora: TDateTimeField;
tITranTipoTran: TByteField;
tITranTipoItem: TByteField;
tITranSubTipo: TByteField;
tITranItemID: TLongWordField;
tITranSubItemID: TLongWordField;
tITranItemPos: TByteField;
tITranTotal: TCurrencyField;
tITranDesconto: TCurrencyField;
tITranTotLiq: TCurrencyField;
tITranDebito: TCurrencyField;
tITranPago: TCurrencyField;
tITranCancelado: TBooleanField;
tITranPagPend: TBooleanField;
tITranFidFator: TShortintField;
tITranFidPontos: TFloatField;
tITranFidMov: TBooleanField;
tITranFidOpe: TByteField;
tTranID: TUnsignedAutoIncField;
tTranUID: TGuidField;
tTranDataHora: TDateTimeField;
tTranCliente: TLongWordField;
tTranTipo: TByteField;
tTranFunc: TStringField;
tTranTotal: TCurrencyField;
tTranDesconto: TCurrencyField;
tTranDescPerc: TFloatField;
tTranDescPorPerc: TBooleanField;
tTranTotLiq: TCurrencyField;
tTranPagEsp: TWordField;
tTranPago: TCurrencyField;
tTranDebitoAnt: TCurrencyField;
tTranDebito: TCurrencyField;
tTranDebitoPago: TCurrencyField;
tTranCreditoAnt: TCurrencyField;
tTranCredito: TCurrencyField;
tTranCreditoUsado: TCurrencyField;
tTranTroco: TCurrencyField;
tTranObs: TnxMemoField;
tTranCancelado: TBooleanField;
tTranCanceladoPor: TStringField;
tTranCanceladoEm: TDateTimeField;
tTranCaixa: TLongWordField;
tTranCaixaPag: TLongWordField;
tTranMaq: TWordField;
tTranSessao: TLongWordField;
tTranQtdTempo: TFloatField;
tTranCredValor: TBooleanField;
tTranFidResgate: TBooleanField;
tTranPagFunc: TStringField;
tTranPagPend: TBooleanField;
qPagEspEspecie: TWordField;
qPagEspTotalValor: TCurrencyField;
qPagEspTotalTroco: TCurrencyField;
qPagEspTotalF: TCurrencyField;
qPagEspNomeEspecie: TStringField;
qPagEspImg: TWordField;
tAuxMEFidPontos: TFloatField;
qRepTranUID: TGuidField;
qRepTranCliente: TLongWordField;
qRepTranTipo: TByteField;
qRepTranDescPerc: TFloatField;
qRepTranDescPorPerc: TBooleanField;
qRepTranPagEsp: TWordField;
qRepTranDebitoAnt: TCurrencyField;
qRepTranDebitoPago: TCurrencyField;
qRepTranCreditoAnt: TCurrencyField;
qRepTranCredito: TCurrencyField;
qRepTranCreditoUsado: TCurrencyField;
qRepTranTroco: TCurrencyField;
qRepTranCaixa: TLongWordField;
qRepTranCaixaPag: TLongWordField;
qRepTranMaq: TWordField;
qRepTranPagFunc: TStringField;
qRepTranPagPend: TBooleanField;
qRepTranID: TLongWordField;
qRepTranSessao: TLongWordField;
qRFFatTipo: TByteField;
qRFPagTipo: TByteField;
qFechaCancelado: TBooleanField;
qFechaTipo: TByteField;
qFechaTotal: TCurrencyField;
qFechaDesconto: TCurrencyField;
qFechaPago: TCurrencyField;
qFechaTroco: TCurrencyField;
qFechaDebito: TCurrencyField;
qME: TnxQuery;
qMEproduto: TLongWordField;
qMEtipotran: TByteField;
qMEfidresgate: TBooleanField;
qMEquant: TFloatField;
qMEtotal: TCurrencyField;
qMEpago: TCurrencyField;
qMEdesconto: TCurrencyField;
tAuxMECancelado: TBooleanField;
qRFPagPend: TnxQuery;
qRFPagPendTipo: TByteField;
qRFPagPendQtd: TLargeintField;
qRFPagPendCredito: TCurrencyField;
qRFPagPendDebito: TCurrencyField;
qRFPagPendPago: TCurrencyField;
qRFPagPendCreditoUsado: TCurrencyField;
qRFPagPendTroco: TCurrencyField;
mtEstDevolucoes: TFloatField;
qDev: TnxQuery;
qDevOpDevValor: TByteField;
qDevQuant: TLargeintField;
qDevTotal: TCurrencyField;
mtRF4: TkbmMemTable;
dsRF4: TDataSource;
mtRF4Item: TIntegerField;
mtRF4Descricao: TStringField;
mtRF4Total: TCurrencyField;
mtRF4Bold: TBooleanField;
mtRF4Cor: TIntegerField;
dbRF4: TfrxDBDataset;
tTranUID_ref: TGuidField;
tTranStatusNFE: TByteField;
tTranChaveNFE: TStringField;
tTranTipoNFE: TByteField;
tTranIncluidoEm: TDateTimeField;
tTranOpDevValor: TByteField;
tTranAmbNFe: TByteField;
tTranStatusCanc: TByteField;
tTranExtra: TnxMemoField;
tAuxTran: TnxTable;
tAuxNFE: TnxTable;
tNFConfig: TnxTable;
tNFConfigtpAmb: TByteField;
tNFConfigTipo: TByteField;
tPostMS: TnxTable;
tPostMSID: TUnsignedAutoIncField;
tPostMSMS: TBlobField;
tPostMSURL: TStringField;
tPostMSInclusao: TDateTimeField;
tPostMSEnvio: TDateTimeField;
tPostMSTries: TWordField;
tPostMSMax: TWordField;
tPostMSNextTry: TLongWordField;
Designer: TfrxDesigner;
repCaixa_en: TfrxReport;
qRepTranDescricao: TWideMemoField;
tTranDescricao: TWideMemoField;
qMEcustot: TExtendedField;
mtPagEsp: TkbmMemTable;
mtPagEspEspecie: TWordField;
mtPagEspNomeEsp: TWideStringField;
mtPagEspVendas: TCurrencyField;
mtPagEspDev: TCurrencyField;
mtPagEspSangria: TCurrencyField;
mtPagEspSupr: TCurrencyField;
mtPagEspTotal: TCurrencyField;
qPagEspTipoTran: TByteField;
mtPagEspTroco: TCurrencyField;
mtMPObs: TkbmMemTable;
frdbMPObs: TfrxDBDataset;
mtMPObsAsterisco: TStringField;
mtMPObsTotal: TCurrencyField;
mtMPObsTroco: TCurrencyField;
mtMPObsNomeEsp: TStringField;
mtMPObsEspecie: TWordField;
mtPagEspObs: TWideMemoField;
repCaixa_es: TfrxReport;
tTranNomeCliente: TWideStringField;
qRepTranEntregar: TBooleanField;
qRepTranHora: TByteField;
qRepTranNomeCliente: TWideStringField;
qRepTranVendedor: TStringField;
qRepTranComissao: TCurrencyField;
qRepTranFrete: TCurrencyField;
qRepTranTotalFinal: TCurrencyField;
tProdDescricao: TWideStringField;
mtEstDescricao: TWideStringField;
qVCCategoria: TWideStringField;
procedure qVCCalcFields(DataSet: TDataSet);
procedure tAuxMECalcFields(DataSet: TDataSet);
procedure DataModuleCreate(Sender: TObject);
procedure mtEstCalcFields(DataSet: TDataSet);
procedure repCaixa_ptBeforePrint(Sender: TfrxReportComponent);
procedure qRepTranCalcFields(DataSet: TDataSet);
procedure tCaixaCalcFields(DataSet: TDataSet);
procedure qPagEspCalcFields(DataSet: TDataSet);
procedure mtRF1CalcFields(DataSet: TDataSet);
procedure mtRF2CalcFields(DataSet: TDataSet);
procedure mtRF3CalcFields(DataSet: TDataSet);
procedure DataModuleDestroy(Sender: TObject);
private
{ Private declarations }
procedure AddItemRF(aItem: Integer; aDescr: String; aValor: Currency; aAddZero: Boolean = True);
procedure SaldoIF(aProduto: Cardinal; var aSaldoI, aSaldoF: Extended);
function PodeFechar: Boolean;
function TemVendaHomo: Boolean;
procedure GeraEmailFechamento;
public
drf : Array[1..20] of TDadosResFin;
FCXRange : TncCaixas;
TemSupSan : Boolean;
FImpTran : Boolean;
TotalTroco : Currency;
procedure AbreConn;
function AbreCaixa(aFunc: String; aSaldo: Currency; aManterSaldo: Boolean; var aNumCx: Integer): Integer;
function FechaCaixa(aFunc: String; aSaldo: Currency; aNumCx: Integer; aReproc: Boolean): Integer;
function Processa(aID: Integer; aCXRange: TncCaixas): Currency;
procedure MostrarCaixa(aID: Integer);
procedure ExportaCaixa(aID: Integer; aArquivo: String);
procedure ExportaCaixaKite(aID: Integer; aArquivo: String; slPar: tStrings);
procedure EmailCaixa(aID: Integer);
function repCaixa: TfrxReport;
{ Public declarations }
end;
var
dmCaixa: TdmCaixa;
const
irfFaturamento = 1;
irfDevolucaoCred = 2;
irfDevolucaoDin = 3;
irfDebitado = 4;
irfCredUsado = 5;
irfDescontos = 6;
irfCancelamentos = 7;
irfVendasRec = 8;
irfVendasRecPend = 9;
irfDebPagos = 10;
irfTrocoCred = 11;
irfTotalRec = 12;
irfSaldoInicial = 13;
irfTotalRec2 = 14;
irfValorDev = 15;
irfDinAdd = 16;
irfDinRem = 17;
irfSaldoFinal = 18;
irfSaldoInformado = 19;
irfQuebraCaixa = 20;
implementation
uses
ncClassesBase, ncErros, Graphics, ncDebug, IdMultipartFormData, nexUrls,
ncHttp;
// START resource string wizard section
{$R *.dfm}
resourcestring
rsInfoTroco = '* Total recebido com vendas foi de %s mas houve troco de %s.';
rsTroco = 'Troco';
rsTotal = 'Total';
const
sqlCanc = 'select Count(ID) as Quant, Sum(Total) as Total from tran where (cancelado=true) and %s';
sqlDev =
'select OpDevValor, Count(ID) as Quant, Sum(Total) as Total from Tran where (tipo=18) and (cancelado<>true) and %s group by OpDevValor';
sqlDesc = 'select Count(ID) as Quant, Sum(Desconto) as Total from tran where (cancelado<>true) and (desconto>0.001) and %s';
sqlVC =
'select P.Categoria, Sum(I.Total) as Total, Sum(I.Desconto) as Desconto, Sum(I.Quant) as Quant from MovEst I, Produto P'+
' WHERE %s and '+
' (P.ID=I.Produto) and '+
' (I.TipoTran=4) and '+
' ((not Cancelado) or (Cancelado is Null)) and '+
' ((not FidResgate) or (FidResgate is null)) '+
' GROUP BY P.Categoria';
sqlPagEsp =
'select Especie, TipoTran, Sum(Valor) as TotalValor, Sum(Troco) as TotalTroco from PagEspecies '+
'where %s and ((Cancelado is Null) or (not Cancelado)) '+
'group by Especie, TipoTran Order by Especie';
sqlRFFat =
'select Tipo, Count(*) as Qtd, Sum(TotLiq) as TotLiq from Tran '+
'where %s and ((Cancelado is Null) or (not Cancelado)) ' +
'group by Tipo';
sqlRFPag =
'select Tipo, Count(*) as Qtd, Sum(Credito) as Credito, Sum(Debito) as Debito, Sum(Pago) as Pago, Sum(CreditoUsado) as CreditoUsado, Sum(Troco) as Troco '+
'from tran where %s and ((Cancelado is Null) or (not Cancelado)) and (CaixaPag=Caixa) group by Tipo';
sqlRFPagPend =
'select Tipo, Count(*) as Qtd, Sum(Credito) as Credito, Sum(Debito) as Debito, Sum(Pago) as Pago, Sum(CreditoUsado) as CreditoUsado, Sum(Troco) as Troco '+
'from tran where %s and ((Cancelado is Null) or (not Cancelado)) and (CaixaPag<>Caixa) group by Tipo';
sqlME =
'select produto, tipotran, fidresgate, sum(quant) as quant, sum(total) as total, sum(pago) as pago, sum(desconto) as desconto, sum(custou * quant) as custot from movest '+
'where %s and (cancelado <> true) group by produto, tipotran, fidresgate';
function InitTran(aDB: TnxDatabase;
const aTables : array of TnxTable;
aWith : Boolean): Boolean;
var I : Integer;
begin
Result := False;
if aDB.InTransaction then Exit;
I := 10;
while I > 0 do begin
try
if aWith then
aDB.StartTransactionWith(aTables)
else
aDB.StartTransaction;
I := 0;
except
Dec(I);
Random(500);
end
end;
Result := True;
end;
function TdmCaixa.AbreCaixa(aFunc: String; aSaldo: Currency; aManterSaldo: Boolean; var aNumCx: Integer): Integer;
var SaldoAnt: Currency;
begin
tCaixa.Active := True;
tTran.IndexName := 'IID'; // do not localize
tTran.Open;
tITran.Open;
InitTran(nxDB, [tCaixa, tTran, tITran], True);
try
tCaixa.IndexName := 'IAberto'; // do not localize
try
if tCaixa.FindKey([True]) then begin
nxDB.Rollback;
Result := ncerrJaTemCaixaAberto;
Exit;
end;
finally
tCaixa.IndexName := 'IID'; // do not localize
end;
if aManterSaldo then begin
if tCaixa.IsEmpty then
SaldoAnt := 0
else begin
tCaixa.Last;
SaldoAnt := tCaixaTotalFinal.Value + tCaixaSaldoAnt.Value + tCaixaSupr.Value - tCaixaSangria.Value;
end;
end else
SaldoAnt := aSaldo;
tCaixa.Insert;
tCaixaAbertura.Value := Now;
tCaixaAberto.Value := True;
tCaixaUsuario.Value := aFunc;
if aManterSaldo or gConfig.PedirSaldoI then
tCaixaSaldoAnt.Value := SaldoAnt;
tCaixaEstSyncOk.Value := False;
tCaixa.Post;
aNumCx := tCaixaID.Value;
Result := 0;
nxDB.Commit;
except
on e: exception do begin
nxDB.Rollback;
Result := ncerrExcecaoNaoTratada_TdmCaixa_AbreCaixa;
DebugMsgEsp(Self, E.Message, False, True);
end;
end;
end;
procedure TdmCaixa.AbreConn;
begin
nxDB.AliasPath := '';
nxDB.AliasName := 'NexCafe'; // do not localize
nxDB.Active := True;
tCli.Open;
tProd.Open;
tCaixa.Open;
tPostMS.Open;
end;
procedure TdmCaixa.AddItemRF(aItem: Integer; aDescr: String; aValor: Currency; aAddZero: Boolean = True);
begin
if (aValor<0.01) and (not aAddZero) then Exit;
mtTot.Append;
mtTotDescricao.Value := aDescr;
if aItem<>99 then
mtTotValor.Value := aValor;
mtTotItem.Value := aItem;
mtTot.Post;
if (aItem<>99) then
case aItem of
irfFaturamento..irfCancelamentos: begin
mtRF1.Append;
mtRF1Descricao.Value := aDescr;
mtRF1Total.Value := aValor;
mtRF1Item.Value := aItem;
mtRF1.Post
end;
irfVendasRec..irfTotalRec: begin
mtRF2.Append;
mtRF2Descricao.Value := aDescr;
mtRF2Total.Value := aValor;
mtRF2Item.Value := aItem;
mtRF2.Post
end;
irfSaldoInicial..irfQuebraCaixa: begin
mtRF3.Append;
mtRF3Descricao.Value := aDescr;
mtRF3Total.Value := aValor;
mtRF3Item.Value := aItem;
mtRF3.Post
end;
end;
end;
procedure TdmCaixa.DataModuleCreate(Sender: TObject);
begin
nxTCPIP.Port := 17200;
TemSupSan := False;
FImpTran := False;
TotalTroco := 0;
FCXRange := TncCaixas.Create;
end;
procedure TdmCaixa.DataModuleDestroy(Sender: TObject);
begin
FCXRange.Free;
end;
procedure TdmCaixa.EmailCaixa(aID: Integer);
begin
Processa(aID, nil);
GeraEmailFechamento;
end;
procedure TdmCaixa.ExportaCaixa(aID: Integer; aArquivo: String);
begin
ExportaCaixaKite(aID, aArquivo, nil);
end;
procedure TdmCaixa.ExportaCaixaKite(aID: Integer; aArquivo: String;
slPar: tStrings);
var sIdent: String;
begin
DebugMsg('TdmCaixa.ExportaCaixa - aID: ' + IntToStr(aID) + ' - aArquivo: ' + aArquivo); // do not localize
Processa(aID, nil);
DebugMsg('TdmCaixa.ExportaCaixa - 2'); // do not localize
tUsuario.Active := True;
if slPar<>nil then begin
slPar.Add('timestamp_de_abertura='+formatDateTime('YYYY-MM-DD HH:NN:SS', tCaixaAbertura.Value)); // do not localize
slPar.Add('timestamp_de_fechamento='+formatDateTime('YYYY-MM-DD HH:NN:SS', tCaixaFechamento.Value)); // do not localize
slPar.Add('username_funcionario='+tCaixaUsuario.Value); // do not localize
slPar.Add('numero_do_caxa='+tCaixaID.AsString); // do not localize
slPar.Add('conta_da_loja='+gConfig.Conta); // do not localize
if tUsuario.FindKey([tCaixaUsuario.Value]) then
slPar.Add('nome_funcionario='+tUsuarioNome.Value) else // do not localize
slPar.Add('nome_funcionario='); // do not localize
if Trim(gConfig.EmailIdent)>'' then
sIdent:= gConfig.EmailIdent + ' - ' else
sIdent:= '';
slPar.Add('subject='+sIdent+rsCaixa+' #' + tCaixaID.AsString+ // do not localize
' - ' + tCaixaAbertura.AsString +
' a ' + tCaixaFechamento.AsString);
end;
pdfExp.FileName := aArquivo;
DebugMsg('TdmCaixa.ExportaCaixa - 3'); // do not localize
pdfExp.DefaultPath := '';
DebugMsg('TdmCaixa.ExportaCaixa - 4'); // do not localize
repCaixa.PrepareReport;
DebugMsg('TdmCaixa.ExportaCaixa - 5'); // do not localize
repCaixa.Export(PDFexp);
DebugMsg('TdmCaixa.ExportaCaixa - 6'); // do not localize
end;
function TdmCaixa.FechaCaixa(aFunc: String; aSaldo: Currency; aNumCx: Integer; aReproc: Boolean): Integer;
var
SAnt: Currency;
SL : TStrings;
begin
InitTran(nxDB, [], False);
try
tCaixa.IndexName := 'IID'; // do not localize
if not tCaixa.FindKey([aNumCx]) then begin
nxDB.Rollback;
Result := ncerrItemInexistente;
Exit;
end;
SAnt := 0;
if aReproc then begin
if tCaixaAberto.Value then begin
nxDB.Rollback;
Raise ENexCafe.Create(SncDMCaixa_OReprocessamentoDeCaixaSóPodeSer);
end;
if gConfig.ManterSaldoCaixa then begin
tCaixa.Prior;
if (tCaixaID.Value < aNumCx) then
if not tCaixaSaldoF.IsNull then
SAnt := tCaixaSaldoF.Value else
SAnt := tCaixaTotalFinal.Value + tCaixaSaldoAnt.Value + tCaixaSupr.Value - tCaixaSangria.Value;
tCaixa.FindKey([aNumCx]);
end else
SAnt := tCaixaSaldoAnt.Value;
end else
if not tCaixaAberto.Value then begin
nxDB.Rollback;
Result := ncerrCaixaJaFoiFechado;
Exit;
end;
if (not aReproc) then begin
if (not PodeFechar) then begin
Result := ncerrNFCeImpedeFecharCaixa;
nxDB.Rollback;
Exit;
end;
if TemVendaHomo then begin
Result := ncerrNFCeCancelarModoHomo;
nxDB.Rollback;
Exit;
end;
end;
{ if aReproc then begin
qCorr.Active := False;
qCorr.ParamByName('Caixa').AsInteger := aNumCx; // do not localize
qCorr.ExecSQL;
qCorr2.Active := False;
qCorr2.SQL.Text := 'update itran '+ // do not localize
'set caixa = ' + IntToStr(aNumCx) + // do not localize
' where tran in (select id from tran where caixa = ' + IntToStr(aNumCx) +')'; // do not localize
qCorr2.ExecSQL;
qCorr2.Active := False;
qCorr2.SQL.Text := 'update movest '+ // do not localize
'set caixa = ' + IntToStr(aNumCx) + // do not localize
' where tran in (select id from tran where caixa = ' + IntToStr(aNumCx) +')'; // do not localize
qCorr2.ExecSQL;
end;}
qFecha.Params[0].AsInteger := aNumCx; // do not localize
qFecha.Active := True;
tCaixa.Edit;
tCaixaCancelamentos.Value := 0;
tCaixaDescontos.Value := 0;
tCaixaTotalFinal.Value := 0;
tCaixaSangria.Value := 0;
tCaixaSupr.Value := 0;
if aReproc then
tCaixaSaldoAnt.Value := SAnt;
while not qFecha.Eof do begin
if qFechaCancelado.Value then
tCaixaCancelamentos.Value := tCaixaCancelamentos.Value + qFechaTotal.Value
else
case qFechaTipo.Value of
trCaixaEnt : tCaixaSupr.Value := tCaixaSupr.Value + qFechaTotal.Value;
trCaixaSai : tCaixaSangria.Value := tCaixaSangria.Value + qFechaTotal.Value;
trEstDevolucao : tCaixaTotalFinal.Value := tCaixaTotalFinal.Value - qFechaTotal.Value;
trEstCompra,
trEstTransfEnt,
trEstOutEntr,
trEstTransf,
trEstSaida,
trEstEntrada,
trCorrDataCx : ;
else
tCaixaTotalFinal.Value := tCaixaTotalFinal.Value + (qFechaPago.Value-qFechaTroco.Value);
end;
tCaixaDescontos.Value := tCaixaDescontos.Value + qFechaDesconto.Value;
qFecha.Next;
end;
tCaixaAberto.Value := False;
if aReproc then
tCaixaReproc.Value := Now else
tCaixaFechamento.Value := Now;
tCaixaEstSyncOk.Value := True;
if gConfig.PedirSaldoF then begin
if (not aReproc) then
tCaixaSaldoF.Value := aSaldo;
tCaixaQuebra.Value :=
tCaixaSaldoF.Value -
(tCaixaTotalFinal.Value + tCaixaSaldoAnt.Value + tCaixaSupr.Value - tCaixaSangria.Value);
end;
tCaixa.Post;
Result := 0;
nxDB.Commit;
Self.GeraEmailFechamento;
except
on e: exception do begin
nxDB.Rollback;
DebugMsgEsp('TdmCaixa.FechaCaixa - Exception: '+E.Message, False, True);
Result := ncerrExcecaoNaoTratada_TdmCaixa_FechaCaixa;
end;
end;
end;
function PosDelim(S: String): Integer;
begin
for Result := 1 to Length(S) do
if S[Result] in [',', ';'] then Exit;
Result := 0;
end;
procedure ObtemDestinos(aDestino: TStrings);
var
P, I : Integer;
S : String;
SL : TStrings;
begin
SL := TStringList.Create;
try
S := aDestino.Text;
SL.Text := '';
for I := 0 to aDestino.Count - 1 do begin
S := aDestino[I];
while Length(S)>0 do begin
P := PosDelim(S);
if P>0 then begin
SL.Add(Trim(Copy(S, 1, P-1)));
Delete(S, 1, P);
end else begin
if Trim(S)>'' then
SL.Add(S);
S := '';
end;
end;
end;
aDestino.Text := SL.Text;
finally
SL.Free;
end;
end;
procedure TdmCaixa.GeraEmailFechamento;
var
S, sDest: String;
I : Integer;
slPar, slDest : TStrings;
ms : TIdMultiPartFormDataStream;
begin
if not gConfig.EmailEnviarCaixa then Exit;
tPostMS.Open;
slPar := TStringList.Create;
slDest := TStringList.Create;
ms := TidMultipartFormDataStream.Create;
try
S := ExtractFilePath(ParamStr(0)) + 'Email\Caixa' + tCaixaID.AsString + '.pdf';
ExportaCaixaKite(tCaixaID.Value, S, slPar);
slDest.Text := gConfig.EmailDestino;
ObtemDestinos(slDest);
sDest := '';
for I := 0 to slDest.Count-1 do begin
if I>0 then sDest := sDest + ', ';
sDest := sDest + slDest[i];
end;
slPar.Add('destinatarios='+sDest);
for i := 0 to slPar.Count-1 do
ms.AddFormField(slPar.Names[i], slPar.ValueFromIndex[i]);
ms.AddFile('pdf', S, 'application/pdf');
ms.Seek(0,0);
with ThttpThreadPost.Create(gUrls.Url('kapi_emailcaixa'), ms, 10) do Resume;
ms := nil;
finally
if ms<>nil then ms.Free;
slPar.Free;
slDest.Free;
end;
end;
procedure TdmCaixa.MostrarCaixa(aID: Integer);
begin
Processa(aID, nil);
repCaixa.ShowReport;
end;
procedure TdmCaixa.mtEstCalcFields(DataSet: TDataSet);
begin
mtEstEntradasTot.Value := mtEstEntradas.Value + mtEstCompras.Value + mtEstDevolucoes.Value;
end;
function GetCor(aItem: Integer): TColor;
begin
case aItem of
irfCancelamentos, irfDescontos, irfQuebraCaixa : Result := clRed;
irfSaldoFinal, irfSaldoInformado : Result := clBlue;
else
Result := clBlack;
end;
end;
function GetBold(aItem: Integer): Boolean;
begin
case aItem of
irfTotalRec,
irfSaldoFinal,
irfSaldoInformado,
irfQuebraCaixa,
irfFaturamento : Result := True;
else
Result := False;
end;
end;
procedure TdmCaixa.mtRF1CalcFields(DataSet: TDataSet);
begin
mtRF1Bold.Value := GetBold(mtRF1Item.Value);
mtRF1Cor.Value := GetCor(mtRF1Item.Value);
end;
procedure TdmCaixa.mtRF2CalcFields(DataSet: TDataSet);
begin
mtRF2Bold.Value := GetBold(mtRF2Item.Value);
mtRF2Cor.Value := GetCor(mtRF2Item.Value);
end;
procedure TdmCaixa.mtRF3CalcFields(DataSet: TDataSet);
begin
mtRF3Bold.Value := GetBold(mtRF3Item.Value);
mtRF3Cor.Value := GetCor(mtRF3Item.Value);
end;
function V2Casas(C: Currency): Currency;
begin
Result := Int(C * 100) / 100;
end;
function TdmCaixa.PodeFechar: Boolean;
begin
{- Cancelamento: Evitar fechamento de caixa ou Processar imediatamente
- Impedir fechamento do caixa quando houver rejeição de NFC-e
- Impedir fechamentp de cx com nfce por transmitir
- Contigencia nao fechar cx}
Result := False;
tNFConfig.Open;
tAuxNFE.Open;
tAuxNFE.IndexName := 'IStatusCancNumSeq';
tAuxTran.Open;
if tAuxNFE.FindKey([statuscanc_nfe_processarnfe]) then Exit;
if tAuxNFE.FindKey([statuscanc_nfe_processatran]) then Exit;
tAuxTran.IndexName := 'ICanceladoStatusNFE';
if tAuxTran.FindKey([False, nfetran_transmitir]) then Exit;
if tAuxTran.FindKey([False, nfetran_contingencia]) then Exit;
if tAuxTran.FindKey([False, nfetran_erro]) then Exit;
Result := True;
end;
function Asterisco(I: integer): String;
begin
Result := '';
while Length(Result)<I do Result := Result + '*';
end;
function TdmCaixa.Processa(aID: Integer; aCXRange: TncCaixas): Currency;
var
Q: TnxQuery;
I, Num, IDCli : Integer;
CustoU, TotFinal, PercDesc, Desc, DescT : Double;
S: String;
Incluir: Boolean;
PagDet, PagReg : Integer;
ValorI : Currency;
qItem: Integer;
DataI, DataF: TDateTime;
SaldoI, SaldoF : Extended;
totVendas, totDev, totSupr, totSangria: Currency;
begin
Fillchar(DRF, SizeOf(DRF), 0);
Result := 0;
mtRF1.EmptyTable;
mtRF2.EmptyTable;
mtRF3.EmptyTable;
mtObs.Active := False;
mtObs.Active := True;
qVC.Active := False;
qDesc.Active := False;
qCanc.Active := False;
qRFFat.Active := False;
qRFPag.Active := False;
qRFPagPend.Active := False;
// qCliValor.Active := False;
mtEst.Active := False;
mtEst.Active := True;
mtTot.Active := False;
mtTot.Active := True;
tCaixa.Open;
tProd.Open;
FillChar(drf, SizeOf(drf), 0);
Num := aID;
if Num > 0 then begin
tCaixa.Locate('ID', Num, []); // do not localize
FCXRange.DataI := tCaixaAbertura.Value;
if tCaixaAberto.Value then
FCXRange.DataF := Date+1 else
FCXRange.DataF := tCaixaFechamento.Value;
FCXRange.StartNewRange(Num, Num);
if Trim(tCaixaObs.Value)>'' then begin
mtObs.Append;
mtObsObs.Value := tCaixaObs.Value;
mtObs.Post;
end;
end else
FCXRange.Assign(aCXRange);
tRepProd.Open;
tRepProd.SetRange([True], [True]);
qRepTran.Active := False;
qRepTran.SQL.Text := 'select * from Tran'; // do not localize
if gConfig.cce(cceTodasTran) then
S := 'all'
else begin
if gConfig.cce(cceTransacoesCanc) then
S := '(Cancelado=True)' else // do not localize
S := '';
if gConfig.cce(cceTransacoesDesc) then
if S>'' then
S := '(Cancelado=True) or (Desconto>0)' else // do not localize
S := '(Desconto>0)'; // do not localize
if gConfig.cce(cceTransacoesObs) then
if S>'' then
S := S + ' or (Trim(Obs)>'+QuotedStr('')+')' else // do not localize
S := '(Trim(Obs)>'+QuotedStr('')+')'; // do not localize
end;
if (gConfig.EmailEnviarCaixa) and (S>'') then begin
FImpTran := True;
if S='all' then
S := 'where (Caixa='+IntToStr(Num)+') order by ID' else
S := 'where (Caixa='+IntToStr(Num)+') and ('+S+') order by ID'; // do not localize
qRepTran.SQL.Text := 'select * from Tran ' + S; // do not localize
qRepTran.Open;
end else begin
// qRepTran.Open;
FImpTran := False;
end;
qDev.SQL.Text := Format(sqlDev, [FCXRange.SQL]);
qDev.Active := True;
qCanc.SQL.Text := Format(sqlCanc, ['('+FCXRange.SQL+' or '+FCXRange.SQL('CaixaPag')+')']);
qCanc.Active := True;
qDesc.SQL.Text := Format(sqlDesc, ['('+FCXRange.SQL+' or '+FCXRange.SQL('CaixaPag')+')']);
qDesc.Active := True;
qVC.SQL.Text := Format(sqlVC, [FCXRange.SQL]);
qVC.Active := True;
qPagEsp.Active := False;
qPagEsp.SQL.Text := Format(sqlPagEsp, [FCXRange.SQL]);
qPagEsp.Active := True;
qPagEsp.First;
TotalTroco := qPagEsp.RecordCount;
if TotalTroco=0 then TotalTroco := 1;
TotalTroco := 0;
while not qPagEsp.Eof do begin
TotalTroco := TotalTroco + qPagEspTotalTroco.Value;
qPagEsp.Next;
end;
qPagEsp.First;
mtPagEsp.Active := False;
mtPagEsp.Active := True;
totVendas := 0;
totDev := 0;
totSupr := 0;
totSangria := 0;
mtMPObs.Active := False;
mtMPObs.Active := True;
qPagEsp.First;
while not qPagEsp.Eof do begin
if mtPagEsp.FindKey([qPagEspEspecie.Value]) then
mtPagEsp.Edit else
mtPagEsp.Append;
mtPagEspNomeEsp.Value := qPagEspNomeEspecie.Value;
mtPagEspEspecie.Value := qPagEspEspecie.Value;
case qPagEspTipoTran.Value of
trEstVenda, trPagDebito : begin
mtPagEspVendas.Value := mtPagEspVendas.Value + qPagEspTotalF.Value;
mtPagEspTroco.Value := mtPagEspTroco.Value + qPagEspTotalTroco.Value;
mtPagEspNomeEsp.Value := qPagEspNomeEspecie.Value;
totVendas := totVendas + qPagEspTotalF.Value;
end;
trEstDevolucao : begin
mtPagEspDev.Value := qPagEspTotalValor.Value;
totDev := totDev + mtPagEspDev.Value;
end;
trCaixaEnt : begin
mtPagEspSupr.Value := qPagEspTotalValor.Value;
totSupr := totSupr + mtPagEspSupr.Value;
end;
trCaixaSai : begin
mtPagEspSangria.Value := qPagEspTotalValor.Value;
totSangria := totSangria + mtPagEspSangria.Value;
end;
end;
mtPagEspTotal.Value := mtPagEspVendas.Value + mtPagEspDev.Value + mtPagEspSupr.Value + mtPagEspSangria.Value;
if mtPagEspTroco.Value>0 then
mtPagEspObs.Value := Format(rsInfoTroco, [CurrencyToStr(mtPagEspVendas.Value+mtPagEspTroco.Value),
CurrencyToStr(mtPagEspTroco.Value)]);
mtPagEsp.Post;
qPagEsp.Next;
end;
mtPagEsp.First;
while not mtPagEsp.Eof do begin
if mtPagEspTroco.Value>0 then begin
mtMPObs.Append;
mtMPObsNomeEsp.Value := mtPagEspNomeEsp.Value;
mtMPObsEspecie.Value := mtPagEspEspecie.Value;
mtMPObsTotal.Value := mtPagEspTotal.Value + mtPagEspTroco.Value;
mtMPObsTroco.Value := mtPagEspTroco.Value;
mtMPObsAsterisco.Value := Asterisco(mtMPObs.RecordCount+1);
mtMPObs.Post;
mtPagEsp.Edit;
mtPagEspNomeEsp.Value := mtMPObsAsterisco.Value + ' ' + mtPagEspNomeEsp.Value;
mtPagEsp.Post;
end;
mtPagEsp.Next;
end;
mtMPObs.First;
if mtPagEsp.RecordCount>1 then begin
mtPagEsp.Append;
mtPagEspEspecie.Value := 65535;
mtPagEspNomeEsp.Value := UpperCase(rsTotal);
mtPagEspVendas.Value := totVendas;
mtPagEspDev.Value := totDev;
mtPagEspSupr.Value := totSupr;
mtPagEspSangria.Value := totSangria;
mtPagEspTotal.Value := totVendas + totDev + totSupr + totSangria;
mtPagEsp.Post;
end;
mtPagEsp.First;
qRFFat.Active := False;
qRFFat.SQL.Text := Format(sqlRFFat, [FCXRange.SQL]);
qRFFat.Active := True;
qRFFat.First;
qRFPag.Active := False;
qRFPag.SQL.Text := Format(sqlRFPag, [FCXRange.SQL('CaixaPag')]);
qRFPag.Active := True;
qRFPag.First;
qRFPagPend.Active := False;
qRFPagPend.SQL.Text := Format(sqlRFPagPend, [FCXRange.SQL('CaixaPag')]);
qRFPagPend.Active := True;
qRFPagPend.First;
qME.Active := False;
qME.SQL.Text := Format(sqlME, [FCXRange.SQL]);
qME.Active := True;
qDev.First;
while not qDev.Eof do
begin
case qDevOpDevValor.Value of
0 : begin
DRF[irfDevolucaoCred].drfValor := DRF[irfDevolucaoCred].drfValor + qDevTotal.Value;
DRF[irfDevolucaoCred].drfQtd := DRF[irfDevolucaoCred].drfQtd + qDevQuant.Value;
end;
1 : begin
DRF[irfDevolucaoDin].drfValor := DRF[irfDevolucaoDin].drfValor + qDevTotal.Value;
DRF[irfDevolucaoDin].drfQtd := DRF[irfDevolucaoDin].drfQtd + qDevQuant.Value;
end;
end;
qDev.next;
end;
while not qRFFat.Eof do begin
case qRFFatTipo.Value of
trEstVenda : begin
drf[irfFaturamento].drfQtd := drf[irfFaturamento].drfQtd + qRFFatQtd.Value;
drf[irfFaturamento].drfValor := drf[irfFaturamento].drfValor + qRFFatTotLiq.Value;
end;
trCaixaEnt : begin
drf[irfDinAdd].drfQtd := qRFFatQtd.Value;
drf[irfDinAdd].drfValor := qRFFatTotLiq.Value;
end;
trCaixaSai : begin
drf[irfDinRem].drfQtd := qRFFatQtd.Value;
drf[irfDinRem].drfValor := qRFFatTotLiq.Value;
end;
end;
qRFFat.Next;
end;
while not qRFPag.Eof do begin
case qRFPagTipo.Value of
trEstVenda :
drf[irfVendasRec].drfValor := drf[irfVendasRec].drfValor + (qRFPagPago.Value - qRFPagTroco.Value - qRFPagCredito.Value);
trPagDebito : begin
drf[irfDebPagos].drfQtd := qRFPagQtd.Value;
drf[irfDebPagos].drfValor := qRFPagPago.Value;
end;
end;
drf[irfTrocoCred].drfValor := drf[irfTrocoCred].drfValor + qRFPagCredito.Value;
drf[irfDebitado].drfValor := drf[irfDebitado].drfValor + qRFPagDebito.Value;
drf[irfCredUsado].drfValor := drf[irfCredUsado].drfValor + qRFPagCreditoUsado.Value;
qRFPag.Next;
end;
while not qRFPagPend.Eof do begin
case qRFPagPendTipo.Value of
trEstVenda:
drf[irfVendasRecPend].drfValor := drf[irfVendasRecPend].drfValor + (qRFPagPendPago.Value - qRFPagPendTroco.Value - qRFPagPendCredito.Value);
trPagDebito : begin
drf[irfDebPagos].drfQtd := qRFPagPendQtd.Value;
drf[irfDebPagos].drfValor := qRFPagPendPago.Value;
end;
end;
drf[irfTrocoCred].drfValor := drf[irfTrocoCred].drfValor + qRFPagPendCredito.Value;
drf[irfDebitado].drfValor := drf[irfDebitado].drfValor + qRFPagPendDebito.Value;
drf[irfCredUsado].drfValor := drf[irfCredUsado].drfValor + qRFPagPendCreditoUsado.Value;
qRFPagPend.Next;
end;
{ dsEst.Dataset := nil;
try
tProd.First;
while not tProd.Eof do begin
tME.SetRange([tProdID.Value, CaixaI], [tProdID.Value, CaixaF]);
if not (tME.Eof and tME.Bof) then begin
mtEst.Append;
mtEstID.Value := tProdID.Value;
mtEstDescricao.Value := tProdDescricao.Value;
tME.First;
DataI := 0;
SaldoI := 0;
DataF := 0;
SaldoF := 0;
while not tME.Eof do begin
if (DataI=0) or (tMEDataHora.Value<DataI) then begin
DataI := tMEDataHora.Value;
SaldoI := tMEEstoqueAnt.Value;
end;
if (DataF=0) or (tMEDataHora.Value>DataF) then begin
DataF := tMEDataHora.Value;
SaldoF := tMESaldoFinal.Value;
end;
case tMETipoTran.Value of
trEstCompra : mtEstCompras.Value := mtEstCompras.Value + tMEQuant.Value;
trEstEntrada : mtEstEntradas.Value := mtEstEntradas.Value + tMEQuant.Value;
trEstSaida : mtEstSaidas.Value := mtEstSaidas.Value + tMEQuant.Value;
else
if tMEFidResgate.Value then begin
mtEstFidResg.Value := mtEstFidResg.Value + tMEQuant.Value;
end else begin
mtEstVendas.Value := mtEstVendas.Value + tMEQuant.Value;
mtEstValorVendas.Value := mtEstValorVendas.Value + tMETotal.Value - tMEDesconto.Value;
CustoU := tMECustoU.Value;
if (CustoU < 0.00009) then
CustoU := tProdCustoUnitario.Value;
mtEstLucro.Value := mtEstLucro.Value + (tMETotal.Value - (CustoU * tMEQuant.Value) - tMEDesconto.Value);
end;
end;
tME.Next;
end;
mtEstSaldoInicial.Value := SaldoI;
mtEstSaldoFinal.Value := SaldoF;
mtEst.Post;
end;
tProd.Next;
end;
finally
dsEst.Dataset := mtEst;
end; }
dsEst.Dataset := nil;
try
qME.First;
while not qME.Eof do begin
if not mtEst.FindKey([qMEProduto.Value]) then begin
mtEst.Append;
mtEstID.Value := qMEProduto.Value;
if tProd.Locate('ID', qMEProduto.Value, []) then
mtEstDescricao.Value := tProdDescricao.Value else
mtEstDescricao.Value := '## PRODUTO FOI APAGADO';
if tProd.FindKey([qMEProduto.Value]) and (not tProdNaoControlaEstoque.Value) then begin
SaldoIF(qMEProduto.Value, SaldoI, SaldoF);
mtEstSaldoInicial.Value := SaldoI;
mtEstSaldoFinal.Value := SaldoF;
end;
end else
mtEst.Edit;
case qMETipoTran.Value of
trEstCompra : mtEstCompras.Value := mtEstCompras.Value + qMEQuant.Value;
trEstDevolucao : mtEstDevolucoes.Value := mtEstDevolucoes.Value + qMEQuant.Value;
trEstEntrada : mtEstEntradas.Value := mtEstEntradas.Value + qMEQuant.Value;
trEstSaida : mtEstSaidas.Value := mtEstSaidas.Value + qMEQuant.Value;
else
if qMEFidResgate.Value then begin
mtEstFidResg.Value := mtEstFidResg.Value + qMEQuant.Value;
end else begin
mtEstVendas.Value := mtEstVendas.Value + qMEQuant.Value;
mtEstValorVendas.Value := mtEstValorVendas.Value + qMETotal.Value - qMEDesconto.Value;
mtEstLucro.Value := mtEstLucro.Value + (qMETotal.Value - qMECustoT.Value - qMEDesconto.Value);
end;
end;
mtEst.Post;
qME.Next;
end;
finally
dsEst.Dataset := mtEst;
end;
PagDet := 0;
PagReg := 0;
ValorI := 0;
mtTot.Open;
mtTot.EmptyTable;
drf[irfTotalRec].drfValor := drf[irfVendasRec].drfValor +
drf[irfVendasRecPend].drfValor +
drf[irfDebPagos].drfValor +
drf[irfTrocoCred].drfValor;
drf[irfTotalRec2].drfValor := drf[irfTotalRec].drfValor;
drf[irfValorDev].drfValor := drf[irfDevolucaoDin].drfValor;
if (Num>0) then
drf[irfSaldoFinal].drfValor := drf[irfTotalRec].drfValor -
drf[irfDevolucaoDin].drfValor +
tCaixaSaldoAnt.Value +
drf[irfDinAdd].drfValor -
drf[irfDinRem].drfValor;
AddItemRF(irfFaturamento, SncDMCaixa_Faturamento, drf[irfFaturamento].drfValor);
AddItemRF(irfDevolucaoDin, SncDMCaixa_DevolucaoDin, drf[irfDevolucaoDin].drfValor, False);
AddItemRF(irfDevolucaoCred, SncDMCaixa_DevolucaoCred, drf[irfDevolucaoCred].drfValor, False);
AddItemRF(99, '', 0);
AddItemRF(irfDebitado, SncDMCaixa_Debitado, drf[irfDebitado].drfValor, False);
AddItemRF(irfCredUsado, SncDMCaixa_CredUsado, drf[irfCredUsado].drfValor, False);
AddItemRF(irfDescontos, SncDMCaixa_Descontos, qDescTotal.Value, False);
AddItemRF(irfCancelamentos, SncDMCaixa_Cancelamentos, qCancTotal.Value, False);
AddItemRF(99, '', 0);
AddItemRF(99, SncDMCaixa_ValoresRecebidos, 0);
AddItemRF(irfVendasRec, SncDMCaixa_Vendas, drf[irfVendasRec].drfValor);
AddItemRF(irfVendasRecPend, SncDMCaixa_VendasRecPend, drf[irfVendasRecPend].drfValor, false);
AddItemRF(irfDebPagos, SncDMCaixa_DebPagos, drf[irfDebPagos].drfValor, False);
AddItemRF(irfTrocoCred, SncDMCaixa_TrocoCreditado, drf[irfTrocoCred].drfValor, false);
AddItemRF(irfTotalRec, SncDMCaixa_TotalRec, drf[irfTotalRec].drfValor);
AddItemRF(99, '', 0);
if (Num>0) then AddItemRF(99, SncDMCaixa_SaldoCaixa, 0);
if (Num>0) then AddItemRF(irfSaldoInicial, SncDMCaixa_SaldoInicial, tCaixaSaldoAnt.Value);
if (Num>0) then AddItemRF(irfTotalRec2, SncDMCaixa_ValoresRecebidos, drf[irfTotalRec2].drfValor);
AddItemRF(irfValorDev, SncDMCaixa_ValoresDevolvidos, drf[irfValorDev].drfValor, False);
AddItemRF(irfDinAdd, '+ '+SncDMCaixa_DinheiroAdicionado, drf[irfDinAdd].drfValor, false);
AddItemRF(irfDinRem, '- '+SncDMCaixa_DinheiroRetirado, drf[irfDinRem].drfValor, false);
if (Num>0) then
begin
AddItemRF(irfSaldoFinal, SncDMCaixa_SaldoFinal, drf[irfSaldoFinal].drfValor);
if (not tCaixaAberto.Value) and gConfig.PedirSaldoF then begin
AddItemRF(irfSaldoInformado, SncDMCaixa_SaldoInformado, tCaixaSaldoF.Value);
AddItemRF(irfQuebraCaixa, SncDMCaixa_QuebraDeCaixa, tCaixaQuebra.Value, False);
end;
end;
Result := drf[irfSaldoFinal].drfValor;
end;
procedure TdmCaixa.qPagEspCalcFields(DataSet: TDataSet);
begin
qPagEspTotalF.Value := qPagEspTotalValor.Value - qPagEspTotalTroco.Value;
end;
procedure TdmCaixa.qRepTranCalcFields(DataSet: TDataSet);
function NaoSim(B: Boolean): String;
begin
if B then
Result := rsSim else
Result := rsNao;
end;
begin
qRepTranNomeTipo.Value := TipoTranToStr(qRepTranTipo.Value);
qRepTranCancFid.Value := NaoSim(qRepTranCancelado.Value) + ' / ' + NaoSim(qRepTranFidResgate.Value);
end;
procedure TdmCaixa.qVCCalcFields(DataSet: TDataSet);
begin
qVCTotFinal.Value := qVCTotal.Value - qVCDesconto.Value;
end;
function TdmCaixa.repCaixa: TfrxReport;
begin
if LinguaPT then
Result := repCaixa_pt
else
if SameText(SLingua, 'es') then
Result := repCaixa_es
else
Result := repCaixa_en;
end;
procedure TdmCaixa.repCaixa_ptBeforePrint(Sender: TfrxReportComponent);
begin
if SameText(Sender.Name, 'srTran') then // do not localize
Sender.Visible := FImpTran;
if SameText(Sender.Name, 'srMovEstoque') then // do not localize
Sender.Visible := gConfig.cce(cceMovEstoque);
if SameText(Sender.Name, 'srEstoqueAbaixoMin') then // do not localize
Sender.Visible := gConfig.cce(cceEstoqueAbaixoMin);
if SameText(Sender.Name, 'Footer2') then // do not localize
Sender.Visible := (Trim(tCaixaObs.Value)>'');
end;
procedure TdmCaixa.SaldoIF(aProduto: Cardinal; var aSaldoI, aSaldoF: Extended);
begin
tAuxME.Active := True;
tAuxME.SetRange([aProduto, FCXRange.DataI], [aProduto, FCXRange.DataF]);
tAuxME.Filter := FCXRange.SQL;
tAuxME.Filtered := True;
if tAuxME.IsEmpty then begin
aSaldoI := 0;
aSaldoF := 0;
Exit;
end;
tAuxME.First;
aSaldoI := tAuxMEEstoqueAnt.Value;
tAuxME.Last;
aSaldoF := tAuxMESaldoFinal.Value;
end;
procedure TdmCaixa.tCaixaCalcFields(DataSet: TDataSet);
begin
tCaixaNomeLoja.Value := gConfig.EmailIdent;
end;
function TdmCaixa.TemVendaHomo: Boolean;
begin
Result := False;
tAuxTran.Open;
tAuxTran.IndexName := 'ITipoNFECanceladoAmbStatusNFE';
Result := tAuxTran.FindKey([tiponfe_nfce, False, 2]) or
tAuxTran.FindKey([tiponfe_nfe, False, 2]);
end;
procedure TdmCaixa.tAuxMECalcFields(DataSet: TDataSet);
begin
if tAuxMENaoControlaEstoque.Value then
tAuxMESaldoFinal.Value := 0 else
if tAuxMECancelado.Value then
tAuxMESaldoFinal.Value := tAuxMEEstoqueAnt.Value
else
if tAuxMEEntrada.Value then
tAuxMESaldoFinal.Value := tAuxMEEstoqueAnt.Value + tAuxMEQuant.Value else
tAuxMESaldoFinal.Value := tAuxMEEstoqueAnt.Value - tAuxMEQuant.Value;
end;
initialization
dmCaixa := nil;
end.
|
{**********************************************************************}
{* Иллюстрация к книге "OpenGL в проектах Delphi" *}
{* Краснов М.В. softgl@chat.ru *}
{**********************************************************************}
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
OpenGL;
type
TfrmGL = class(TForm)
procedure FormCreate(Sender: TObject);
procedure FormPaint(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
private
hrc: HGLRC;
end;
var
frmGL: TfrmGL;
implementation
{$R *.DFM}
{=======================================================================
Перерисовка окна}
procedure TfrmGL.FormPaint(Sender: TObject);
begin
wglMakeCurrent(Canvas.Handle, hrc);
glViewPort (0, 0, ClientWidth, ClientHeight); // область вывода
glClearColor (0.5, 0.5, 0.75, 1.0); // цвет фона
glClear (GL_COLOR_BUFFER_BIT); // очистка буфера цвета
{--- красный треугольник ---}
glColor3f (1.0, 0.0, 0.0); // текущий цвет примитивов
glBegin (GL_TRIANGLES);
glVertex2f (-1, -1);
glVertex2f (-1, 1);
glVertex2f (-0.1, 0);
glEnd;
{--- синий треугольник ---}
glColor3f (0.0, 0.0, 1.0); // текущий цвет примитивов
glBegin (GL_TRIANGLES);
glVertex2f (0.1, 0);
glVertex2f (1, 1);
glVertex2f (1, -1);
glEnd;
SwapBuffers(Canvas.Handle); // содержимое буфера - на экран
wglMakeCurrent(0, 0);
end;
{=======================================================================
Формат пикселя}
procedure SetDCPixelFormat (hdc : HDC);
var
pfd : TPixelFormatDescriptor;
nPixelFormat : Integer;
begin
FillChar (pfd, SizeOf (pfd), 0);
pfd.dwFlags := PFD_DRAW_TO_WINDOW or PFD_SUPPORT_OPENGL or PFD_DOUBLEBUFFER;
nPixelFormat := ChoosePixelFormat (hdc, @pfd);
SetPixelFormat (hdc, nPixelFormat, @pfd);
end;
{=======================================================================
Создание формы}
procedure TfrmGL.FormCreate(Sender: TObject);
begin
SetDCPixelFormat(Canvas.Handle);
hrc := wglCreateContext(Canvas.Handle);
end;
{=======================================================================
Конец работы приложения}
procedure TfrmGL.FormDestroy(Sender: TObject);
begin
wglDeleteContext(hrc);
end;
procedure TfrmGL.FormMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
{=======================================================================
Перевод цвета из TColor в OpenGL}
procedure ColorToGL (c : TColor; var R, G, B : GLfloat);
begin
R := (c mod $100) / 255;
G := ((c div $100) mod $100) / 255;
B := (c div $10000) / 255;
end;
var
R, G, B : GLfloat;
begin
ColorToGL (Canvas.Pixels [X,Y], R, G, B);
If (R <> 0) and (B = 0) then
ShowMessage ('Выбран красный треугольник')
else
If (R = 0) and (B <> 0) then
ShowMessage ('Выбран синий треугольник')
else
ShowMessage ('Ничего не выбрано');
end;
end.
|
{
InCo- Fing
Laboratorio 2018
Programa Principal
}
program Tarea;
(****************************************)
(* Definicion de tipos dados en la letra *)
(****************************************)
{$INCLUDE estructuras.pas}
type
TipoComando = (enc, des, largo, aparece, salir, error);
Comando = record case com: TipoComando of
enc : ( txtClaro : TipoTexto;
claveEnc : TipoClave );
des : ( txtEncript : TipoTexto;
claveDes : TipoClave );
largo : ( claveLar : TipoClave;
txtLar : TipoTexto);
aparece : (txtAp : TipoTexto;
claveAp : TipoClave;
palabra : TipoPalabra);
salir : ();
error : ();
end;
{ aquí se incluye el archivo entregado por el estudiante}
(****************************************)
(* Procedimientos de encriptar y desencriptar
y funcion de posibles claves *)
(****************************************)
{$INCLUDE tarea.pas}
procedure LeerComando(var cmd : Comando);
{ lectura de una linea de comando con los siguientes posibles formatos:
- e:CLAVE:TEXTO
- d:CLAVE:TEXTO
- c:PALABRA:TEXTO
- a:CLAVE:PALABRA:TEXTO
- s
}
const SEP = ':';
const COMA = ',';
var bien : boolean;
texto : TipoTexto;
clave : TipoClave;
palabra : TipoPalabra;
procedure LeerCom (var cmd : Comando);
{ lee la letra que indica el comando y en caso de ser necesario el
separador (:)
si se produce algun error de formato se retorna el comando de tipo error. }
var aux : char;
begin
read(aux);
case aux of
'e' : cmd.com := enc;
'd' : cmd.com := des;
'c' : cmd.com := largo;
'a' : cmd.com := aparece;
's' : cmd.com := salir;
else cmd.com := error
end;
if aux in ['e','d','c','a'] then
begin
read(aux);
if aux <> SEP then
cmd.com := error
end
end;
procedure LeerClave (var clave : TipoClave; var ok : boolean);
{ lee la clave, en ok se retorna si no se
produce algun error de formato }
var aux : char;
k : integer;
begin
ok := true;
k := 0;
read(aux);
repeat
k := k * 10 + ord(aux) - ord('0');
ok := (aux >= '0') and (aux <= '9') and (k >= 1) and (k <= 28);
read(aux);
until (aux = COMA) or not ok;
if ok then
begin
clave.a := k;
k := 0;
read(aux);
repeat
k := k * 10 + ord(aux) - ord('0');
ok := (aux >= '0') and (aux <= '9') and (k >= 1) and (k <= 28);
read(aux);
until (aux = SEP) or not ok;
if ok then clave.b := k;
end;
end;
procedure LeerPalabra (var texto : TipoPalabra; var ok : boolean);
{ lee una palabra y el separador
en ok se retorna si no se produce algun error de formato }
var aux : char;
begin
texto.tope := 0;
ok := true;
read(aux);
while ok and (aux <> SEP) do
begin
ok := (texto.tope < MaxPalabra) and
(((aux >= 'A') and (aux <= 'Z')) or ((aux = '~') or (aux = '.')));
if ok then
begin
texto.tope := texto.tope + 1;
texto.palabra[texto.tope] := aux;
end;
read(aux)
end
end;
procedure LeerTexto (var texto : TipoTexto; var ok : boolean);
{ lee un texto
en ok se retorna si no se produce algun error de formato }
var aux : char;
begin
texto.tope := 0;
ok := true;
while ok and not eoln do
begin
read(aux);
ok := (texto.tope < MaxTexto) and
(((aux >= 'A') and (aux <= 'Z')) or ((aux = '~') or ((aux = ' ') or (aux = '.'))));
if ok then
begin
texto.tope := texto.tope + 1;
texto.texto[texto.tope] := aux;
end
end
end;
begin
LeerCom(cmd);
case cmd.com of
enc, des : begin
LeerClave (clave,bien);
if bien then LeerTexto(texto,bien);
if bien then
if cmd.com = enc then
begin
cmd.claveEnc := clave;
cmd.txtClaro := texto
end
else
begin
cmd.claveDes := clave;
cmd.txtEncript := texto
end
else
cmd.com := error
end;
aparece : begin
LeerClave (clave,bien);
if bien then LeerPalabra(palabra,bien);
if bien then LeerTexto(texto,bien);
if bien then
begin
cmd.palabra := palabra;
cmd.txtAp := texto;
cmd.claveAp := clave;
end else
cmd.com := error
end;
largo : begin
LeerClave (clave,bien);
if bien then LeerTexto(texto,bien);
if bien then
begin
cmd.txtLar := texto;
cmd.claveLar := clave
end else
cmd.com := error
end
end;
if not eoln then cmd.com := error;
readln
end;
procedure MostrarTexto (t : TipoTexto);
{ muestra el contenido del texto }
var i : integer;
begin
write('<|');
for i := 1 to t.tope do write (t.texto[i]);
writeln('|>')
end;
procedure MostrarLista (l : listaInt);
{ muestra el contenido de la lista }
begin
write('<|');
if l <> nil then
begin
write(l^.info);
l := l^.sig
end;
while l <> nil do
begin
write (' ', l^.info);
l := l^.sig
end;
writeln('|>')
end;
procedure BorrarLista(lista : listaInt);
{ libera el espacio ocupado por la lista }
var
tmp,p : listaInt;
begin
p:= lista;
while p <> nil do
begin
tmp:= p;
p:= p^.sig;
dispose(tmp);
end;
end;
var cmd : Comando;
salida : TipoTexto;
lista : listaInt;
{ Programa Principal }
begin
writeln('### COMIENZO ###');
repeat
LeerComando(cmd);
case cmd.com of
enc : begin
encriptar(cmd.txtClaro,cmd.claveEnc,salida);
MostrarTexto(salida)
end;
des : begin
desencriptar(cmd.txtEncript,cmd.claveDes,salida);
MostrarTexto(salida)
end;
largo : begin
lista := LargosPalabras(cmd.txtLar,cmd.claveLar);
MostrarLista(lista);
BorrarLista(lista)
end;
aparece : begin
writeln(AparecePalabra(cmd.palabra,cmd.txtAp,cmd.claveAp));
end;
error : writeln('Error al leer comando.')
end
until cmd.com = salir;
writeln('### FIN');
end.
|
unit xElecTA;
interface
uses xElecLine, xElecPoint, System.Classes, System.SysUtils, xElecFunction ;
type
/// <summary>
/// 电流互感器
/// </summary>
TElecTA = class
private
FOnValueChnage: TNotifyEvent;
FTAFirstValue: Double;
FTASecondValue: Double;
FTAName: string;
FFirstCurrentL: TElecLine;
FSecondCurrentH: TElecLine;
FSecondCurrentL: TElecLine;
FFirstCurrentH: TElecLine;
procedure ValueChangeCurrent(Sender : TObject);
procedure ValueChange(Sender : TObject);
procedure SetTAName(const Value: string);
public
constructor Create;
destructor Destroy; override;
/// <summary>
/// 电流互感器名称
/// </summary>
property TAName : string read FTAName write SetTAName;
/// <summary>
/// 一次电压 高端
/// </summary>
property FirstCurrentH : TElecLine read FFirstCurrentH write FFirstCurrentH;
/// <summary>
/// 一次电压 低端
/// </summary>
property FirstCurrentL : TElecLine read FFirstCurrentL write FFirstCurrentL;
/// <summary>
/// 二次电压 高端
/// </summary>
property SecondCurrentH : TElecLine read FSecondCurrentH write FSecondCurrentH;
/// <summary>
/// 二次电压 低端
/// </summary>
property SecondCurrentL : TElecLine read FSecondCurrentL write FSecondCurrentL;
/// <summary>
/// TA变比一次侧值
/// </summary>
property TAFirstValue : Double read FTAFirstValue write FTAFirstValue;
/// <summary>
/// TA变比二次侧值
/// </summary>
property TASecondValue : Double read FTASecondValue write FTASecondValue;
/// <summary>
/// 值改变事件
/// </summary>
property OnValueChnage : TNotifyEvent read FOnValueChnage write FOnValueChnage;
public
/// <summary>
/// 清空电压值
/// </summary>
procedure ClearVolVlaue;
/// <summary>
/// 清除权值
/// </summary>
procedure FirstClearWValue;
/// <summary>
/// 清空电流列表
/// </summary>
procedure FirstClearCurrentList;
/// <summary>
/// 清除权值
/// </summary>
procedure SecondClearWValue;
/// <summary>
/// 清空电流列表
/// </summary>
procedure SecondClearCurrentList;
/// <summary>
/// 刷新值
/// </summary>
procedure RefurshValue;
end;
implementation
{ TElecTA }
procedure TElecTA.FirstClearCurrentList;
begin
FFirstCurrentH.ClearCurrentList;
FFirstCurrentL.ClearCurrentList;
end;
procedure TElecTA.ClearVolVlaue;
begin
end;
procedure TElecTA.FirstClearWValue;
begin
FFirstCurrentH.ClearWValue;
FFirstCurrentL.ClearWValue;
end;
procedure TElecTA.RefurshValue;
begin
if Assigned(FFirstCurrentH) then
begin
GetTwoPointCurrent(FFirstCurrentH, FFirstCurrentL, FFirstCurrentH.Current);
FSecondCurrentH.Current.Value := FFirstCurrentH.Current.Value/FTAFirstValue*FTASecondValue;
FSecondCurrentH.Current.Angle := FFirstCurrentH.Current.Angle;
// 递归所有电流低端节点
// 赋值权值
FSecondCurrentL.CalcCurrWValue;
// 初始化电流原件电流列表
FSecondCurrentH.SendCurrentValue;
end;
end;
constructor TElecTA.Create;
begin
FFirstCurrentL:= TElecLine.Create;
FSecondCurrentH:= TElecLine.Create;
FSecondCurrentL:= TElecLine.Create;
FFirstCurrentH:= TElecLine.Create;
FFirstCurrentL.LineName:= 'TA一次低端';
FSecondCurrentH.LineName:= 'TA二次高端';
FSecondCurrentL.LineName:= 'TA二次低端';
FFirstCurrentH.LineName:= 'TA一次高端';
FFirstCurrentH.ConnPointAdd(FFirstCurrentL);
FSecondCurrentL.Current.IsLowPoint:= True;
FSecondCurrentL.Current.IsHighPoint:= False;
FSecondCurrentH.Current.IsLowPoint:= False;
FSecondCurrentH.Current.IsHighPoint:= True;
FFirstCurrentH.OnChangeCurrent := ValueChangeCurrent;
FSecondCurrentH.OnChange := ValueChange;
FTAFirstValue:= 100;
FTASecondValue:= 5;
FTAName := '电流互感器';
end;
destructor TElecTA.Destroy;
begin
FFirstCurrentL.Free;
FSecondCurrentH.Free;
FSecondCurrentL.Free;
FFirstCurrentH.Free;
inherited;
end;
procedure TElecTA.SecondClearCurrentList;
begin
FSecondCurrentH.ClearCurrentList;
FSecondCurrentL.ClearCurrentList;
end;
procedure TElecTA.SecondClearWValue;
begin
FSecondCurrentH.ClearWValue;
// FSecondCurrentL.ClearWValue;
end;
procedure TElecTA.SetTAName(const Value: string);
begin
FTAName := Value;
FFirstCurrentL.LineName:= FTAName + '一次低端';
FSecondCurrentH.LineName:= FTAName + '二次高端';
FSecondCurrentL.LineName:= FTAName + '二次低端';
FFirstCurrentH.LineName:= FTAName + '一次高端';
end;
procedure TElecTA.ValueChange(Sender: TObject);
begin
if Assigned(FOnValueChnage) then
begin
FOnValueChnage(Self);
end;
end;
procedure TElecTA.ValueChangeCurrent(Sender: TObject);
begin
// if Assigned(FFirstCurrentH) then
// begin
// FSecondCurrentH.Current.Value := FFirstCurrentH.Current.Value/FTAFirstValue*FTASecondValue;
// FSecondCurrentH.Current.Angle := FFirstCurrentH.Current.Angle;
//
////
//// // 递归所有电流低端节点
//// // 赋值权值
//// FSecondCurrentL.CalcCurrWValue;
//
// // 清空原件电流列表
// SecondClearCurrentList;
//
// // 初始化电流原件电流列表
// FSecondCurrentH.SendCurrentValue;
//
//
//
// end;
end;
end.
|
unit uSortInfo;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, xSortInfo;
type
TfSortInfo = class(TForm)
lblMemo: TLabel;
mmoSortRemark: TMemo;
lbl1: TLabel;
edtSortName: TEdit;
pnl1: TPanel;
bvl1: TBevel;
btnOK: TButton;
btnCancel: TButton;
private
FSortInfo : TSortInfo;
public
/// <summary>
/// 显示信息
/// </summary>
procedure ShowInfo(ASortInfo : TSortInfo);
/// <summary>
/// 保存信息
/// </summary>
procedure SaveInfo;
end;
var
fSortInfo: TfSortInfo;
implementation
{$R *.dfm}
{ TfS17SortInfo }
procedure TfSortInfo.SaveInfo;
begin
if Assigned(FSortInfo) then
begin
FSortInfo.SortName := edtSortName.Text;
FSortInfo.SortRemark := mmoSortRemark.Text;
end;
end;
procedure TfSortInfo.ShowInfo(ASortInfo: TSortInfo);
begin
if Assigned(ASortInfo) then
begin
FSortInfo := ASortInfo;
edtSortName.Text := FSortInfo.SortName;
mmoSortRemark.Text := FSortInfo.SortRemark;
end;
end;
end.
|
unit VCLBI.Editor.Gridify;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BI.DataItem, BI.Workflow, Vcl.ComCtrls,
Vcl.StdCtrls, Vcl.ExtCtrls, VCLBI.Editor.ListItems,
VCLBI.Editor.DataComponent;
type
TGridifyEditor = class(TForm)
PanelButtons: TPanel;
PanelOk: TPanel;
BOk: TButton;
BCancel: TButton;
PageControl1: TPageControl;
TabValue: TTabSheet;
TabRows: TTabSheet;
TabColumns: TTabSheet;
procedure FormShow(Sender: TObject);
private
{ Private declarations }
FData : TDataItem;
IRows,
IColumns : TFormListItems;
IValue : TDataComponent;
procedure SelectedChanged(Sender: TObject);
public
{ Public declarations }
class function Choose(const AOwner:TComponent;
const AData:TDataItem;
const AGridOwner:TComponent;
out AGrid:TDataGridifyItem):Boolean; static;
end;
implementation
|
unit URegraCRUDCarteiraVacinacao;
interface
uses
URegraCRUD
, URepositorioDB
, URepositorioCarteiraVacinacao
, UEntidade
, UCarteiraVacinacao
;
type
TRegraCRUDCarteiraVacinacao = class(TRegraCRUD)
protected
procedure ValidaInsercao(const coENTIDADE: TENTIDADE); override;
public
constructor Create; override;
end;
implementation
{ TRegraCRUDCidade }
uses
SysUtils
, UUtilitarios
, UMensagens
, UConstantes
;
constructor TRegraCRUDCarteiraVacinacao.Create;
begin
inherited;
FRepositorioDB := TRepositorioDB<TENTIDADE>(TRepositorioCarteiraVacinacao.Create);
end;
procedure TRegraCRUDCarteiraVacinacao.ValidaInsercao(const coENTIDADE: TENTIDADE);
begin
inherited;
if (TCARTEIRA_VACINACAO(coENTIDADE).NOME) = EmptyStr then
raise EValidacaoNegocio.Create (STR_CODIGO_VACINA_NAO_INFORAMADO);
if Trim(TCARTEIRA_VACINACAO(coENTIDADE).VACINA) = EmptyStr Then
raise EValidacaoNegocio.Create(STR_VACINA_NAO_INFORMADA);
if Trim(TCARTEIRA_VACINACAO(coENTIDADE).DOSE) = EmptyStr Then
raise EValidacaoNegocio.Create(STR_DOSE_NAO_INFORMADA);
//if Trim(TCARTEIRA_VACINACAO(coENTIDADE).DATA) = EmptyStr Then
//raise EValidacaoNegocio.Create(STR_DATA_VACINA_NAO_INFORMADA);
if Trim(TCARTEIRA_VACINACAO(coENTIDADE).RESPONSAVEL) = EmptyStr Then
raise EValidacaoNegocio.Create(STR_RESPONSAVEL_NAO_INFORMADO);
if Trim(TCARTEIRA_VACINACAO(coENTIDADE).COD_COREN) = EmptyStr Then
raise EValidacaoNegocio.Create(STR_CODIGO_COREN_NAO_INFORMADO);
if Trim(TCARTEIRA_VACINACAO(coENTIDADE).COD_LOTE) = EmptyStr Then
raise EValidacaoNegocio.Create(STR_CODIGO_LOTE_NAO_INFORMADO);
//if Trim(TCARTEIRA_VACINACAO(coENTIDADE).LOTE_VENCIMENTO) = EmptyStr Then
//raise EValidacaoNegocio.Create(STR_LOTE_VENCIMENTO_NAO_INFORMADO);
if Trim(TCARTEIRA_VACINACAO(coENTIDADE).UNIDADE_SAUDE) = EmptyStr Then
raise EValidacaoNegocio.Create(STR_UNIDADE_SAUDE_NAO_INFORMADA);
end;
end.
|
unit SearchCategoryQuery;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BaseQuery, FireDAC.Stan.Intf,
FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS,
FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt,
Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Vcl.StdCtrls, DSWrap;
type
TSearchCategoryW = class(TDSWrap)
private
FExternalID: TFieldWrap;
FID: TFieldWrap;
FParentId: TFieldWrap;
FValue: TFieldWrap;
public
constructor Create(AOwner: TComponent); override;
property ExternalID: TFieldWrap read FExternalID;
property ID: TFieldWrap read FID;
property ParentId: TFieldWrap read FParentId;
property Value: TFieldWrap read FValue;
end;
TQuerySearchCategory = class(TQueryBase)
private
FW: TSearchCategoryW;
function SearchByLevel(ALevel: Integer): Integer;
function SearchSubCategories(const AParentID: Integer): Integer;
{ Private declarations }
public
constructor Create(AOwner: TComponent); override;
function CalculateExternalId(ParentId, ALevel: Integer): string;
function SearchByExternalID(const AExternalID: String): Integer;
function SearchBySubgroup(const ASubgroup: String): Integer;
function SearchByID(const AID: Integer; TestResult: Integer = -1): Integer;
function SearchByParentAndValue(const AParentID: Integer; const AValue:
String): Integer;
function SearchDuplicate(const AID: Integer; TestResult: Integer = -1): Integer;
property W: TSearchCategoryW read FW;
{ Public declarations }
end;
type
TSearchSubCategories = class(TObject)
private
public
class function Search(const AParentID: Integer): Integer; static;
end;
implementation
{$R *.dfm}
uses StrHelper, System.Generics.Collections;
constructor TQuerySearchCategory.Create(AOwner: TComponent);
begin
inherited;
FW := TSearchCategoryW.Create(FDQuery);
end;
function TQuerySearchCategory.SearchByParentAndValue(const AParentID: Integer;
const AValue: String): Integer;
begin
Assert(AParentID > 0);
Assert(not AValue.IsEmpty);
Result := SearchEx([TParamRec.Create(W.ParentId.FullName, AParentID),
TParamRec.Create(W.Value.FullName, AValue, ftWideString, True)]);
end;
function TQuerySearchCategory.CalculateExternalId(ParentId,
ALevel: Integer): string;
var
AID: Integer;
AInteger: Integer;
AIntegers: TList<Integer>;
begin
SearchByLevel(ALevel);
// Список целых чисел
AIntegers := TList<Integer>.Create;
try
FDQuery.First;
while not FDQuery.Eof do
begin
// Получаем номер без уровня
AIntegers.Add(W.ExternalID.F.AsString.Substring(2).ToInteger);
FDQuery.Next;
end;
AIntegers.Sort;
AID := 1;
for AInteger in AIntegers do
begin
if AInteger <> AID then
Break;
Inc(AID);
end;
finally
FreeAndNil(AIntegers);
end;
Result := Format('%.2d%.3d', [ALevel, AID]);
end;
function TQuerySearchCategory.SearchByExternalID(const AExternalID
: String): Integer;
begin
Assert(not AExternalID.IsEmpty);
Result := SearchEx([TParamRec.Create(W.ExternalID.FullName, AExternalID,
ftWideString)]);
end;
function TQuerySearchCategory.SearchBySubgroup(const ASubgroup: String)
: Integer;
var
AStipulation: string;
AParamName: string;
begin
Assert(not ASubgroup.IsEmpty);
AParamName := 'SubGroup';
AStipulation := Format('instr('',''||:%s||'','', '',''||%s||'','') > 0',
[AParamName, W.ExternalID.FullName]);
// Меняем SQL запрос
FDQuery.SQL.Text := ReplaceInSQL(SQL, AStipulation, 0);
SetParamType(AParamName, ptInput, ftWideString);
Result := Search([AParamName], [ASubgroup]);
end;
function TQuerySearchCategory.SearchByID(const AID: Integer;
TestResult: Integer = -1): Integer;
begin
Assert(AID > 0);
Result := SearchEx([TParamRec.Create(W.ID.FullName, AID)], TestResult);
end;
function TQuerySearchCategory.SearchSubCategories(const AParentID
: Integer): Integer;
begin
Assert(AParentID > 0);
Result := SearchEx([TParamRec.Create(W.ParentId.FullName, AParentID)]);
end;
function TQuerySearchCategory.SearchByLevel(ALevel: Integer): Integer;
var
ALevelStr: string;
begin
Assert(ALevel > 0);
ALevelStr := Format('%.2d%%', [ALevel]);
Result := SearchEx([TParamRec.Create(W.ExternalID.FullName, ALevelStr,
ftWideString, False, 'like')]);
end;
function TQuerySearchCategory.SearchDuplicate(const AID: Integer; TestResult:
Integer = -1): Integer;
var
AStipulation: string;
begin
Assert(AID > 0);
AStipulation := Format('%s = (select %s from ProductCategories where %s = :%s)',
[W.Value.FullName, W.Value.FieldName, W.ID.FieldName, W.ID.FieldName]);
// Меняем SQL запрос
FDQuery.SQL.Text := ReplaceInSQL(SQL, AStipulation, 0);
SetParamType(W.ID.FieldName);
Result := Search([W.ID.FieldName], [AID], TestResult);
end;
class function TSearchSubCategories.Search(const AParentID: Integer): Integer;
var
qSearchSubCategory: TQuerySearchCategory;
begin
qSearchSubCategory := TQuerySearchCategory.Create(nil);
try
Result := qSearchSubCategory.SearchSubCategories(AParentID);
finally
FreeAndNil(qSearchSubCategory)
end;
end;
constructor TSearchCategoryW.Create(AOwner: TComponent);
begin
inherited;
FID := TFieldWrap.Create(Self, 'pc.ID', '', True);
FExternalID := TFieldWrap.Create(Self, 'pc.ExternalID');
FParentId := TFieldWrap.Create(Self, 'pc.ParentId');
FValue := TFieldWrap.Create(Self, 'pc.Value');
end;
end.
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2019 The Bitcoin Core developers
// Copyright (c) 2020-2020 Skybuck Flying
// Copyright (c) 2020-2020 The Delphicoin Developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
// Bitcoin file: src/primitives/transaction.h
// Bitcoin file: src/primitives/transaction.cpp
// Bitcoin commit hash: f656165e9c0d09e654efabd56e6581638e35c26c
unit Unit_TTxOut;
interface
/** An output of a transaction. It contains the public key that the next input
* must be able to sign with to claim it.
*/
class CTxOut
{
public:
CAmount nValue;
CScript scriptPubKey;
CTxOut()
{
SetNull();
}
CTxOut(const CAmount& nValueIn, CScript scriptPubKeyIn);
SERIALIZE_METHODS(CTxOut, obj) { READWRITE(obj.nValue, obj.scriptPubKey); }
void SetNull()
{
nValue = -1;
scriptPubKey.clear();
}
bool IsNull() const
{
return (nValue == -1);
}
friend bool operator==(const CTxOut& a, const CTxOut& b)
{
return (a.nValue == b.nValue &&
a.scriptPubKey == b.scriptPubKey);
}
friend bool operator!=(const CTxOut& a, const CTxOut& b)
{
return !(a == b);
}
std::string ToString() const;
};
implementation
CTxOut::CTxOut(const CAmount& nValueIn, CScript scriptPubKeyIn)
{
nValue = nValueIn;
scriptPubKey = scriptPubKeyIn;
}
std::string CTxOut::ToString() const
{
return strprintf("CTxOut(nValue=%d.%08d, scriptPubKey=%s)", nValue / COIN, nValue % COIN, HexStr(scriptPubKey).substr(0, 30));
}
end.
|
unit fConsultBSt;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, ORCtrls, StdCtrls, ORFn, uConsults, fBase508Form,
VA508AccessibilityManager;
type
TfrmConsultsByStatus = class(TfrmBase508Form)
pnlBase: TORAutoPanel;
lblStatus: TLabel;
radSort: TRadioGroup;
lstStatus: TORListBox;
cmdOK: TButton;
cmdCancel: TButton;
procedure cmdCancelClick(Sender: TObject);
procedure cmdOKClick(Sender: TObject);
private
FChanged: Boolean;
FStatus: string;
FStatusName: string;
FAscending: Boolean;
end;
TStatusContext = record
Changed: Boolean;
Status: string;
StatusName: string;
Ascending: Boolean;
end;
function SelectStatus(FontSize: Integer; CurrentContext: TSelectContext; var StatusContext: TStatusContext): boolean ;
implementation
{$R *.DFM}
uses rConsults, rCore, uCore;
const
TX_STAT_TEXT = 'Select a consult status or press Cancel.';
TX_STAT_CAP = 'Missing Status';
function SelectStatus(FontSize: Integer; CurrentContext: TSelectContext; var StatusContext: TStatusContext): boolean ;
{ displays Status select form for consults and returns a record of the selection }
var
frmConsultsByStatus: TfrmConsultsByStatus;
W, H, i, j: Integer;
CurrentStatus: string;
begin
frmConsultsByStatus := TfrmConsultsByStatus.Create(Application);
try
with frmConsultsByStatus do
begin
Font.Size := FontSize;
W := ClientWidth;
H := ClientHeight;
ResizeToFont(FontSize, W, H);
ClientWidth := W; pnlBase.Width := W;
ClientHeight := H; pnlBase.Height := H;
FChanged := False;
with radSort do {if SortConsultsAscending then ItemIndex := 0 else} ItemIndex := 1;
FastAssign(SubSetOfStatus, lstStatus.Items);
CurrentStatus := CurrentContext.Status;
if CurrentStatus <> '' then with lstStatus do
begin
i := 1;
while Piece(CurrentStatus, ',', i) <> '' do
begin
j := SelectByID(Piece(CurrentStatus, ',', i));
if j > -1 then Selected[j] := True;
Inc(i);
end;
end;
ShowModal;
with StatusContext do
begin
Changed := FChanged;
Status := FStatus;
StatusName := FStatusName;
Ascending := FAscending;
Result := Changed ;
end; {with StatusContext}
end; {with frmConsultsByStatus}
finally
frmConsultsByStatus.Release;
end;
end;
procedure TfrmConsultsByStatus.cmdCancelClick(Sender: TObject);
begin
Close;
end;
procedure TfrmConsultsByStatus.cmdOKClick(Sender: TObject);
var
i: integer;
begin
if lstStatus.SelCount = 0 then
begin
InfoBox(TX_STAT_TEXT, TX_STAT_CAP, MB_OK or MB_ICONWARNING);
Exit;
end;
FChanged := True;
with lstStatus do for i := 0 to Items.Count-1 do if Selected[i] then
begin
if Piece(Items[i], U, 1) <> '999' then
FStatus := FStatus + Piece(Items[i], U, 1) + ','
else
FStatus := FStatus + Piece(Items[i],U,3) ;
FStatusName := FStatusName + DisplayText[i] + ',' ;
end;
FStatus := Copy(FStatus, 1, Length(FStatus)-1);
FStatusName := Copy(FStatusName, 1, Length(FStatusName)-1);
FAscending := radSort.ItemIndex = 0;
Close;
end;
end.
|
unit fODGen;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
fODBase, ComCtrls, ExtCtrls, StdCtrls, ORDtTm, ORCtrls, ORFn, rODBase, fBase508Form,
VA508AccessibilityManager;
type
TDialogCtrl = class
public
ID: string;
DataType: Char;
Required: Boolean;
Preserve: Boolean;
Prompt: TStaticText;
Editor: TWinControl;
IHidden: string;
EHidden: string;
end;
TfrmODGen = class(TfrmODBase)
sbxMain: TScrollBox;
lblOrderSig: TLabel;
VA508CompMemOrder: TVA508ComponentAccessibility;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure cmdAcceptClick(Sender: TObject);
procedure VA508CompMemOrderStateQuery(Sender: TObject; var Text: string);
private
FilterOut: boolean;
TsID: string; //treating specialty id
TSDomain: string;
AttendID: string;
AttendDomain: string;
procedure ControlChange(Sender: TObject);
procedure LookupNeedData(Sender: TObject; const StartFrom: string;
Direction, InsertAt: Integer);
procedure PlaceControls;
procedure PlaceDateTime(DialogCtrl: TDialogCtrl; DialogItem: TDialogItem; CurrentItemNumber: Integer);
procedure PlaceFreeText(DialogCtrl: TDialogCtrl; DialogItem: TDialogItem; CurrentItemNumber: Integer);
procedure PlaceHidden(DialogCtrl: TDialogCtrl; DialogItem: TDialogItem);
procedure PlaceNumeric(DialogCtrl: TDialogCtrl; DialogItem: TDialogItem; CurrentItemNumber: Integer);
procedure PlaceSetOfCodes(DialogCtrl: TDialogCtrl; DialogItem: TDialogItem; CurrentItemNumber: Integer);
procedure PlaceYesNo(DialogCtrl: TDialogCtrl; DialogItem: TDialogItem; CurrentItemNumber: Integer);
procedure PlaceLookup(DialogCtrl: TDialogCtrl; DialogItem: TDialogItem; CurrentItemNumber: Integer);
procedure PlaceMemo(DialogCtrl: TDialogCtrl; DialogItem: TDialogItem; CurrentItemNumber: Integer);
procedure PlaceLabel(DialogCtrl: TDialogCtrl; DialogItem: TDialogItem);
procedure TrimAllMemos;
procedure SetComponentName(Editor: TWinControl; Index: Integer; DialogCtrl: TDialogCtrl);
protected
FFormCloseCalled : Boolean;
FCharHt: Integer;
FCharWd: Integer;
FDialogItemList: TList;
FDialogCtrlList: TList;
FEditorLeft: Integer;
FEditorTop: Integer;
FFirstCtrl: TWinControl;
FLabelWd: Integer;
procedure InitDialog; override;
procedure SetDialogIEN(Value: Integer); override;
procedure Validate(var AnErrMsg: string); override;
procedure UpdateAccessibilityActions(var Actions: TAccessibilityActions); override;
public
procedure SetupDialog(OrderAction: Integer; const ID: string); override;
end;
var
frmODGen: TfrmODGen;
implementation
{$R *.DFM}
uses rCore, rOrders, uConst, VAUtils;
const
HT_FRAME = 8;
HT_LBLOFF = 3;
HT_SPACE = 6;
WD_MARGIN = 6;
TX_STOPSTART = 'The stop date must be after the start date.';
procedure TfrmODGen.FormCreate(Sender: TObject);
var
TheEvtType: string;
IDs,TSstr, AttendStr: string;
begin
FFormCloseCalled := false;
inherited;
FilterOut := True;
if Self.EvtID < 1 then
FilterOut := False;
if Self.EvtID > 0 then
begin
TheEvtType := Piece(EventInfo1(IntToStr(Self.EvtId)), '^', 1);
if (TheEvtType = 'A') or (TheEvtType = 'T') or (TheEvtType = 'M') or (TheEvtType = 'O') then
FilterOut := False;
end;
FillerID := 'OR'; // does 'on Display' order check **KCM**
IDs := GetPromptIDs;
TSstr := Piece(IDs,'~',1);
TsDomain := Piece(TSstr,'^', 1);
TsID := Piece(TSstr,'^', 2);
AttendStr := Piece(IDs,'~',2);
AttendDomain := Piece(AttendStr,'^',1);
AttendID := Piece(AttendStr,'^',2);
FDialogItemList := TList.Create;
FDialogCtrlList := TList.Create;
end;
procedure TfrmODGen.FormClose(Sender: TObject; var Action: TCloseAction);
var
i: Integer;
DialogCtrl: TDialogCtrl;
begin
with FDialogItemList do for i := 0 to Count - 1 do TDialogItem(Items[i]).Free;
with FDialogCtrlList do for i := 0 to Count - 1 do
begin
DialogCtrl := TDialogCtrl(Items[i]);
with DialogCtrl do
begin
if Prompt <> nil then Prompt.Free;
if Editor <> nil then case DataType of
'D': TORDateBox(Editor).Free;
'F': TEdit(Editor).Free;
'N': TEdit(Editor).Free;
'P': TORComboBox(Editor).Free;
'R': TORDateBox(Editor).Free;
'S': TORComboBox(Editor).Free;
'W': TMemo(Editor).Free;
'Y': TORComboBox(Editor).Free;
else Editor.Free;
end;
Free;
end;
end;
FDialogItemList.Free;
FDialogCtrlList.Free;
FFormCloseCalled := true;
inherited;
end;
procedure TfrmODGen.SetDialogIEN(Value: Integer);
{ Sets up a generic ordering dialog on the fly. Called before SetupDialog. }
var
DialogNames: TDialogNames;
begin
inherited;
StatusText('Loading Dialog Definition');
IdentifyDialog(DialogNames, DialogIEN);
Caption := DialogNames.Display;
Responses.Dialog := DialogNames.BaseName; // loads formatting info
LoadOrderPrompting(FDialogItemList, DialogNames.BaseIEN); // loads prompting info
PlaceControls;
StatusText('');
end;
procedure TfrmODGen.SetupDialog(OrderAction: Integer; const ID: string);
var
i: Integer;
theEvtInfo: string;
thePromptIen: integer;
AResponse: TResponse;
AnEvtResponse: TResponse;
begin
inherited;
if OrderAction in [ORDER_COPY, ORDER_EDIT, ORDER_QUICK] then with Responses do
begin
Changing := True;
// for copy & edit, SetDialogIEN hasn't been called yet
if (Length(ID) > 0) and (DialogIEN = 0) then SetDialogIEN(DialogForOrder(ID));
with FDialogCtrlList do for i := 0 to Count -1 do with TDialogCtrl(Items[i]) do
begin
if (ID = 'EVENT') and ( Responses.EventIFN > 0 ) then
begin
thePromptIen := GetIENForPrompt(ID);
if thePromptIen = 0 then
thePromptIen := GetEventPromptID;
AResponse := FindResponseByName('EVENT', 1);
if AResponse <> nil then
begin
theEvtInfo := EventInfo1(AResponse.IValue);
AResponse.EValue := Piece(theEvtInfo,'^',4);
end;
if AResponse = nil then
begin
AnEvtResponse := TResponse.Create;
AnEvtResponse.PromptID := 'EVENT';
AnEvtResponse.PromptIEN := thePromptIen;
AnEvtResponse.Instance := 1;
AnEvtResponse.IValue := IntToStr(Responses.EventIFN);
theEvtInfo := EventInfo1(AnEvtResponse.IValue);
AnEvtResponse.EValue := Piece(theEvtInfo,'^',4);
Responses.TheList.Add(AnEvtResponse);
end;
end;
if Editor <> nil then SetControl(Editor, ID, 1);
if DataType = 'H' then
begin
AResponse := FindResponseByName(ID, 1);
if AResponse <> nil then
begin
IHidden := AResponse.IValue;
EHidden := AResponse.EValue;
end; {if AResponse}
end; {if DataType}
end; {with TDialogCtrl}
Changing := False;
end; {if OrderAction}
UpdateColorsFor508Compliance(Self);
ControlChange(Self);
if (FFirstCtrl <> nil) and (FFirstCtrl.Enabled) then SetFocusedControl(FFirstCtrl);
end;
procedure TfrmODGen.UpdateAccessibilityActions(var Actions: TAccessibilityActions);
begin
exclude(Actions, aaColorConversion);
end;
procedure TfrmODGen.InitDialog;
var
i: Integer;
begin
inherited; // inherited does a ClearControls (probably never called since always quick order)
{NEED TO CLEAR CONTROLS HERE OR CHANGE ClearControls so can clear children of container}
with FDialogCtrlList do for i := 0 to Count -1 do
with TDialogCtrl(Items[i]) do if (Editor <> nil) and not Preserve then
begin
// treat the list & combo boxes differently so their lists aren't cleared
if (Editor is TListBox) then TListBox(Editor).ItemIndex := -1
else if (Editor is TComboBox) then
begin
TComboBox(Editor).Text := '';
TComboBox(Editor).ItemIndex := -1;
end
else if (Editor is TORComboBox) then
begin
TORComboBox(Editor).Text := '';
TORComboBox(Editor).ItemIndex := -1;
end
else ClearControl(Editor);
end;
if FFirstCtrl <> nil then ActiveControl := FFirstCtrl;
end;
procedure TfrmODGen.VA508CompMemOrderStateQuery(Sender: TObject;
var Text: string);
begin
inherited;
Text := memOrder.Text;
end;
procedure TfrmODGen.Validate(var AnErrMsg: string);
var
i: Integer;
ALabel, AMsg: string;
AResponse: TResponse;
DialogCtrl: TDialogCtrl;
StartDT, StopDT: TFMDateTime;
procedure SetError(const x: string);
begin
if Length(AnErrMsg) > 0 then AnErrMsg := AnErrMsg + CRLF;
AnErrMsg := AnErrMsg + x;
end;
begin
inherited;
with FDialogCtrlList do for i := 0 to Count -1 do
begin
DialogCtrl := TDialogCtrl(Items[i]);
with DialogCtrl do
begin
if Prompt <> nil then ALabel := Piece(Prompt.Caption, ':', 1) else ALabel := '<Unknown>';
if Required then
begin
AResponse := Responses.FindResponseByName(ID, 1);
if (AResponse = nil) or ((AResponse <> nil) and (Trim(AResponse.EValue) = ''))
then SetError(ALabel + ' is required.');
end;
if ((DataType = 'D') or (DataType = 'R')) and (Editor <> nil) then
begin
TORDateBox(Editor).Validate(AMsg);
if Length(AMsg) > 0 then SetError('For ' + ALabel + ': ' + AMsg);
end;
if (DataType = 'N') then
begin
AResponse := Responses.FindResponseByName(ID, 1);
if (AResponse <> nil) and (Length(AResponse.EValue) > 0) then with AResponse do
begin
ValidateNumericStr(EValue, Piece(TEdit(Editor).Hint, '|', 2), AMsg);
if Length(AMsg) > 0 then SetError('For ' + ALabel + ': ' + AMsg);
end; {if AResponse}
end; {if DataType}
end; {with DialogCtrl}
end; {with FDialogCtrlList}
with Responses do
begin
AResponse := FindResponseByName('START', 1);
if AResponse <> nil then StartDT := StrToFMDateTime(AResponse.EValue) else StartDT := 0;
AResponse := FindResponseByName('STOP', 1);
if AResponse <> nil then StopDT := StrToFMDateTime(AResponse.EValue) else StopDT := 0;
if (StopDT > 0) and (StopDT <= StartDT) then SetError(TX_STOPSTART);
end;
end;
procedure TfrmODGen.PlaceControls;
var
i: Integer;
DialogItem: TDialogItem;
DialogCtrl: TDialogCtrl;
begin
FCharHt := MainFontHeight;
FCharWd := MainFontWidth;
FEditorTop := HT_SPACE;
FLabelWd := 0;
with FDialogItemList do for i := 0 to Count - 1 do with TDialogItem(Items[i]) do
if not Hidden then FLabelWd := HigherOf(FLabelWd, Canvas.TextWidth(Prompt));
FEditorLeft := FLabelWd + (WD_MARGIN * 2);
with FDialogItemList do for i := 0 to Count - 1 do
begin
DialogItem := TDialogItem(Items[i]);
if FilterOut then
begin
if ( compareText(TsID,DialogItem.Id)=0 ) or ( compareText(TSDomain,DialogItem.Domain)=0) then
Continue;
if (Pos('primary',LowerCase(DialogItem.Prompt)) > 0) then
Continue;
if (compareText(AttendID,DialogItem.ID) = 0) or ( compareText(AttendDomain,DialogItem.Domain)=0 ) then
Continue;
end;
DialogCtrl := TDialogCtrl.Create;
DialogCtrl.ID := DialogItem.ID;
DialogCtrl.DataType := DialogItem.DataType;
DialogCtrl.Required := DialogItem.Required;
DialogCtrl.Preserve := Length(DialogItem.EDefault) > 0;
case DialogItem.DataType of
'D': PlaceDateTime(DialogCtrl, DialogItem, I);
'F': PlaceFreeText(DialogCtrl, DialogItem, i);
'H': PlaceHidden(DialogCtrl, DialogItem);
'N': PlaceNumeric(DialogCtrl, DialogItem, i);
'P': PlaceLookup(DialogCtrl, DialogItem, i);
'R': PlaceDateTime(DialogCtrl, DialogItem, i);
'S': PlaceSetOfCodes(DialogCtrl, DialogItem, i);
'W': PlaceMemo(DialogCtrl, DialogItem, i);
'Y': PlaceYesNo(DialogCtrl, DialogItem, i);
end;
FDialogCtrlList.Add(DialogCtrl);
if (DialogCtrl.Editor <> nil) and (FFirstCtrl = nil) then FFirstCtrl := DialogCtrl.Editor;
end;
end;
procedure TfrmODGen.PlaceDateTime(DialogCtrl: TDialogCtrl; DialogItem: TDialogItem; CurrentItemNumber: Integer);
var
item: TVA508AccessibilityItem;
id508: integer;
const
NUM_CHAR = 22;
begin
with DialogCtrl do
begin
Editor := TORDateBox.Create(Self);
Editor.Parent := sbxMain;
Editor.SetBounds(FEditorLeft, FEditorTop, NUM_CHAR * FCharWd, HT_FRAME * FCharHt);
TORDateBox(Editor).DateOnly := Pos('T', DialogItem.Domain) = 0;
with TORDateBox(Editor) do RequireTime := (not DateOnly) and (Pos('R', DialogItem.Domain) > 0); //v26.48 - RV PSI-05-002
SetComponentName(Editor, CurrentItemNumber, DialogCtrl);
// TORDateBox(Editor).Name := DialogCtrl.ID + IntToStr(CurrentItemNumber);
TORDateBox(Editor).Text := DialogItem.EDefault;
TORDateBox(Editor).Hint := DialogItem.HelpText;
TORDateBox(Editor).Caption := DialogItem.Prompt;
if Length(DialogItem.HelpText) > 0 then TORDateBox(Editor).ShowHint := True;
TORDateBox(Editor).OnExit := ControlChange;
PlaceLabel(DialogCtrl, DialogItem);
FEditorTop := FEditorTop + HT_FRAME + FCharHt + HT_SPACE;
amgrMain.AccessData.Add.component := Editor;
item := amgrMain.AccessData.FindItem(Editor, False);
id508:= item.INDEX;
amgrMain.AccessData[id508].AccessText := TORDateBox(Editor).Caption + ' Press the enter key to access.';
end;
end;
procedure TfrmODGen.PlaceFreeText(DialogCtrl: TDialogCtrl; DialogItem: TDialogItem; CurrentItemNumber: Integer);
begin
with DialogCtrl do
begin
Editor := TCaptionEdit.Create(Self);
Editor.Parent := sbxMain;
Editor.SetBounds(FEditorLeft, FEditorTop,
sbxMain.Width - FEditorLeft - WD_MARGIN - GetSystemMetrics(SM_CXVSCROLL),
HT_FRAME * FCharHt);
TEdit(Editor).MaxLength := StrToIntDef(Piece(DialogItem.Domain, ':', 2), 0);
SetComponentName(Editor, CurrentItemNumber, DialogCtrl);
// TCaptionEdit(Editor).Name := DialogCtrl.ID + IntToStr(CurrentItemNumber);
TEdit(Editor).Text := DialogItem.EDefault;
TEdit(Editor).Hint := DialogItem.HelpText;
TCaptionEdit(Editor).Caption := DialogItem.Prompt;
if Length(DialogItem.HelpText) > 0 then TEdit(Editor).ShowHint := True;
TEdit(Editor).OnChange := ControlChange;
PlaceLabel(DialogCtrl, DialogItem);
FEditorTop := FEditorTop + HT_FRAME + FCharHt + HT_SPACE;
end;
end;
procedure TfrmODGen.PlaceNumeric(DialogCtrl: TDialogCtrl; DialogItem: TDialogItem; CurrentItemNumber: Integer);
const
NUM_CHAR = 16;
begin
with DialogCtrl do
begin
Editor := TCaptionEdit.Create(Self);
Editor.Parent := sbxMain;
Editor.SetBounds(FEditorLeft, FEditorTop, NUM_CHAR * FCharWd, HT_FRAME * FCharHt);
TEdit(Editor).MaxLength := NUM_CHAR;
SetComponentName(Editor, CurrentItemNumber, DialogCtrl);
// TCaptionEdit(Editor).Name := DialogCtrl.ID + IntToStr(CurrentItemNumber);
TEdit(Editor).Text := DialogItem.EDefault;
TEdit(Editor).Hint := DialogItem.HelpText + '|' + DialogItem.Domain;
TCaptionEdit(Editor).Caption := DialogItem.Prompt;
if Length(DialogItem.HelpText) > 0 then TEdit(Editor).ShowHint := True;
TEdit(Editor).OnChange := ControlChange;
PlaceLabel(DialogCtrl, DialogItem);
FEditorTop := FEditorTop + HT_FRAME + FCharHt + HT_SPACE;
end;
end;
procedure TfrmODGen.PlaceSetOfCodes(DialogCtrl: TDialogCtrl; DialogItem: TDialogItem; CurrentItemNumber: Integer);
const
NUM_CHAR = 32;
var
x, y: string;
begin
with DialogCtrl do
begin
Editor := TORComboBox.Create(Self);
Editor.Parent := sbxMain;
TORComboBox(Editor).Style := orcsDropDown;
TORComboBox(Editor).ListItemsOnly := True;
TORComboBox(Editor).Pieces := '2';
SetComponentName(Editor, CurrentItemNumber, DialogCtrl);
// TORComboBox(Editor).Name := DialogCtrl.ID + IntToStr(CurrentItemNumber);
Editor.SetBounds(FEditorLeft, FEditorTop, NUM_CHAR * FCharWd, HT_FRAME * FCharHt);
x := DialogItem.Domain;
repeat
y := Piece(x, ';', 1);
Delete(x, 1, Length(y) + 1);
y := Piece(y, ':', 1) + U + Piece(y, ':', 2);
TORComboBox(Editor).Items.Add(y);
until Length(x) = 0;
TORComboBox(Editor).SelectByID(DialogItem.IDefault);
//TORComboBox(Editor).Text := DialogItem.EDefault;
TORComboBox(Editor).RpcCall := DialogItem.HelpText;
if Length(DialogItem.HelpText) > 0 then TORComboBox(Editor).ShowHint := True;
TORComboBox(Editor).OnChange := ControlChange;
PlaceLabel(DialogCtrl, DialogItem);
FEditorTop := FEditorTop + HT_FRAME + FCharHt + HT_SPACE;
end;
end;
procedure TfrmODGen.PlaceYesNo(DialogCtrl: TDialogCtrl; DialogItem: TDialogItem; CurrentItemNumber: Integer);
const
NUM_CHAR = 9;
begin
with DialogCtrl do
begin
Editor := TORComboBox.Create(Self);
Editor.Parent := sbxMain;
TORComboBox(Editor).Style := orcsDropDown;
TORComboBox(Editor).ListItemsOnly := True;
TORComboBox(Editor).Pieces := '2';
SetComponentName(Editor, CurrentItemNumber, DialogCtrl);
//TORComboBox(Editor).Name := DialogCtrl.ID + IntToStr(CurrentItemNumber);
Editor.SetBounds(FEditorLeft, FEditorTop, NUM_CHAR * FCharWd, HT_FRAME * FCharHt);
TORComboBox(Editor).Items.Add('0^No');
TORComboBox(Editor).Items.Add('1^Yes');
TORComboBox(Editor).SelectByID(DialogItem.IDefault);
//TORComboBox(Editor).Text := DialogItem.EDefault;
TORComboBox(Editor).RpcCall := DialogItem.HelpText;
if Length(DialogItem.HelpText) > 0 then TORComboBox(Editor).ShowHint := True;
TORComboBox(Editor).OnChange := ControlChange;
PlaceLabel(DialogCtrl, DialogItem);
FEditorTop := FEditorTop + HT_FRAME + FCharHt + HT_SPACE;
end;
end;
procedure TfrmODGen.PlaceLookup(DialogCtrl: TDialogCtrl; DialogItem: TDialogItem; CurrentItemNumber: Integer);
const
NUM_CHAR = 32;
var
idx,defidx,evtChars: integer;
GblRef, XRef: string;
TopTSList: TStringList;
begin
with DialogCtrl do
begin
GblRef := DialogItem.Domain;
if CharInSet(CharAt(GblRef, 1), ['0'..'9','.']) then
GblRef := GlobalRefForFile(Piece(GblRef, ':', 1))
else
GblRef := Piece(GblRef, ':', 1);
if CharAt(GblRef, 1) <> U then GblRef := U + GblRef;
if Length(DialogItem.CrossRef) > 0 then XRef := DialogItem.CrossRef else XRef := 'B';
XRef := GblRef + '"' + XRef + '")';
Editor := TORComboBox.Create(Self);
Editor.Parent := sbxMain;
TORComboBox(Editor).Style := orcsDropDown;
TORComboBox(Editor).ListItemsOnly := True;
TORComboBox(Editor).Pieces := '2';
TORComboBox(Editor).LongList := True;
SetComponentName(Editor, CurrentItemNumber, DialogCtrl);
// TORComboBox(Editor).Name := DialogCtrl.ID + IntToStr(CurrentItemNumber);
// 2nd bar piece of hint is not visible, hide xref, global ref, & screen code in tab pieces
TORComboBox(Editor).RpcCall := DialogItem.HelpText + '|' + XRef + #9 + GblRef + #9 +
DialogItem.ScreenRef;
if ( compareText(TsID,DialogItem.Id)=0 ) or (compareText(TSDomain,DialogItem.Domain)=0)then
begin
TopTSList := TStringList.Create;
DialogItem.IDefault := Piece(GetDefaultTSForEvt(Self.EvtID),'^',1);
GetTSListForEvt(TStrings(TopTSList),Self.EvtID);
if TopTSList.Count > 0 then
begin
if Length(DialogItem.IDefault)>0 then
begin
defidx := -1;
for idx := 0 to topTSList.Count - 1 do
if Piece(TopTSList[idx],'^',1)= DialogItem.IDefault then
begin
defidx := idx;
break;
end;
if defidx >= 0 then
topTSList.Move(defidx,0);
end;
with TORComboBox(Editor) do
begin
FastAddStrings(TStrings(TopTSList), TORComboBox(Editor).Items);
LongList := false;
end;
end else
TORComboBox(Editor).OnNeedData := LookupNeedData;
if Length(DialogItem.IDefault)<1 then
DialogItem.IDefault := '0';
end else
TORComboBox(Editor).OnNeedData := LookupNeedData;
Editor.SetBounds(FEditorLeft, FEditorTop, NUM_CHAR * FCharWd, HT_FRAME * FCharHt);
TORComboBox(Editor).InitLongList(DialogItem.EDefault);
TORComboBox(Editor).SelectByID(DialogItem.IDefault);
if Length(DialogItem.HelpText) > 0 then TORComboBox(Editor).ShowHint := True;
TORComboBox(Editor).OnChange := ControlChange;
if ( AnsiCompareText(ID,'EVENT')=0 ) and (Self.EvtID>0)then
begin
evtChars := length(Responses.EventName);
if evtChars > NUM_CHAR then
Editor.SetBounds(FEditorLeft, FEditorTop, (evtChars + 6) * FCharWd, HT_FRAME * FCharHt);
TORComboBox(Editor).Enabled := False;
end;
PlaceLabel(DialogCtrl, DialogItem);
FEditorTop := FEditorTop + HT_FRAME + FCharHt + HT_SPACE;
end;
end;
procedure TfrmODGen.LookupNeedData(Sender: TObject; const StartFrom: string;
Direction, InsertAt: Integer);
var
XRef, GblRef, ScreenRef: string;
begin
inherited;
XRef := Piece(TORComboBox(Sender).RpcCall, '|', 2);
GblRef := Piece(XRef, #9, 2);
ScreenRef := Piece(XRef, #9, 3);
XRef := Piece(XRef, #9, 1);
TORComboBox(Sender).ForDataUse(SubsetOfEntries(StartFrom, Direction, XRef, GblRef, ScreenRef));
end;
procedure TfrmODGen.PlaceMemo(DialogCtrl: TDialogCtrl; DialogItem: TDialogItem; CurrentItemNumber: Integer);
const
NUM_LINES = 3;
begin
with DialogCtrl do
begin
Editor := TCaptionMemo.Create(Self);
Editor.Parent := sbxMain;
Editor.SetBounds(FEditorLeft, FEditorTop,
sbxMain.Width - FEditorLeft - WD_MARGIN - GetSystemMetrics(SM_CXVSCROLL),
(FCharHt * NUM_LINES) + HT_FRAME);
SetComponentName(Editor, CurrentItemNumber, DialogCtrl);
// TCaptionMemo(Editor).Name := DialogCtrl.ID + IntToStr(CurrentItemNumber);
TMemo(Editor).Text := DialogItem.EDefault;
TMemo(Editor).Hint := DialogItem.HelpText;
TCaptionMemo(Editor).Caption := DialogItem.Prompt;
if Length(DialogItem.HelpText) > 0 then TMemo(Editor).ShowHint := True;
TMemo(Editor).ScrollBars := ssVertical;
TMemo(Editor).OnChange := ControlChange;
PlaceLabel(DialogCtrl, DialogItem);
FEditorTop := FEditorTop + HT_FRAME + (FCharHt * 3) + HT_SPACE;
end;
end;
procedure TfrmODGen.PlaceHidden(DialogCtrl: TDialogCtrl; DialogItem: TDialogItem);
begin
DialogCtrl.IHidden := DialogItem.IDefault;
DialogCtrl.EHidden := DialogItem.EDefault;
end;
procedure TfrmODGen.PlaceLabel(DialogCtrl: TDialogCtrl; DialogItem: TDialogItem);
var
ht: integer;
begin
with DialogCtrl do
begin
Prompt := TStaticText.Create(Self);
Prompt.Parent := sbxMain;
Prompt.Caption := DialogItem.Prompt;
ht := Prompt.Height; // CQ#15849
if ht < FCharHt then
ht := FCharHt;
Prompt.AutoSize := False;
Prompt.SetBounds(WD_MARGIN, FEditorTop + HT_LBLOFF, FLabelWd, ht);
Prompt.Alignment := taRightJustify;
Prompt.Visible := True;
end;
end;
procedure TfrmODGen.TrimAllMemos;
var
i : integer;
Memo : TMemo;
begin
if FFormCloseCalled then Exit; //it is possible for TrimAllMemos to get called after FormClose
if Not Assigned(FDialogCtrlList) then Exit;
for i := 0 to FDialogCtrlList.Count - 1 do
if TDialogCtrl(FDialogCtrlList.Items[i]).Editor is TMemo then begin
Memo := TMemo(TDialogCtrl(FDialogCtrlList.Items[i]).Editor);
Memo.Lines.Text := Trim(Memo.Lines.Text);
end;
end;
procedure TfrmODGen.cmdAcceptClick(Sender: TObject);
var
ReleasePending: boolean;
Msg: TMsg;
begin
inherited;
ReleasePending := PeekMessage(Msg, Handle, CM_RELEASE, CM_RELEASE, PM_REMOVE);
TrimAllMemos;
Application.ProcessMessages;
if ReleasePending then
Release;
end;
procedure TfrmODGen.ControlChange(Sender: TObject);
var
i: Integer;
begin
inherited;
if Changing then Exit;
with FDialogCtrlList do for i := 0 to Count - 1 do with TDialogCtrl(Items[i]) do
begin
case DataType of
'D': Responses.Update(ID, 1, FloatToStr(TORDateBox(Editor).FMDateTime),
TORDateBox(Editor).Text);
'F': Responses.Update(ID, 1, TEdit(Editor).Text, TEdit(Editor).Text);
'H': Responses.Update(ID, 1, IHidden, EHidden);
'N': Responses.Update(ID, 1, TEdit(Editor).Text, TEdit(Editor).Text);
'P': Responses.Update(ID, 1, TORComboBox(Editor).ItemID, TORComboBox(Editor).Text);
'R': Responses.Update(ID, 1, TORDateBox(Editor).Text, TORDateBox(Editor).Text);
'S': Responses.Update(ID, 1, TORComboBox(Editor).ItemID, TORComboBox(Editor).Text);
'W': Responses.Update(ID, 1, TX_WPTYPE, TMemo(Editor).Text);
'Y': Responses.Update(ID, 1, TORComboBox(Editor).ItemID, TORComboBox(Editor).Text);
end;
end;
memOrder.Text := Responses.OrderText;
end;
procedure TfrmODGen.SetComponentName(Editor: TWinControl; Index: Integer; DialogCtrl: TDialogCtrl);
Var
I: Integer;
SaveName: String;
begin
//strip all non alphanumeric characters to create the save name
SaveName := '';
//Check for blank id
if DialogCtrl.ID = '' then DialogCtrl.ID := 'EMPTY';
for i := 1 to length(DialogCtrl.ID) do begin
if CharInSet(DialogCtrl.ID[i], ['A'..'Z']) or
CharInSet(DialogCtrl.ID[i], ['a'..'z']) or
CharInSet(DialogCtrl.ID[i], ['0'..'9']) then
SaveName := SaveName + DialogCtrl.ID[i];
end;
SaveName := SaveName + '_' + IntToStr(Index);
//extra backup - make sure that the component name doesn't already exist
//Now set up the component name
try
Editor.Name := SaveName;
except
Editor.Name := SaveName + '_' + IntToStr(Index);
end;
end;
end.
|
{-----------------------------------------------------------------------------
Author: Roman Fadeyev
Purpose: Диалог для выбора индикатора для вставки его в чарт
History:
-----------------------------------------------------------------------------}
unit FC.Trade.CreateAlerterDialog;
{$I Compiler.inc}
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ufmDialogOKCancel_B, ActnList, StdCtrls, ExtendControls, ExtCtrls,
StockChart.Definitions,FC.Definitions, ComCtrls;
type
TAlerterNode = class(TTreeNode)
private
FAlerter : IStockAlerterInfo;
public
property Alerter: IStockAlerterInfo read FAlerter write FAlerter;
end;
TfmCreateAlerterDialog = class(TfmDialogOkCancel_B)
Panel1: TPanel;
tvAlerters: TExtendTreeView;
laHeader: TLabel;
procedure tvAlertersDblClick(Sender: TObject);
procedure acOKUpdate(Sender: TObject);
private
function GetSelected: IStockAlerterInfo;
procedure SetAlerters;
public
constructor Create(aOwner:TComponent); override;
property SelectedAlerter: IStockAlerterInfo read GetSelected;
end;
implementation
uses ufmDialog_B,FC.Singletons, ufmDialogOK_B;
type
TTreeViewFriend = class (TExtendTreeView);
{$R *.dfm}
{ TfmSelectAlerter }
constructor TfmCreateAlerterDialog.Create(aOwner: TComponent);
begin
inherited;
TTreeViewFriend(tvAlerters).CreateWndRestores:=false;
HandleNeeded;
SetAlerters;
end;
function TfmCreateAlerterDialog.GetSelected: IStockAlerterInfo;
var
aNode: TAlerterNode;
begin
result:=nil;
if (tvAlerters.Selected<>nil) and (tvAlerters.Selected is TAlerterNode) then
begin
aNode:=TAlerterNode(tvAlerters.Selected);
result:=aNode.Alerter;
end;
end;
procedure TfmCreateAlerterDialog.SetAlerters;
var
aCategories : TStringList;
i,j : integer;
aAlerter: IStockAlerterInfo;
aNode1 : TTreeNode;
aNode2 : TAlerterNode;
begin
tvAlerters.Items.Clear;
tvAlerters.HandleNeeded;
if (AlerterFactory.AlerterCount=0) then
exit;
//Заполняем список индикаторов
aCategories:=TStringList.Create;
tvAlerters.Items.BeginUpdate;
try
aCategories.Sorted:=true;
aCategories.Duplicates:=dupIgnore;
for i:=0 to AlerterFactory.AlerterCount-1 do
aCategories.Add(AlerterFactory.GetAlerterInfo(i).Category);
for i:=0 to aCategories.Count-1 do
begin
aNode1:=nil;
for j:=0 to AlerterFactory.AlerterCount-1 do
begin
aAlerter:=AlerterFactory.GetAlerterInfo(j);
if (aAlerter.Category=aCategories[i])then
begin
if aNode1=nil then
aNode1:=tvAlerters.Items.AddChild(nil,aCategories[i]);
aNode2:=TAlerterNode.Create(tvAlerters.Items);
//aNode2.Text:=aAlerter.Name;
aNode2.Alerter:=aAlerter;
tvAlerters.Items.AddNode(aNode2, aNode1, aAlerter.Name, nil, naAddChild);
end;
end
end;
for i:=0 to tvAlerters.Items.Count-1 do
tvAlerters.Items[i].Expanded:=true;
finally
tvAlerters.Items.EndUpdate;
aCategories.Free;
end;
tvAlerters.AlphaSort(true);
if tvAlerters.Items.Count>0 then
begin
tvAlerters.Items[0].MakeVisible;
tvAlerters.Items[0].Focused:=true;
tvAlerters.Items[0].Selected:=true;
end;
end;
procedure TfmCreateAlerterDialog.acOKUpdate(Sender: TObject);
begin
TAction(Sender).Enabled:=SelectedAlerter<>nil;
end;
procedure TfmCreateAlerterDialog.tvAlertersDblClick(Sender: TObject);
begin
inherited;
acOK.Execute;
end;
end.
|
unit MediaStream.Writer.Wave;
interface
uses Windows,Classes,SysUtils,MMSystem,MediaProcessing.Definitions;
type
//Запись в Wav-файл (только Audio-потока)
TMediaStreamWriter_Wave = class
private
FStream: TStream;
FFileName: string;
FDataBytesWritten : integer;
FFormat: TPCMWaveFormat;
FOwnStream: boolean;
procedure SetFileName(const Value: string);
procedure WriteHeader;
protected
procedure OpenInternal;
//Закрыть файл
procedure CloseInternal;
procedure CheckOpened;
public
//Открыть файл для записи
procedure Open(const aFileName: string;
nChannels: Word;
nSamplesPerSec: DWORD;
wBitsPerSample: Word); overload;
procedure Open(const aStream: TStream;
nChannels: Word;
nSamplesPerSec: DWORD;
wBitsPerSample: Word); overload;
procedure Close;
function Opened: boolean;
procedure WritePcmData(aData: pointer; aDataSize: cardinal);
property FileName: string read FFileName write SetFileName;
function DefaultExtension: string;
constructor Create;
destructor Destroy; override;
end;
implementation
type
(*
The canonical WAVE format starts with the RIFF header:
0 4 ChunkID Contains the letters "RIFF" in ASCII form
(0x52494646 big-endian form).
4 4 ChunkSize 36 + SubChunk2Size, or more precisely:
4 + (8 + SubChunk1Size) + (8 + SubChunk2Size)
This is the size of the rest of the chunk
following this number. This is the size of the
entire file in bytes minus 8 bytes for the
two fields not included in this count:
ChunkID and ChunkSize.
8 4 Format Contains the letters "WAVE"
(0x57415645 big-endian form).
The "WAVE" format consists of two subchunks: "fmt " and "data":
The "fmt " subchunk describes the sound data's format:
12 4 Subchunk1ID Contains the letters "fmt "
(0x666d7420 big-endian form).
16 4 Subchunk1Size 16 for PCM. This is the size of the
rest of the Subchunk which follows this number.
20 2 AudioFormat PCM = 1 (i.e. Linear quantization)
Values other than 1 indicate some
form of compression.
22 2 NumChannels Mono = 1, Stereo = 2, etc.
24 4 SampleRate 8000, 44100, etc.
28 4 ByteRate == SampleRate * NumChannels * BitsPerSample/8
32 2 BlockAlign == NumChannels * BitsPerSample/8
The number of bytes for one sample including
all channels. I wonder what happens when
this number isn't an integer?
34 2 BitsPerSample 8 bits = 8, 16 bits = 16, etc.
2 ExtraParamSize if PCM, then doesn't exist
X ExtraParams space for extra parameters
The "data" subchunk contains the size of the data and the actual sound:
36 4 Subchunk2ID Contains the letters "data"
(0x64617461 big-endian form).
40 4 Subchunk2Size == NumSamples * NumChannels * BitsPerSample/8
This is the number of bytes in the data.
You can also think of this as the size
of the read of the subchunk following this
number.
44 * Data The actual sound data.
*)
TWaveHeader = record
Marker1: Array[0..3] of AnsiChar; //Contains the letters "RIFF" in ASCII form
BytesFollowing: LongInt;
Marker2: Array[0..3] of AnsiChar; //Contains the letters "WAVE"
Marker3: Array[0..3] of AnsiChar; //Contains the letters "fmt "
Fixed1: LongInt;
//Скопировано из WAVEFORMATEX
wFormatTag: Word; { format type }
nChannels: Word; { number of channels (i.e. mono, stereo, etc.) }
nSamplesPerSec: DWORD; { sample rate }
nAvgBytesPerSec: DWORD; { for buffer estimation }
nBlockAlign: Word; { block size of data }
wBitsPerSample: Word; { number of bits per sample of mono data }
Marker4: Array[0..3] of AnsiChar; // Contains the letters "data"
DataBytes: LongInt;
end;
{ TMediaStreamWriter_Wave }
constructor TMediaStreamWriter_Wave.Create;
begin
inherited Create;
end;
destructor TMediaStreamWriter_Wave.Destroy;
begin
Close;
inherited;
end;
procedure TMediaStreamWriter_Wave.CheckOpened;
begin
if not Opened then
raise Exception.Create('Записыватель еще не инициализирован');
end;
procedure TMediaStreamWriter_Wave.Close;
begin
CloseInternal;
end;
procedure TMediaStreamWriter_Wave.CloseInternal;
begin
if FStream<>nil then
begin
FStream.Seek(0,soFromBeginning);
WriteHeader;
if FOwnStream then
FreeAndNil(FStream)
else
FStream:=nil;
FFileName:='';
end;
end;
procedure TMediaStreamWriter_Wave.Open(const aFileName: string;
nChannels: Word;
nSamplesPerSec: DWORD;
wBitsPerSample: Word);
begin
Close();
FFormat.wf.wFormatTag := WAVE_FORMAT_PCM;
FFormat.wf.nChannels :=nChannels;
FFormat.wBitsPerSample:=wBitsPerSample;
FFormat.wf.nSamplesPerSec:=nSamplesPerSec;
FFormat.wf.nBlockAlign:=(wBitsPerSample div 8) * nChannels;
FFormat.wf.nAvgBytesPerSec:=FFormat.wf.nBlockAlign * nSamplesPerSec;
FFileName:=aFileName;
OpenInternal;
end;
procedure TMediaStreamWriter_Wave.Open(const aStream: TStream; nChannels: Word;
nSamplesPerSec: DWORD; wBitsPerSample: Word);
begin
Close();
FFormat.wf.wFormatTag := WAVE_FORMAT_PCM;
FFormat.wf.nChannels :=nChannels;
FFormat.wBitsPerSample:=wBitsPerSample;
FFormat.wf.nSamplesPerSec:=nSamplesPerSec;
FFormat.wf.nBlockAlign:=(wBitsPerSample div 8) * nChannels;
FFormat.wf.nAvgBytesPerSec:=FFormat.wf.nBlockAlign * nSamplesPerSec;
FStream:=aStream;
FOwnStream:=false;
WriteHeader
end;
function TMediaStreamWriter_Wave.Opened: boolean;
begin
result:=FStream<>nil;
end;
procedure TMediaStreamWriter_Wave.WritePcmData(aData: pointer; aDataSize: cardinal);
begin
CheckOpened;
FStream.WriteBuffer(aData^,aDataSize);
inc(FDataBytesWritten,aDataSize);
end;
procedure TMediaStreamWriter_Wave.SetFileName(const Value: string);
begin
if Opened then
raise Exception.Create('Уже открыт');
FFileName := Value;
end;
procedure TMediaStreamWriter_Wave.OpenInternal;
begin
FDataBytesWritten:=0;
FStream:=TFileStream.Create(FFileName,fmCreate or fmShareDenyWrite);
//Заголовок
WriteHeader;
end;
function TMediaStreamWriter_Wave.DefaultExtension: string;
begin
result:='.wav'
end;
procedure TMediaStreamWriter_Wave.WriteHeader;
var
WaveHeader: TWaveHeader;
begin
WaveHeader.Marker1 := 'RIFF';
WaveHeader.BytesFollowing := FDataBytesWritten + sizeof(TWaveHeader)-8;
WaveHeader.Marker2 := 'WAVE';
WaveHeader.Marker3 := 'fmt ';
WaveHeader.Fixed1 := 16;
WaveHeader.wFormatTag := WAVE_FORMAT_PCM;
WaveHeader.nChannels :=self.FFormat.wf.nChannels;
WaveHeader.wBitsPerSample:=self.FFormat.wBitsPerSample;
WaveHeader.nSamplesPerSec:=self.FFormat.wf.nSamplesPerSec;
WaveHeader.nBlockAlign:=self.FFormat.wf.nBlockAlign;
WaveHeader.nAvgBytesPerSec:=Self.FFormat.wf.nAvgBytesPerSec;
WaveHeader.Marker4 := 'data';
WaveHeader.DataBytes := FDataBytesWritten;
FStream.WriteBuffer(WaveHeader, sizeof(WaveHeader));
end;
end.
|
{*******************************************************}
{ }
{ Delphi Runtime Library }
{ }
{ Copyright(c) 1995-2014 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit Bde.Bdeconst;
interface
resourcestring
SAutoSessionExclusive = 'Die Eigenschaft AutoSessionName kann nicht aktiviert werden, wenn sich mehr als eine Session in einem Formular oder einem Datenmodul befinden';
SAutoSessionExists = 'Dem Formular oder Datenmodul kann keine Session hinzugefügt werden, da Session '#39'%s'#39' AutoSessionName aktiviert hat';
SAutoSessionActive = 'Während AutoSessionName aktiviert ist, kann SessionName nicht geändert werden.';
SDuplicateDatabaseName = 'Doppelter Datenbankname '#39'%s'#39;
SDuplicateSessionName = 'Doppelter Name für eine Sitzung: '#39'%s'#39;
SInvalidSessionName = 'Ungültiger Sitzungsname %s';
SDatabaseNameMissing = 'Datenbankname fehlt';
SSessionNameMissing = 'Name der Sitzung fehlt';
SDatabaseOpen = 'Operation bei geöffneter Datenbank nicht ausführbar';
SDatabaseClosed = 'Operation bei geschlossener Datenbank nicht ausführbar';
SDatabaseHandleSet = 'Datenbank-Handle gehört zu einer anderen Sitzung';
SSessionActive = 'Diese Operation kann auf eine aktive Sitzung nicht angewendet werden';
SHandleError = 'Fehler beim Erstellen des Cursor-Handle';
SInvalidFloatField = 'Feld '#39'%s'#39' kann nicht in Fließkommawert konvertiert werden';
SInvalidIntegerField = 'Feld '#39'%s'#39' kann nicht in Integerwert konvertiert werden';
STableMismatch = 'Quell- und Zieltabellen sind inkompatibel';
SFieldAssignError = 'Die Felder '#39'%s'#39' und '#39'%s'#39' sind nicht zuweisungskompatibel';
SNoReferenceTableName = 'Für Feld '#39'%s'#39' wurde kein Referenztabellenname angegeben';
SCompositeIndexError = 'Array mit Feldwerten kann nicht mit Ausdrucksindizes verwendet werden';
SInvalidBatchMove = 'Ungültige Batch-Move-Parameter';
SEmptySQLStatement = 'Keine SQL-Anweisung verfügbar';
SNoParameterValue = 'Fehlender Wert für Parameter '#39'%s'#39;
SNoParameterType = 'Kein Parametertyp für Parameter '#39'%s'#39;
SLoginError = 'Verbindung zu Datenbank '#39'%s'#39' nicht möglich';
SInitError = 'Bei der Initialisierung der Borland Database Engine ist ein Fehler aufgetreten (Fehler $%.4x)';
SDatabaseEditor = '&Datenbank-Editor...';
SExplore = 'E&xplorer';
SLinkDetail = #39'%s'#39' kann nicht geöffnet werden';
SLinkMasterSource = 'Die MasterSource-Eigenschaft von '#39'%s'#39' muss mit einer Datenquelle (DataSource) verbunden sein';
SLinkMaster = 'MasterSource-Tabelle kann nicht geöffnet werden';
SGQEVerb = 'SQL-&Builder...';
SBindVerb = '&Parameter definieren...';
SIDAPILangID = '0007';
SDisconnectDatabase = 'Die Datenbank ist aktuell verbunden. Verbindung beenden und fortsetzen?';
SBDEError = 'BDE-Fehler $%.4x';
SLookupSourceError = 'Kann doppelte DataSource und LookupSource nicht benutzen';
SLookupTableError = 'LookupSource muss mit TTable-Komponente verbunden werden';
SLookupIndexError = '%s muss der aktive Index der Nachschlagetabelle sein.';
SParameterTypes = ';Eingabe;Ausgabe;Eingabe/Ausgabe;Ergebnis';
SInvalidParamFieldType = 'Sie müssen einen gültigen Feldtypen auswählen';
STruncationError = 'Parameter '#39'%s'#39' bei der Ausgabe abgeschnitten';
SDataTypes = ';String;SmallInt;Integer;Word;Boolean;Float;Currency;BCD;Date;Time;DateTime;;;;Blob;Memo;Graphic;;;;;Cursor;';
SResultName = 'Ergebnis';
SDBCaption = '%s%s%s Datenbanken';
SParamEditor = '%s%s%s Parameter';
SIndexFilesEditor = '%s%s%s Indexdateien';
SNoIndexFiles = '(Keine)';
SIndexDoesNotExist = 'Index existiert nicht. Index: %s';
SNoTableName = 'Eigenschaft TableName fehlt';
SNoDataSetField = 'Eigenschaft DataSetField fehlt';
SBatchExecute = 'A&usführen';
SNoCachedUpdates = 'Nicht im Cached-Update-Modus';
SInvalidAliasName = 'Ungültiger Aliasname %s';
SNoFieldAccess = 'Auf Feld '#39'%s'#39' kann in einem Filter nicht zugegriffen werden';
SUpdateSQLEditor = 'UpdateS&QL-Editor...';
SNoDataSet = 'Keine Datenmengenverknüpfung';
SUntitled = 'Unbenannte Anwendung';
SUpdateWrongDB = 'Aktualisierung nicht möglich, %s gehört zu %s';
SUpdateFailed = 'Aktualisierung misslungen';
SSQLGenSelect = 'Sie müssen mindestens ein Schlüsselfeld und ein Updatefeld auswählen';
SSQLNotGenerated = 'Aktualisierungs-SQL-Anweisungen nicht generiert; trotzdem beenden?';
SSQLDataSetOpen = 'Feldnamen für %s wurden nicht erkannt';
SLocalTransDirty = 'Die Isolationsebene für Transaktionen muss für lokale Datenbanken Dirty-Read sein.';
SMissingDataSet = 'Eigenschaft DataSet fehlt';
SNoProvider = 'Kein Provider verfügbar';
SNotAQuery = 'Die Datenmenge ist keine Abfrage';
implementation
end.
|
unit fBaseFrame;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs;
type
TfrmBase = class(TFrame)
private
{ Private declarations }
FSubFrame: TfrmBase;
FRefCtrl: TDataModule;
function GetCanClose: boolean;
public
{ Public declarations }
procedure Show; virtual; abstract;
procedure Carica(Id: integer); virtual; abstract;
property SubFrame: TfrmBase read FSubFrame write FSubFrame;
property CanClose: boolean read GetCanClose;
property RefCtrl: TDataModule read FRefCtrl write FRefCtrl;
end;
TfrmBaseClass = class of TfrmBase;
function GetDetailControlClass(ATag: Integer): TfrmBaseClass;
procedure RegisterFrame(AID: Integer; AFrameClass: TfrmBaseClass);
implementation
{$R *.dfm}
var
AFrameClasses: array [0..1] of TfrmBaseClass;
function GetDetailControlClass(ATag: Integer): TfrmBaseClass;
begin
Result := AFrameClasses[ATag];
end;
procedure RegisterFrame(AID: Integer; AFrameClass: TfrmBaseClass);
begin
AFrameClasses[AID] := AFrameClass;
end;
function TfrmBase.GetCanClose: boolean;
begin
result := not Assigned(FSubFrame) or not FSubFrame.Visible;
end;
end.
|
unit ANovaComposicao;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, formularios,
Grids, CGrades, StdCtrls, Mask, DBCtrls, Tabela, DBKeyViolation, DB, DBClient,
BotaoCadastro, Buttons, Componentes1, ExtCtrls, PainelGradiente, Localizacao, UnDadosProduto,
UnDadosLOcaliza, UnProdutos;
type
TFNovaComposicao = class(TFormularioPermissao)
PainelGradiente1: TPainelGradiente;
PanelColor1: TPanelColor;
PanelColor2: TPanelColor;
BotaoGravar1: TBotaoGravar;
BotaoCancelar1: TBotaoCancelar;
BFechar: TBitBtn;
Composicao: TSQL;
DataComposicao: TDataSource;
ECodigo: TDBKeyViolation;
DBEditColor1: TDBEditColor;
Label1: TLabel;
Label2: TLabel;
Grade: TRBStringGridColor;
EFiguraGRF: TRBEditLocaliza;
ComposicaoCODCOMPOSICAO: TFMTBCDField;
ComposicaoNOMCOMPOSICAO: TWideStringField;
ComposicaoDATULTIMAALTERACAO: TSQLTimeStampField;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure BFecharClick(Sender: TObject);
procedure GradeCarregaItemGrade(Sender: TObject; VpaLinha: Integer);
procedure GradeDadosValidos(Sender: TObject; var VpaValidos: Boolean);
procedure GradeKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure GradeMudouLinha(Sender: TObject; VpaLinhaAtual,
VpaLinhaAnterior: Integer);
procedure GradeNovaLinha(Sender: TObject);
procedure GradeSelectCell(Sender: TObject; ACol, ARow: Integer;
var CanSelect: Boolean);
procedure ComposicaoAfterInsert(DataSet: TDataSet);
procedure ComposicaoAfterEdit(DataSet: TDataSet);
procedure ComposicaoBeforePost(DataSet: TDataSet);
procedure BotaoGravar1DepoisAtividade(Sender: TObject);
procedure EFiguraGRFRetorno(VpaColunas: TRBColunasLocaliza);
procedure ComposicaoAfterScroll(DataSet: TDataSet);
procedure ComposicaoAfterPost(DataSet: TDataSet);
private
{ Private declarations }
VprDFigura : TRBDFiguraGRF;
VprFiguras : TList;
procedure CarTitulosGrade;
public
{ Public declarations }
end;
var
FNovaComposicao: TFNovaComposicao;
implementation
uses APrincipal, AComposicoes, FunObjeto, ConstMsg, UnSistema;
{$R *.DFM}
{ ****************** Na criação do Formulário ******************************** }
procedure TFNovaComposicao.FormCreate(Sender: TObject);
begin
{ abre tabelas }
{ chamar a rotina de atualização de menus }
Composicao.Open;
CarTitulosGrade;
VprFiguras := TList.Create;
end;
{******************************************************************************}
procedure TFNovaComposicao.GradeCarregaItemGrade(Sender: TObject;
VpaLinha: Integer);
begin
VprDFigura := TRBDFiguraGRF(VprFiguras.Items[VpaLinha-1]);
if VprDFigura.CodFiguraGRF <> 0 then
Grade.Cells[1,VpaLinha]:= InttoStr(VprDFigura.CodFiguraGRF)
else
Grade.Cells[1,VpaLinha]:= '';
Grade.Cells[2,VpaLinha]:= VprDFigura.NomFiguraGRF;
end;
{******************************************************************************}
procedure TFNovaComposicao.GradeDadosValidos(Sender: TObject;
var VpaValidos: Boolean);
begin
VpaValidos := true;
if not EFiguraGRF.AExisteCodigo(Grade.Cells[1,Grade.ALinha]) then
begin
VpaValidos := false;
aviso('FIGURA GRF NÃO CADASTRADA!!!'#13'A figura GRF digitada não existe cadastrada.');
Grade.Col := 1;
end;
if Vpavalidos then
begin
if FunProdutos.FiguraGRFDuplicada(VprFiguras) then
begin
VpaValidos := false;
aviso('FIGURA DUPLICADA!!!'#13'Essa figura já foi digitada.');
end;
end;
end;
{******************************************************************************}
procedure TFNovaComposicao.GradeKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
case key of
114 :
begin
case Grade.AColuna of
1: EFiguraGRF.AAbreLocalizacao;
end;
end;
end;
end;
procedure TFNovaComposicao.GradeMudouLinha(Sender: TObject; VpaLinhaAtual,
VpaLinhaAnterior: Integer);
begin
if VprFiguras.Count >0 then
begin
VprDFigura := TRBDFiguraGRF(VprFiguras.Items[VpaLinhaAtual-1]);
end;
end;
procedure TFNovaComposicao.GradeNovaLinha(Sender: TObject);
begin
VprDFigura := TRBDFiguraGRF.cria;
VprFiguras.add(VprDFigura);
end;
procedure TFNovaComposicao.GradeSelectCell(Sender: TObject; ACol, ARow: Integer;
var CanSelect: Boolean);
begin
if Grade.AEstadoGrade in [egInsercao,EgEdicao] then
if Grade.AColuna <> ACol then
begin
case Grade.AColuna of
1 :if not EFiguraGRF.AExisteCodigo(Grade.Cells[1,Grade.ALinha]) then
begin
if not EFiguraGRF.AAbreLocalizacao then
begin
Grade.Cells[1,Grade.ALinha] := '';
abort;
end;
end;
end;
end;
end;
{ ******************* Quando o formulario e fechado ************************** }
procedure TFNovaComposicao.BFecharClick(Sender: TObject);
begin
close;
end;
{******************************************************************************}
procedure TFNovaComposicao.FormClose(Sender: TObject; var Action: TCloseAction);
begin
{ fecha tabelas }
{ chamar a rotina de atualização de menus }
FreeTObjectsList(VprFiguras);
VprFiguras.free;
Action := CaFree;
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
Ações Diversas
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{******************************************************************************}
procedure TFNovaComposicao.BotaoGravar1DepoisAtividade(Sender: TObject);
var
VpfResultado : string;
begin
VpfResultado := FunProdutos.GravaFigurasGRF(ComposicaoCODCOMPOSICAO.AsInteger,VprFiguras);
if vpfresultado <> '' then
aviso(VpfResultado);
end;
procedure TFNovaComposicao.CarTitulosGrade;
begin
Grade.Cells[1,0] := 'Código';
Grade.Cells[2,0] := 'Figura';
end;
{******************************************************************************}
procedure TFNovaComposicao.ComposicaoAfterEdit(DataSet: TDataSet);
begin
ECodigo.ReadOnly := true;
end;
{******************************************************************************}
procedure TFNovaComposicao.ComposicaoAfterInsert(DataSet: TDataSet);
begin
ECodigo.ProximoCodigo;
ECodigo.ReadOnly := false;
end;
procedure TFNovaComposicao.ComposicaoAfterPost(DataSet: TDataSet);
begin
Sistema.MarcaTabelaParaImportar('COMPOSICAO');
end;
{******************************************************************************}
procedure TFNovaComposicao.ComposicaoAfterScroll(DataSet: TDataSet);
begin
FunProdutos.CarFigurasGRF(ComposicaoCODCOMPOSICAO.AsInteger,VprFiguras);
Grade.ADados := VprFiguras;
Grade.CarregaGrade;
end;
{******************************************************************************}
procedure TFNovaComposicao.ComposicaoBeforePost(DataSet: TDataSet);
begin
if Composicao.State in [dsInsert] then
ECodigo.VerificaCodigoUtilizado;
ComposicaoDATULTIMAALTERACAO.AsDateTime := Sistema.RDataServidor;
end;
{******************************************************************************}
procedure TFNovaComposicao.EFiguraGRFRetorno(VpaColunas: TRBColunasLocaliza);
begin
if VpaColunas.items[0].AValorRetorno <> '' then
begin
VprDFigura.CodFiguraGRF := StrToINt(VpaColunas.items[0].AValorRetorno);
VprDFigura.NomFiguraGRF := VpaColunas.items[1].AValorRetorno;
Grade.Cells[1,Grade.ALinha] := VpaColunas.items[0].AValorRetorno;
Grade.Cells[2,Grade.ALinha] := VpaColunas.items[1].AValorRetorno;
end
else
begin
VprDFigura.CodFiguraGRF:= 0;
VprDFigura.NomFiguraGRF := '';
end;
end;
Initialization
{ *************** Registra a classe para evitar duplicidade ****************** }
RegisterClasses([TFNovaComposicao]);
end.
|
program Prog2;
function letter(s: string; i: integer) : integer;
const
letters = ['a'..'z', 'A'..'Z']; { алфавит }
var
count: integer;
begin
if s[i] in letters then count := 1 else count := 0; { если s[i] это буква -- будем прибавлять 1 иначе 0 }
if i < length(s) then count := count + letter(s, i + 1); { складываем текущий результат и рекурсивно вызываем себя }
letter := count; { возвращаем результат }
end;
var
s: string;
begin
Write('Enter string: ');
read(s);
WriteLn('Letters count: ', letter(s, 0)) { вызов функции. начинаем считать с 0-го символа }
end.
|
unit UServerContainer;
interface
uses
SysUtils, Classes, IniFiles,
DSTCPServerTransport, DSServer, DSCommonServer;
type
TServerContainer = class(TDataModule)
DSServer1: TDSServer;
DSTCPServerTransport1: TDSTCPServerTransport;
DSServerClass1: TDSServerClass;
procedure DSServerClass1GetClass(DSServerClass: TDSServerClass;
var PersistentClass: TPersistentClass);
procedure DataModuleCreate(Sender: TObject);
private
{ Private declarations }
public
end;
var
ServerContainer: TServerContainer;
function StartService: Boolean;
procedure StopService;
function GetServiceStarted: Boolean;
implementation
uses UServerMethods, UGlobalVar;
{$R *.dfm}
function StartService: Boolean;
begin
try
if not Assigned(ServerContainer) then
ServerContainer := TServerContainer.Create(nil);
with ServerContainer do
begin
if not DSServer1.Started then
DSServer1.Start;
Result := DSServer1.Started;
end;
except
Result := False;
end;
end;
procedure StopService;
begin
if Assigned(ServerContainer) then
begin
if ServerContainer.DSServer1.Started then
ServerContainer.DSServer1.Stop;
FreeAndNil(ServerContainer);
end;
end;
function GetServiceStarted: Boolean;
begin
if Assigned(ServerContainer) then
Result := ServerContainer.DSServer1.Started
else
Result := False;
end;
procedure TServerContainer.DataModuleCreate(Sender: TObject);
var
lIni: TIniFile;
lPort: Integer;
begin
lIni := TIniFile.Create(GLB.AppPath + 'config\telnet.ini');
try
lPort := lIni.ReadInteger('TCPTransport', 'Port', 211);
DSTCPServerTransport1.Port := lPort;
finally
lIni.Free;
end;
end;
procedure TServerContainer.DSServerClass1GetClass(
DSServerClass: TDSServerClass; var PersistentClass: TPersistentClass);
begin
PersistentClass := UServerMethods.TServerMethods;
end;
end.
|
unit KZDeskManagers;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, LMessages, ComCtrls, ExtCtrls, Dialogs,
LCLIntf, LCLType, SrcEditorIntf, IDEMsgIntf;
type
TKZParentType = (kzptParent, kzptParentWindow, kzptDock, kzptNone);
type
TKZLMessageHandlerEvent = procedure(Sender: TObject; SenderCtrl: TControl; Msg: TLMessage) of object;
{ TKZLMessageHandler }
TKZLMessageHandler = class(TPersistent)
private
Control: TControl;
InheritedWndMethod: TWndMethod;
FMessagesIgnore: TList;
function ValidControl: Boolean;
public
OnBefforeMessage,
OnAfterMessage: TKZLMessageHandlerEvent;
procedure SelfWndMethod(var TheMessage: TLMessage);
procedure DestroyMe(Sender: TObject);
constructor Create(AControl: TControl);
procedure AddMessageIgnore(LM_: Integer);
procedure RemoveMessageIgnore(LM_: Integer);
end;
{
TKZDeskManagerFormInfo = class
public
Form: TCustomForm;
MessageHandler: TKZLMessageHandler;
end;
}
{ TKZDeskManager }
TKZDeskManager = class
private
function getItems(AIndex: Integer): TCustomForm; // TKZDeskManagerFormInfo;
protected
FRemoveBorder: Boolean;
FormParent: TWinControl;
ParentType: TKZParentType;
FItems: TList;
function IsMessageShowing(LM: TLMessage): Boolean;
public
AutoShowHideForms: Boolean;
property Items[AIndex: Integer]: TCustomForm { TKZDeskManagerFormInfo } read getItems;
procedure FormParentResize(Sender: TObject);
procedure FormParentVisibleChange(Sender: TObject);
procedure Prepare(_Form: TCustomForm); virtual;
procedure AddForm(_Form: TCustomForm); virtual;
procedure RemoveForm(_Form: TCustomForm); virtual;
procedure HideForms; virtual;
procedure ShowForms; virtual;
procedure BefforeMessage(Sender: TObject; SenderWindow: TControl; Msg: TLMessage); virtual;
procedure AfterMessage(Sender: TObject; SenderWindow: TControl; Msg: TLMessage); virtual;
constructor Create(_ParentControl: TWinControl; _ParentType: TKZParentType);
destructor Destroy; override;
end;
{ TKZCodeExplorerViewManager }
TKZCodeExplorerViewManager = class(TKZDeskManager)
public
procedure BefforeMessage(Sender: TObject; SenderWindow: TControl; Msg: TLMessage); override;
end;
{ TKZObjectInspectorManager }
TKZObjectInspectorManager = class(TKZDeskManager)
public
procedure Prepare(_Form: TCustomForm); override;
procedure BefforeMessage(Sender: TObject; SenderWindow: TControl; Msg: TLMessage); override;
procedure AfterMessage(Sender: TObject; SenderWindow: TControl; Msg: TLMessage); override;
end;
{ TKZMessagesViewManager }
TKZMessagesViewManager = class(TKZDeskManager)
public
procedure Prepare(_Form: TCustomForm); override;
procedure BefforeMessage(Sender: TObject; SenderWindow: TControl; Msg: TLMessage); override;
procedure AfterMessage(Sender: TObject; SenderWindow: TControl; Msg: TLMessage); override;
end;
{ TKZPackageManager }
TKZPackageManager = class(TKZDeskManager)
public
procedure BefforeMessage(Sender: TObject; SenderWindow: TControl; Msg: TLMessage); override;
end;
{ TKZSourceEditorManager }
TKZSourceEditorManager = class(TKZDeskManager)
public
procedure AddForm(_Form: TCustomForm); override;
procedure Prepare(_Form: TCustomForm); override;
procedure ShowForms; override;
procedure HideForms; override;
procedure BefforeMessage(Sender: TObject; SenderWindow: TControl; Msg: TLMessage); override;
procedure AfterMessage(Sender: TObject; SenderWindow: TControl; Msg: TLMessage); override;
end;
implementation
{ TKZSourceEditorManager }
procedure TKZSourceEditorManager.AddForm(_Form: TCustomForm);
begin
inherited AddForm(_Form);
end;
procedure TKZSourceEditorManager.Prepare(_Form: TCustomForm);
begin
inherited Prepare(_Form);
end;
procedure TKZSourceEditorManager.ShowForms;
var
i, a: Integer;
begin
inherited ShowForms;
// Veja a nota no 'HideForms;'. Aqui habilitamos novamente o SynEdit.
for i := 0 to FItems.Count - 1 do
begin
with TSourceEditorWindowInterface(Items[i]) do
begin
for a := 0 to Count - 1 do
begin
Items[a].EditorControl.Enabled := True;
end;
end;
end;
end;
procedure TKZSourceEditorManager.HideForms;
var
i, a: Integer;
begin
// Antes de esconder os forms editores, devemos desabilitar os SynEdits deles.
// Isso é necessário pois após esconder/mostrar o form, a posição do cursor no
// SynEdit se perde, e o editor fica como se alguém tivesse apertando a tecla
// END no editor, indo para o final da linha. Desabilitar o editor durate o pro-
// cesso impede que isso aconteça.
for i := 0 to FItems.Count - 1 do
begin
for a := 0 to TSourceEditorWindowInterface(Items[i]).Count - 1 do
begin
TSourceEditorWindowInterface(Items[i]).Items[a].
EditorControl.Enabled := False;
end;
end;
inherited HideForms;
end;
procedure TKZSourceEditorManager.BefforeMessage(Sender: TObject;
SenderWindow: TControl; Msg: TLMessage);
begin
inherited BefforeMessage(Sender, SenderWindow, Msg);
// Se ele vai exibir, precisa exibir a tabsheet antes
if IsMessageShowing(Msg) then
begin
if FormParent.Parent is TTabSheet then
begin
TTabSheet(FormParent.Parent).PageControl.ActivePage := TTabSheet(FormParent.Parent);
end;
end;
end;
procedure TKZSourceEditorManager.AfterMessage(Sender: TObject;
SenderWindow: TControl; Msg: TLMessage);
begin
inherited AfterMessage(Sender, SenderWindow, Msg);
if
(SourceEditorManagerIntf <> Nil) and
(SourceEditorManagerIntf.ActiveEditor <> Nil) and
(SourceEditorManagerIntf.ActiveEditor.EditorControl <> Nil)
then
begin
// Aqui damos foco no SynEdit. Isso é importante, pois como desabilitamos o
// editor no 'HideForms;', quando o editor aparece, fica sem foco.
with SourceEditorManagerIntf.ActiveEditor.EditorControl do
begin
if CanFocus then SetFocus;
end;
end;
end;
{ TKZPackageManager }
procedure TKZPackageManager.BefforeMessage(Sender: TObject;
SenderWindow: TControl; Msg: TLMessage);
begin
inherited BefforeMessage(Sender, SenderWindow, Msg);
{
// Se ele vai exibir, precisa exibir a tabsheet antes
if IsMessageShowing(Msg) then
begin
//if FormParent.Parent is TTabSheet then
//begin
//TTabSheet(FormParent.Parent).PageControl.ActivePage := TTabSheet(FormParent.Parent);
//ShowMessage('PK!');
//end;
end;
}
end;
{ TKZMessagesViewManager }
procedure TKZMessagesViewManager.Prepare(_Form: TCustomForm);
begin
inherited Prepare(_Form);
TPanel( FormParent ).BevelOuter := bvNone;
end;
procedure TKZMessagesViewManager.BefforeMessage(Sender: TObject;
SenderWindow: TControl; Msg: TLMessage);
begin
inherited BefforeMessage(Sender, SenderWindow, Msg);
end;
procedure TKZMessagesViewManager.AfterMessage(Sender: TObject;
SenderWindow: TControl; Msg: TLMessage);
begin
inherited AfterMessage(Sender, SenderWindow, Msg);
//if IsMessageShowing(Msg) then FormParentResize(FormParent);
end;
{ TKZObjectInspectorManager }
procedure TKZObjectInspectorManager.Prepare(_Form: TCustomForm);
begin
inherited Prepare(_Form);
_Form.FindChildControl('StatusBar').Visible := False;
// Teste
//while _Form.ControlCount > 0 do
//begin
// _Form.Controls[0].Parent := FormParent;
//end;
end;
procedure TKZObjectInspectorManager.BefforeMessage(Sender: TObject;
SenderWindow: TControl; Msg: TLMessage);
begin
inherited BefforeMessage(Sender, SenderWindow, Msg);
if IsMessageShowing(Msg) then
begin
if FormParent is TTabSheet then
with TTabSheet(FormParent) do
begin
PageControl.ActivePage := TTabSheet(FormParent);
end;
end;
{
if Msg.msg = LM_KEYDOWN {LM_SETEDITABLE} then
begin
LCLIntf.SetActiveWindow(TWinControl( SenderWindow ).Handle);
//SenderWindow.Parent.SetFocus;
//TWinControl( SenderWindow ).SetFocus;
IDEMessagesWindow.AddMsg('bah', '', 0);
end;
}
end;
procedure TKZObjectInspectorManager.AfterMessage(Sender: TObject;
SenderWindow: TControl; Msg: TLMessage);
begin
inherited AfterMessage(Sender, SenderWindow, Msg);
//if Pos('Unk', GetMessageName(Msg.msg)) = 0 then
//IDEMessagesWindow.AddMsg(FormatDateTime('HH:MM:ss', Now) + ': ' + GetMessageName(Msg.msg), '', 0);
end;
{ TKZCodeExplorerViewManager }
procedure TKZCodeExplorerViewManager.BefforeMessage(Sender: TObject;
SenderWindow: TControl; Msg: TLMessage);
begin
inherited BefforeMessage(Sender, SenderWindow, Msg);
if IsMessageShowing(Msg) then
begin
if FormParent is TTabSheet then
with TTabSheet(FormParent) do
begin
PageControl.ShowTabs := True;
PageControl.ActivePage := TTabSheet(FormParent);
end;
end;
end;
{ TKZLMessageHandler }
function TKZLMessageHandler.ValidControl: Boolean;
begin
Result := (Assigned(Control)) and (Control <> Nil);
end;
procedure TKZLMessageHandler.SelfWndMethod(var TheMessage: TLMessage);
var
i: Integer;
begin
if (not ValidControl) then Exit;
for i := 0 to FMessagesIgnore.Count - 1 do
begin
if Integer(FMessagesIgnore[i]) = TheMessage.msg then
begin
Exit;
end;
end;
if Assigned(OnBefforeMessage) then
OnBefforeMessage(Self, Control, TheMessage);
if Assigned(InheritedWndMethod) then
InheritedWndMethod(TheMessage);
if Assigned(OnAfterMessage) then
OnAfterMessage(Self, Control, TheMessage);
end;
procedure TKZLMessageHandler.DestroyMe(Sender: TObject);
begin
Free;
end;
constructor TKZLMessageHandler.Create(AControl: TControl);
begin
inherited Create;
FMessagesIgnore := TList.Create;
Control := AControl;
InheritedWndMethod := Control.WindowProc;
Control.WindowProc := @SelfWndMethod;
//Control.AddHandlerOnBeforeDestruction(@DestroyMe);
end;
procedure TKZLMessageHandler.AddMessageIgnore(LM_: Integer);
begin
FMessagesIgnore.Add(Pointer(LM_));
end;
procedure TKZLMessageHandler.RemoveMessageIgnore(LM_: Integer);
begin
FMessagesIgnore.Remove(Pointer(LM_));
end;
{ TKZDeskManager }
function TKZDeskManager.getItems(AIndex: Integer): TCustomForm; // TKZDeskManagerFormInfo;
begin
if FItems = Nil then
Result := Nil
else
Result := TCustomForm(FItems[AIndex]);
end;
function TKZDeskManager.IsMessageShowing(LM: TLMessage): Boolean;
begin
Result := (LM.msg = LM_SHOWWINDOW) and (TLMShowWindow(LM).Show);
end;
procedure TKZDeskManager.FormParentResize(Sender: TObject);
var
i: Integer;
begin
if FItems = Nil then Exit;
for i := 0 to FItems.Count - 1 do
begin
//if (Items[i].Form <> Nil) and (Assigned(Items[i].Form)) then
if Assigned( Items[i] ) then
begin
//with Items[i].Form do
with Items[i] do
begin
Left := 0;
Top := 0;
Width := FormParent.Width;
Height := FormParent.Height;
end;
end;
end;
end;
procedure TKZDeskManager.FormParentVisibleChange(Sender: TObject);
begin
if (not AutoShowHideForms) or (FormParent = Nil) then Exit;
if FormParent.Visible then
ShowForms
else
HideForms;
end;
procedure TKZDeskManager.Prepare(_Form: TCustomForm);
begin
AddForm(_Form);
end;
procedure TKZDeskManager.AddForm(_Form: TCustomForm);
var
aRect: TRect;
//item: TKZDeskManagerFormInfo;
begin
with _Form do
begin
if Self.FRemoveBorder then
BorderStyle := bsNone;
case ParentType of
kzptNone : ;
kzptDock :
begin
aRect.Left := 0;
aRect.Top := 0;
aRect.Right := Width;
aRect.Bottom := Height;
Dock(FormParent, aRect);
end;
kzptParent : Parent := FormParent;
kzptParentWindow : ParentWindow := FormParent.Handle;
end;
with TKZLMessageHandler.Create(_Form) do
begin
OnBefforeMessage := @BefforeMessage;
OnAfterMessage := @AfterMessage;
end;
end;
FItems.Add(_Form);
{
item := TKZDeskManagerFormInfo.Create;
with item do
begin
Form := _Form;
if Self.FRemoveBorder then
Form.BorderStyle := bsNone;
case ParentType of
kzptNone : ;
kzptDock :
begin
aRect.Left := 0;
aRect.Top := 0;
aRect.Right := Form.Width;
aRect.Bottom := Form.Height;
Form.Dock(FormParent, aRect);
end;
kzptParent : Form.Parent := FormParent;
kzptParentWindow : Form.ParentWindow := FormParent.Handle;
end;
//MessageHandler := TKZLMessageHandler.Create(Form);
with TKZLMessageHandler.Create(Form) do
begin
OnBefforeMessage := @BefforeMessage;
OnAfterMessage := @AfterMessage;
end;
end;
FItems.Add(item);
}
end;
procedure TKZDeskManager.RemoveForm(_Form: TCustomForm);
var
i: Integer;
begin
if FItems = Nil then Exit;
FItems.Remove(_Form);
{
for i := 0 to FItems.Count - 1 do
begin
if Items[i].Form = _Form then
begin
//Items[i].MessageHandler.Free;
FItems.Remove(_Form);
Break;
end;
end;
}
end;
procedure TKZDeskManager.HideForms;
var
i: Integer;
begin
if FItems = Nil then Exit;
for i := 0 to FItems.Count - 1 do
begin
if (Items[i] <> Nil) and (Assigned(Items[i])) then
begin
with Items[i] do
begin
Hide;
end;
end;
end;
end;
procedure TKZDeskManager.ShowForms;
var
i: Integer;
begin
if FItems = Nil then Exit;
for i := 0 to FItems.Count - 1 do
begin
if (Items[i] <> Nil) and (Assigned(Items[i])) then
begin
with Items[i] do
begin
Visible := True;
end;
end;
end;
end;
procedure TKZDeskManager.BefforeMessage(Sender: TObject;
SenderWindow: TControl; Msg: TLMessage);
begin
if Msg.msg = LM_DESTROY then
begin
RemoveForm(TCustomForm( SenderWindow ));
end;
end;
procedure TKZDeskManager.AfterMessage(Sender: TObject; SenderWindow: TControl;
Msg: TLMessage);
begin
if IsMessageShowing(Msg) then
FormParentResize(FormParent);
end;
constructor TKZDeskManager.Create(_ParentControl: TWinControl;
_ParentType: TKZParentType);
begin
FormParent := _ParentControl;
ParentType := _ParentType;
FItems := TList.Create;
FormParent.AddHandlerOnResize(@FormParentResize);
FormParent.AddHandlerOnVisibleChanged(@FormParentVisibleChange);
FRemoveBorder := True;
AutoShowHideForms := False;
end;
destructor TKZDeskManager.Destroy;
begin
FreeAndNil(FItems);
inherited Destroy;
end;
end.
|
unit CounterU;
interface
uses
Windows, Messages, SysUtils, Classes, HTTPApp, HTTPProd, SiteProd,
WebAdapt, WebComp, WebModu;
type
TCounter = class(TWebPageModule)
Adapter: TAdapter;
Count: TAdapterField;
Increment: TAdapterAction;
Dec: TAdapterAction;
PageProducer: TPageProducer;
Arg1: TAdapterField;
Add: TAdapterAction;
Subtract: TAdapterAction;
procedure GetParams(Sender: TObject; Params: TStrings);
procedure PageProducerModuleActivate(Sender: TObject);
procedure IncrementExecute(Sender: TObject; Params: TStrings);
procedure CountGetValue(Sender: TObject; var Value: Variant);
procedure DecExecute(Sender: TObject; Params: TStrings);
procedure Arg1Execute(Sender: TObject; Params: TStrings);
procedure Arg1GetValue(Sender: TObject; var Value: Variant);
private
FCount: Integer;
{ Private declarations }
public
{ Public declarations }
end;
function Counter: TCounter;
implementation
{$R *.dfm} {*.html}
uses WebReq, WebCntxt, WebFact, SiteComp, AdaptReq;
function Counter: TCounter;
begin
Result := TCounter(WebContext.FindModuleClass(TCounter));
end;
procedure TCounter.GetParams(Sender: TObject;
Params: TStrings);
begin
Params.Add(Format('Count=%d', [FCount]));
end;
procedure TCounter.PageProducerModuleActivate(Sender: TObject);
begin
// Initialize data
FCount := 0;
end;
procedure TCounter.IncrementExecute(Sender: TObject;
Params: TStrings);
begin
// Retrieve last value
FCount := StrToInt(Params.Values['Count']);
Inc(FCount);
end;
procedure TCounter.CountGetValue(Sender: TObject;
var Value: Variant);
begin
Value := FCount;
end;
procedure TCounter.DecExecute(Sender: TObject; Params: TStrings);
begin
FCount := StrToInt(Params.Values['Count']);
FCount := FCount - 1;
end;
procedure TCounter.Arg1Execute(Sender: TObject; Params: TStrings);
var
Value: IActionFieldValue;
begin
FCount := StrToInt(Params.Values['Count']);
Value := Arg1.ActionValue;
if Assigned(Value) then
try
if Value.ValueCount > 1 then
raise Exception.Create('Multiple values not supported')
else
if Sender = Add then
FCount := FCount + Value.Values[0]
else if Sender = Subtract then
FCount := FCount - Value.Values[0]
else
Assert(False);
except
on E: Exception do
Adapter.Errors.AddError(E);
end;
end;
procedure TCounter.Arg1GetValue(Sender: TObject; var Value: Variant);
begin
// Echo last value
if Arg1.ActionValue <> nil then
Value := Arg1.ActionValue.Values[0]
end;
initialization
if WebRequestHandler <> nil then
WebRequestHandler.AddWebModuleFactory(TWebPageModuleFactory.Create(TCounter, TWebPageInfo.Create([wpPublished {, wpLoginRequired}], '.html'), crOnDemand, caCache));
end.
|
unit Unit_Main_Gauche;
interface
uses
Main, Classes, Forms, SysUtils, ExtCtrls, Graphics,
mmSystem, Notes_MIDI, Musiques;
type
TMain_Gauche = class(TThread)
private
idNote: integer;
procedure OnTerminateProcedure(Sender : TObject);
protected
procedure ToucheDown;
procedure ToucheUp;
procedure Execute; override;
public
ThreadTerminated : Boolean;
constructor Create(Suspended : Boolean);
end;
implementation
constructor TMain_Gauche.Create(Suspended: Boolean);
begin
FreeOnTerminate := True;
inherited Create(Suspended);
OnTerminate := OnTerminateProcedure;
ThreadTerminated := False;
end;
procedure TMain_Gauche.ToucheDown;
begin
Form1.PianoToucheDown(Musique1_MG[idNote].Note1);
end;
procedure TMain_Gauche.ToucheUp;
begin
Form1.PianoToucheUp(Musique1_MG[idNote].Note1);
end;
procedure TMain_Gauche.Execute;
var
i: integer;
begin
for i := 0 to Length(Musique1_MG)-1 do
begin
if ThreadTerminated then exit;
idNote := i;
if Musique1_MG[i].Note1<>'' then
Synchronize(ToucheDown);
Sleep(Round(((60/BPM)*1000) * Musique1_MG[i].Duree));
if Musique1_MG[i].Note1<>'' then
Synchronize(ToucheUp);
end;
end;
procedure TMain_Gauche.OnTerminateProcedure(Sender: TObject);
begin
ThreadTerminated:=True;
end;
end.
|
unit uFeaPocket;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, ExtCtrls, StdCtrls, Math, uObjectFeature,
Buttons, jpeg, Vcl.Imaging.pngimage;
type
TfFeaPocket = class(TForm)
Panel1: TPanel;
PgCtrl: TPageControl;
tabPocketCirc: TTabSheet;
tabPocketRect: TTabSheet;
Image2: TImage;
comRectRadius: TComboBox;
Label1: TLabel;
edRectRadius: TLabeledEdit;
lbRectRadius: TLabel;
Image3: TImage;
edY: TLabeledEdit;
edX: TLabeledEdit;
Label3: TLabel;
edZ: TEdit;
Label5: TLabel;
Panel2: TPanel;
btnSad: TSpeedButton;
btnCancel: TBitBtn;
btnSave: TBitBtn;
Label2: TLabel;
comEdgeStyle: TComboBox;
edEdgeSize: TEdit;
lbEdgeSize: TLabel;
comEdgeStyleValue: TComboBox;
edPriemer: TEdit;
edVyska: TEdit;
edSirka: TEdit;
LinkLabel: TLabel;
procedure comRectRadiusChange(Sender: TObject);
function CountRadius: Double;
procedure CheckRadius(Sender: TObject);
procedure btnSaveClick(Sender: TObject);
procedure EditFeature(fea: integer);
procedure DecimalPoint(Sender: TObject; var Key: Char);
procedure FormActivate(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure btnSadClick(Sender: TObject);
procedure comEdgeStyleChange(Sender: TObject);
procedure LinkLabelClick(Sender: TObject);
procedure MathExp(Sender: TObject);
private
{ Private declarations }
public
is_editing: boolean; // udava, ci je okno otvorene pre vytvorenie alebo editovanie prvku
edited_feature_ID: integer; // cislo upravovanej feature
{ Public declarations }
end;
var
fFeaPocket: TfFeaPocket;
implementation
uses uMain, uMyTypes, uPanelSett, uConfig, uObjectPanel, uTranslate, uLib;
{$R *.dfm}
procedure TfFeaPocket.FormCreate(Sender: TObject);
begin
fMain.imgList_common.GetBitmap(0, btnSad.Glyph);
btnCancel.Glyph := fPanelSett.btnCancel.Glyph;
btnSave.Glyph := fPanelSett.btnSave.Glyph;
PgCtrl.ActivePageIndex := 0;
PgCtrl.OnDrawTab := fmain.DrawTabs;
end;
procedure TfFeaPocket.LinkLabelClick(Sender: TObject);
begin
fMain.BrowseWiki('tools-maximum-depths');
end;
procedure TfFeaPocket.MathExp(Sender: TObject);
begin
uLib.SolveMathExpression(Sender);
end;
procedure TfFeaPocket.FormActivate(Sender: TObject);
begin
if PgCtrl.ActivePageIndex = 0 then begin
edPriemer.SelectAll;
edPriemer.SetFocus;
end;
if PgCtrl.ActivePageIndex = 1 then begin
edSirka.SelectAll;
edSirka.SetFocus;
end;
end;
procedure TfFeaPocket.comEdgeStyleChange(Sender: TObject);
begin
comEdgeStyleValue.ItemIndex := comEdgeStyle.ItemIndex;
edEdgeSize.Enabled := (comEdgeStyle.ItemIndex = 1);
lbEdgeSize.Enabled := edEdgeSize.Enabled;
if edEdgeSize.Enabled then edEdgeSize.SetFocus;
end;
procedure TfFeaPocket.comRectRadiusChange(Sender: TObject);
begin
edRectRadius.Enabled := (comRectRadius.ItemIndex = 1);
lbRectRadius.Enabled := edRectRadius.Enabled;
if edRectRadius.Enabled then edRectRadius.SetFocus;
if not edRectRadius.Enabled then CheckRadius(sender);
end;
function TfFeaPocket.CountRadius: Double;
var
x, y: Double;
begin
try
x := StrToFloat(edSirka.Text);
y := StrToFloat(edVyska.Text);
result := 0.5; // default 1mm freza
if (x > 2) AND (y > 2) then result := 0.75; // freza 1.5 mm
if (x > 4) AND (y > 4) then result := 1; // freza 2 mm
if (x > 6) AND (y > 6) then result := 1.5; // freza 3 mm
if (x > 15) AND (y > 15) then result := 3; // freza 6 mm
except
result := 0;
end;
end;
procedure TfFeaPocket.CheckRadius(Sender: TObject);
begin
// podla toho, aky radius je vybraty v rozbalovacom menu,
// vpise hodnotu do editu Radius
if comRectRadius.ItemIndex = 0 then
edRectRadius.Text := FormatFloat('0.##', CountRadius );
if comRectRadius.ItemIndex = 2 then
edRectRadius.Text := '0';
end;
function CheckMinMax: boolean;
var
dummyInt, i: integer;
nastroj: string;
begin
result := true;
with fFeaPocket do begin
try
if (StrToFloat(edZ.Text) < 0) then begin
MessageBox(handle, PChar(TransTxt('Please enter depth as positive value')), PChar(TransTxt('Error')), MB_ICONERROR);
edZ.SetFocus;
result := false;
end;
if (StrToFloat(edZ.Text) >= _PNL.Hrubka) then begin
MessageBox(handle, PChar(TransTxt('Depth is too big.')+#13+TransTxt('Maximum = ')+FloatToStr(_PNL.Hrubka)), PChar(TransTxt('Error')), MB_ICONERROR);
edZ.SetFocus;
result := false;
end;
if (PgCtrl.ActivePageIndex = 0) then begin
if (StrToFloat(edPriemer.Text) < 1) then begin
MessageBox(handle, PChar(TransTxt('Diameter too small')), PChar(TransTxt('Error')), MB_ICONERROR);
edPriemer.Text := '1';
edPriemer.SetFocus;
result := false;
end;
if (StrToFloat(edPriemer.Text) >= (_PNL.Vyska+10)) OR (StrToFloat(edPriemer.Text) >= (_PNL.Sirka+10)) then begin
MessageBox(handle, PChar(TransTxt('Diameter too big')), PChar(TransTxt('Error')), MB_ICONERROR);
edPriemer.Text := FormatFloat('##0.###', Min(_PNL.Vyska,_PNL.Sirka)-1 );
edPriemer.SetFocus;
result := false;
end;
// kontrola maximalnej hlbky pre dany nastroj
for i := 0 to cfgToolMaxDepth.Count - 1 do begin
// vyberie sa maximalne velky nastroj, ktory dokaze urobit dany radius
if StrToFloat(cfgToolMaxDepth.Names[i]) <= StrToFloat(edPriemer.Text) then
nastroj := cfgToolMaxDepth.Names[i];
end;
if GetToolMaxDepth(nastroj) < StrToFloat(edZ.Text) then begin
MessageBox(handle, PChar(TransTxt('Depth is too big.')), PChar(TransTxt('Error')), MB_ICONERROR);
edZ.SetFocus;
result := false;
end;
end;
if (PgCtrl.ActivePageIndex = 1) then begin
if (StrToFloat(edSirka.Text) < 1) then begin
MessageBox(handle, PChar(TransTxt('Width too small')), PChar(TransTxt('Error')), MB_ICONERROR);
edSirka.Text := '1';
edSirka.SetFocus;
result := false;
end;
if (StrToFloat(edSirka.Text) > (_PNL.Sirka+10)) then begin
MessageBox(handle, PChar(TransTxt('Width too big')), PChar(TransTxt('Error')), MB_ICONERROR);
edSirka.Text := FormatFloat('##0.###',_PNL.Sirka+10);
edSirka.SetFocus;
result := false;
end;
if (StrToFloat(edVyska.Text) < 1) then begin
MessageBox(handle, PChar(TransTxt('Height too small')), PChar(TransTxt('Error')), MB_ICONERROR);
edVyska.Text := '1';
edVyska.SetFocus;
result := false;
end;
if (StrToFloat(edVyska.Text) > (_PNL.Vyska+10)) then begin
MessageBox(handle, PChar(TransTxt('Height too big')), PChar(TransTxt('Error')), MB_ICONERROR);
edVyska.Text := FormatFloat('##0.###',_PNL.Vyska+10);
edVyska.SetFocus;
result := false;
end;
if (StrToFloat(edRectRadius.Text) < 0.5) AND (comRectRadius.ItemIndex <> 2) then begin
MessageBox(handle, PChar(TransTxt('Radius too small')), PChar(TransTxt('Error')), MB_ICONERROR);
edRectRadius.Text := '0.5';
edRectRadius.SetFocus;
result := false;
end;
if (StrToFloat(edRectRadius.Text) > StrToFloat(edSirka.Text)/2) OR (StrToFloat(edRectRadius.Text) > StrToFloat(edVyska.Text)/2) then begin
MessageBox(handle, PChar(TransTxt('Radius too big')), PChar(TransTxt('Error')), MB_ICONERROR);
edRectRadius.Text := FormatFloat('##0.###', Min( StrToFloat(edSirka.Text) , StrToFloat(edVyska.Text) )/2 );
edRectRadius.SetFocus;
result := false;
end;
// kontrola maximalnej hlbky pre dany nastroj
for i := 0 to cfgToolMaxDepth.Count - 1 do begin
// vyberie sa maximalne velky nastroj, ktory dokaze urobit dany radius
if StrToFloat(cfgToolMaxDepth.Names[i])/2 <= StrToFloat(edRectRadius.Text) then
nastroj := cfgToolMaxDepth.Names[i];
end;
// v pripade zapichov sa vhodny nastroj vyberie inak
if StrToFloat(edRectRadius.Text) = 0 then begin
if CountRadius <= 0.75 then
nastroj := '1' // zapich v rohoch 1mm frezou (len u ozaj malych objektov)
else
nastroj := '1.5'; // zapich v rohoch u ostatnych - natvrdo 1.5mm frezou
end;
if GetToolMaxDepth(nastroj) < StrToFloat(edZ.Text) then begin
MessageBox(handle, PChar(TransTxt('Depth too big for required tool (increase corner radius). Max.depth =')+' '+cfgToolMaxDepth.Values[nastroj]+'mm'), PChar(TransTxt('Error')), MB_ICONERROR);
comRectRadius.SetFocus;
result := false;
end;
end;
if (comEdgeStyleValue.Text = 'cham45') then
if (StrToFLoat(edEdgeSize.Text) > StrToFloat(edZ.Text)) then begin
MessageBox(handle, PChar(TransTxt('Chamfer too big.')), PChar(TransTxt('Error')), MB_ICONERROR);
edEdgeSize.SetFocus;
result := false;
end;
except
MessageBox(handle, PChar(TransTxt('Incorrect numerical value')), PChar(TransTxt('Error')), MB_ICONERROR);
result := false;
end;
end; // with
end;
procedure TfFeaPocket.btnSaveClick(Sender: TObject);
var
feaID: integer;
newFea: TFeatureObject;
begin
if not CheckMinMax then begin
ModalResult := mrNone;
Exit;
end;
_PNL.PrepareUndoStep;
// ak niekto zada zrazenie hrany 0x45' tak automaticky sa zrazenie hrany vypne
try
if StrToFloat(edEdgeSize.Text)=0 then begin
comEdgeStyle.ItemIndex := 0;
comEdgeStyleValue.ItemIndex := 0;
edEdgeSize.Text := '';
end;
except
end;
if PgCtrl.ActivePageIndex = 0 then begin
if is_editing then feaID := edited_feature_ID
else feaID := _PNL.AddFeature(ftPocketCirc);
if feaID = -1 then Exit;
// este to dame do UNDO listu
if is_editing then
_PNL.CreateUndoStep('MOD', 'FEA', feaID)
else
_PNL.CreateUndoStep('CRT', 'FEA', feaID);
newFea := _PNL.GetFeatureByID(feaID);
newFea.Rozmer1 := StrToFloat(edPriemer.Text);
end;
if PgCtrl.ActivePageIndex = 1 then begin
if is_editing then feaID := edited_feature_ID
else feaID := _PNL.AddFeature(ftPocketRect);
if feaID = -1 then Exit;
// este to dame do UNDO listu
if is_editing then
_PNL.CreateUndoStep('MOD', 'FEA', feaID)
else
_PNL.CreateUndoStep('CRT', 'FEA', feaID);
newFea := _PNL.GetFeatureByID(feaID);
newFea.Rozmer1 := StrToFloat(edSirka.Text);
newFea.Rozmer2 := StrToFloat(edVyska.Text);
newFea.Rozmer3 := StrToFloat(edRectRadius.Text);
if newFea.Rozmer3 = 0 then begin // ak maju byt zapichy v rohoch, do Rozmer4 ulozi nastroj, ktory to bude robit (koli kresleniu)
if CountRadius <= 0.75 then
newFea.Rozmer4 := 1 // zapich v rohoch 1mm frezou (len u ozaj malych objektov)
else
newFea.Rozmer4 := 1.5; // zapich v rohoch u ostatnych - natvrdo 1.5mm frezou
end; // begin a end len koli 2 vnorenym if (aby nepomiesal ELSE)
end;
// ========== spolocne vlastnosti ===================
newFea.Poloha := MyPoint( StrToFloat(edX.Text), StrToFloat(edY.Text) );
newFea.Hlbka1 := StrToFloat(edZ.Text);
// styl opracovania hrany
newFea.Param2 := comEdgeStyleValue.Text;
if (comEdgeStyle.ItemIndex > 0) AND (StrToFloat(edEdgeSize.Text) > 0) then
newFea.Rozmer5 := StrToFloat(edEdgeSize.Text)
else
newFea.Rozmer5 := 0;
ModalResult := mrOK;
_PNL.Draw;
end;
procedure TfFeaPocket.EditFeature(fea: integer);
var
feature: TFeatureObject;
begin
is_editing := true;
edited_feature_ID := fea;
feature := _PNL.GetFeatureByID(fea);
if feature.Param2 = '' then feature.Param2 := '0'; // ak nie je zadefinovana hrana, zadefinujeme ju na 'ziadnu'
comEdgeStyleValue.ItemIndex := comEdgeStyleValue.Items.IndexOf(feature.Param2);
comEdgeStyle.ItemIndex := comEdgeStyleValue.ItemIndex;
if comEdgeStyle.ItemIndex > 0 then begin
edEdgeSize.Enabled := true;
edEdgeSize.Text := FloatToStr(feature.Rozmer5);
end else begin
edEdgeSize.Enabled := false;
end;
lbEdgeSize.Enabled := edEdgeSize.Enabled;
edX.Text := FormatFloat('0.###', feature.X);
edY.Text := FormatFloat('0.###', feature.Y);
edZ.Text := FormatFloat('0.###', feature.Hlbka1);
case feature.Typ of
ftPocketCirc: begin
tabPocketCirc.TabVisible := true;
tabPocketRect.TabVisible := false;
edPriemer.Text := FormatFloat('0.###', feature.Rozmer1);
end;
ftPocketRect: begin
tabPocketRect.TabVisible := true;
tabPocketCirc.TabVisible := false;
edSirka.Text := FormatFloat('0.###', feature.Rozmer1);
edVyska.Text := FormatFloat('0.###', feature.Rozmer2);
edRectRadius.Text := FormatFloat('0.###', feature.Rozmer3);
// este nastavime combo (podla toho ci hodnota radiusu = vypocitanej hodnote podla frezy)
if (feature.Rozmer3 = CountRadius) then
comRectRadius.ItemIndex := 0
else if (feature.Rozmer3 = 0) then
comRectRadius.ItemIndex := 2
else
comRectRadius.ItemIndex := 1;
edRectRadius.Enabled := (comRectRadius.ItemIndex = 1);
lbRectRadius.Enabled := edRectRadius.Enabled;
end;
end; //case
end;
procedure TfFeaPocket.DecimalPoint(Sender: TObject; var Key: Char);
begin
fMain.CheckDecimalPoint(sender, key, btnSave);
end;
procedure TfFeaPocket.btnSadClick(Sender: TObject);
begin
fmain.ShowWish('Pocket');
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.7 9/5/2004 3:16:58 PM JPMugaas
Should work in D9 DotNET.
Rev 1.6 3/8/2004 10:14:54 AM JPMugaas
Property editor for SASL mechanisms now supports TIdDICT.
Rev 1.5 2/26/2004 8:53:14 AM JPMugaas
Hack to restore the property editor for SASL mechanisms.
Rev 1.4 1/25/2004 4:28:42 PM JPMugaas
Removed a discontinued Unit.
Rev 1.3 1/25/2004 3:11:06 PM JPMugaas
SASL Interface reworked to make it easier for developers to use.
SSL and SASL reenabled components.
Rev 1.2 10/12/2003 1:49:28 PM BGooijen
Changed comment of last checkin
Rev 1.1 10/12/2003 1:43:28 PM BGooijen
Changed IdCompilerDefines.inc to Core\IdCompilerDefines.inc
Rev 1.0 11/14/2002 02:18:56 PM JPMugaas
}
unit IdDsnRegister;
interface
{$I IdCompilerDefines.inc}
uses
Classes,
{$IFDEF DOTNET}
Borland.Vcl.Design.DesignIntF,
Borland.Vcl.Design.DesignEditors
{$ELSE}
{$IFDEF FPC}
PropEdits,
ComponentEditors
{$ELSE}
{$IFDEF VCL_6_OR_ABOVE}
DesignIntf,
DesignEditors
{$ELSE}
Dsgnintf
{$ENDIF}
{$ENDIF}
{$ENDIF}
;
// Procs
type
TIdPropEdSASL = class(TClassProperty)
public
procedure Edit; override;
function GetAttributes: TPropertyAttributes; override;
function GetValue: string; override;
procedure SetValue(const Value: string); override;
end;
{$IFDEF TSelectionEditor}
{$IFDEF USE_OPENSSL}
TIdOpenSSLSelectionEditor = class(TSelectionEditor)
public
procedure RequiresUnits(Proc: TGetStrProc); override;
end;
{$ENDIF}
TIdFTPServerSelectionEditor = class(TSelectionEditor)
public
procedure RequiresUnits(Proc: TGetStrProc); override;
end;
{$ENDIF}
procedure Register;
implementation
uses
IdDsnResourceStrings,
{$IFDEF WIDGET_WINFORMS}
IdDsnSASLListEditorFormNET,
{$R 'IdDsnSASLListEditorFormNET.TfrmSASLListEditor.resources' 'IdDsnSASLListEditorFormNET.resx'}
{$ENDIF}
{$IFDEF WIDGET_VCL_LIKE_OR_KYLIX}
IdDsnSASLListEditorFormVCL,
{$ENDIF}
{$IFDEF TSelectionEditor}
{$IFDEF USE_OPENSSL}
IdSSLOpenSSL,
{$ENDIF}
IdFTPServer,
{$ENDIF}
IdSASL, IdSASLCollection,
SysUtils, TypInfo;
{Since we are removing New Design-Time part, we remove the "New Message Part Editor"}
{IdDsnNewMessagePart, }
type
{$IFDEF WIDGET_WINFORMS}
//we make a create here because I'm not sure how the Visual Designer for WinForms
//we behave in a package. I know it can act weird if something is renamed
TfrmSASLListEditor = class(IdDsnSASLListEditorFormNET.TfrmSASLListEditor)
public
constructor Create(AOwner : TComponent);
end;
{$ENDIF}
{$IFDEF WIDGET_VCL_LIKE_OR_KYLIX}
TfrmSASLListEditor = class(TfrmSASLListEditorVCL);
{$ENDIF}
{ TfrmSASLListEditor }
{$IFDEF WIDGET_WINFORMS}
constructor TfrmSASLListEditor.Create(AOwner : TComponent);
begin
inherited Create;
end;
{$ENDIF}
{$IFDEF TSelectionEditor}
{$IFDEF USE_OPENSSL}
{TIdOpenSSLSelectionEditor}
procedure TIdOpenSSLSelectionEditor.RequiresUnits(Proc: TGetStrProc);
begin
inherited RequiresUnits(Proc);
//for new callback event
Proc('IdCTypes');
Proc('IdSSLOpenSSLHeaders');
end;
{$ENDIF}
{TIdFTPServerSelectionEditor}
procedure TIdFTPServerSelectionEditor.RequiresUnits(Proc: TGetStrProc);
begin
inherited RequiresUnits(Proc);
Proc('IdFTPListOutput');
Proc('IdFTPList');
end;
{$ENDIF}
{ TIdPropEdSASL }
procedure TIdPropEdSASL.Edit;
var
LF: TfrmSASLListEditor;
LComp: TPersistent;
LList: TIdSASLEntries;
begin
inherited Edit;
LComp := GetComponent(0);
{$IFDEF HAS_GetObjectProp}
LList := TIdSASLEntries(GetObjectProp(LComp, GetPropInfo, TIdSASLEntries));
{$ELSE}
LList := TObject(GetOrdProp(LComp, GetPropInfo)) as TIdSASLEntries;
{$ENDIF}
LF := TfrmSASLListEditor.Create(nil);
try
if LComp is TComponent then begin
LF.SetComponentName(TComponent(LComp).Name);
end;
LF.SetList(LList);
if LF.Execute then begin
LF.GetList(LList);
end;
finally
FreeAndNil(LF);
end;
end;
function TIdPropEdSASL.GetAttributes: TPropertyAttributes;
begin
Result := inherited GetAttributes + [paDialog];
end;
function TIdPropEdSASL.GetValue: string;
begin
Result := GetStrValue;
end;
procedure TIdPropEdSASL.SetValue(const Value: string);
begin
inherited SetValue(Value);
end;
procedure Register;
begin
RegisterPropertyEditor(TypeInfo(TIdSASLEntries), nil, '', TIdPropEdSASL);
{$IFDEF TSelectionEditor}
{$IFDEF USE_OPENSSL}
RegisterSelectionEditor(TIdServerIOHandlerSSLOpenSSL, TIdOpenSSLSelectionEditor);
RegisterSelectionEditor(TIdSSLIOHandlerSocketOpenSSL, TIdOpenSSLSelectionEditor);
{$ENDIF}
RegisterSelectionEditor(TIdFTPServer,TIdFTPServerSelectionEditor);
{$ENDIF}
end;
end.
|
unit array_dynamic_4;
interface
implementation
type
TIntArray = array of int32;
var
A: TIntArray;
G, X: Int32;
procedure Test(Arr: TIntArray);
var
L, R: Int32;
begin
L := 0;
R := 9;
X := L + (R - L) shr 1;
G := Arr[X];
end;
initialization
A := [4, 7, 1 , 6, 2, 0, 3, 5, 9, 8];
Test(A);
finalization
Assert(G = 2);
end. |
unit untUserManager;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, GridsEh, DBGridEh, StdCtrls, DB,
Mask, RzEdit, RzDBEdit, RzButton, RzLabel, ImgList,
RzPanel, ActnList, Menus, DBGridEhGrouping;
type
TfrmUserManager = class(TForm)
pnlTop: TPanel;
pnlCenter: TPanel;
dbgrdhUserInfo: TDBGridEh;
edtUserName: TRzDBEdit;
edtRealName: TRzDBEdit;
edtEmail: TRzDBEdit;
RzToolbar1: TRzToolbar;
btnCreate: TRzToolButton;
ilUserManager: TImageList;
btnDelete: TRzToolButton;
lblusername: TRzLabel;
lblrealname: TRzLabel;
lblemail: TRzLabel;
lblpassword: TRzLabel;
edtPassword: TRzDBEdit;
btnUpdate: TRzToolButton;
btnOK: TRzToolButton;
btnCancel: TRzToolButton;
actlstUserManager: TActionList;
actCreate: TAction;
actDelete: TAction;
actUpdate: TAction;
actSetRole: TAction;
pmUserManager: TPopupMenu;
N1: TMenuItem;
N2: TMenuItem;
N3: TMenuItem;
N4: TMenuItem;
btnExit: TRzToolButton;
btnRefresh: TRzToolButton;
actRefresh: TAction;
procedure FormCreate(Sender: TObject);
procedure actCreateExecute(Sender: TObject);
procedure actDeleteExecute(Sender: TObject);
procedure actUpdateExecute(Sender: TObject);
procedure actSetRoleExecute(Sender: TObject);
procedure btnOKClick(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btnExitClick(Sender: TObject);
procedure actRefreshExecute(Sender: TObject);
private
procedure SetButtonEnable;
public
{ Public declarations }
end;
//var
// frmUserManager: TfrmUserManager;
implementation
uses untSysManagerDM, untCommonUtil, untSetRole;
{$R *.dfm}
procedure TfrmUserManager.FormCreate(Sender: TObject);
begin
frmSysManagerDM.qryUserInfo.Open;
end;
//设置按钮互斥状态
procedure TfrmUserManager.SetButtonEnable;
begin
//按钮
btnCreate.Enabled := not btnCreate.Enabled;
btnDelete.Enabled := not btnDelete.Enabled;
btnUpdate.Enabled := not btnUpdate.Enabled;
btnOK.Enabled := not btnOK.Enabled;
btnCancel.Enabled := not btnCancel.Enabled;
//编辑框
edtUserName.ReadOnly := not edtUserName.ReadOnly;
edtRealName.ReadOnly := not edtRealName.ReadOnly;
edtEmail.ReadOnly := not edtEmail.ReadOnly;
edtPassword.ReadOnly := not edtPassword.ReadOnly;
//表格
dbgrdhUserInfo.Enabled := not dbgrdhUserInfo.Enabled;
end;
//创建
procedure TfrmUserManager.actCreateExecute(Sender: TObject);
begin
SetButtonEnable;
if frmSysManagerDM.qryUserInfo.State <> dsBrowse then
frmSysManagerDM.qryUserInfo.Cancel;
frmSysManagerDM.qryUserInfo.Append;
frmSysManagerDM.qryUserInfo.FieldByName('create_date').AsDateTime := Date+Time;
end;
//删除
procedure TfrmUserManager.actDeleteExecute(Sender: TObject);
begin
if Application.MessageBox('确定删除记录?', '提示', MB_OKCANCEL +
MB_DEFBUTTON2) = IDOK then
begin
if frmSysManagerDM.qryUserInfo.State = dsBrowse then
begin
frmSysManagerDM.qryUserInfo.Delete;
end else
begin
frmSysManagerDM.qryUserInfo.Cancel;
frmSysManagerDM.qryUserInfo.Delete;
end;
end;
end;
//修改
procedure TfrmUserManager.actUpdateExecute(Sender: TObject);
begin
SetButtonEnable;
if frmSysManagerDM.qryUserInfo.State = dsBrowse then
begin
frmSysManagerDM.qryUserInfo.Edit;
end else
begin
frmSysManagerDM.qryUserInfo.Cancel;
frmSysManagerDM.qryUserInfo.Edit;
end;
end;
//设置用户角色
procedure TfrmUserManager.actSetRoleExecute(Sender: TObject);
begin
if frmSysManagerDM.qryUserInfo.RecordCount > 0 then
ShowModalForm(TfrmSetRole)
else
ShowMessage('请选择用户!');
end;
//确定
procedure TfrmUserManager.btnOKClick(Sender: TObject);
begin
if frmSysManagerDM.qryUserInfo.State in [dsInsert,dsEdit] then
begin
frmSysManagerDM.qryUserInfo.Post;
end;
SetButtonEnable;
end;
//取消
procedure TfrmUserManager.btnCancelClick(Sender: TObject);
begin
if frmSysManagerDM.qryUserInfo.State in [dsInsert,dsEdit] then
begin
frmSysManagerDM.qryUserInfo.Cancel;
end;
SetButtonEnable;
end;
//窗口关闭
procedure TfrmUserManager.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
frmSysManagerDM.qryUserInfo.Close;
end;
//退出窗口
procedure TfrmUserManager.btnExitClick(Sender: TObject);
begin
Self.Close;
end;
//刷新
procedure TfrmUserManager.actRefreshExecute(Sender: TObject);
begin
frmSysManagerDM.qryUserInfo.Refresh;
end;
end.
|
unit Room;
interface
uses
Classes, SysUtils, Contnrs,
Client;
type
EIncorrectRoomName = class(Exception);
ERoomExists = class(Exception);
EAlreadyInChannel = class(Exception);
TRoom = class
constructor Create(RoomName: string);
public
dRoomName: string;
dUsers: TObjectList;
procedure AddUser(Client: TClient);
procedure RemoveUser(var Client: TClient);
function IsUserInRoom(var Client: TClient) : boolean;
function RoomName : string;
// Уведомить всех о выходе пользователя
procedure NotifyUsers(NickName: string);
// Отправить текст всем пользователям в комнате
procedure SendText(NickName, Text: string);
function GetListOfUsers : string;
end;
implementation
{ TRoom }
constructor TRoom.Create(RoomName: string);
begin
dRoomName := RoomName;
dUsers := TObjectList.Create;
dUsers.OwnsObjects := False;
end;
procedure TRoom.AddUser(Client: TClient);
begin
if dUsers.IndexOf(Client) = -1 then
dUsers.Add(Client)
else
raise EAlreadyInChannel.CreateFmt('Client #%d / %s is already in channel ' +
'%s', [Client.SocketHandle, Client.NickName, RoomName]);
end;
procedure TRoom.RemoveUser(var Client: TClient);
var
i, j: integer;
tmpClient: TClient;
begin
for i := 0 to dUsers.Count - 1 do
begin
tmpClient := dUsers.Items[i] as TClient;
if tmpClient.dSocketHandle = Client.dSocketHandle then
begin
dUsers.Delete(i);
for j := 0 to dUsers.Count - 1 do
begin
tmpClient := dUsers.Items[j] as TClient;
tmpClient.dSocket.SendText('$p ' + Client.NickName + ' ' + dRoomName + #13#10);
end;
Exit;
end;
end;
end;
function TRoom.IsUserInRoom(var Client: TClient) : boolean;
var
flag: boolean;
i: integer;
tmpClient: TClient;
begin
flag := False;
for i := 0 to dUsers.Count - 1 do
begin
tmpClient := dUsers.Items[i] as TClient;
if tmpClient.dSocketHandle = Client.dSocketHandle then
begin
flag := True;
Break;
end;
end;
Result := flag;
end;
function TRoom.RoomName : string;
begin
Result := dRoomName;
end;
procedure TRoom.NotifyUsers(NickName: string);
var
i: integer;
tmpClient: TClient;
begin
for i := 0 to dUsers.Count - 1 do
begin
tmpClient := dUsers.Items[i] as TClient;
tmpClient.dSocket.SendText('$n ' + NickName + ' ' + dRoomName + #13#10);
end;
end;
procedure TRoom.SendText(NickName, Text: string);
var
i: integer;
tmpClient: TClient;
begin
for i := 0 to dUsers.Count - 1 do
begin
tmpClient := dUsers.Items[i] as TClient;
tmpClient.dSocket.SendText('$m ' + dRoomName + ' ' +
NickName + ' ' + Text + #13#10);
end;
end;
function TRoom.GetListOfUsers : string;
var
str: string;
i: integer;
tmpClient: TClient;
begin
str := '';
for i := 0 to dUsers.Count - 1 do
begin
tmpClient := dUsers.Items[i] as TClient;
str := str + tmpClient.NickName + ' ';
end;
Result := str;
end;
end.
|
unit Rollbar;
interface
uses
{$IF CompilerVersion > 26} //Delphi XE6 or later.
System.JSON;
{$ELSE}
Data.DBXJSON;
{$ENDIF}
type
IRollbarRequest = interface
function ToJSON: string;
function GetUnixTimestamp: Int64;
function GetAccessToken: string;
function GetClient: TJSONObject;
function GetCodeVersion: string;
function GetContext: string;
function GetCustom: TJSONObject;
function GetEnvironment: string;
function GetFingerprint: string;
function GetFramework: string;
function GetLanguage: string;
function GetLevel: string;
function GetNotifierName: string;
function GetNotifierVersion: string;
function GetPersonEmail: string;
function GetPersonId: string;
function GetPersonUsername: string;
function GetRequest: TJSONObject;
function GetServerBranch: string;
function GetServerCodeVersion: string;
function GetServerHost: string;
function GetServerRoot: string;
function GetTimestamp: TDateTime;
function GetTitle: string;
function GetUUID: string;
procedure SetAccessToken(const Value: string);
procedure SetCodeVersion(const Value: string);
procedure SetContext(const Value: string);
procedure SetEnvironment(const Value: string);
procedure SetFingerprint(const Value: string);
procedure SetFramework(const Value: string);
procedure SetLanguage(const Value: string);
procedure SetLevel(const Value: string);
procedure SetNotifierName(const Value: string);
procedure SetNotifierVersion(const Value: string);
procedure SetPersonEmail(const Value: string);
procedure SetPersonId(const Value: string);
procedure SetPersonUsername(const Value: string);
procedure SetServerBranch(const Value: string);
procedure SetServerCodeVersion(const Value: string);
procedure SetServerHost(const Value: string);
procedure SetServerRoot(const Value: string);
procedure SetTimestamp(const Value: TDateTime);
procedure SetTitle(const Value: string);
procedure SetUUID(const Value: string);
property AccessToken: string read GetAccessToken write SetAccessToken;
property Environment: string read GetEnvironment write SetEnvironment;
property Level: string read GetLevel write SetLevel;
property Timestamp: TDateTime read GetTimestamp write SetTimestamp;
property CodeVersion: string read GetCodeVersion write SetCodeVersion;
property Language: string read GetLanguage write SetLanguage;
property Framework: string read GetFramework write SetFramework;
property Context: string read GetContext write SetContext;
property Request: TJSONObject read GetRequest;
property PersonId: string read GetPersonId write SetPersonId;
property PersonUsername: string read GetPersonUsername write SetPersonUsername;
property PersonEmail: string read GetPersonEmail write SetPersonEmail;
property ServerHost: string read GetServerHost write SetServerHost;
property ServerRoot: string read GetServerRoot write SetServerRoot;
property ServerBranch: string read GetServerBranch write SetServerBranch;
property ServerCodeVersion: string read GetServerCodeVersion write SetServerCodeVersion;
property Client: TJSONObject read GetClient;
property Custom: TJSONObject read GetCustom;
property Fingerprint: string read GetFingerprint write SetFingerprint;
property Title: string read GetTitle write SetTitle;
property UUID: string read GetUUID write SetUUID;
property NotifierName: string read GetNotifierName write SetNotifierName;
property NotifierVersion: string read GetNotifierVersion write SetNotifierVersion;
//Not streamed
property UnixTimestamp: Int64 read GetUnixTimestamp;
end;
IRollbarMessage = interface(IRollbarRequest)
function GetBody: string;
procedure SetBody(const Value: string);
property Body: string read GetBody write SetBody;
end;
TDynStringArray = array of string;
IRollbarFrame = interface
function GetFilename: string;
function GetLineNo: Integer;
function GetColNo: Integer;
function GetMethod: string;
function GetCode: string;
function GetContextPre: TDynStringArray;
function GetContextPost: TDynStringArray;
procedure SetFilename(const Value: string);
procedure SetLineNo(const Value: Integer);
procedure SetColNo(const Value: Integer);
procedure SetMethod(const Value: string);
procedure SetCode(const Value: string);
procedure AddContextPre(const Value: string);
procedure AddContextPost(const Value: string);
property Filename: string read GetFilename write SetFilename;
property LineNo: Integer read GetLineNo write SetLineNo;
property ColNo: Integer read GetColNo write SetColNo;
property Method: string read GetMethod write SetMethod;
property Code: string read GetCode write SetCode;
property ContextPre: TDynStringArray read GetContextPre;
property ContextPost: TDynStringArray read GetContextPost;
// Args and KwArgs we will leave out for now....
end;
TRollbarFrames = array of IRollbarFrame;
IRollbarTrace = interface(IRollbarRequest)
function GetExceptionClass: string;
function GetExceptionMessage: string;
function GetExceptionDescription: string;
function GetFrames: TRollbarFrames;
procedure SetExceptionClass(const Value: string);
procedure SetExceptionMessage(const Value: string);
procedure SetExceptionDescription(const Value: string);
function AddFrame: IRollbarFrame;
property ExceptionClass: string read GetExceptionClass write SetExceptionClass;
property ExceptionMessage: string read GetExceptionMessage write SetExceptionMessage;
property ExceptionDescription: string read GetExceptionDescription write SetExceptionDescription;
property Frames: TRollbarFrames read GetFrames;
end;
IRollbarResponse = interface
function GetErr: Integer;
function GetResultUUID: string;
function GetErrMsg: string;
property Err: Integer read GetErr;
property ResultUUID: string read GetResultUUID;
property ErrMsg: string read GetErrMsg;
end;
IRollbarServer = interface
function Submit(Request: IRollbarRequest): IRollbarResponse;
end;
TRollbar = class
public
class function Message: IRollbarMessage;
class function Trace: IRollbarTrace;
class function Server(AccessToken, Environment: string): IRollbarServer;
end;
implementation
uses
IdBaseComponent,
IdComponent,
IdHTTP,
IdTCPConnection,
IdTCPClient,
JSONSerialize,
System.Classes,
System.DateUtils,
System.SysUtils;
type
TRollbarBase = class(TInterfacedObject, IRollbarRequest)
private
FAccessToken: string;
FClient: TJSONObject;
FCodeVersion: string;
FContext: string;
FCustom: TJSONObject;
FEnvironment: string;
FFingerprint: string;
FFramework: string;
FLanguage: string;
FLevel: string;
FNotifierName: string;
FNotifierVersion: string;
FPersonEmail: string;
FPersonId: string;
FPersonUsername: string;
FRequest: TJSONObject;
FServerBranch: string;
FServerCodeVersion: string;
FServerHost: string;
FServerRoot: string;
FTimestamp: Int64;
FTitle: string;
FUUID: string;
function GetAccessToken: string;
function GetClient: TJSONObject;
function GetCodeVersion: string;
function GetContext: string;
function GetCustom: TJSONObject;
function GetEnvironment: string;
function GetFingerprint: string;
function GetFramework: string;
function GetLanguage: string;
function GetLevel: string;
function GetNotifierName: string;
function GetNotifierVersion: string;
function GetPersonEmail: string;
function GetPersonId: string;
function GetPersonUsername: string;
function GetRequest: TJSONObject;
function GetServerBranch: string;
function GetServerCodeVersion: string;
function GetServerHost: string;
function GetServerRoot: string;
function GetTimestamp: TDateTime;
function GetTitle: string;
function GetUUID: string;
procedure SetAccessToken(const Value: string);
procedure SetCodeVersion(const Value: string);
procedure SetContext(const Value: string);
procedure SetEnvironment(const Value: string);
procedure SetFingerprint(const Value: string);
procedure SetFramework(const Value: string);
procedure SetLanguage(const Value: string);
procedure SetLevel(const Value: string);
procedure SetNotifierName(const Value: string);
procedure SetNotifierVersion(const Value: string);
procedure SetPersonEmail(const Value: string);
procedure SetPersonId(const Value: string);
procedure SetPersonUsername(const Value: string);
procedure SetServerBranch(const Value: string);
procedure SetServerCodeVersion(const Value: string);
procedure SetServerHost(const Value: string);
procedure SetServerRoot(const Value: string);
procedure SetTimestamp(const Value: TDateTime);
procedure SetTitle(const Value: string);
procedure SetUUID(const Value: string);
function GetUnixTimestamp: Int64;
public
destructor Destroy; override;
function ToJSON: string;
[JSONPath('access_token')]
property AccessToken: string read GetAccessToken write SetAccessToken;
[JSONPath('data/environment')]
property Environment: string read GetEnvironment write SetEnvironment;
[JSONPath('data/level')]
property Level: string read GetLevel write SetLevel;
property Timestamp: TDateTime read GetTimestamp write SetTimestamp;
[JSONPath('data/timestamp')]
property UnixTimestamp: Int64 read GetUnixTimestamp;
[JSONPath('data/code_version')]
property CodeVersion: string read GetCodeVersion write SetCodeVersion;
[JSONPath('data/language')]
property Language: string read GetLanguage write SetLanguage;
[JSONPath('data/framework')]
property Framework: string read GetFramework write SetFramework;
[JSONPath('data/context')]
property Context: string read GetContext write SetContext;
[JSONPath('data/request')]
property Request: TJSONObject read GetRequest;
[JSONPath('data/person/id')]
property PersonId: string read GetPersonId write SetPersonId;
[JSONPath('data/person/username')]
property PersonUsername: string read GetPersonUsername write SetPersonUsername;
[JSONPath('data/person/email')]
property PersonEmail: string read GetPersonEmail write SetPersonEmail;
[JSONPath('data/server/host')]
property ServerHost: string read GetServerHost write SetServerHost;
[JSONPath('data/server/root')]
property ServerRoot: string read GetServerRoot write SetServerRoot;
[JSONPath('data/server/branch')]
property ServerBranch: string read GetServerBranch write SetServerBranch;
[JSONPath('data/server/code_version')]
property ServerCodeVersion: string read GetServerCodeVersion write SetServerCodeVersion;
[JSONPath('data/client')]
property Client: TJSONObject read GetClient;
[JSONPath('data/custom')]
property Custom: TJSONObject read GetCustom;
[JSONPath('data/fingerprint')]
property Fingerprint: string read GetFingerprint write SetFingerprint;
[JSONPath('data/title')]
property Title: string read GetTitle write SetTitle;
[JSONPath('data/uuid')]
property UUID: string read GetUUID write SetUUID;
[JSONPath('data/notifier/name')]
property NotifierName: string read GetNotifierName write SetNotifierName;
[JSONPath('data/notifier/version')]
property NotifierVersion: string read GetNotifierVersion write SetNotifierVersion;
end;
TRollbarMessage = class(TRollbarBase, IRollbarMessage)
private
FBody: string;
function GetBody: string;
procedure SetBody(const Value: string);
public
[JSONPath('data/body/message/body')]
property Body: string read GetBody write SetBody;
end;
TRollbarFrame = class(TInterfacedObject, IRollbarFrame)
private
FFilename: string;
FLineNo: Integer;
FColNo: Integer;
FMethod: string;
FCode: string;
FContextPre: TDynStringArray;
FContextPost: TDynStringArray;
function GetFilename: string;
function GetLineNo: Integer;
function GetColNo: Integer;
function GetMethod: string;
function GetCode: string;
function GetContextPre: TDynStringArray;
function GetContextPost: TDynStringArray;
procedure SetFilename(const Value: string);
procedure SetLineNo(const Value: Integer);
procedure SetColNo(const Value: Integer);
procedure SetMethod(const Value: string);
procedure SetCode(const Value: string);
public
procedure AddContextPre(const Value: string);
procedure AddContextPost(const Value: string);
[JSONPath('filename')]
property Filename: string read GetFilename write SetFilename;
[JSONPath('lineno')]
property LineNo: Integer read GetLineNo write SetLineNo;
[JSONPath('colno')]
property ColNo: Integer read GetColNo write SetColNo;
[JSONPath('method')]
property Method: string read GetMethod write SetMethod;
[JSONPath('code')]
property Code: string read GetCode write SetCode;
[JSONPath('context/pre')]
property ContextPre: TDynStringArray read GetContextPre;
[JSONPath('context/post')]
property ContextPost: TDynStringArray read GetContextPost;
// Args and KwArgs we will leave out for now....
end;
TRollbarTrace = class(TRollbarBase, IRollbarTrace)
private
FExceptionClass: string;
FExceptionMessage: string;
FExceptionDescription: string;
FFrames: TRollbarFrames;
function GetExceptionClass: string;
function GetExceptionMessage: string;
function GetExceptionDescription: string;
function GetFrames: TRollbarFrames;
procedure SetExceptionClass(const Value: string);
procedure SetExceptionMessage(const Value: string);
procedure SetExceptionDescription(const Value: string);
public
function AddFrame: IRollbarFrame;
[JSONPath('data/body/trace/exception/class')]
property ExceptionClass: string read GetExceptionClass write SetExceptionClass;
[JSONPath('data/body/trace/exception/message')]
property ExceptionMessage: string read GetExceptionMessage write SetExceptionMessage;
[JSONPath('data/body/trace/exception/description')]
property ExceptionDescription: string read GetExceptionDescription write SetExceptionDescription;
[JSONPath('data/body/trace/frames')]
property Frames: TRollbarFrames read GetFrames;
end;
TRollbarResponse = class(TInterfacedObject, IRollbarResponse)
private
FJsonResp: TJSONObject;
function GetErr: Integer;
function GetResultUUID: string;
function GetErrMsg: string;
public
constructor Create(JsonResp: TJSONObject);
property Err: Integer read GetErr;
property ResultUUID: string read GetResultUUID;
property ErrMsg: string read GetErrMsg;
end;
TRollbarServer = class(TInterfacedObject, IRollbarServer)
private
FSvr: TIdHttp;
FAccessToken: string;
FEnvironment: string;
public
constructor Create(AccessToken: string; Environment: string);
destructor Destroy; override;
function Submit(Request: IRollbarRequest): IRollbarResponse;
end;
function TryGetJSONValue(const Root: TJSONObject; const Path: string; var Value: TJSONValue): Boolean;
begin
{$IF CompilerVersion > 26} //Delphi XE6 or later.
Result := Root.TryGetValue(Path, Value);
{$ELSE}
Value := Root.Get(Path).JsonValue;
Result := Assigned(Value);
{$ENDIF}
end;
{ TRollbarBase }
destructor TRollbarBase.Destroy;
begin
FreeAndNil(FClient);
FreeAndNil(FCustom);
FreeAndNil(FRequest);
inherited;
end;
function TRollbarBase.GetAccessToken: string;
begin
Result := FAccessToken;
end;
function TRollbarBase.GetClient: TJSONObject;
begin
if not Assigned(FClient) then
begin
FClient := TJSONObject.Create;
FClient.Owned := False;
end;
Result := FClient;
end;
function TRollbarBase.GetCodeVersion: string;
begin
Result := FCodeVersion;
end;
function TRollbarBase.GetContext: string;
begin
Result := FContext;
end;
function TRollbarBase.GetCustom: TJSONObject;
begin
if not Assigned(FCustom) then
begin
FCustom := TJSONObject.Create;
FCustom.Owned := False;
end;
Result := FCustom;
end;
function TRollbarBase.GetEnvironment: string;
begin
Result := FEnvironment;
end;
function TRollbarBase.GetFingerprint: string;
begin
Result := FFingerprint;
end;
function TRollbarBase.GetFramework: string;
begin
Result := FFramework;
end;
function TRollbarBase.GetLanguage: string;
begin
Result := FLanguage;
end;
function TRollbarBase.GetLevel: string;
begin
Result := FLevel;
end;
function TRollbarBase.GetNotifierName: string;
begin
Result := FNotifierName;
end;
function TRollbarBase.GetNotifierVersion: string;
begin
Result := FNotifierVersion;
end;
function TRollbarBase.GetPersonEmail: string;
begin
Result := FPersonEmail;
end;
function TRollbarBase.GetPersonId: string;
begin
Result := FPersonId;
end;
function TRollbarBase.GetPersonUsername: string;
begin
Result := FPersonUsername;
end;
function TRollbarBase.GetRequest: TJSONObject;
begin
if not Assigned(FRequest) then
begin
FRequest := TJSONObject.Create;
FRequest.Owned := False;
end;
Result := FRequest;
end;
function TRollbarBase.GetServerBranch: string;
begin
Result := FServerBranch;
end;
function TRollbarBase.GetServerCodeVersion: string;
begin
Result := FServerCodeVersion;
end;
function TRollbarBase.GetServerHost: string;
begin
Result := FServerHost;
end;
function TRollbarBase.GetServerRoot: string;
begin
Result := FServerRoot;
end;
function TRollbarBase.GetTimestamp: TDateTime;
begin
Result := TDateTime(UnixToDateTime(FTimestamp));
end;
function TRollbarBase.GetTitle: string;
begin
Result := FTitle;
end;
function TRollbarBase.GetUnixTimestamp: Int64;
begin
Result := FTimestamp;
end;
function TRollbarBase.GetUUID: string;
begin
Result := FUUID;
end;
procedure TRollbarBase.SetAccessToken(const Value: string);
begin
FAccessToken := Value;
end;
procedure TRollbarBase.SetCodeVersion(const Value: string);
begin
FCodeVersion := Value;
end;
procedure TRollbarBase.SetContext(const Value: string);
begin
FContext := Value;
end;
procedure TRollbarBase.SetEnvironment(const Value: string);
begin
FEnvironment := Value;
end;
procedure TRollbarBase.SetFingerprint(const Value: string);
begin
FFingerprint := Value;
end;
procedure TRollbarBase.SetFramework(const Value: string);
begin
FFramework := Value;
end;
procedure TRollbarBase.SetLanguage(const Value: string);
begin
FLanguage := Value;
end;
procedure TRollbarBase.SetLevel(const Value: string);
begin
FLevel := Value;
end;
procedure TRollbarBase.SetNotifierName(const Value: string);
begin
FNotifierName := Value;
end;
procedure TRollbarBase.SetNotifierVersion(const Value: string);
begin
FNotifierVersion := Value;
end;
procedure TRollbarBase.SetPersonEmail(const Value: string);
begin
FPersonEmail := Value;
end;
procedure TRollbarBase.SetPersonId(const Value: string);
begin
FPersonId := Value;
end;
procedure TRollbarBase.SetPersonUsername(const Value: string);
begin
FPersonUsername := Value;
end;
procedure TRollbarBase.SetServerBranch(const Value: string);
begin
FServerBranch := Value;
end;
procedure TRollbarBase.SetServerCodeVersion(const Value: string);
begin
FServerCodeVersion := Value;
end;
procedure TRollbarBase.SetServerHost(const Value: string);
begin
FServerHost := Value;
end;
procedure TRollbarBase.SetServerRoot(const Value: string);
begin
FServerRoot := Value;
end;
procedure TRollbarBase.SetTimestamp(const Value: TDateTime);
begin
FTimestamp := DateTimeToUnix(Value);
end;
procedure TRollbarBase.SetTitle(const Value: string);
begin
FTitle := Value;
end;
procedure TRollbarBase.SetUUID(const Value: string);
begin
FUUID := Value;
end;
function TRollbarBase.ToJSON: string;
begin
Result := JSONString(self);
end;
{ TRollbar }
class function TRollbar.Message: IRollbarMessage;
begin
Result := TRollbarMessage.Create;
end;
class function TRollbar.Server(AccessToken, Environment: string): IRollbarServer;
begin
Result := TRollbarServer.Create(AccessToken, Environment);
end;
class function TRollbar.Trace: IRollbarTrace;
begin
Result := TRollbarTrace.Create;
end;
{ TRollbarMessage }
function TRollbarMessage.GetBody: string;
begin
Result := FBody;
end;
procedure TRollbarMessage.SetBody(const Value: string);
begin
FBody := Value;
end;
{ TRollbarResponse }
constructor TRollbarResponse.Create(JsonResp: TJSONObject);
begin
inherited Create;
FJsonResp := JsonResp;
end;
function TRollbarResponse.GetErr: Integer;
var
AValue: TJSONValue;
begin
Result := 0;
if TryGetJSONValue(FJsonResp, 'err', AValue) then
Result := (AValue as TJSONNumber).AsInt;
end;
function TRollbarResponse.GetErrMsg: string;
var
AValue: TJSONValue;
begin
Result := '';
if TryGetJSONValue(FJsonResp, 'message', AValue) then
Result := (AValue as TJSONString).ToString;
end;
function TRollbarResponse.GetResultUUID: string;
var
AValue1, AValue2: TJSONValue;
begin
Result := '';
if TryGetJSONValue(FJsonResp, 'result', AValue1) then
if TryGetJSONValue((AValue1 as TJSONObject), 'uuid', AValue2) then
Result := (AValue2 as TJSONString).ToString;
end;
{ TRollbarServer }
constructor TRollbarServer.Create(AccessToken: string; Environment: string);
begin
inherited Create;
fSvr := TIdHttp.Create(nil);
fSvr.HandleRedirects := true;
fSvr.ReadTimeout := 5000;
FAccessToken := AccessToken;
FEnvironment := Environment;
end;
destructor TRollbarServer.Destroy;
begin
fSvr.Free;
inherited;
end;
function TRollbarServer.Submit(Request: IRollbarRequest): IRollbarResponse;
const
FMT = 'payload=%s';
ENDPOINT = 'https://api.rollbar.com/api/1/item/';
var
jsonToSend: TStrings;
sResult: string;
jsonResult: TJSONValue;
begin
Request.AccessToken := FAccessToken;
Request.Environment := FEnvironment;
jsonToSend := TStringList.create;
try
jsonToSend.Add(Format(FMT, [Request.ToJSON]));
sResult := fSvr.Post(ENDPOINT, jsonToSend);
jsonResult := TJSONObject.ParseJSONValue(sResult);
Result := TRollbarResponse.Create(jsonResult as TJSONObject);
finally
jsonToSend.Destroy;
end;
end;
{ TRollbarFrame }
procedure TRollbarFrame.AddContextPost(const Value: string);
begin
SetLength(FContextPost, Length(FContextPost) + 1);
FContextPost[Length(FContextPost) - 1] := Value;
end;
procedure TRollbarFrame.AddContextPre(const Value: string);
begin
SetLength(FContextPre, Length(FContextPre) + 1);
FContextPre[Length(FContextPre) - 1] := Value;
end;
function TRollbarFrame.GetCode: string;
begin
Result := FCode;
end;
function TRollbarFrame.GetColNo: Integer;
begin
Result := FColNo;
end;
function TRollbarFrame.GetContextPost: TDynStringArray;
begin
Result := FContextPost;
end;
function TRollbarFrame.GetContextPre: TDynStringArray;
begin
Result := FContextPre;
end;
function TRollbarFrame.GetFilename: string;
begin
Result := FFilename;
end;
function TRollbarFrame.GetLineNo: Integer;
begin
Result := FLineNo;
end;
function TRollbarFrame.GetMethod: string;
begin
Result := FMethod;
end;
procedure TRollbarFrame.SetCode(const Value: string);
begin
FCode := Value;
end;
procedure TRollbarFrame.SetColNo(const Value: Integer);
begin
FColNo := Value;
end;
procedure TRollbarFrame.SetFilename(const Value: string);
begin
FFilename := Value;
end;
procedure TRollbarFrame.SetLineNo(const Value: Integer);
begin
FLineNo := Value;
end;
procedure TRollbarFrame.SetMethod(const Value: string);
begin
FMethod := Value;
end;
{ TRollbarTrace }
function TRollbarTrace.AddFrame: IRollbarFrame;
begin
Result := TRollbarFrame.Create;
SetLength(FFrames, Length(FFrames) + 1);
FFrames[Length(FFrames) - 1] := Result;
end;
function TRollbarTrace.GetExceptionClass: string;
begin
Result := FExceptionClass;
end;
function TRollbarTrace.GetExceptionDescription: string;
begin
Result := FExceptionDescription;
end;
function TRollbarTrace.GetExceptionMessage: string;
begin
Result := FExceptionMessage;
end;
function TRollbarTrace.GetFrames: TRollbarFrames;
begin
Result := FFrames;
end;
procedure TRollbarTrace.SetExceptionClass(const Value: string);
begin
FExceptionClass := Value;
end;
procedure TRollbarTrace.SetExceptionDescription(const Value: string);
begin
FExceptionDescription := Value;
end;
procedure TRollbarTrace.SetExceptionMessage(const Value: string);
begin
FExceptionMessage := Value;
end;
end.
|
{*******************************************************}
{ }
{ Delphi DataSnap Framework }
{ }
{ Copyright(c) 2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit DSServerDsnResStrs;
interface
resourcestring
// DSServerReg
rsServerModule = 'Server Module';
rsServerModuleComment = 'Creates a module which implements DataSnap server methods. Use this module to add custom server methods or use the built in IAppServer support. The IAppServer interface provides a provider/resolver model for passing DataSets between server and clients.';
// DSWebBrokerReg
SNewDSWebAppExpertCaption = 'New DataSnap WebBroker Application';
SNewDSWebAppExpertComment =
'The DataSnap WebBroker Application Wizard provides an easy way to implement a server application using both the WebBroker and DataSnap technologies.';
SNewDSWebAppExpertName = 'DataSnap WebBroker Application';
SNewDSRESTAppExpertCaption = 'New DataSnap REST Application';
SNewDSRESTAppExpertComment = 'Creates a DataSnap server with support for REST communication and with web pages that invoke server methods using Java Script and JSON.';
SNewDSRESTAppExpertName = 'DataSnap REST Application';
sDirectoryContainsAProject = 'Directory (%s) already contains DataSnap REST project files, either remove/delete the files or select a different location';
sSpecifyDirectory = 'Please enter a project location';
// DSStandAloneReg
SNewDSStandAloneAppExpertComment = 'The DataSnap Server Wizard provides an easy way to implement a server application using the DataSnap technology.';
SNewDSStandAloneAppExpertName = 'DataSnap Server';
// DSStandAloneForm
sSelectProtocol = 'Select one or more protocols';
// DSCreators
rsDataSnapServerPage = 'DataSnap Server';
rsDatasnapServer = 'DataSnap Server';
rsDataSnapServerMethodsModuleFormName = 'ServerMethods'; // If blank will default to DSDataModule
// DSServerMrWizard
sFeaturesPageTitle = 'Server Features';
sFeaturesPageDescription = 'Check the features to add to the DataSnap server';
sNoFeatureSelected = 'Select a feature for more information';
sProtocolFeatureName = 'Protocols';
sProtocolFeatureDescription = 'Choose the protocols that can be used to connect to the DataSnap server.';
sTCPProtocolFeatureName = 'TCP/IP';
sTCPProtocolFeatureDescription = 'Check TCP/IP to add support for TCP/IP connections. DataSnap DBExpress clients can connect using TCP/IP.';
sHTTPProtocolFeatureName = 'HTTP';
sHTTPSProtocolFeatureDescription = 'Check HTTPS to add support for HTTP(Secure) connections. ' +
'REST clients (including Delphi, C++, JavaScript and PHP) as well as DBExpress clients can connect using HTTPS';
sHTTPProtocolFeatureDescription = 'Check HTTP to add support for HTTP connections. ' +
'REST clients (including Delphi, C++, JavaScript and PHP) as well as DBExpress clients can connect using HTTP.';
sHTTPSProtocolFeatureName = 'HTTPS';
sAuthenticationFeatureName = 'Authentication';
sAuthenticationFeatureDescription = 'Authentication controls access to the DataSnap server based on a user name and password provided by the client.';
sAuthorizationFeatureName = 'Authorization';
sAuthorizationFeatureDescription = 'Authorization controls access to server methods based on user roles.';
sServerMethodClassFeatureName = 'Server Methods Class';
sServerMethodClassFeatureDescription = 'Add a server methods class to the DataSnap server.';
sSampleMethodsFeatureName = 'Sample Methods';
sSampleMethodsFeatureDescription = 'Include sample methods EchoString and ReverseString.';
sSampleWebFilesFeatureName = 'Sample Web Files';
sSampleWebFilesFeatureDescription = 'Include sample web pages and related files.';
sWebFilesFeatureName = 'JavaScript Files';
sWebFilesFeatureDescription = 'Include the JavaScript files for REST client development, along with proxy generator components configured for JavaScript proxy generation.';
sConnectorsFeatureName = 'Mobile Connectors';
sConnectorsFeatureDescription = 'Include support for proxy dispatching for mobile connector development.';
sServerModuleFeatureName = 'Server Module';
sServerModuleFeatureDescription = 'Create a separate module for DS server components. ' +
'This enables support for heavy weight callbacks in DataSnap WebBroker applications.';
sFiltersFeatureName = 'Filters';
sFiltersFeatureDescription = 'Encryption and Compression filters for the selected protocol(s). The filters '+
'will be used with DataSnap SQL connections to the server.';
sEncryptionFeatureName = 'Encryption';
sEncryptionFeatureDescription = 'Add a PC1 and RSA filter for the selected protocol(s). The RSA filter requires '+
'the OpenSSL libraries to be present on the server and any clients.';
sCompressionFeatureName = 'Compression';
sCompressionFeatureDescription = 'Add a Zlib compression filter for the selected protocol(s).';
sHTTPPortLabel = '&HTTP Port:';
sHTTPSPortLabel = 'HTTP&S Port:';
sTCPIPPortLabel = '&TCP/IP Port:';
// DSProjectLocationWizardPage
sLocationPageInfo = 'This directory is the root location of the web application. ' +
'This is the output directory of the project executable and the location of web application files such as .js, .html, and .css files, and other static files.';
sLocationPageTitle = 'Project location';
sLocationPageDescription = 'Provide the directory where the project will be created.';
// DSPortFrame
rsTestPortOK = 'Test port succeeded';
// DSStandAlonAppWizardPage
sConsoleInfo = 'A console application has a text-only interface';
sServiceInfo = 'A service application is installed as a Windows service';
sVCLInfo = 'A VCL application displays a VCL form';
sDSStandAloneApWizardPageTitle = 'Project type';
sDSStandAloneApWizardPageDescription = 'Specify the type of this application';
// DSPortsWizardPage
sPortsPageInfo = 'Click a field for more information';
sPortsPageTitle = 'Port Numbers';
sPortsPageDescription = 'Specify the ports that will be used by the DataSnap server to listen for client requests. ' +
'Use the "Test" button to make sure the port number is not already in use on this computer.';
sHTTPPortInfo = 'HTTP port. Port 80 is the well know HTTP port number used by web servers such as IIS.';
sHTTPSPortInfo = 'HTTPS port. Port 443 is the well known HTTPS port number used by web servers such as IIS.';
sTCPIPPortInfo = 'TCP/IP port. The default DataSnap TCP/IP port number is 211.';
// DSServerClassWizardPage
sComponentInfo = 'The TComponent ancestor type provides a simple code-only implementation.';
sDataModuleInfo = 'The TDataModule ancestor type provides a design surface for dropping non-visual components';
sDSServerModuleInfo = 'The TDSServerModule ancestor type provides a design surface and also implements the IAppServer interface.';
sClassWizardPageTitle = 'Server methods ancestor class';
sClassWizardPageDescription = 'Select an ancestor type for the server methods class.';
implementation
end.
|
{
En los datos de entrada se proporcionan dos tiempos como enteros de la forma hhmm
donde hh representa las horas (menos de 24) y mm los minutos (menos de 60).
Determine la suma de estos dos tiempos, y exhiba el resultado en la forma d hhmm,
donde d es días, ya sea cero o uno.
Ejemplo de entrada : 1345 2153.
Ejemplo de salida : 1 1138.
0}
PROGRAM dias17(input, output);
VAR
hora, minuto,dia,t1, t2: integer;
BEGIN
read(t1, t2);
minuto := abs((t1 mod 100)+(t2 mod 100)-60);
hora := abs((1 + t1 div 100)+(t2 div 100)-24);
dia := (hora div 24)+1;
writeln(dia,' ',hora,minuto);
END.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ }
{ Copyright(c) 2010-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit Macapi.OCMarshal;
interface
type
///
/// Procedure type for the transform procedure used by <code>moXForm<code>
/// marshaling operations.
TXFormProc = procedure(Src: Pointer; Dest: Pointer);
///
/// Method type for the transform procedure used by <code>moXFormWithContext<code>
/// marshaling operations.
TXFormWithContextProc = procedure(Src: Pointer; Dest: Pointer) of object;
///
/// Kind of marshal operations that we support.
TMarshalOpKind = (
///
/// Copy data from source to destination. Size is specified in the operation.
moCopy,
/// Store a reference to the destination buffer at the given location.
/// Used for when you need to allocate a local buffer, and include a
/// pointer to that local buffer in your marshaled arguments.
moLocalRef,
/// Stores a constant value at the given location in the destination
/// buffer. No data from the source buffer is used.
moStore,
/// Applies a transform function to get data from the source buffer
/// to the destination buffer. The size of the transformation is
/// arbitrary. The contents of the source buffer may or may not be
/// used.
moXForm,
/// Applies a transform function as per <code>moXForm</code>, but
/// instead of the function being a flat function, it's a method.
/// Thus you can capture some context when you are creating the
/// marhsaler, and have that context available when the marshaler
/// is executed.
moXFormWithContext
);
///
/// Each marshal operation in a marshaler is specified with a separate
/// record. Each operation will be applied to a source buffer and
/// a destination buffer. The marshaler will use the data from the
/// marshal operations to determine the fixed up source and destination
/// buffers to apply the operation to.
TMarshalOp = record
///
/// The kind of the operation.
Kind: TMarshalOpKind;
///
/// The offset from the start of the source buffer to apply this
/// operation to.
Src: Integer;
///
/// The offset from the start of the destination buffer to apply this
/// operation to.
Dest: Integer;
case TMarshalOpKind of
moCopy: (
///
/// Size, in bytes, of data to copy.
Size: Integer;
);
moLocalRef: (
///
/// The offset from the start of the destination buffer to be used
/// to compute the pointer to be stored. When the operation is
/// executed, the marshaler will add <code>Offset</code> to the
/// destination buffer, and store it at the offset in the buffer
/// specified by the <code>Dest</code> field.
/// When using this operation, the <code>Src</code> field is not used.
Offset: Integer;
);
moStore: (
///
/// The value to be stored at the offset specified by <code>Dest</code>.
/// When using this operation, the <code>Src</code> field is not used.
Value: NativeInt;
);
moXForm: (
///
/// The procedure to call to perform the transform. It will be
/// passed the buffers specified by the <code>Src</code> and <code>Dest</code>
/// fields.
XFormProc: TXFormProc;
);
moXFormWithContext: (
///
/// The method to call to perform the transform. It will be
/// passed the buffers specified by the <code>Src</code> and <code>Dest</code>
/// fields.
XFormContextProc: TXFormWithContextProc;
);
end;
PMarshalOp = ^TMarshalOp;
///
/// A general purpose marshaling class that can marshal data from an
/// input buffer to an output buffer given a set of marshaling operations
/// that are configured by the client.
TMarshaler = class
private
FOps: TArray<TMarshalOp>;
public
///
/// Create the marshaler with an array of marshal operations.
constructor Create(Ops: TArray<TMarshalOp>);
///
/// Executes the marshaling operations on the given source and destination
/// buffers.
/// <param name="Src">Pointer to an input buffer. The buffer must be large
/// enough to be accesible by all the marhsaling operations.</param>
/// <param name="Dest">Pointer to the destination buffer. The buffer
/// must be large enough to accept all the data from the marshaling
/// operations.</param>
procedure Execute(Src: Pointer; Dest: Pointer);
///
/// Returns a string representation of the marshaler. Useful for diagnostic
/// purposes only.
function ToString: string; override;
///
/// Marshaling operations frequently include multiple operations that can
/// be collapsed into one. This function takes an array of marshaling operations
/// and elides all adjacent copy operations that target contiguous regions of
/// stack space. In some cases, this can reduce all the marshaling operations
/// in an array down to one. The array length is modified on the input ops
/// array, and operations are shifted down and modified as needed.
class procedure Optimize(var Ops: TArray<TMarshalOp>); static;
end;
implementation
uses System.SysUtils;
constructor TMarshaler.Create(Ops: TArray<TMarshalOp>);
begin
FOps := Ops;
end;
procedure TMarshaler.Execute(Src: Pointer; Dest: Pointer);
var
I: Integer;
Op: PMarshalOp;
S: PByte;
D: PByte;
begin
for I:= 0 to Length(FOps) - 1 do
begin
Op := @FOps[I];
S := PByte(Src) + Op.Src;
D := PByte(Dest) + Op.Dest;
case Op^.Kind of
moCopy:
Move(PPointer(S)^, PPointer(D)^, Op^.Size);
moLocalRef:
PPointer(D)^ := Pointer(PByte(Dest) + Op^.Offset);
moStore:
PPointer(D)^ := Pointer(Op^.Value);
moXForm:
Op^.XFormProc(S, D);
moXFormWithContext:
Op^.XFormContextProc(S, D);
else
Assert(False);
end;
end;
end;
function TMarshaler.ToString: string;
var
Buff: TStringBuilder;
I: Integer;
Op: PMarshalOp;
begin
Buff := TStringBuilder.Create;
Buff.Append('[');
for I:= 0 to Length(FOps) - 1 do
begin
Op := @FOps[I];
if I > 0 then
Buff.Append(', ');
case Op^.Kind of
moCopy:
Buff.AppendFormat('C(%d,%d,%d)', [Op^.Src, Op^.Dest, Op^.Size]);
moStore:
Buff.AppendFormat('S(%d,%ld)', [Op^.Dest, Op^.Value]);
moLocalRef:
Buff.AppendFormat('L(%d,%d)', [Op^.Dest, Op^.Offset]);
moXForm:
Buff.AppendFormat('X(%d,%d)', [Op^.Src, Op^.Dest]);
moXFormWithContext:
Buff.AppendFormat('XC(%d,%d)', [Op^.Src, Op^.Dest]);
else
Assert(False);
end;
end;
Buff.Append(']');
Result := Buff.ToString;
end;
class procedure TMarshaler.Optimize(var Ops: TArray<TMarshalOp>);
var
I: Integer;
NextIdx: Integer;
Last: PMarshalOp;
RegionSize: Integer;
procedure InitRegion;
begin
Last := @Ops[0];
NextIdx := 1;
if Last.Kind = moCopy then
RegionSize := Last.Size
else
RegionSize := 0;
end;
procedure CloseRegion;
begin
if Last.Kind = moCopy then
begin
Assert(RegionSize <> 0);
Last.Size := RegionSize;
end
else
begin
Assert(RegionSize = 0);
end;
if I - NextIdx > 0 then
Ops[NextIdx] := Ops[I];
Last := @Ops[NextIdx];
if Last.Kind = moCopy then
RegionSize := Last.Size
else
RegionSize := 0;
Inc(NextIdx);
end;
begin
if Length(Ops) = 0 then Exit;
InitRegion;
for I:= 1 to Length(Ops) - 1 do
begin
case Last.Kind of
moCopy:
begin
if Ops[I].Kind = moCopy then
begin
// Check to see if the current op is a copy op that is contiguous
// with the last op. If so, we can merge them.
if (Ops[I].Src = Last^.Src + RegionSize) and
(Ops[I].Dest = Last^.Dest + RegionSize) then
// regions are contiguous - update the region size
Inc(RegionSize, Ops[I].Size)
else
// regions are not contiguous. Seal off the last copy, and restart.
CloseRegion;
end
else
// current op is not a copy - can't merge
CloseRegion;
end;
moXForm, moXFormWithContext:
CloseRegion;
end;
end;
if RegionSize > 0 then
begin
// Possibly we merged in copy ops from the end of the list. RegionSize can
// only be positive if there was a copy behind us.
Assert(Last^.Kind = moCopy);
Last^.Size := RegionSize;
end;
SetLength(Ops, NextIdx);
end;
end.
|
{ Invokable interface IuTravel }
unit uTravelIntf;
interface
uses Soap.InvokeRegistry, System.Types, Soap.XSBuiltIns, Soap.encddecd,
System.IOUtils, FMX.Dialogs, FMX.Forms, Classes, SysUtils, System.UITypes,
System.Variants,
FMX.Graphics, Data.DB, Data.DbxSqlite, Data.SqlExpr;
type
TTravelServ = class(TRemotable)
private
FName: string;
FId: string;
procedure SetId(const Value: string);
procedure SetName(const Value: string);
published
property Id: string read FId write SetId;
property Name: string read FName write SetName;
end;
TTravelServArray = array of TTravelServ;
{ Invokable interfaces must derive from IInvokable }
IuTravel = interface(IInvokable)
['{B59BB327-A858-448F-8209-BE7BA39C0FDE}']
function ConectToDb: TSQLConnection;
function LoadClients: TTravelServArray;
procedure AddClientInDb(Item: TTravelServ);
{ Methods of Invokable interface must not use the default }
{ calling convention; stdcall is recommended }
end;
implementation
{ TTravelServ }
procedure TTravelServ.SetId(const Value: string);
begin
FId := Value;
end;
procedure TTravelServ.SetName(const Value: string);
begin
FName := Value;
end;
initialization
{ Invokable interfaces must be registered }
InvRegistry.RegisterInterface(TypeInfo(IuTravel));
end.
|
unit ufirparalinha;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, Buttons,
StdCtrls, ExtCtrls, ButtonPanel;
type
{ TfrmIrParaLinha }
TfrmIrParaLinha = class(TForm)
ButtonPanel1 : TButtonPanel;
edLinha: TEdit;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
lblPrimeiraLinha: TLabel;
lblUltimaLinha: TLabel;
procedure btnOkClick(Sender: TObject);
procedure btCancelarClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
private
{ private declarations }
FLinha: Integer;
FPrimeiraLinha: Integer;
FUltimaLinha: Integer;
{ Private declarations }
public
Property Linha:Integer read FLinha;
Property PrimeiraLinha:Integer read FPrimeiraLinha write FPrimeiraLinha;
Property UltimaLinha:Integer read FUltimaLinha write FUltimaLinha;
{ public declarations }
end;
var
frmIrParaLinha: TfrmIrParaLinha;
implementation
{$R *.lfm}
{ TfrmIrParaLinha }
procedure TfrmIrParaLinha.btnOkClick(Sender: TObject);
begin
Try
FLinha := StrToInt(edLinha.Text);
if (FLinha < FPrimeiraLinha)
or (FLinha > FUltimaLinha) then
begin
// TODO: gerar um exceção
ShowMessage('Linha Inválida');
edLinha.SetFocus;
exit;
end;
except
ShowMessage('Linha Inválida');
edLinha.SetFocus;
end;// Try..Except
Close;
end;
procedure TfrmIrParaLinha.btCancelarClick(Sender: TObject);
begin
Close;
end;
procedure TfrmIrParaLinha.FormCreate(Sender: TObject);
begin
FLinha := -1;
end;
procedure TfrmIrParaLinha.FormShow(Sender: TObject);
begin
lblPrimeiraLinha.Caption := IntToStr(FPrimeiraLinha);
lblUltimaLinha.Caption := IntToStr(FUltimaLinha);
end;
end.
|
unit GSyncObjTests;
interface
uses
{$IFDEF FPC} contnrs, fgl {$ELSE}Generics.Collections, System.Rtti{$ENDIF},
Classes,
SyncObjs,
Gevent,
Greenlets,
SysUtils,
GInterfaces,
Hub,
GreenletsImpl,
AsyncThread,
GreenletTests,
TestFramework;
const
cTestSeqCount = 10;
cTestSeq: array[0..cTestSeqCount-1] of Integer = (1,2,3,1,8,123,4,2,9,0);
type
TCondVarRoundRobinThread = class(TThread)
strict private
FCond: TGCondVariable;
FLock: TCriticalSection;
FValue: PInteger;
FPredValue: Integer;
FError: Boolean;
FLastWriter: PPointer;
FCounter: Integer;
protected
procedure Execute; override;
public
constructor Create(Cond: TGCondVariable;
Lock: TCriticalSection; Value: PInteger; LastWriter: PPointer);
destructor Destroy; override;
property Error: Boolean read FError;
property Counter: Integer read FCounter;
end;
TMultipleGreenletsThread = class(TThread)
strict private
FOnStart: TEvent;
FWorkersCount: Integer;
FRoutine: TSymmetricRoutine;
protected
procedure Execute; override;
public
constructor Create(const Routine: TSymmetricRoutine; WorkersCount: Integer);
destructor Destroy; override;
procedure Start;
end;
TGSyncObjsTests = class(TTestCase)
strict private
FCondVar: TGCondVariable;
FSemaphore: TGSemaphore;
FQueue: TGQueue<Integer>;
FObjQueue: TGQueue<TSmartPointer<TTestObj>>;
FOutput: TStrings;
FArray: array of NativeUInt;
FGeventCountOnStart: Integer;
procedure CondVarTest;
procedure CondVarProc(const Args: array of const);
procedure CondVarBroadcast;
procedure QueueTest;
procedure QueueGCTest;
procedure SemaphoreTest1;
procedure SemaphoreTest2;
procedure SemaphoreProc(const Args: array of const);
procedure GeneratorBody1(const A: array of const);
procedure GeneratorBody2(const A: array of const);
procedure Generator2Routine(const Args: array of const);
procedure PrintThroughSem(const Msg: string);
procedure EnumTestObjs(const Args: array of const);
procedure EnumGCTestObjs(const Args: array of const);
procedure OnTestFree(Sender: TObject);
procedure CondVarSync1;
procedure CondVarSync2;
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure CondVariable;
procedure CondVariableWhileKill;
procedure CondVariableSyncMech;
procedure Semaphore1;
procedure Semaphore2;
procedure Semaphore3;
procedure Semaphore4;
procedure Semaphore5;
procedure Queue;
procedure QueueGC;
procedure Generator1;
procedure Generator2;
procedure GeneratorMultiple;
procedure GeneratorObjects;
procedure GeneratorGCObjects;
// threaded
procedure CondVariableRoundRobin;
end;
TRefObject = class
public
constructor Create;
destructor Destroy; override;
end;
var
GlobalRefCount: Integer;
implementation
uses GarbageCollector;
{ TGSyncObjsTests }
procedure TGSyncObjsTests.CondVarBroadcast;
begin
GreenSleep(100);
FCondVar.Broadcast;
GreenSleep(100);
FCondVar.Broadcast
end;
procedure TGSyncObjsTests.CondVariable;
var
G: IRawGreenlet;
begin
G := TGreenlet.Spawn(CondVarTest);
G.Join;
end;
procedure TGSyncObjsTests.CondVariableRoundRobin;
var
T1, T2: TCondVarRoundRobinThread;
Value: Integer;
LastWriter: Pointer;
Cond: TGCondVariable;
Lock: TCriticalSection;
Stop, Start: TTime;
Error: Boolean;
begin
Lock := TCriticalSection.Create;
Cond := TGCondVariable.Make(Lock);
Error := False;
Value := 0;
LastWriter := nil;
T1 := TCondVarRoundRobinThread.Create(Cond, Lock, @Value, @LastWriter);
T2 := TCondVarRoundRobinThread.Create(Cond, Lock, @Value, @LastWriter);
try
Sleep(1000);
Cond.Signal;
Start := Now;
Stop := Now + TimeOut2Time(1000);
while Now < Stop do begin
Error := T1.Error or T2.Error;
if Error then begin
Lock.Acquire;
Value := 100000000;
Lock.Release;
end;
end;
finally
Lock.Acquire;
Value := 1000000000;
Lock.Release;
T1.Terminate;
T2.Terminate;
Cond.Broadcast;
T1.WaitFor;
{$IFDEF DEBUG}
DebugString('T1');
{$ENDIF}
Cond.Broadcast;
T2.WaitFor;
{$IFDEF DEBUG}
DebugString('T2');
{$ENDIF}
T1.Free;
T2.Free;
Lock.Free;
end;
CheckFalse(Error);
{$IFDEF DEBUG}
DebugString(Format('Timeout = %d, counters = %d',
[
Time2Timeout(Stop - Start),
T1.Counter+T2.Counter
]));
{$ENDIF}
end;
procedure TGSyncObjsTests.CondVariableSyncMech;
var
G1, G2: TSymmetric;
begin
G1 := TSymmetric.Create(CondVarSync1);
G2 := TSymmetric.Create(CondVarSync2);
Join([G2, G1]);
Check(FOutput.CommaText = 'g2,g1,g2,g1');
end;
procedure TGSyncObjsTests.CondVariableWhileKill;
var
G: IRawGreenlet;
begin
G := TGreenlet.Spawn(CondVarProc, [1]);
try
FCondVar := TGCondVariable.Make;
finally
FCondVar := TGCondVariable.Make;
end;
end;
procedure TGSyncObjsTests.CondVarProc(const Args: array of const);
var
Index: Integer;
begin
Index := Args[0].AsInteger;
FOutput.Add(IntToStr(Index));
FCondVar.Wait;
FOutput.Add(IntToStr(Index));
FCondVar.Wait;
FOutput.Add(IntToStr(Index));
end;
procedure TGSyncObjsTests.CondVarSync1;
begin
FOutput.Add('g1');
FCondVar.Signal;
FOutput.Add('g1');
end;
procedure TGSyncObjsTests.CondVarSync2;
begin
FOutput.Add('g2');
FCondVar.Wait;
FOutput.Add('g2');
end;
procedure TGSyncObjsTests.CondVarTest;
var
Gr: TGreenGroup<Integer>;
begin
Gr[0] := TGreenlet.Spawn(CondVarProc, [0]);
Gr[1] := TGreenlet.Spawn(CondVarProc, [1]);
Gr[2] := TGreenlet.Spawn(CondVarBroadcast);
Gr.Join;
Check(FOutput.CommaText = '0,1,0,1,0,1');
end;
procedure TGSyncObjsTests.EnumGCTestObjs(const Args: array of const);
var
Obj: TObject;
I: Integer;
begin
for I := 0 to High(Args) do begin
Obj := Args[I].AsObject;
TGenerator<TObject>.Yield(Obj);
end;
end;
procedure TGSyncObjsTests.EnumTestObjs(const Args: array of const);
var
Count, I: Integer;
A: TTestObj;
begin
Count := Args[0].AsInteger;
for I := 1 to Count do begin
A := TTestObj.Create;
A.OnDestroy := Self.OnTestFree;
TGenerator<TTestObj>.Yield(A);
end;
end;
procedure TGSyncObjsTests.Generator1;
var
Gen: TGenerator<Integer>;
I: Integer;
List: TList<Integer>;
begin
List := TList<Integer>.Create;
Gen := TGenerator<Integer>.Create(GeneratorBody1, [4, 11, 3]);
try
for I in Gen do begin
List.Add(I);
end;
Check(List.Count = 3);
Check(List[0] = 4);
Check(List[1] = 7);
Check(List[2] = 10);
finally
List.Free;
end;
end;
procedure TGSyncObjsTests.Generator2;
var
Gen: TGenerator<Integer>;
I: Integer;
List: TList<Integer>;
begin
List := TList<Integer>.Create;
Gen := TGenerator<Integer>.Create(GeneratorBody2, [1, 2, -300, 3, 4, -100, 5]);
try
for I in Gen do begin
List.Add(I);
end;
Check(List.Count = 5);
Check(List[0] = 1);
Check(List[1] = 2);
Check(List[2] = 3);
Check(List[3] = 4);
Check(List[4] = 5);
finally
List.Free;
end;
end;
procedure TGSyncObjsTests.Generator2Routine(const Args: array of const);
var
Gen: TGenerator<Integer>;
List: TList<Integer>;
Iter: Integer;
Tail: tTuple;
I: Integer;
begin
List := TList<Integer>(Args[0].AsObject);
SetLength(Tail, Length(Args)-1);
for I := 0 to High(Tail) do
Tail[I] := Args[I+1];
Gen := TGenerator<Integer>.Create(GeneratorBody2, Tail);
for Iter in Gen do
List.Add(Iter);
end;
procedure TGSyncObjsTests.GeneratorBody1(const A: array of const);
var
Cur, Stop, Step: Integer;
begin
Cur := A[0].AsInteger;
Stop := A[1].AsInteger;
if Length(A) > 2 then
Step := A[2].AsInteger
else
Step := 1;
while Cur <= Stop do begin
TGenerator<Integer>.Yield(Cur);
Inc(Cur, Step);
end;
end;
procedure TGSyncObjsTests.GeneratorBody2(const A: array of const);
var
I, Value: Integer;
begin
for I := 0 to High(A) do begin
Value := A[I].AsInteger;
if Value >= 0 then
TGenerator<Integer>.Yield(Value)
else
GreenSleep(-Value);
end;
end;
procedure TGSyncObjsTests.GeneratorGCObjects;
var
A1, A2, A3: TTestObj;
procedure RunInternal;
var
Gen: TGenerator<TObject>;
I: TObject;
begin
GC(A1);
GC(A2);
GC(A3);
Gen := TGenerator<TObject>.Create(EnumGCTestObjs, [A1, A2, A3]);
{$IFDEF DEBUG}
Check(GCCounter > 0);
{$ENDIF}
for I in Gen do begin
TTestObj(I).OnDestroy := Self.OnTestFree;
end;
{$IFDEF DEBUG}
Check(GCCounter > 0);
{$ENDIF}
end;
begin
{$IFDEF DEBUG}
GCCounter := 0;
{$ENDIF}
A1 := TTestObj.Create;
A2 := TTestObj.Create;
A3 := TTestObj.Create;
RunInternal;
Check(FOutput.Count = 3);
Check(FOutput.CommaText = 'OnDestroy,OnDestroy,OnDestroy');
{$IFDEF DEBUG}
CheckEquals(GCCounter, 0);
{$ENDIF}
CheckFalse(TGarbageCollector.ExistsInGlobal(A2));
CheckFalse(TGarbageCollector.ExistsInGlobal(A1));
CheckFalse(TGarbageCollector.ExistsInGlobal(A3));
end;
procedure TGSyncObjsTests.GeneratorMultiple;
var
G1, G2, G3: TGreenlet;
L1, L2, L3: TList<Integer>;
function MakeCommaText(const L: TList<Integer>): string;
var
Strs: TStrings;
I: Integer;
begin
Strs := TStringList.Create;
try
for I := 0 to L.Count-1 do
Strs.Add(IntToStr(L[I]));
Result := Strs.CommaText;
finally
Strs.Free
end;
end;
begin
L1 := TList<Integer>.Create;
L2 := TList<Integer>.Create;
L3 := TList<Integer>.Create;
G1 := TGreenlet.Spawn(Generator2Routine, [L1, 1,2,-100,4,5]);
G2 := TGreenlet.Spawn(Generator2Routine, [L2, 10,11,-200,-100,12]);
G3 := TGreenlet.Spawn(Generator2Routine, [L3, -100,40,50]);
try
Check(Greenlets.Join([G1, G2, G3], 1000));
Check(MakeCommaText(L1) = '1,2,4,5');
Check(MakeCommaText(L2) = '10,11,12');
Check(MakeCommaText(L3) = '40,50');
finally
L1.Free;
L2.Free;
L3.Free;
end;
end;
procedure TGSyncObjsTests.GeneratorObjects;
var
Count: Integer;
procedure RunInternal;
var
Gen: TGenerator<TTestObj>;
I: TTestObj;
begin
Gen := TGenerator<TTestObj>.Create(EnumTestObjs, [Count]);
for I in Gen do begin
Check(Assigned(I));
end;
end;
begin
Count := 5;
RunInternal;
Check(FOutput.Count = Count);
Check(FOutput.CommaText = 'OnDestroy,OnDestroy,OnDestroy,OnDestroy,OnDestroy');
end;
procedure TGSyncObjsTests.OnTestFree(Sender: TObject);
begin
FOutput.Add('OnDestroy')
end;
procedure TGSyncObjsTests.PrintThroughSem(const Msg: string);
begin
FSemaphore.Acquire;
try
GreenSleep(0);
FOutput.Add(Msg);
finally
FSemaphore.Release
end;
end;
procedure TGSyncObjsTests.Queue;
var
I: Integer;
G: IRawGreenlet;
begin
for I := 0 to cTestSeqCount-1 do
FQueue.Enqueue(cTestSeq[I]);
CheckEquals(FQueue.Count, cTestSeqCount, 'Queue.Count problems');
G := TGreenlet.Spawn(QueueTest);
G.Join;
for I := 0 to cTestSeqCount-1 do
FQueue.Enqueue(cTestSeq[I]);
FQueue.Clear;
Check(FQueue.Count = 0, 'FQueue.Clear problems');
end;
procedure TGSyncObjsTests.QueueGC;
var
I: Integer;
Obj: TTestObj;
G: IRawGreenlet;
begin
for I := 0 to cTestSeqCount-1 do begin
Obj := TTestObj.Create;
Obj.OnDestroy := Self.OnTestFree;
Obj.Name := IntToStr(cTestSeq[I]);
FObjQueue.Enqueue(Obj);
end;
CheckEquals(FObjQueue.Count, cTestSeqCount, 'Queue.Count problems');
G := TGreenlet.Spawn(QueueGCTest);
G.Join;
Check(FOutput.IndexOf('OnDestroy') <> -1);
FOutput.Clear;
for I := 0 to cTestSeqCount-1 do begin
Obj := TTestObj.Create;
Obj.OnDestroy := Self.OnTestFree;
FObjQueue.Enqueue(Obj);
end;
FObjQueue.Clear;
Check(FObjQueue.Count = 0, 'FQueue.Clear problems');
Check(FOutput.CommaText <> '');
Check(FOutput.IndexOf('OnDestroy') <> -1);
end;
procedure TGSyncObjsTests.QueueGCTest;
var
I, J: Integer;
Val: TSmartPointer<TTestObj>;
begin
I := 0;
for J := cTestSeqCount downto 1 do begin
CheckEquals(FObjQueue.Count, J);
FObjQueue.Dequeue(Val);
CheckEquals(Val.Get.Name, IntToStr(cTestSeq[I]));
Inc(I)
end;
end;
procedure TGSyncObjsTests.QueueTest;
var
I, J, Val: Integer;
begin
I := 0;
for J := cTestSeqCount downto 1 do begin
CheckEquals(FQueue.Count, J);
FQueue.Dequeue(Val);
CheckEquals(Val, cTestSeq[I]);
Inc(I)
end;
end;
procedure TGSyncObjsTests.Semaphore1;
var
G: IRawGreenlet;
begin
G := TGreenlet.Spawn(SemaphoreTest1);
G.Join
end;
procedure TGSyncObjsTests.Semaphore2;
var
G: IRawGreenlet;
begin
G := TGreenlet.Spawn(SemaphoreTest2);
G.Join
end;
procedure TGSyncObjsTests.Semaphore3;
var
G: IRawGreenlet;
begin
FSemaphore := TGSemaphore.Make(5);
G := TGreenlet.Spawn(SemaphoreTest1);
G.Join
end;
procedure TGSyncObjsTests.Semaphore4;
var
G: IRawGreenlet;
begin
FSemaphore := TGSemaphore.Make(1);
G := TGreenlet.Spawn(SemaphoreTest1);
G.Join
end;
procedure TGSyncObjsTests.Semaphore5;
begin
TSymmetric<string>.Spawn(PrintThroughSem, '1');
TSymmetric<string>.Spawn(PrintThroughSem, '2');
TSymmetric<string>.Spawn(PrintThroughSem, '3');
TSymmetric<string>.Spawn(PrintThroughSem, '4');
TSymmetric<string>.Spawn(PrintThroughSem, '5');
JoinAll;
Check(FOutput.CommaText = '1,2,3,4,5');
end;
procedure TGSyncObjsTests.SemaphoreProc(const Args: array of const);
var
Index, I, Timeout : Integer;
begin
Index := Args[0].AsInteger;
Timeout := Args[1].AsInteger;
for I := 1 to 1 do begin
FSemaphore.Acquire;
try
FQueue.Enqueue(Index);
if Timeout > 0 then
Greenlets.GreenSleep(Timeout);
finally
FSemaphore.Release;
end;
end;
end;
procedure TGSyncObjsTests.SemaphoreTest1;
var
Gr: TGreenGroup<Integer>;
I, Val: Integer;
begin
Gr[0] := TGreenlet.Spawn(SemaphoreProc, [0, 100]);
Gr[1] := TGreenlet.Spawn(SemaphoreProc, [1, 100]);
Gr[2] := TGreenlet.Spawn(SemaphoreProc, [2, 100]);
Gr[3] := TGreenlet.Spawn(SemaphoreProc, [3, 100]);
for I := 0 to Gr.Count-1 do
Gr[I].SetName(Format('G%d', [I]));
Gr.Join;
I := 0;
while FQueue.Count > 0 do begin
FQueue.Dequeue(Val);
Check(Val = (I mod Gr.Count), 'TestQueue iteration ' + IntToStr(I) + ' error');
Inc(I);
end;
end;
procedure TGSyncObjsTests.SemaphoreTest2;
var
Gr: TGreenGroup<Integer>;
I, Val: Integer;
begin
Gr[0] := TGreenlet.Spawn(SemaphoreProc, [0, 0]);
Gr[1] := TGreenlet.Spawn(SemaphoreProc, [1, 0]);
Gr[2] := TGreenlet.Spawn(SemaphoreProc, [2, 0]);
Gr[3] := TGreenlet.Spawn(SemaphoreProc, [3, 0]);
for I := 0 to Gr.Count-1 do
Gr[I].SetName(Format('G%d', [I]));
Gr.Join;
I := 0;
while FQueue.Count > 0 do begin
FQueue.Dequeue(Val);
Check(Val = (I mod Gr.Count), 'TestQueue iteration ' + IntToStr(I) + ' error');
Inc(I);
end;
end;
procedure TGSyncObjsTests.SetUp;
begin
inherited;
// в джоинере хаба создается Gevent
JoinAll;
{$IFDEF DEBUG}
GreenletCounter := 0;
GeventCounter := 0;
{$ENDIF}
FOutput := TStringList.Create;
FCondVar := TGCondVariable.Make;
FSemaphore := TGSemaphore.Make(3);
FQueue := TGQueue<Integer>.Make;
FObjQueue := TGQueue<TSmartPointer<TTestObj>>.Make;
{$IFDEF DEBUG}
FGeventCountOnStart := GeventCounter;
{$ENDIF}
end;
procedure TGSyncObjsTests.TearDown;
begin
inherited;
FOutput.Free;
SetLength(FArray, 0);
{$IFDEF DEBUG}
Check(GreenletCounter = 0, 'GreenletCore.RefCount problems');
// некоторые тесты привоят к вызову DoSomethingLater
DefHub.Serve(1000);
Check(GeventCounter = FGeventCountOnStart, 'Gevent.RefCount problems');
{$ENDIF}
end;
{ TRefObject }
constructor TRefObject.Create;
begin
Inc(GlobalRefCount)
end;
destructor TRefObject.Destroy;
begin
Dec(GlobalRefCount);
inherited;
end;
{ TCondVarRoundRobinThread }
constructor TCondVarRoundRobinThread.Create(Cond: TGCondVariable;
Lock: TCriticalSection; Value: PInteger; LastWriter: PPointer);
begin
FCond := Cond;
FLock := Lock;
FValue := Value;
FLastWriter := LastWriter;
inherited Create(False)
end;
destructor TCondVarRoundRobinThread.Destroy;
begin
DefHub(Self).Free;
inherited;
end;
procedure TCondVarRoundRobinThread.Execute;
var
Inc: Integer;
begin
FLock.Acquire;
if FLastWriter^ = nil then begin
FLastWriter^ := Pointer(Self);
FValue^ := 1;
end;
while not Terminated do begin
FCond.Wait(FLock);
FLock.Acquire;
Inc := FValue^ - FPredValue;
if Abs(Inc) > 2 then begin
FError := True;
FLock.Release;
Exit;
end;
if FLastWriter^ <> Pointer(Self) then begin
if FValue^ = 1000 then begin
FValue^ := FValue^ - 1
end
else if FValue^ = 0 then begin
FValue^ := FValue^ + 1
end
else begin
FValue^ := FValue^ + Inc;
end;
FLastWriter^ := Pointer(Self);
FPredValue := FValue^;
FCounter := FCounter + 1;
end;
FCond.Signal
end;
end;
{ TMultipleGreenletsThread }
constructor TMultipleGreenletsThread.Create(const Routine: TSymmetricRoutine;
WorkersCount: Integer);
begin
FRoutine := Routine;
FWorkersCount := WorkersCount;
FOnStart := TEvent.Create(nil, True, False, '');
inherited Create(False);
end;
destructor TMultipleGreenletsThread.Destroy;
begin
FOnStart.Free;
inherited;
end;
procedure TMultipleGreenletsThread.Execute;
var
Workers: array of IRawGreenlet;
I: Integer;
begin
SetLength(Workers, FWorkersCount);
FOnStart.WaitFor;
for I := 0 to FWorkersCount-1 do
Workers[I] := TGreenlet.Spawn(FRoutine);
try
Join(Workers);
finally
for I := 0 to FWorkersCount-1 do
Workers[I] := nil
end;
SetLength(Workers, 0);
end;
procedure TMultipleGreenletsThread.Start;
begin
FOnStart.SetEvent
end;
initialization
RegisterTest('GSyncObjs', TGSyncObjsTests.Suite);
//RegisterTest('ChannelTests', TChannelTests.Suite);
end.
|
unit frBands;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, StdCtrls, uCfgStorage;
type
{ TfraBands }
TfraBands = class(TFrame)
chk10m: TCheckBox;
chk12m: TCheckBox;
chk15m: TCheckBox;
chk160m: TCheckBox;
chk17m: TCheckBox;
chk20m: TCheckBox;
chk30m: TCheckBox;
chk40m: TCheckBox;
chk60m: TCheckBox;
chk80m: TCheckBox;
private
{ private declarations }
public
procedure LoadSettings(ini : TCfgStorage);
procedure SaveSettings(ini : TCfgStorage);
end;
implementation
{$R *.lfm}
procedure TFraBands.LoadSettings(ini : TCfgStorage);
begin
chk160m.Checked := ini.ReadBool('Bands','160M',True);
chk80m.Checked := ini.ReadBool('Bands','80M',True);
chk40m.Checked := ini.ReadBool('Bands','40M',True);
chk30m.Checked := ini.ReadBool('Bands','30M',False);
chk20m.Checked := ini.ReadBool('Bands','20M',True);
chk17m.Checked := ini.ReadBool('Bands','17M',False);
chk15m.Checked := ini.ReadBool('Bands','15M',True);
chk12m.Checked := ini.ReadBool('Bands','12M',False);
chk10m.Checked := ini.ReadBool('Bands','10M',True);
end;
procedure TFraBands.SaveSettings(ini : TCfgStorage);
begin
ini.WriteBool('Bands','160M',chk160m.Checked);
ini.WriteBool('Bands','80M',chk80m.Checked);
ini.WriteBool('Bands','40M',chk40m.Checked);
ini.WriteBool('Bands','30M',chk30m.Checked);
ini.WriteBool('Bands','20M',chk20m.Checked);
ini.WriteBool('Bands','17M',chk17m.Checked);
ini.WriteBool('Bands','15M',chk15m.Checked);
ini.WriteBool('Bands','12M',chk12m.Checked);
ini.WriteBool('Bands','10M',chk10m.Checked)
end;
end.
|
unit DX.Messages.Dialog.UITypesHelper;
interface
uses
System.Classes, System.SysUtils, System.UITypes,
DX.Messages.Dialog.Types;
type
TUITypesHelper = class(TObject)
public
class function MessageButtonFromDialogOption(AOption: TDialogOption): TMsgDlgBtn;
class function MessageButtonsFromDialogOptions(AOptions: TDialogOptions): TMsgDlgButtons;
class function DialogOptionFromModalResult(AResult: TModalResult): TDialogOption;
end;
implementation
{ TUITypesHelper }
class function TUITypesHelper.DialogOptionFromModalResult(AResult: TModalResult): TDialogOption;
begin
case AResult of
mrOk:
result := TDialogOption.OK;
mrCancel:
result := TDialogOption.Cancel;
mrYes:
result := TDialogOption.Yes;
mrNo:
result := TDialogOption.No
else
raise Exception.Create('Unknown Dialog Option');
end;
end;
class function TUITypesHelper.MessageButtonFromDialogOption(AOption: TDialogOption): TMsgDlgBtn;
begin
case AOption of
Yes:
result := TMsgDlgBtn.mbYes;
No:
result := TMsgDlgBtn.mbNo;
OK:
result := TMsgDlgBtn.mbOK;
Cancel:
result := TMsgDlgBtn.mbCancel;
Close:
result := TMsgDlgBtn.mbClose
else
raise Exception.Create('Unknown Dialog Option');
end;
end;
class function TUITypesHelper.MessageButtonsFromDialogOptions(AOptions: TDialogOptions): TMsgDlgButtons;
var
LOption: TDialogOption;
begin
result := [];
for LOption in AOptions do
begin
result := result + [MessageButtonFromDialogOption(LOption)];
end;
end;
end.
|
{******************************************}
{ }
{ vtk GridReport library }
{ }
{ Copyright (c) 2003 by vtkTools }
{ }
{******************************************}
{Registers the components and determine where to install them on the Component palette}
unit vgr_ControlsReg;
{$I vtk.inc}
interface
uses
Classes,
vgr_ColorButton, vgr_FontComboBox,
vgr_ControlBar, vgr_Label, vgr_MultiPageButton;
procedure Register;
implementation
{$R *.res}
procedure Register;
begin
RegisterComponents('vtkTools CommonControls', [TvgrColorButton,
TvgrFontComboBox,
TvgrControlBar,
TvgrControlBarManager,
TvgrBevelLabel,
TvgrMultiPageButton]);
end;
end.
|
unit TestObservers;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, contnrs;
type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
end;
//----------------------------------------------------
TObserver = class;
TObservable = class
private
FObservers: TObjectList;
public
procedure RegisterObserver (AObserver: TObserver);
procedure UnregisterObserver(AObserver: TObserver);
procedure object_is_changed;
constructor create;
destructor destroy;
end;
TObserver = class
private
FObservable: TObservable;
public
procedure action; // метод слушателя вызываемый субъектом после того как состояние изменилось
constructor Create(AObservable: TObservable);
destructor Destroy;
end;
TClassA = class //класс субъект
observable: TObservable; // делегируем
procedure change_state;
constructor create;
destructor destroy;
end;
type
TClassB = class (TObserver) //класс слушатель (наследник)
end;
var
Form1: TForm1;
implementation {$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
var
objA: TClassA;objB, objB2: TClassB;
begin
objA:=TClassA.Create; //Субъект
objB:=TClassB.Create(objA.observable); //Слушатель 1
objB2:=TClassB.Create(objA.observable); //Слушатель 2
objA.change_state; // изменение состояние объекта
objB2.Destroy; //исключение возникает здесь
objB.Destroy; //быть может и здесь
objA.Destroy;
end;
{ TObservable }
constructor TObservable.create;
begin
FObservers:=TObjectList.Create;
end;
destructor TObservable.destroy;
begin
FObservers.Destroy;
end;
procedure TObservable.object_is_changed;
var
i: Integer;
begin
for i:=0 to FObservers.Count-1 do TObserver(FObservers[i]).action; //вызываем методы слушателей
end;
procedure TObservable.RegisterObserver (AObserver: TObserver);
begin
FObservers.Add(AObserver);
end;
procedure TObservable.UnregisterObserver(AObserver: TObserver);
begin
FObservers.Remove(AObserver);
end;
{ TObserver }
constructor TObserver.Create(AObservable: TObservable);
begin
inherited Create;
AObservable.RegisterObserver(Self);
FObservable := AObservable;
end;
destructor TObserver.Destroy;
begin
FObservable.UnregisterObserver(Self);
end;
procedure TObserver.action;
begin
Form1.Caption:= Form1.Caption + '+'; // каждый слушатель добавит к заголовку окна '+'
end;
{ TClassA }
procedure TClassA.change_state;
begin
observable.object_is_changed; //вызываем метод чтобы оповестить слушателей
end;
constructor TClassA.create;
begin
observable:=TObservable.create;
end;
destructor TClassA.destroy;
begin
observable.destroy;
end;
end.
|
unit dwm_unit;
interface
uses windows;
const
WM_DWMCOMPOSITIONCHANGED = $031E;
type
_DWM_BLURBEHIND = record
dwFlags: dword;
fEnable: bool;
hRgnBlur: HRGN;
fTransitionOnMaximized: bool;
end;
P_DWM_BLURBEHIND = ^_DWM_BLURBEHIND;
_DWM = class
private
IsVista: boolean;
hDwmLib: uint;
DwmIsCompositionEnabled: function(pfEnabled: PBoolean): HRESULT; stdcall;
DwmEnableBlurBehindWindow: function(destWnd: HWND; bb: P_DWM_BLURBEHIND): HRESULT; stdcall;
public
constructor Create;
destructor Destroy; override;
function CompositingEnabled: boolean;
procedure EnableBlurBehindWindow(const AHandle: THandle; rgn: HRGN);
procedure DisableBlurBehindWindow(const AHandle: THandle);
end;
var DWM: _DWM;
implementation
//------------------------------------------------------------------------------
constructor _DWM.Create;
var
VerInfo: TOSVersioninfo;
begin
VerInfo.dwOSVersionInfoSize:= sizeof(TOSVersionInfo);
GetVersionEx(VerInfo);
IsVista:= VerInfo.dwMajorVersion >= 6;
hDwmLib:= LoadLibrary('dwmapi.dll');
if hDwmLib <> 0 then
begin
@DwmIsCompositionEnabled:= GetProcAddress(hDwmLib, 'DwmIsCompositionEnabled');
@DwmEnableBlurBehindWindow:= GetProcAddress(hDwmLib, 'DwmEnableBlurBehindWindow');
end;
end;
//------------------------------------------------------------------------------
destructor _DWM.Destroy;
begin
FreeLibrary(hDwmLib);
inherited;
end;
//------------------------------------------------------------------------------
function _DWM.CompositingEnabled: boolean;
var
enabled: Boolean;
begin
enabled:= false;
if @DwmIsCompositionEnabled <> nil then DwmIsCompositionEnabled(@enabled);
result:= enabled;
end;
//------------------------------------------------------------------------------
procedure _DWM.EnableBlurBehindWindow(const AHandle: THandle; rgn: HRGN);
var
bb: _DWM_BLURBEHIND;
begin
if CompositingEnabled and (@DwmEnableBlurBehindWindow <> nil) then
begin
ZeroMemory(@bb, SizeOf(bb));
bb.dwFlags:= 3;
bb.fEnable:= true;
bb.hRgnBlur:= rgn;
DwmEnableBlurBehindWindow(AHandle, @bb);
end else
DisableBlurBehindWindow(AHandle);
end;
//------------------------------------------------------------------------------
procedure _DWM.DisableBlurBehindWindow(const AHandle: THandle);
var
bb: _DWM_BLURBEHIND;
begin
if @DwmEnableBlurBehindWindow <> nil then
begin
ZeroMemory(@bb, SizeOf(bb));
bb.dwFlags:= 1;
bb.fEnable:= false;
DwmEnableBlurBehindWindow(AHandle, @bb);
end;
end;
//------------------------------------------------------------------------------
initialization
DWM:= _DWM.Create;
finalization
DWM.free;
end.
|
unit CalcTarifaBairro;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Padrao1, cxGraphics, cxControls, cxLookAndFeels, StrUtils,
cxLookAndFeelPainters, cxContainer, cxEdit, cxStyles, cxCustomData, cxFilter,
cxData, cxDataStorage, DB, cxDBData, cxCheckBox, Menus, FMTBcd, DBClient,
Provider, SqlExpr, cxButtons, ExtCtrls, cxGridLevel, cxGridCustomTableView,
cxGridTableView, cxGridDBTableView, cxClasses, cxGridCustomView, cxGrid,
StdCtrls, Buttons, cxTextEdit, cxLabel, cxGroupBox, Gauges,
dxSkinsCore, dxSkinsDefaultPainters, dxSkinscxPCPainter,
fmeBairro, cxMaskEdit, cxDropDownEdit, cxCalendar,
cxDBEdit, cxCurrencyEdit, dxSkinBlack, dxSkinBlue, dxSkinBlueprint,
dxSkinCaramel, dxSkinCoffee, dxSkinDarkRoom, dxSkinDarkSide,
dxSkinDevExpressDarkStyle, dxSkinDevExpressStyle, dxSkinFoggy,
dxSkinGlassOceans, dxSkinHighContrast, dxSkiniMaginary, dxSkinLilian,
dxSkinLiquidSky, dxSkinLondonLiquidSky, dxSkinMcSkin, dxSkinMetropolis,
dxSkinMetropolisDark, dxSkinMoneyTwins, dxSkinOffice2007Black,
dxSkinOffice2007Blue, dxSkinOffice2007Green, dxSkinOffice2007Pink,
dxSkinOffice2007Silver, dxSkinOffice2010Black, dxSkinOffice2010Blue,
dxSkinOffice2010Silver, dxSkinOffice2013DarkGray, dxSkinOffice2013LightGray,
dxSkinOffice2013White, dxSkinOffice2016Colorful, dxSkinOffice2016Dark,
dxSkinPumpkin, dxSkinSeven, dxSkinSevenClassic, dxSkinSharp, dxSkinSharpPlus,
dxSkinSilver, dxSkinSpringTime, dxSkinStardust, dxSkinSummer2008,
dxSkinTheAsphaltWorld, dxSkinValentine, dxSkinVisualStudio2013Blue,
dxSkinVisualStudio2013Dark, dxSkinVisualStudio2013Light, dxSkinVS2010,
dxSkinWhiteprint, dxSkinXmas2008Blue, Vcl.ComCtrls, dxCore, cxDateUtils,
cxNavigator;
type
TfrmCalcTarifaBairro = class(TfrmPadrao1)
gb1: TcxGroupBox;
cxLabel7: TcxLabel;
btnAplicar: TBitBtn;
GridTable1: TcxGrid;
GridTable1DBTableView1: TcxGridDBTableView;
GridTable1DBTableView1Column7: TcxGridDBColumn;
GridTable1DBTableView1Column8: TcxGridDBColumn;
GridTable1DBTableView1Column1: TcxGridDBColumn;
GridTable1DBTableView1Column2: TcxGridDBColumn;
GridTable1DBTableView1Column5: TcxGridDBColumn;
GridTable1DBTableView1Column3: TcxGridDBColumn;
GridTable1DBTableView1Column4: TcxGridDBColumn;
GridTable1Level1: TcxGridLevel;
Panel1: TPanel;
btnSair: TcxButton;
lblTitColPesquisa: TcxLabel;
edPesquisa: TcxTextEdit;
dspUnidConsum: TDataSetProvider;
cdsUnidConsum: TClientDataSet;
ds1: TDataSource;
provCalcFatBairro: TDataSetProvider;
cdsCalcFatBairro: TClientDataSet;
qryCalcFatBairro: TSQLQuery;
btnVerificar: TBitBtn;
btnCalcular: TBitBtn;
GridTable1DBTableView1Column6: TcxGridDBColumn;
GridTable1DBTableView1Column9: TcxGridDBColumn;
GridTable1DBTableView1Column10: TcxGridDBColumn;
GridTable1DBTableView1Column11: TcxGridDBColumn;
GridTable1DBTableView1Column12: TcxGridDBColumn;
Gauge1: TGauge;
btnCalcIndividual: TcxButton;
btnDetCalculo: TcxButton;
qryUnidConsum: TSQLQuery;
btnLimpar: TBitBtn;
GridTable1DBTableView1Column13: TcxGridDBColumn;
GridTable1DBTableView1Column14: TcxGridDBColumn;
frmeBairro1: TfrmeBairro;
cxLabel1: TcxLabel;
cxLabel2: TcxLabel;
edDtEmissao: TcxDateEdit;
edDtVencto: TcxDateEdit;
cdsCalcFatBairroID_UNID_CONSUM: TIntegerField;
cdsCalcFatBairroNOME_PESSOA: TStringField;
cdsCalcFatBairroDT_LIGACAO: TDateField;
cdsCalcFatBairroDESCR_TIPO_PESSOA: TStringField;
cdsCalcFatBairroCPF_CNPJ_FTDO: TStringField;
cdsCalcFatBairroNUM_HIDROMETRO: TStringField;
cdsCalcFatBairroOBSERV_FATURA: TStringField;
cdsCalcFatBairroQTD_TORNEIRA: TIntegerField;
cdsCalcFatBairroMULTIPLICADOR: TIntegerField;
cdsCalcFatBairroVAL_PRINCIPAL: TFMTBCDField;
cdsCalcFatBairroVAL_MULTA: TFMTBCDField;
cdsCalcFatBairroVAL_OUTRO_DEB: TFMTBCDField;
cdsCalcFatBairroVAL_OUTRO_CRED: TFMTBCDField;
cdsCalcFatBairroVAL_TOTAL: TFMTBCDField;
cdsCalcFatBairroMSG_CALC: TStringField;
Label5: TLabel;
edMsgCalc: TcxDBTextEdit;
edTotValPrincipal: TcxCurrencyEdit;
edTotValMulta: TcxCurrencyEdit;
edTotValOutroDeb: TcxCurrencyEdit;
edTotValOutroCred: TcxCurrencyEdit;
edTotValTotal: TcxCurrencyEdit;
qryResumoBairro: TSQLQuery;
qryResumoBairroANO_MES: TStringField;
qryResumoBairroENDER_ID_BAIRRO: TIntegerField;
qryResumoBairroVAL_PRINCIPAL: TFMTBCDField;
qryResumoBairroVAL_MULTA: TFMTBCDField;
qryResumoBairroVAL_OUTRO_DEB: TFMTBCDField;
qryResumoBairroVAL_OUTRO_CRED: TFMTBCDField;
qryResumoBairroVAL_TOTAL: TFMTBCDField;
qryCalcFatIndividual: TSQLQuery;
provCalcFatIndividual: TDataSetProvider;
cdsCalcFatIndividual: TClientDataSet;
cdsCalcFatIndividualR_ITEM: TIntegerField;
cdsCalcFatIndividualR_COD_ITEM: TStringField;
cdsCalcFatIndividualR_DESCRICAO: TStringField;
cdsCalcFatIndividualR_REFENCIA: TStringField;
cdsCalcFatIndividualR_VALOR: TFMTBCDField;
cdsCalcFatIndividualR_TIPO: TStringField;
cdsCalcFatIndividualR_OBSERVACAO: TStringField;
cdsCalcFatIndividualR_QTD_TORNEIRA: TIntegerField;
cdsCalcFatIndividualR_MULTIPLIC: TIntegerField;
cdsCalcFatIndividualR_CONSUMO_M3: TIntegerField;
cdsCalcFatIndividualR_QTD_DIAS_ATRASO: TIntegerField;
cdsCalcFatIndividualR_ANO_MES_MULTA: TStringField;
mTbDetCalc: TClientDataSet;
mTbDetCalcID: TIntegerField;
mTbDetCalcCOD_ITEM: TStringField;
mTbDetCalcDESCRICAO: TStringField;
mTbDetCalcREFERENCIA: TStringField;
mTbDetCalcVALOR: TCurrencyField;
mTbDetCalcTIPO: TStringField;
mTbDetCalcID_UNID_CONSUM: TIntegerField;
GridDetCalc: TcxGrid;
GridDetCalcDBTableView1: TcxGridDBTableView;
GridDetCalcDBTableView1Column7: TcxGridDBColumn;
GridDetCalcDBTableView1Column4: TcxGridDBColumn;
GridDetCalcDBTableView1Column1: TcxGridDBColumn;
GridDetCalcDBTableView1Column8: TcxGridDBColumn;
GridDetCalcDBTableView1Column2: TcxGridDBColumn;
GridDetCalcDBTableView1Column3: TcxGridDBColumn;
GridDetCalcLevel1: TcxGridLevel;
btnGravar: TcxButton;
qryBairroEmissao: TSQLQuery;
qryBairroEmissaoDT_EMISSAO: TDateField;
qryBairroEmissaoDT_VENCIMENTO: TDateField;
dsDetCalc: TDataSource;
qryDetCalc: TSQLQuery;
qryDetCalcR_ID: TIntegerField;
qryDetCalcR_REFERENCIA: TStringField;
qryDetCalcR_DESCRICAO: TStringField;
qryDetCalcR_VALOR: TFMTBCDField;
qryDetCalcR_TIPO: TStringField;
qryDetCalcR_COD: TStringField;
mTbDetCalcANO_MES_MULTA: TStringField;
mTbDetCalcQTD_DIAS_MULTA: TIntegerField;
qryDetCalcR_ANO_MES_MULTA: TStringField;
qryDetCalcR_QTD_DIAS_MULTA: TIntegerField;
Label1: TLabel;
edQtdUC_Bairro: TcxCurrencyEdit;
Label2: TLabel;
edQtdUC_Calc: TcxCurrencyEdit;
Label3: TLabel;
qryUC: TSQLQuery;
qryUCQTD: TIntegerField;
qryBairroEmissaoQTD_UNID_CONSUM_TOTAL: TIntegerField;
qryBairroEmissaoQTD_UNID_CONSUM_CALC: TIntegerField;
cdsCalcFatBairroCALCULAR: TStringField;
btnCancelar: TcxButton;
qryMovim: TSQLQuery;
qryMovimR_QTD_DIAS: TIntegerField;
GridTable1DBTableView1Column15: TcxGridDBColumn;
cdsCalcFatBairroFORMA_CALCULO: TStringField;
cdsUnidConsumID: TIntegerField;
cdsUnidConsumNOME_PESSOA: TStringField;
cdsUnidConsumDT_LIGACAO: TDateField;
cdsUnidConsumDESCR_TIPO_PESSOA: TStringField;
cdsUnidConsumCPF_CNPJ_FTDO: TStringField;
cdsUnidConsumNUM_HIDROMETRO: TStringField;
cdsUnidConsumOBSERV_FATURA: TStringField;
cdsUnidConsumQTD_TORNEIRA: TIntegerField;
cdsUnidConsumMULTIPLICADOR: TIntegerField;
cdsUnidConsumSITUACAO: TStringField;
cdsUnidConsumFORMA_CALCULO: TStringField;
cdsUnidConsumCONSUMO: TLargeintField;
cdsCalcFatBairroCONSUMO: TIntegerField;
GridTable1DBTableView1Column16: TcxGridDBColumn;
cdsUnidConsumCATEGORIA: TStringField;
cdsCalcFatBairroCATEGORIA: TStringField;
cdsCalcFatBairroQTD_DIAS_USO: TIntegerField;
cdsUnidConsumDESCR_SITUACAO: TStringField;
cdsCalcFatBairroSITUACAO: TStringField;
cdsCalcFatBairroDESCR_SITUACAO: TStringField;
procedure btnLimparClick(Sender: TObject);
procedure btnSairClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure FormShow(Sender: TObject);
procedure btnAplicarClick(Sender: TObject);
procedure btnVerificarClick(Sender: TObject);
procedure btnCalcularClick(Sender: TObject);
procedure edPesquisaPropertiesChange(Sender: TObject);
procedure GridTable1DBTableView1ColumnHeaderClick(Sender: TcxGridTableView;
AColumn: TcxGridColumn);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btnCalcIndividualClick(Sender: TObject);
procedure btnDetCalculoClick(Sender: TObject);
procedure btnCancelarClick(Sender: TObject);
procedure edDtVenctoExit(Sender: TObject);
procedure frmeBairro1edIdExit(Sender: TObject);
procedure btnGravarClick(Sender: TObject);
procedure cdsCalcFatBairroBeforeDelete(DataSet: TDataSet);
procedure edTotValPrincipalPropertiesChange(Sender: TObject);
procedure frmeBairro1edIdPropertiesChange(Sender: TObject);
procedure edPesquisaKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure cdsCalcFatBairroAfterScroll(DataSet: TDataSet);
private
pv_sCodIndex: string;
pv_lCalculando: Boolean;
procedure HabilitaBotoes(lOpcao1, lOpcao2, lOpcao3: Boolean);
procedure AtualizaTotais;
function ValItemCalc(sCod, sDC: string): Currency;
{ Private declarations }
public
{ Public declarations }
end;
var
frmCalcTarifaBairro: TfrmCalcTarifaBairro;
implementation
uses udmPrincipal, VarGlobais, gsLib, UtilsDb, DetalhaFatura, CalcTarifaIndividual, MsgDialog;
{$R *.dfm}
procedure TfrmCalcTarifaBairro.btnAplicarClick(Sender: TObject);
begin
Screen.Cursor := crHourGlass;
qryBairroEmissao.Close;
qryBairroEmissao.ParamByName('pAnoMes').Value := glb_sAnoMesTrab;
qryBairroEmissao.ParamByName('pBairro').Value := StrToInt(Trim(frmeBairro1.edId.Text));
qryBairroEmissao.Open;
if not qryBairroEmissaoDT_VENCIMENTO.IsNull then
begin
edDtEmissao.Text:= qryBairroEmissaoDT_EMISSAO.AsString;
edDtVencto.Text := qryBairroEmissaoDT_VENCIMENTO.AsString;
edQtdUC_Bairro.Value := qryBairroEmissaoQTD_UNID_CONSUM_TOTAL.Value;
edQtdUC_Calc.Value := qryBairroEmissaoQTD_UNID_CONSUM_CALC.Value;
end else
begin
qryUC.Close;
qryUC.Params[0].Value := qryBairroEmissao.ParamByName('pBairro').Value;
qryUC.Open;
if not qryUCQTD.IsNull then
edQtdUC_Bairro.Value := qryUCQTD.Value
else
edQtdUC_Bairro.Value := 0;
edQtdUC_Calc.Value := 0;
end;
cdsCalcFatBairro.Close;
qryCalcFatBairro.ParamByName('pAnoMes').Value := glb_sAnoMesTrab;
qryCalcFatBairro.ParamByName('pAnoMes2').Value:= glb_sAnoMesTrab;
qryCalcFatBairro.ParamByName('pBairro').Value := StrToInt(Trim(frmeBairro1.edId.Text));
qryCalcFatBairro.ParamByName('pLogradIni').Value := 1;
qryCalcFatBairro.ParamByName('pLogradFim').Value := 99999;
cdsCalcFatBairro.Open;
cdsCalcFatBairro.IndexFieldNames:= 'NOME_PESSOA';
GridTable1DBTableView1ColumnHeaderClick(GridTable1DBTableView1,GridTable1DBTableView1.Columns[1]);
GridTable1.SetFocus;
HabilitaBotoes(False,True,False);
btnCalcular.Enabled := (cdsCalcFatBairro.RecordCount > 0);
btnCancelar.Enabled := (cdsCalcFatBairro.RecordCount > 0);
cdsCalcFatBairro.First;
if cdsCalcFatBairro.RecordCount = 0 then
edDtEmissao.SetFocus
else
GridTable1.SetFocus;
AtualizaTotais;
btnDetCalculo.Enabled := (edTotValTotal.Value > 0);
Screen.Cursor := crDefault;
end;
procedure TfrmCalcTarifaBairro.btnCalcularClick(Sender: TObject);
var
sDtMovim,
sDtMovim2 : String[10];
sMesAno : String[6];
sIdUnidConsum : String;
iQtdUnidConsum,
iQtdCalc : Integer;
dDtTemp1,
dDtTemp2 : TDate;
iErro : Integer;
crValPrincipal,
crValMulta,
crValOutrosDeb,
crValOutrosCred: Currency;
begin
if (Empty(frmeBairro1.edId.Text)) or
(EmptyData(edDtEmissao.Text)) or
(EmptyData(edDtVencto.Text)) then
begin
frmeBairro1.edId.SetFocus;
exit;
end;
Screen.Cursor := crHourGlass;
pv_lCalculando := True;
Panel1.Caption := 'Aguarde, Calculando ...';
Application.ProcessMessages;
dDtTemp1 := StrToDate(DtEmissaoMesAnterior(StrToInt(Trim(frmeBairro1.edId.Text)),glb_sAnoMesTrab));
dDtTemp2 := StrToDate(edDtEmissao.Text);
Gauge1.Progress:= 0;
Gauge1.MaxValue:= cdsCalcFatBairro.RecordCount;
iQtdUnidConsum := Gauge1.MaxValue;
cdsCalcFatBairro.First;
sMesAno := InverteAnoMes(glb_sAnoMesTrab,'2');
edQtdUC_Calc.Value := 0;
iQtdCalc := Inteiro(edQtdUC_Calc.Value);
edTotValPrincipal.Value:= 0;
edTotValMulta.Value := 0;
edTotValOutroDeb.Value := 0;
edTotValOutroCred.Value:= 0;
edTotValTotal.Value := 0;
mTbDetCalc.EmptyDataSet;
mTbDetCalc.Close;
mTbDetCalc.Open;
cdsCalcFatBairro.IndexFieldNames:= 'NOME_PESSOA';
cdsCalcFatBairro.First;
while not cdsCalcFatBairro.eof do
begin
if (cdsCalcFatBairroSITUACAO.Value = '0') or // aguardando ligação ou insenta
(cdsCalcFatBairroSITUACAO.Value = '4') then
begin
Gauge1.Progress := Gauge1.Progress + 1;
cdsCalcFatBairro.Next;
Continue;
end;
if (cdsCalcFatBairroCALCULAR.Value <> 'S') or
((cdsCalcFatBairroqtd_dias_uso.Value < 15) and
(cdsCalcFatBairroFORMA_CALCULO.Value = '2')) then
begin
Gauge1.Progress := Gauge1.Progress + 1;
cdsCalcFatBairro.Next;
Continue;
end;
iErro := 0;
sIdUnidConsum := cdsCalcFatBairroID_UNID_CONSUM.AsString;
crValPrincipal := 0;
crValMulta := 0;
crValOutrosDeb := 0;
crValOutrosCred:= 0;
cdsCalcFatIndividual.Close;
qryCalcFatIndividual.ParamByName('panomes').Value := glb_sAnoMesTrab;
qryCalcFatIndividual.ParamByName('puc').Value := cdsCalcFatBairroID_UNID_CONSUM.Value;
qryCalcFatIndividual.ParamByName('pdtpagini').Value := dDtTemp1;
qryCalcFatIndividual.ParamByName('pdtpagfim').Value := dDtTemp2;
qryCalcFatIndividual.ParamByName('pQtdDias').Value := cdsCalcFatBairroqtd_dias_uso.Value;
try
cdsCalcFatIndividual.Open;
except
on E: Exception do
begin
iErro := 1;
Mensagem('Erro ao Calcular a Tarifa da Unid. Consumidora: '+
cdsCalcFatBairroID_UNID_CONSUM.AsString+#13+
'('+E.Message+')',
'E R R O !!!',MB_OK+MB_ICONERROR);
cdsCalcFatBairro.Next;
continue;
end;
end;
if iErro = 1 then
begin
Gauge1.Progress := Gauge1.Progress + 1;
cdsCalcFatBairro.Next;
Continue;
end;
while not cdsCalcFatIndividual.eof do
begin
if cdsCalcFatIndividualR_COD_ITEM.Value = '001' then
crValPrincipal := cdsCalcFatIndividualR_VALOR.AsCurrency
else
if cdsCalcFatIndividualR_COD_ITEM.Value = '555' then
crValMulta := crValMulta + cdsCalcFatIndividualR_VALOR.AsCurrency
else
if (cdsCalcFatIndividualR_COD_ITEM.Value = '777') and
(cdsCalcFatIndividualR_TIPO.Value = 'D') then
crValOutrosDeb := crValOutrosDeb + cdsCalcFatIndividualR_VALOR.AsCurrency
else
crValOutrosCred := crValOutrosCred + cdsCalcFatIndividualR_VALOR.AsCurrency;
mTbDetCalc.Insert;
mTbDetCalcID_UNID_CONSUM.Value := cdsCalcFatBairroID_UNID_CONSUM.Value;
mTbDetCalcID.Value := cdsCalcFatIndividualR_ITEM.Value;
mTbDetCalcCOD_ITEM.Value := cdsCalcFatIndividualR_COD_ITEM.Value;
mTbDetCalcDESCRICAO.Value := cdsCalcFatIndividualR_DESCRICAO.Value;
mTbDetCalcREFERENCIA.Value := cdsCalcFatIndividualR_REFENCIA.Value;
mTbDetCalcVALOR.Value := cdsCalcFatIndividualR_VALOR.AsCurrency;
mTbDetCalcTIPO.Value := cdsCalcFatIndividualR_TIPO.Value;
mTbDetCalcANO_MES_MULTA.Value := cdsCalcFatIndividualR_ANO_MES_MULTA.Value;
mTbDetCalcQTD_DIAS_MULTA.Value := cdsCalcFatIndividualR_QTD_DIAS_ATRASO.Value;
mTbDetCalc.Post;
cdsCalcFatIndividual.Next;
end;
cdsCalcFatBairro.edit;
cdsCalcFatBairroVAL_PRINCIPAL.AsCurrency := crValPrincipal;
cdsCalcFatBairroVAL_MULTA.AsCurrency := crValMulta;
cdsCalcFatBairroVAL_OUTRO_DEB.AsCurrency := crValOutrosDeb;
cdsCalcFatBairroVAL_OUTRO_CRED.AsCurrency:= crValOutrosCred;
cdsCalcFatBairroVAL_TOTAL.AsCurrency := (cdsCalcFatBairroVAL_PRINCIPAL.AsCurrency +
cdsCalcFatBairroVAL_MULTA.AsCurrency + cdsCalcFatBairroVAL_OUTRO_DEB.AsCurrency) -
cdsCalcFatBairroVAL_OUTRO_CRED.AsCurrency;
cdsCalcFatBairro.Post;
if cdsCalcFatBairroVAL_TOTAL.AsCurrency > 0 then
begin
inc(iQtdCalc);
edQtdUC_Calc.Value := iQtdCalc;
edTotValPrincipal.Value:= edTotValPrincipal.Value + cdsCalcFatBairroVAL_PRINCIPAL.AsCurrency;
edTotValMulta.Value := edTotValMulta.Value + cdsCalcFatBairroVAL_MULTA.AsCurrency;
edTotValOutroDeb.Value := edTotValOutroDeb.Value + cdsCalcFatBairroVAL_OUTRO_DEB.AsCurrency;
edTotValOutroCred.Value:= edTotValOutroCred.Value + cdsCalcFatBairroVAL_OUTRO_CRED.AsCurrency;
end;
Application.ProcessMessages;
Gauge1.Progress := Gauge1.Progress + 1;
cdsCalcFatBairro.Next;
end;
Mensagem('Processo de Cálculo, Concluído ...',
'AVISO !',
MB_OK+MB_ICONEXCLAMATION);
Gauge1.Progress := 0;
Panel1.Caption := '';
Application.ProcessMessages;
GridTable1.SetFocus;
HabilitaBotoes(False,False,True);
pv_lCalculando := False;
btnCancelar.Enabled := True;
Screen.Cursor := crDefault;
end;
procedure TfrmCalcTarifaBairro.btnCancelarClick(
Sender: TObject);
Var
iErro: Integer;
sDelArqInicia: string[1];
iOpCancel: Integer;
sTextSQL: String;
lCancelou: Boolean;
begin
if cdsCalcFatBairroVAL_TOTAL.AsCurrency = 0 then exit;
if GridDetCalc.Visible then
btnDetCalculo.Click;
iOpCancel := frmMsgDialog.Executa('CANCELAR CÁLCULO DE FATURAS MENSAIS. ',
'SELECIONE A OPÇÃO ABAIXO ...',
'&INDIVIDUAL','&BAIRRO TODO','&NÃO CANCELAR');
//if not Confirma('DESEJA REALMENTE CANCELAR O CÁLCULO DESSA FATURA ?') then
// exit;
lCancelou := False;
iErro := 0;
if iOpCancel = 1 then
begin
lCancelou := True;
sTextSQL := 'delete from calc_fatura_mensal where '+
'(id_unid_consum = '+cdsCalcFatBairroID_UNID_CONSUM.AsString+') and '+
'(ano_mes = '+QuotedStr(glb_sAnoMesTrab)+')';
Try
dmPrincipal.SConPrincipal.ExecuteDirect(sTextSQL);
except
iErro := 1;
End;
cdsCalcFatBairro.Delete;
end else
if iOpCancel = 2 then
begin
if not Confirma('Deseja Realmente CANCELAR todo o Cálculo desse Bairro ?') then exit;
Screen.Cursor := crHourGlass;
lCancelou := True;
pv_lCalculando := True;
sTextSQL := 'delete from calc_fatura_mensal where '+
'(ender_id_bairro = '+Trim(frmeBairro1.edId.Text)+') and '+
'(ano_mes = '+QuotedStr(glb_sAnoMesTrab)+')';
try
dmPrincipal.SConPrincipal.ExecuteDirect(sTextSQL);
except
iErro := 1;
end;
Screen.Cursor := crDefault;
end;
if (lCancelou) and (iErro = 0) Then
Mensagem('CÁLCULO CANCELADO COM SUCESSO ...','AVISO !!!',
MB_OK+MB_ICONINFORMATION);
if iOpCancel = 2 then
begin
cdsCalcFatBairro.EmptyDataSet;
btnLimpar.Click;
end;
end;
procedure TfrmCalcTarifaBairro.btnDetCalculoClick(Sender: TObject);
begin
if btnDetCalculo.Tag = 1 then
begin
if Not mTbDetCalc.FindKey([cdsCalcFatBairroID_UNID_CONSUM.Value]) then
begin
qryDetCalc.Close;
qryDetCalc.ParamByName('panomes').Value := glb_sAnoMesTrab;
qryDetCalc.ParamByName('puc').Value := cdsCalcFatBairroID_UNID_CONSUM.Value;
qryDetCalc.Open;
while not qryDetCalc.eof do
begin
mTbDetCalc.Insert;
mTbDetCalcID_UNID_CONSUM.Value := cdsCalcFatBairroID_UNID_CONSUM.Value;
mTbDetCalcID.Value := qryDetCalcR_ID.Value;
mTbDetCalcCOD_ITEM.Value := qryDetCalcR_COD.Value;
mTbDetCalcDESCRICAO.Value := qryDetCalcR_DESCRICAO.Value;
mTbDetCalcREFERENCIA.Value := qryDetCalcR_REFERENCIA.Value;
mTbDetCalcVALOR.Value := qryDetCalcR_VALOR.AsCurrency;
mTbDetCalcTIPO.Value := qryDetCalcR_TIPO.Value;
mTbDetCalcANO_MES_MULTA.Value := qryDetCalcR_ANO_MES_MULTA.Value;
mTbDetCalcQTD_DIAS_MULTA.Value := qryDetCalcR_QTD_DIAS_MULTA.Value;
mTbDetCalc.Post;
qryDetCalc.Next;
end;
end;
mTbDetCalc.Filtered := False;
mTbDetCalc.Filter := 'ID_UNID_CONSUM = '+cdsCalcFatBairroID_UNID_CONSUM.AsString;
mTbDetCalc.Filtered := True;
cdsCalcFatBairro.DisableControls;
GridDetCalc.Visible := True;
GridDetCalc.SetFocus;
btnDetCalculo.Tag := 2;
btnDetCalculo.Font.Style := [];
end else
begin
mTbDetCalc.Filtered := False;
GridDetCalc.Visible := False;
cdsCalcFatBairro.EnableControls;
btnDetCalculo.Tag := 1;
btnDetCalculo.Font.Style := [fsBold];
end;
end;
procedure TfrmCalcTarifaBairro.btnCalcIndividualClick(Sender: TObject);
begin
{
frmCalcTarifaIndividual := TfrmCalcTarifaIndividual.Create(Self);
frmCalcTarifaIndividual.pb_iUnidConsum := cdsCalcFatBairroID_UNID_CONSUM.Value;
frmCalcTarifaIndividual.pb_sAnoMes := glb_sAnoMesTrab;
frmCalcTarifaIndividual.ShowModal;
FreeAndNil(frmCalcTarifaIndividual);
}
end;
procedure TfrmCalcTarifaBairro.btnGravarClick(Sender: TObject);
Var
iErro,
iUC,
iBairro: Integer;
sSQL1: string;
sAnoMes: string[6];
begin
Screen.Cursor := crHourGlass;
Panel1.Caption:= 'Aguarde, Salvando ...';
Application.ProcessMessages;
cdsCalcFatBairro.DisableControls;
Gauge1.Progress := 0;
Gauge1.MaxValue := cdsCalcFatBairro.RecordCount;
cdsCalcFatBairro.First;
iErro := 0;
sAnoMes := glb_sAnoMesTrab;
iBairro := StrToInt(Trim(frmeBairro1.edId.Text));
while not cdsCalcFatBairro.eof do
begin
Gauge1.Progress := Gauge1.Progress + 1;
if cdsCalcFatBairroVAL_TOTAL.AsCurrency = 0 then
begin
cdsCalcFatBairro.Next;
Continue;
end;
iUC := cdsCalcFatBairroID_UNID_CONSUM.Value;
if dmPrincipal.SalvaCalcFaturaMensal(sAnoMes,
iUC,
edDtEmissao.Text,
edDtVencto.Text,
cdsCalcFatBairroQTD_TORNEIRA.Value,
cdsCalcFatBairroMULTIPLICADOR.Value,
cdsCalcFatBairroNUM_HIDROMETRO.Value,
cdsCalcFatBairroVAL_PRINCIPAL.AsCurrency,
cdsCalcFatBairroVAL_MULTA.AsCurrency,
cdsCalcFatBairroVAL_OUTRO_DEB.AsCurrency,
cdsCalcFatBairroVAL_OUTRO_CRED.AsCurrency) then
begin
sSQL1 := 'delete from calc_fatura_mensal_multa '+
'where (id_unid_consum = '+IntToStr(iUC)+') and '+
' (ano_mes_calc = '+QuotedStr(sAnoMes)+')';
dmPrincipal.SConPrincipal.ExecuteDirect(sSQL1);
mTbDetCalc.FindKey([iUC]);
while (not mTbDetCalc.eof) and
(mTbDetCalcID_UNID_CONSUM.Value = iUC) do
begin
if mTbDetCalcCOD_ITEM.Value = '555' then
begin
if not dmPrincipal.SalvaMultaFaturaMensal(iUC,
sAnoMes,
mTbDetCalcANO_MES_MULTA.Value,
mTbDetCalcQTD_DIAS_MULTA.Value,
mTbDetCalcVALOR.AsCurrency) then
begin
iErro := 1;
Break;
end;
end;
mTbDetCalc.Next;
end;
end else
iErro := 1;
cdsCalcFatBairro.Next;
end;
if iErro = 0 then
begin
sSQL1 := 'execute procedure sp_calc_resumo_bairro('+QuotedStr(sAnoMes)+','+
IntToStr(iBairro)+','+QuotedStr(edDtEmissao.Text)+','+
QuotedStr(edDtVencto.Text)+')';
Try
dmPrincipal.SConPrincipal.ExecuteDirect(sSQL1);
except
on E: Exception do
begin
iErro := 1;
Mensagem('Não foi Calcular os Totais do Bairro ...'+#13+
'('+E.Message+')','E R R O !!!',MB_OK+MB_ICONERROR);
end;
End;
end;
cdsCalcFatBairro.EnableControls;
if iErro = 0 then
Mensagem('Cálculo do Bairro Salvo com Sucesso ...','AVISO !!!',MB_OK+MB_ICONINFORMATION);
HabilitaBotoes(False,False,False);
Panel1.Caption:= '';
Application.ProcessMessages;
Screen.Cursor := crDefault;
btnLimpar.SetFocus;
end;
procedure TfrmCalcTarifaBairro.btnSairClick(Sender: TObject);
begin
Close;
end;
procedure TfrmCalcTarifaBairro.btnVerificarClick(Sender: TObject);
Var
iQtdUnidConsum: Integer;
lCalcUC: Boolean;
dDtLigacao: TDate;
begin
Screen.Cursor := crHourGlass;
pv_lCalculando := True;
Panel1.Caption := 'Aguarde, processando ...';
Application.ProcessMessages;
if GridDetCalc.Visible then
btnDetCalculo.Click;
mTbDetCalc.EmptyDataSet;
mTbDetCalc.Close;
mTbDetCalc.Open;
cdsCalcFatBairro.DisableControls;
cdsCalcFatBairro.IndexFieldNames := 'id_unid_consum';
cdsUnidConsum.Close;
qryUnidConsum.ParamByName('pBairro').AsString := Trim(frmeBairro1.edId.Text);
cdsUnidConsum.Open;
Gauge1.Progress := 0;
Gauge1.MaxValue := cdsUnidConsum.RecordCount;
iQtdUnidConsum := Gauge1.MaxValue;
while not cdsUnidConsum.eof do
begin
Gauge1.Progress := Gauge1.Progress + 1;
lCalcUC := True;
{dDtLigacao := cdsUnidConsumDT_LIGACAO.Value;
if (dDtLigacao is null) or (DateToStr(dDtLigacao)='31/12/1899') then
dDtLigacao := StrToDate(')
}
qryMovim.Close;
qryMovim.ParamByName('pAnoMes').Value := glb_sAnoMesTrab;
qryMovim.ParamByName('pUC').Value := cdsUnidConsumID.Value;
qryMovim.Open;
if not cdsCalcFatBairro.FindKey([cdsUnidConsumID.Value]) then
begin
cdsCalcFatBairro.Insert;
cdsCalcFatBairroID_UNID_CONSUM.Value := cdsUnidConsumID.Value;
cdsCalcFatBairroNOME_PESSOA.Value := cdsUnidConsumNOME_PESSOA.Value;
cdsCalcFatBairroDT_LIGACAO.Value := cdsUnidConsumDT_LIGACAO.Value;
cdsCalcFatBairroDESCR_TIPO_PESSOA.Value := cdsUnidConsumDESCR_TIPO_PESSOA.Value;
cdsCalcFatBairroCPF_CNPJ_FTDO.Value := cdsUnidConsumCPF_CNPJ_FTDO.Value;
cdsCalcFatBairroCATEGORIA.Value := cdsUnidConsumCATEGORIA.Value;
cdsCalcFatBairroNUM_HIDROMETRO.Value := cdsUnidConsumNUM_HIDROMETRO.Value;
cdsCalcFatBairroOBSERV_FATURA.Value := cdsUnidConsumOBSERV_FATURA.Value;
cdsCalcFatBairroQTD_TORNEIRA.Value := cdsUnidConsumQTD_TORNEIRA.Value;
cdsCalcFatBairroMULTIPLICADOR.Value := cdsUnidConsumMULTIPLICADOR.Value;
cdsCalcFatBairroSITUACAO.Value := cdsUnidConsumSITUACAO.Value;
cdsCalcFatBairroDESCR_SITUACAO.Value := cdsUnidConsumDESCR_SITUACAO.Value;
cdsCalcFatBairroVAL_PRINCIPAL.AsCurrency := 0;
cdsCalcFatBairroVAL_MULTA.AsCurrency := 0;
cdsCalcFatBairroVAL_OUTRO_DEB.AsCurrency := 0;
cdsCalcFatBairroVAL_OUTRO_CRED.AsCurrency := 0;
cdsCalcFatBairroVAL_TOTAL.AsCurrency := 0;
cdsCalcFatBairroqtd_dias_uso.Value := qryMovimR_QTD_DIAS.Value;
cdsCalcFatBairroCONSUMO.Value := cdsUnidConsumCONSUMO.Value;
cdsCalcFatBairroCALCULAR.Value := 'S';
end else
begin
cdsCalcFatBairro.edit;
cdsCalcFatBairroCALCULAR.Value := 'N';
end;
cdsCalcFatBairro.Post;
cdsUnidConsum.Next;
end;
qryMovim.Close;
cdsCalcFatBairro.EnableControls;
Gauge1.Progress := 0;
Panel1.Caption := '';
Application.ProcessMessages;
HabilitaBotoes(False,True,False);
btnVerificar.Enabled := False;
btnCalcular.Enabled := (cdsUnidConsum.RecordCount > 0);
GridTable1DBTableView1ColumnHeaderClick(GridTable1DBTableView1,GridTable1DBTableView1.Columns[1]);
btnCancelar.Enabled := (cdsCalcFatBairro.RecordCount > 0);
pv_lCalculando := False;
Screen.Cursor := crDefault;
end;
procedure TfrmCalcTarifaBairro.cdsCalcFatBairroAfterScroll(DataSet: TDataSet);
begin
if pv_lCalculando then exit;
btnDetCalculo.Enabled := (cdsCalcFatBairroVAL_TOTAL.AsCurrency > 0);
end;
procedure TfrmCalcTarifaBairro.cdsCalcFatBairroBeforeDelete(DataSet: TDataSet);
begin
edTotValPrincipal.Value := edTotValPrincipal.Value - cdsCalcFatBairroVAL_PRINCIPAL.AsCurrency;
edTotValMulta.Value := edTotValMulta.Value - cdsCalcFatBairroVAL_MULTA.AsCurrency;
edTotValOutroDeb.Value := edTotValOutroDeb.Value - cdsCalcFatBairroVAL_OUTRO_DEB.AsCurrency;
edTotValOutroCred.Value := edTotValOutroCred.Value - cdsCalcFatBairroVAL_OUTRO_CRED.AsCurrency;
mTbDetCalc.FindKey([cdsCalcFatBairroID_UNID_CONSUM.Value]);
while (not mTbDetCalc.Eof) and
(mTbDetCalcID_UNID_CONSUM.Value = cdsCalcFatBairroID_UNID_CONSUM.Value) do
mTbDetCalc.Delete;
end;
procedure TfrmCalcTarifaBairro.btnLimparClick(Sender: TObject);
begin
edTotValPrincipal.Value := 0;
edTotValMulta.Value := 0;
edTotValOutroDeb.Value := 0;
edTotValOutroCred.Value := 0;
edQtdUC_Bairro.Value := 0;
edQtdUC_Calc.Value := 0;
Gauge1.Progress := 0;
HabilitaBotoes(True,False,False);
cdsUnidConsum.Close;
cdsCalcFatBairro.Close;
qryBairroEmissao.Close;
if GridDetCalc.Visible then
btnDetCalculo.Click;
frmeBairro1.edId.Text := '';
frmeBairro1.edId.SetFocus;
cdsCalcFatBairro.Close;
btnCancelar.Enabled := False;
end;
procedure TfrmCalcTarifaBairro.edDtVenctoExit(Sender: TObject);
begin
if EmptyData(edDtVencto.Text) then exit;
if StrToDate(edDtVencto.Text) <= StrToDate(edDtEmissao.Text) then
edDtEmissao.SetFocus;
end;
procedure TfrmCalcTarifaBairro.edPesquisaKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
inherited;
if Shift = [] then NavegaClient(Key,GridTable1DBTableView1);
end;
procedure TfrmCalcTarifaBairro.edPesquisaPropertiesChange(
Sender: TObject);
begin
if not TcxTextEdit(Sender).Enabled then exit;
PesquisaIncremental(TcxTextEdit(Sender).Text,ds1,pv_sCodIndex);
end;
procedure TfrmCalcTarifaBairro.edTotValPrincipalPropertiesChange(Sender: TObject);
begin
edTotValTotal.Value := (edTotValPrincipal.Value + edTotValMulta.Value + edTotValOutroDeb.Value) -
edTotValOutroCred.Value;
Application.ProcessMessages;
end;
procedure TfrmCalcTarifaBairro.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
inherited;
cdsUnidConsum.Close;
qryBairroEmissao.Close;
end;
procedure TfrmCalcTarifaBairro.FormCreate(Sender: TObject);
begin
inherited;
pv_sCodIndex := 'NOME_PESSOA';
Caption := 'CÁLCULAR FATURAS DO MÊS POR BAIRRO ...';
end;
procedure TfrmCalcTarifaBairro.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
inherited;
If (Shift = []) And (Key = VK_F3) Then
if not frmeBairro1.Enabled then
if edPesquisa.Enabled then
edPesquisa.SetFocus;
end;
procedure TfrmCalcTarifaBairro.FormShow(Sender: TObject);
begin
inherited;
pv_lCalculando := False;
mTbDetCalc.CreateDataSet;
mTbDetCalc.Open;
mTbDetCalc.IndexFieldNames := 'ID_UNID_CONSUM;COD_ITEM;ID';
HabilitaBotoes(True,False,False);
btnCancelar.Enabled := False;
frmeBairro1.edId.SetFocus;
end;
procedure TfrmCalcTarifaBairro.frmeBairro1edIdExit(Sender: TObject);
begin
inherited;
frmeBairro1.edIdExit(Sender);
end;
procedure TfrmCalcTarifaBairro.frmeBairro1edIdPropertiesChange(Sender: TObject);
begin
inherited;
if Trim(frmeBairro1.edId.Text) = '' then frmeBairro1.edDescricao.Text := '';
end;
procedure TfrmCalcTarifaBairro.GridTable1DBTableView1ColumnHeaderClick(
Sender: TcxGridTableView; AColumn: TcxGridColumn);
begin
edPesquisa.Enabled := (GridTable1DBTableView1.Columns[AColumn.Index].Tag = 1);
lblTitColPesquisa.Enabled := edPesquisa.Enabled;
cdsCalcFatBairro.IndexFieldNames := GridTable1DBTableView1.
Columns[AColumn.Index].DataBinding.FieldName;
end;
procedure TfrmCalcTarifaBairro.HabilitaBotoes(lOpcao1,lOpcao2,lOpcao3: Boolean);
begin
frmeBairro1.Enabled := lOpcao1;
btnAplicar.Enabled := lOpcao1;
//edDtEmissao.Properties.ReadOnly:= Not lOpcao1;
//edDtVencto.Properties.ReadOnly := Not lOpcao1;
btnLimpar.Enabled := Not lOpcao1;
btnVerificar.Enabled := Not lOpcao1;
btnCalcular.Enabled := lOpcao2;
btnGravar.Enabled := lOpcao3;
btnDetCalculo.Enabled := lOpcao3;
end;
procedure TfrmCalcTarifaBairro.AtualizaTotais;
begin
qryResumoBairro.Close;
qryResumoBairro.ParamByName('panomes').Value := glb_sAnoMesTrab;
qryResumoBairro.ParamByName('pbairro').Value := StrToInt(Trim(frmeBairro1.edId.Text));
qryResumoBairro.Open;
edTotValPrincipal.Value := qryResumoBairroVAL_PRINCIPAL.AsCurrency;
edTotValMulta.Value := qryResumoBairroVAL_MULTA.AsCurrency;
edTotValOutroDeb.Value := qryResumoBairroVAL_OUTRO_DEB.AsCurrency;
edTotValOutroCred.Value := qryResumoBairroVAL_OUTRO_cred.AsCurrency;
end;
function TfrmCalcTarifaBairro.ValItemCalc(sCod, sDC: string): Currency;
Var
crTemp: Currency;
begin
crTemp := 0;
cdsCalcFatIndividual.DisableControls;
cdsCalcFatIndividual.First;
while not cdsCalcFatIndividual.eof do
begin
if (cdsCalcFatIndividualR_COD_ITEM.Value = sCod) and
(cdsCalcFatIndividualR_TIPO.Value = sDC) then
crTemp := crTemp + cdsCalcFatIndividualR_VALOR.AsCurrency;
cdsCalcFatIndividual.Next;
end;
cdsCalcFatIndividual.EnableControls;
Result := crTemp;
end;
end.
|
unit ProcessListUnit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, ImgList, ActnList, Menus, ToolWin, StdCtrls;
type
TFormProcessList = class(TForm)
ImageListSort: TImageList;
ImageListTools: TImageList;
ActionListTools: TActionList;
ActionCopyFileName: TAction;
PopupMenuTools: TPopupMenu;
ToolBarSelect: TToolBar;
ToolButtonCopyFileName: TToolButton;
GroupBoxProcessList: TGroupBox;
ListViewProcess: TListView;
ImageListProcess: TImageList;
procedure FormCreate(Sender: TObject);
procedure ListViewProcessDblClick(Sender: TObject);
procedure ListViewProcessColumnClick(Sender: TObject;
Column: TListColumn);
procedure ListViewProcessCompare(Sender: TObject; Item1,
Item2: TListItem; Data: Integer; var Compare: Integer);
procedure ActionCopyFileNameExecute(Sender: TObject);
procedure ActionListToolsUpdate(Action: TBasicAction;
var Handled: Boolean);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
procedure GetCurrentProcessList;
function GetSelected: THandle;
public
{ Public declarations }
property Selected: THandle read GetSelected;
end;
//var//
// FormProcessList: TFormProcessList;//
implementation
{$R *.dfm}
uses TlHelp32, PsAPI, Clipbrd, IniFiles, ShellAPI, CommCtrl, ControlFunctions51,
StringFunctions51;
procedure TFormProcessList.GetCurrentProcessList;
var
vSnapshot: THandle;
vProcessEntry32: TProcessEntry32;
vProcess: THandle;
vBuffer: array[0..MAX_PATH] of Char;
L: Integer;
vHandle: THandle;
begin
vSnapshot := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
vProcessEntry32.dwSize := SizeOf(TProcessEntry32);
Process32First(vSnapshot, vProcessEntry32);
repeat
if vProcessEntry32.th32ProcessID <> 0 then
with ListViewProcess.Items.Add do
begin
vProcess := OpenProcess(PROCESS_QUERY_INFORMATION or PROCESS_VM_READ,
False, vProcessEntry32.th32ProcessID);
try
L := GetModuleFileNameEx(vProcess, 0, vBuffer, SizeOf(vBuffer));
Data := Pointer(vProcessEntry32.th32ProcessID);
Caption := vProcessEntry32.szExeFile;
SubItems.Add(Format('%0:d($%0:x)', [vProcessEntry32.th32ProcessID]));
SubItems.Add(Format('%0:d($%0:x)', [vProcessEntry32.th32ParentProcessID]));
vHandle := ExtractIcon(HInstance, vBuffer, 0);
if vHandle <> 0 then
begin
ImageList_AddIcon(
ImageListProcess.Handle,
vHandle
);
DestroyIcon(vHandle);
ImageIndex := ImageListProcess.Count - 1;
end else ImageIndex := 0;
if L <> 0 then
SubItems.Add(vBuffer)
else SubItems.Add(vProcessEntry32.szExeFile);
finally
CloseHandle(vProcess);
end;
end;
until not Process32Next(vSnapshot, vProcessEntry32);
CloseHandle(vSnapshot);
end;
procedure TFormProcessList.FormCreate(Sender: TObject);
begin
GetCurrentProcessList;
ListViewHeaderImages(ListViewProcess, ImageListSort);
with TIniFile.Create(ChangeFileExt(ParamStr(0), '.ini')) do try
Font.Name := ReadString(Self.ClassName, 'Font.Name', Font.Name);
Font.Size := ReadInteger(Self.ClassName, 'Font.Size', Font.Size);
try
Font.Color := StringToColor(ReadString(Self.ClassName, 'Font.Color',
ColorToString(Font.Color)));
except
end;
Left := ReadInteger(Self.ClassName, 'Left', Left);
Top := ReadInteger(Self.ClassName, 'Top', Top);
Height := ReadInteger(Self.ClassName, 'Height', Height);
Width := ReadInteger(Self.ClassName, 'Width', Width);
finally
Free;
end;
end;
procedure TFormProcessList.ListViewProcessDblClick(Sender: TObject);
begin
ModalResult := mrOK;
end;
function TFormProcessList.GetSelected: THandle;
begin
Result := 0;
if not Assigned(ListViewProcess.Selected) then Exit;
Result := Integer(ListViewProcess.Selected.Data);
end;
procedure TFormProcessList.ListViewProcessColumnClick(Sender: TObject;
Column: TListColumn);
var
I: Integer;
begin
if Abs(TListView(Sender).Tag) = Column.Index + 1 then
TListView(Sender).Tag := -TListView(Sender).Tag
else TListView(Sender).Tag := Column.Index + 1;
TListView(Sender).AlphaSort;
for I := 0 to TListView(Sender).Columns.Count - 1 do
ListColumnImageIndex(TListView(Sender).Columns[I], -1);
ListColumnImageIndex(Column, Ord(TListView(Sender).Tag > 0));
end;
procedure TFormProcessList.ListViewProcessCompare(Sender: TObject; Item1,
Item2: TListItem; Data: Integer; var Compare: Integer);
var
I: Integer;
A, B: string;
vDataA, vDataB: Extended;
begin
I := TListView(Sender).Tag;
if I = 0 then Exit;
if Abs(I) = 1 then begin
A := Item1.Caption;
B := Item2.Caption;
end else begin
if Abs(I) - 2 < Item1.SubItems.Count then
A := Item1.SubItems[Abs(I) - 2]
else A := '';
if Abs(I) - 2 < Item2.SubItems.Count then
B := Item2.SubItems[Abs(I) - 2]
else B := '';
end;
if (Pos('(', A) > 0) and (Pos('(', B) > 0) then
begin
A := StrLeft(A, '(');
B := StrLeft(B, '(');
end;
if TryStrToFloat(A, vDataA) and TryStrToFloat(B, vDataB) then
Compare := Trunc(I * vDataA - I * vDataB)
else Compare := CompareText(A, B) * I;
end;
procedure TFormProcessList.ActionCopyFileNameExecute(Sender: TObject);
begin
if not Assigned(ListViewProcess.Selected) then Exit;
Clipboard.AsText := ListViewProcess.Selected.SubItems[1]
end;
procedure TFormProcessList.ActionListToolsUpdate(Action: TBasicAction;
var Handled: Boolean);
begin
ActionCopyFileName.Enabled := Assigned(ListViewProcess.Selected);
end;
procedure TFormProcessList.FormDestroy(Sender: TObject);
begin
with TIniFile.Create(ChangeFileExt(ParamStr(0), '.ini')) do try
WriteInteger(Self.ClassName, 'Left', Left);
WriteInteger(Self.ClassName, 'Top', Top);
WriteInteger(Self.ClassName, 'Height', Height);
WriteInteger(Self.ClassName, 'Width', Width);
finally
Free;
end;
end;
end.
|
unit FtpDataModule;
interface
uses
SysUtils, Classes, IdBaseComponent, IdComponent, IdTCPConnection,
IdTCPClient, IdFTP;
type
TFtpData = class(TDataModule)
id_FTP: TIdFTP;
procedure DataModuleCreate(Sender: TObject);
procedure id_FTPStatus(ASender: TObject; const AStatus: TIdStatus;
const AStatusText: String);
procedure id_FTPWork(Sender: TObject; AWorkMode: TWorkMode;
const AWorkCount: Integer);
private
fWorkCountMax: Integer;
fLocalStartFolder: string;
fRemoteStartFolder: string;
{ Private declarations }
public
procedure Initialize(const iConfigFile:string);
procedure Sync(const iRemoteFolder,iLocalFolder:string);
end;
var
FtpData: TFtpData;
implementation
uses
Forms, IniFiles,
eStrings, IdFTPList;
{$R *.dfm}
procedure TFtpData.DataModuleCreate(Sender: TObject);
begin
Initialize(ChangeFileExt(Application.ExeName,'.cfg'));
id_FTP.Connect(true);
try
id_FTP.ChangeDir(fRemoteStartFolder);
writeln('Changed to folder '+fRemoteStartFolder);
Sync(fRemoteStartFolder,fLocalStartFolder);
finally
id_FTP.Disconnect();
end;
end;
procedure TFtpData.Initialize(const iConfigFile: string);
begin
with TMemIniFile.Create(iConfigFile) do try
writeln('Loading config from '+iConfigFile);
id_FTP.Host := ReadString('FTP','Server','');
id_FTP.Port := StrToIntDef(ReadString('FTP','Server','21'),21);
id_FTP.Username := ReadString('FTP','Login','anonymous');
id_FTP.Password := ReadString('FTP','Password','email@email.com');
id_FTP.Passive := ReadString('FTP','Passive','1') = '1';
fRemoteStartFolder := MakePathUnix(ReadString('FTP','Folder',''));
fLocalStartFolder := MakePath(ReadString('Local','Folder',''));
ForceDirectories(fLocalStartFolder);
finally
Free();
end;
end;
procedure TFtpData.id_FTPStatus(ASender: TObject; const AStatus: TIdStatus;
const AStatusText: String);
begin
//writeln('Status: '+AStatusText);
end;
procedure TFtpData.Sync(const iRemoteFolder, iLocalFolder: string);
var i:integer;
lFileSize: int64;
lName: string;
lListing:TIdFTPListItems;
f:file;
begin
id_FTP.List(nil);
lListing := TIdFTPListItems.Create;
try
lListing.Assign(id_FTP.DirectoryListing);
for i := 0 to lListing.Count-1 do begin
lName := lListing[i].FileName;
case lListing[i].ItemType of
ditDirectory:begin
if not DirectoryExists(iLocalFolder+lName) then begin
CreateDir(iLocalFolder+lName);
writeln('folder '+iLocalFolder+lName+ ' (created)');
end
else begin
writeln('folder '+iLocalFolder+lName+ ' (exists)');
end;
id_FTP.ChangeDir(iRemoteFolder+lName);
try
Sync(MakePathUnix(iRemoteFolder+lName),MakePath(iLocalFolder+lName));
finally
id_FTP.ChangeDir(iRemoteFolder);
end;
end;
ditFile:begin
if not FileExists(iLocalFolder+lName) then begin
//CreateDir(iLocalFolder+lName);
writeln('file '+iLocalFolder+lName+ ' (missing)');
fWorkCountMax := lListing[i].Size;
try
fWorkCountMax := lListing[i].Size;
id_FTP.Get(iRemoteFolder+lName,iLocalFolder+lName,true);
except
on E:Exception do writeln('Failed ('+E.ClassName+': '+E.Message+')');
end;
end
else begin
AssignFile(f,iLocalFolder+lName);
Reset(f,1);
try
lFileSize := FileSize(f);
finally
CloseFile(f);
end;
if (lFileSize < lListing[i].Size) then begin
writeln(Format('file '+iLocalFolder+lName+ ' (partial %s of %s)',[SizeString(lFileSize),SizeString(lListing[i].Size)]));
try
DeleteFile(iLocalFolder+lName);
fWorkCountMax := lListing[i].Size;
id_FTP.Get(iRemoteFolder+lName,iLocalFolder+lName,true);
except
on E:Exception do writeln('Failed ('+E.ClassName+': '+E.Message+')');
end;
end
else begin
writeln('file '+iLocalFolder+lName+ ' (exists)');
end;
end;
end;
end;
end; // for
finally
FreeAndNil(lListing);
end;
end;
function PercentageBar(iProgress,iMax:int64):string;
var lBars,lPercentage:int64;
begin
lBars := 50;
lPercentage := iProgress*lBars div iMax;
result := WordStrFillSpace(iProgress*100 div iMax,3)+'% |'+FillStr('','#',lPercentage)+FillStr('','-',lBars-lPercentage)+'|'
end;
procedure TFtpData.id_FTPWork(Sender: TObject; AWorkMode: TWorkMode;
const AWorkCount: Integer);
begin
write(PercentageBar(AWorkCount,fWorkCountMax)+' Total: '+SizeString(fWorkCountMax)+' Received: '+SizeString(AWorkCount)+#13);
end;
end.
|
unit ORStaticText;
(*************************************************************************************************
OR Static Text control - Static Text control that adds multi-line capability;
mainly used to replace label controls that speech engines can't read.
**************************************************************************************************)
interface
uses
Windows, Messages, Graphics, Controls, ExtCtrls, StdCtrls, Classes, SysUtils;
type
{ TORStaticText component class }
TORStaticText = class(TPanel) // Does not accept controls
private
fLines: TStringList; // property holder for Lines
fDisplayed: TStringList;
fTransparent: boolean; // property holder for Transparent
fVerticalSpace: integer; // property holder for VerticalSpace
Resizing: boolean; // flag stating the control is resizing
Painting: boolean;
FirstTime: boolean; // flag stating the control needs initialization
fWordWrap: boolean;
fMaxWidth: integer;
fWrapByChar: boolean;
fPauseResize: boolean;
ResizeRequested: boolean;
LargestTextWidth: integer;
LargestPixelWidth: integer;
LargestPixelHeight: integer;
procedure TextToCanvas(y: integer; s: string);
procedure SetMaxWidth(const Value: integer);
procedure SetWrapByChar(const Value: boolean);
protected
procedure DoEnter; override; // fires when the control is entered; used for displaying the focus status
procedure DoExit; override; // fires when the control is exited; used for displaying the focus status
procedure SetName(const Value: TComponentName); override; // Sets the text in the control when the name is changed
function GetText: string; // read accessor for Text
procedure SetLines(const Value: TStringList); // write accessor for Lines
procedure SetText(const Value: string); // write accessor for Text
procedure SetVerticalSpace(const Value: integer); // write accessor for VerticalSpace
procedure SetTransparent(const Value: boolean); // write accessor for Transparent
procedure SetWordWrap(const Value: boolean);
procedure Paint; override; // draws the control on the canvas
procedure Resize; override;
public
property Caption;
property Displayed: TStringList read fDisplayed;
constructor Create(AOwner: TComponent); override; // constructor
destructor Destroy; override; // destructor
procedure PauseResize;
procedure ResumeResize;
published
property AutoSize;
property Text: string read GetText write SetText; // control text in a single line
property Lines: TStringList read fLines write SetLines; // user-formatted text; CRLF delimited
property Transparent: boolean read fTransparent write SetTransparent default True; // determines if the background is transparent
property VerticalSpace: integer read fVerticalSpace write SetVerticalSpace default 1; // number of vertical pixel spaces between items when using multi-line
property WordWrap: boolean read fWordWrap write SetWordWrap default True;
property MaxWidth: integer read fMaxWidth write SetMaxWidth default 0;
property WrapByChar: boolean read fWrapByChar write SetWrapByChar default False;
end;
implementation
uses
StrUtils, Math, Forms, System.UITypes, ORFn;
{ TORStaticText }
{==================================================================================================}
{ constructor Create - Create an instance of TORStaticText. }
{--------------------------------------------------------------------------------------------------}
{ AOwner: component responsible for creation/destruction of the component }
{==================================================================================================}
constructor TORStaticText.Create(AOwner: TComponent);
begin
inherited;
// initialize objects
fLines := TStringList.Create;
fDisplayed := TStringList.Create;
// set internal property values
fTransparent := True;
fVerticalSpace := 1;
AutoSize := False;
fWordWrap := True;
Caption := '';
fWrapByChar := False;
fPauseResize := False;
ResizeRequested := False;
// set flags
Resizing := False;
Painting := False;
FirstTime := True;
// set inherited property values
BevelInner := bvNone;
BevelOuter := bvNone;
Alignment := taLeftJustify;
Height := 1;
Width := 1;
ControlStyle := ControlStyle - [csAcceptsControls]; // should react like an edit, not like a panel
end;
{==================================================================================================}
{ destructor Destroy - destroy the instance of TORStatic }
{--------------------------------------------------------------------------------------------------}
{==================================================================================================}
destructor TORStaticText.Destroy;
begin
// free up objects
if assigned(fLines) then fLines.Free;
if assigned(fDisplayed) then fDisplayed.Free;
inherited;
end;
{==================================================================================================}
{ procedure DoEnter - override of TWinControl DoEnter: fired when a control is entered }
{ Needed to repaint the control to show focus }
{--------------------------------------------------------------------------------------------------}
{==================================================================================================}
procedure TORStaticText.DoEnter;
begin
Paint;
inherited;
end;
{==================================================================================================}
{ procedure DoExit - override of TWinControl DoExit: fired when a control is exited }
{ Needed to repaint the control to show loss of focus }
{--------------------------------------------------------------------------------------------------}
{==================================================================================================}
procedure TORStaticText.DoExit;
begin
Paint;
inherited;
end;
{==================================================================================================}
{ function GetText - write accessor for Text property }
{--------------------------------------------------------------------------------------------------}
{==================================================================================================}
function TORStaticText.GetText: string;
begin
Result := fLines.Text;
end;
{==================================================================================================}
{ procedure TextToCanvas - Draws the text on the canvas based on the current control properties }
{--------------------------------------------------------------------------------------------------}
{ y: y coordinate to start drawing the string }
{ s: string to be drawn on canvas }
{==================================================================================================}
procedure TORStaticText.TextToCanvas(y: integer; s: string);
begin
if assigned(Canvas) then begin
case Alignment of // x position based on alignment property of control
taLeftJustify: Canvas.TextOut(Margins.Left, y, s);
taRightJustify: Canvas.TextOut((Width - Margins.Right - Canvas.TextWidth(s)), y, s);
taCenter: Canvas.TextOut(((Width div 2) - Margins.Right - (Canvas.TextWidth(s) div 2)), y, s);
end;
end;
end;
{==================================================================================================}
{ procedure Paint - override of TWinControl Paint }
{ Draws the control on the canvas }
{--------------------------------------------------------------------------------------------------}
{==================================================================================================}
procedure TORStaticText.Paint;
var
r: TRect; // rectangle used to draw the border
i: integer; // loops
py: integer; // position y
OldPenColor, // saves the former pen color while drawing the border
OldBrushColor: TColor; // saves the former brush color while drawing the border
OldPenStyle: TPenStyle; // saves the former pen style while drawing the border
OldBrushStyle: TBrushStyle; // saves the former brush style while drawing the border
begin
if assigned(Canvas) then begin
if not Painting then begin
Painting := True;
try
{------------------}
{ Draw the outline }
{------------------}
OldBrushColor := Canvas.Brush.Color;
OldBrushStyle := Canvas.Brush.Style;
OldPenColor := Canvas.Pen.Color; // save old settings
OldPenStyle := Canvas.Pen.Style;
try
Canvas.Font.Assign(Font); // make sure using the correct font to draw with
Canvas.Pen.Width := 1;
if Transparent then begin
Canvas.Brush.Style := bsClear;
Canvas.Brush.Color := clNone;
end else begin
Canvas.Brush.Style := bsSolid;
Canvas.Brush.Color := Color;
end;
Canvas.Brush.Color := clNone;
Canvas.Brush.Style := bsClear;
if Focused then begin // focused control uses dotted line in font color
Canvas.Pen.Style := psDot;
Canvas.Pen.Color := Font.Color;
end else begin // normal drawing just draws a rectangle that overwrites previous rectangles
Canvas.Pen.Style := psSolid;
Canvas.Pen.Color := Color;
end;
r := Rect(0, 0, Width, Height);
if Transparent then begin
Canvas.TextFlags := 0;
Canvas.FrameRect(r);
end else begin
Canvas.TextFlags := ETO_OPAQUE;
Canvas.Rectangle(r); // draw the rectangle
end;
{---------------}
{ Draw the text }
{---------------}
// write out the strings after determining if they are wrapped
py := Margins.Top;
for i := 0 to (fDisplayed.Count - 1) do begin // loop through lines, determine if they need wrapped
//ExtTextOut(Canvas.Handle, Margins.Left, py, TextFlags, nil, fDisplayed[i], Length(fDisplayed[i]), nil);
TextToCanvas(py, fDisplayed[i]);
inc(py, LargestPixelHeight + VerticalSpace);
end;
finally
Canvas.Brush.Color := OldBrushColor;
Canvas.Brush.Style := OldBrushStyle;
Canvas.Pen.Color := OldPenColor;
Canvas.Pen.Style := OldPenStyle;
end;
finally
Painting := False;
end;
end;
end;
end;
procedure TORStaticText.PauseResize;
begin
fPauseResize := True;
end;
{==================================================================================================}
{ procedure Resize - override of TWinControl Resize }
{ Resizes the controls based on current property settings }
{--------------------------------------------------------------------------------------------------}
{==================================================================================================}
procedure TORStaticText.Resize;
var
i: integer;
TextWidth: integer;
TextHeight: integer;
sl: TStringList;
begin
inherited;
if fPauseResize then begin
ResizeRequested := True;
end else begin
if not Resizing then begin
Resizing := True;
try
LargestTextWidth := 0;
LargestPixelWidth := 0;
LargestPixelHeight := 0;
if fWordWrap and (fMaxWidth > 0) then begin // word handling is Word Wrap
for i := 0 to (fLines.Count - 1) do begin
if Trim(fLines[i]) <> '' then begin
TextWidth := Canvas.TextWidth(fLines[i]);
LargestTextWidth := Max(LargestTextWidth, TextWidth);
LargestPixelWidth := Max(LargestPixelWidth, (TextWidth div Length(fLines[i]) + 1));
TextHeight := Canvas.TextHeight(fLines[i]);
LargestPixelHeight := Max(LargestPixelHeight, TextHeight + 1);
end;
end;
if (fMaxWidth > 0) then begin
LargestTextWidth := Min(LargestTextWidth, fMaxWidth);
end;
for i := 0 to (fLines.Count - 1) do begin
if fWrapByChar then
sl := WrapTextByChar(fLines[i], fMaxWidth, Canvas, PreSeparatorChars, PostSeparatorChars)
else
sl := WrapTextByPixels(fLines[i], LargestTextWidth, Canvas, PreSeparatorChars, PostSeparatorChars);
fDisplayed.AddStrings(sl);
end;
end else begin // no word wrapping
fDisplayed.Text := fLines.Text;
end;
if AutoSize then begin
Width := LargestTextWidth * LargestPixelWidth + Margins.Left + Margins.Right;
Height := fDisplayed.Count * LargestPixelHeight + Margins.Top + Margins.Bottom;
end;
Invalidate;
finally
Resizing := False;
end;
end;
end;
end;
procedure TORStaticText.ResumeResize;
begin
fPauseResize := False;
if ResizeRequested then Resize;
end;
{==================================================================================================}
{ procedure SetLines - write accessor for Lines property }
{--------------------------------------------------------------------------------------------------}
{ Value: Lines' new value }
{==================================================================================================}
procedure TORStaticText.SetLines(const Value: TStringList);
begin
if (Value.Text <> fLines.Text) then begin
fLines.Text := Value.Text;
Resize;
end;
end;
{==================================================================================================}
{ procedure SetMultiLine - write accessor for MultiLine property }
{--------------------------------------------------------------------------------------------------}
{ Value: MultiLine's new value }
{==================================================================================================}
procedure TORStaticText.SetMaxWidth(const Value: integer);
begin
if (fMaxWidth <> Value) then begin
fMaxWidth := Value;
Resize;
end;
end;
{==================================================================================================}
{ procedure SetName - overwrite write accessor for Name property }
{--------------------------------------------------------------------------------------------------}
{ Value: New name for the component }
{==================================================================================================}
procedure TORStaticText.SetName(const Value: TComponentName);
begin
if (Name <> Value) then begin
inherited SetName(Value);
fLines.Text := Name;
end;
end;
{==================================================================================================}
{ procedure SetTransparent - write accessor for Transparent property }
{--------------------------------------------------------------------------------------------------}
{ Value: Transparent's new value }
{==================================================================================================}
procedure TORStaticText.SetText(const Value: string);
begin
if (Value <> fLines.Text) then begin
fLines.Text := Value;
Resize;
end;
end;
procedure TORStaticText.SetTransparent(const Value: boolean);
begin
if (fTransparent <> Value) then begin
fTransparent := Value;
if Value then
ControlStyle := ControlStyle - [csOpaque]
else
ControlStyle := ControlStyle + [csOpaque];
end;
Invalidate;
end;
{==================================================================================================}
{ procedure SetVerticalSpace - write accessor for VerticalSpace property }
{--------------------------------------------------------------------------------------------------}
{ Value: VerticalSpace's new value }
{==================================================================================================}
procedure TORStaticText.SetVerticalSpace(const Value: integer);
begin
if (fVerticalSpace <> Value) then begin
fVerticalSpace := Value;
Invalidate;
end;
end;
procedure TORStaticText.SetWordWrap(const Value: boolean);
begin
if (fWordWrap <> Value) then begin
fWordWrap := Value;
end;
Resize;
end;
procedure TORStaticText.SetWrapByChar(const Value: boolean);
begin
fWrapByChar := Value;
Resize;
end;
end.
|
unit VypoctyBody;
interface
uses Typy, ComCtrls, SysUtils;
function VzdialenostDvochBodov( A, B : TBod ) : Real;
function TaziskoBodov( Zoznam : TListItems ) : TBod;
implementation
function VzdialenostDvochBodov( A, B : TBod ) : Real;
begin
VzdialenostDvochBodov := Sqrt( Sqr(A.X - B.X) + Sqr(A.Y - B.Y) );
end;
function TaziskoBodov( Zoznam : TListItems ) : TBod;
var Vystup : TBod;
I : word;
begin
Vystup.X := 0;
Vystup.Y := 0;
with Zoznam do
begin
for I := 1 to Count do
begin
Vystup.X := Vystup.X + StrToFloat( Item[I-1].SubItems[0] );
Vystup.Y := Vystup.Y + StrToFloat( Item[I-1].SubItems[1] );
end;
Vystup.X := Vystup.X / Count;
Vystup.Y := Vystup.Y / Count;
end;
Result := Vystup;
end;
end.
|
// Ported CrystalDiskInfo (The MIT License, http://crystalmark.info)
unit SMARTSupport.JMicron61x;
interface
uses
BufferInterpreter, Device.SMART.List, SMARTSupport, Support;
type
TJMicron61xSMARTSupport = class(TSMARTSupport)
private
const
EntryID = $AA;
public
function IsThisStorageMine(
const IdentifyDevice: TIdentifyDeviceResult;
const SMARTList: TSMARTValueList): Boolean; override;
function GetTypeName: String; override;
function IsSSD: Boolean; override;
function IsInsufficientSMART: Boolean; override;
function GetSMARTInterpreted(
const SMARTList: TSMARTValueList): TSMARTInterpreted; override;
function IsWriteValueSupported(
const SMARTList: TSMARTValueList): Boolean; override;
protected
function ErrorCheckedGetLife(const SMARTList: TSMARTValueList): Integer;
override;
function InnerIsErrorAvailable(const SMARTList: TSMARTValueList):
Boolean; override;
function InnerIsCautionAvailable(const SMARTList: TSMARTValueList):
Boolean; override;
function InnerIsError(const SMARTList: TSMARTValueList): TSMARTErrorResult;
override;
function InnerIsCaution(const SMARTList: TSMARTValueList):
TSMARTErrorResult; override;
end;
implementation
{ TJMicron61xSMARTSupport }
function TJMicron61xSMARTSupport.GetTypeName: String;
begin
result := 'SmartJMicron61x';
end;
function TJMicron61xSMARTSupport.IsInsufficientSMART: Boolean;
begin
result := false;
end;
function TJMicron61xSMARTSupport.IsSSD: Boolean;
begin
result := true;
end;
function TJMicron61xSMARTSupport.IsThisStorageMine(
const IdentifyDevice: TIdentifyDeviceResult;
const SMARTList: TSMARTValueList): Boolean;
begin
result :=
(SMARTList.Count >= 13) and
(SMARTList[0].Id = $01) and
(SMARTList[1].Id = $02) and
(SMARTList[2].Id = $03) and
(SMARTList[3].Id = $05) and
(SMARTList[4].Id = $07) and
(SMARTList[5].Id = $08) and
(SMARTList[6].Id = $09) and
(SMARTList[7].Id = $0A) and
(SMARTList[8].Id = $0C) and
(SMARTList[9].Id = $A8) and
(SMARTList[10].Id = $AF) and
(SMARTList[11].Id = $C0) and
(SMARTList[12].Id = $C2);
end;
function TJMicron61xSMARTSupport.ErrorCheckedGetLife(
const SMARTList: TSMARTValueList): Integer;
begin
result := SMARTList[SMARTList.GetIndexByID($AA)].Current;
end;
function TJMicron61xSMARTSupport.InnerIsErrorAvailable(
const SMARTList: TSMARTValueList): Boolean;
begin
result := true;
end;
function TJMicron61xSMARTSupport.InnerIsCautionAvailable(
const SMARTList: TSMARTValueList): Boolean;
begin
result := IsEntryAvailable(EntryID, SMARTList);
end;
function TJMicron61xSMARTSupport.InnerIsError(
const SMARTList: TSMARTValueList): TSMARTErrorResult;
begin
result.Override := false;
result.Status :=
InnerCommonIsError(EntryID, SMARTList).Status;
end;
function TJMicron61xSMARTSupport.InnerIsCaution(
const SMARTList: TSMARTValueList): TSMARTErrorResult;
begin
result := InnerCommonIsCaution(EntryID, SMARTList, CommonLifeThreshold);
end;
function TJMicron61xSMARTSupport.IsWriteValueSupported(
const SMARTList: TSMARTValueList): Boolean;
begin
result := false;
end;
function TJMicron61xSMARTSupport.GetSMARTInterpreted(
const SMARTList: TSMARTValueList): TSMARTInterpreted;
const
ReadError = true;
EraseError = false;
UsedHourID = $09;
ThisErrorType = ReadError;
ErrorID = $01;
ReplacedSectorsID = $05;
begin
FillChar(result, SizeOf(result), 0);
result.UsedHour := SMARTList.ExceptionFreeGetRAWByID(UsedHourID);
result.ReadEraseError.TrueReadErrorFalseEraseError := ReadError;
result.ReadEraseError.Value := SMARTList.ExceptionFreeGetRAWByID(ErrorID);
result.ReplacedSectors :=
SMARTList.ExceptionFreeGetRAWByID(ReplacedSectorsID);
end;
end.
|
{*******************************************************}
{ }
{ Delphi DataSnap Framework }
{ Copyright(c) 2014-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit Datasnap.DSConnectionMetaDataProvider;
interface
uses
Datasnap.DSCommonProxy, Datasnap.DSMetaData, Data.SqlExpr, System.Classes;
type
TDSConnectionMetaDataProvider = class(TDSCustomMetaDataProvider)
private
[Weak]FConnection: TSQLConnection;
procedure SetConnection(const Value: TSQLConnection);
protected
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
public
function HasProvider: Boolean; override;
function GetProvider: IDSProxyMetaDataLoader; override;
published
property SQLConnection: TSQLConnection read FConnection write SetConnection;
end;
implementation
uses
Data.DBXCommon;
{ TDSConnectionMetaDataProvider }
function TDSConnectionMetaDataProvider.GetProvider: IDSProxyMetaDataLoader;
var
LOpen: Boolean;
begin
if HasProvider then
begin
Result := TDSProxyMetaDataLoader.Create(
function: TDBXConnection
begin
LOpen := FConnection.DBXConnection <> nil;
FConnection.Open;
Result := FConnection.DBXConnection;
end,
procedure(C: TDBXConnection)
begin
if LOpen then
FConnection.Close;
end);
end
else
Result := nil;
end;
function TDSConnectionMetaDataProvider.HasProvider: Boolean;
begin
Result := FConnection <> nil;
end;
procedure TDSConnectionMetaDataProvider.Notification(
AComponent: TComponent; Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if (Operation = opRemove) and (AComponent = FConnection) then
FConnection := nil;
end;
procedure TDSConnectionMetaDataProvider.SetConnection(
const Value: TSQLConnection);
begin
if Value <> FConnection then
begin
if Assigned(FConnection) then
FConnection.RemoveFreeNotification(Self);
FConnection := Value;
if Value <> nil then
begin
Value.FreeNotification(Self);
end;
end;
end;
end.
|
{*******************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ }
{ Copyright (c) 2000, 2001 Borland Software Corp. }
{ }
{*******************************************************}
unit MidComp;
interface
{$IFDEF MSWINDOWS}
{ MSXML.H defines another IXMLDocument and references the type...
The compiler must see this before it sees the IXMLDocument
introduced in this unit - otherwise, references will cause
ambiguity errors }
(*$HPPEMIT '#include <msxml.h>' *)
{$ENDIF}
{$IFDEF LINUX}
{ MidComp.hpp and XMLIntf.hpp both define IXMLDocument and
XMLDoc.hpp uses that type.
The compiler must see XMLDoc.hpp before it sees the IXMLDocument
introduced in this unit - otherwise, references will cause
ambiguity errors }
(*$HPPEMIT '#include <XMLDoc.hpp>' *)
{$ENDIF}
uses Classes, HTTPApp, HTTPProd, Masks, WebComp;
type
IScriptManager = interface;
IScriptProducer = interface
['{555DA472-F254-11D2-AA55-00A024C11562}']
function GetScriptManager: IScriptManager;
property ScriptManager: IScriptManager read GetScriptManager;
end;
IXMLRowSet = interface;
IXMLDocuments = interface;
IXMLDocument = interface;
IXMLRowSets = interface;
IIncludeFiles = interface;
IFunctions = interface;
IVars = interface;
IScriptBlocks = interface;
IHTMLBlocks = interface;
IAddScriptElements = interface;
IScriptManager = interface
['{94B8B14E-E6D6-11D2-AFA6-00C04FB16EC3}']
function GetXMLDocuments: IXMLDocuments;
function GetIncludeFiles: IIncludeFiles;
function GetFunctions: IFunctions;
function GetWarnings: TStrings;
function GetScriptBlocks: IScriptBlocks;
function GetVars: IVars;
function GetHTMLBlocks: IHTMLBlocks;
function GetOptions: TWebContentOptions;
function GetAddElementsIntf: IAddScriptElements;
procedure AddError(const Error: string);
property XMLDocuments: IXMLDocuments read GetXMLDocuments;
property IncludeFiles: IIncludeFiles read GetIncludeFiles;
property Warnings: TStrings read GetWarnings;
property Functions: IFunctions read GetFunctions;
property Vars: IVars read GetVars;
property ScriptBlocks: IScriptBlocks read GetScriptBlocks;
property HTMLBlocks: IHTMLBlocks read GetHTMLBlocks;
property Options: TWebContentOptions read GetOptions;
property AddElementsIntf: IAddScriptElements read GetAddElementsIntf;
end;
IIncludeFile = interface;
IIncludeFiles = interface
['{F735BC77-E7A4-11D2-AFA7-00C04FB16EC3}']
function GetCount: Integer;
function GetItem(I: Integer): IIncludeFile;
property Count: Integer read GetCount;
property Items[I: Integer]: IIncludeFile read GetItem;
end;
IIncludeFile = interface
['{F735BC78-E7A4-11D2-AFA7-00C04FB16EC3}']
function GetFileName: string;
property FileName: string read GetFileName;
end;
IFunction = interface;
IFunctions = interface
['{3AA43171-EC43-11D2-AFAE-00C04FB16EC3}']
function GetCount: Integer;
function GetItem(I: Integer): IFunction;
property Count: Integer read GetCount;
property Items[I: Integer]: IFunction read GetItem;
end;
IFunction = interface
['{3AA43172-EC43-11D2-AFAE-00C04FB16EC3}']
function GetFunctionName: string;
function GetBody: string;
property FunctionName: string read GetFunctionName;
property Body: string read GetBody;
end;
IVar = interface;
IVars = interface
['{8AFBBDE2-2A11-11D3-AAAB-00A024C11562}']
function GetCount: Integer;
function GetItem(I: Integer): IVar;
property Count: Integer read GetCount;
property Items[I: Integer]: IVar read GetItem;
end;
IVar = interface
['{8AFBBDE3-2A11-11D3-AAAB-00A024C11562}']
function GetVarName: string;
function GetScript: string;
property VarName: string read GetVarName;
property Script: string read GetScript;
end;
IHTMLBlock = interface;
IHTMLBlocks = interface
['{8AFBBDE4-2A11-11D3-AAAB-00A024C11562}']
function GetCount: Integer;
function GetItem(I: Integer): IHTMLBlock;
property Count: Integer read GetCount;
property Items[I: Integer]: IHTMLBlock read GetItem;
end;
IHTMLBlock = interface
['{8AFBBDE5-2A11-11D3-AAAB-00A024C11562}']
function GetBlockName: string;
function GetHTML: string;
property BlockName: string read GetBlockName;
property HTML: string read GetHTML;
end;
IScriptBlock = interface;
IScriptBlocks = interface
['{8AFBBDE6-2A11-11D3-AAAB-00A024C11562}']
function GetCount: Integer;
function GetItem(I: Integer): IScriptBlock;
property Count: Integer read GetCount;
property Items[I: Integer]: IScriptBlock read GetItem;
end;
IScriptBlock = interface
['{8AFBBDE7-2A11-11D3-AAAB-00A024C11562}']
function GetBlockName: string;
function GetScript: string;
property BlockName: string read GetBlockName;
property Script: string read GetScript;
end;
IXMLDocuments = interface
['{94B8B150-E6D6-11D2-AFA6-00C04FB16EC3}']
function GetCount: Integer;
function GetItem(I: Integer): IXMLDocument;
property Count: Integer read GetCount;
property Items[I: Integer]: IXMLDocument read GetItem;
end;
IXMLDocument = interface
['{94B8B151-E6D6-11D2-AFA6-00C04FB16EC3}']
function GetRowSets: IXMLRowSets;
function GetComponent: TComponent;
function GetDocumentVarName: string;
function GetXMLVarName: string;
property RowSets: IXMLRowSets read GetRowSets;
property Component: TComponent read GetComponent;
property DocumentVarName: string read GetDocumentVarName;
property XMLVarName: string read GetXMLVarName;
end;
IXMLRowSets = interface
['{94B8B152-E6D6-11D2-AFA6-00C04FB16EC3}']
function GetCount: Integer;
function GetItem(I: Integer): IXMLRowSet;
property Count: Integer read GetCount;
property Items[I: Integer]: IXMLRowSet read GetItem;
end;
IXMLRowSet = interface
['{94B8B14F-E6D6-11D2-AFA6-00C04FB16EC3}']
function GetPath: TStrings;
function GetRowSetVarName: string;
function GetMasterRowSetVarName: string;
function GetMasterDataSetFieldName: string;
property MasterRowSetVarName: string read GetMasterRowSetVarName;
property MasterDataSetFieldName: string read GetMasterDataSetFieldName;
property RowSetVarName: string read GetRowSetVarName;
end;
TAddScriptElementsEvent = procedure(Data: Pointer; AddScriptElements: IAddScriptElements) of object;
IAddScriptElements = interface
['{2FF3A331-E790-11D2-AFA7-00C04FB16EC3}']
function GetScriptManager: IScriptManager;
function AddIncludeFile(FileName: string): Boolean;
function AddRowSet(XMLProducer: TComponent; Path: TStrings): Boolean;
function AddScriptBlock(Name: string; Script: string): Boolean;
function AddHTMLBlock(Name: string; HTML: string): Boolean;
function AddVar(Name: string; Script: string): Boolean;
function AddFunction(Name: string; Body: string): Boolean;
procedure AddError(Text: string);
procedure AddPass(Event: TAddScriptElementsEvent; Data: Pointer);
procedure AddScriptComponents(List: TObject);
property ScriptManager: IScriptManager read GetScriptManager;
end;
IScriptComponent = interface
['{1B9B0962-D28E-11D2-AF8A-00C04FB16EC3}']
procedure AddElements(AddIntf: IAddScriptElements);
function GetSubComponents: TObject; // Object implementing IWebComponentContainer
property SubComponents: TObject read GetSubComponents;
end;
implementation
{$IFDEF MSWINDOWS}
uses Windows, Messages, SysUtils, WebConst ;
{$ENDIF}
{$IFDEF LINUX}
uses SysUtils, WebConst;
{$ENDIF}
end.
|
unit ILTranslator;
interface
uses
System.SysUtils, System.Classes, Generics.Defaults, Generics.Collections, System.Math, NPCompiler.Utils,
NPCompiler.DataTypes, IL.Types, IL.TypeInfo, VM.Core, VM.Invoke, VM.Types; // system
const
C_1M_ITEMS = 1024*1024;
cRttiUnitName = 'sys.rtti';
type
TNativeUIntArray = array of NativeUInt;
type
TInstructions = array[0..C_1M_ITEMS] of NativeUInt;
PInstructions = ^TInstructions;
PInstruction = ^NativeUInt;
TILArgs = class
end;
TILInstruction = record
public
Cond: TILCondition; // условие
Code: TILCode; // код
Offset: UInt32; // смещение в target коде
Line: Integer; // строка в исходном коде
Args: TILArgs; // аргументы
end;
PILInstr = ^TILInstruction;
TILInstructions = array of TILInstruction;
TILVarClass = (
VarMutable, // модифицируемая переменная
VarParam, // модифицируемый параметр
VarConst, // немодифицируемый параметр
VarResult // возвращаемый параметр
);
PILVariable = ^TILVariable;
TILVariable = record
public
Name: string; // название переменной
Flags: UInt8; // флаги
RTTI: TRTTIField;
AbsoluteTo: PILVariable;
AbsoluteOffset: Integer;
VarScope: TILARG_SCOPE;
VarClass: TILVarClass; // класс модификации переменной
TmpUsed: Boolean;
DefaultValue: Pointer; // указатель на значени по умолчанию
IsResult: Boolean; // это результат
IsParam: Boolean; // это параметр
end;
TILVariables = array of TILVariable;
PILVariables = ^TILVariables;
TParams = array of TRTTIParameter;
TILUnit = class;
TILArgument = class;
PILType = ^TIMGType;
TILProc = class
private
VarsTmp: array of PILVariable;// список временных переменных
function GetILCount: Integer; inline;
public
type
TILProcedures = array of TILProc;
var
Name: string; // название(для отладки)
Struct: PILType; // структруа (если метод)
ILUnit: TILUnit; // Модуль в котором обьявлена процедура
Flags: UInt8; // Флаги
Params: TParams; // Параметры
Vars: TILVariables; // Локальные переменные, включая параметры
ProcType: TProcType; // Тип процедуры (процедура/функция)
NestedProcs: TILProcedures; // Локальные процедуры
CodeSize: UInt32; // Размер машинного кода в байтах
IL: TILInstructions; // IL-инструкции (дебаг/коррекция смещений переходов)
InvokeAdapterID: Integer; // ID адаптера вызова импортируемой процедуры
ImportIndex: Integer; // индекс из таблицы импорта (-1 не является импортируемой)
ProcInfo: TOffset; // RTTI процедуры
// поля продублированные из RTTI
Offset: TOffset; // смещение начала кода процедуры в образе
StackSize: Integer; // Размер стека (память локальных переменных)
ImportLib: TOffset; // библиотека импорта (0 если нет)
ImportName: TOffset; // имя в библиотеке импорта (0 если нет)
CallConvention: TCallConvention;// натация вызова
VirtualIndex: Integer;
ExportIndex: Integer;
IsIntfMethod: Boolean;
SelfArg: TILArgument;
function IsImported: Boolean; inline;
function GetTMPVar(DataTypeID: TDataTypeID; IsReference: Boolean): PILVariable;
function GetStackSize: Integer;
public
destructor Destroy; override;
property ILCount: Integer read GetILCount;
end;
TILProcedures = TILProc.TILProcedures;
TIMGType = packed record
ID: TDataTypeID; // ID типа
Name: string; // название типа
Offset: TOffset; // смещение в секции RTTI
StrictRTTI: TOffset; // смещение в урезанной секции RTTI
Fields: TILVariables; // поля
Methods: TILProcedures; // методы
end;
TIMGTypes = array of TIMGType;
TExportUnits = array [0..65535] of TRTTIUnit;
PExportUnits = ^TExportUnits;
TUInt32DynArray = array of UInt32;
PUInt32DynArray = TUInt32DynArray;
TConstInfoRec = packed record
TypeInfo: TOffset;
Value: TOffset;
Size: Integer;
end;
PConstInfoRec =^TConstInfoRec;
TConstInfoArray = array of TConstInfoRec;
TILBreakPoint = record
SrcTextLine: Integer; // строка в исходном коде
VMTextLine: Integer; // строка в target-asm коде
Offset: TOffset; // смещение в target коде
end;
TILBreakPoints = array of TILBreaKPoint;
// модули
TILUnit = class
public
Name: string; // название модуля
Flags: Integer;
Index: Integer; // индекс в пакете
Consts: TConstInfoArray; // таблица смещений констант модуля
Procs: TILProcedures; // процедуры
Vars: TILVariables; // глобальные переменные
ExportProcsCount: Integer; // кол-во экспортируемых процедур
VMVars: PVMVariables; // глобальные переменные модуля
VMUnit: PRTTIUnit; // ссылка на RTTI описание в VM образе
Types: TIMGTypes; // типы обьявленные в модуле
BreakPoints: TILBreakPoints; // точки останова
InitProc: TILProc; // секция инициализации
FinalProc: TILProc;
destructor Destroy; override; // секция финализации
end;
// тип аргумента инструкции
TILArgumentType = (
atImmConst, // аргумент задан константой (непосредственной или табличной)
atLocal, // аргумент задан локальной переменной
atGlobal, // аргумент задан глобальной переменной
atField, // аргумент задан полем структуры
atReference // аргумент задан ссылкой (ссылка может быть только локальной)
);
TILMethod = record
Self: TILArgument;
Proc: TILProc;
end;
PILMethod = ^TILMethod;
// контекст трансляции
TILTContext = record
PUnit: TILUnit; // текущий модуль
Proc: TILProc; // текущая процедура
Cond: TILCondition; // условие текущей IL инструкции
Stream: TStream; // входной поток
ILCode: TILCode; // код IL инструкции
ILIndex: Integer; // индекс IL инструкции
ILCount: Integer;
Args: TILArgs; // аргументы IL инструкции
end;
TILUnits = array of TILUnit;
TCallType = (
CallStatic,
CallStaticExternal,
CallIndirect,
CallMethod,
CallMethodIndirect,
CallMethodVirtual,
CallMethodInterface,
CallMethodExternal
);
TVMArgType = (
VMARG_IMM,
VMARG_VAR
);
TVMCodeClass = (
vmStore,
vmClear,
vmIncRef,
vmDecRef
);
TILArgData = record
case Integer of
0: (I8: Int8);
1: (I16: Int16);
2: (I32: Int32);
3: (I64: Int64);
4: (NInt: NativeInt);
5: (U8: UInt8);
6: (U16: UInt16);
7: (U32: UInt32);
8: (U64: UInt64);
9: (NUInt: NativeUInt);
10: (PTR: Pointer);
11: (AsVariable: PILVariable);
12: (AsProcedure: TILProc);
13: (AsTypeInfo: PRTTIType);
14: (AsMethod: TILMethod);
end;
TILTranslator = class;
TVMCodeArg = class
protected
public
function GetDataCnt(MT: TILTranslator): Integer; virtual;
procedure WriteData(MT: TILTranslator; const Proc: TILProc; IP: PNativeUInt); virtual; abstract;
end;
TVMCodeArgGeneric<T> = class(TVMCodeArg)
private
FValue: T;
public
property Value: T read FValue;
constructor Create(const Value: T);
end;
TILArgument = class(TVMCodeArg)
private
FData: TILArgData;
public
ArgumentType: TILArgumentType;
ArgClass: TILARG_CLASS;
ArgScope: TILARG_SCOPE;
TypeInfo: TOffset;
Next: TILArgument;
property I8: Int8 read FData.I8 write FData.I8;
property I16: Int16 read FData.I16 write FData.I16;
property I32: Int32 read FData.I32 write FData.I32;
property I64: Int64 read FData.I64 write FData.I64;
property NInt: NativeInt read FData.NInt write FData.NInt;
property U8: UInt8 read FData.U8 write FData.U8;
property U16: UInt16 read FData.U16 write FData.U16;
property U32: UInt32 read FData.U32 write FData.U32;
property U64: UInt64 read FData.U64 write FData.U64;
property NUInt: NativeUInt read FData.NUInt write FData.NUInt;
property PTR: Pointer read FData.PTR write FData.PTR;
property AsVariable: PILVariable read FData.AsVariable write FData.AsVariable;
property AsProcedure: TILProc read FData.AsProcedure write FData.AsProcedure;
property AsTypeInfo: PRTTIType read FData.AsTypeInfo write FData.AsTypeInfo;
property AsMethod: TILMethod read FData.AsMethod write FData.AsMethod;
function IsLocalVar: Boolean;
function IsReference: Boolean; inline;
function IsResultVar: Boolean; inline;
function GetVarOffset: TOffset;
function GetDataCnt(MT: TILTranslator): Integer; override;
procedure Clear;
constructor Create;
constructor CreateFromVar(Variable: PILVariable);
destructor Destroy; override;
procedure WriteData(MT: TILTranslator; const Proc: TILProc; IP: PNativeUInt); override;
end;
TVMCodeArgILType = class(TVMCodeArgGeneric<PILType>)
public
procedure WriteData(MT: TILTranslator; const Proc: TILProc; IP: PNativeUInt); override;
end;
TVMCAILProc = class(TVMCodeArgGeneric<TILProc>)
public
procedure WriteData(MT: TILTranslator; const Proc: TILProc; IP: PNativeUInt); override;
end;
TVMCAProcRtti = class(TVMCodeArgGeneric<TILProc>)
public
procedure WriteData(MT: TILTranslator; const Proc: TILProc; IP: PNativeUInt); override;
end;
TVMCodeLine = record
SrcTextLine: Integer;
AsmTextLine: Integer;
UnitID: Integer;
Offset: Integer;
end;
TVMCodeLines = TList<TVMCodeLine>;
TStrLiteral = record
DTID: TDataTypeID;
Offset: TOffset;
end;
TStrLiteralsArray = array of TStrLiteral;
TRTTIClasses = record
_trtti: TOffset;
_trttiunit: TOffset;
_trttiordinal: TOffset;
_trttiarray: TOffset;
_trttiset: TOffset;
_trttidynarray: TOffset;
_trttifloat: TOffset;
_trttipointer: TOffset;
_trttivariant: TOffset;
_trttirecord: TOffset;
_trtticlass: TOffset;
_trttiinterface: TOffset;
_trttiproctype: TOffset;
_trttiprocedure: TOffset;
end;
TReadTypeContext = record
Stream: TStream;
ILUnit: TILUnit;
ILType: PILType;
TypeName: TOffset;
end;
TIL_D_Args = class(TILArgs)
D: TILArgument;
end;
TIL_DS_Args = class(TILArgs)
D: TILArgument;
S: TILArgument;
end;
TIL_LR_Args = class(TILArgs)
L: TILArgument;
R: TILArgument;
end;
TIL_CMP_ARGS = TIL_LR_Args;
TIL_CMPJ_ARGS = TIL_LR_Args;
TIL_TEST_ARGS = TIL_LR_Args;
TIL_CONVERT_ARGS = TIL_DS_Args;
TIL_DSS_Args = class(TILArgs)
D: TILArgument;
L: TILArgument;
R: TILArgument;
end;
TIL_LEA_ARGS = class(TILArgs)
D: TILArgument;
B: TILArgument;
Offset: TILArgument;
end;
TIL_ARRDALLOC_ARGS = TIL_DS_Args;
TIL_ARRAYLENGTH_ARGS = TIL_DS_Args;
TIL_TYPEINFO_ARGS = TIL_DS_Args;
TIL_QUERYTYPE_ARGS = TIL_DSS_Args;
TIL_MOVE_ARGS = TIL_DS_Args;
TIL_MOVEZERO_ARGS = TIL_D_Args;
TIL_NOT_ARGS = TIL_DS_Args;
TIL_INC_ARGS = TIL_D_Args;
TIL_GETBIT_ARGS = class(TILArgs)
Dst, BitArray, BitIndex: TILArgument;
end;
TIL_SETBIT_ARGS = class(TILArgs)
Dst, BitIndex, BitValue: TILArgument;
end;
TIL_SETBOOL_ARGS = TIL_D_Args;
TIL_ETHROW_ARGS = TIL_D_Args;
TIL_STRONGREF_ARGS = TIL_DS_Args;
TIL_WEAKREF_ARGS = TIL_DS_Args;
TIL_DNEW_ARGS = TIL_D_Args;
TIL_DNEWOBJ_ARGS = TIL_DS_Args;
TIL_DFREE_ARGS = TIL_D_Args;
TIL_INCREF_ARGS = TIL_D_Args;
TIL_DECREF_ARGS = TIL_D_Args;
TIL_DECREFFINAL_ARGS = class(TILArgs)
Dst: TILArgument;
FinalProc: TILArgument;
end;
TIL_INIT_ARGS = TIL_D_Args;
TIL_JMP_ARGS = TIL_D_Args;
TIL_MEMSET_ARGS = class(TILArgs)
Dst, Bpt: TILArgument;
end;
TIL_INHTCALL_ARGS = class(TILArgs)
ProcArg: TILArgument;
TypeArg: TILArgument;
SelfArg: TILArgument;
end;
TIL_GETPTR_ARGS = TIL_DS_Args;
TIL_GETSPTR_ARGS = class(TILArgs)
D, B, S: TILArgument;
end;
TIL_LDMETHOD_ARGS = TIL_DS_Args;
TIL_LDSMETHOD_ARGS = class(TILArgs)
D, B, S: TILArgument;
end;
TIL_NEARCALL_ARGS = TIL_D_Args;
TIL_ARRAYCOPY_ARGS = class(TILArgs)
D, S, F, L: TILArgument;
end;
TIL_RDREF_ARGS = TIL_DS_Args;
TIL_WDREF_ARGS = TIL_DS_Args;
TIL_ARRAYMOVE_ARGS = class(TILArgs)
SrcArr: TILArgument;
SrcIdx: TILArgument;
DstArr: TILArgument;
DstIdx: TILArgument;
Cnt: TILArgument;
end;
TIL_CHCKBND_ARGS = class(TILArgs)
AArray: TILArgument;
AIndex: TILArgument;
end;
TILArguments = array of TILArgument;
TIL_PCALL_ARGS = class(TILArgs)
PArg: TILArgument;
CallArgs: TILArguments;
end;
TIL_FMACRO_ARGS = class(TILArgs)
M, D: TILArgument;
end;
{ветвление}
TILBranch = record
CmpArgs: TIL_LR_Args; // аргументы инструкции сравнения
CmpCond: TILCondition; // условие сравнения
ElseIdx: Integer; // индекс первой инструкции else секции
EndIdx: Integer; // индекс последней инструкции ветвления if/case/else
end;
PILBranch = ^TILBranch;
{контекст ветвлений}
TILBranchContext = record
type
TILBranchStack = TPool<TILBranch>;
private
FItems: TILBranchStack;
function GetLast: PILBranch;
function GetCount: Integer;
public
procedure Init;
procedure Add(const Args: TIL_LR_Args);
procedure BrClose;
property Last: PILBranch read GetLast;
property Count: Integer read GetCount;
end;
PILBranchContext = ^TILBranchContext;
{базовый класс IL транслятора}
TILTranslator = class
private
FIncludeDebugInfo: Boolean;
FIncludeRTTI: Boolean;
FIMG: TILMemoryStream;
procedure SetRTTICharset(const Value: TRTTICharset);
protected
FIMGHeader: PIMGHeader;
FUnits: TILUnits;
VMUnits: PRTTIUnitsSArray;
FSystemTypes: TIMGTypes; // встроенные типы
FRTTI: TILMemoryStream; // RTTI сборки
FRTTIProcs: TILMemoryStream; // RTTI процедур сборки
FRTTICharset: TRTTICharset; // набор символов для RTTI
FRTTIClassTypes: TRTTIClasses; // classtypes для RTTI
FConstsSize: UInt32;
FStrLiterals: TStrLiteralsArray; // таблица смещений строковых литералов сборки
FStrLiteralsValues: TStrArray; // таблица значений строковых литералов сборки
FInterfaceCnt: Integer;
FInterfaceID: Integer;
FInterfaces: TList<PRTTIInterface>;
FImportTableCount: Integer;
FArgs: TObjectsPool<TVMCodeArg>;
FCodeAlign: Integer; // выравнивание кода
FDataAlign: Integer; // выравнивание данных
procedure LoadILUnitDecl(Index: Integer; Stream: TStream); virtual;
procedure LoadILUnitBody(ILUnit: TILUnit; Stream: TStream); virtual;
procedure LoadILTypes(ILUnit: TILUnit; Stream: TStream); virtual;
procedure LoadILConsts(ILUnit: TILUnit; Stream: TStream); virtual; abstract;
procedure LoadILSimpleConst(Stream: TStream; DataType: PRTTIType); virtual;
procedure LoadILRecordConst(ILUnit: TILUnit; Stream: TStream; CItem: PConstInfoRec); virtual;
procedure LoadILGlobalVars(ILUnit: TILUnit; Stream: TStream); virtual;
procedure LoadILProcDecls(Stream: TStream; ILUnit: TILUnit; ParentProc: TILProc; out Procedures: TILProcedures); virtual;
procedure LoadILProcBodies(Stream: TStream; ILUnit: TILUnit; ParentProc: TILProc; const Procedures: TILProcedures); virtual;
procedure LoadILProcBody(Stream: TStream; Proc: TILProc); virtual;
procedure LoadILParameters(Stream: TStream; Proc: TILProc); virtual;
procedure LoadILParameter(ILUnit: TILUnit; Stream: TStream; ParamsCount: Integer; Params: PRTTIParams); virtual;
procedure LoadILLocalVars(Proc: TILProc; Stream: TStream; var MemSize: Integer; StartVarIndex, VarCount: Integer); virtual;
procedure LoadILMethodsBodies(ILUnit: TILUnit; Stream: TStream); virtual;
procedure LoadILArgumentInternal(const Context: TILTContext; out Arg: TILArgument; PrevArg: TILArgument); virtual;
procedure LoadILArgument(const Context: TILTContext; out Arg: TILArgument);
procedure LoadILMethodArg(const Context: TILTContext; SelfArg: TILArgument; var Arg: TILArgument);
procedure CheckListArg(const Context: TILTContext; var Arg: TILArgument); virtual;
procedure AfterLoadILGlobalVars(ILUnit: TILUnit); virtual;
procedure AddFixOffset(Offset: TOffset); virtual;
function GetTMPVar(const Context: TILTContext; DataTypeID: TDataTypeID; IsReference: Boolean): PILVariable;
function GetUnitsCount: Integer;
function GetString(const Name: TOffset): UnicodeString;
function GetUnit(Index: Integer): TILUnit; inline;
function GetILType(UnitID, TypeID: Integer): PILType; inline;
function GetIMGPtr(const offset: TOffset): Pointer; inline;
function GetILMethod(Struct: PRTTIStruct; MethodIndex: Integer): TILProc;
function GetILField(Struct: PRTTIStruct; FieldIndex: Integer): PILVariable;
function GetParamDataSize(RTTI: PRTTIField): Integer;
function GetProcName(Proc: TILProc): string;
function GetSysTypeInfo(SysTypeIndex: Integer): PRTTIType; inline;
function GetTypeInfo(const ARG: TILArgument): PRTTIType; overload; inline;
function GetProcInfo(const ProcInfoOffset: TOffset): PRTTIProcedure; overload; inline;
function GetProcInfo(const Proc: TILProc): PRTTIProcedure; overload; inline;
function ArgGet: TILArgument; overload;
function ArgGet(const ILVar: PILVariable): TILArgument; overload;
function ArgGet(const ILType: PILType): TVMCodeArg; overload;
function ArgGet(const ILProc: TILProc): TVMCodeArg; overload;
function GetArgProcRtti(const ILProc: TILProc): TVMCodeArg; overload;
function CreateILUnit(const Name: string): TILUnit; virtual;
function CreateILUnitProc(ILUnit: TILUnit): TILProc; virtual;
function PrepareCALLInfo(const ProcArg: TILArgument; out ParamsCount: Integer; out Params: PRTTIParams; out ResultType: PRTTIType;
out ADDR: NativeUInt): TCallType;
function PassByRef(const Param: PRTTIParameter): Boolean;
function ReadVarStaticArrayValue(Stream: TStream; const Variable: PILVariable; ArrType: PRTTIArray): Pointer;
function ReadGlobalVarValue(Stream: TStream; const Variable: PILVariable): Pointer;
function ReadTypeSpecInfo(Stream: TStream): TOffset;
// функция вычитывает информацию о типе
function ReadVarType(ILUnit: TILUnit; Stream: TStream; VarFlags: Integer): TOffset;
procedure ReadImportInfo(Stream: TStream; TypeInfo: PRTTIType);
procedure ReadILFields(ILUnit: TILUnit; Stream: TStream; Struct: PRTTIStruct; ILType: PILType); virtual;
procedure ReadILMethodDecl(ILUnit: TILUnit; Stream: TStream; ProcInfo: PRTTIProcedure); virtual;
procedure ReadILMethodsDecls(ILUnit: TILUnit; Stream: TStream; Struct: PRTTIStruct; var Procedures: TILProcedures); virtual;
procedure RTTIProcToILProc(RTTIProc: PRTTIProcedure; Proc: TILProc);
//////////////////////////////////////////////////////////////////////////////////////////
/// Функции загрузки RTTI
procedure ReadOrdinalTypeInfo(var Context: TReadTypeContext); virtual;
procedure ReadSetTypeInfo(var Context: TReadTypeContext); virtual;
procedure ReadArrayTypeInfo(var Context: TReadTypeContext); virtual;
procedure ReadDynArrayTypeInfo(var Context: TReadTypeContext); virtual;
procedure ReadRecordTypeInfo(var Context: TReadTypeContext); virtual;
procedure ReadClassTypeInfo(var Context: TReadTypeContext); virtual;
procedure ReadIntfTypeInfo(var Context: TReadTypeContext); virtual;
procedure ReadPointerType(var Context: TReadTypeContext); virtual;
procedure ReadWeakRefType(var Context: TReadTypeContext); virtual;
procedure ReadClassOfType(var Context: TReadTypeContext); virtual;
procedure ReadProcTypeInfo(var Context: TReadTypeContext); virtual;
procedure ReadClassIntfaces(var Context: TReadTypeContext; var ClassType: PRTTIClass); virtual;
procedure ReadILCode(Stream: TStream; Proc: TILProc); virtual;
procedure CorrectProcJMPOffsets(Proc: TILProc); virtual;
procedure BeforeInstruction(const Ctx: TILTContext); virtual;
procedure AfterInstruction(const Ctx: TILTContext); virtual;
procedure Translate_NOPE(const Ctx: TILTContext); virtual; abstract;
procedure Translate_2OperandOpCode(const Ctx: TILTContext; var Args: TIL_DS_Args); virtual; abstract;
procedure Translate_3OperandOpCode(const Ctx: TILTContext; var Args: TIL_DSS_Args); virtual; abstract;
procedure Translate_LDPTR_Instruction(const Ctx: TILTContext; var Dst: TILArgument; const Src: TILArgument); virtual; abstract;
procedure Translate_LEA(const Ctx: TILTContext; var Args: TIL_LEA_Args); virtual; abstract;
procedure Translate_ARRDALLOC(const Ctx: TILTContext; var Args: TIL_ARRDALLOC_ARGS); virtual; abstract;
procedure Translate_ARRAYLENGTH(const Ctx: TILTContext; var Args: TIL_ARRAYLENGTH_ARGS); virtual; abstract;
procedure Translate_ARRAYCOPY(const Ctx: TILTContext; var Args: TIL_ARRAYCOPY_ARGS); virtual; abstract;
procedure Translate_ARRAYMOVE(const Ctx: TILTContext; var Args: TIL_ARRAYMOVE_ARGS); virtual; abstract;
procedure Translate_TYPEINFO(const Ctx: TILTContext; var Args: TIL_TYPEINFO_ARGS); virtual; abstract;
procedure Translate_QUERYTYPE(const Ctx: TILTContext; var Args: TIL_QUERYTYPE_ARGS); virtual; abstract;
procedure Translate_UNIQUE(const Ctx: TILTContext; var Args: TIL_D_Args); virtual; abstract;
procedure Translate_CMP(const Ctx: TILTContext; var Args: TIL_CMP_ARGS); virtual; abstract;
procedure Translate_CMPJ(const Ctx: TILTContext; var Args: TIL_CMPJ_ARGS); virtual; abstract;
procedure Translate_TEST(const Ctx: TILTContext; var Args: TIL_TEST_ARGS); virtual; abstract;
procedure Translate_CONVERT(const Ctx: TILTContext; var Args: TIL_CONVERT_ARGS); virtual; abstract;
procedure Translate_MOVE(const Ctx: TILTContext; var Args: TIL_MOVE_ARGS); virtual; abstract;
procedure Translate_MOVEZERO(const Ctx: TILTContext; var Args: TIL_MOVEZERO_ARGS); virtual; abstract;
procedure Translate_NOT(const Ctx: TILTContext; var Args: TIL_NOT_ARGS); virtual; abstract;
procedure Translate_INC(const Ctx: TILTContext; var Args: TIL_INC_ARGS); virtual; abstract;
procedure Translate_GETBIT(const Ctx: TILTContext; var Args: TIL_GETBIT_ARGS); virtual; abstract;
procedure Translate_SETBIT(const Ctx: TILTContext; var Args: TIL_SETBIT_ARGS); virtual; abstract;
procedure Translate_SETBOOL(const Ctx: TILTContext; var Args: TIL_SETBOOL_ARGS); virtual; abstract;
procedure Translate_TRYBEGIN(const Ctx: TILTContext); virtual; abstract;
procedure Translate_TRYEND(const Ctx: TILTContext); virtual; abstract;
procedure Translate_NEARCALL(const Ctx: TILTContext; var Args: TIL_NEARCALL_ARGS); virtual; abstract;
procedure Translate_ETHROW(const Ctx: TILTContext; var Args: TIL_ETHROW_ARGS); virtual; abstract;
procedure Translate_INCREF(const Ctx: TILTContext; var Args: TIL_INCREF_ARGS); virtual; abstract;
procedure Translate_DECREF(const Ctx: TILTContext; var Args: TIL_DECREF_ARGS); virtual; abstract;
procedure Translate_DECREFFINAL(const Ctx: TILTContext; var Args: TIL_DECREFFINAL_ARGS); virtual; abstract;
procedure Translate_INIT(const Ctx: TILTContext; var Args: TIL_INIT_ARGS); virtual; abstract;
procedure Translate_WEAKREF(const Ctx: TILTContext; var Args: TIL_WEAKREF_ARGS); virtual; abstract;
procedure Translate_STRONGREF(const Ctx: TILTContext; var Args: TIL_STRONGREF_ARGS); virtual; abstract;
procedure Translate_MEMSET(const Ctx: TILTContext; var Args: TIL_MEMSET_ARGS); virtual; abstract;
procedure Translate_PCALL(const Ctx: TILTContext; var Args: TIL_PCALL_ARGS); virtual; abstract;
procedure Translate_CHKBND(const Ctx: TILTContext; var Args: TIL_CHCKBND_ARGS); virtual; abstract;
procedure Translate_MEMGET(const Ctx: TILTContext; var Args: TIL_DNEW_ARGS); virtual; abstract;
procedure Translate_MEMFREE(const Ctx: TILTContext; var Args: TIL_DFREE_ARGS); virtual; abstract;
procedure Translate_DNEWOBJ(const Ctx: TILTContext; var Args: TIL_DNEWOBJ_ARGS); virtual; abstract;
procedure Translate_JMP(const Ctx: TILTContext; var Args: TIL_JMP_ARGS); virtual; abstract;
procedure Translate_RET(const Ctx: TILTContext); virtual; abstract;
procedure Translate_GETPTR(const Ctx: TILTContext; var Args: TIL_GETPTR_ARGS); virtual; abstract;
procedure Translate_LDMETHOD(const Ctx: TILTContext; var Args: TIL_LDMETHOD_ARGS); virtual; abstract;
procedure Translate_LDSMETHOD(const Ctx: TILTContext; var Args: TIL_LDSMETHOD_ARGS); virtual; abstract;
procedure Translate_GETSPTR(const Ctx: TILTContext; var Args: TIL_GETSPTR_ARGS); virtual; abstract;
procedure Translate_RDREF(const Ctx: TILTContext; var Args: TIL_RDREF_ARGS); virtual; abstract;
procedure Translate_WDREF(const Ctx: TILTContext; var Args: TIL_WDREF_ARGS); virtual; abstract;
procedure Translate_REFCNT(const Ctx: TILTContext; var Args: TIL_DS_ARGS); virtual; abstract;
procedure Translate_NOW(const Ctx: TILTContext; var Args: TIL_D_Args); virtual; abstract;
procedure Translate_FMACRO(const Ctx: TILTContext; var Args: TIL_FMACRO_ARGS); virtual; abstract;
procedure Translate_LDMETHODPTR_Instruction(const Ctx: TILTContext; const Dst, Method: TILArgument); virtual; abstract;
procedure Read_2OperandOpCode(var Ctx: TILTContext);
procedure Read_3OperandOpCode(var Ctx: TILTContext);
procedure Read_LEA(var Ctx: TILTContext);
procedure Read_ARRDALLOC(var Ctx: TILTContext);
procedure Read_ARRAYLENGTH(var Ctx: TILTContext);
procedure Read_ARRAYCOPY(var Ctx: TILTContext);
procedure Read_ARRAYMOVE(var Ctx: TILTContext);
procedure Read_TYPEINFO(var Ctx: TILTContext);
procedure Read_QUERYTYPE(var Ctx: TILTContext);
procedure Read_UNIQUE(var Ctx: TILTContext);
procedure Read_CMP(var Ctx: TILTContext);
procedure Read_CMPJ(var Ctx: TILTContext);
procedure Read_TEST(var Ctx: TILTContext);
procedure Read_CONVERT(var Ctx: TILTContext);
procedure Read_MOVE(var Ctx: TILTContext);
procedure Read_MOVEZERO(var Ctx: TILTContext);
procedure Read_NOT(var Ctx: TILTContext);
procedure Read_INC(var Ctx: TILTContext);
procedure Read_GETBIT(var Ctx: TILTContext);
procedure Read_SETBIT(var Ctx: TILTContext);
procedure Read_SETBOOL(var Ctx: TILTContext);
procedure Read_TRYBEGIN(var Ctx: TILTContext);
procedure Read_TRYEND(var Ctx: TILTContext);
procedure Read_NEARCALL(var Ctx: TILTContext);
procedure Read_ETHROW(var Ctx: TILTContext);
procedure Read_INCREF(var Ctx: TILTContext);
procedure Read_DECREF(var Ctx: TILTContext);
procedure Read_DECREFFINAL(var Ctx: TILTContext);
procedure Read_INIT(var Ctx: TILTContext);
procedure Read_WEAKREF(var Ctx: TILTContext);
procedure Read_STRONGREF(var Ctx: TILTContext);
procedure Read_MEMSET(var Ctx: TILTContext);
procedure Read_INHT_CALL(var Ctx: TILTContext);
procedure Read_PCALL(var Ctx: TILTContext);
procedure Read_PCALL_UNSAFE(var Ctx: TILTContext);
procedure Read_CHKBND(var Ctx: TILTContext);
procedure Read_MEMGET(var Ctx: TILTContext);
procedure Read_MEMFREE(var Ctx: TILTContext);
procedure Read_DNEWOBJ(var Ctx: TILTContext);
procedure Read_JMP(var Ctx: TILTContext);
procedure Read_RET(var Ctx: TILTContext);
procedure Read_GETPTR(var Ctx: TILTContext);
procedure Read_LDMETHOD(var Ctx: TILTContext);
procedure Read_LDSMETHOD(var Ctx: TILTContext);
procedure Read_GETSPTR(var Ctx: TILTContext);
procedure Read_RDREF(var Ctx: TILTContext);
procedure Read_WDREF(var Ctx: TILTContext);
procedure Read_REFCNT(var Ctx: TILTContext);
procedure Read_NOW(var Ctx: TILTContext);
procedure Read_FMACRO(var Ctx: TILTContext);
procedure WriteProcProlog(Proc: TILProc); virtual;
procedure WriteProcEpilog(Proc: TILProc; LastILCode: TILCode); virtual;
procedure WriteVMExportProcs(ILUnit: TILUnit); virtual;
procedure WriteILUnitProlog(Stream: TStream; ILUnit: TILUnit); virtual;
procedure WriteILUnitEpilog(Stream: TStream; ILUnit: TILUnit); virtual;
procedure WriteProcsRTTI(ILUnit: TILUnit); virtual;
procedure WriteTypesRTTIArray(ILUnit: TILUnit); virtual; abstract;
procedure WriteUnitsRTTIArray(UnitsCount: Integer); virtual;
procedure WriteProcLocalVarDebugInfo(Proc: TILProc); virtual;
procedure MapImportMethod(aType: PRTTIType; Proc: TILProc); virtual; abstract;
procedure MapImportProc(Proc: TILProc); virtual; abstract;
procedure MapImportType(aType: PRTTIType); virtual;
procedure MapRTTIClassTypes; virtual;
procedure MakeImportTable; virtual; abstract;
procedure SetSystemTypesOffsets(Types: PSystemTypes; Offsets: TIMGTypes);
procedure CorrectOffsets; virtual;
public
constructor Create; virtual;
destructor Destroy; override;
/////////////////////////////////
property IMG: TILMemoryStream read FIMG;
property IncludeRTTI: Boolean read FIncludeRTTI write FIncludeRTTI;
property IncludeDebugInfo: Boolean read FIncludeDebugInfo write FIncludeDebugInfo;
property Units[Index: Integer]: TILUnit read GetUnit;
property UnitsCount: Integer read GetUnitsCount;
property RTTICharset: TRTTICharset read FRTTICharset write SetRTTICharset;
function GetTypeInfo(const TypeInfoOffset: TOffset): PRTTIType; overload; inline;
procedure LoadILCode(Stream: TStream); overload; virtual;
procedure LoadILCode(const Path: string); overload; virtual;
procedure SaveTargetCode(Stream: TStream); overload; virtual; abstract;
procedure SaveTargetCode(const Path: string); overload; virtual;
end;
procedure AbortWork(const Message: string; const Params: array of const); overload;
procedure AbortWork(const Message: string); overload;
procedure AbortWorkNotSupported(const Message: string = '');
implementation
function MemAlign(Value: Integer; Align: Integer = 4): Integer; overload;
var
M: Integer;
begin
M := (Value mod Align);
if M = 0 then
Result := Value
else
Result := Value + (Align - M);
end;
procedure AbortWork(const Message: string; const Params: array of const); overload;
begin
raise Exception.CreateFmt(Message, Params);
end;
procedure AbortWork(const Message: string); overload;
begin
raise Exception.Create(Message);
end;
procedure AbortWorkNotSupported(const Message: string = '');
begin
AbortWork(Message + 'not supportd');
end;
function TILProc.GetTMPVar(DataTypeID: TDataTypeID; IsReference: Boolean): PILVariable;
var
i, c: Integer;
begin
c := Length(VarsTmp);
for i := 0 to c - 1 do
begin
Result := VarsTmp[i];
if not Result.TmpUsed then
begin
Result.TmpUsed := True;
Exit;
end;
end;
SetLength(VarsTmp, c + 1);
New(Result);
VarsTmp[c] := Result;
Result.VarScope := ARG_SCOPE_LOCAL;
Result.VarClass := VarMutable;
Result.TmpUsed := True;
Result.RTTI.Name := 0;
Result.RTTI.IsReference := IsReference;
Result.AbsoluteTo := nil;
if c > 0 then begin
Result.RTTI.Offset := VarsTmp[c - 1].RTTI.Offset + MemAlign(cDataTypeSizes[DataTypeID]);
end else begin
Result.RTTI.Offset := StackSize;
end;
end;
destructor TILProc.Destroy;
var
i: Integer;
begin
for i := 0 to Length(VarsTmp) - 1 do
Dispose(VarsTmp[i]);
for i := 0 to Length(NestedProcs) - 1 do
NestedProcs[i].Free;
// освобождаем аргументы
for i := 0 to Length(IL) - 1 do
IL[i].Args.Free;
end;
function TILProc.GetILCount: Integer;
begin
Result := Length(IL);
end;
function TILProc.GetStackSize: Integer;
var
c: Integer;
begin
Result := StackSize;
c := Length(VarsTmp);
if c > 0 then
Result := VarsTmp[c - 1].RTTI.Offset + PTR_SIZE;
end;
function TILProc.IsImported: Boolean;
begin
Result := (ImportLib > 0);
end;
{ TVMCodeArg }
function TVMCodeArg.GetDataCnt(MT: TILTranslator): Integer;
begin
Result := 1;
end;
{ TVMCodeArgILType }
procedure TVMCodeArgILType.WriteData(MT: TILTranslator; const Proc: TILProc; IP: PNativeUInt);
begin
if MT.IncludeRTTI then
IP^ := FValue.Offset
else
IP^ := FValue.StrictRTTI;
end;
{ TVMCAILProc }
procedure TVMCAILProc.WriteData(MT: TILTranslator; const Proc: TILProc; IP: PNativeUInt);
begin
IP^ := FValue.Offset;
end;
{ TVMCodeArgGeneric<T> }
constructor TVMCodeArgGeneric<T>.Create(const Value: T);
begin
FValue := Value;
end;
{ TVMCAProcRtti }
procedure TVMCAProcRtti.WriteData(MT: TILTranslator; const Proc: TILProc; IP: PNativeUInt);
begin
IP^ := FValue.ProcInfo;
end;
{ TILArgument }
procedure TILArgument.Clear;
begin
FData.I64 := 0;
ArgumentType := atImmConst;
ArgClass := ARG_VAR;
ArgScope := ARG_SCOPE_LOCAL;
TypeInfo := 0;
Next := nil;
end;
function TILArgument.IsLocalVar: Boolean;
begin
Result := (ArgClass = ARG_VAR) and (ArgScope = ARG_SCOPE_LOCAL) and
((NUInt > 10000) and not AsVariable.RTTI.IsReference);
end;
function TILArgument.IsReference: Boolean;
begin
Result := ArgumentType = atReference;
end;
function TILArgument.IsResultVar: Boolean;
begin
Result := (ArgClass = ARG_VAR) and AsVariable.IsResult;
end;
procedure TILArgument.WriteData(MT: TILTranslator; const Proc: TILProc; IP: PNativeUInt);
var
Offset: NativeUInt;
ti: PRTTIType;
begin
case ArgClass of
ARG_VAR: Offset := FData.AsVariable.RTTI.Offset;
ARG_PROC: Offset := FData.AsProcedure.Offset;
ARG_SCONST, ARG_TCONST, ARG_SIZEOF: Offset := FData.NUInt;
ARG_CONST: begin
ti := MT.GetTypeInfo(TypeInfo);
if ti.DataSize = 8 then
begin
PInt64(IP)^ := FData.I64;
Exit;
end;
Offset := FData.NUInt;
end;
ARG_TYPE: Offset := TypeInfo;
else
assert(false);
Exit;
end;
IP^ := Offset;
end;
constructor TILArgument.Create;
begin
end;
constructor TILArgument.CreateFromVar(Variable: PILVariable);
begin
FData.AsVariable := Variable;
ArgClass := ARG_VAR;
ArgScope := Variable.VarScope;
end;
destructor TILArgument.Destroy;
begin
inherited;
end;
function TILArgument.GetDataCnt(MT: TILTranslator): Integer;
var
ti: PRTTIType;
begin
if (ArgClass = ARG_CONST) then
begin
ti := MT.GetTypeInfo(TypeInfo);
if ti.DataSize = 8 then
Exit(2);
end;
Result := 1;
end;
function TILArgument.GetVarOffset: TOffset;
begin
Result := AsVariable.RTTI.Offset
end;
{ TILTranslator }
procedure TILTranslator.CheckListArg(const Context: TILTContext; var Arg: TILArgument);
var
Src: TILArgument;
begin
Src := Arg;
// аллокация временной переменной в Arg
Arg := ArgGet();
Arg.ArgumentType := atReference;
Arg.ArgScope := ARG_SCOPE_LOCAL;
Arg.Next := nil;
Arg.AsVariable := GetTMPVar(Context, dtPointer, True);
// инструкция загрузки адреса
Translate_LDPTR_Instruction(Context, Arg, Src);
// освобождаем если небыло надобности
if Arg.NUInt = Src.NUInt then
Arg.AsVariable.TmpUsed := False;
// освобождаем цепочку
//ArgReturn(Src);
end;
procedure TILTranslator.CorrectOffsets;
begin
end;
procedure TILTranslator.CorrectProcJMPOffsets(Proc: TILProc);
begin
end;
constructor TILTranslator.Create;
begin
FIMG := TILMemoryStream.Create;
FRTTI := TILMemoryStream.Create;
FRTTIProcs := TILMemoryStream.Create;
FInterfaces := TList<PRTTIInterface>.Create;
FRTTICharset := RTTICharsetUTF16;
FDataAlign := PTR_SIZE;
FCodeAlign := PTR_SIZE;
end;
function TILTranslator.CreateILUnit(const Name: string): TILUnit;
begin
Result := TILUnit.Create;
end;
function TILTranslator.CreateILUnitProc(ILUnit: TILUnit): TILProc;
begin
Result := TILProc.Create;
end;
destructor TILTranslator.Destroy;
var
i: Integer;
begin
for i := 0 to FArgs.Count - 1 do
FArgs.Items[i].Free;
FInterfaces.Free;
FRTTIProcs.Free;
FRTTI.Free;
FIMG.Free;
for i := 0 to Length(FUnits) - 1 do
FUnits[i].Free;
inherited;
end;
function TILTranslator.GetILField(Struct: PRTTIStruct; FieldIndex: Integer): PILVariable;
var
IMGType: ^TIMGType;
Fields: TILVariables;
Ancestor: PRTTIStruct;
begin
while Struct.Ancestor <> 0 do
begin
Ancestor := PRTTIStruct(GetTypeInfo(Struct.Ancestor));
if FieldIndex >= Ancestor.TotalFieldsCount then
Break;
Struct := Ancestor;
end;
IMGType := Addr(FUnits[Struct.UnitID].Types[Struct.Index]);
Fields := IMGType.Fields;
Result := Addr(Fields[FieldIndex - (Struct.TotalFieldsCount - Struct.FieldsCount)]);
end;
function TILTranslator.GetILMethod(Struct: PRTTIStruct; MethodIndex: Integer): TILProc;
var
IMGType: ^TIMGType;
Methods: TILProcedures;
Ancestor: PRTTIStruct;
begin
while Struct.Ancestor <> 0 do
begin
Ancestor := PRTTIStruct(GetTypeInfo(Struct.Ancestor));
if MethodIndex >= Ancestor.TotalMethodsCount then
Break;
Struct := Ancestor;
end;
IMGType := Addr(FUnits[Struct.UnitID].Types[Struct.Index]);
Methods := IMGType.Methods;
Result := Methods[MethodIndex - (Struct.TotalMethodsCount - Struct.MethodsCount)];
end;
function TILTranslator.GetILType(UnitID, TypeID: Integer): PILType;
begin
Result := addr(FUnits[UnitID].Types[TypeID]);
end;
function TILTranslator.GetIMGPtr(const offset: TOffset): Pointer;
begin
if offset > 0 then
Result := PByte(IMG.Memory) + offset
else
Result := nil;
end;
function TILTranslator.GetParamDataSize(RTTI: PRTTIField): Integer;
var
TI: PRTTIType;
begin
if RTTI.IsReference then
Exit(PTR_SIZE);
TI := GetTypeInfo(RTTI.DataType);
if TI.DataSize > 8 then
Exit(PTR_SIZE);
if IsDataTypeReferenced(TI.DataTypeID) then
Result := PTR_SIZE
else
Result := MemAlign(TI.DataSize);
end;
function TILTranslator.GetProcInfo(const Proc: TILProc): PRTTIProcedure;
begin
Result := GetProcInfo(Proc.ProcInfo);
end;
function TILTranslator.GetProcName(Proc: TILProc): string;
begin
Result := Proc.Name;
if Assigned(Proc.Struct) then
Result := Proc.Struct.Name + '.' + Result;
end;
function TILTranslator.GetProcInfo(const ProcInfoOffset: TOffset): PRTTIProcedure;
begin
// if ProcInfoOffset > 0 then
Result := PRTTIProcedure(PByte(FRTTIProcs.Memory) + ProcInfoOffset)
// else
// Result := nil;
end;
function TILTranslator.ArgGet: TILArgument;
begin
Result := TILArgument.Create;
FArgs.Add(Result);
end;
function TILTranslator.ArgGet(const ILVar: PILVariable): TILArgument;
begin
Result := TILArgument.CreateFromVar(ILVar);
FArgs.Add(Result);
end;
function TILTranslator.ArgGet(const ILType: PILType): TVMCodeArg;
begin
Result := TVMCodeArgILType.Create(ILType);
FArgs.Add(Result);
end;
procedure TILTranslator.AddFixOffset(Offset: TOffset);
begin
end;
procedure TILTranslator.AfterInstruction(const Ctx: TILTContext);
begin
end;
procedure TILTranslator.AfterLoadILGlobalVars(ILUnit: TILUnit);
begin
end;
function TILTranslator.ArgGet(const ILProc: TILProc): TVMCodeArg;
begin
Result := TVMCAILProc.Create(ILProc);
FArgs.Add(Result);
end;
procedure TILTranslator.BeforeInstruction(const Ctx: TILTContext);
begin
end;
function TILTranslator.GetArgProcRtti(const ILProc: TILProc): TVMCodeArg;
begin
Result := TVMCAProcRtti.Create(ILProc);
FArgs.Add(Result);
end;
function TILTranslator.GetString(const Name: TOffset): UnicodeString;
begin
if Name > 0 then
case FRTTICharset of
RTTICharsetASCII: Result := UnicodeString(AnsiString(PByte(IMG.Memory) + Name));
RTTICharsetUTF16: Result := UnicodeString(PByte(IMG.Memory) + Name);
end else
Result := '';
end;
function TILTranslator.GetSysTypeInfo(SysTypeIndex: Integer): PRTTIType;
begin
if (SysTypeIndex < 0) or (SysTypeIndex >= TSystemTypes.Count) then
raise Exception.CreateFmt('Invalid system type index: %d', [SysTypeIndex]);
Result := PRTTIType(PByte(FRTTI.Memory) + FSystemTypes[SysTypeIndex].Offset);
end;
function TILTranslator.GetTypeInfo(const ARG: TILArgument): PRTTIType;
begin
Result := GetTypeInfo(ARG.TypeInfo);
end;
function TILTranslator.GetTMPVar(const Context: TILTContext; DataTypeID: TDataTypeID; IsReference: Boolean): PILVariable;
begin
Result := Context.Proc.GetTMPVar(DataTypeID, IsReference);
Result.RTTI.DataType := FSystemTypes[Integer(dtPointer)].Offset;
end;
function TILTranslator.GetTypeInfo(const TypeInfoOffset: TOffset): PRTTIType;
begin
if TypeInfoOffset > 0 then
Result := PRTTIType(PByte(FRTTI.Memory) + TypeInfoOffset)
else
Result := nil;
end;
function TILTranslator.GetUnit(Index: Integer): TILUnit;
begin
Result := FUnits[Index];
end;
function TILTranslator.GetUnitsCount: Integer;
begin
Result := Length(FUnits);
end;
procedure TILTranslator.LoadILArgument(const Context: TILTContext; out Arg: TILArgument);
begin
LoadILArgumentInternal(Context, Arg, nil);
end;
procedure TILTranslator.LoadILArgumentInternal(const Context: TILTContext; out Arg: TILArgument; PrevArg: TILArgument);
var
DataPrefix: Byte;
Idx: Integer;
TypeInfo: PRTTIType;
Variable: PILVariable;
UnitID: Integer;
Data: UInt64;
begin
Arg := ArgGet();
DataPrefix := Context.Stream.ReadUInt8;
{если аргумент - непосредственная константа}
if Check(DataPrefix, ARG_IMMCONST) then
begin
Idx := DataPrefix and 63;
Arg.TypeInfo := FSystemTypes[Idx].Offset;
TypeInfo := GetSysTypeInfo(Idx);
Data := 0;
Context.Stream.Read(Data, TypeInfo.DataSize);
Arg.U64 := Data;
Arg.ArgumentType := atImmConst;
{Расширение знака}
case TypeInfo.DataTypeID of
dtInt8: Arg.I64 := Arg.I8;
dtInt16: Arg.I64 := Arg.I16;
dtInt32: Arg.I64 := Arg.I32;
end;
Arg.ArgClass := TILARG_CLASS.ARG_CONST;
Arg.ArgScope := TILARG_SCOPE.ARG_SCOPE_LOCAL;
end else begin
Arg.ArgClass := TILARG_CLASS((DataPrefix shr 2) and 7);
Arg.ArgScope := TILARG_SCOPE(DataPrefix and 3);
// если аргумент обьявлен в другом модуле
if Arg.ArgScope = ARG_SCOPE_UNIT then
UnitID := Context.Stream.ReadStretchUInt
else
UnitID := Context.PUnit.Index;
Arg.U64 := Context.Stream.ReadStretchUInt;
case Arg.ArgClass of
{аргумент - переменная}
ARG_VAR: begin
case Arg.ArgScope of
////////////////////////////////////////////////////////////
/// локальная переменная
ARG_SCOPE_LOCAL: begin
Variable := Addr(Context.Proc.Vars[Arg.U32]);
Arg.TypeInfo := Variable.RTTI.DataType;
if Variable.RTTI.IsReference then
Arg.ArgumentType := atReference
else
Arg.ArgumentType := atLocal;
Arg.PTR := Variable;
end;
////////////////////////////////////////////////////////////
/// глобальная переменная
ARG_SCOPE_GLOBAL: begin
Variable := Addr(Context.PUnit.Vars[Arg.U32]);
Arg.TypeInfo := Variable.RTTI.DataType;
if Variable.RTTI.IsReference then
raise Exception.Create('Invalid combination [GLOBAL VAR and REFERENCE]');
Arg.ArgumentType := atGlobal;
Arg.AsVariable := Variable;
end;
////////////////////////////////////////////////////////////
/// поле структуры
ARG_SCOPE_STRUCT: begin
{в контексте цепочки X.Y.Z...}
if Assigned(PrevArg) then begin
Arg.ArgumentType := atImmConst;
end else begin
TypeInfo := GetTypeInfo(Context.Proc.Struct.Offset);
Arg.AsVariable := GetILField(PRTTIStruct(TypeInfo), Arg.U32);
Arg.TypeInfo := Arg.AsVariable.RTTI.DataType;
Arg.ArgScope := ARG_SCOPE_STRUCT;
Arg.ArgumentType := atField;
//Assert(false);
end;
end;
ARG_SCOPE_UNIT: begin
Variable := Addr(FUnits[UnitID].Vars[Arg.U32]);
Arg.TypeInfo := Variable.RTTI.DataType;
if Variable.RTTI.IsReference then
raise Exception.Create('Invalid combination [GLOBAL VAR and REFERENCE]');
Arg.ArgumentType := atGlobal;
// сохраняем в аргументе адрес описания глобальной переменной
// позже в процедуре CorrectOffsets адрес будет заменен на смещение
Arg.PTR := Variable;
end;
end;
end;
{аргумент - процедура}
ARG_PROC, ARG_METHOD: begin
// сохраняем в аргументе адрес описания процедуры
// позже в процедуре CorrectOffsets адрес будет заменен на смещение
case Arg.ArgScope of
// вложенная процедура
ARG_SCOPE_LOCAL: begin
Assert(Arg.I32 < Length(Context.Proc.NestedProcs));
Arg.AsProcedure := Context.Proc.NestedProcs[Arg.U32];
Arg.ArgumentType := atLocal;
end;
// глобальная процедура
ARG_SCOPE_GLOBAL: begin
Arg.AsProcedure := Context.PUnit.Procs[Arg.U32];
Arg.ArgumentType := atGlobal;
Arg.TypeInfo := FSystemTypes[Ord(dtInt32)].Offset;
end;
// метод
ARG_SCOPE_STRUCT: LoadILMethodArg(Context, PrevArg, ARG);
ARG_SCOPE_UNIT: begin
Arg.AsProcedure := FUnits[UnitID].Procs[Arg.U32];
Arg.ArgumentType := atGlobal;
Arg.TypeInfo := FSystemTypes[Ord(dtInt32)].Offset;
end;
end;
end;
{аргумент - тип}
ARG_TYPE: begin
case Arg.ArgScope of
ARG_SCOPE_LOCAL, ARG_SCOPE_GLOBAL, ARG_SCOPE_STRUCT: Arg.TypeInfo := Context.PUnit.Types[Arg.U32 - TSystemTypes.Count].Offset;
ARG_SCOPE_UNIT: if Arg.U32 < TSystemTypes.Count then
Arg.TypeInfo := FSystemTypes[Arg.U32].Offset
else
Arg.TypeInfo := FUnits[UnitID].Types[Arg.U32 - TSystemTypes.Count].Offset;
else
AbortWork('not supported', []);
end;
Arg.AsTypeInfo := GetTypeInfo(Arg.TypeInfo);
Arg.ArgumentType := atImmConst;
end;
{аргумент - строковая константа}
ARG_SCONST: begin
Arg.U64 := FStrLiterals[Arg.U32].Offset;
Arg.TypeInfo := FSystemTypes[Ord(dtString)].Offset;
Arg.ArgScope := ARG_SCOPE_GLOBAL;
Arg.ArgumentType := atImmConst;
end;
{аргумент - бинарная константа}
ARG_TCONST: begin
Idx := Arg.U32;
Arg.U64 := Context.PUnit.Consts[Idx].Value;
Arg.TypeInfo := Context.PUnit.Consts[Idx].TypeInfo;
Arg.ArgScope := ARG_SCOPE_GLOBAL;
Arg.ArgumentType := atImmConst;
end;
{аргумент - константа-размер типа}
ARG_SIZEOF: begin
Arg.TypeInfo := FSystemTypes[Ord(dtInt32)].Offset;
Arg.ArgumentType := atImmConst;
if Arg.U32 >= TSystemTypes.Count then
TypeInfo := GetTypeInfo(FUnits[UnitID].Types[Arg.U32 - TSystemTypes.Count].Offset)
else
TypeInfo := GetTypeInfo(FSystemTypes[Arg.U32].Offset);
Arg.U64 := TypeInfo.DataSize;
end;
else
AbortWork('Argument class %d is not supported', [Integer(Arg.ArgClass)]);
end;
end;
// если цепочка,- загружаем следующий аргумент
if (DataPrefix and ARG_NEXT) = ARG_NEXT then
LoadILArgumentInternal(Context, Arg.Next, Arg);
end;
procedure TILTranslator.LoadILCode(Stream: TStream);
procedure WriteAsAnsiString(Index: Integer; const s: RawByteString);
var
Len: Integer;
UStr: string;
begin
Len := Length(s);
{$IFDEF CPUX64}IMG.WriteInt32(0);{$ENDIF} // padding for 64 bit compilers
IMG.WriteInt16(0); // кодировка
IMG.WriteInt16(1); // размер символа
IMG.WriteInt32(-1); // refcount (-1 - константа)
IMG.WriteInt32(Len); // str length
UStr := UnicodeString(s);
FStrLiterals[Index].DTID := dtAnsiString;
FStrLiterals[Index].Offset := IMG.Position;
FStrLiteralsValues[Index] := UStr;
if Len > 0 then
IMG.WriteBuffer(s[Low(s)], Len*SizeOf(Byte)); // str data
IMG.WriteUInt8(0); // ending zero
end;
procedure WriteAsUnicodeString(Index: Integer; const s: string);
var
Len: Integer;
UStr: string;
begin
Len := Length(s);
{$IFDEF CPUX64}IMG.WriteInt32(0);{$ENDIF} // padding for 64 bit compilers
IMG.WriteInt16(1200); // кодировка
IMG.WriteInt16(2); // размер символа
IMG.WriteInt32(-1); // refcount (-1 - константа)
IMG.WriteInt32(Len); // str length
UStr := UnicodeString(s);
FStrLiterals[Index].DTID := dtString;
FStrLiterals[Index].Offset := IMG.Position;
FStrLiteralsValues[Index] := UStr;
if Len > 0 then
IMG.WriteBuffer(UStr[Low(UStr)], Len*SizeOf(Word)); // str data
IMG.WriteUInt16(0); // ending zero
end;
procedure ReadStrLiterals(Stream: TStream);
var
DTID: TDataTypeID;
i, c: Integer;
RawStr: RawByteString;
begin
c := Stream.ReadStretchUInt;
SetLength(FStrLiterals, c);
SetLength(FStrLiteralsValues, c);
for i := 0 to c - 1 do begin
DTID := TDataTypeID(Stream.ReadUInt8);
RawStr := Stream.ReadRawByteString;
case DTID of
dtAnsiString: WriteAsAnsiString(i, RawStr);
dtString: WriteAsUnicodeString(i, UTF8ToString(RawStr));
else
raise Exception.Create('Invalid literal type');
end;
end;
end;
var
i, c: Integer;
SysTypes: PSystemTypes;
ILUnit: TILUnit;
begin
IMG.Size := 1024*1024*4; // начальное значение образа 4MB
FRTTI.Size := 1024*1024*1; // 1MB
FRTTIProcs.Size := 1024*1024*1; // 1MB
{заголовок}
FIMGHeader := IMG.MemoryPosition;
FIMGHeader.Signature := VM_IMG_SIGNATURE_V1;
IMG.IncPosition(SizeOf(TIMGHeader));
IncludeDebugInfo := Stream.ReadBoolean;
{табличные строковые литералы}
FIMGHeader.ConstsOffset := IMG.Position;
ReadStrLiterals(Stream);
FConstsSize := IMG.Position - FIMGHeader.ConstsOffset;
{системный RTTI}
FRTTI.WriteUInt32(VM_IMG_RTTI_SIGNATURE);
SysTypes := FRTTI.MemoryPosition;
// инициализируем встроенные типы
InitSystemTypes(SysTypes^);
FRTTI.IncPosition(SizeOf(TSystemTypes));
SetLength(FSystemTypes, TSystemTypes.Count);
// инициализируем встроенные типы (задаем смещения)
SetSystemTypesOffsets(SysTypes, FSystemTypes);
{модули}
c := Stream.ReadStretchUInt;
if c = 0 then
raise Exception.Create('The program has no units');
SetLength(FUnits, c);
{пишем дин массив RTTI модулей}
WriteUnitsRTTIArray(c);
VMUnits := IMG.MemoryPosition;
IMG.IncPosition(SizeOf(TRTTIUnit)*c);
{декларации модулей}
for i := 0 to c - 1 do
LoadILUnitDecl(i, Stream);
{связвание RTTI классов}
MapRTTIClassTypes;
{таблица импорта}
if FImportTableCount > 0 then
MakeImportTable;
FIMGHeader.ImportTableCount := FImportTableCount;
{тела модулей}
for i := 0 to c - 1 do begin
ILUnit := FUnits[i];
LoadILUnitBody(ILUnit, Stream);
end;
{коррекция смещений в образе}
CorrectOffsets;
end;
procedure TILTranslator.LoadILCode(const Path: string);
var
Stream: TFileStream;
begin
Stream := TFileStream.Create(Path, fmOpenRead);
try
LoadILCode(Stream);
finally
Stream.Free;
end;
end;
procedure TILTranslator.LoadILGlobalVars(ILUnit: TILUnit; Stream: TStream);
var
i, c, Idx: Integer;
pVar: PILVariable;
Prefix: Integer;
begin
c := Stream.ReadStretchUInt;
SetLength(ILUnit.Vars, c);
for i := 0 to c - 1 do
begin
Prefix := Stream.ReadUInt8;
pVar := addr(ILUnit.Vars[i]);
pVar.RTTI.Offset := 0;
pVar.VarScope := ARG_SCOPE_GLOBAL;
pVar.RTTI.FClassID := rttiVar;
pVar.RTTI.TypeInfo := nil;
pVar.RTTI.RefCount := -1;
pVar.RTTI.WeekInfo := nil;
pVar.RTTI.SyncInfo := nil;
pVar.RTTI.DataType := ReadVarType(ILUnit, Stream, Prefix);
if Check(Prefix, ILVAR_HASINDEX) then begin
Idx := Stream.ReadStretchUInt;
pVar.AbsoluteTo := addr(ILUnit.Vars[Idx]);
pVar.AbsoluteOffset := Stream.ReadStretchUInt;
end;
pVar.RTTI.IsReference := Check(Prefix, ILVAR_REFERENCE);
pVar.RTTI.IsConstant := Check(Prefix, ILVAR_CONSTPARAM);
if IncludeDebugInfo then
begin
Idx := Stream.ReadStretchUInt;
pVar.RTTI.Name := FStrLiterals[Idx].Offset;
pVar.Name := FStrLiteralsValues[Idx];
end else
pVar.Name := '$' + IntToStr(i);
pVar.DefaultValue := nil;
if Check(Prefix, ILVAR_HASVALUE) then
pVar.DefaultValue := ReadGlobalVarValue(Stream, pVar);
end;
AfterLoadILGlobalVars(ILUnit);
end;
procedure TILTranslator.LoadILLocalVars(Proc: TILProc; Stream: TStream; var MemSize: Integer; StartVarIndex, VarCount: Integer);
var
i, Idx: Integer;
LocalVar: PILVariable;
TypeInfo: PRTTIType;
Variables: TILVariables;
begin
Variables := Proc.Vars;
for i := StartVarIndex to VarCount - 1 do
try
LocalVar := addr(Variables[i]);
LocalVar.Flags := Stream.ReadUInt8;
LocalVar.VarScope := ARG_SCOPE_LOCAL;
LocalVar.RTTI.DataType := ReadVarType(Proc.ILUnit, Stream, LocalVar.Flags);
LocalVar.DefaultValue := nil;
LocalVar.RTTI.IsReference := Check(LocalVar.Flags, ILVAR_REFERENCE);
LocalVar.RTTI.IsConstant := Check(LocalVar.Flags, ILVAR_CONSTPARAM);
LocalVar.IsResult := False;
LocalVar.IsParam := False;
if Check(LocalVar.Flags, ILVAR_HASINDEX) then
begin
Idx := Stream.ReadStretchUInt;
LocalVar.AbsoluteOffset := Stream.ReadStretchUInt;
LocalVar.RTTI.Offset := Variables[Idx].RTTI.Offset;
end else begin
LocalVar.RTTI.Offset := MemSize;
TypeInfo := GetTypeInfo(LocalVar.RTTI.DataType);
if (TypeInfo.DataTypeID = dtClass) or LocalVar.RTTI.IsReference then
Inc(MemSize, MemAlign(PTR_SIZE))
else
Inc(MemSize, MemAlign(TypeInfo.DataSize));
end;
if IncludeDebugInfo then
begin
Idx := Stream.ReadStretchUInt;
LocalVar.RTTI.Name := FStrLiterals[Idx].Offset;
LocalVar.Name := FStrLiteralsValues[IDx];
end else
LocalVar.Name := '$' + IntToStr(i);
except
on e: exception do
raise Exception.CreateFmt('Read local variable ERROR[unit: %s proc: %s varidx: %d]: %s',
[Proc.ILUnit.Name, Proc.Name, i, e.Message]);
end;
end;
procedure TILTranslator.LoadILMethodArg(const Context: TILTContext; SelfArg: TILArgument; var Arg: TILArgument);
var
StructInfo: PRTTIType;
Method: TILProc;
M: TILMethod;
begin
if not Assigned(SelfArg) then
begin
StructInfo := GetTypeInfo(Context.Proc.Struct.Offset);
Assert(StructInfo.DataTypeID in [dtRecord, dtClass, dtInterface]);
SelfArg := Context.Proc.SelfArg;
end else
case SelfArg.ArgClass of
ARG_VAR: StructInfo := GetTypeInfo(SelfArg.AsVariable.RTTI.DataType);
ARG_TYPE: StructInfo := SelfArg.AsTypeInfo;
else
AbortWork('Self argument class is not supported');
StructInfo := nil;
end;
Method := GetILMethod(PRTTIStruct(StructInfo), Arg.U32);
M.Self := SelfArg;
M.Proc := Method;
Arg.AsMethod := M;
end;
procedure TILTranslator.LoadILMethodsBodies(ILUnit: TILUnit; Stream: TStream);
var
Index, TI, MI, TypesCount, MethodsCount: Integer;
Methods: TILProcedures;
ILType: PILType;
Proc: TILProc;
begin
TypesCount := Stream.ReadStretchUInt;
for TI := 0 to TypesCount - 1 do
begin
// читаем индекс типа
Index := Stream.ReadStretchUInt;
Index := Index - TSystemTypes.Count;
if (Index < 0) or (Index >= Length(ILUnit.Types)) then
AbortWork('Invalid type index: %d', [Index]);
// выделяем необходимое кол-во структур для методов
MethodsCount := Stream.ReadStretchUInt;
ILType := addr(ILUnit.Types[Index]);
Methods := ILType.Methods;
for MI := 0 to MethodsCount - 1 do
begin
Proc := Methods[MI];
{читаем тело метода}
LoadILProcBody(Stream, Proc);
end;
end;
end;
procedure TILTranslator.LoadILParameters(Stream: TStream; Proc: TILProc);
var
c: Integer;
begin
c := Stream.ReadStretchUInt;
SetLength(Proc.Params, c);
if c > 0 then
LoadILParameter(Proc.ILUnit, Stream, c, PRTTIParams(addr(Proc.Params[0])));
end;
procedure TILTranslator.LoadILParameter(ILUnit: TILUnit; Stream: TStream; ParamsCount: Integer; Params: PRTTIParams);
var
i, Idx: Integer;
Param: PRTTIParameter;
Prefix: Integer;
//PRTTI: PRTTIType;
begin
for i := 0 to ParamsCount - 1 do
begin
Param := addr(Params[i]);
Prefix := Stream.ReadUInt8;
Param.DataType := ReadVarType(ILUnit, Stream, Prefix);
Param.IsReference := Check(Prefix, ILVAR_REFERENCE);
Param.IsConstant := Check(Prefix, ILVAR_CONSTPARAM);
//PRTTI := GetTypeInfo(Param.DataType);
if IncludeDebugInfo then begin
Idx := Stream.ReadStretchUInt;
Param.Name := FStrLiterals[Idx].Offset;
end else
Param.Name := 0;
end;
end;
procedure TILTranslator.LoadILProcBodies(Stream: TStream; ILUnit: TILUnit; ParentProc: TILProc; const Procedures: TILProcedures);
var
i: Integer;
Proc: TILProc;
begin
// Загрузка тел процедур
for i := 0 to Length(Procedures) - 1 do begin
Proc := Procedures[i];
if not Proc.IsImported then
LoadILProcBody(Stream, Proc);
end;
end;
procedure TILTranslator.LoadILProcBody(Stream: TStream; Proc: TILProc);
var
i, ParamIndex, TotalVarsCnt, ParamsCnt, LocalVarsCnt, ExtraVarsCnt: Integer;
LocalVar: PILVariable;
Param: PRTTIParameter;
SelfTypeInfo: TOffset;
MemOffset: Integer;
StructInfo: PRTTIStruct;
begin
ParamsCnt := Length(Proc.Params);
// читаем кол-во локальных переменных
LocalVarsCnt := Stream.ReadStretchUInt;
if Assigned(Proc.Struct) then
begin
SelfTypeInfo := Proc.Struct.Offset;
StructInfo := PRTTIStruct(GetTypeInfo(SelfTypeInfo));
end else begin
StructInfo := nil;
SelfTypeInfo := 0;
end;
if (SelfTypeInfo <> 0) and (ILPROC_HASSELFPTR and Proc.Flags <> 0) then
begin
ExtraVarsCnt := 1;
end else begin
ExtraVarsCnt := 0;
end;
MemOffset := Proc.StackSize;
// так как в IL коде параметры и локальные переменные суть одно и тоже (единое пространство индексов),
// то переносим спиок параметров в список переменных, проставляя смещение в стеке
TotalVarsCnt := ParamsCnt + LocalVarsCnt + ExtraVarsCnt;
SetLength(Proc.Vars, TotalVarsCnt);
if TotalVarsCnt > 0 then
FillChar(Proc.Vars[0], TotalVarsCnt, 0);
// перенос, параметров в локальные переменные
ParamIndex := 0;
for i := 0 to ParamsCnt + ExtraVarsCnt - 1 do
begin
LocalVar := addr(Proc.Vars[i]);
if (((ILPROC_HASRESULT and Proc.Flags) <> 0) and
((ILPROC_HASSELFPTR and Proc.Flags) <> 0) and (i = 1)) or
(((ILPROC_HASRESULT and Proc.Flags) = 0) and
((ILPROC_HASSELFPTR and Proc.Flags) <> 0) and (i = 0)) then
begin
LocalVar.RTTI.DataType := SelfTypeInfo;
LocalVar.RTTI.Offset := MemOffset;
Inc(MemOffset, MemAlign(PTR_SIZE));
LocalVar.RTTI.IsReference := (StructInfo.DataTypeID = dtRecord);
LocalVar.RTTI.Name := 0;
LocalVar.VarClass := VarConst; // константный параметр
LocalVar.Name := 'Self';
LocalVar.AbsoluteTo := nil;
LocalVar.IsResult := False;
end else begin
Param := Addr(Proc.Params[ParamIndex]);
LocalVar.RTTI.DataType := Param.DataType;
LocalVar.RTTI.Offset := MemOffset;
LocalVar.IsResult := (Proc.ProcType = ptFunction) and (i = 0);
Inc(MemOffset, MemAlign(GetParamDataSize(Param)));
LocalVar.RTTI.IsReference := Param.IsReference;
LocalVar.RTTI.Name := Param.Name;
if Param.IsConstant then
LocalVar.VarClass := VarConst
else
LocalVar.VarClass := VarParam;
LocalVar.Name := GetString(Param.Name);
LocalVar.AbsoluteTo := nil;
Inc(ParamIndex);
end;
LocalVar.IsParam := True;
end;
{если это метод, добавляем аргумент - self}
if (Proc.Flags and ILPROC_HASSELFPTR) <> 0 then
begin
Proc.SelfArg := ArgGet();
Proc.SelfArg.ArgumentType := atLocal;
Proc.SelfArg.ArgClass := ARG_VAR;
Proc.SelfArg.ArgScope := ARG_SCOPE_LOCAL;
Proc.SelfArg.TypeInfo := SelfTypeInfo;
if (Proc.Flags and ILPROC_HASRESULT) <> 0 then
Proc.SelfArg.AsVariable := addr(Proc.Vars[1])
else
Proc.SelfArg.AsVariable := addr(Proc.Vars[0]);
end;
// загружаем RTTI локальных переменных
LoadILLocalVars(Proc, Stream, MemOffset, ParamsCnt + ExtraVarsCnt, TotalVarsCnt);
{ if FIncludeDebugInfo then
WriteLocalVarDebugInfo(Proc);}
Proc.StackSize := MemOffset;
// загружаем локальные процедуры
if (Proc.Flags and ILPROC_HASLOCALPROCS) <> 0 then
begin
LoadILProcDecls(Stream, Proc.ILUnit, Proc, Proc.NestedProcs);
LoadILProcBodies(Stream, Proc.ILUnit, Proc, Proc.NestedProcs);
end;
// задаем смещение в памяти начала кода процедуры
Proc.Offset := MemAlign(IMG.Position, FCodeAlign);
IMG.Position := Proc.Offset;
// читаем и транслируем IL-код процедуры
ReadILCode(Stream, Proc);
// корректируем размер стека + размер для временных переменных
Proc.StackSize := Proc.GetStackSize;
end;
procedure TILTranslator.WriteProcLocalVarDebugInfo(Proc: TILProc);
var
i, c: Integer;
PVar: PILVariable;
LVar: PRTTILocalVar;
ProcInfo: PRTTIProcedure;
LVars: PRTTILocalVarsSArray;
begin
c := Length(Proc.Vars);
FRTTI.WriteNativeInt(-1); // refcnt
FRTTI.WriteNativeInt(c); // length
ProcInfo := GetProcInfo(Proc);
if c = 0 then
begin
ProcInfo.LocalVars := 0;
Exit;
end;
ProcInfo.LocalVars := FRTTI.Position;
LVars := FRTTI.MemoryPosition;
FRTTI.IncPosition(SizeOf(TRTTILocalVar)*C);
for i := 0 to c - 1 do
begin
PVar := @(Proc.Vars[i]);
LVar := @(LVars[i]);
LVar.Name := PVar.RTTI.Name;
LVar.DataType := PVar.RTTI.DataType;
LVar.Offset := PVar.RTTI.Offset;
LVar.IsReference := PVar.RTTI.IsReference;
LVar.IsParam := PVar.IsParam;
end;
end;
procedure TILTranslator.LoadILProcDecls(Stream: TStream; ILUnit: TILUnit; ParentProc: TILProc; out Procedures: TILProcedures);
var
i, c: Integer;
Proc: TILProc;
NameIndex: Integer;
TypeInfo: PRTTIType;
ProcInfo: PRTTIProcedure;
begin
// Загрузка деклараций
c := Stream.ReadStretchUInt;
SetLength(Procedures, c);
for i := 0 to c - 1 do
begin
Proc := CreateILUnitProc(ILUnit);
Procedures[i] := Proc;
{выделяем память в RTTI секции}
Proc.ProcInfo := FRTTIProcs.Position;
ProcInfo := FRTTIProcs.MemoryPosition;
FRTTIProcs.IncPosition(SizeOf(TRTTIProcedure));
FillChar(ProcInfo^, Sizeof(TRTTIProcedure), 0);
ProcInfo.RefCount := -1;
ProcInfo.FClassID := rttiProc;
Proc.ILUnit := ILUnit;
Proc.StackSize := 0;
Proc.Offset := 0;
Proc.Flags := Stream.ReadUInt8;
ProcInfo.Flags := Proc.Flags;
Proc.CallConvention := TCallConvention(Stream.ReadUInt8);
ProcInfo.CallConvention := Proc.CallConvention;
Proc.ProcType := TProcType(Proc.Flags and ILPROC_HASRESULT);
{экспортируемая процедура}
if Check(Proc.Flags, ILPROC_EXPORT) then
begin
Proc.ExportIndex := ILUnit.ExportProcsCount;
Inc(ILUnit.ExportProcsCount);
end else begin
Proc.ExportIndex := -1;
end;
{чтение имени процедуры}
if Check(Proc.Flags, ILPROC_EXPORT) or IncludeDebugInfo then
begin
NameIndex := Stream.ReadStretchUInt;
ProcInfo.Name := FStrLiterals[NameIndex].Offset;
Proc.Name := GetString(ProcInfo.Name);
end;
{импортируемая процедура}
if Check(Proc.Flags, ILPROC_IMPORT) then begin
NameIndex := Stream.ReadStretchUInt;
Proc.ImportLib := FStrLiterals[NameIndex].Offset;
ProcInfo.ImportLib := Proc.ImportLib;
NameIndex := Stream.ReadStretchUInt;
Proc.ImportName := FStrLiterals[NameIndex].Offset;
ProcInfo.ImportName := Proc.ImportName;
Inc(FImportTableCount);
end;
if Check(Proc.Flags, ILPROC_VIRTUAL) then
begin
Proc.VirtualIndex := Stream.ReadStretchUInt;
ProcInfo.VirtualIndex := Proc.VirtualIndex;
end;
{читаем парметры}
LoadILParameters(Stream, Proc);
if Check(Proc.Flags, ILPROC_HASRESULT) then
begin
ProcInfo.ResultType := Proc.Params[0].DataType;
TypeInfo := GetTypeInfo(ProcInfo.ResultType);
if TypeInfo.DataTypeID in [dtRecord, dtGuid, dtStaticArray] then
Proc.Params[0].IsReference := True;
end;
{поиск импортируемой процедуры}
if (Proc.Flags and ILPROC_IMPORT) <> 0 then
MapImportProc(Proc);
end;
end;
procedure TILTranslator.LoadILSimpleConst(Stream: TStream; DataType: PRTTIType);
begin
end;
procedure TILTranslator.LoadILRecordConst(ILUnit: TILUnit; Stream: TStream; CItem: PConstInfoRec);
var
i: Integer;
Fld: PRTTIField;
Fields: TRTTIFields;
FldDataType: PRTTIType;
StructInfo: PRTTIStruct;
begin
StructInfo := PRTTIStruct(GetTypeInfo(CItem.TypeInfo));
CItem.Value := IMG.Position;
CItem.Size := StructInfo.DataSize;
Fields := TRTTIFields(GetTypeInfo(StructInfo.Fields));
for i := 0 to Length(Fields) - 1 do
begin
Fld := @(Fields[i]);
FldDataType := GetTypeInfo(Fld.DataType);
if FldDataType.DataTypeID in [dtString, dtAnsiString] then
AddFixOffset(IMG.Position);
LoadILSimpleConst(Stream, FldDataType);
end;
end;
procedure TILTranslator.LoadILTypes(ILUnit: TILUnit; Stream: TStream);
var
i, c, RTTISize: Integer;
dt: UInt8;
TypeInfo: PRTTIType;
Idx: Integer;
Context: TReadTypeContext;
IMGType: ^TIMGType;
begin
c := Stream.ReadStretchUInt;
SetLength(ILUnit.Types, c);
Context.Stream := Stream;
Context.ILUnit := ILUnit;
// пердварительная аллокация
for i := 0 to c - 1 do begin
dt := Stream.ReadUInt8;
IMGType := addr(ILUnit.Types[i]);
IMGType.ID := TDataTypeID(dt and 127);
IMGType.Offset := FRTTI.Position;
case IMGType.ID of
dtEnum: RTTISize := SizeOf(TRTTIOrdinal);
dtRange: RTTISize := SizeOf(TRTTIOrdinal);
dtSet: RTTISize := SizeOf(TRTTIOrdinal);
dtStaticArray: RTTISize := SizeOf(TRTTIArray);
dtDynArray, dtOpenArray: RTTISize := SizeOf(TRTTIDynArray);
dtPointer: RTTISize := SizeOf(TRTTIPointer);
dtWeakRef: RTTISize := SizeOf(TRTTIPointer);
dtRecord: RTTISize := SizeOf(TRTTIRecord);
dtClass: RTTISize := SizeOf(TRTTIClass);
dtClassOf: RTTISize := SizeOf(TRTTIPointer);
dtProcType: RTTISize := SizeOf(TRTTIProcType);
dtInterface: begin
RTTISize := SizeOf(TRTTIInterface);
Inc(FInterfaceCnt);
end;
else
RTTISize := 0;
Assert(False);
end;
FRTTI.IncPosition(RTTISize);
TypeInfo := GetTypeInfo(IMGType.Offset);
FillChar(TypeInfo^, RTTISize, #0);
TypeInfo.RefCount := -1;
TypeInfo.DataTypeID := IMGType.ID;
if IMGType.ID = dtInterface then
begin
PRTTIInterface(TypeInfo).InterfaceID := FInterfaceID;
FInterfaces.Add(PRTTIInterface(TypeInfo));
Inc(FInterfaceID);
end;
end;
// второй проход
for i := 0 to c - 1 do begin
dt := Stream.ReadUInt8; // читаем DataTypeID
if IncludeDebugInfo then begin
Idx := Stream.ReadStretchUInt;
Context.TypeName := FStrLiterals[Idx].Offset;
end else
Context.TypeName := 0;
Context.ILType := Addr(ILUnit.Types[i]);
Assert(TDataTypeID(dt) = Context.ILType.ID);
TypeInfo := GetTypeInfo(Context.ILType.Offset);
TypeInfo.Name := Context.TypeName;
TypeInfo.UnitID := ILUnit.Index;
TypeInfo.Index := i;
Context.ILType.Name := GetString(TypeInfo.Name);
case Context.ILType.ID of
dtEnum: ReadOrdinalTypeInfo(Context);
dtRange: ReadOrdinalTypeInfo(Context);
dtSet: ReadSetTypeInfo(Context);
dtStaticArray: ReadArrayTypeInfo(Context);
dtDynArray, dtOpenArray: ReadDynArrayTypeInfo(Context);
dtPointer: ReadPointerType(Context);
dtWeakRef: ReadWeakRefType(Context);
dtRecord: ReadRecordTypeInfo(Context);
dtClass: ReadClassTypeInfo(Context);
dtClassOf: ReadClassOfType(Context);
dtProcType: ReadProcTypeInfo(Context);
dtInterface: ReadIntfTypeInfo(Context);
else
AbortWork('Unknown type info: %s', [GetDataTypeName(Context.ILType.ID)]);
end;
end;
WriteTypesRTTIArray(ILUnit);
end;
procedure TILTranslator.LoadILUnitBody(ILUnit: TILUnit; Stream: TStream);
var
i, c, SrcTextLine: Integer;
begin
{глобальные процедуры}
LoadILProcBodies(Stream, ILUnit, nil, ILUnit.Procs);
{методы}
LoadILMethodsBodies(ILUnit, Stream);
WriteILUnitProlog(Stream, ILUnit);
WriteILUnitEpilog(Stream, ILUnit);
if IncludeDebugInfo then
begin
c := Stream.ReadStretchUInt;
SetLength(ILUnit.BreakPoints, c);
for i := 0 to c - 1 do begin
SrcTextLine := Stream.ReadStretchUInt;
ILUnit.BreakPoints[i].SrcTextLine := SrcTextLine;
ILUnit.BreakPoints[i].VMTextLine := 0; // установка позже
ILUnit.BreakPoints[i].Offset := 0; // установка позже
end;
end;
WriteVMExportProcs(ILUnit);
WriteProcsRTTI(ILUnit);
end;
procedure TILTranslator.LoadILUnitDecl(Index: Integer; Stream: TStream);
var
NameIndex: UInt32;
ProcInfo: PRTTIProcedure;
UFlags: UInt32;
UName: string;
ILUnit: TILUnit;
begin
UFlags := Stream.ReadStretchUInt;
{RTTI имя}
NameIndex := Stream.ReadStretchUInt;
UName := FStrLiteralsValues[NameIndex];
ILUnit := CreateILUnit(UName);
ILUnit.Name := UName;
ILUnit.Flags := UFlags;
ILUnit.Index := Index;
FUnits[Index] := ILUnit;
ILUnit.VMUnit := addr(VMUnits[Index]);
ILUnit.VMUnit.FClassID := rttiUnit;
ILUnit.VMUnit.RefCount := -1;
ILUnit.VMUnit.Name := FStrLiterals[NameIndex].Offset;
ILUnit.VMUnit.Procs := FRTTIProcs.Position;
{типы}
LoadILTypes(ILUnit, Stream);
{константы}
LoadILConsts(ILUnit, Stream);
{глобальные переменные}
LoadILGlobalVars(ILUnit, Stream);
{глобальные процедуры}
LoadILProcDecls(Stream, ILUnit, nil, ILUnit.Procs);
ILUnit.InitProc := CreateILUnitProc(ILUnit);
ILUnit.InitProc.ProcInfo := FRTTIProcs.Position;
ProcInfo := FRTTIProcs.MemoryPosition;
FRTTIProcs.IncPosition(SizeOf(TRTTIProcedure));
FillChar(ProcInfo^, Sizeof(TRTTIProcedure), 0);
ProcInfo.RefCount := -1;
ProcInfo.FClassID := rttiProc;
ILUnit.FinalProc := CreateILUnitProc(ILUnit);
ILUnit.FinalProc.ProcInfo := FRTTIProcs.Position;
ProcInfo := FRTTIProcs.MemoryPosition;
FRTTIProcs.IncPosition(SizeOf(TRTTIProcedure));
FillChar(ProcInfo^, Sizeof(TRTTIProcedure), 0);
ProcInfo.RefCount := -1;
ProcInfo.FClassID := rttiProc;
end;
procedure TILTranslator.MapImportType(aType: PRTTIType);
var
LibName, TypeName: UnicodeString;
RegType: TTypeRegInfo;
begin
LibName := GetString(aType.ImportLib);
TypeName := GetString(aType.ImportName);
RegType := FindType(LibName, TypeName);
if not Assigned(RegType) then
raise Exception.CreateFmt('Import type "%s" in library "%s" is not found', [TypeName, LibName]);
end;
procedure TILTranslator.MapRTTIClassTypes;
var
i, j, pi: Integer;
UN: TILUnit;
TD: PILType;
TI: PRTTIType;
ProcInfo: PRTTIProcedure;
TypeName: string;
begin
for i := 0 to Length(FUnits) - 1 do
begin
UN := FUnits[i];
if LowerCase(UN.Name) = cRttiUnitName then
begin
for j := 0 to Length(UN.Types) - 1 do
begin
TD := addr(UN.Types[j]);
TypeName := LowerCase(TD.Name);
if TypeName = 'trtti' then
FRTTIClassTypes._trtti := TD.Offset
else
if TypeName = 'trttiunit' then
FRTTIClassTypes._trttiunit := TD.Offset
else
if TypeName = 'trttiordinal' then
FRTTIClassTypes._trttiordinal := TD.Offset
else
if TypeName = 'trttiarray' then
FRTTIClassTypes._trttiarray := TD.Offset
else
if TypeName = 'trttiset' then
FRTTIClassTypes._trttiset := TD.Offset
else
if TypeName = 'trttidynarray' then
FRTTIClassTypes._trttidynarray := TD.Offset
else
if TypeName = 'trttifloat' then
FRTTIClassTypes._trttifloat := TD.Offset
else
if TypeName = 'trttipointer' then
FRTTIClassTypes._trttipointer := TD.Offset
else
if TypeName = 'trttivariant' then
FRTTIClassTypes._trttivariant := TD.Offset
else
if TypeName = 'trttirecord' then
FRTTIClassTypes._trttirecord := TD.Offset
else
if TypeName = 'trtticlass' then
FRTTIClassTypes._trtticlass := TD.Offset
else
if TypeName = 'trttiinterface' then
FRTTIClassTypes._trttiinterface := TD.Offset
else
if TypeName = 'trttiproctype' then
FRTTIClassTypes._trttiproctype := TD.Offset
else
if TypeName = 'trttiprocedure' then
FRTTIClassTypes._trttiprocedure := TD.Offset;
end;
break;
end;
end;
// RTTI классы не найдены
if FRTTIClassTypes._trtti = 0 then
Exit;
{проставляем classinfo для системных типов}
for i := 0 to Length(FSystemTypes) - 1 do
begin
TD := addr(FSystemTypes[i]);
TI := GetTypeInfo(TD.Offset);
case TI.DataTypeID of
dtInt8, dtInt16, dtInt32, dtInt64,
dtUInt8, dtUInt16, dtUInt32, dtUInt64,
dtNativeInt, dtNativeUInt,
dtBoolean, dtChar, dtAnsiChar: TI.TypeInfo := Pointer(FRTTIClassTypes._trttiordinal);
dtString, dtAnsiString: TI.TypeInfo := Pointer(FRTTIClassTypes._trttiarray);
dtFloat32, dtFloat64: TI.TypeInfo := Pointer(FRTTIClassTypes._trttifloat);
dtPointer: TI.TypeInfo := Pointer(FRTTIClassTypes._trttipointer);
dtVariant: TI.TypeInfo := Pointer(FRTTIClassTypes._trttivariant);
dtGuid: TI.TypeInfo := Pointer(FRTTIClassTypes._trtti);
else
AbortWork('Invalid RTTI for system type: ' + GetDataTypeName(TI.DataTypeID));
end;
end;
{проставляем classinfo для пользовательских типов}
for i := 0 to Length(FUnits) - 1 do
begin
UN := FUnits[i];
UN.VMUnit.TypeInfo := Pointer(FRTTIClassTypes._trttiunit);
for j := 0 to Length(UN.Types) - 1 do
begin
TD := addr(UN.Types[j]);
TI := GetTypeInfo(TD.Offset);
case TI.DataTypeID of
dtInt8, dtInt16, dtInt32, dtInt64,
dtUInt8, dtUInt16, dtUInt32, dtUInt64,
dtNativeInt, dtNativeUInt,
dtBoolean, dtEnum, dtRange, dtChar, dtAnsiChar: TI.TypeInfo := Pointer(FRTTIClassTypes._trttiordinal);
dtSet: TI.TypeInfo := Pointer(FRTTIClassTypes._trttiset);
dtStaticArray, dtString, dtAnsiString: TI.TypeInfo := Pointer(FRTTIClassTypes._trttiarray);
dtDynArray, dtOpenArray: TI.TypeInfo := Pointer(FRTTIClassTypes._trttidynarray);
dtFloat32, dtFloat64: TI.TypeInfo := Pointer(FRTTIClassTypes._trttifloat);
dtPointer: TI.TypeInfo := Pointer(FRTTIClassTypes._trttipointer);
dtVariant: TI.TypeInfo := Pointer(FRTTIClassTypes._trttivariant);
dtGuid: TI.TypeInfo := Pointer(FRTTIClassTypes._trtti);
dtRecord: TI.TypeInfo := Pointer(FRTTIClassTypes._trttirecord);
dtClass: TI.TypeInfo := Pointer(FRTTIClassTypes._trtticlass);
dtInterface: TI.TypeInfo := Pointer(FRTTIClassTypes._trttiinterface);
dtProcType: TI.TypeInfo := Pointer(FRTTIClassTypes._trttiproctype);
else
AbortWork('Invalid RTTI for type: ' + GetDataTypeName(TI.DataTypeID));
end;
// methods
for pi := 0 to Length(TD.Methods) - 1 do
begin
ProcInfo := GetProcInfo(TD.Methods[pi].ProcInfo);
ProcInfo.TypeInfo := Pointer(FRTTIClassTypes._trttiprocedure);
end;
end;
// global procs
for pi := 0 to Length(UN.Procs) - 1 do
begin
ProcInfo := GetProcInfo(UN.Procs[pi].ProcInfo);
ProcInfo.TypeInfo := Pointer(FRTTIClassTypes._trttiprocedure);
end;
// init
ProcInfo := GetProcInfo(UN.InitProc.ProcInfo);
ProcInfo.TypeInfo := Pointer(FRTTIClassTypes._trttiprocedure);
// final
ProcInfo := GetProcInfo(UN.FinalProc.ProcInfo);
ProcInfo.TypeInfo := Pointer(FRTTIClassTypes._trttiprocedure);
end;
end;
procedure TILTranslator.ReadArrayTypeInfo(var Context: TReadTypeContext);
var
i, c: Integer;
TotalElCnt, ElCnt: Int32;
DimTypeInfo: PRTTIOrdinal;
TI: TOffset;
Dimenstions: PRTTIDimensions;
Result: PRTTIArray;
begin
with Context do begin
c := Stream.ReadStretchUInt;
Result := PRTTIArray(GetTypeInfo(Context.ILType.Offset));
Result.Dimensions := FRTTI.Position;
FRTTI.IncPosition(c*SizeOf(TRTTIOrdinal));
Dimenstions := PRTTIDimensions(GetTypeInfo(Result.Dimensions));
FillChar(Dimenstions^, c*SizeOf(TRTTIOrdinal), #0);
Result.DimensionsCount := c;
Result.DataTypeID := dtStaticArray;
TotalElCnt := 1;
for i := 0 to c - 1 do begin
TI := ReadTypeSpecInfo(Stream);
Dimenstions[i] := TI;
DimTypeInfo := PRTTIOrdinal(GetTypeInfo(TI));
ElCnt := DimTypeInfo.HiBound - DimTypeInfo.LoBound + 1;
TotalElCnt := TotalElCnt * ElCnt;
end;
Result.ElementTypeInfoOffset := ReadTypeSpecInfo(Stream);
Result.DataSize := TotalElCnt * GetTypeInfo(Result.ElementTypeInfoOffset).DataSize;
end;
end;
procedure TILTranslator.ReadClassIntfaces(var Context: TReadTypeContext; var ClassType: PRTTIClass);
var
i, j, UnitID, TypeID, IntfCnt, MCnt, MIdx: Integer;
IMTables: PIMTS;
IntfType: PILType;
IntfRTTI: PRTTIInterface;
Method: TILProc;
IMT: PIMT;
begin
with Context do begin
// кол-во интерфейсов которые имплементирует класс
IntfCnt := Stream.ReadStretchUInt;
ClassType.IMTS := IMG.Position;
IMTables := IMG.MemoryPosition;
IMG.IncPosition(FInterfaceCnt*PTR_SIZE);
FillChar(IMTables^, FInterfaceCnt*PTR_SIZE, #0);
// читаем список интерфейсов
for i := 0 to IntfCnt - 1 do
begin
UnitID := Stream.ReadStretchUInt;
TypeID := Stream.ReadStretchUInt;
MCnt := Stream.ReadStretchUInt;
IntfType := GetILType(UnitID, TypeID - TSystemTypes.Count);
Assert(Assigned(IntfType));
IntfRTTI := PRTTIInterface(GetTypeInfo(IntfType.Offset));
// выделяем память под IMT
IMTables[IntfRTTI.InterfaceID] := IMG.Position;
IMT := IMG.MemoryPosition;
IMG.IncPosition(MCnt*PTR_SIZE);
// читаем список методотов класса для данного интерфейса
for j := 0 to MCnt - 1 do begin
MIdx := Stream.ReadStretchUInt;
Method := GetILMethod(ClassType, MIdx);
IMT[j] := TOffset(Method); // сохраняем для последующей корректировки
end;
end;
end;
end;
procedure TILTranslator.ReadClassOfType(var Context: TReadTypeContext);
var
Result: PRTTIPointer;
begin
with Context do begin
Result := PRTTIPointer(GetTypeInfo(Context.ILType.Offset));
Result.DataTypeID := dtClassOf;
Result.DataSize := PTR_SIZE;
Result.RefTypeInfoOffset := ReadTypeSpecInfo(Stream);
end;
end;
procedure TILTranslator.ReadClassTypeInfo(var Context: TReadTypeContext);
var
i: Integer;
Ancestor: PRTTIClass;
Flags: UInt8;
Methods: TILProcedures;
VMTCount, MaxVirtIndex, VIdx: Integer;
AncestorVMTCount: Integer;
AVMT, VMT: PVMT;
Result: PRTTIClass;
begin
Result := PRTTIClass(GetTypeInfo(Context.ILType.Offset));
Result.DataTypeID := dtClass;
Result.DataSize := 0;
with Context do
begin
Flags := Stream.ReadUInt8;
if Check(Flags, ILTYPE_HAS_ANCESTOR) then
begin
Result.Ancestor := ReadTypeSpecInfo(Stream);
Ancestor := PRTTIClass(GetTypeInfo(Result.Ancestor));
AncestorVMTCount := Ancestor.VMTCount;
Result.TotalMethodsCount := Ancestor.TotalMethodsCount;
Result.TotalFieldsCount := Ancestor.TotalFieldsCount;
end else begin
Ancestor := nil;
Result.Ancestor := 0;
AncestorVMTCount := 0;
Result.TotalMethodsCount := 0;
Result.TotalFieldsCount := 0;
end;
Result.TypePacked := Check(Flags, ILTYPE_PACKED);
if Check(Flags, ILTYPE_IMPORT) then
begin
ReadImportInfo(Stream, Result);
MapImportType(Result);
end else begin
Result.ImportLib := 0;
Result.ImportName := 0;
end;
{загрузка полей}
ReadILFields(ILUnit, Stream, Result, ILType);
Inc(Result.TotalFieldsCount, Length(ILType.Fields));
{загрузка деклараций методов}
ReadILMethodsDecls(ILUnit, Stream, Result, Methods);
Inc(Result.TotalMethodsCount, Length(Methods));
MaxVirtIndex := -1;
for i := 0 to Length(Methods) - 1 do
if (Methods[i].Flags and ILPROC_VIRTUAL) > 0 then
MaxVirtIndex := Max(MaxVirtIndex, Methods[i].VirtualIndex);
if MaxVirtIndex < AncestorVMTCount then
VMTCount := AncestorVMTCount
else
VMTCount := MaxVirtIndex + 1;
// тут необходимо скопировать основной образ данные по VMT
VMT := PVMT(IMG.MemoryPosition);
Result.VMT := IMG.Position;
Result.VMTCount := VMTCount;
IMG.IncPosition(VMTCount*PTR_SIZE);
if Assigned(Ancestor) then
begin
AVMT := GetIMGPtr(Ancestor.VMT);
Move(AVMT^, VMT^, AncestorVMTCount*PTR_SIZE);
end;
{заполняем VMT элементами TILProc}
for i := 0 to Length(Methods) - 1 do
if (Methods[i].Flags and ILPROC_VIRTUAL) > 0 then
begin
VIdx := Methods[i].VirtualIndex;
VMT[VIdx] := NativeUInt(Methods[i]);
end;
ILType.Methods := Methods;
if Check(Flags, ILTYPE_IMPL_INTERFACES) then
ReadClassIntfaces(Context, Result);
end;
end;
procedure TILTranslator.ReadDynArrayTypeInfo(var Context: TReadTypeContext);
var
ElDt: TOffset;
Result: PRTTIDynArray;
ProcIndex: Integer;
begin
with Context do begin
Result := PRTTIDynArray(GetTypeInfo(Context.ILType.Offset));
Result.DimensionsCount := 1;
Result.DataTypeID := ILType.ID;
Result.Flags := Stream.ReadUInt8;
if Check(Result.Flags, ILARRAY_HAS_INIT) then
begin
ProcIndex := Stream.ReadStretchUInt;
Result.InitProc := ProcIndex;
end;
if Check(Result.Flags, ILARRAY_HAS_FINAL) then
begin
ProcIndex := Stream.ReadStretchUInt;
Result.FinalUIdx := ProcIndex;
ProcIndex := Stream.ReadStretchUInt;
Result.FinalProc := ProcIndex;
end;
ElDt := ReadTypeSpecInfo(Stream);
Result.Dimensions := FSystemTypes[Ord(dtUInt32)].Offset;
Result.ElementTypeInfoOffset := ElDt;
Result.DataSize := PTR_SIZE;
end;
end;
function TILTranslator.ReadVarStaticArrayValue(Stream: TStream; const Variable: PILVariable; ArrType: PRTTIArray): Pointer;
function GetArrayElementCount(ArrType: PRTTIArray): Integer;
var
i: Integer;
Dimentions: PRTTIDimensions;
DimTypeInfo: PRTTIOrdinal;
begin
Result := 1;
for i := 0 to ArrType.DimensionsCount - 1 do
begin
Dimentions := PRTTIDimensions(GetTypeInfo(ArrType.Dimensions));
DimTypeInfo := PRTTIOrdinal(GetTypeInfo(Dimentions[i]));
Result := Result * ((DimTypeInfo.HiBound - DimTypeInfo.LoBound) + 1);
end;
end;
var
i, c: Integer;
ElDt: PRTTIType;
Ptr: PByte;
begin
c := GetArrayElementCount(ArrType);
ElDt := GetTypeInfo(ArrType.ElementTypeInfoOffset);
Result := GetMemory(ElDt.DataSize*c);
Ptr := Result;
for i := 1 to c do
begin
Stream.Read(Ptr^, ElDt.DataSize);
Inc(Ptr, ElDt.DataSize);
end;
end;
function TILTranslator.ReadGlobalVarValue(Stream: TStream; const Variable: PILVariable): Pointer;
var
VarType: PRTTIType;
Idx: Integer;
begin
VarType := GetTypeInfo(Variable.RTTI.DataType);
case VarType.DataTypeID of
dtStaticArray: Result := ReadVarStaticArrayValue(Stream, Variable, PRTTIArray(VarType));
dtString, dtAnsiString: begin
Result := GetMemory(VarType.DataSize);
Idx := Stream.ReadStretchUInt();
PNativeInt(Result)^ := FStrLiterals[Idx].Offset;
end;
else
Result := GetMemory(VarType.DataSize);
Stream.Read(Result^, VarType.DataSize);
end;
end;
procedure TILTranslator.ReadILCode(Stream: TStream; Proc: TILProc);
var
i,
ILCount: Integer;
ILCode: TILCode;
Context: TILTContext;
InstrByte, CondByte: UInt8;
StartIMGPosition: Integer;
Condition: TILCondition;
ProcInfo: PRTTIProcedure;
IL: TILInstructions;
ILInstr: PILInstr;
begin
StartIMGPosition := IMG.Position;
ProcInfo := GetProcInfo(Proc.ProcInfo);
ILCode := icRet;
if Assigned(ProcInfo) then
ProcInfo.ADDR := StartIMGPosition;
ILCount := Stream.ReadStretchUInt;
SetLength(IL, ILCount);
FillChar(IL[0], Sizeof(TILInstruction)*ILCount, 0);
Context.PUnit := Proc.ILUnit;
Context.Proc := Proc;
Context.Stream := Stream;
Context.ILCount := ILCount;
{вычитываем IL инструкции и их аргументы}
for i := 0 to ILCount - 1 do begin
InstrByte := Stream.ReadUInt8;
ILCode := TILCode(InstrByte and 127);
if (InstrByte and 128) <> 0 then
CondByte := Stream.ReadUInt8
else
CondByte := 0;
Condition := TILCondition(CondByte and 15);
Context.Cond := Condition;
Context.ILCode := ILCode;
ILInstr := @(IL[i]);
ILInstr.Cond := Condition;
ILInstr.Code := ILCode;
Context.Args := nil;
Context.ILIndex := i;
try
case ILCode of
icNope: Translate_NOPE(Context);
icNeg,
icNot: Read_NOT(Context);
icCmp: Read_CMP(Context);
icCmpJmp: Read_CMPJ(Context);
icTest: Read_TEST(Context);
icCovert: Read_CONVERT(Context);
icCheckBound: Read_CHKBND(Context);
icGetBit: Read_GETBIT(Context);
icSetBit: Read_SETBIT(Context);
icSetBool: Read_SETBOOL(Context);
icMove: Read_MOVE(Context);
icMoveZero: Read_MOVEZERO(Context);
icLea, icLea2: Read_LEA(Context);
icAdd2, icSub2, icMul2, icIntDiv2, icDiv2, icModDiv2,
icAnd2, icOr2, icXor2, icShl2, icShr2, icRol2,
icRor2: begin
{преобразуем двух-адресную в трех-адресную команду}
Context.ILCode := TILCode(Ord(ILCode) - (Ord(icRor2) - Ord(icAdd2) + 1));
Read_2OperandOpCode(Context);
end;
icInc, icDec: Read_INC(Context);
icAdd, icSub, icMul, icIntDiv, icDiv, icModDiv,
icAnd, icOr, icXor, icShl, icShr, icRol, icRor: Read_3OperandOpCode(Context);
icGetPtr: Read_GETPTR(Context);
icGetSelfPtr: Read_GETSPTR(Context);
icLoadMethod: Read_LDMETHOD(Context);
icLoadSelfMethod: Read_LDSMETHOD(Context);
icReadDRef: Read_RDREF(Context);
icWriteDRef: Read_WDREF(Context);
icUnique: Read_UNIQUE(Context);
icArrayDAlloc,
icArrayRAlloc: Read_ARRDALLOC(Context);
icArrayLength: Read_ARRAYLENGTH(Context);
icArrayCopy: Read_ARRAYCOPY(Context);
icMemMove: Read_ARRAYMOVE(Context);
icMemSet: Read_MEMSET(Context);
icTypeInfo: Read_TYPEINFO(Context);
icQueryType: Read_QUERYTYPE(Context);
icRefCount: Read_REFCNT(Context);
icNow: Read_NOW(Context);
icMemGet: Read_MEMGET(Context);
icMemFree: Read_MEMFREE(Context);
icDNewObj: Read_DNEWOBJ(Context);
icTryBegin: Read_TRYBEGIN(Context);
icTryEnd: Read_TRYEND(Context);
icNearCall: Read_NEARCALL(Context);
icEThrow: Read_ETHROW(Context);
icInhtCall: Read_INHT_CALL(Context);
icProcCall, icVirtCall: Read_PCALL(Context);
icUSafeCall: Read_PCALL_UNSAFE(Context);
icInit: Read_INIT(Context);
icIncRef: Read_INCREF(Context);
icDecRef: Read_DECREF(Context);
icDecRefFinal: Read_DECREFFINAL(Context);
icWeakRef: Read_WEAKREF(Context);
icStrongRef: Read_STRONGREF(Context);
icJmp: Read_JMP(Context);
icRet: Read_RET(Context);
icFMacro: Read_FMACRO(Context);
icPlatform:
AbortWork('Platform instructions are not supported by VM');
else
AbortWork('Unknown IL instruction: %s', [GetILCodeName(ILCode)]);
end;
if IncludeDebugInfo then
ILInstr.Line := Stream.ReadStretchUInt;
ILInstr.Args := Context.Args;
except
on e: exception do
raise Exception.CreateFmt('Read IL code ERROR[unit: %s proc: %s; ilcode: %s; illine: %d]: %s',
[Proc.ILUnit.Name, GetProcName(Proc), GetILCodeName(ILCode), i, e.message]);
end;
end;
Proc.IL := IL;
{пролог процедуры}
WriteProcProlog(Proc);
{трансляция IL инструкций}
for i := 0 to ILCount - 1 do
begin
ILInstr := @(IL[i]);
ILCode := ILInstr.Code;
Context.ILIndex := i;
Context.Cond := ILInstr.Cond;
Context.ILCode := ILCode;
Context.Args := ILInstr.Args;
ILInstr.Offset := IMG.Position;
try
BeforeInstruction(Context);
case ILCode of
icNope: Translate_NOPE(Context);
icNeg,
icNot: Translate_NOT(Context, TIL_NOT_ARGS(Context.Args));
icCmp: Translate_CMP(Context, TIL_CMP_ARGS(Context.Args));
icCmpJmp: Translate_CMPJ(Context, TIL_CMP_ARGS(Context.Args));
icTest: Translate_TEST(Context, TIL_CMP_ARGS(Context.Args));
icCovert: Translate_CONVERT(Context, TIL_CONVERT_ARGS(Context.Args));
icCheckBound: Translate_CHKBND(Context, TIL_CHCKBND_ARGS(Context.Args));
icGetBit: Translate_GETBIT(Context, TIL_GETBIT_ARGS(Context.Args));
icSetBit: Translate_SETBIT(Context, TIL_SETBIT_ARGS(Context.Args));
icSetBool: Translate_SETBOOL(Context, TIL_SETBOOL_ARGS(Context.Args));
icMove: Translate_MOVE(Context, TIL_MOVE_ARGS(Context.Args));
icMoveZero: Translate_MOVEZERO(Context, TIL_MOVEZERO_ARGS(Context.Args));
icLea, icLea2: Translate_LEA(Context, TIL_LEA_ARGS(Context.Args));
icAdd2, icSub2, icMul2, icIntDiv2, icDiv2, icModDiv2,
icAnd2, icOr2, icXor2, icShl2, icShr2, icRol2,
icRor2: begin
{преобразуем двух-адресную в трех-адресную команду}
Context.ILCode := TILCode(Ord(ILCode) - (Ord(icRor2) - Ord(icAdd2) + 1));
Translate_2OperandOpCode(Context, TIL_DS_ARGS(Context.Args));
end;
icInc, icDec: Translate_INC(Context, TIL_INC_ARGS(Context.Args));
icAdd, icSub, icMul, icIntDiv, icDiv, icModDiv,
icAnd, icOr, icXor, icShl, icShr, icRol, icRor: Translate_3OperandOpCode(Context, TIL_DSS_ARGS(Context.Args));
icGetPtr: Translate_GETPTR(Context, TIL_GETPTR_ARGS(Context.Args));
icGetSelfPtr: Translate_GETSPTR(Context, TIL_GETSPTR_ARGS(Context.Args));
icLoadMethod: Translate_LDMETHOD(Context, TIL_LDMETHOD_ARGS(Context.Args));
icLoadSelfMethod: Translate_LDSMETHOD(Context, TIL_LDSMETHOD_ARGS(Context.Args));
icReadDRef: Translate_RDREF(Context, TIL_RDREF_ARGS(Context.Args));
icWriteDRef: Translate_WDREF(Context, TIL_WDREF_ARGS(Context.Args));
icUnique: Translate_UNIQUE(Context, TIL_D_ARGS(Context.Args));
icArrayDAlloc,
icArrayRAlloc: Translate_ARRDALLOC(Context, TIL_ARRDALLOC_ARGS(Context.Args));
icArrayLength: Translate_ARRAYLENGTH(Context, TIL_ARRAYLENGTH_ARGS(Context.Args));
icArrayCopy: Translate_ARRAYCOPY(Context, TIL_ARRAYCOPY_ARGS(Context.Args));
icMemMove: Translate_ARRAYMOVE(Context, TIL_ARRAYMOVE_ARGS(Context.Args));
icMemSet: Translate_MEMSET(Context, TIL_MEMSET_ARGS(Context.Args));
icTypeInfo: Translate_TYPEINFO(Context, TIL_TYPEINFO_ARGS(Context.Args));
icQueryType: Translate_QUERYTYPE(Context, TIL_QUERYTYPE_ARGS(Context.Args));
icRefCount: Translate_REFCNT(Context, TIL_DS_ARGS(Context.Args));
icNow: Translate_NOW(Context, TIL_D_ARGS(Context.Args));
icMemGet: Translate_MEMGET(Context, TIL_DNEW_ARGS(Context.Args));
icMemFree: Translate_MEMFREE(Context, TIL_DFREE_ARGS(Context.Args));
icDNewObj: Translate_DNEWOBJ(Context, TIL_DNEWOBJ_ARGS(Context.Args));
icTryBegin: Translate_TRYBEGIN(Context);
icTryEnd: Translate_TRYEND(Context);
icNearCall: Translate_NEARCALL(Context, TIL_D_ARGS(Context.Args));
icEThrow: Translate_ETHROW(Context, TIL_ETHROW_ARGS(Context.Args));
icInhtCall: Translate_PCALL(Context, TIL_PCALL_ARGS(Context.Args));
icProcCall, icVirtCall: Translate_PCALL(Context, TIL_PCALL_ARGS(Context.Args));
icUSafeCall: Translate_PCALL(Context, TIL_PCALL_ARGS(Context.Args));
icInit: Translate_INIT(Context, TIL_INIT_ARGS(Context.Args));
icIncRef: Translate_INCREF(Context, TIL_INCREF_ARGS(Context.Args));
icDecRef: Translate_DECREF(Context, TIL_DECREF_ARGS(Context.Args));
icDecRefFinal: Translate_DECREFFINAL(Context, TIL_DECREFFINAL_ARGS(Context.Args));
icWeakRef: Translate_WEAKREF(Context, TIL_WEAKREF_ARGS(Context.Args));
icStrongRef: Translate_STRONGREF(Context, TIL_STRONGREF_ARGS(Context.Args));
icJmp: Translate_JMP(Context, TIL_JMP_ARGS(Context.Args));
icRet: Translate_RET(Context);
icFMacro: Translate_FMACRO(Context, TIL_FMACRO_ARGS(Context.Args));
icPlatform:
AbortWork('Platform instructions are not supported by VM');
else
AbortWork('Unknown IL instruction: %s', [GetILCodeName(ILCode)]);
end;
AfterInstruction(Context);
except
on e: exception do
raise Exception.CreateFmt('Translate IL code ERROR[unit: %s proc: %s; ilcode: %s; illine: %d]: %s',
[Proc.ILUnit.Name, GetProcName(Proc), GetILCodeName(ILCode), i, e.message]);
end;
end;
// добавляем финальный _RET
WriteProcEpilog(Proc, ILCode);
// размер кода
Proc.CodeSize := IMG.Position - StartIMGPosition;
// корректировка размера стека
PNativeUInt(PByte(GetIMGPtr(StartIMGPosition)) + PTR_SIZE)^ := Proc.GetStackSize;
// Коррекция адресов джампов
CorrectProcJMPOffsets(Proc);
end;
procedure TILTranslator.ReadILFields(ILUnit: TILUnit; Stream: TStream; Struct: PRTTIStruct; ILType: PILType);
var
i, CNT, Idx: Integer;
FieldOffset, FieldSize: Integer;
Prefix: Integer;
Fields: TRTTIFields;
Field: PRTTIField;
TypeInfo: PRTTIType;
Variables: TILVariables;
AbsoluteIndex: Integer;
AbsoluteOffset: Integer;
AVar: PILVariable;
FieldsDataSize: Integer; // общий размер всех полей (с учетом предка)
Ancestor: PRTTIStruct;
begin
{кол-во полей}
CNT := Stream.ReadStretchUInt;
Struct.FieldsCount := CNT;
if CNT > 0 then
begin
// пишем заголовок дин. массива
FRTTI.WriteNativeInt(1); // refcnt
FRTTI.WriteNativeInt(CNT); // len
Struct.Fields := FRTTI.Position;
Fields := TRTTIFields(FRTTI.MemoryPosition);
{выделяем память для RTTI полей}
FRTTI.IncPosition(SizeOf(TRTTIField)*CNT);
FillChar(Fields[0], SizeOf(TRTTIField)*CNT, #0);
SetLength(Variables, CNT);
end else begin
Struct.Fields := 0;
Fields := nil;
end;
if Struct.Ancestor > 0 then
begin
Ancestor := PRTTIStruct(GetTypeInfo(Struct.Ancestor));
FieldsDataSize := Ancestor.DataSize;
if Struct.DataTypeID = dtClass then
FieldOffset := FieldsDataSize - 4*PTR_SIZE
else
FieldOffset := FieldsDataSize;
end else begin
FieldsDataSize := 0;
if Struct.DataTypeID = dtClass then
FieldOffset := -4*PTR_SIZE
else
FieldOffset := 0;
end;
for i := 0 to CNT - 1 do begin
Prefix := Stream.ReadUInt8;
Field := Addr(Fields[i]);
{тип поля}
Field.DataType := ReadVarType(ILUnit, Stream, Prefix);
{absolute индекс}
if (ILVAR_HASINDEX and Prefix) <> 0 then begin
AbsoluteIndex := Stream.ReadStretchUInt;
AbsoluteOffset := Stream.ReadStretchUInt;
end else begin
AbsoluteIndex := -1;
AbsoluteOffset := -1;
end;
{имя поля}
if IncludeDebugInfo then begin
Idx := Stream.ReadStretchUInt;
Field.Name := FStrLiterals[Idx].Offset;
end;
TypeInfo := GetTypeInfo(Field.DataType);
if AbsoluteIndex = -1 then begin
Field.Offset := FieldOffset;
if cDataTypeManaged[TypeInfo.DataTypeID] then
FieldSize := PTR_SIZE
else
FieldSize := TypeInfo.DataSize;
if Struct.TypePacked then
begin
FieldOffset := FieldOffset + FieldSize;
Inc(FieldsDataSize, FieldSize);
end else begin
FieldOffset := FieldOffset + MemAlign(FieldSize);
Inc(FieldsDataSize, MemAlign(FieldSize));
end;
end else begin
AVar := addr(Variables[AbsoluteIndex]);
Field.Offset := AVar.RTTI.Offset;
Variables[i].AbsoluteTo := AVar;
Variables[i].AbsoluteOffset := AbsoluteOffset;
// необходимо правильно расчитать размер структуры, сейчас код работает только если размер absolute поля <= dest поля
end;
Variables[i].Name := GetString(Field.Name);
Variables[i].RTTI := Field^;
end;
Inc(Struct.DataSize, FieldsDataSize);
ILType.Fields := Variables;
end;
procedure TILTranslator.ReadILMethodDecl(ILUnit: TILUnit; Stream: TStream; ProcInfo: PRTTIProcedure);
var
Flags: UInt8;
NameIndex: Integer;
Params: PRTTIParams;
TypeInfo: PRTTIType;
begin
ProcInfo.RefCount := -1;
ProcInfo.FClassID := rttiProc;
Flags := Stream.ReadUInt8;
ProcInfo.Flags := Flags;
{call convention}
ProcInfo.CallConvention := TCallConvention(Stream.ReadUInt8);
{имя процедуры}
if IncludeDebugInfo then
ProcInfo.Name := FStrLiterals[Stream.ReadStretchUInt].Offset;
{импортируемая процедура}
if (Flags and ILPROC_IMPORT) <> 0 then begin
NameIndex := Stream.ReadStretchUInt;
ProcInfo.ImportLib := FStrLiterals[NameIndex].Offset;
NameIndex := Stream.ReadStretchUInt;
ProcInfo.ImportName := FStrLiterals[NameIndex].Offset;
Inc(FImportTableCount);
end;
if (Flags and ILPROC_VIRTUAL) <> 0 then
ProcInfo.VirtualIndex := Stream.ReadStretchUInt
else
ProcInfo.VirtualIndex := -1;
{парметры}
ProcInfo.ParamsCount := Stream.ReadStretchUInt;
if ProcInfo.ParamsCount > 0 then
begin
ProcInfo.Params := FRTTI.Position;
Params := FRTTI.MemoryPosition;
{$IFDEF DEBUG}FillChar(Params^, ProcInfo.ParamsCount*SizeOf(TRttiParameter), #0);{$ENDIF}
FRTTI.IncPosition(ProcInfo.ParamsCount*SizeOf(TRttiParameter));
LoadILParameter(ILUnit, Stream, ProcInfo.ParamsCount, Params);
if (Flags and ILPROC_HASRESULT) > 0 then
begin
ProcInfo.ResultType := Params[0].DataType;
{если структурный value-тип то передаем его по ссылке}
TypeInfo := GetTypeInfo(ProcInfo.ResultType);
if TypeInfo.DataTypeID in [dtRecord, dtGuid, dtStaticArray] then
Params[0].IsReference := True;
end;
end else
ProcInfo.Params := 0;
end;
procedure TILTranslator.ReadILMethodsDecls(ILUnit: TILUnit; Stream: TStream; Struct: PRTTIStruct; var Procedures: TILProcedures);
var
i, MCount: Integer;
Methods: PRTTIProcedures;
Method: PRTTIProcedure;
StructOffset: TOffset;
Proc: TILProc;
begin
MCount := Stream.ReadStretchUInt;
Struct.MethodsCount := MCount;
SetLength(Procedures, MCount);
if MCount > 0 then
begin
Struct.Methods := FRTTIProcs.Position;
Methods := PRTTIProcedures(FRTTIProcs.MemoryPosition);
FRTTIProcs.IncPosition(SizeOf(IL.TypeInfo.TRTTIProcedure)*MCount);
FillChar(Methods^, SizeOf(IL.TypeInfo.TRTTIProcedure)*MCount, #0);
StructOffset := GetOffset(FRTTI.Memory, Struct);
for i := 0 to MCount - 1 do begin
Method := addr(Methods[i]);
Proc := CreateILUnitProc(ILUnit);
Procedures[i] := Proc;
Method.StructInfo := StructOffset;
ReadILMethodDecl(ILUnit, Stream, Method);
Proc.ILUnit := ILUnit;
Proc.IsIntfMethod := Assigned(Struct) and (Struct.DataTypeID = dtInterface);
if Assigned(Struct) then
Proc.Struct := GetILType(ILUnit.Index, Struct.Index);
{копируем необходимые поля в структру TILProc}
RTTIProcToILProc(Method, Proc);
if (Struct.ImportLib > 0) or (Proc.ImportLib > 0) then
MapImportMethod(Struct, Proc);
end;
end else
Struct.Methods := 0;
end;
procedure TILTranslator.ReadImportInfo(Stream: TStream; TypeInfo: PRTTIType);
var
Index: Integer;
begin
Index := Stream.ReadStretchUInt;
TypeInfo.ImportLib := FStrLiterals[Index].Offset;
Index := Stream.ReadStretchUInt;
TypeInfo.ImportName := FStrLiterals[Index].Offset;
end;
procedure TILTranslator.ReadIntfTypeInfo(var Context: TReadTypeContext);
var
Flags: UInt8;
Procs: TILProcedures;
i, FieldsCount: Integer;
ARTTI: PRTTIInterface;
StartMethodIdx: Integer;
Result: PRTTIInterface;
begin
Result := PRTTIInterface(GetTypeInfo(Context.ILType.Offset));
with Context do begin
Flags := Stream.ReadUInt8;
if (Flags and 1) = 1 then //STRUCT_HAS_ANCESTOR
begin
Result.Ancestor := ReadTypeSpecInfo(Stream);
ARTTI := PRTTIInterface(GetTypeInfo(Result.Ancestor));
StartMethodIdx := ARTTI.MethodsCount;
Result.TotalMethodsCount := ARTTI.TotalMethodsCount;
end else begin
Result.Ancestor := 0;
StartMethodIdx := 0;
Result.TotalMethodsCount := 0;
end;
Result.TotalFieldsCount := 0;
if (Flags and 2) = 2 then //STRUCT_IMPORT
begin
ReadImportInfo(Stream, Result);
// MapImportType(Result);
end else begin
Result.ImportLib := 0;
Result.ImportName := 0;
end;
Result.DataTypeID := dtInterface;
Result.DataSize := PTR_SIZE;
FieldsCount := Stream.ReadStretchUInt;
Assert(FieldsCount = 0); // кол-во полей, для интерфейса всегда ноль!
ReadILMethodsDecls(ILUnit, Stream, Result, Procs);
ILType.Methods := Procs;
Inc(Result.TotalMethodsCount, Length(Procs));
for i := 0 to Length(Procs) - 1 do
Procs[i].Offset := StartMethodIdx + i;
// читаем GUID
Result.GUID := Stream.ReadGuid();
end;
end;
procedure TILTranslator.ReadOrdinalTypeInfo(var Context: TReadTypeContext);
var
Result: PRTTIOrdinal;
begin
with Context do begin
Result := PRTTIOrdinal(GetTypeInfo(Context.ILType.Offset));
Result.DataTypeID := ILType.ID;
Result.Signed := Stream.ReadBoolean;
Result.LoBound := Stream.ReadInt64;
Result.HiBound := Stream.ReadInt64;
Result.DataSize := GetRangeByteSize(Result.HiBound, Result.LoBound);
end;
end;
procedure TILTranslator.ReadPointerType(var Context: TReadTypeContext);
var
Result: PRTTIPointer;
begin
with Context do begin
Result := PRTTIPointer(GetTypeInfo(Context.ILType.Offset));
Result.DataTypeID := dtPointer;
Result.DataSize := PTR_SIZE;
Result.RefTypeInfoOffset := ReadTypeSpecInfo(Stream);
end;
end;
procedure TILTranslator.ReadProcTypeInfo(var Context: TReadTypeContext);
type
TFlags = set of (ProcHasResult, ProcStatic);
var
c: Integer;
Flags: Byte;
Params: PRTTIParams;
Result: PRTTIProcType;
begin
with Context do begin
Result := PRTTIProcType(GetTypeInfo(Context.ILType.Offset));
Result.DataTypeID := dtProcType;
{флаги}
Flags := Stream.ReadStretchUInt;
Result.ProcStatic := (ProcStatic in TFlags(Flags));
if Result.ProcStatic then
Result.DataSize := PTR_SIZE
else
Result.DataSize := PTR_SIZE*2;
{параметры}
c := Stream.ReadStretchUInt;
Result.ParamsCount := c;
Result.Params := FRTTI.Position;
FRTTI.IncPosition(c*SizeOf(TRTTIParameter));
Params := PRTTIParams(GetTypeInfo(Result.Params));
FillChar(Params^, c*SizeOf(TRTTIParameter), #0);
LoadILParameter(ILUnit, Stream, c, Params);
if Check(Flags, ILPROC_HASRESULT) then
Result.ResultType := Params[0].DataType;
end;
end;
procedure TILTranslator.ReadRecordTypeInfo(var Context: TReadTypeContext);
var
Ancestor: PRTTIStruct;
Flags: UInt8;
Procs: TILProcedures;
Result: PRTTIRecord;
begin
Result := PRTTIRecord(GetTypeInfo(Context.ILType.Offset));
Result.DataTypeID := dtRecord;
with Context do begin
Flags := Stream.ReadUInt8;
if (Flags and ILTYPE_HAS_ANCESTOR) <> 0 then begin
Result.Ancestor := ReadTypeSpecInfo(Stream);
Ancestor := PRTTIStruct(GetTypeInfo(Result.Ancestor));
Result.DataSize := Ancestor.DataSize;
Result.TotalMethodsCount := Ancestor.TotalMethodsCount;
Result.TotalFieldsCount := Ancestor.TotalFieldsCount;
end else begin
Result.Ancestor := 0;
Result.TotalMethodsCount := 0;
Result.TotalFieldsCount := 0;
end;
if (Flags and ILTYPE_IMPORT) <> 0 then //STRUCT_IMPORT
begin
ReadImportInfo(Stream, Result);
end else begin
Result.ImportLib := 0;
Result.ImportName := 0;
end;
Result.TypePacked := (Flags and ILTYPE_PACKED) <> 0;
{загрузка полей}
ReadILFields(ILUnit, Stream, Result, ILType);
Inc(Result.TotalFieldsCount, Length(ILType.Fields));
{загрузка методов}
ReadILMethodsDecls(ILUnit, Stream, Result, Procs);
Inc(Result.TotalMethodsCount, Length(Procs));
ILType.Methods := Procs;
end;
end;
procedure TILTranslator.ReadSetTypeInfo(var Context: TReadTypeContext);
var
DimInfoOffset: TOffset;
DimInfo: PRTTIOrdinal;
BitsCount: Integer;
Result: PRTTISet;
begin
with Context do begin
Result := PRTTISet(GetTypeInfo(Context.ILType.Offset));
Result.DataTypeID := dtSet;
Result.DimensionsCount := 1;
Result.ElementTypeInfoOffset := 0; // bit
DimInfoOffset := ReadTypeSpecInfo(Stream);
Result.Dimensions := DimInfoOffset;
DimInfo := PRTTIOrdinal(GetTypeInfo(DimInfoOffset));
// вычисляем размер сета
BitsCount := Int64(DimInfo.HiBound) - DimInfo.LoBound + 1;
Result.DataSize := (BitsCount div 8) + ifthen((BitsCount mod 8) <> 0, 1, 0);
end;
end;
function TILTranslator.ReadTypeSpecInfo(Stream: TStream): TOffset;
var
UnitIdx,
TypeIdx: Integer;
U: TILUnit;
begin
TypeIdx := Stream.ReadStretchUInt;
if TypeIdx < TSystemTypes.Count then
Exit(FSystemTypes[TypeIdx].Offset);
UnitIdx := Stream.ReadStretchUInt;
U := FUnits[UnitIdx];
Result := U.Types[TypeIdx - TSystemTypes.Count].Offset;
end;
function TILTranslator.ReadVarType(ILUnit: TILUnit; Stream: TStream; VarFlags: Integer): TOffset;
var
UnitIdx,
TypeIdx: Integer;
U: TILUnit;
begin
if (VarFlags and ILVAR_UNITTYPE) <> 0 then
begin
UnitIdx := Stream.ReadStretchUInt;
U := FUnits[UnitIdx];
end else
U := ILUnit;
TypeIdx := Stream.ReadStretchUInt;
if TypeIdx < TSystemTypes.Count then
Exit(FSystemTypes[TypeIdx].Offset);
TypeIdx := TypeIdx - TSystemTypes.Count;
if TypeIdx < Length(U.Types) then
Result := U.Types[TypeIdx].Offset
else begin
AbortWork('Ivalid type index[unit: %s]: %d', [ILUnit.Name, TypeIdx]);
Result := 0;
end;
end;
procedure TILTranslator.ReadWeakRefType(var Context: TReadTypeContext);
var
Result: PRTTIPointer;
begin
with Context do begin
Result := PRTTIPointer(GetTypeInfo(Context.ILType.Offset));
Result.DataTypeID := dtWeakRef;
Result.DataSize := PTR_SIZE;
Result.RefTypeInfoOffset := ReadTypeSpecInfo(Stream);
end;
end;
procedure TILTranslator.Read_2OperandOpCode(var Ctx: TILTContext);
var
Args: TIL_DS_Args;
begin
Args := TIL_DS_Args.Create;
// приемник (он же источник 1)
LoadILArgument(Ctx, Args.D);
// источник 2
LoadILArgument(Ctx, Args.S);
Ctx.Args := Args;
end;
procedure TILTranslator.Read_3OperandOpCode(var Ctx: TILTContext);
var
Args: TIL_DSS_Args;
begin
Args := TIL_DSS_Args.Create;
LoadILArgument(Ctx, Args.D); // приемник
LoadILArgument(Ctx, Args.L); // источник 1
LoadILArgument(Ctx, Args.R); // источник 2
Ctx.Args := Args;
end;
procedure TILTranslator.Read_ARRAYCOPY(var Ctx: TILTContext);
var
Args: TIL_ARRAYCOPY_ARGS;
begin
Args := TIL_ARRAYCOPY_ARGS.Create;
LoadILArgument(Ctx, Args.D); // dst
LoadILArgument(Ctx, Args.S); // src
LoadILArgument(Ctx, Args.F); // from
LoadILArgument(Ctx, Args.L); // length
Ctx.Args := Args;
end;
procedure TILTranslator.Read_ARRAYLENGTH(var Ctx: TILTContext);
var
Args: TIL_ARRAYLENGTH_ARGS;
begin
Args := TIL_ARRAYLENGTH_ARGS.Create;
LoadILArgument(Ctx, Args.D);
LoadILArgument(Ctx, Args.S);
Ctx.Args := Args;
end;
procedure TILTranslator.Read_ARRAYMOVE(var Ctx: TILTContext);
var
Args: TIL_ARRAYMOVE_ARGS;
begin
Args := TIL_ARRAYMOVE_ARGS.Create;
LoadILArgument(Ctx, Args.SrcArr);
LoadILArgument(Ctx, Args.SrcIdx);
LoadILArgument(Ctx, Args.DstArr);
LoadILArgument(Ctx, Args.DstIdx);
LoadILArgument(Ctx, Args.Cnt);
Ctx.Args := Args;
end;
procedure TILTranslator.Read_ARRDALLOC(var Ctx: TILTContext);
var
Args: TIL_ARRDALLOC_ARGS;
begin
Args := TIL_ARRDALLOC_ARGS.Create;
LoadILArgument(Ctx, Args.D); // dest
LoadILArgument(Ctx, Args.S); // length
Ctx.Args := Args;
end;
procedure TILTranslator.Read_CHKBND(var Ctx: TILTContext);
var
Args: TIL_CHCKBND_ARGS;
begin
Args := TIL_CHCKBND_ARGS.Create;
LoadILArgument(Ctx, Args.AArray);
LoadILArgument(Ctx, Args.AIndex);
Ctx.Args := Args;
end;
procedure TILTranslator.Read_CMP(var Ctx: TILTContext);
var
Args: TIL_CMP_ARGS;
begin
Args := TIL_CMP_ARGS.Create;
LoadILArgument(Ctx, Args.L);
LoadILArgument(Ctx, Args.R);
Ctx.Args := Args;
end;
procedure TILTranslator.Read_CMPJ(var Ctx: TILTContext);
var
Args: TIL_CMPJ_ARGS;
begin
Args := TIL_CMPJ_ARGS.Create;
LoadILArgument(Ctx, Args.L);
LoadILArgument(Ctx, Args.R);
//LoadILArgument(Ctx, Args.D);
// todo
Ctx.Args := Args;
end;
procedure TILTranslator.Read_CONVERT(var Ctx: TILTContext);
var
Args: TIL_CONVERT_ARGS;
begin
Args := TIL_CONVERT_ARGS.Create;
LoadILArgument(Ctx, Args.D);
LoadILArgument(Ctx, Args.S);
Ctx.Args := Args;
end;
procedure TILTranslator.Read_DECREF(var Ctx: TILTContext);
var
Args: TIL_DECREF_ARGS;
begin
Args := TIL_DECREF_ARGS.Create;
LoadILArgument(Ctx, Args.D);
Ctx.Args := Args;
end;
procedure TILTranslator.Read_DECREFFINAL(var Ctx: TILTContext);
var
Args: TIL_DECREFFINAL_ARGS;
TypeInfo: PRTTIType;
begin
Args := TIL_DECREFFINAL_ARGS.Create;
// загружаем первый аргумент - переменную
LoadILArgument(Ctx, Args.Dst);
TypeInfo := GetTypeInfo(Args.Dst);
Assert(Args.Dst.ArgClass = ARG_VAR);
// загружаем аргумет - процедуру/метод финализации
if TypeInfo.DataTypeID = dtClass then
LoadILArgumentInternal(Ctx, Args.FinalProc, Args.Dst)
else
LoadILArgument(Ctx, Args.FinalProc);
Ctx.Args := Args;
end;
procedure TILTranslator.Read_MEMFREE(var Ctx: TILTContext);
var
Args: TIL_DFREE_ARGS;
begin
Args := TIL_DFREE_ARGS.Create;
LoadILArgument(Ctx, Args.D);
Ctx.Args := Args;
end;
procedure TILTranslator.Read_MEMGET(var Ctx: TILTContext);
var
Args: TIL_DNEW_ARGS;
begin
Args := TIL_DNEW_ARGS.Create;
LoadILArgument(Ctx, Args.D);
Ctx.Args := Args;
end;
procedure TILTranslator.Read_DNEWOBJ(var Ctx: TILTContext);
var
Args: TIL_DNEWOBJ_ARGS;
begin
Args := TIL_DNEWOBJ_ARGS.Create;
LoadILArgument(Ctx, Args.S);
LoadILArgument(Ctx, Args.D);
Ctx.Args := Args;
end;
procedure TILTranslator.Read_ETHROW(var Ctx: TILTContext);
var
Args: TIL_ETHROW_ARGS;
begin
Args := TIL_ETHROW_ARGS.Create;
LoadILArgument(Ctx, Args.D);
Ctx.Args := Args;
end;
procedure TILTranslator.Read_FMACRO(var Ctx: TILTContext);
var
Args: TIL_FMACRO_ARGS;
begin
Args := TIL_FMACRO_ARGS.Create;
LoadILArgument(Ctx, Args.D);
LoadILArgument(Ctx, Args.M);
Ctx.Args := Args;
end;
procedure TILTranslator.Read_GETBIT(var Ctx: TILTContext);
var
Args: TIL_GETBIT_ARGS;
begin
Args := TIL_GETBIT_ARGS.Create;
LoadILArgument(Ctx, Args.Dst);
LoadILArgument(Ctx, Args.BitArray);
LoadILArgument(Ctx, Args.BitIndex);
Ctx.Args := Args;
end;
procedure TILTranslator.Read_GETPTR(var Ctx: TILTContext);
var
Args: TIL_GETPTR_ARGS;
begin
Args := TIL_GETPTR_ARGS.Create;
LoadILArgument(Ctx, Args.D);
LoadILArgumentInternal(Ctx, Args.S, nil);
Ctx.Args := Args;
end;
procedure TILTranslator.Read_GETSPTR(var Ctx: TILTContext);
var
Args: TIL_GETSPTR_ARGS;
begin
Args := TIL_GETSPTR_ARGS.Create;
LoadILArgument(Ctx, Args.D);
Args.B := ArgGet();
Args.B.ArgClass := ARG_VAR;
Args.B.ArgScope := ARG_SCOPE_LOCAL;
if Ctx.Proc.ProcType = ptProcedure then
Args.B.AsVariable := Addr(Ctx.Proc.Vars[0])
else
Args.B.AsVariable := Addr(Ctx.Proc.Vars[1]);
Args.B.TypeInfo := Args.B.AsVariable.RTTI.DataType;
if Args.B.AsVariable.RTTI.IsReference then
Args.B.ArgumentType := atReference
else
Args.B.ArgumentType := atLocal;
LoadILArgumentInternal(Ctx, Args.S, Args.B);
Args.B.Next := Args.S;
Ctx.Args := Args;
end;
procedure TILTranslator.Read_INC(var Ctx: TILTContext);
var
Args: TIL_INC_ARGS;
begin
Args := TIL_INC_ARGS.Create;
LoadILArgument(Ctx, Args.D);
Ctx.Args := Args;
end;
procedure TILTranslator.Read_INCREF(var Ctx: TILTContext);
var
Args: TIL_INCREF_ARGS;
begin
Args := TIL_INCREF_ARGS.Create;
LoadILArgument(Ctx, Args.D);
Ctx.Args := Args;
end;
procedure TILTranslator.Read_INHT_CALL(var Ctx: TILTContext);
var
Args: TIL_PCALL_ARGS;
MethodIdx, i, Cnt: Integer;
Struct: PRTTIStruct;
IMGType: ^TIMGType;
M: TILMethod;
TypeArg: TILArgument;
SelfArg: TILArgument;
begin
Args := TIL_PCALL_ARGS.Create;
LoadILArgument(Ctx, TypeArg);
Struct := PRTTIStruct(TypeArg.AsTypeInfo);
IMGType := addr(FUnits[Struct.UnitID].Types[Struct.Index]);
Assert(Struct.DataTypeID = dtClass);
MethodIdx := Ctx.Stream.ReadStretchUInt;
LoadILArgumentInternal(Ctx, SelfArg, nil);
Args.PArg := ArgGet();
Args.PArg.ArgumentType := atImmConst;
Args.PArg.ArgClass := ARG_METHOD;
Args.PArg.ArgScope := ARG_SCOPE_STRUCT;
M.Self := SelfArg;
M.Proc := IMGType.Methods[MethodIdx];
Args.PArg.AsMethod := M;
// читаем аргументы вызова
cnt := Ctx.Stream.ReadStretchUInt;
SetLength(Args.CallArgs, cnt);
for i := 0 to cnt - 1 do
LoadILArgument(Ctx, Args.CallArgs[i]);
Ctx.Args := Args;
end;
procedure TILTranslator.Read_INIT(var Ctx: TILTContext);
var
Args: TIL_INIT_ARGS;
begin
Args := TIL_INIT_ARGS.Create;
LoadILArgument(Ctx, Args.D);
Ctx.Args := Args;
end;
procedure TILTranslator.Read_JMP(var Ctx: TILTContext);
var
Args: TIL_JMP_ARGS;
begin
Args := TIL_JMP_ARGS.Create;
LoadILArgument(Ctx, Args.D);
Ctx.Args := Args;
end;
procedure TILTranslator.Read_LDMETHOD(var Ctx: TILTContext);
var
Args: TIL_LDMETHOD_ARGS;
begin
Args := TIL_LDMETHOD_ARGS.Create;
LoadILArgument(Ctx, Args.D);
LoadILArgumentInternal(Ctx, Args.S, nil);
Ctx.Args := Args;
end;
procedure TILTranslator.Read_LDSMETHOD(var Ctx: TILTContext);
var
Args: TIL_LDSMETHOD_ARGS;
begin
Args := TIL_LDSMETHOD_ARGS.Create;
LoadILArgument(Ctx, Args.D);
Args.B := ArgGet();
Args.B.ArgClass := ARG_VAR;
Args.B.ArgScope := ARG_SCOPE_LOCAL;
if Ctx.Proc.ProcType = ptProcedure then
Args.B.AsVariable := Addr(Ctx.Proc.Vars[0])
else
Args.B.AsVariable := Addr(Ctx.Proc.Vars[1]);
Args.B.TypeInfo := Args.B.AsVariable.RTTI.DataType;
if Args.B.AsVariable.RTTI.IsReference then
Args.B.ArgumentType := atReference
else
Args.B.ArgumentType := atLocal;
LoadILArgumentInternal(Ctx, Args.S, Args.B);
Args.B.Next := Args.S;
Ctx.Args := Args;
end;
procedure TILTranslator.Read_LEA(var Ctx: TILTContext);
var
Args: TIL_LEA_Args;
begin
Args := TIL_LEA_Args.Create;
LoadILArgument(Ctx, Args.D); // приемник
LoadILArgument(Ctx, Args.B); // база
if Ctx.ILCode = icLea then
LoadILArgument(Ctx, Args.Offset); // смещение
Ctx.Args := Args;
end;
procedure TILTranslator.Read_MEMSET(var Ctx: TILTContext);
var
Args: TIL_MEMSET_ARGS;
begin
Args := TIL_MEMSET_ARGS.Create;
LoadILArgument(Ctx, Args.Dst);
LoadILArgument(Ctx, Args.Bpt);
Ctx.Args := Args;
end;
procedure TILTranslator.Read_MOVE(var Ctx: TILTContext);
var
Args: TIL_MOVE_ARGS;
begin
Args := TIL_MOVE_ARGS.Create;
LoadILArgument(Ctx, Args.D);
LoadILArgument(Ctx, Args.S);
Ctx.Args := Args;
end;
procedure TILTranslator.Read_MOVEZERO(var Ctx: TILTContext);
var
Args: TIL_MOVEZERO_ARGS;
begin
Args := TIL_MOVEZERO_ARGS.Create;
LoadILArgument(Ctx, Args.D);
Ctx.Args := Args;
end;
procedure TILTranslator.Read_NEARCALL(var Ctx: TILTContext);
var
Args: TIL_NEARCALL_ARGS;
begin
Args := TIL_NEARCALL_ARGS.Create;
LoadILArgument(Ctx, Args.D);
Ctx.Args := Args;
end;
procedure TILTranslator.Read_NOT(var Ctx: TILTContext);
var
Args: TIL_NOT_ARGS;
begin
Args := TIL_NOT_ARGS.Create;
LoadILArgument(Ctx, Args.D);
LoadILArgument(Ctx, Args.S);
Ctx.Args := Args;
end;
procedure TILTranslator.Read_NOW(var Ctx: TILTContext);
var
Args: TIL_D_Args;
begin
Args := TIL_D_Args.Create;
LoadILArgument(Ctx, Args.D);
Ctx.Args := Args;
end;
procedure TILTranslator.Read_PCALL(var Ctx: TILTContext);
var
Args: TIL_PCALL_ARGS;
i, cnt: Integer;
PArg: TILArgument;
begin
Args := TIL_PCALL_ARGS.Create;
LoadILArgumentInternal(Ctx, PArg, nil);
if Assigned(PArg.Next) then
Args.PArg := PArg.Next
else
Args.PArg := PArg;
// читаем аргументы вызова
cnt := Ctx.Stream.ReadStretchUInt;
SetLength(Args.CallArgs, cnt);
for i := 0 to cnt - 1 do
LoadILArgument(Ctx, Args.CallArgs[i]);
Ctx.Args := Args;
end;
procedure TILTranslator.Read_PCALL_UNSAFE(var Ctx: TILTContext);
var
Args: TIL_PCALL_ARGS;
i, cnt: Integer;
PArg, TArg: TILArgument;
begin
Args := TIL_PCALL_ARGS.Create;
LoadILArgumentInternal(Ctx, PArg, nil);
LoadILArgumentInternal(Ctx, TArg, nil);
PArg.TypeInfo := TArg.TypeInfo;
Args.PArg := PArg;
// читаем аргументы вызова
cnt := Ctx.Stream.ReadStretchUInt;
SetLength(Args.CallArgs, cnt);
for i := 0 to cnt - 1 do
LoadILArgument(Ctx, Args.CallArgs[i]);
Ctx.Args := Args;
end;
procedure TILTranslator.Read_QUERYTYPE(var Ctx: TILTContext);
var
Args: TIL_QUERYTYPE_ARGS;
begin
Args := TIL_QUERYTYPE_ARGS.Create;
LoadILArgument(Ctx, Args.D);
LoadILArgument(Ctx, Args.L);
LoadILArgument(Ctx, Args.R);
Ctx.Args := Args;
end;
procedure TILTranslator.Read_RDREF(var Ctx: TILTContext);
var
Args: TIL_RDREF_ARGS;
begin
Args := TIL_RDREF_ARGS.Create;
LoadILArgument(Ctx, Args.D);
LoadILArgument(Ctx, Args.S);
Ctx.Args := Args;
end;
procedure TILTranslator.Read_REFCNT(var Ctx: TILTContext);
var
Args: TIL_DS_Args;
begin
Args := TIL_DS_Args.Create;
LoadILArgument(Ctx, Args.D);
LoadILArgument(Ctx, Args.S);
Ctx.Args := Args;
end;
procedure TILTranslator.Read_RET(var Ctx: TILTContext);
begin
Ctx.Args := nil;
end;
procedure TILTranslator.Read_SETBIT(var Ctx: TILTContext);
var
Args: TIL_SETBIT_ARGS;
begin
Args := TIL_SETBIT_ARGS.Create;
LoadILArgument(Ctx, Args.Dst);
LoadILArgument(Ctx, Args.BitIndex);
LoadILArgument(Ctx, Args.BitValue);
Ctx.Args := Args;
end;
procedure TILTranslator.Read_SETBOOL(var Ctx: TILTContext);
var
Args: TIL_SETBOOL_ARGS;
begin
Args := TIL_SETBOOL_ARGS.Create;
LoadILArgument(Ctx, Args.D);
Ctx.Args := Args;
end;
procedure TILTranslator.Read_STRONGREF(var Ctx: TILTContext);
var
Args: TIL_STRONGREF_ARGS;
begin
Args := TIL_STRONGREF_ARGS.Create;
LoadILArgument(Ctx, Args.D);
LoadILArgument(Ctx, Args.S);
Ctx.Args := Args;
end;
procedure TILTranslator.Read_TEST(var Ctx: TILTContext);
var
Args: TIL_TEST_ARGS;
begin
Args := TIL_TEST_ARGS.Create;
LoadILArgument(Ctx, Args.L);
LoadILArgument(Ctx, Args.R);
Ctx.Args := Args;
end;
procedure TILTranslator.Read_TRYBEGIN(var Ctx: TILTContext);
var
A: TILArgument;
begin
LoadILArgument(Ctx, A);
Translate_TRYBEGIN(Ctx);
end;
procedure TILTranslator.Read_TRYEND(var Ctx: TILTContext);
var
A: TILArgument;
begin
LoadILArgument(Ctx, A);
Translate_TRYEND(Ctx);
end;
procedure TILTranslator.Read_TYPEINFO(var Ctx: TILTContext);
var
Args: TIL_TYPEINFO_ARGS;
begin
Args := TIL_TYPEINFO_ARGS.Create;
LoadILArgument(Ctx, Args.D);
LoadILArgument(Ctx, Args.S);
Ctx.Args := Args;
end;
procedure TILTranslator.Read_UNIQUE(var Ctx: TILTContext);
var
Args: TIL_D_Args;
begin
Args := TIL_D_Args.Create;
LoadILArgument(Ctx, Args.D);
Ctx.Args := Args;
end;
procedure TILTranslator.Read_WDREF(var Ctx: TILTContext);
var
Args: TIL_WDREF_ARGS;
begin
Args := TIL_WDREF_ARGS.Create;
LoadILArgument(Ctx, Args.D);
LoadILArgument(Ctx, Args.S);
Ctx.Args := Args;
end;
procedure TILTranslator.Read_WEAKREF(var Ctx: TILTContext);
var
Args: TIL_WEAKREF_ARGS;
begin
Args := TIL_WEAKREF_ARGS.Create;
LoadILArgument(Ctx, Args.D);
LoadILArgument(Ctx, Args.S);
Ctx.Args := Args;
end;
procedure TILTranslator.RTTIProcToILProc(RTTIProc: PRTTIProcedure; Proc: TILProc);
var
RTTIParams: PRTTIParams;
begin
Proc.ProcInfo := GetOffset(FRTTIProcs.Memory, RTTIProc);
SetLength(Proc.Params, RTTIProc.ParamsCount);
if RTTIProc.ParamsCount > 0 then
begin
RTTIParams := PRTTIParams(GetTypeInfo(RTTIProc.Params));
Move(RTTIParams[0], Proc.Params[0], SizeOf(TRttiParameter)*RTTIProc.ParamsCount);
end;
Proc.Flags := RTTIProc.Flags;
Proc.Name := GetString(RTTIProc.Name);
if RTTIProc.ResultType <> 0 then
Proc.ProcType := ptFunction
else
Proc.ProcType := ptProcedure;
Proc.VirtualIndex := RTTIProc.VirtualIndex;
Proc.ImportLib := RTTIProc.ImportLib;
Proc.ImportName := RTTIProc.ImportName;
Proc.CallConvention := RTTIProc.CallConvention;
{экспортируемая процедура}
if Check(RTTIProc.Flags, ILPROC_EXPORT) then
begin
Proc.ExportIndex := Proc.ILUnit.ExportProcsCount;
Inc(Proc.ILUnit.ExportProcsCount);
end else begin
Proc.ExportIndex := -1;
end;
end;
procedure TILTranslator.SaveTargetCode(const Path: string);
var
Stream: TFileStream;
begin
Stream := TFileStream.Create(Path, fmCreate);
try
SaveTargetCode(Stream);
finally
Stream.Free;
end;
end;
procedure TILTranslator.SetRTTICharset(const Value: TRTTICharset);
begin
FRTTICharset := Value;
end;
procedure TILTranslator.SetSystemTypesOffsets(Types: PSystemTypes; Offsets: TIMGTypes);
var
B: Pointer;
off: UInt32;
begin
B := Types;
off := SizeOf(UInt32); // RTTI signature
Offsets[Ord(dtInt8)].Offset := off + GetOffset(B, @Types._Int8);
Offsets[Ord(dtInt8)].ID := dtInt8;
Offsets[Ord(dtInt16)].Offset := off + GetOffset(B, @Types._Int16);
Offsets[Ord(dtInt16)].ID := dtInt16;
Offsets[Ord(dtInt32)].Offset := off + GetOffset(B, @Types._Int32);
Offsets[Ord(dtInt32)].ID := dtInt32;
Offsets[Ord(dtInt64)].Offset := off + GetOffset(B, @Types._Int64);
Offsets[Ord(dtInt64)].ID := dtInt64;
Offsets[Ord(dtUInt8)].Offset := off + GetOffset(B, @Types._UInt8);
Offsets[Ord(dtUInt8)].ID := dtUInt8;
Offsets[Ord(dtUInt16)].Offset := off + GetOffset(B, @Types._UInt16);
Offsets[Ord(dtUInt16)].ID := dtUInt16;
Offsets[Ord(dtUInt32)].Offset := off + GetOffset(B, @Types._UInt32);
Offsets[Ord(dtUInt32)].ID := dtUInt32;
Offsets[Ord(dtUInt64)].Offset := off + GetOffset(B, @Types._UInt64);
Offsets[Ord(dtUInt64)].ID := dtUInt64;
Offsets[Ord(dtNativeInt)].Offset := off + GetOffset(B, @Types._NativeInt);
Offsets[Ord(dtNativeInt)].ID := dtNativeInt;
Offsets[Ord(dtNativeUInt)].Offset := off + GetOffset(B, @Types._NativeUInt);
Offsets[Ord(dtNativeUInt)].ID := dtNativeUInt;
Offsets[Ord(dtFloat32)].Offset := off + GetOffset(B, @Types._Float32);
Offsets[Ord(dtFloat32)].ID := dtFloat32;
Offsets[Ord(dtFloat64)].Offset := off + GetOffset(B, @Types._Float64);
Offsets[Ord(dtFloat64)].ID := dtFloat64;
Offsets[Ord(dtBoolean)].Offset := off + GetOffset(B, @Types._Boolean);
Offsets[Ord(dtBoolean)].ID := dtBoolean;
Offsets[Ord(dtAnsiChar)].Offset := off + GetOffset(B, @Types._AnsiChar);
Offsets[Ord(dtAnsiChar)].ID := dtAnsiChar;
Offsets[Ord(dtChar)].Offset := off + GetOffset(B, @Types._Char);
Offsets[Ord(dtChar)].ID := dtChar;
Offsets[Ord(dtAnsiString)].Offset := off + GetOffset(B, @Types._AnsiString);
Offsets[Ord(dtAnsiString)].ID := dtAnsiString;
Offsets[Ord(dtString)].Offset := off + GetOffset(B, @Types._String);
Offsets[Ord(dtString)].ID := dtString;
Offsets[Ord(dtVariant)].Offset := off + GetOffset(B, @Types._Variant);
Offsets[Ord(dtVariant)].ID := dtVariant;
Offsets[Ord(dtGuid)].Offset := off + GetOffset(B, @Types._GUID);
Offsets[Ord(dtGuid)].ID := dtGuid;
Offsets[Ord(dtPointer)].Offset := off + GetOffset(B, @Types._Pointer);
Offsets[Ord(dtPointer)].ID := dtPointer;
end;
procedure TILTranslator.WriteILUnitEpilog(Stream: TStream; ILUnit: TILUnit);
begin
if (ILUnit.Flags and ILUNIT_HASFINAL) = 0 then
Exit;
ILUnit.FinalProc.ILUnit := ILUnit;
ILUnit.FinalProc.Name := '$finalization';
ILUnit.FinalProc.ProcType := ptProcedure;
LoadILProcBody(Stream, ILUnit.FinalProc);
ILUnit.VMUnit.FinalProc := ILUnit.FinalProc.Offset;
end;
procedure TILTranslator.WriteILUnitProlog(Stream: TStream; ILUnit: TILUnit);
begin
if (ILUnit.Flags and ILUNIT_HASINIT) = 0 then
Exit;
ILUnit.InitProc.ILUnit := ILUnit;
ILUnit.InitProc.Name := '$initialization';
ILUnit.InitProc.ProcType := ptProcedure;
LoadILProcBody(Stream, ILUnit.InitProc);
ILUnit.VMUnit.InitProc := ILUnit.InitProc.Offset;
end;
procedure TILTranslator.WriteProcEpilog(Proc: TILProc; LastILCode: TILCode);
begin
end;
procedure TILTranslator.WriteProcProlog(Proc: TILProc);
begin
end;
procedure TILTranslator.WriteProcsRTTI(ILUnit: TILUnit);
begin
end;
procedure TILTranslator.WriteUnitsRTTIArray(UnitsCount: Integer);
begin
end;
procedure TILTranslator.WriteVMExportProcs(ILUnit: TILUnit);
begin
end;
function TILTranslator.PassByRef(const Param: PRTTIParameter): Boolean;
var
ti: PRTTIType;
begin
Result := Param.IsReference;
if not Result and Param.IsConstant then
begin
ti := GetTypeInfo(Param.DataType);
Result := ti.DataTypeID in [dtStaticArray, dtRecord, dtGuid, dtVariant];
end;
end;
function TILTranslator.PrepareCALLInfo(const ProcArg: TILArgument; out ParamsCount: Integer; out Params: PRTTIParams;
out ResultType: PRTTIType; out ADDR: NativeUInt): TCallType;
var
TypeInfo: PRTTIType;
Proc: TILProc;
Struct: PRTTIType;
begin
if ProcArg.ArgClass = ARG_VAR then
begin
{косвенный вызов через переменная процедурного типа}
TypeInfo := GetTypeInfo(ProcArg.TypeInfo);
Assert(TypeInfo.DataTypeID = dtProcType);
Params := PRTTIParams(GetTypeInfo(PRTTIProcType(TypeInfo).Params));
ParamsCount := PRTTIProcType(TypeInfo).ParamsCount;
if PRTTIProcType(TypeInfo).ResultType > 0 then
ResultType := GetTypeInfo(PRTTIProcType(TypeInfo).ResultType)
else
ResultType := nil;
ADDR := NativeUInt(ProcArg.PTR);
if TypeInfo.DataSize = PTR_SIZE*2 then
Result := CallMethodIndirect
else
Result := CallIndirect;
end else begin
{прямой вызов процедуры}
if ProcArg.ArgScope <> ARG_SCOPE_STRUCT then
begin
Proc := ProcArg.AsProcedure;
if not Proc.IsImported then
Result := CallStatic
else
Result := CallStaticExternal;
ADDR := NativeUInt(ProcArg.PTR);
ParamsCount := Length(Proc.Params);
if ParamsCount > 0 then
Params := PRTTIParams(@Proc.Params[0])
else
Params := nil;
if Proc.ProcType = ptFunction then
ResultType := GetTypeInfo(Params[0].DataType)
else
ResultType := nil;
end else
{прямой вызов метода}
begin
Proc := ProcArg.AsMethod.Proc;
ADDR := NativeUInt(Proc);
ParamsCount := Length(Proc.Params);
if ParamsCount > 0 then
Params := PRTTIParams(@Proc.Params[0])
else
Params := nil;
if Proc.ProcType = ptFunction then
begin
ResultType := GetTypeInfo(Params[0].DataType);
//Dec(ParamsCount);
end else
ResultType := nil;
if ProcArg.AsMethod.Self.ArgClass = ARG_TYPE then
Struct := GetTypeInfo(ProcArg.AsMethod.Self.TypeInfo)
else
Struct := GetTypeInfo(ProcArg.AsMethod.Self.AsVariable.RTTI.DataType);
if Struct.ImportLib > 0 then begin
if (ILPROC_HASSELFPTR and Proc.Flags) <> 0 then
Result := CallMethodExternal
else
Result := CallStaticExternal;
end else
if (ILPROC_HASSELFPTR and Proc.Flags) <> 0 then
begin
if Struct.DataTypeID = dtInterface then
Result := CallMethodInterface
else
Result := CallMethod;
end else
Result := CallStatic;
end;
end;
end;
{ TILUnit }
destructor TILUnit.Destroy;
var
ti, pi: Integer;
begin
for pi := 0 to Length(Procs) - 1 do
Procs[pi].Free;
for ti := 0 to Length(Types) - 1 do
begin
for pi := 0 to Length(Types[ti].Methods) - 1 do
Types[ti].Methods[pi].Free;
end;
InitProc.Free;
FinalProc.Free;
inherited;
end;
{ TILBranchContext }
procedure TILBranchContext.Add(const Args: TIL_LR_Args);
var
Item: ^TILBranch;
begin
Item := FItems.Add();
Item.CmpArgs := Args;
Item.ElseIdx := -1;
Item.EndIdx := -1;
end;
procedure TILBranchContext.BrClose;
begin
FItems.Position := FItems.Position - 1;
end;
function TILBranchContext.GetCount: Integer;
begin
Result := FItems.Position + 1;
end;
function TILBranchContext.GetLast: PILBranch;
begin
if FItems.Position >= 0 then
Result := addr(FItems.Items[FItems.Position])
else begin
AbortWork('Branch stack is empty');
Result := nil;
end;
end;
procedure TILBranchContext.Init;
begin
FItems := TILBranchStack.Create(4);
end;
end.
|
unit TableConditionUnit;
interface
function cFirstTable ( const CondNumber : integer ) : boolean;
function cSecondTable ( const CondNumber : integer ) : boolean;
function cThirdTable ( const CondNumber : integer ) : boolean;
function cFourthTable ( const CondNumber : integer ) : boolean;
function cFifthTable ( const CondNumber : integer ) : boolean;
function cSixthTable ( const CondNumber : integer ) : boolean;
function cSeventhTable ( const CondNumber : integer ) : boolean;
function cEighthTable ( const CondNumber : integer ) : boolean;
function cNinethTable ( const CondNumber : integer ) : boolean;
implementation
uses MainUnit, ClassUnit, GameUnit;
function cFirstTable ( const CondNumber : integer ) : boolean;
begin
case CondNumber of
1 : Result := MainForm.Start;
else Result := false;
end;
end;
function cSecondTable ( const CondNumber : integer ) : boolean;
begin
case CondNumber of
1 : Result := (gaBonus in Game.Hero.GlobalAimes);
2 : Result := (gaMonster in Game.Hero.GlobalAimes);
3 : Result := Game.HasBonuses;
4 : Result := Game.HasMonsters;
5 : Result := Game.HasLifeBonuses;
6 : Result := Game.HasAttackBonuses;
7 : Result := Game.HasDefenceBonuses;
8 : Result := Game.Hero.IsFewLife;
9 : Result := Game.Hero.IsFewDefence;
10 : Result := Game.Hero.IsAimChanging;
else Result := false;
end;
end;
function cThirdTable ( const CondNumber : integer ) : boolean;
begin
Game.ReAimHero;
case CondNumber of
1 : Result := Game.Hero.IsRightAim;
2 : Result := Game.Hero.IsLeftAim;
3 : Result := Game.Hero.IsUpAim;
4 : Result := Game.Hero.IsDownAim;
5 : Result := (Game.Hero.NeedCage is TMonster);
6 : Result := (Game.Hero.NeedCage is TObstacle);
7 : Result := (Game.Hero.NeedCage is TBonus);
8 : if (Game.Hero.NeedCage is TMonster) then
Result := (Game.DeathByFirstAttack((Game.Hero.NeedCage as TMonster), Game.Hero))
else
Result := false;
9 : Result := (Game.Hero.NeedCage is TExit) and (Game.Hero.Aim = atExit);
10 : Result := Game.Hero.IsAimReached;
else Result := false;
end;
end;
function cFourthTable ( const CondNumber : integer ) : boolean;
begin
case CondNumber of
1 : Result := (Game.Hero.MoveCage[1] is TMonster);
2 : Result := (Game.Hero.MoveCage[8] is TObstacle);
3 : Result := (Game.Hero.MoveCage[8] is TMonster);
4 : Result := (Game.Hero.MoveCage[8] is TBonus);
5 : Result := (Game.Hero.MoveCage[7] is TObstacle);
6 : Result := (Game.Hero.MoveCage[7] is TMonster);
7 : Result := (Game.Hero.MoveCage[7] is TBonus);
8 : Result := (Game.Hero.MoveCage[6] is TObstacle);
9 : Result := (Game.Hero.MoveCage[6] is TMonster);
10 : Result := (Game.Hero.MoveCage[6] is TBonus);
11 : Result := (Game.Hero.MoveCage[5] is TObstacle);
12 : Result := (Game.Hero.MoveCage[5] is TMonster);
13 : Result := (Game.Hero.MoveCage[5] is TBonus);
14 : Result := (Game.Hero.MoveCage[4] is TObstacle);
15 : Result := (Game.Hero.MoveCage[4] is TMonster);
16 : Result := (Game.Hero.MoveCage[4] is TBonus);
17 : if Game.Hero.MoveCage[8] is TMonster then
Result := Game.DeathByFirstAttack((Game.Hero.MoveCage[8] as TCreature), Game.Hero)
else
if Game.Hero.MoveCage[7] is TMonster then
Result := Game.DeathByFirstAttack((Game.Hero.MoveCage[7] as TCreature), Game.Hero)
else
if Game.Hero.MoveCage[6] is TMonster then
Result := Game.DeathByFirstAttack((Game.Hero.MoveCage[6] as TCreature), Game.Hero)
else
if Game.Hero.MoveCage[5] is TMonster then
Result := Game.DeathByFirstAttack((Game.Hero.MoveCage[5] as TCreature), Game.Hero)
else
if Game.Hero.MoveCage[4] is TMonster then
Result := Game.DeathByFirstAttack((Game.Hero.MoveCage[4] as TCreature), Game.Hero)
else
Result := false;
else Result := false;
end;
end;
function cFifthTable ( const CondNumber : integer ) : boolean;
begin
case CondNumber of
1 : Result := (Game.Hero.MoveCage[1] is TObstacle);
2 : Result := (Game.Hero.MoveCage[2] is TObstacle);
3 : Result := (Game.Hero.MoveCage[2] is TMonster);
4 : Result := (Game.Hero.MoveCage[2] is TBonus);
5 : Result := (Game.Hero.MoveCage[3] is TObstacle);
6 : Result := (Game.Hero.MoveCage[3] is TMonster);
7 : Result := (Game.Hero.MoveCage[3] is TBonus);
8 : Result := (Game.Hero.MoveCage[4] is TObstacle);
9 : Result := (Game.Hero.MoveCage[4] is TMonster);
10 : Result := (Game.Hero.MoveCage[4] is TBonus);
11 : Result := (Game.Hero.MoveCage[5] is TObstacle);
12 : Result := (Game.Hero.MoveCage[5] is TMonster);
13 : Result := (Game.Hero.MoveCage[5] is TBonus);
14 : if Game.Hero.MoveCage[2] is TMonster then
Result := Game.DeathByFirstAttack((Game.Hero.MoveCage[2] as TCreature), Game.Hero)
else
if Game.Hero.MoveCage[3] is TMonster then
Result := Game.DeathByFirstAttack((Game.Hero.MoveCage[3] as TCreature), Game.Hero)
else
if Game.Hero.MoveCage[4] is TMonster then
Result := Game.DeathByFirstAttack((Game.Hero.MoveCage[4] as TCreature), Game.Hero)
else
if Game.Hero.MoveCage[5] is TMonster then
Result := Game.DeathByFirstAttack((Game.Hero.MoveCage[5] as TCreature), Game.Hero)
else
Result := false;
else Result := false;
end;
end;
function cSixthTable ( const CondNumber : integer ) : boolean;
begin
if Game.CurrentMonster <> nil
then
case CondNumber of
1 : Result := Game.CurrentMonster.IsRightAim;
2 : Result := Game.CurrentMonster.IsLeftAim;
3 : Result := Game.CurrentMonster.IsUpAim;
4 : Result := Game.CurrentMonster.IsDownAim;
5 : Result := (Game.CurrentMonster.NeedCage is TMonster) or (Game.CurrentMonster.NeedCage is TObstacle);
6 : Result := (Game.CurrentMonster.NeedCage is THero);
7 : Result := Game.EofMonster;
else Result := false;
end
else
case CondNumber of
7 : Result := true;
else Result := false;
end;
end;
function cSeventhTable ( const CondNumber : integer ) : boolean;
begin
case CondNumber of
1 : Result := (Game.CurrentMonster.MoveCage[1] is TMonster) or (Game.CurrentMonster.MoveCage[1] is TObstacle);
2 : Result := (Game.CurrentMonster.MoveCage[2] is TMonster) or (Game.CurrentMonster.MoveCage[2] is TObstacle);
3 : Result := (Game.CurrentMonster.MoveCage[3] is TMonster) or (Game.CurrentMonster.MoveCage[3] is TObstacle);
4 : Result := (Game.CurrentMonster.MoveCage[4] is TMonster) or (Game.CurrentMonster.MoveCage[4] is TObstacle);
5 : Result := (Game.CurrentMonster.MoveCage[5] is TMonster) or (Game.CurrentMonster.MoveCage[5] is TObstacle);
6 : Result := (Game.CurrentMonster.MoveCage[6] is TMonster) or (Game.CurrentMonster.MoveCage[6] is TObstacle);
7 : Result := (Game.CurrentMonster.MoveCage[7] is TMonster) or (Game.CurrentMonster.MoveCage[7] is TObstacle);
8 : Result := (Game.CurrentMonster.MoveCage[8] is TMonster) or (Game.CurrentMonster.MoveCage[8] is TObstacle);
9 : Result := (Game.CurrentMonster.MissTurnCount >= 10);
else Result := false;
end;
end;
function cEighthTable ( const CondNumber : integer ) : boolean;
begin
case CondNumber of
1 : Result := (Game.Hero.Life <= 0);
2 : Result := (Game.BattleMonster.Life <= 0);
3 : Result := Game.BattleTurn.touche;
4 : Result := Game.BattleTurn.defenceOut;
5 : Result := Game.BattleTurn.lifeOut;
6 : Result := Game.BattleTurn.contreattack;
else Result := false;
end;
end;
function cNinethTable ( const CondNumber : integer ) : boolean;
begin
case CondNumber of
1 : Result := (Game.Hero.Life <= 0);
2 : Result := (Game.BattleMonster.Life <= 0);
3 : Result := Game.BattleTurn.touche;
4 : Result := Game.BattleTurn.defenceOut;
5 : Result := Game.BattleTurn.lifeOut;
6 : Result := Game.BattleTurn.contreattack;
else Result := false;
end;
end;
end.
|
unit fmImageViewU;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, ExtCtrls, ExtDlgs, JPeg, Mask, DB,
DBCtrls, Grids, DBGrids, GridsEh, DBGridEh;
type
TfmImageView = class(TForm)
pnImageControls: TPanel;
ScrollBox1: TScrollBox;
ImgView: TImage;
SavePictureDialog: TSavePictureDialog;
OpenPictureDialog: TOpenPictureDialog;
lbImageSize: TLabel;
lbImageComment: TLabel;
pFotoList: TPanel;
Splitter1: TSplitter;
dbedtImageComment: TDBEdit;
btnLoadImage: TBitBtn;
btnSaveImage: TBitBtn;
pImageNavigate: TPanel;
btnMiniSize: TBitBtn;
btnFullSize: TBitBtn;
btnNext: TBitBtn;
btnBack: TBitBtn;
geImage: TDBGridEh;
lNull: TLabel;
btnAddImage: TBitBtn;
btnDeleteImage: TBitBtn;
btnClose: TBitBtn;
procedure btnLoadImageClick(Sender: TObject);
procedure btnSaveImageClick(Sender: TObject);
procedure btnDeleteImageClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure dbedtImageCommentKeyPress(Sender: TObject; var Key: Char);
procedure SavePictureDialogTypeChange(Sender: TObject);
procedure btnFullSizeClick(Sender: TObject);
procedure btnMiniSizeClick(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure btnAddImageClick(Sender: TObject);
procedure btnCloseClick(Sender: TObject);
private
{ Private declarations }
public
ACurrentSubID: Integer; //текущий ID субъекта по которому открыты контакты.
Procedure ShowPicture(); //Извлекает из базы картинку при её наличии и выводит на форму.
Procedure OpenPictViewer(Const AID: integer; ALocate: Integer = 0; AShowForm: Boolean = True);
{ Public declarations }
end;
var
fmImageView: TfmImageView;
implementation
Uses Math, dataU;
{$R *.dfm}
{ TfmImageView }
////////////////////////////////////////////////////////////////////////////////
//
// ПРОЦЕДУРА: ShowPicture
//
// НАЗНАЧЕНИЕ:
// Извлекает из базы картинку при её наличии и выводит на форму.
//
procedure TfmImageView.ShowPicture;
var
Jpg: TJPEGImage;
Bmp: TBitmap;
begin
Try
Jpg := TJPegImage.Create;
Jpg.Assign(Data.dsImageVal);//получил доступ к фото
if not (Data.dsImageVal.IsNull{ FieldByName('Val').Value = ''}) then
begin
ImgView.Picture.assign(jpg);//вывел его в компонент ImgView
lNull.Visible := False;
end
else
lNull.Visible := True;
Except
Try
Bmp := TBitmap.Create;
Bmp.Assign(Data.dsImageVal);//получил доступ к фото
if not (Data.dsImageVal.IsNull{.FieldByName('Val').Value = ''}) then
begin
ImgView.Picture.assign(bmp);//вывел его фото в компонент ImgView
lNull.Visible := False;
end
else
lNull.Visible := True;
Except
ImgView.Picture.Bitmap.FreeImage;
End;
End;
btnMiniSizeClick(self);
// сделаем так что бы появились СкроллБары
lbImageSize.Left := ImgView.Width - lbImageSize.Width;
lbImageSize.Top := ImgView.Height - lbImageSize.Height;
end;
////////////////////////////////////////////////////////////////////////////////
//
// Загружаем фотографию с диска в базу и сразу отображаем её в окне.
//
procedure TfmImageView.btnLoadImageClick(Sender: TObject);
begin
If Application.MessageBox('Вы действительно хотите загрузить другое изображение? Имеющееся изображение будет перетерто!', 'Подтверждение',
MB_YESNO + MB_ICONQUESTION + MB_DEFBUTTON1) = ID_YES then
if OpenPictureDialog.Execute then
begin
Data.dsImage.Edit;
Data.dsImageVal.LoadFromFile(OpenPictureDialog.FileName);
Data.dsImageFileName.Value := ExtractFileName(OpenPictureDialog.FileName);
Data.dsImage.Post;
ShowPicture();
end;
end;
////////////////////////////////////////////////////////////////////////////////
//
// Выгружаем фотографию из базы на диск
//
procedure TfmImageView.btnSaveImageClick(Sender: TObject);
begin
SavePictureDialog.DefaultExt := 'jpg';
SavePictureDialog.FileName := ExtractFileName(Data.dsImageFileName.Value);
if SavePictureDialog.Execute then
begin
Data.dsImageVal.SaveToFile(SavePictureDialog.FileName);
end;
end;
////////////////////////////////////////////////////////////////////////////////
//
// Удаляем фотографию из БД
//
procedure TfmImageView.btnCloseClick(Sender: TObject);
begin
Close;
end;
procedure TfmImageView.btnDeleteImageClick(Sender: TObject);
begin
If Application.MessageBox('Вы действительно хотите удалить фотографию?', 'Подтверждение',
MB_YESNO + MB_ICONQUESTION + MB_DEFBUTTON1) = ID_YES then
begin
Data.dsImage.Edit;
Data.dsImageVal.Clear;
Data.dsImage.Post;
ImgView.Picture := nil;
ImgView.Height := 100;
ImgView.Width := 100;
lbImageSize.Left := 1;
lbImageSize.Top := 1;
Data.dsImage.Delete;
end;
end;
////////////////////////////////////////////////////////////////////////////////
//
// При открытии формы загружаем изображение при его наличии либо выводим пустой фон
//
procedure TfmImageView.FormShow(Sender: TObject);
begin
Caption := 'Фотографии записи: '+ QuotedStr(data.dsSubjectFIO.AsString);
ImgView.Picture := nil;
ImgView.Height := 100;
ImgView.Width := 100;
lbImageSize.Left := 1;
lbImageSize.Top := 1;
ShowPicture();
end;
procedure TfmImageView.OpenPictViewer(const AID: integer; ALocate: Integer = 0; AShowForm: Boolean = True);
begin
ACurrentSubID := AID;
if data.dsImage.Active then
data.dsImage.Close;
data.dsImage.CommandText := Format('select * from [Image] where SubjectID = %s',[IntToStr(AID)]);
data.dsImage.Open;
if ALocate <> 0 then
data.dsImage.Locate('ID',IntToStr(ALocate),[]);
if AShowForm then
fmImageView.ShowModal;
end;
////////////////////////////////////////////////////////////////////////////////
//
// При нажатии "Enter" во время ввода комментария к фото, сохраняем его(Коммент).
//
procedure TfmImageView.dbedtImageCommentKeyPress(Sender: TObject; var Key: Char);
begin
If Key = #13 then
If Data.dsImage.State in [dsEdit, dsInsert] then
Data.dsImage.Post;
end;
////////////////////////////////////////////////////////////////////////////////
//
// При выборе фильтра, расширение выставляем.
//
procedure TfmImageView.SavePictureDialogTypeChange(Sender: TObject);
begin
if SavePictureDialog.FilterIndex = 1 then
SavePictureDialog.DefaultExt := 'jpg'
else If SavePictureDialog.FilterIndex = 2 then
SavePictureDialog.DefaultExt := 'bmp';
end;
////////////////////////////////////////////////////////////////////////////////
//
// Отобразим картинку в оригенальном размере (разрешении)
//
procedure TfmImageView.btnFullSizeClick(Sender: TObject);
begin
ImgView.Align := alNone;
ImgView.AutoSize := True;
ImgView.Stretch := False;
ImgView.Center := False;
// сделаем так что бы появились СкроллБары
lbImageSize.Left := ImgView.Width - lbImageSize.Width;
lbImageSize.Top := ImgView.Height - lbImageSize.Height;
ImgView.Align := alClient;
ImgView.Center := True;
end;
////////////////////////////////////////////////////////////////////////////////
//
// Растянем изображение в соответствии с размероми окна.
//
procedure TfmImageView.btnMiniSizeClick(Sender: TObject);
begin
lbImageSize.Left := 0;
lbImageSize.Top := 0;
ImgView.AutoSize := False;
ImgView.Align := alClient;
ImgView.Proportional := True;
ImgView.Stretch := True;
end;
////////////////////////////////////////////////////////////////////////////////
//
// Сделаем так что бы картинка всегда была по центру поля с изображением.
//
procedure TfmImageView.FormResize(Sender: TObject);
begin
If ((ImgView.Picture.Height < ScrollBox1.Height) or (ImgView.Picture.Width < ScrollBox1.Width)) then
begin
ImgView.Align := alClient;
ImgView.Center := True;
end;
end;
////////////////////////////////////////////////////////////////////////////////
//
// Добавим новую картинку (фотографию)
//
procedure TfmImageView.btnAddImageClick(Sender: TObject);
begin
if OpenPictureDialog.Execute then
begin
Data.dsImage.Insert;
Data.dsImageVal.LoadFromFile(OpenPictureDialog.FileName);
Data.dsImageFileName.Value := OpenPictureDialog.FileName;
Data.dsImageName.Value := ExtractFileName(OpenPictureDialog.FileName);
Data.dsImage.Post;
ShowPicture();
end;
end;
end.
|
{Copyright (C) 2013 Benito van der Zander
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; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
}
{** @abstract(This unit contains a mock internet access class, i.e. a class that simulates an internet connection for e.g. unit tests)
See TMockInternetAccess}
unit mockinternetaccess;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, internetaccess;
type TMockTransfer = procedure (const method: string; const url: TDecodedUrl; const postdata: TInternetAccessDataBlock; var outdata: string) of object;
{ TInternetAccessNonSense }
{ TMockInternetAccess }
(***
@abstract(This class simulates an internet access, e.g. for unit tests)
There are three ways to use it:
@unorderedList(
@item(Just use it, without any changes. Then it will simulate a server returning DefaultMockPage on every request)
@item(Assign a method to the event OnTransfer, which will be called by every request, and simulate whatever you want )
@item(Assign a path to SimulatedServerPath, then it will simulate a server, returning the files from that directory)
)
*)
TMockInternetAccess = class(TInternetAccess)
constructor create();override;
constructor create(const internetConfig: TInternetConfig);override;
procedure doTransferUnChecked(var transfer: TTransfer); override;
destructor Destroy; override;
public
OnTransfer: TMockTransfer;
SimulatedServerPath: string;
end;
var DefaultMockPage: string = '<html>Internet disabled</html>';
implementation
uses bbutils;
constructor TMockInternetAccess.create();
begin
inherited;
end;
constructor TMockInternetAccess.create(const internetConfig: TInternetConfig);
begin
inherited;
end;
procedure TMockInternetAccess.doTransferUnChecked(var transfer: TTransfer);
var result: string;
begin
with transfer do begin
if SimulatedServerPath = '' then result := DefaultMockPage
else result := strLoadFromFile(SimulatedServerPath + decodedUrl.path + decodedUrl.params);
if Assigned(OnTransfer) then OnTransfer(method, decodedUrl, data, result);
if result <> '' then writeBlock(pointer(result)^, length(result));
end;
end;
destructor TMockInternetAccess.Destroy;
begin
inherited Destroy;
end;
end.
|
unit Unit4;
interface
uses
Winapi.Windows,
Winapi.Messages,
System.SysUtils,
System.Variants,
System.Classes,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Vcl.StdCtrls,
IniFiles,
Synautil,
httpsend,
msxml,
xmldom,
XMLIntf,
msxmldom,
XMLDoc;
type
TForm4 = class(TForm)
Edit1: TEdit;
Edit2: TEdit;
Edit3: TEdit;
Save: TButton;
Send: TButton;
Ping: TButton;
Memo1: TMemo;
procedure SaveClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure Edit1Change(Sender: TObject);
procedure Edit2Change(Sender: TObject);
procedure PingClick(Sender: TObject);
procedure SendClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form4: TForm4;
ini: TIniFile;
implementation
{$R *.dfm}
procedure TForm4.Edit1Change(Sender: TObject);
begin
Edit3.Text := Edit1.Text + ':' + Edit2.Text;
end;
procedure TForm4.Edit2Change(Sender: TObject);
begin
Edit3.Text := Edit1.Text + ':' + Edit2.Text;
end;
procedure TForm4.FormCreate(Sender: TObject);
begin
ini := TIniFile.Create(extractfilepath(paramstr(0))+'Config.ini');
try
Edit1.Text := ini.ReadString('DATA', 'EDIT1', '127.0.0.1');
Edit2.Text := ini.ReadString('DATA', 'EDIT2', '7000');
Edit3.Text := Edit1.Text + ':' + Edit2.Text;
finally
//ini.Free;
end;
end;
procedure TForm4.PingClick(Sender: TObject);
var
http:Thttpsend;
url:string;
begin
ini := TIniFile.Create(extractfilepath(paramstr(0))+'Config.ini');
http:=Thttpsend.Create;
url:='http://' + ini.ReadString('HTTP', 'IP', '127.0.0.1') + ':' + ini.ReadString('HTTP', 'PORT', '7000');
if http.HTTPMethod('GET', url) then
begin
ShowMessage('Все ок!');
end
else
begin
ShowMessage('Нет ответа от сервера.');
end;
http.Free;
end;
procedure TForm4.SaveClick(Sender: TObject);
begin
//ini := TIniFile.Create(extractfilepath(paramstr(0))+'Config.ini');
try
ini.WriteString('HTTP', 'IP', '127.0.0.1');
ini.WriteString('HTTP', 'PORT', '7000');
ini.WriteString('DATA', 'EDIT1', Edit1.Text);
ini.WriteString('DATA', 'EDIT2', Edit2.Text);
ini.WriteString('DATA', 'EDIT3', Edit3.Text);
finally
//ini.Free;
end;
end;
procedure TForm4.SendClick(Sender: TObject);
var
filexml, res: TXMLDocument;
S, Sres: TStringStream;
Http: THTTPSend;
i: Integer;
url: string;
begin
filexml:= TXMLDocument.Create(Form4);
S := TStringStream.Create;
with filexml do
begin
Active := True;
Version := '1.0';
Encoding := 'UTF-8';
with AddChild('Items') do
begin
with AddChild('Item') do
begin
Attributes['name'] := 'one';
Attributes['value'] := Edit1.Text;
end;
with AddChild('Item') do
begin
Attributes['name'] := 'two';
Attributes['value'] := Edit2.Text;
end;
with AddChild('Item') do
begin
Attributes['name'] := 'three';
Attributes['value'] := Edit3.Text;
end;
end;
SaveToStream(S);
end;
try
Http := THTTPSend.Create;
Http.Document.LoadFromStream(S);
url := 'http://' + ini.ReadString('HTTP', 'IP', '127.0.0.1') + ':' + ini.ReadString('HTTP', 'PORT', '7000');
filexml.Active := False;
if Http.HTTPMethod('POST', url) then
begin
Memo1.Lines.Clear;
res := TXMLDocument.Create(Form4);
Sres := TStringStream.Create;
Http.Document.SaveToStream(Sres);
res.LoadFromStream(Sres);
res.Active := True;
for i := 0 to res.DocumentElement.ChildNodes.Count-1 do
begin
//data.DocumentElement.ChildNodes[i].Attributes['value'] := AnsiReverseString(Memo1.Lines[i]);
Memo1.Lines.Add(res.DocumentElement.ChildNodes[i].Attributes['value']);
end;
end
else
begin
Memo1.Lines.Clear;
Memo1.Lines.Add('Сервер не отвечает');
end;
finally
filexml.Free;
http.Free;
S.Destroy;
end;
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.2 2004.10.26 2:19:58 PM czhower
Resolved alias conflict.
Rev 1.1 14/07/2004 21:37:26 CCostelloe
Changed Get/SetMessage to Get/SetIdMessage to avoid conflict under C++ with
Windows' GetMessage
Rev 1.0 11/13/2002 07:57:28 AM JPMugaas
2000-APR-14 Peter Mee: Converted to Indy.
2001-MAY-03 Idan Cohen: Added Create and Destroy of TIdMessage.
}
unit IdMessageCollection;
{
TIdMessageCollection: Contains a collection of IdMessages.
Originally by Peter Mee.
}
interface
{$i IdCompilerDefines.inc}
uses
Classes,
IdMessage;
type
TIdMessageItems = class of TIdMessageItem;
TIdMessageItem = class(TCollectionItem)
protected
FAttempt: Integer;
FQueued: Boolean;
public
Msg: TIdMessage;
//
property Attempt: Integer read FAttempt write FAttempt;
property Queued: Boolean read FQueued write FQueued;
constructor Create(Collection: TCollection); override;
destructor Destroy; override;
end;
TIdMessageCollection = class(TCollection)
private
function GetIdMessage(index: Integer): TIdMessage;
procedure SetIdMessage(index: Integer; const Value: TIdMessage);
public
function Add: TIdMessageItem;
property Messages[index: Integer]: TIdMessage read GetIdMessage write SetIdMessage; Default;
end;
implementation
uses
IdGlobal, SysUtils;
function TIdMessageCollection.Add;
begin
Result := TIdMessageItem(inherited Add);
end;
{ TIdMessageItem }
constructor TIdMessageItem.Create(Collection: TCollection);
begin
inherited Create(Collection);
Msg := TIdMessage.Create(nil);
end;
destructor TIdMessageItem.Destroy;
begin
FreeAndNil(Msg);
inherited Destroy;
end;
function TIdMessageCollection.GetIdMessage(index: Integer): TIdMessage;
begin
Result := TIdMessageItem(Items[index]).Msg;
end;
procedure TIdMessageCollection.SetIdMessage(index: Integer; const Value: TIdMessage);
begin
//I think it should be freed before the new value is assigned or else the
//pointer will be lost.
// RLebeau 6/3/2010: this is taking ownership of the input TIdMessage
// pointer! We should probably be calling Assign() instead, and let
// the caller manage its TIdMessage object separately. Or else make
// the Messages[] property read-only instead...
TIdMessageItem(Items[index]).Msg.Free;
TIdMessageItem(Items[index]).Msg := Value;
end;
end.
|
unit ClientMain;
{ RDS Client Demo -
Open and Run RDSServer.DPR before running this project.
You can switch between using the supplied AppServer and
the default RDS DataFactory by selecting from the Combobox.
When using the DataFactory the ConnectionString on the dataset is
used by the DataFactory.Query method.
If you have not used the DataFactory before you will need to
edit the MSDFMAP.INI file in your Windows directory:
In the [connect default] section change the Access to ReadWrite.
In the [sql default] section, comment out the SQL=" " line.
}
interface
uses
Windows, Forms, StdCtrls, ExtCtrls, Classes, Controls, Grids, DB, ADODB,
DBGrids;
type
TForm1 = class(TForm)
DBGrid1: TDBGrid;
Employee: TADODataSet;
DataSource1: TDataSource;
RDSConnection1: TRDSConnection;
Panel1: TPanel;
ServerNameCombo: TComboBox;
OpenButton: TButton;
procedure OpenButtonClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.OpenButtonClick(Sender: TObject);
begin
RDSConnection1.Close;
RDSConnection1.ServerName := ServerNameCombo.Text;
Employee.Close;
Employee.Open;
end;
end.
|
unit add_string_seg_2;
interface
implementation
function AddStringSegment(const Str, Seg: string; const Separator: string): string;
var
sl: int32;
begin
sl := length(Separator);
if (Str <> '') and
(Seg <> '') and
(copy(Str, length(Str) - sl, sl) <> Separator) and
(copy(Seg, 0, sl) <> Separator) then
Result := Str + Separator + Seg
else
Result := Str + Seg;
end;
var S: string;
procedure Test;
begin
S := AddStringSegment(S, 'X', ',');
S := AddStringSegment(S, 'YY', ',');
S := AddStringSegment(S, 'ZZZ', ',');
end;
initialization
Test();
finalization
Assert(S = 'X,YY,ZZZ');
end. |
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ FireDAC IBM DB2 driver }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
{$IF DEFINED(IOS) OR DEFINED(ANDROID)}
{$HPPEMIT LINKUNIT}
{$ELSE}
{$IFDEF WIN32}
{$HPPEMIT '#pragma link "FireDAC.Phys.DB2.obj"'}
{$ELSE}
{$HPPEMIT '#pragma link "FireDAC.Phys.DB2.o"'}
{$ENDIF}
{$ENDIF}
unit FireDAC.Phys.DB2;
interface
uses
System.Classes,
FireDAC.Stan.Error,
FireDAC.Phys, FireDAC.Phys.ODBCCli, FireDAC.Phys.ODBCWrapper, FireDAC.Phys.ODBCBase;
type
EDB2NativeException = class;
TFDPhysDB2DriverLink = class;
EDB2NativeException = class(EODBCNativeException)
public
function AppendError(AHandle: TODBCHandle; ARecNum: SQLSmallint;
const ASQLState: String; ANativeError: SQLInteger; const ADiagMessage,
AResultMessage, ACommandText, AObject: String; AKind: TFDCommandExceptionKind;
ACmdOffset, ARowIndex: Integer): TFDDBError; override;
end;
[ComponentPlatformsAttribute(pfidWindows or pfidLinux)]
TFDPhysDB2DriverLink = class(TFDPhysODBCBaseDriverLink)
protected
function GetBaseDriverID: String; override;
end;
{-------------------------------------------------------------------------------}
implementation
uses
System.Variants, System.SysUtils, System.StrUtils, Data.DB,
FireDAC.Stan.Consts, FireDAC.Stan.Intf, FireDAC.Stan.Util, FireDAC.Stan.Param,
FireDAC.DatS,
FireDAC.Phys.Intf, FireDAC.Phys.SQLGenerator, FireDAC.Phys.DB2Meta,
FireDAC.Phys.DB2Def;
type
TFDPhysDB2Driver = class;
TFDPhysDB2Connection = class;
TFDPhysDB2EventAlerter = class;
TFDPhysDB2EventAlerter_DBMS_ALERT = class;
TFDPhysDB2EventAlerter_DBMS_PIPE = class;
TFDPhysDB2Command = class;
TFDPhysDB2Driver = class(TFDPhysODBCDriverBase)
protected
class function GetBaseDriverID: String; override;
class function GetBaseDriverDesc: String; override;
class function GetRDBMSKind: TFDRDBMSKind; override;
class function GetConnectionDefParamsClass: TFDConnectionDefParamsClass; override;
procedure InternalLoad; override;
function InternalCreateConnection(AConnHost: TFDPhysConnectionHost): TFDPhysConnection; override;
procedure GetODBCConnectStringKeywords(AKeywords: TStrings); override;
function BuildODBCConnectString(const AConnectionDef: IFDStanConnectionDef): String; override;
function GetConnParams(AKeys: TStrings; AParams: TFDDatSTable): TFDDatSTable; override;
end;
TFDPhysDB2Connection = class(TFDPhysODBCConnectionBase)
private
FExtendedMetadata: Boolean;
procedure UpdateCurrentSchema;
protected
function InternalCreateCommandGenerator(const ACommand:
IFDPhysCommand): TFDPhysCommandGenerator; override;
function InternalCreateCommand: TFDPhysCommand; override;
function InternalCreateEvent(const AEventKind: String): TFDPhysEventAlerter; override;
function InternalCreateMetadata: TObject; override;
procedure GetStrsMaxSizes(AStrDataType: SQLSmallint; AFixedLen: Boolean;
out ACharSize, AByteSize: Integer); override;
procedure UpdateDecimalSep; override;
procedure SetupConnection; override;
function GetExceptionClass: EODBCNativeExceptionClass; override;
end;
TFDPhysDB2EventAlerter = class(TFDPhysEventAlerter)
private
FWaitConnection: IFDPhysConnection;
FWaitCommand: IFDPhysCommand;
FWaitThread: TThread;
FSignalCommand: IFDPhysCommand;
protected
procedure DoFired; virtual; abstract;
procedure InternalAllocHandle; override;
procedure InternalReleaseHandle; override;
procedure InternalRegister; override;
procedure InternalUnregister; override;
end;
TFDPhysDB2EventAlerter_DBMS_ALERT = class(TFDPhysDB2EventAlerter)
protected
// TFDPhysEventAlerter
procedure DoFired; override;
procedure InternalRegister; override;
procedure InternalHandle(AEventMessage: TFDPhysEventMessage); override;
procedure InternalAbortJob; override;
procedure InternalUnregister; override;
procedure InternalSignal(const AEvent: String; const AArgument: Variant); override;
end;
TFDPhysDB2EventAlerter_DBMS_PIPE = class(TFDPhysDB2EventAlerter)
private
FReadCommand,
FWriteCommand: IFDPhysCommand;
protected
// TFDPhysEventAlerter
procedure DoFired; override;
procedure InternalAllocHandle; override;
procedure InternalRegister; override;
procedure InternalHandle(AEventMessage: TFDPhysEventMessage); override;
procedure InternalAbortJob; override;
procedure InternalReleaseHandle; override;
procedure InternalSignal(const AEvent: String; const AArgument: Variant); override;
end;
TFDPhysDB2Command = class(TFDPhysODBCCommand)
protected
function InternalOpen(var ACount: TFDCounter): Boolean; override;
procedure InternalExecute(ATimes, AOffset: Integer; var ACount: TFDCounter); override;
end;
const
S_FD_Choose = 'Choose';
S_FD_Unicode = 'Unicode';
{-------------------------------------------------------------------------------}
{ EDB2NativeException }
{-------------------------------------------------------------------------------}
function EDB2NativeException.AppendError(AHandle: TODBCHandle;
ARecNum: SQLSmallint; const ASQLState: String; ANativeError: SQLInteger;
const ADiagMessage, AResultMessage, ACommandText, AObject: String;
AKind: TFDCommandExceptionKind; ACmdOffset, ARowIndex: Integer): TFDDBError;
var
sObj: String;
procedure ExtractObjName;
var
i1, i2: Integer;
begin
i1 := Pos('"', ADiagMessage);
if i1 <> 0 then begin
i2 := Pos('"', ADiagMessage, i1 + 1);
if i2 <> 0 then
sObj := Copy(ADiagMessage, i1 + 1, i2 - i1 - 1);
end;
end;
begin
// following is not supported by DB2:
// ekUserPwdExpired
// ekUserPwdWillExpire
// ekRecordLocked
sObj := AObject;
case ANativeError of
100:
AKind := ekNoDataFound;
-803:
begin
AKind := ekUKViolated;
// first "xxxx" - constraint
// second "xxxx" - table name
ExtractObjName;
end;
-530:
begin
AKind := ekFKViolated;
// first "xxxx" - constraint
ExtractObjName;
end;
-204:
begin
AKind := ekObjNotExists;
// first "xxxx" - table name
ExtractObjName;
end;
-30082:
AKind := ekUserPwdInvalid;
end;
if AKind = ekOther then
if ASQLState = '40003' then
AKind := ekServerGone;
Result := inherited AppendError(AHandle, ARecNum, ASQLState, ANativeError,
ADiagMessage, AResultMessage, ACommandText, sObj, AKind, ACmdOffset,
ARowIndex);
end;
{-------------------------------------------------------------------------------}
{ TFDPhysDB2DriverLink }
{-------------------------------------------------------------------------------}
function TFDPhysDB2DriverLink.GetBaseDriverID: String;
begin
Result := S_FD_DB2Id;
end;
{-------------------------------------------------------------------------------}
{ TFDPhysDB2Driver }
{-------------------------------------------------------------------------------}
class function TFDPhysDB2Driver.GetBaseDriverID: String;
begin
Result := S_FD_DB2Id;
end;
{-------------------------------------------------------------------------------}
class function TFDPhysDB2Driver.GetBaseDriverDesc: String;
begin
Result := 'IBM DB2 Server';
end;
{-------------------------------------------------------------------------------}
class function TFDPhysDB2Driver.GetRDBMSKind: TFDRDBMSKind;
begin
Result := TFDRDBMSKinds.DB2;
end;
{-------------------------------------------------------------------------------}
class function TFDPhysDB2Driver.GetConnectionDefParamsClass: TFDConnectionDefParamsClass;
begin
Result := TFDPhysDB2ConnectionDefParams;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysDB2Driver.InternalLoad;
begin
ODBCAdvanced := 'IGNOREWARNINGS=1';
inherited InternalLoad;
if ODBCDriver = '' then
ODBCDriver := FindBestDriver(['IBM DATA SERVER DRIVER for ODBC%',
'IBM DB2 ODBC DRIVER%', 'IBM DB2 DRIVER FOR ODBC%']);
end;
{-------------------------------------------------------------------------------}
function TFDPhysDB2Driver.InternalCreateConnection(
AConnHost: TFDPhysConnectionHost): TFDPhysConnection;
begin
Result := TFDPhysDB2Connection.Create(Self, AConnHost);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysDB2Driver.GetODBCConnectStringKeywords(AKeywords: TStrings);
begin
inherited GetODBCConnectStringKeywords(AKeywords);
AKeywords.Add(S_FD_ConnParam_DB2_Alias + '=DBALIAS');
AKeywords.Add(S_FD_ConnParam_Common_Database);
AKeywords.Add(S_FD_ConnParam_Common_Server + '=HOSTNAME');
AKeywords.Add(S_FD_ConnParam_Common_Port);
AKeywords.Add(S_FD_ConnParam_DB2_Protocol);
AKeywords.Add(S_FD_ConnParam_Common_OSAuthent + '=Trusted_Connection');
AKeywords.Add('=IGNOREWARNINGS');
end;
{-------------------------------------------------------------------------------}
function TFDPhysDB2Driver.BuildODBCConnectString(const AConnectionDef: IFDStanConnectionDef): String;
var
s: String;
begin
Result := inherited BuildODBCConnectString(AConnectionDef);
if TFDPhysDB2ConnectionDefParams(AConnectionDef.Params).ExtendedMetadata then
s := '1'
else
s := '0';
Result := Result + ';EXTCOLINFO=' + s;
end;
{-------------------------------------------------------------------------------}
function TFDPhysDB2Driver.GetConnParams(AKeys: TStrings; AParams: TFDDatSTable): TFDDatSTable;
begin
Result := inherited GetConnParams(AKeys, AParams);
Result.Rows.Add([Unassigned, S_FD_ConnParam_DB2_Alias, '@S', '', S_FD_ConnParam_DB2_Alias, 3]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_Server, '@S', '', S_FD_ConnParam_Common_Server, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_Port, '@I', '', S_FD_ConnParam_Common_Port, -1]); // 50000
Result.Rows.Add([Unassigned, S_FD_ConnParam_DB2_Protocol, '@S', '', S_FD_ConnParam_DB2_Protocol, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_OSAuthent, '@Y', '', S_FD_ConnParam_Common_OSAuthent, 2]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_DB2_StringFormat, S_FD_Choose + ';' + S_FD_Unicode, S_FD_Choose, S_FD_ConnParam_DB2_StringFormat, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_ExtendedMetadata, '@L', S_FD_False, S_FD_ConnParam_Common_ExtendedMetadata, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_DB2_TxSupported, S_FD_Yes + ';' + S_FD_No, S_FD_Yes, S_FD_ConnParam_DB2_TxSupported, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_MetaDefSchema, '@S', '', S_FD_ConnParam_Common_MetaDefSchema, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_MetaCurSchema, '@S', '', S_FD_ConnParam_Common_MetaCurSchema, -1]);
end;
{-------------------------------------------------------------------------------}
{ TFDPhysDB2Connection }
{-------------------------------------------------------------------------------}
function TFDPhysDB2Connection.InternalCreateCommand: TFDPhysCommand;
begin
Result := TFDPhysDB2Command.Create(Self);
end;
{-------------------------------------------------------------------------------}
function TFDPhysDB2Connection.InternalCreateEvent(const AEventKind: String): TFDPhysEventAlerter;
begin
if CompareText(AEventKind, S_FD_EventKind_DB2_DBMS_ALERT) = 0 then
Result := TFDPhysDB2EventAlerter_DBMS_ALERT.Create(Self, AEventKind)
else if CompareText(AEventKind, S_FD_EventKind_DB2_DBMS_PIPE) = 0 then
Result := TFDPhysDB2EventAlerter_DBMS_PIPE.Create(Self, AEventKind)
else
Result := nil;
end;
{-------------------------------------------------------------------------------}
function TFDPhysDB2Connection.InternalCreateCommandGenerator(
const ACommand: IFDPhysCommand): TFDPhysCommandGenerator;
begin
if ACommand <> nil then
Result := TFDPhysDb2CommandGenerator.Create(ACommand)
else
Result := TFDPhysDb2CommandGenerator.Create(Self);
end;
{-------------------------------------------------------------------------------}
function TFDPhysDB2Connection.InternalCreateMetadata: TObject;
var
iSrvVer, iClntVer: TFDVersion;
begin
GetVersions(iSrvVer, iClntVer);
Result := TFDPhysDb2Metadata.Create(Self, iSrvVer, iClntVer, GetKeywords,
FExtendedMetadata, TFDPhysDB2ConnectionDefParams(ConnectionDef.Params).TxSupported = tsYes);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysDB2Connection.GetStrsMaxSizes(AStrDataType: SQLSmallint;
AFixedLen: Boolean; out ACharSize: Integer; out AByteSize: Integer);
begin
// char - 254
// varchar - 32672
// long varchar - 32700
// clob - 2147483647
// graphic - 127 * 2
// vargraphic - 16336 * 2
// long vargraphic - 16350 * 2
// dbclob - 1073741823 * 2
// blob - 2147483647
case AStrDataType of
SQL_C_CHAR, SQL_C_BINARY:
begin
if AFixedLen then
AByteSize := 254
else
AByteSize := 32672;
ACharSize := AByteSize;
end;
SQL_C_WCHAR:
begin
if AFixedLen then
AByteSize := 254
else
AByteSize := 32672;
ACharSize := AByteSize div SizeOf(SQLWChar);
end;
else
FDCapabilityNotSupported(Self, [S_FD_LPhys, S_FD_DB2Id]);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysDB2Connection.UpdateDecimalSep;
var
oStmt: TODBCCommandStatement;
oCol: TODBCVariable;
pData: SQLPointer;
iSize: SQLLen;
sNum: String;
begin
inherited UpdateDecimalSep;
try
oStmt := TODBCCommandStatement.Create(ODBCConnection);
try
oStmt.Open(1, 'SELECT 12.34 FROM SYSIBM.SYSDUMMY1');
oCol := oStmt.AddCol(1, SQL_NUMERIC, SQL_C_CHAR);
oStmt.Fetch(1);
oCol.GetData(0, pData, iSize, True);
sNum := ODBCConnection.Encoder.Decode(pData, iSize, ecANSI);
ODBCConnection.DecimalSepCol := sNum[3];
finally
FDFree(oStmt);
end;
except
// silent
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysDB2Connection.GetExceptionClass: EODBCNativeExceptionClass;
begin
Result := EDB2NativeException;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysDB2Connection.SetupConnection;
var
oParams: TFDPhysDB2ConnectionDefParams;
begin
inherited SetupConnection;
oParams := ConnectionDef.Params as TFDPhysDB2ConnectionDefParams;
FExtendedMetadata := oParams.ExtendedMetadata;
if oParams.StringFormat = sfUnicode then
ODBCConnection.MAPCHAR := SQL_MAPCHAR_WCHAR;
if FExtendedMetadata then
ODBCConnection.DESCRIBE_OUTPUT_LEVEL := 3
else
ODBCConnection.DESCRIBE_OUTPUT_LEVEL := 2;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysDB2Connection.UpdateCurrentSchema;
var
oStmt: TODBCCommandStatement;
oCol: TODBCVariable;
pData: SQLPointer;
iSize: SQLLen;
begin
oStmt := TODBCCommandStatement.Create(ODBCConnection);
try
oStmt.Open(1, 'SELECT CURRENT_SCHEMA FROM SYSIBM.SYSDUMMY1');
oCol := oStmt.AddCol(1, SQL_VARCHAR, SQL_C_CHAR, 30);
oStmt.Fetch(1);
oCol.GetData(0, pData, iSize, True);
FCurrentSchema := ODBCConnection.Encoder.Decode(pData, iSize, ecANSI);
finally
FDFree(oStmt);
end;
end;
{-------------------------------------------------------------------------------}
{ TFDPhysDB2EventThread }
{-------------------------------------------------------------------------------}
type
TFDPhysDB2EventThread = class(TThread)
private
[weak] FAlerter: TFDPhysDB2EventAlerter;
protected
procedure Execute; override;
public
constructor Create(AAlerter: TFDPhysDB2EventAlerter);
destructor Destroy; override;
end;
{-------------------------------------------------------------------------------}
constructor TFDPhysDB2EventThread.Create(AAlerter: TFDPhysDB2EventAlerter);
begin
inherited Create(False);
FAlerter := AAlerter;
FreeOnTerminate := True;
end;
{-------------------------------------------------------------------------------}
destructor TFDPhysDB2EventThread.Destroy;
begin
FAlerter.FWaitThread := nil;
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysDB2EventThread.Execute;
begin
while not Terminated and FAlerter.IsRunning do
try
FAlerter.FWaitCommand.Execute();
if not Terminated then
FAlerter.DoFired;
except
on E: EFDDBEngineException do
if E.Kind <> ekCmdAborted then begin
Terminate;
FAlerter.AbortJob;
end;
end;
end;
{-------------------------------------------------------------------------------}
{ TFDPhysDB2EventAlerter }
{-------------------------------------------------------------------------------}
procedure TFDPhysDB2EventAlerter.InternalAllocHandle;
begin
FWaitConnection := GetConnection.Clone;
if FWaitConnection.State = csDisconnected then
FWaitConnection.Open;
FWaitConnection.CreateCommand(FWaitCommand);
SetupCommand(FWaitCommand);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysDB2EventAlerter.InternalRegister;
begin
FWaitThread := TFDPhysDB2EventThread.Create(Self);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysDB2EventAlerter.InternalUnregister;
begin
FWaitThread := nil;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysDB2EventAlerter.InternalReleaseHandle;
begin
FSignalCommand := nil;
FWaitCommand := nil;
FWaitConnection := nil;
end;
{-------------------------------------------------------------------------------}
{ TFDPhysDB2EventMessage_DBMS_ALERT }
{-------------------------------------------------------------------------------}
type
TFDPhysDB2EventMessage_DBMS_ALERT = class(TFDPhysEventMessage)
private
FName,
FMessage: String;
public
constructor Create(const AName, AMessage: String);
end;
{-------------------------------------------------------------------------------}
constructor TFDPhysDB2EventMessage_DBMS_ALERT.Create(const AName, AMessage: String);
begin
inherited Create;
FName := AName;
FMessage := AMessage;
end;
{-------------------------------------------------------------------------------}
{ TFDPhysDB2EventAlerter_DBMS_ALERT }
{-------------------------------------------------------------------------------}
const
C_WakeUpEvent = C_FD_SysNamePrefix + 'WAKEUP';
procedure TFDPhysDB2EventAlerter_DBMS_ALERT.InternalRegister;
var
sSQL: String;
i: Integer;
oPar: TFDParam;
begin
sSQL := 'BEGIN' + C_FD_EOL + 'CALL DBMS_ALERT.REGISTER(''' + C_WakeUpEvent + ''');' + C_FD_EOL;
for i := 0 to GetNames().Count - 1 do
sSQL := sSQL + 'CALL DBMS_ALERT.REGISTER(' + QuotedStr(Trim(GetNames()[i])) + ');' + C_FD_EOL;
sSQL := sSQL + 'END;';
FWaitCommand.Prepare(sSQL);
FWaitCommand.Execute();
FWaitCommand.CommandText := 'BEGIN' + C_FD_EOL +
'CALL DBMS_ALERT.WAITANY(:name, :message, :status, :timeout);' + C_FD_EOL +
'END;';
oPar := FWaitCommand.Params[0];
oPar.ParamType := ptOutput;
oPar.DataType := ftString;
oPar.Size := 128;
oPar := FWaitCommand.Params[1];
oPar.ParamType := ptOutput;
oPar.DataType := ftString;
oPar.Size := 32672;
oPar := FWaitCommand.Params[2];
oPar.ParamType := ptOutput;
oPar.DataType := ftInteger;
oPar := FWaitCommand.Params[3];
oPar.ParamType := ptInput;
oPar.DataType := ftInteger;
oPar.AsInteger := 86400;
FWaitCommand.Prepare();
inherited InternalRegister;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysDB2EventAlerter_DBMS_ALERT.DoFired;
begin
if (FWaitCommand.Params[2].AsInteger = 0) and
(CompareText(FWaitCommand.Params[0].AsString, C_WakeUpEvent) <> 0) then
FMsgThread.EnqueueMsg(TFDPhysDB2EventMessage_DBMS_ALERT.Create(
FWaitCommand.Params[0].AsString, FWaitCommand.Params[1].AsString));
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysDB2EventAlerter_DBMS_ALERT.InternalHandle(AEventMessage: TFDPhysEventMessage);
var
oMsg: TFDPhysDB2EventMessage_DBMS_ALERT;
begin
oMsg := TFDPhysDB2EventMessage_DBMS_ALERT(AEventMessage);
InternalHandleEvent(oMsg.FName, oMsg.FMessage);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysDB2EventAlerter_DBMS_ALERT.InternalAbortJob;
begin
if FWaitThread <> nil then begin
FWaitThread.Terminate;
InternalSignal(C_WakeUpEvent, Null);
FWaitCommand.AbortJob(True);
while FWaitThread <> nil do
Sleep(1);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysDB2EventAlerter_DBMS_ALERT.InternalUnregister;
var
sSQL: String;
i: Integer;
begin
inherited InternalUnregister;
if FWaitCommand <> nil then
try
sSQL := 'BEGIN' + C_FD_EOL + 'CALL DBMS_ALERT.REMOVE(''' + C_WakeUpEvent + ''');' + C_FD_EOL;
for i := 0 to GetNames().Count - 1 do
sSQL := sSQL + 'CALL DBMS_ALERT.REMOVE(' + QuotedStr(Trim(GetNames()[i])) + ');' + C_FD_EOL;
sSQL := sSQL + 'END;';
FWaitCommand.Prepare(sSQL);
FWaitCommand.Execute();
except
// hide exception
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysDB2EventAlerter_DBMS_ALERT.InternalSignal(const AEvent: String;
const AArgument: Variant);
var
oPar: TFDParam;
begin
if FSignalCommand = nil then begin
GetConnection.CreateCommand(FSignalCommand);
SetupCommand(FSignalCommand);
FSignalCommand.CommandText := 'BEGIN CALL DBMS_ALERT.SIGNAL(:name, :message); END;';
oPar := FSignalCommand.Params[0];
oPar.DataType := ftString;
oPar.Size := 128;
oPar := FSignalCommand.Params[1];
oPar.DataType := ftString;
oPar.Size := 32672;
FSignalCommand.Prepare();
end;
FSignalCommand.Params[0].AsString := AEvent;
FSignalCommand.Params[1].AsString := VarToStr(AArgument);
FSignalCommand.Execute();
end;
{-------------------------------------------------------------------------------}
{ TFDPhysDB2EventMessage_DBMS_PIPE }
{-------------------------------------------------------------------------------}
type
TFDPhysDB2EventMessage_DBMS_PIPE = class(TFDPhysEventMessage)
private
FName: String;
FValues: Variant;
public
constructor Create(const AName: String; const AValues: Variant);
end;
{-------------------------------------------------------------------------------}
constructor TFDPhysDB2EventMessage_DBMS_PIPE.Create(const AName: String;
const AValues: Variant);
begin
inherited Create;
FName := AName;
FValues := AValues;
end;
{-------------------------------------------------------------------------------}
{ TFDPhysDB2EventAlerter_DBMS_PIPE }
{-------------------------------------------------------------------------------}
procedure TFDPhysDB2EventAlerter_DBMS_PIPE.InternalAllocHandle;
begin
if GetNames().Count > 1 then
FDException(Self, [S_FD_LPhys, S_FD_DB2Id], er_FD_OraPipeAlertToMany, []);
inherited InternalAllocHandle;
FWaitConnection.CreateCommand(FReadCommand);
SetupCommand(FReadCommand);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysDB2EventAlerter_DBMS_PIPE.InternalRegister;
var
oPar: TFDParam;
begin
FWaitCommand.CommandText := 'BEGIN' + C_FD_EOL +
'SET :result = DBMS_PIPE.RECEIVE_MESSAGE(:name, :timeout);' + C_FD_EOL +
'END;';
oPar := FWaitCommand.Params[0];
oPar.ParamType := ptOutput;
oPar.DataType := ftInteger;
oPar := FWaitCommand.Params[1];
oPar.ParamType := ptInput;
oPar.DataType := ftString;
oPar.Size := 128;
oPar := FWaitCommand.Params[2];
oPar.ParamType := ptInput;
oPar.DataType := ftInteger;
oPar.AsInteger := 86400;
FWaitCommand.Prepare();
FWaitCommand.Params[1].AsString := GetNames()[0];
FReadCommand.CommandText := 'BEGIN' + C_FD_EOL +
'SET :tp = DBMS_PIPE.NEXT_ITEM_TYPE();' + C_FD_EOL +
'IF :tp = 6 THEN' + C_FD_EOL +
' CALL DBMS_PIPE.UNPACK_MESSAGE(:num);' + C_FD_EOL +
'ELSEIF :tp = 9 THEN' + C_FD_EOL +
' CALL DBMS_PIPE.UNPACK_MESSAGE(:vc);' + C_FD_EOL +
'ELSEIF :tp = 12 THEN' + C_FD_EOL +
' CALL DBMS_PIPE.UNPACK_MESSAGE(:dt);' + C_FD_EOL +
'ELSEIF :tp = 23 THEN' + C_FD_EOL +
' CALL DBMS_PIPE.UNPACK_MESSAGE_RAW(:vc);' + C_FD_EOL +
'END IF;' + C_FD_EOL +
'END;';
oPar := FReadCommand.Params[0];
oPar.ParamType := ptOutput;
oPar.DataType := ftInteger;
oPar := FReadCommand.Params[1];
oPar.ParamType := ptOutput;
oPar.DataType := ftInteger;
oPar := FReadCommand.Params[2];
oPar.ParamType := ptOutput;
oPar.DataType := ftString;
oPar.Size := 1024;
oPar := FReadCommand.Params[3];
oPar.ParamType := ptOutput;
oPar.DataType := ftDateTime;
FReadCommand.Prepare();
inherited InternalRegister;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysDB2EventAlerter_DBMS_PIPE.DoFired;
var
i: Integer;
vVal: Variant;
aValues: Variant;
begin
case FWaitCommand.Params[0].AsInteger of
0: {success}
begin
i := 0;
aValues := Null;
while True do begin
FReadCommand.Execute();
case FReadCommand.Params[0].AsInteger of
0:
Break;
9 {vc}, 23 {raw}:
vVal := FReadCommand.Params[2].AsString;
6 {num}:
vVal := FReadCommand.Params[1].AsInteger;
12 {date}:
vVal := FReadCommand.Params[3].AsDateTime;
else
vVal := Null;
end;
if i = 0 then
aValues := VarArrayCreate([0, 0], varVariant)
else
VarArrayRedim(aValues, i);
aValues[i] := vVal;
Inc(i);
end;
FMsgThread.EnqueueMsg(TFDPhysDB2EventMessage_DBMS_PIPE.Create(
FWaitCommand.Params[1].AsString, aValues));
end;
1: {timeout}
;
else
FWaitThread.Terminate;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysDB2EventAlerter_DBMS_PIPE.InternalHandle(
AEventMessage: TFDPhysEventMessage);
var
oMsg: TFDPhysDB2EventMessage_DBMS_PIPE;
begin
oMsg := TFDPhysDB2EventMessage_DBMS_PIPE(AEventMessage);
InternalHandleEvent(oMsg.FName, oMsg.FValues);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysDB2EventAlerter_DBMS_PIPE.InternalAbortJob;
begin
if FWaitThread <> nil then begin
FWaitThread.Terminate;
InternalSignal(GetNames()[0], Null);
FWaitCommand.AbortJob(True);
while (FWaitThread <> nil) and (FWaitThread.ThreadID <> TThread.Current.ThreadID) do
Sleep(1);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysDB2EventAlerter_DBMS_PIPE.InternalReleaseHandle;
begin
FReadCommand := nil;
FWriteCommand := nil;
inherited InternalReleaseHandle;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysDB2EventAlerter_DBMS_PIPE.InternalSignal(
const AEvent: String; const AArgument: Variant);
var
i: Integer;
oPar: TFDParam;
begin
if FSignalCommand = nil then begin
GetConnection.CreateCommand(FSignalCommand);
SetupCommand(FSignalCommand);
FSignalCommand.CommandText := 'BEGIN DECLARE i INTEGER; i := DBMS_PIPE.SEND_MESSAGE(:name); END;';
oPar := FSignalCommand.Params[0];
oPar.DataType := ftString;
oPar.Size := 128;
FSignalCommand.Prepare();
GetConnection.CreateCommand(FWriteCommand);
SetupCommand(FWriteCommand);
FWriteCommand.CommandText := 'BEGIN CALL DBMS_PIPE.PACK_MESSAGE(:name); END;';
end;
if VarIsArray(AArgument) then
for i := VarArrayLowBound(AArgument, 1) to VarArrayHighBound(AArgument, 1) do begin
FWriteCommand.Disconnect;
oPar := FWriteCommand.Params[0];
oPar.Clear();
oPar.DataType := ftUnknown;
oPar.Value := AArgument[i];
FWriteCommand.Execute();
end
else if not (VarIsNull(AArgument) or VarIsEmpty(AArgument)) then begin
FWriteCommand.Disconnect;
oPar := FWriteCommand.Params[0];
oPar.Clear();
oPar.DataType := ftUnknown;
oPar.Value := AArgument;
FWriteCommand.Execute();
end;
FSignalCommand.Params[0].AsString := AEvent;
FSignalCommand.Execute();
end;
{-------------------------------------------------------------------------------}
{ TFDPhysDB2Command }
{-------------------------------------------------------------------------------}
procedure TFDPhysDB2Command.InternalExecute(ATimes, AOffset: Integer;
var ACount: TFDCounter);
begin
inherited InternalExecute(ATimes, AOffset, ACount);
if GetCommandKind = skSetSchema then
TFDPhysDB2Connection(FConnectionObj).UpdateCurrentSchema;
end;
{-------------------------------------------------------------------------------}
function TFDPhysDB2Command.InternalOpen(var ACount: TFDCounter): Boolean;
begin
Result := inherited InternalOpen(ACount);
if GetCommandKind = skSetSchema then
TFDPhysDB2Connection(FConnectionObj).UpdateCurrentSchema;
end;
{-------------------------------------------------------------------------------}
function DB2NativeExceptionLoad(const AStorage: IFDStanStorage): TObject;
begin
Result := EDB2NativeException.Create;
EDB2NativeException(Result).LoadFromStorage(AStorage);
end;
{-------------------------------------------------------------------------------}
initialization
FDRegisterDriverClass(TFDPhysDB2Driver);
FDStorageManager().RegisterClass(EDB2NativeException, 'DB2NativeException',
@DB2NativeExceptionLoad, @FDExceptionSave);
finalization
FDUnregisterDriverClass(TFDPhysDB2Driver);
end.
|
{*******************************************************}
{ }
{ Borland Delphi Test Server }
{ }
{ Copyright (c) 2000-2001 Borland Software Corporation }
{ }
{*******************************************************}
unit SvrStatsFrame;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ActnList, SvrLog;
type
TStatsFrame = class(TFrame)
Button1: TButton;
ActionList1: TActionList;
ResetCountsAction: TAction;
lblTotalResponseTime: TLabel;
lblAvgResponseTime: TLabel;
lblLastResponseTime: TLabel;
lblRequestCount: TLabel;
Label3: TLabel;
Label5: TLabel;
Label7: TLabel;
Label8: TLabel;
Label1: TLabel;
Label2: TLabel;
lblMinResponseTime: TLabel;
lblMaxResponseTime: TLabel;
GroupBox1: TGroupBox;
procedure ResetCountsActionExecute(Sender: TObject);
procedure ResetCountsActionUpdate(Sender: TObject);
private
FResponseCount: Uint;
FRequestCount: Uint;
FTotalResponseTime: TDateTime;
FLastResponseTime: TDateTime;
FMaxResponseTime: TDateTime;
FMinResponseTime: TDateTime;
function GetAvgResponseTime: TDateTime;
procedure UpdateUI;
public
procedure LogStatistics(ATransaction: TTransactionLogEntry);
property RequestCount: Uint read FRequestCount;
property ResponseCount: Uint read FResponseCount;
property TotalResponseTime: TDateTime read FTotalResponseTime;
property AvgResponseTime: TDateTime read GetAvgResponseTime;
property LastResponseTime: TDateTime read FLastResponseTime;
property MaxResponseTime: TDateTime read FMaxResponseTime;
property MinResponseTime: TDateTime read FMinResponseTime;
end;
implementation
{$R *.dfm}
function TStatsFrame.GetAvgResponseTime: TDateTime;
begin
if ResponseCount <> 0 then
Result := TotalResponseTime / ResponseCount
else
Result := 0;
end;
procedure TStatsFrame.LogStatistics(ATransaction: TTransactionLogEntry);
begin
if ATransaction is TRequestTransaction then
Inc(FRequestCount);
if ATransaction is TResponseTransaction then
begin
Inc(FResponseCount);
FLastResponseTime := TResponseTransaction(ATransaction).ElapsedTime;
FTotalResponseTime :=
FTotalResponseTime + FLastResponseTime;
if (FMinResponseTime = 0) or (FLastResponseTime < FMinResponseTime) then
FMinResponseTime := FLastResponseTime;
if (FLastResponseTime > FMaxResponseTime) then
FMaxResponseTime := FLastResponseTime;
end;
UpdateUI;
end;
procedure TStatsFrame.ResetCountsActionExecute(Sender: TObject);
begin
FRequestCount := 0;
FTotalResponseTime := 0;
FResponseCount := 0;
FLastResponseTime := 0;
FMinResponseTime := 0;
FMaxResponseTime := 0;
UpdateUI;
end;
procedure TStatsFrame.ResetCountsActionUpdate(Sender: TObject);
begin
(Sender as TAction).Enabled := RequestCount > 0;
end;
procedure TStatsFrame.UpdateUI;
begin
lblRequestCount.Caption := IntToStr(RequestCount);
lblTotalResponseTime.Caption := FormatDateTime('hh:mm:ss:zzz', TotalResponseTime);
lblAvgResponseTime.Caption := FormatDateTime('hh:mm:ss:zzz', AvgResponseTime);
lblLastResponseTime.Caption := FormatDateTime('hh:mm:ss:zzz', LastResponseTime);
lblMinResponseTime.Caption := FormatDateTime('hh:mm:ss:zzz', MinResponseTime);
lblMaxResponseTime.Caption := FormatDateTime('hh:mm:ss:zzz', MaxResponseTime);
end;
end.
|
unit ufrmNewCourse;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, TypInfo, StdCtrls, uclAllClasses;
type
TfrmNewCourse = class(TForm)
pnlNewCourse: TPanel;
pnlInner: TPanel;
lblCourseName: TLabel;
lblHGeading: TLabel;
lblDuration: TLabel;
edtCourseName: TEdit;
edtDuration: TEdit;
comboxRatings: TComboBox;
btnAdd: TButton;
lblRating: TLabel;
procedure btnAddClick(Sender: TObject);
procedure edtDurationKeyPress(Sender: TObject; var Key: Char);
private
{ Private declarations }
FNewCourse: TStringList;
procedure SetNewCourse(const Value: TStringList);
public
{ Public declarations }
published
property CourseList : TStringList read FNewCourse write SetNewCourse;
end;
{==============================================================================}
implementation
uses ufrmMain;
{$R *.dfm}
procedure TfrmNewCourse.SetNewCourse(const Value: TStringList);
begin
FNewCourse := Value;
end;
{ Introducing new course on click ADD event }
procedure TfrmNewCourse.btnAddClick(Sender: TObject);
var
LCourse : TCourse;
begin
try
LCourse := TCourse.Create;
LCourse.CourseName := edtCourseName.Text;
if (LCourse.CourseName <> '') and (LCourse.CourseName <> ' ')
and (LCourse.CourseName <> ' ') then
begin
{Course duration should be in between 0 and 25 months}
if (StrToInt(edtDuration.Text) > 0) AND (StrToInt(edtDuration.Text) < 25) then
begin
LCourse.CourseDuration := StrToInt(edtDuration.Text);
{get enum is present in typeinfo unit and returns string from enum TRating}
LCourse.Ratings := GetEnumName(TypeInfo(TRating), Integer(comboxRatings.ItemIndex));
FNewCourse.Sorted := True;
FNewCourse.CaseSensitive := True;
FNewCourse.Duplicates := dupError;
FNewCourse.AddObject(LCourse.CourseName, LCourse);
MessageDlg('Course Added Sucessfully!!',mtInformation,[mbOK], 0);
end // inside if ends here
else
begin
MessageDlg('Course Duration should be greater than 0 month and less than 24 months',mtWarning,[mbOK], 0);
end; //inside else end here
end // if for blank entry ends here
else
begin
MessageDlg('Course name cannot be empty',mtWarning,[mbOK], 0);
end;
except
on E : EStringListError do
begin
MessageDlg('Duplicate Entry Not allowed',mtWarning,[mbOK], 0);
edtCourseName.Clear;
edtDuration.Clear;
comboxRatings.ItemIndex := -1;
end;
on E : Exception do
begin
MessageDlg('Illegal use of applicaion! Press Ok to Continue',mtError,[mbOK], 0);
edtCourseName.Clear;
edtDuration.Clear;
comboxRatings.ItemIndex := -1;
end;
end;
edtCourseName.Clear;
edtDuration.Clear;
comboxRatings.ItemIndex := -1;edtCourseName.Clear;
edtDuration.Clear;
comboxRatings.ItemIndex := -1;
end;
procedure TfrmNewCourse.edtDurationKeyPress(Sender: TObject;
var Key: Char);
begin
if not (Key in [#8, '0'..'9']) then //#8 is backspace
begin
ShowMessage('Invalid Key pressed');
Key := #0;
end;
end;
end. // end of Introduce course NewCourse unit
|
{ GS1 interface library for FPC and Lazarus
Copyright (C) 2020-2021 Lagunov Aleksey alexs75@yandex.ru
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at your
option) any later version with the following modification:
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent modules,and
to copy and distribute the resulting executable under terms of your choice,
provided that you also meet, for each linked independent module, the terms
and conditions of the license of that module. An independent module is a
module which is not derived from or based on this library. If you modify
this library, you may extend this exception to your version of the library,
but you are not obligated to do so. If you do not wish to do so, delete this
exception statement from your version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License
for more details.
You should have received a copy of the GNU Library General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
}
unit receipt_list;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, JSONObjects, AbstractSerializationObjects;
type
{ TDocumentDataDto }
TDocumentDataDto = class(TJSONSerializationObject)
private
FErrors: TXSDStringArray;
FReceiptId: TXSDStringArray;
procedure SetErrors(AValue: TXSDStringArray);
procedure SetReceiptId(AValue: TXSDStringArray);
protected
procedure InternalRegisterPropertys; override;
procedure InternalInitChilds; override;
public
destructor Destroy; override;
published
property Errors:TXSDStringArray read FErrors write SetErrors;
property ReceiptId:TXSDStringArray read FReceiptId write SetReceiptId;
end;
{ TReceiptContentItem }
TReceiptContentItem = class(TJSONSerializationObject)
private
FName: string;
FNds: Integer;
FNdsSum: Integer;
FPaymentType: Integer;
FPrice: Integer;
FProductCode: string;
FProductType: Integer;
FQuantity: Double;
FSum: Integer;
FUit: string;
procedure SetName(AValue: string);
procedure SetNds(AValue: Integer);
procedure SetNdsSum(AValue: Integer);
procedure SetPaymentType(AValue: Integer);
procedure SetPrice(AValue: Integer);
procedure SetProductCode(AValue: string);
procedure SetProductType(AValue: Integer);
procedure SetQuantity(AValue: Double);
procedure SetSum(AValue: Integer);
procedure SetUit(AValue: string);
protected
procedure InternalRegisterPropertys; override;
procedure InternalInitChilds; override;
public
destructor Destroy; override;
published
property PaymentType:Integer read FPaymentType write SetPaymentType;
property ProductType:Integer read FProductType write SetProductType;
property Name:string read FName write SetName;
property ProductCode:string read FProductCode write SetProductCode;
property Price:Integer read FPrice write SetPrice;
property Quantity:Double read FQuantity write SetQuantity;
property Nds:Integer read FNds write SetNds;
property NdsSum:Integer read FNdsSum write SetNdsSum;
property Sum:Integer read FSum write SetSum;
property Uit:string read FUit write SetUit;
end;
TReceiptContentItems = specialize GXMLSerializationObjectList<TReceiptContentItem>;
{ TReceiptContent }
TReceiptContent = class(TJSONSerializationObject)
private
FBuyerInn: string;
FCashTotalSum: Integer;
FCode: Integer;
FCreditSum: Integer;
FDateTime: Integer;
FEcashTotalSum: Integer;
FFiscalDocumentFormatVer: Integer;
FFiscalDocumentNumber: Integer;
FFiscalDriveNumber: string;
FIndicationfiscalSign: Integer;
FItems: TReceiptContentItems;
FkktRegId: string;
Fnds18: Integer;
FOfdINN: string;
FOperationType: Integer;
FOperatorFIO: string;
FOperatorInn: string;
FPrepaidSum: Integer;
FProvisionSum: Integer;
FRequestNumber: Integer;
FRetailAddress: string;
FRetailPlace: string;
FShiftNumber: Integer;
FTaxationType: Integer;
FTotalSum: Integer;
FUserInn: string;
procedure SetBuyerInn(AValue: string);
procedure SetCashTotalSum(AValue: Integer);
procedure SetCode(AValue: Integer);
procedure SetCreditSum(AValue: Integer);
procedure SetDateTime(AValue: Integer);
procedure SetEcashTotalSum(AValue: Integer);
procedure SetFiscalDocumentFormatVer(AValue: Integer);
procedure SetFiscalDocumentNumber(AValue: Integer);
procedure SetFiscalDriveNumber(AValue: string);
procedure SetIndicationfiscalSign(AValue: Integer);
procedure SetkktRegId(AValue: string);
procedure Setnds18(AValue: Integer);
procedure SetOfdINN(AValue: string);
procedure SetOperationType(AValue: Integer);
procedure SetOperatorFIO(AValue: string);
procedure SetOperatorInn(AValue: string);
procedure SetPrepaidSum(AValue: Integer);
procedure SetProvisionSum(AValue: Integer);
procedure SetRequestNumber(AValue: Integer);
procedure SetRetailAddress(AValue: string);
procedure SetRetailPlace(AValue: string);
procedure SetShiftNumber(AValue: Integer);
procedure SetTaxationType(AValue: Integer);
procedure SetTotalSum(AValue: Integer);
procedure SetUserInn(AValue: string);
protected
procedure InternalRegisterPropertys; override;
procedure InternalInitChilds; override;
public
destructor Destroy; override;
published
property Code:Integer read FCode write SetCode;
property IndicationfiscalSign:Integer read FIndicationfiscalSign write SetIndicationfiscalSign;
property FiscalDocumentFormatVer:Integer read FFiscalDocumentFormatVer write SetFiscalDocumentFormatVer;
property FiscalDocumentNumber:Integer read FFiscalDocumentNumber write SetFiscalDocumentNumber;
property FiscalDriveNumber:string read FFiscalDriveNumber write SetFiscalDriveNumber;
property UserInn:string read FUserInn write SetUserInn;
property BuyerInn:string read FBuyerInn write SetBuyerInn;
property RequestNumber:Integer read FRequestNumber write SetRequestNumber;
property DateTime:Integer read FDateTime write SetDateTime;
property ShiftNumber:Integer read FShiftNumber write SetShiftNumber;
property OperationType:Integer read FOperationType write SetOperationType;
property TaxationType:Integer read FTaxationType write SetTaxationType;
property OperatorFIO:string read FOperatorFIO write SetOperatorFIO;
property OperatorInn:string read FOperatorInn write SetOperatorInn;
property kktRegId:string read FkktRegId write SetkktRegId;
property RetailAddress:string read FRetailAddress write SetRetailAddress;
property RetailPlace:string read FRetailPlace write SetRetailPlace;
property Items:TReceiptContentItems read FItems;
property TotalSum:Integer read FTotalSum write SetTotalSum;
property CashTotalSum:Integer read FCashTotalSum write SetCashTotalSum;
property EcashTotalSum:Integer read FEcashTotalSum write SetEcashTotalSum;
property PrepaidSum:Integer read FPrepaidSum write SetPrepaidSum;
property CreditSum:Integer read FCreditSum write SetCreditSum;
property ProvisionSum:Integer read FProvisionSum write SetProvisionSum;
property nds18:Integer read Fnds18 write Setnds18;
property OfdINN:string read FOfdINN write SetOfdINN;
end;
{ TReceiptBody }
TReceiptBody = class(TJSONSerializationObject)
private
FReceipt: TReceiptContent;
protected
procedure InternalRegisterPropertys; override;
procedure InternalInitChilds; override;
public
destructor Destroy; override;
published
property Receipt:TReceiptContent read FReceipt;
end;
{ TReceiptItem }
TReceiptItem = class(TJSONSerializationObject)
private
FAType: string;
FBody: TReceiptBody;
FContent: string;
FDocDate: string;
FDocErrors: TXSDStringArray;
FDocumentDataDto: TDocumentDataDto;
FDownloadDesc: string;
FDownloadStatus: string;
FErrors: TXSDStringArray;
FInput: Boolean;
FNumber: string;
FPdfFile: string;
FReceivedAt: string;
FSenderName: string;
FStatus: string;
FTotal: Cardinal;
FVat: Cardinal;
procedure SetAType(AValue: string);
procedure SetContent(AValue: string);
procedure SetDocDate(AValue: string);
procedure SetDocErrors(AValue: TXSDStringArray);
procedure SetDownloadDesc(AValue: string);
procedure SetDownloadStatus(AValue: string);
procedure SetErrors(AValue: TXSDStringArray);
procedure SetInput(AValue: Boolean);
procedure SetNumber(AValue: string);
procedure SetPdfFile(AValue: string);
procedure SetReceivedAt(AValue: string);
procedure SetSenderName(AValue: string);
procedure SetStatus(AValue: string);
procedure SetTotal(AValue: Cardinal);
procedure SetVat(AValue: Cardinal);
protected
procedure InternalRegisterPropertys; override;
procedure InternalInitChilds; override;
public
constructor Create; override;
destructor Destroy; override;
published
property Number:string read FNumber write SetNumber;
property DocDate:string read FDocDate write SetDocDate;
property ReceivedAt:string read FReceivedAt write SetReceivedAt;
property AType:string read FAType write SetAType;
property Status:string read FStatus write SetStatus;
property SenderName:string read FSenderName write SetSenderName;
property Total:Cardinal read FTotal write SetTotal;
property Vat:Cardinal read FVat write SetVat;
property DownloadStatus:string read FDownloadStatus write SetDownloadStatus;
property DownloadDesc:string read FDownloadDesc write SetDownloadDesc;
property Input:Boolean read FInput write SetInput;
property PdfFile:string read FPdfFile write SetPdfFile;
property Errors:TXSDStringArray read FErrors write SetErrors;
property DocErrors:TXSDStringArray read FDocErrors write SetDocErrors;
property DocumentDataDto:TDocumentDataDto read FDocumentDataDto;
property Body:TReceiptBody read FBody;
property Content:string read FContent write SetContent;
end;
TReceiptItemList = specialize GXMLSerializationObjectList<TReceiptItem>;
{ TReceiptItems }
TReceiptItems = class(TJSONSerializationObject)
private
FResults: TReceiptItemList;
FTotal: Integer;
procedure SetTotal(AValue: Integer);
protected
procedure InternalRegisterPropertys; override;
procedure InternalInitChilds; override;
public
destructor Destroy; override;
constructor Create; override;
published
property Results:TReceiptItemList read FResults;
property Total:Integer read FTotal write SetTotal;
end;
implementation
{ TReceiptContentItem }
procedure TReceiptContentItem.SetName(AValue: string);
begin
if FName=AValue then Exit;
FName:=AValue;
ModifiedProperty('Name');
end;
procedure TReceiptContentItem.SetNds(AValue: Integer);
begin
if FNds=AValue then Exit;
FNds:=AValue;
ModifiedProperty('Nds');
end;
procedure TReceiptContentItem.SetNdsSum(AValue: Integer);
begin
if FNdsSum=AValue then Exit;
FNdsSum:=AValue;
ModifiedProperty('NdsSum');
end;
procedure TReceiptContentItem.SetPaymentType(AValue: Integer);
begin
if FPaymentType=AValue then Exit;
FPaymentType:=AValue;
ModifiedProperty('PaymentType');
end;
procedure TReceiptContentItem.SetPrice(AValue: Integer);
begin
if FPrice=AValue then Exit;
FPrice:=AValue;
ModifiedProperty('Price');
end;
procedure TReceiptContentItem.SetProductCode(AValue: string);
begin
if FProductCode=AValue then Exit;
FProductCode:=AValue;
ModifiedProperty('ProductCode');
end;
procedure TReceiptContentItem.SetProductType(AValue: Integer);
begin
if FProductType=AValue then Exit;
FProductType:=AValue;
ModifiedProperty('ProductType');
end;
procedure TReceiptContentItem.SetQuantity(AValue: Double);
begin
if FQuantity=AValue then Exit;
FQuantity:=AValue;
ModifiedProperty('Quantity');
end;
procedure TReceiptContentItem.SetSum(AValue: Integer);
begin
if FSum=AValue then Exit;
FSum:=AValue;
ModifiedProperty('Sum');
end;
procedure TReceiptContentItem.SetUit(AValue: string);
begin
if FUit=AValue then Exit;
FUit:=AValue;
ModifiedProperty('Uit');
end;
procedure TReceiptContentItem.InternalRegisterPropertys;
begin
inherited InternalRegisterPropertys;
RegisterProperty('PaymentType', 'paymentType', [], '', -1, -1);
RegisterProperty('ProductType', 'productType', [], '', -1, -1);
RegisterProperty('Name', 'name', [], '', -1, -1);
RegisterProperty('ProductCode', 'productCode', [], '', -1, -1);
RegisterProperty('Price', 'price', [], '', -1, -1);
RegisterProperty('Quantity', 'quantity', [], '', -1, -1);
RegisterProperty('Nds', 'nds', [], '', -1, -1);
RegisterProperty('NdsSum', 'ndsSum', [], '', -1, -1);
RegisterProperty('Sum', 'sum', [], '', -1, -1);
RegisterProperty('Uit', 'uit', [], '', -1, -1);
end;
procedure TReceiptContentItem.InternalInitChilds;
begin
inherited InternalInitChilds;
end;
destructor TReceiptContentItem.Destroy;
begin
inherited Destroy;
end;
{ TReceiptContent }
procedure TReceiptContent.SetCode(AValue: Integer);
begin
if FCode=AValue then Exit;
FCode:=AValue;
ModifiedProperty('Code');
end;
procedure TReceiptContent.SetCashTotalSum(AValue: Integer);
begin
if FCashTotalSum=AValue then Exit;
FCashTotalSum:=AValue;
ModifiedProperty('CashTotalSum');
end;
procedure TReceiptContent.SetBuyerInn(AValue: string);
begin
if FBuyerInn=AValue then Exit;
FBuyerInn:=AValue;
ModifiedProperty('BuyerInn');
end;
procedure TReceiptContent.SetCreditSum(AValue: Integer);
begin
if FCreditSum=AValue then Exit;
FCreditSum:=AValue;
ModifiedProperty('CreditSum');
end;
procedure TReceiptContent.SetDateTime(AValue: Integer);
begin
if FDateTime=AValue then Exit;
FDateTime:=AValue;
ModifiedProperty('DateTime');
end;
procedure TReceiptContent.SetEcashTotalSum(AValue: Integer);
begin
if FEcashTotalSum=AValue then Exit;
FEcashTotalSum:=AValue;
ModifiedProperty('EcashTotalSum');
end;
procedure TReceiptContent.SetFiscalDocumentFormatVer(AValue: Integer);
begin
if FFiscalDocumentFormatVer=AValue then Exit;
FFiscalDocumentFormatVer:=AValue;
ModifiedProperty('FiscalDocumentFormatVer');
end;
procedure TReceiptContent.SetFiscalDocumentNumber(AValue: Integer);
begin
if FFiscalDocumentNumber=AValue then Exit;
FFiscalDocumentNumber:=AValue;
ModifiedProperty('FiscalDocumentNumber');
end;
procedure TReceiptContent.SetFiscalDriveNumber(AValue: string);
begin
if FFiscalDriveNumber=AValue then Exit;
FFiscalDriveNumber:=AValue;
ModifiedProperty('FiscalDriveNumber');
end;
procedure TReceiptContent.SetIndicationfiscalSign(AValue: Integer);
begin
if FIndicationfiscalSign=AValue then Exit;
FIndicationfiscalSign:=AValue;
ModifiedProperty('IndicationfiscalSign');
end;
procedure TReceiptContent.SetkktRegId(AValue: string);
begin
if FkktRegId=AValue then Exit;
FkktRegId:=AValue;
ModifiedProperty('kktRegId');
end;
procedure TReceiptContent.Setnds18(AValue: Integer);
begin
if Fnds18=AValue then Exit;
Fnds18:=AValue;
ModifiedProperty('nds18');
end;
procedure TReceiptContent.SetOfdINN(AValue: string);
begin
if FOfdINN=AValue then Exit;
FOfdINN:=AValue;
ModifiedProperty('OfdINN');
end;
procedure TReceiptContent.SetOperationType(AValue: Integer);
begin
if FOperationType=AValue then Exit;
FOperationType:=AValue;
ModifiedProperty('OperationType');
end;
procedure TReceiptContent.SetOperatorFIO(AValue: string);
begin
if FOperatorFIO=AValue then Exit;
FOperatorFIO:=AValue;
ModifiedProperty('OperatorFIO');
end;
procedure TReceiptContent.SetOperatorInn(AValue: string);
begin
if FOperatorInn=AValue then Exit;
FOperatorInn:=AValue;
ModifiedProperty('OperatorInn');
end;
procedure TReceiptContent.SetPrepaidSum(AValue: Integer);
begin
if FPrepaidSum=AValue then Exit;
FPrepaidSum:=AValue;
ModifiedProperty('PrepaidSum');
end;
procedure TReceiptContent.SetProvisionSum(AValue: Integer);
begin
if FProvisionSum=AValue then Exit;
FProvisionSum:=AValue;
ModifiedProperty('ProvisionSum');
end;
procedure TReceiptContent.SetRequestNumber(AValue: Integer);
begin
if FRequestNumber=AValue then Exit;
FRequestNumber:=AValue;
ModifiedProperty('RequestNumber');
end;
procedure TReceiptContent.SetRetailAddress(AValue: string);
begin
if FRetailAddress=AValue then Exit;
FRetailAddress:=AValue;
ModifiedProperty('RetailAddress');
end;
procedure TReceiptContent.SetRetailPlace(AValue: string);
begin
if FRetailPlace=AValue then Exit;
FRetailPlace:=AValue;
ModifiedProperty('RetailPlace');
end;
procedure TReceiptContent.SetShiftNumber(AValue: Integer);
begin
if FShiftNumber=AValue then Exit;
FShiftNumber:=AValue;
ModifiedProperty('ShiftNumber');
end;
procedure TReceiptContent.SetTaxationType(AValue: Integer);
begin
if FTaxationType=AValue then Exit;
FTaxationType:=AValue;
ModifiedProperty('TaxationType');
end;
procedure TReceiptContent.SetTotalSum(AValue: Integer);
begin
if FTotalSum=AValue then Exit;
FTotalSum:=AValue;
ModifiedProperty('TotalSum');
end;
procedure TReceiptContent.SetUserInn(AValue: string);
begin
if FUserInn=AValue then Exit;
FUserInn:=AValue;
ModifiedProperty('UserInn');
end;
procedure TReceiptContent.InternalRegisterPropertys;
begin
inherited InternalRegisterPropertys;
RegisterProperty('Code', 'code', [], '', -1, -1);
RegisterProperty('IndicationfiscalSign', 'indicationfiscalSign', [], '', -1, -1);
RegisterProperty('FiscalDocumentFormatVer', 'fiscalDocumentFormatVer', [], '', -1, -1);
RegisterProperty('FiscalDocumentNumber', 'fiscalDocumentNumber', [], '', -1, -1);
RegisterProperty('FiscalDriveNumber', 'fiscalDriveNumber', [], '', -1, -1);
RegisterProperty('UserInn', 'userInn', [], '', -1, -1);
RegisterProperty('RequestNumber', 'requestNumber', [], '', -1, -1);
RegisterProperty('DateTime', 'dateTime', [], '', -1, -1);
RegisterProperty('ShiftNumber', 'shiftNumber', [], '', -1, -1);
RegisterProperty('OperationType', 'operationType', [], '', -1, -1);
RegisterProperty('TaxationType', 'taxationType', [], '', -1, -1);
RegisterProperty('OperatorFIO', 'operator', [], '', -1, -1);
RegisterProperty('OperatorInn', 'operatorInn', [], '', -1, -1);
RegisterProperty('BuyerInn', 'buyerInn', [], '', -1, -1);
RegisterProperty('kktRegId', 'kktRegId', [], '', -1, -1);
RegisterProperty('RetailAddress', 'retailAddress', [], '', -1, -1);
RegisterProperty('RetailPlace', 'retailPlace', [], '', -1, -1);
RegisterProperty('Items', 'items', [], '', -1, -1);
RegisterProperty('TotalSum', 'totalSum', [], '', -1, -1);
RegisterProperty('CashTotalSum', 'cashTotalSum', [], '', -1, -1);
RegisterProperty('EcashTotalSum', 'ecashTotalSum', [], '', -1, -1);
RegisterProperty('PrepaidSum', 'prepaidSum', [], '', -1, -1);
RegisterProperty('CreditSum', 'creditSum', [], '', -1, -1);
RegisterProperty('ProvisionSum', 'provisionSum', [], '', -1, -1);
RegisterProperty('nds18', 'nds18', [], '', -1, -1);
RegisterProperty('OfdINN', 'ofdINN', [], '', -1, -1);
end;
procedure TReceiptContent.InternalInitChilds;
begin
inherited InternalInitChilds;
FItems:=TReceiptContentItems.Create;
end;
destructor TReceiptContent.Destroy;
begin
FreeAndNil(FItems);
inherited Destroy;
end;
{ TReceiptBody }
procedure TReceiptBody.InternalRegisterPropertys;
begin
inherited InternalRegisterPropertys;
RegisterProperty('Receipt', 'receipt', [], '', -1, -1);
end;
procedure TReceiptBody.InternalInitChilds;
begin
inherited InternalInitChilds;
FReceipt:=TReceiptContent.Create;
end;
destructor TReceiptBody.Destroy;
begin
FreeAndNil(FReceipt);
inherited Destroy;
end;
{ TDocumentDataDto }
procedure TDocumentDataDto.SetErrors(AValue: TXSDStringArray);
begin
if FErrors=AValue then Exit;
FErrors:=AValue;
ModifiedProperty('Errors');
end;
procedure TDocumentDataDto.SetReceiptId(AValue: TXSDStringArray);
begin
if FreceiptId=AValue then Exit;
FreceiptId:=AValue;
ModifiedProperty('ReceiptId');
end;
procedure TDocumentDataDto.InternalRegisterPropertys;
begin
inherited InternalRegisterPropertys;
RegisterProperty('Errors', 'errors', [], '', -1, -1);
RegisterProperty('ReceiptId', 'receiptId', [], '', -1, -1);
end;
procedure TDocumentDataDto.InternalInitChilds;
begin
inherited InternalInitChilds;
end;
destructor TDocumentDataDto.Destroy;
begin
inherited Destroy;
end;
{ TReceiptItem }
procedure TReceiptItem.SetAType(AValue: string);
begin
if FAType=AValue then Exit;
FAType:=AValue;
ModifiedProperty('AType');
end;
procedure TReceiptItem.SetContent(AValue: string);
begin
if FContent=AValue then Exit;
FContent:=AValue;
ModifiedProperty('Content');
end;
procedure TReceiptItem.SetDocDate(AValue: string);
begin
if FDocDate=AValue then Exit;
FDocDate:=AValue;
ModifiedProperty('DocDate');
end;
procedure TReceiptItem.SetDocErrors(AValue: TXSDStringArray);
begin
if FDocErrors=AValue then Exit;
FDocErrors:=AValue;
ModifiedProperty('DocErrors');
end;
procedure TReceiptItem.SetDownloadDesc(AValue: string);
begin
if FDownloadDesc=AValue then Exit;
FDownloadDesc:=AValue;
ModifiedProperty('');
end;
procedure TReceiptItem.SetDownloadStatus(AValue: string);
begin
if FDownloadStatus=AValue then Exit;
FDownloadStatus:=AValue;
ModifiedProperty('DownloadStatus');
end;
procedure TReceiptItem.SetErrors(AValue: TXSDStringArray);
begin
if FErrors=AValue then Exit;
FErrors:=AValue;
ModifiedProperty('Errors');
end;
procedure TReceiptItem.SetInput(AValue: Boolean);
begin
if FInput=AValue then Exit;
FInput:=AValue;
ModifiedProperty('Input');
end;
procedure TReceiptItem.SetNumber(AValue: string);
begin
if FNumber=AValue then Exit;
FNumber:=AValue;
ModifiedProperty('Number');
end;
procedure TReceiptItem.SetPdfFile(AValue: string);
begin
if FPdfFile=AValue then Exit;
FPdfFile:=AValue;
ModifiedProperty('PdfFile');
end;
procedure TReceiptItem.SetReceivedAt(AValue: string);
begin
if FReceivedAt=AValue then Exit;
FReceivedAt:=AValue;
ModifiedProperty('ReceivedAt');
end;
procedure TReceiptItem.SetSenderName(AValue: string);
begin
if FSenderName=AValue then Exit;
FSenderName:=AValue;
ModifiedProperty('SenderName');
end;
procedure TReceiptItem.SetStatus(AValue: string);
begin
if FStatus=AValue then Exit;
FStatus:=AValue;
ModifiedProperty('Status');
end;
procedure TReceiptItem.SetTotal(AValue: Cardinal);
begin
if FTotal=AValue then Exit;
FTotal:=AValue;
ModifiedProperty('Total');
end;
procedure TReceiptItem.SetVat(AValue: Cardinal);
begin
if FVat=AValue then Exit;
FVat:=AValue;
ModifiedProperty('Vat');
end;
procedure TReceiptItem.InternalRegisterPropertys;
begin
inherited InternalRegisterPropertys;
RegisterProperty('Number', 'number', [], '', -1, -1);
RegisterProperty('DocDate', 'docDate', [], '', -1, -1);
RegisterProperty('ReceivedAt', 'receivedAt', [], '', -1, -1);
RegisterProperty('AType', 'type', [], '', -1, -1);
RegisterProperty('Status', 'status', [], '', -1, -1);
RegisterProperty('SenderName', 'senderName', [], '', -1, -1);
RegisterProperty('Total', 'total', [], '', -1, -1);
RegisterProperty('Vat', 'vat', [], '', -1, -1);
RegisterProperty('DownloadStatus', 'downloadStatus', [], '', -1, -1);
RegisterProperty('DownloadDesc', 'downloadDesc', [], '', -1, -1);
RegisterProperty('Input', 'input', [], '', -1, -1);
RegisterProperty('PdfFile', 'pdfFile', [], '', -1, -1);
RegisterProperty('DocErrors', 'docErrors', [], '', -1, -1);
RegisterProperty('Errors', 'errors', [], '', -1, -1);
RegisterProperty('DocumentDataDto', 'documentDataDto', [], '', -1, -1);
RegisterProperty('Body', 'body', [], '', -1, -1);
RegisterProperty('Content', 'content', [], '', -1, -1);
end;
procedure TReceiptItem.InternalInitChilds;
begin
inherited InternalInitChilds;
FDocumentDataDto:=TDocumentDataDto.Create;
FBody:=TReceiptBody.Create;
end;
constructor TReceiptItem.Create;
begin
inherited Create;
FIgnoreReadUndefProps:=true;
end;
destructor TReceiptItem.Destroy;
begin
FreeAndNil(FDocumentDataDto);
FreeAndNil(FBody);
inherited Destroy;
end;
{ TReceiptItems }
procedure TReceiptItems.SetTotal(AValue: Integer);
begin
if FTotal=AValue then Exit;
FTotal:=AValue;
ModifiedProperty('Total');
end;
procedure TReceiptItems.InternalRegisterPropertys;
begin
inherited InternalRegisterPropertys;
RegisterProperty('Results', 'results', [], '', -1, -1);
RegisterProperty('Total', 'total', [], '', -1, -1);
end;
procedure TReceiptItems.InternalInitChilds;
begin
inherited InternalInitChilds;
FResults:=TReceiptItemList.Create;
end;
destructor TReceiptItems.Destroy;
begin
FreeAndNil(FResults);
inherited Destroy;
end;
constructor TReceiptItems.Create;
begin
inherited Create;
FIgnoreReadUndefProps:=true;
end;
end.
|
unit MD5.Logs;
interface
uses
MD5.Utils,
System.Classes,
System.SysUtils,
System.StrUtils;
const
LOG_FILENAME_STAMP = 'dd-mm-yyyy@hh-nn-ss,z';
LOG_FILENAME_PREFIX = 'log_';
LOG_FILENAME_EXT = '.txt';
type
TLog = class
private
FStream: TStreamWriter;
FPrintDateTime: Boolean;
public
constructor Create(const BasePath: String; const FileNameSuffix: String; PrintDateTime: Boolean);
destructor Destroy; override;
// Вывод лога
procedure AddText(const S: String);
procedure AddLine; overload;
// Разграничение
procedure AddDiv; // одинарная граница
procedure AddPart; // двойная граница
end;
IMPLEMENTATION
{ TLogs }
procedure TLog.AddText(const S: String);
begin
FStream.WriteLine(S);
end;
procedure TLog.AddLine;
begin
FStream.WriteLine;
end;
procedure TLog.AddDiv;
begin
FStream.WriteLine(StringOfChar('.', 120));
end;
procedure TLog.AddPart;
begin
FStream.WriteLine(StringOfChar('=', 120+9));
end;
constructor TLog.Create(const BasePath: String; const FileNameSuffix: String; PrintDateTime: Boolean);
var
LogFileName: String;
begin
FPrintDateTime := PrintDateTime;
{ DONE 5 -cvery important :Если два раза запустить MD5, то тут произойдет ошибка при открытии файла log.txt.
Предусмотреть log файл, в имени которого будет дата и время создания. }
LogFileName := LOG_FILENAME_PREFIX +
FormatDateTime(LOG_FILENAME_STAMP, Now) +
IfThen(FileNameSuffix='', '', '-') +
FileNameSuffix +
LOG_FILENAME_EXT;
inherited Create;
FStream := TStreamWriter.Create(BasePath + LogFileName, TRUE, TEncoding.Unicode, 4096);
if FPrintDateTime then FStream.WriteLine('Log file created at ' + CurrentDateTime);
end;
destructor TLog.Destroy;
begin
if FPrintDateTime then
begin
AddDiv;
FStream.WriteLine('Log file closed at ' + CurrentDateTime);
end;
AddPart;
FStream.Free;
inherited;
end;
end.
|
unit oCoverSheetParam;
{
================================================================================
*
* Application: CPRS - Coversheet
* Developer: doma.user@domain.ext
* Site: Salt Lake City ISC
*
* Description: Simple object that maintains the parameters for any
* CoverSheet panel.
*
* Notes:
*
================================================================================
}
interface
uses
System.Classes,
System.SysUtils,
Vcl.Controls,
Vcl.Graphics,
iCoverSheetIntf;
type
TCoverSheetParam = class(TInterfacedObject, ICoverSheetParam)
private
//
protected
fID: integer;
fDisplayCol: integer;
fDisplayRow: integer;
fTitle: string;
function getID: integer;
function getDisplayColumn: integer;
function getDisplayRow: integer;
function getTitle: string;
procedure setDisplayColumn(const aValue: integer);
procedure setDisplayRow(const aValue: integer);
procedure setTitle(const aValue: string);
function NewCoverSheetControl(aOwner: TComponent): TControl; virtual; abstract;
public
constructor Create;
destructor Destroy; override;
end;
implementation
{ TCoverSheetParam }
constructor TCoverSheetParam.Create;
begin
inherited Create;
fID := 0;
fDisplayCol := -1;
fDisplayRow := -1;
fTitle := 'Base TCoverSheetParam';
end;
destructor TCoverSheetParam.Destroy;
begin
inherited;
end;
function TCoverSheetParam.getID: integer;
begin
Result := fID;
end;
function TCoverSheetParam.getDisplayColumn: integer;
begin
Result := fDisplayCol;
end;
function TCoverSheetParam.getDisplayRow: integer;
begin
Result := fDisplayRow;
end;
function TCoverSheetParam.getTitle: string;
begin
Result := fTitle;
end;
procedure TCoverSheetParam.setDisplayColumn(const aValue: integer);
begin
fDisplayCol := aValue;
end;
procedure TCoverSheetParam.setDisplayRow(const aValue: integer);
begin
fDisplayRow := aValue;
end;
procedure TCoverSheetParam.setTitle(const aValue: string);
begin
fTitle := aValue;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.