text stringlengths 14 6.51M |
|---|
unit FileUtils;
interface
uses
SysUtils;
const
MaxSizeOfBuffer = 256*1024;
type
TFile = class(TObject)
private
F: File of Byte;
Name: String;
Buffer: array[0..MaxSizeOfBuffer] of Byte;
PositionOfBuffer: Cardinal;
SizeOfBuffer: Cardinal;
public
Position: Cardinal;
Size: Cardinal;
constructor Open(FileName: String);
constructor Create(FileName: String);
destructor Destroy;
procedure Clear;
procedure ReadBit(Number: Cardinal; var Value: Byte);
procedure Read(var Buf; Count: Cardinal);
procedure ReadString(var Buf: String; Count: Cardinal);
procedure WriteBit(Number: Cardinal; var Value: Byte);
procedure Write(var Buf; Count: Cardinal);
procedure WriteString(var Buf: String; Count: Cardinal);
procedure Delete(Start, Count: Cardinal);
procedure Insert(Start, Count: Cardinal);
end;
implementation
constructor TFile.Open(FileName: String);
begin
inherited Create;
AssignFile(F, FileName);
Name := FileName;
Reset(F);
Position := 0;
PositionOfBuffer := 0;
if FileSize(F)>=MaxSizeOfBuffer then SizeOfBuffer := MaxSizeOfBuffer else SizeOfBuffer := FileSize(F);
BlockRead(F, Buffer, SizeOfBuffer);
if PositionOfBuffer+SizeOfBuffer<FileSize(F) then Size := FileSize(F) else Size := PositionOfBuffer+SizeOfBuffer;
end;
constructor TFile.Create(FileName: String);
begin
inherited Create;
AssignFile(F, FileName);
Name := FileName;
ReWrite(F);
Position := 0;
PositionOfBuffer := 0;
SizeOfBuffer := 0;
Size := 0;
end;
procedure TFile.ReadBit(Number: Cardinal; var Value: Byte);
var
PositionInByte, Mask, i: Byte;
begin
Position := Number div 8;
Read(Value, 1);
PositionInByte := Number mod 8;
Mask := 1;
for i := 1 to PositionInByte do Mask := Mask*2;
Value := Value and Mask;
if Value <> 0 then Value := 1;
end;
procedure TFile.Read(var Buf; Count: Cardinal);
var
i: Cardinal;
P: PByteArray;
begin
if Position>=Size then Position := Size-1;
if Position+Count>Size then Count := Size - Position;
if (Position<PositionOfBuffer)or(Position+Count>PositionOfBuffer+MaxSizeOfBuffer) then
begin
Seek(F, PositionOfBuffer);
BlockWrite(F, Buffer, SizeOfBuffer);
PositionOfBuffer := Position;
if Size-Position>=MaxSizeOfBuffer then SizeOfBuffer := MaxSizeOfBuffer else SizeOfBuffer := Size - Position;
Seek(F, PositionOfBuffer);
if SizeOfBuffer<>0 then BlockRead(F, Buffer, SizeOfBuffer);
end;
P := @Buf;
for i := 0 to Count-1 do P^[i] := Buffer[Position-PositionOfBuffer+i];
Position := Position+Count;
end;
procedure TFile.ReadString(var Buf: String; Count: Cardinal);
var
i: Cardinal;
Ch: Char;
begin
Buf := '';
for i := 1 to Count do
begin
Read(Ch, 1);
Buf := Buf + Ch;
end;
end;
procedure TFile.WriteBit(Number: Cardinal; var Value: Byte);
var
PositionInByte, Mask, Value2, i: Byte;
begin
Position := Number div 8;
Read(Value2, 1);
PositionInByte := Number mod 8;
Mask := 1;
for i := 1 to PositionInByte do Mask := Mask*2;
if Value = 0 then
Value2 := Value2 and (255-Mask)
else
Value2 := Value2 or Mask;
Position := Number div 8;
Write(Value2, 1);
end;
procedure TFile.Write(var Buf; Count: Cardinal);
var
i: Cardinal;
P: PByteArray;
begin
if Position>Size then Position := Size;
if (Position<PositionOfBuffer)or(Position+Count>PositionOfBuffer+MaxSizeOfBuffer) then
begin
Seek(F, PositionOfBuffer);
BlockWrite(F, Buffer, SizeOfBuffer);
PositionOfBuffer := Position;
if Size-Position>=MaxSizeOfBuffer then SizeOfBuffer := MaxSizeOfBuffer else SizeOfBuffer :=Size-Position;
Seek(F, PositionOfBuffer);
if SizeOfBuffer<>0 then BlockRead(F, Buffer, SizeOfBuffer);
end;
if Position+Count>PositionOfBuffer+SizeOfBuffer then
begin
SizeOfBuffer := Position-PositionOfBuffer+Count;
Size := PositionOfBuffer+SizeOfBuffer;
end;
P := @Buf;
for i := 0 to Count-1 do Buffer[Position-PositionOfBuffer+i] := P^[i];
Position := Position+Count;
end;
procedure TFile.WriteString(var Buf: String; Count: Cardinal);
var
i: Cardinal;
Ch: Char;
begin
for i := 1 to Count do
begin
Ch := Buf[i];
Write(Ch, 1);
end;
end;
procedure TFile.Clear;
begin
PositionOfBuffer := 0;
SizeOFBuffer := 0;
Position := 0;
Seek(F, 0);
if FileSize(F)<>0 then Truncate(F);
Size := 0;
end;
procedure TFile.Delete(Start, Count: Cardinal);
const
MaxBufSize = 128*1024;
var
BufSize: Cardinal;
Buf: array [0..MaxBufSize] of Byte;
i: Cardinal;
begin
if Start>Size then Exit;
if Start+Count>Size then Count := Size-Start;
Seek(F, PositionOfBuffer);
BlockWrite(F, Buffer, SizeOfBuffer);
Position := Start+Count;
if Size-Position>=MaxBufSize then BufSize := MaxBufSize else BufSize := Size-Position;
while BufSize<>0 do
begin
Seek(F, Position);
BlockRead(F, Buf, BufSize);
Seek(F, Start+Position-(Start+Count));
BlockWrite(F, Buf, BufSize);
Position := Position+BufSize;
if Size-Position>=MaxBufSize then BufSize := MaxBufSize else BufSize := Size-Position;
end;
Seek(F, Size-Count);
if Start<>Size then Truncate(F);
Size := FileSize(F);
PositionOfBuffer := 0;
Position := 0;
if Size>=MaxSizeOfBuffer then SizeOfBuffer := MaxSizeOfBuffer else SizeOfBuffer :=Size;
Seek(F, 0);
if SizeOfBuffer<>0 then BlockRead(F, Buffer, SizeOfBuffer);
end;
procedure TFile.Insert(Start, Count: Cardinal);
const
MaxBufSize = 128*1024;
var
BufSize: Cardinal;
Buf: array [0..MaxBufSize] of Byte;
i, PreviusSize: Cardinal;
begin
if Start>Size then Start := Size;
if Count = 0 then Exit;
PreviusSize := Size;
Position := Size;
for i := 1 to Count do Write(Buf, 1);
Seek(F, PositionOfBuffer);
BlockWrite(F, Buffer, SizeOfBuffer);
Position := PreviusSize;
while Position <> Start do
begin
if Position-Start<MaxBufSize then
begin
Position := Start;
BufSize := Position-Start;
end
else
begin
Position := Position-MaxBufSize;
BufSize := MaxBufSize;
end;
Seek(F, Position);
BlockRead(F, Buf, BufSize);
Seek(F, Position+Count);
BlockWrite(F, Buf, BufSize);
end;
PositionOfBuffer := 0;
Position := 0;
if Size>=MaxSizeOfBuffer then SizeOfBuffer := MaxSizeOfBuffer else SizeOfBuffer :=Size;
Seek(F, 0);
if SizeOfBuffer<>0 then BlockRead(F, Buffer, SizeOfBuffer);
end;
destructor TFile.Destroy;
begin
Seek(F, PositionOfBuffer);
BlockWrite(F, Buffer, SizeOfBuffer);
CloseFile(F);
inherited Destroy;
end;
end.
|
{
перехватчик реализующий сжатие и шифрование данных
}
unit aDCIntercept;
interface
uses
Classes, SysUtils,
IdGlobal, IdIntercept, IdCompressionIntercept, IdBlockCipherIntercept,
DCPcrypt2, DCPblowfish, DCPsha1;
type
TaDCBlockCipherIntercept = class(TIdBlockCipherIntercept)
private
FOnDecrypt: TIdInterceptStreamEvent;
FOnEncrypt: TIdInterceptStreamEvent;
protected
procedure Decrypt (var VData : TIdBytes); override;
procedure Encrypt (var VData : TIdBytes); override;
published
property OnDecrypt: TIdInterceptStreamEvent read FOnDecrypt write FOnDecrypt;
property OnEncrypt: TIdInterceptStreamEvent read FOnEncrypt write FOnEncrypt;
end;
TaDCIntercept = class(TIdConnectionIntercept)
private
FCrypter: TDCP_blockcipher;
FBlockCipherIntercept: TaDCBlockCipherIntercept;
FCompressionIntercept: TIdCompressionIntercept;
FCryptKey: RawByteString;
procedure SetCryptKey(const Value: RawByteString);
function GetCompressionLevel: TIdCompressionLevel;
procedure SetCompressionLevel(const Value: TIdCompressionLevel);
protected
procedure BlockCipherInterceptSend(ASender: TIdConnectionIntercept; var VBuffer: TIdBytes);
procedure BlockCipherInterceptReceive(ASender: TIdConnectionIntercept; var VBuffer: TIdBytes);
public
destructor Destroy; override;
procedure Receive(var VBuffer: TIdBytes); override;
procedure Send(var VBuffer: TIdBytes); override;
published
property Intercept;
property CompressionLevel: TIdCompressionLevel read GetCompressionLevel write SetCompressionLevel;
property CryptKey: RawByteString read FCryptKey write SetCryptKey;
end;
implementation
{ TaDCIntercept }
procedure TaDCIntercept.BlockCipherInterceptReceive(ASender: TIdConnectionIntercept; var VBuffer: TIdBytes);
var
LCount: Byte;
LCountPos: Byte;
begin
{.$R-}
LCountPos := FBlockCipherIntercept.BlockSize - 1;
//LCount := TBytes(ASrcData)[LCountPos];
//LCount := PByte(longword(ASrcData)+LCountPos)^;
LCount := VBuffer[LCountPos];
FCrypter.Reset;
FCrypter.Decrypt(VBuffer[0], VBuffer[0], LCount);
//TBytes(ADstData)[LCountPos] := LCount;
//PByte(longword(ADstData)+LCountPos)^ := LCount;
VBuffer[LCountPos] := LCount;
{.$R+}
end;
procedure TaDCIntercept.BlockCipherInterceptSend(ASender: TIdConnectionIntercept; var VBuffer: TIdBytes);
var
LCount: Byte;
LCountPos: Byte;
begin
{.$R-}
LCountPos := FBlockCipherIntercept.BlockSize - 1;
//LCount := TBytes(ASrcData)[LCountPos];
//LCount := PByte(longword(ASrcData)+LCountPos)^;
LCount := VBuffer[LCountPos];
FCrypter.Reset;
FCrypter.Encrypt(VBuffer[0], VBuffer[0], LCount);
//TBytes(ADstData)[LCountPos] := LCount;
//PByte(longword(ADstData)+LCountPos)^ := LCount;
VBuffer[LCountPos] := LCount;
{.$R+}
end;
destructor TaDCIntercept.Destroy;
begin
FreeAndNil(FCompressionIntercept);
FreeAndNil(FBlockCipherIntercept);
FreeAndNil(FCrypter);
inherited Destroy;
end;
function TaDCIntercept.GetCompressionLevel: TIdCompressionLevel;
begin
if Assigned(FCompressionIntercept) then
Result := FCompressionIntercept.CompressionLevel
else
Result := 0;
end;
procedure TaDCIntercept.Receive(var VBuffer: TIdBytes);
begin
inherited Receive(VBuffer);
// при приеме
// сначала расшифровываем
if Assigned(FBlockCipherIntercept) then
FBlockCipherIntercept.Receive(VBuffer);
// а потом разжимаем
if Assigned(FCompressionIntercept) then
FCompressionIntercept.Receive(VBuffer);
end;
procedure TaDCIntercept.Send(var VBuffer: TIdBytes);
begin
inherited Send(VBuffer);
// при отправке
// сначала сжимаем
if Assigned(FCompressionIntercept) then
FCompressionIntercept.Send(VBuffer);
// а потом шифруем
if Assigned(FBlockCipherIntercept) then
FBlockCipherIntercept.Send(VBuffer);
end;
procedure TaDCIntercept.SetCompressionLevel(const Value: TIdCompressionLevel);
begin
if Value = CompressionLevel then
Exit;
FreeAndNil(FCompressionIntercept);
if Value = 0 then
Exit;
FCompressionIntercept := TIdCompressionIntercept.Create(nil);
FCompressionIntercept.CompressionLevel := Value;
end;
procedure TaDCIntercept.SetCryptKey(const Value: RawByteString);
begin
if FCryptKey = Value then
Exit;
FreeAndNil(FBlockCipherIntercept);
FreeAndNil(FCrypter);
FCryptKey := Value;
if Length(FCryptKey) = 0 then
Exit;
FCrypter := TDCP_blowfish.Create(nil);
FCrypter.InitStr(FCryptKey, TDCP_sha1);
FBlockCipherIntercept := TaDCBlockCipherIntercept.Create(nil);
FBlockCipherIntercept.BlockSize := (FCrypter.BlockSize div 8) + 1;
//FBlockCipherIntercept.OnReceive := BlockCipherInterceptReceive;
//FBlockCipherIntercept.OnSend := BlockCipherInterceptSend;
FBlockCipherIntercept.OnDecrypt := BlockCipherInterceptReceive;
FBlockCipherIntercept.OnEncrypt := BlockCipherInterceptSend;
end;
{ TaDCBlockCipherIntercept }
procedure TaDCBlockCipherIntercept.Decrypt(var VData: TIdBytes);
begin
if Assigned(FOnDecrypt) then
FOnDecrypt(Self, VData);
end;
procedure TaDCBlockCipherIntercept.Encrypt(var VData: TIdBytes);
begin
if Assigned(FOnEncrypt) then
FOnEncrypt(Self, VData);
end;
end.
|
unit ufMain;
{*******************************************************************************
Project link : https://https://github.com/gilmarcarvalho/DemoRESTBase64
Created In : 2019-09-04 13:18:10
Created By : Gilmar Alves de Carvalho - (linkedin.com/in/gilmar-carvalho)
*******************************************************************************}
interface
uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Data.DB,
FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param,
FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf,
FireDAC.Comp.DataSet, FireDAC.Comp.Client, Vcl.Grids,
Vcl.DBGrids, Data.Bind.Components, Data.Bind.ObjectScope,
Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.ValEdit, Vcl.ComCtrls,System.NetEncoding,
Vcl.Imaging.Jpeg, WSClient,Dialogs;
type
TfMain = class(TForm)
Edit1: TEdit;
Label1: TLabel;
Label4: TLabel;
PageControl1: TPageControl;
TabSheet2: TTabSheet;
DBGrid3: TDBGrid;
FDMemTable1: TFDMemTable;
DataSource1: TDataSource;
Panel1: TPanel;
Button2: TButton;
Panel2: TPanel;
Label2: TLabel;
FDMemTable1Codigo: TIntegerField;
FDMemTable1Nome: TStringField;
FDMemTable1Imagem: TBlobField;
Label3: TLabel;
RichEdit1: TRichEdit;
Panel3: TPanel;
Image1: TImage;
procedure FDMemTable1AfterScroll(DataSet: TDataSet);
procedure FormShow(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
Processing:boolean;
baseURL:string;
WSClient:TWSClient;
Procedure Base64toPicture(B64Value:string; toPic:TPicture);
public
{ Public declarations }
end;
var
fMain: TfMain;
implementation
{$R *.dfm}
procedure TfMain.Base64toPicture(B64Value:string; toPic:TPicture);
var st : TStringStream;
Img : TMemoryStream;
begin
{declare unit for each corresponding
image format ex.vcl.imaging.jpeg, vlc.imaging.png}
try
st := TStringStream.Create(B64Value);
st.Position := 0;
img := TMemoryStream.Create;
TNetEncoding.Base64.Decode(st, img);
img.Position := 0;
toPic.LoadFromStream(img);
finally
st.Free;
img.Free;
end;
end;
procedure TfMain.Button2Click(Sender: TObject);
begin
processing:=true;
wsclient.JsonToDataset(baseURL+'/tpessoa/list',fdmemtable1);
processing:=false;
end;
procedure TfMain.FDMemTable1AfterScroll(DataSet: TDataSet);
var
s:string;
begin
if processing then exit;
s:=fdmemtable1.Fields[2].AsString;
richedit1.Lines.Text:=s;
Base64toPicture(s,image1.Picture);
end;
procedure TfMain.FormClose(Sender: TObject; var Action: TCloseAction);
begin
wsclient.Free;
end;
procedure TfMain.FormShow(Sender: TObject);
begin
WSClient:=tWSClient.create;
baseurl:='http://localhost:8080/datasnap/rest';
end;
end.
|
(******************************************************************************
* PasVulkan *
******************************************************************************
* Version see PasVulkan.Framework.pas *
******************************************************************************
* zlib license *
*============================================================================*
* *
* Copyright (C) 2016-2020, Benjamin Rosseaux (benjamin@rosseaux.de) *
* *
* This software is provided 'as-is', without any express or implied *
* warranty. In no event will the authors be held liable for any damages *
* arising from the use of this software. *
* *
* Permission is granted to anyone to use this software for any purpose, *
* including commercial applications, and to alter it and redistribute it *
* freely, subject to the following restrictions: *
* *
* 1. The origin of this software must not be misrepresented; you must not *
* claim that you wrote the original software. If you use this software *
* in a product, an acknowledgement in the product documentation would be *
* appreciated but is not required. *
* 2. Altered source versions must be plainly marked as such, and must not be *
* misrepresented as being the original software. *
* 3. This notice may not be removed or altered from any source distribution. *
* *
******************************************************************************
* General guidelines for code contributors *
*============================================================================*
* *
* 1. Make sure you are legally allowed to make a contribution under the zlib *
* license. *
* 2. The zlib license header goes at the top of each source file, with *
* appropriate copyright notice. *
* 3. This PasVulkan wrapper may be used only with the PasVulkan-own Vulkan *
* Pascal header. *
* 4. After a pull request, check the status of your pull request on *
http://github.com/BeRo1985/pasvulkan *
* 5. Write code which's compatible with Delphi >= 2009 and FreePascal >= *
* 3.1.1 *
* 6. Don't use Delphi-only, FreePascal-only or Lazarus-only libraries/units, *
* but if needed, make it out-ifdef-able. *
* 7. No use of third-party libraries/units as possible, but if needed, make *
* it out-ifdef-able. *
* 8. Try to use const when possible. *
* 9. Make sure to comment out writeln, used while debugging. *
* 10. Make sure the code compiles on 32-bit and 64-bit platforms (x86-32, *
* x86-64, ARM, ARM64, etc.). *
* 11. Make sure the code runs on all platforms with Vulkan support *
* *
******************************************************************************)
unit PasVulkan.CPU.Info;
{$i PasVulkan.inc}
{$ifndef fpc}
{$ifdef conditionalexpressions}
{$if CompilerVersion>=24.0}
{$legacyifend on}
{$ifend}
{$endif}
{$endif}
interface
uses SysUtils,
Classes,
Math,
Vulkan,
PasMP,
PasVulkan.Types;
const CPUFeatures_X86_F16C_Mask=1 shl 0;
type TCPUFeatures=TpvUInt32;
var CPUFeatures:TCPUFeatures=0;
procedure CheckCPU;
implementation
var CPUChecked:TPasMPBool32=false;
{$if defined(cpu386) or defined(cpuamd64) or defined(cpux86_64) or defined(cpux64)}
type TCPUIDData=record
case TpvUInt32 of
0:(
Data:array[0..3] of TpvUInt32;
);
1:(
EAX,EBX,EDX,ECX:TpvUInt32;
);
2:(
String_:array[0..15] of AnsiChar;
);
end;
PCPUIDData=^TCPUIDData;
procedure GetCPUID(Value:TpvUInt32;out Data:TCPUIDData); assembler;
asm
{$if defined(cpuamd64) or defined(cpux86_64) or defined(cpux64)}
push rbx
{$if defined(Windows) or defined(Win32) or defined(Win64)}
// Win64 ABI (rcx, rdx, ...)
mov eax,ecx
mov r8,rdx
{$else}
// SysV x64 ABI (rdi, rsi, ...)
mov eax,edi
mov r8,rsi
{$ifend}
{$else}
// register (eax, edx, ...)
push ebx
push edi
mov edi,edx
{$ifend}
cpuid
{$if defined(cpuamd64) or defined(cpux86_64) or defined(cpux64)}
mov dword ptr [r8+0],eax
mov dword ptr [r8+4],ebx
mov dword ptr [r8+8],edx
mov dword ptr [r8+12],ecx
pop rbx
{$else}
mov dword ptr [edi+0],eax
mov dword ptr [edi+4],ebx
mov dword ptr [edi+8],edx
mov dword ptr [edi+12],ecx
pop edi
pop ebx
{$ifend}
end;
{$ifend}
procedure DoCheckCPU;
{$if defined(cpu386) or defined(cpuamd64) or defined(cpux86_64) or defined(cpux64)}
var CPUIDData:TCPUIDData;
begin
CPUFeatures:=0;
begin
GetCPUID(0,CPUIDData);
end;
begin
GetCPUID(1,CPUIDData);
if (CPUIDData.ECX and (TpvUInt32(1) shl 29))<>0 then begin
CPUFeatures:=CPUFeatures or CPUFeatures_X86_F16C_Mask;
end;
end;
end;
{$else}
begin
end;
{$ifend}
procedure CheckCPU;
begin
if (not CPUChecked) and
(not TPasMPInterlocked.CompareExchange(CPUChecked,TPasMPBool32(true),TPasMPBool32(false))) then begin
DoCheckCPU;
end;
end;
initialization
CheckCPU;
end.
|
(*======================================================================*
| unitProcesses |
| |
| OS agnostic process enumeration classes. |
| |
| 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/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. |
| |
| Copyright © Colin Wilson 2005 All Rights Reserved |
| |
| Version Date By Description |
| ------- ---------- ---- ------------------------------------------|
| 10.0 08/03/2006 CPWW BDS 2006 release version |
*======================================================================*)
unit unitProcesses;
interface
uses Windows, Classes, SysUtils, psapi, tlhelp32, contnrs, DateUtils;
type
TProcessSnapshot = class;
TProcess = class;
TModule = class
private
fOwner : TProcess;
fFileName : string;
fhModule : THandle;
fVersionCache : string;
fFileDateTime : TDateTime;
fFileSize : DWORD;
fObjectTag: TObject;
function GetVersion: string; // Module handle (in the context of the module's process)
procedure GetFileDetails;
function GetFileDateTime: TDateTime;
function GetFileSize: DWORD;
function GetFileName: string;
protected
constructor Create (AOwner : TProcess; fInitDetails : PModuleEntry32); overload;
constructor Create (AOwner : TProcess; hOwner, hModule : THandle); overload;
public
property FileName : string read GetFileName;
property Version : string read GetVersion;
property FileDateTime : TDateTime read GetFileDateTime;
property FileSize : DWORD read GetFileSize;
property ObjectTag : TObject read fObjectTag write fObjectTag;
property Owner : TProcess read fOwner;
end;
TProcess = class
private
fParentProcessID: DWORD;
fProcessID: DWORD;
fEXEName: string;
fBasePriority : Longint;
fModules : TObjectList;
fObjectTag: TObject;
fOwner : TProcessSnapshot;
constructor Create (AOwner : TProcessSnapshot; fInitDetails : PProcessEntry32); overload;
constructor Create (AOwner : TProcessSnapshot; fPID : DWORD); overload;
function GetModule(idx: Integer): TModule;
function GetModuleCount: Integer;
function GetBaseModule: TModule;
public
destructor Destroy; override;
property ProcessID : DWORD read fProcessID;
property ParentProcessID : DWORD read fParentProcessID;
property EXEName : string read fEXEName;
property BasePriority : Longint read fBasePriority;
property ModuleCount : Integer read GetModuleCount;
property Module [idx : Integer] : TModule read GetModule; default;
property BaseModule : TModule read GetBaseModule;
property ObjectTag : TObject read fObjectTag write fObjectTag;
end;
TPSSortColumn = (psPID, psParentPID, psBasePriority, psName, psDate, psSize, psVersion);
TPSSortDirection = (psAscending, psDescending);
TProcessEnumerator = (peAuto, peToolHelp, pePSAPI);
TProcessSnapshot = class (TComponent)
private
fProcesses : TObjectList;
fProcessEnumerator: TProcessEnumerator;
fSortColumn : TPSSortColumn;
fSortDirection : TPSSortDirection;
function GetProcess(idx: Integer): TProcess;
function GetProcessCount: Integer;
procedure SetProcessEnumerator(const Value: TProcessEnumerator);
procedure LoadEnumerator;
protected
procedure Loaded; override;
public
constructor Create (AOwner : TComponent); override;
destructor Destroy; override;
procedure SortProcesses (column : TPSSortColumn; direction : TPSSortDirection);
procedure TakeSnapshot;
property ProcessCount : Integer read GetProcessCount;
property Process [idx : Integer] : TProcess read GetProcess; default;
property SortColumn : TPSSortColumn read fSortColumn;
property SortDirection : TPSSortDirection read fSortDirection;
published
property ProcessEnumerator : TProcessEnumerator read fProcessEnumerator write SetProcessEnumerator;
end;
EProcessSnapshot = class (exception);
procedure CheckToolHelp;
procedure CheckPSAPI;
implementation
resourcestring
rstNoToolHelp = 'Internal error. No ToolHelp';
rstNoPSAPI = 'Internal error. No PSAPI';
rstCantSnapshot = 'Internal error. Can''t enumerate processes on this computer';
rstIdle = 'Idle';
rstSystem = 'System';
const SE_DEBUG_NAME = 'SeDebugPrivilege';
type // Support for NtQueryInformationProcess
TProcessInfoClass = (
ProcessBasicInformation,
ProcessQuotaLimits,
ProcessIoCounters,
ProcessVmCounters,
ProcessTimes,
ProcessBasePriority,
ProcessRaisePriority,
ProcessDebugPort,
ProcessExceptionPort,
ProcessAccessToken,
ProcessLdtInformation,
ProcessLdtSize,
ProcessDefaultHardErrorMode,
ProcessIoPortHandlers, // Note: this is kernel mode only
ProcessPooledUsageAndLimits,
ProcessWorkingSetWatch,
ProcessUserModeIOPL,
ProcessEnableAlignmentFaultFixup,
ProcessPriorityClass,
ProcessWx86Information,
ProcessHandleCount,
ProcessAffinityMask,
ProcessPriorityBoost,
ProcessDeviceMap,
ProcessSessionInformation,
ProcessForegroundInformation,
ProcessWow64Information,
MaxProcessInfoClass);
TProcessBasicInformation = record
ExitStatus : Longint;
PebBaseAddress : Pointer;
AffinityMask : DWORD;
BasePriority : Longint;
UniqueProcessId : DWORD;
InheritedFromUniqueProcessId : DWORD;
end;
TfnNtQueryInformationProcess = function (
Handle : THandle;
infoClass : TProcessInfoClass;
processInformation : Pointer;
processInformationLength : ULONG;
returnLength : PULONG
) : DWORD; stdcall;
var
gUsesToolHelp : boolean = False;
gUsesPSAPI : boolean = False;
gCheckedToolHelp : boolean = False;
gCheckedPSAPI : boolean = False;
gOldState : DWORD = $BadF00d;
NTQueryInformationProcess : TfnNTQueryInformationProcess;
function EnableNTPrivilege (const privilege : string; state : Integer) : Integer;
var
hToken : THandle;
aluid : TLargeInteger;
cbPrevTP : DWORD;
tp, fPrevTP : PTokenPrivileges;
begin
result := 0;
if OpenProcessToken (GetCurrentProcess, TOKEN_ADJUST_PRIVILEGES or TOKEN_QUERY, hToken) then
try
LookupPrivilegeValue (Nil, PChar (privilege), aluid);
cbPrevTP := SizeOf (TTokenPrivileges) + sizeof (TLUIDAndAttributes);
GetMem (tp, cbPrevTP);
GetMem (fPrevTP, cbPrevTP);
try
tp^.PrivilegeCount := 1;
tp^.Privileges [0].Luid := aLuid;
tp^.Privileges [0].Attributes := state;
if not AdjustTokenPrivileges (hToken, False, tp^, cbPrevTP, fPrevTP^, cbPrevTP) then
RaiseLastOSError;
result := fPrevTP^.Privileges [0].Attributes;
finally
FreeMem (fPrevTP);
FreeMem (tp);
end
finally
CloseHandle (hToken);
end
end;
function GetFileVersion (const fileName : string) : string;
var
size, zero : DWORD;
buffer, pBuffer: pointer;
info : PVSFixedFileInfo;
begin
result := '';
size := GetFileVersionInfoSize (PChar (FileName), zero);
if size > 0 then
begin
GetMem (buffer, size);
if not GetFileVersionInfo (PChar (FileName), zero, size, buffer) then
RaiseLastOSError;
if not VerQueryValue (buffer, '\', pBuffer, size) then
RaiseLastOSError;
info := PVSFixedFileInfo (pBuffer);
result := Format ('%d.%d.%d.%d', [HiWord (info^.dwProductVersionMS), LoWord (info^.dwProductVersionMS), HiWord (info^.dwProductVersionLS), LoWord (info^.dwProductVersionLS)])
end
else
result := '-'
end;
function UsesToolHelp : boolean;
var
KernelHandle : THandle;
begin
if not gCheckedToolHelp then
begin
gCheckedToolHelp := True;
KernelHandle := GetModuleHandle(kernel32);
gUsesToolHelp := Assigned (GetProcAddress(KernelHandle, 'CreateToolhelp32Snapshot'))
end;
result := gUsesToolHelp
end;
function UsesPSAPI : boolean;
var
hPSAPI : THandle;
hNTDLL : THandle;
begin
if not gCheckedPSAPI then
begin
gCheckedPSAPI := True;
hPSAPI := LoadLibrary('PSAPI.dll');
if hPSAPI <> 0 then
begin
FreeLibrary (hPSAPI);
gUsesPSAPI := True;
hNTDLL := GetModuleHandle ('ntdll.dll');
if hNTDLL <> 0 then
begin
NTQueryInformationProcess := GetProcAddress (hNTDLL, 'ZwQueryInformationProcess');
if not Assigned (NTQueryInformationProcess) then
raise EProcessSnapshot.Create(rstCantSnapshot);
end
end
end;
result := gUsesPSAPI
end;
procedure CheckToolHelp;
begin
if not UsesToolHelp then
raise EProcessSnapshot.Create(rstNoToolhelp);
end;
procedure CheckPSAPI;
begin
if not UsesPSAPI then
raise EProcessSnapshot.Create (rstNoPSAPI)
end;
{ TProcess }
constructor TProcess.Create(AOwner: TProcessSnapshot;
fInitDetails: PProcessEntry32);
var
hSnapshot : THandle;
moduleEntry : TModuleEntry32;
begin
fOwner := AOwner;
CheckToolHelp;
fModules := TObjectList.Create;
fProcessID := fInitDetails^.th32ProcessID;
fParentProcessID := fInitDetails^.th32ParentProcessID;
fEXEName := fInitDetails^.szExeFile;
fBasePriority := fInitDetails^.pcPriClassBase;
if fParentProcessID <> 0 then
begin
hSnapshot := TlHelp32.CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, fProcessID);
if hSnapshot <> INVALID_HANDLE_VALUE then
try
moduleEntry.dwSize := sizeof (moduleEntry);
if Module32First (hSnapshot, moduleentry) then
begin
fEXEName := moduleEntry.szExePath;
repeat
fModules.Add(TModule.Create(self, @moduleEntry))
until not Module32Next (hSnapshot, moduleEntry)
end
finally
Closehandle (hSnapshot)
end
end
end;
constructor TProcess.Create(AOwner: TProcessSnapshot; fPID: DWORD);
var
hProcess : THandle;
processInfo : TProcessBasicInformation;
baseName : array [0..MAX_PATH] of char;
buffer, p : PDWORD;
bufLen : DWORD;
i, modCount : Integer;
begin
fOwner := AOwner;
CheckPSAPI;
fModules := TObjectList.Create;
fProcessID := fPID;
if fPID = 0 then
fEXEName := rstIdle
else
begin
hProcess := OpenProcess (PROCESS_QUERY_INFORMATION or PROCESS_VM_READ, False, fPid);
if hProcess <> 0 then
try
buffer := Nil;
try
ReallocMem (buffer, 1024*1024);
if not psapi.EnumProcessModules(hProcess, buffer, 1024*1024, bufLen) then bufLen := 0;
ReallocMem (buffer, bufLen);
modCount := bufLen div sizeof (PDWORD);
p := buffer;
for i := 0 to modCount - 1 do
begin
fModules.Add(TModule.Create(self, hProcess, p^));
Inc (p)
end
finally
ReallocMem (buffer, 0)
end;
if psapi.GetModuleBaseName(hProcess, 0, baseName, sizeof (baseName)) > 0 then
fEXEName := baseName
else
fEXEName := rstSystem;
if NTQueryInformationProcess (hProcess, ProcessBasicInformation, @processInfo, SizeOf (processInfo), nil) = 0 then
begin
fParentProcessID := processInfo.InheritedFromUniqueProcessId;
fBasePriority := processInfo.BasePriority
end
finally
CloseHandle (hProcess)
end
end
end;
destructor TProcess.Destroy;
begin
fModules.Free;
inherited;
end;
function TProcess.GetBaseModule: TModule;
begin
if ModuleCount > 0 then
result := Module [0]
else
result := Nil
end;
function TProcess.GetModule(idx: Integer): TModule;
begin
result := TModule (fModules [idx])
end;
function TProcess.GetModuleCount: Integer;
begin
result := fModules.Count
end;
{ TProcessSnapshot }
constructor TProcessSnapshot.Create;
begin
inherited Create (Aowner);
fSortColumn := psPID;
fProcesses := TObjectList.Create;
if not (csDesigning in ComponentState) then
LoadEnumerator;
end;
destructor TProcessSnapshot.Destroy;
begin
fProcesses.Free;
inherited;
end;
function TProcessSnapshot.GetProcess(idx: Integer): TProcess;
begin
result := TProcess (fProcesses [idx]);
end;
function TProcessSnapshot.GetProcessCount: Integer;
begin
result := fProcesses.Count
end;
procedure TProcessSnapshot.Loaded;
begin
inherited;
LoadEnumerator;
end;
procedure TProcessSnapshot.LoadEnumerator;
begin
if (csDesigning in ComponentState) or (csLoading in ComponentState) then
Exit;
gUsesToolHelp := False;
gUsesPSAPI := False;
gCheckedToolHelp := False;
gCheckedPSAPI := False;
case ProcessEnumerator of
peAuto: if not UsesPSAPI and not UsesToolHelp then
raise EProcessSnapshot.Create (rstCantSnapshot);
pePSAPI : CheckPSAPI;
peToolHelp : CheckToolHelp;
end;
TakeSnapshot;
end;
procedure TProcessSnapshot.SetProcessEnumerator(
const Value: TProcessEnumerator);
begin
if Value <> fProcessEnumerator then
begin
fProcessEnumerator := Value;
if not (csLoading in ComponentState) then
LoadEnumerator;
end
end;
function CompareProcesses (p1, p2 : Pointer) : Integer;
var
pr1, pr2 : TProcess;
m1, m2 : TModule;
column : TPSSortColumn;
direction : TPSSortDirection;
begin
pr1 := TProcess (p1);
pr2 := TProcess (p2);
m1 := pr1.BaseModule;
m2 := pr2.BaseModule;
column := pr1.fOwner.fSortColumn;
direction := pr1.fOwner.fSortDirection;
result := 99;
if (column in [psDate, psSize]) and ((m1 = Nil) or (m2 = Nil)) then
begin
if m1 = Nil then
if m2 = Nil then
result := 0
else
result := -1
else
if m2 = Nil then
result := 1
end;
if result = 99 then
case column of
psPID : result := pr1.ProcessID - pr2.ProcessID;
psParentPID : result := pr1.ParentProcessID - pr2.ParentProcessID;
psBasePriority : result := pr1.BasePriority - pr2.BasePriority;
psName : result := CompareText (pr1.EXEName, pr2.EXEName);
psDate : result := CompareDateTime (m1.FileDateTime, m2.FileDateTime);
psSize : result := m1.FileSize - m2.FileSize
else
result := 0
end;
if direction = psDescending then
result := -result
end;
procedure TProcessSnapshot.SortProcesses (column : TPSSortColumn; direction : TPSSortDirection);
begin
fSortColumn := column;
fSortDirection := direction;
fProcesses.Sort(CompareProcesses);
end;
procedure TProcessSnapshot.TakeSnapshot;
var
buffer, p : PDWORD;
bufLen : DWORD;
i, count : Integer;
hSnapshot : THandle;
processEntry : TProcessEntry32;
begin
if csDesigning in ComponentState then
Exit;
fProcesses.Clear;
if gUsesToolhelp then
begin
hSnapshot := TlHelp32.CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if hSnapshot <> INVALID_HANDLE_VALUE then
try
processEntry.dwSize := sizeof (processEntry);
if Process32First (hSnapshot, processEntry) then
repeat
fProcesses.Add(TProcess.Create(self, @processEntry))
until not Process32Next (hSnapshot, processEntry)
finally
Closehandle (hSnapshot)
end
end
else
begin
buffer := Nil;
try
ReallocMem (buffer, 1024*1024);
if not EnumProcesses (buffer, 1024*1024, bufLen) then bufLen := 0;
ReallocMem (buffer, bufLen);
count := bufLen div sizeof (DWORD);
p := buffer;
for i := 0 to count - 1 do
begin
fProcesses.Add(TProcess.Create(self, p^));
Inc (p)
end
finally
ReallocMem (buffer, 0)
end
end;
SortProcesses (fSortColumn, fSortDirection);
end;
{ TModule }
constructor TModule.Create(AOwner: TProcess; fInitDetails: PModuleEntry32);
begin
fVersionCache := '~';
fOwner := AOwner;
fFileName := fInitDetails.szExePath;
fhModule := fInitDetails.hModule;
end;
constructor TModule.Create(AOwner: TProcess; hOwner, hModule: THandle);
var
szfileName : array [0..MAX_PATH] of char;
begin
fVersionCache := '~';
fOwner := AOwner;
fhModule := hModule;
GetModuleFileNameEx (hOwner, hModule, szFileName, sizeof (szFileName));
fFileName := szFilename
end;
function TModule.GetFileDateTime: TDateTime;
begin
GetFileDetails;
result := fFileDateTime;
end;
procedure TModule.GetFileDetails;
var
f : TSearchRec;
begin
if fVersionCache = '~' then
begin
fVersionCache := GetFileVersion (FileName);
if FindFirst (FileName, faAnyFile, f) = 0 then
try
fFileDateTime := FileDateToDateTime (f.Time);
fFileSize := f.Size
finally
FindClose (f)
end
end
end;
function TModule.GetFileName: string;
var
sysDir : string;
begin
result := fFileName;
if Copy (result, 1, 4) = '\??\' then
Delete (result, 1, 4);
if Copy (result, 1, 11) = '\SystemRoot' then
begin
SetLength (sysDir, MAX_PATH);
GetWindowsDirectory (PChar (sysDir), MAX_PATH);
sysDir := PChar (sysDir);
result := sysDir + Copy (result, 12, MaxInt)
end
end;
function TModule.GetFileSize: DWORD;
begin
GetFileDetails;
result := fFileSize;
end;
function TModule.GetVersion: string;
begin
GetFileDetails;
result := fVersionCache;
end;
initialization
if SysUtils.Win32Platform = VER_PLATFORM_WIN32_NT then
gOldState := EnableNTPrivilege (SE_DEBUG_NAME, SE_PRIVILEGE_ENABLED);
finalization
if gOldState <> $badf00d then
EnableNTPrivilege (SE_DEBUG_NAME, gOldState)
end. |
program SymbolType;
var
c: char;
begin
read(c);
write('The symbol is ');
case c of
'a'..'z', 'A'..'Z':
writeln('a latin letter');
'0'..'9':
writeln('a digit');
'+', '-', '/', '*':
writeln('an arithmetic operation symbol');
'<', '>', '=':
writeln('a comparision sign');
else
writeln('other symbol')
end
end.
|
unit FreeOTFEExplorerfrmSelectDirectoryDlg;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ComCtrls, SDFilesystemCtrls, SDUForms,
SDFilesystem, OTFEFreeOTFE_InstructionRichEdit;
type
TSelectDirType = (sdtDefault, sdtMove, sdtCopy, sdtStore);
TfrmSelectDirectoryDlg = class(TSDUForm)
SDFilesystemTreeView1: TSDFilesystemTreeView;
pbOK: TButton;
pbCancel: TButton;
Label2: TLabel;
reInstructions: TOTFEFreeOTFE_InstructionRichEdit;
procedure FormShow(Sender: TObject);
procedure pbOKClick(Sender: TObject);
procedure SDFilesystemTreeView1Change(Sender: TObject; Node: TTreeNode);
procedure SDFilesystemTreeView1DblClick(Sender: TObject);
private
FSelectedPath: string;
protected
procedure EnableDisableControls();
public
SelectDirType: TSelectDirType;
Items: TStrings;
Filesystem: TSDCustomFilesystem;
published
property SelectedPath: string read FSelectedPath;
end;
function SelectFilesystemDirectory(
AOwner: TComponent;
Filesystem: TSDCustomFilesystem;
selectDirType: TSelectDirType;
items: TStrings
): string;
implementation
{$R *.dfm}
uses
SDUi18n,
SDUGeneral;
function SelectFilesystemDirectory(
AOwner: TComponent;
Filesystem: TSDCustomFilesystem;
selectDirType: TSelectDirType;
items: TStrings
): string;
var
dlg: TfrmSelectDirectoryDlg;
retval: string;
begin
retval := '';
dlg:= TfrmSelectDirectoryDlg.Create(AOwner);
try
dlg.SelectDirType := selectDirType;
dlg.Items := Items;
dlg.Filesystem := Filesystem;
if (dlg.ShowModal = mrOK) then
begin
retval := dlg.SelectedPath;
end;
finally
dlg.Free();
end;
Result := retval;
end;
procedure TfrmSelectDirectoryDlg.FormShow(Sender: TObject);
var
dlgCaption: widestring;
dlgInstructions: widestring;
dlgOKButton: widestring;
itemText: string;
begin
SDFilesystemTreeView1.ReadOnly := TRUE;
SDFilesystemTreeView1.Filesystem := Filesystem;
SDFilesystemTreeView1.Initialize();
// Expand out the root node
if (SDFilesystemTreeView1.GoToPath(PATH_SEPARATOR, FALSE) <> nil) then
begin
SDFilesystemTreeView1.Selected.Expand(FALSE);
end;
dlgCaption := _('Select folder');
dlgInstructions := _('Please select folder:');
dlgOKButton := _('OK');
itemText:= SDUParamSubstitute(
_('these %1 items'),
[inttostr(Items.count)]
);
if (Items.Count = 1) then
begin
itemText := ''''+ExtractFilename(Items[0])+'''';
end;
case SelectDirType of
sdtMove:
begin
dlgCaption := _('Move Items');
dlgInstructions := SDUParamSubstitute(
_('Select the place where you want to move %1. Then click the Move button'),
[itemText]
);
dlgOKButton := _('Move');
end;
sdtCopy:
begin
dlgCaption := _('Copy Items');
dlgInstructions := SDUParamSubstitute(
_('Select the place where you want to copy %1. Then click the Copy button'),
[itemText]
);
dlgOKButton := _('Copy');
end;
sdtStore:
begin
dlgCaption := _('Store Items');
dlgInstructions := SDUParamSubstitute(
_('Select the place where you want to store %1. Then click the Store button'),
[itemText]
);
dlgOKButton := _('Store');
end;
end;
self.Caption := dlgCaption;
reInstructions.Text := dlgInstructions;
pbOK.Caption := dlgOKButton;
EnableDisableControls();
end;
procedure TfrmSelectDirectoryDlg.pbOKClick(Sender: TObject);
begin
FSelectedPath := '';
if (SDFilesystemTreeView1.SelectionCount = 1) then
begin
FSelectedPath := SDFilesystemTreeView1.PathToNode(SDFilesystemTreeView1.Selected);
ModalResult := mrOK;
end;
end;
procedure TfrmSelectDirectoryDlg.SDFilesystemTreeView1Change(Sender: TObject;
Node: TTreeNode);
begin
EnableDisableControls();
end;
procedure TfrmSelectDirectoryDlg.SDFilesystemTreeView1DblClick(
Sender: TObject);
begin
if (pbOK.Enabled) then
begin
pbOKClick(pbOK);
end;
end;
procedure TfrmSelectDirectoryDlg.EnableDisableControls();
begin
SDUEnableControl(pbOK, (SDFilesystemTreeView1.SelectionCount = 1));
end;
END.
|
unit Aurelius.Drivers.Exceptions;
{$I Aurelius.inc}
interface
uses
Aurelius.Global.Exceptions;
type
ETransactionNotOpen = class(EOPFBaseException)
public
constructor Create;
end;
EConnectionNotOpen = class(EOPFBaseException)
public
constructor Create;
end;
implementation
{ ETransactionNotOpen }
constructor ETransactionNotOpen.Create;
begin
inherited Create('Cannot commit or rollback. Transaction is not open.');
end;
{ EConnectionNotOpen }
constructor EConnectionNotOpen.Create;
begin
inherited Create('Cannot perform operation, connection is not open.');
end;
end.
|
unit Unit2;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, TAGraph, Forms, Controls, Graphics, Dialogs,
ExtCtrls;
type
{ TPlot }
TPlotPoint=record x,y:real; end;
TPlotPoints=array of TPlotPoint;
TPlot=class
canvas:TCanvas;
rect,view_rect:TRect;
xo,x1,x2,sx1,sx2:real; xaxis:string;
yo,y1,y2,sy1,sy2:real; yaxis:string;
grid_color,axis_color,background,color:TColor;
x,y:real; nfirst:boolean;
arrow_len, arrow_angle:double;
axis_w1:integer;
plots:array of TPlotPoints;
procedure SetDefault;
procedure Draw;
procedure setRect(r:TRect);
procedure clear;
procedure addPoints(points:TPlotPoints);
procedure drawBackground;
procedure drawGrid;
procedure drawAxis;
procedure drawAxisNumbers;
procedure drawAxisNames;
procedure drawLines;
procedure draw_shape(c:TCanvas;xOs,yOs:integer);
procedure startLine;
procedure lineTo(xx,yy:real);
procedure x2v(xx,yy:real;var rx,ry:real);
procedure x2vi(xx,yy:real;var rx,ry:integer);
procedure drawArrow(ax,ay,bx,by:real);
procedure podgon(xx1,xx2,yy1,yy2:real);
end;
{ TForm2 }
TForm2 = class(TForm)
PaintBox1: TPaintBox;
procedure FormCreate(Sender: TObject);
procedure PaintBox1Click(Sender: TObject);
procedure PaintBox1Paint(Sender: TObject);
private
plot:TPlot;
{ private declarations }
public
{ public declarations }
procedure setData(const x,y:array of real);
end;
var
Form2: TForm2;
dx,dy,x0,y0:integer;
implementation
uses math;
{$R *.lfm}
{ TForm2 }
{
function ColX(MasX:TMas;usp:String):integer;
var
i,k:integer;
begin k:=0;
if usp='+' then
begin
for i:=Low(MasX) to High(MasX) do
begin
if MasX[i]>=0 then k:=k+1;
end;
end
else
begin
for i:=Low(MasX) to High(MasX) do
begin
if MasX[i]<0 then k:=k+1;
end;
end;
result:=k;
end;
function Max(a,b:real):real;
begin
if a>=b then result:=a
else result:=b;
end;
procedure Draw(MasX,MasY:Tmas);
var
i:integer;
begin
//x0:=Form2.PaintBox1.ClientWidth/2;
//y0:=Form2.PaintBox1.ClientHeight/2;
dx:=trunc(x0/(Max(ColX(MasX,'+'),ColX(MasX,'-'))+1));
dy:=trunc(y0/(Max(ColX(MasY,'+'),ColX(MasY,'-'))+1));
//Form2.PaintBox1.Canvas.Line(0,0,0,y0);
end;
}
{ TPlot }
procedure TPlot.draw_shape(c:TCanvas; xOs,yOs:integer);
begin
end;
procedure TPlot.SetDefault;
begin
rect.Left:=0;
rect.Right:=640;
rect.Top:=0;
rect.Bottom:=480;
view_rect:=rect;
xo:=0;x1:=-1;x2:=1; sx1:=0.2; sx2:=0.1; xaxis:='X';
yo:=0;y1:=-1;y2:=1; sy1:=0.2; sy2:=0.1; yaxis:='Y';
grid_color:=RGBToColor(0,$90,0);
axis_color:=RGBToColor($B0,$B0,$B0);
background:=RGBToColor(0,0,0);
color:=RGBToColor(255,255,255);
arrow_len:=10;
arrow_angle:=Pi/180*10;
axis_w1:=4;
end;
procedure TPlot.Draw;
begin
drawBackground;
drawAxisNumbers;
drawGrid;
drawAxis;
drawAxisNames;
drawLines;
end;
procedure TPlot.setRect(r: TRect);
var margin:integer;
begin
margin:=20;
rect:=r;
view_rect:=r;
inc(rect.Left,margin);
dec(rect.Right,margin);
inc(rect.Top,margin);
dec(rect.Bottom,margin);
end;
procedure TPlot.clear;
begin
setlength(plots,0);
end;
procedure TPlot.addPoints(points: TPlotPoints);
var n:integer;
begin
n:=length(plots);
setlength(plots,n+1);
plots[n]:=points;
end;
procedure TPlot.drawBackground;
begin
canvas.Brush.Color:=background;
canvas.FillRect(view_rect);
end;
procedure TPlot.drawGrid;
var xx,yy,xxpoint,yypoint:real; px1,px2,py1,py2:integer;
TreoBeginUp,TreoBeginDown,TreoEnd:TPoint;
Treo:array of TPoint;
begin
Canvas.Pen.Color:=grid_color;
Canvas.Pen.Style:=TPenStyle.psDash;
xx:=xo;
xxpoint:=xo;
yypoint:=yo;
Canvas.Pen.Color:=clRed;
Canvas.Brush.Color:=clRed;
while xxpoint<=x1 do
begin
while yypoint<=y1 do
begin
//Canvas.Ellipse(StrToInt(IntToStr(round(xxpoint))),StrToInt(IntToStr(round(yypoint))),100,100);
drawArrow(xxpoint,yypoint,xxpoint+5,yypoint+5);
//TreoBeginUp.x:=StrToInt(IntToStr(round(xxpoint)));
//TreoBeginUp.y:=StrToInt(IntToStr(round(yypoint)))-StrToInt(IntToStr(round(sy1)));
// TreoBeginDown.x:=StrToInt(IntToStr(round(xxpoint)));
//TreoBeginDown.y:=StrToInt(IntToStr(round(yypoint)))+StrToInt(IntToStr(round(sy1)));
//TreoEnd.x:=StrToInt(IntToStr(round(xxpoint)))+StrToInt(IntToStr(round(sx1)));
//TreoEnd.y:=StrToInt(IntToStr(round(yypoint)))+StrToInt(IntToStr(round(sy1)));
//SetLength(Treo,3);
//Treo[0]:=TreoBeginUp;
//Treo[1]:=TreoBeginDown;
//Treo[2]:=TreoEnd;
//Canvas.Polyline(Treo);
//yypoint:=yypoint+sy1;
end;
end;
Canvas.Pen.Color:=grid_color;
//Canvas.Brush.Color:=clBlack;
while xx>=x1 do
begin
x2vi(xx,y1,px1,py1);
x2vi(xx,y2,px2,py2);
Canvas.Line(px1,py1,px2,py2);
//Canvas.Ellipse(px2,py2-5,px2+5,py2+5);
xx:=xx-sx1;
end;
xx:=xo+sx1;
while xx<=x2 do
begin
x2vi(xx,y1,px1,py1);
x2vi(xx,y2,px2,py2);
Canvas.Line(px1,py1,px2,py2);
//Canvas.Ellipse(px2,py2-5,px2+5,py2+5);
xx:=xx+sx1;
end;
yy:=y0;
while yy>=y1 do
begin
x2vi(x1,yy,px1,py1);
x2vi(x2,yy,px2,py2);
Canvas.Line(px1,py1,px2,py2);
//Canvas.Ellipse(px2,py2-5,px2+5,py2+5);
yy:=yy-sy1;
end;
yy:=y0+sy1;
while yy<=y2 do
begin
x2vi(x1,yy,px1,py1);
x2vi(x2,yy,px2,py2);
Canvas.Line(px1,py1,px2,py2);
//Canvas.Ellipse(px2,py2-5,px2+5,py2+5);
yy:=yy+sy1;
end;
Canvas.Pen.Style:=TPenStyle.psSolid;
end;
procedure TPlot.drawAxis;
begin
Canvas.Brush.Color:=clBlack;
Canvas.Pen.Color:=axis_color;
drawArrow(x1,yo,x2,y0);
drawArrow(xo,y1,xo,y2);
end;
procedure TPlot.drawAxisNumbers;
var px1,py1,px2,py2,px3,py3,hh:integer;
txt:string;
xx,yy:real;
w,h:integer;
function fmt(a:real):string;
begin
result:=Format('%.2f',[a]);
end;
begin
Canvas.Pen.Color:=axis_color;
Canvas.Font.Color:=axis_color;
Canvas.Font.Name:='Verdana';
Canvas.Font.Size:=8;
hh:=axis_w1;
xx:=xo;
while xx>=x1 do xx:=xx-sx1;
xx:=xx+sx1;
while xx<=x2 do
begin
x2vi(xx,yo,px1,py1);
Canvas.Line(px1,py1-hh,px1,py1+hh);
txt:=fmt(xx);
w:=Canvas.GetTextWidth(txt);
h:=Canvas.GetTextHeight(txt);
Canvas.TextOut(px1-w div 2,py1-hh-h-2,txt);
xx:=xx+sx1;
end;
yy:=yo;
while yy>=y1 do yy:=yy-sy1;
yy:=yy+sy1;
while yy<=y2 do
begin
x2vi(xo,yy,px1,py1);
Canvas.Line(px1-hh,py1,px1+hh,py1);
txt:=fmt(yy);
w:=Canvas.GetTextWidth(txt);
h:=Canvas.GetTextHeight(txt);
Canvas.TextOut(px1+hh+2,py1-h div 2-2,txt);
yy:=yy+sy1;
end;
end;
procedure TPlot.drawAxisNames;
var p1x,p1y,p2x,p2y:integer; txt:string; w,h:integer;
begin
Canvas.Font.Color:=axis_color;
Canvas.Font.Name:='Verdana';
Canvas.Font.Size:=10;
x2vi(x2,y0,p1x,p1y);
txt:=xaxis;
w:=Canvas.GetTextWidth(txt);
h:=Canvas.GetTextHeight(txt);
p2x:=round(p1x-w-arrow_len);
p2y:=round(p1y+axis_w1+2);
Canvas.TextOut(p2x,p2y,txt);
x2vi(x0,y2,p1x,p1y);
txt:=yaxis;
w:=Canvas.GetTextWidth(txt);
h:=Canvas.GetTextHeight(txt);
p2x:=round(p1x-w-axis_w1-2);
p2y:=round(p1y+arrow_len-h div 2+2);
Canvas.TextOut(p2x,p2y,txt);
end;
procedure TPlot.startLine;
begin
nfirst:=true;
canvas.Pen.Color:=color;
end;
procedure TPlot.lineTo(xx, yy: real);
var px1,px2,py1,py2:integer;
begin
if nfirst then nfirst:=false else
begin
x2vi(x,y,px1,py1);
x2vi(xx,yy,px2,py2);
canvas.Line(px1,py1,px2,py2);
end;
x:=xx;
y:=yy;
end;
procedure TPlot.x2v(xx, yy: real; var rx, ry: real);
begin
rx:=rect.Left + (rect.Right-rect.Left)*(xx-x1)/(x2-x1);
ry:=rect.Bottom - (rect.Bottom-rect.Top)*(yy-y1)/(y2-y1);
end;
procedure TPlot.x2vi(xx, yy: real; var rx, ry: integer);
begin
rx:=round(rect.Left + (rect.Right-rect.Left)*(xx-x1)/(x2-x1));
ry:=round(rect.Top + (rect.Bottom-rect.Top)*(yy-y2)/(y1-y2));
end;
procedure TPlot.drawArrow(ax, ay, bx, by: real);
var s,c,nx,ny,mx,my,len:real;
p1x,p1y,p2x,p2y,p3x,p3y,p4x,p4y:real;
begin
s:=sin(arrow_angle);
c:=cos(arrow_angle);
x2v(ax,ay,p1x,p1y);
x2v(bx,by,p2x,p2y);
nx:=p2x-p1x;
ny:=p2y-p1y;
len:=sqrt(nx*nx+ny*ny);
nx:=nx/len;
ny:=ny/len;
mx:= -ny;
my:=nx;
p3x:=p2x-arrow_len*( nx*c+s*mx);
p3y:=p2y-arrow_len*( ny*c+s*my);
p4x:=p2x-arrow_len*( nx*c-s*mx);
p4y:=p2y-arrow_len*( ny*c-s*my);
Canvas.Line(round(p1x),round(p1y),round(p2x),round(p2y));
Canvas.Line(round(p2x),round(p2y),round(p3x),round(p3y));
Canvas.Line(round(p2x),round(p2y),round(p4x),round(p4y));
end;
procedure TPlot.podgon(xx1, xx2, yy1, yy2: real);
var dx,dy,px,py, sdx,sdy,nx,ny:real;
begin
dx:=xx2-xx1;
dy:=yy2-yy1;
px:=ceil( ln(dx)/ln(10) ) - 2;
py:=ceil( ln(dy)/ln(10) ) - 2;
sdx:=power(10,px);
sdy:=power(10,py);
nx:=dx/sdx;
if nx>50 then sdx:=sdx*5 else
if nx>25 then sdx:=sdx*2.5;
ny:=dy/sdy;
if ny>50 then sdy:=sdy*5 else
if ny>25 then sdy:=sdy*2.5;
x1:=floor(xx1/sdx)*sdx;
x2:=ceil(xx2/sdx)*sdx;
if (xo<x1) then xo:=x1;
if (xo>x2) then xo:=x2;
y1:=floor(yy1/sdy)*sdy;
y2:=ceil(yy2/sdy)*sdy;
if (yo<y1) then yo:=y1;
if (yo>y2) then yo:=y2;
sx1:=sdx;
sx2:=sdx*0.1;
sy1:=sdy;
sy2:=sdy*0.1;
end;
procedure TPlot.drawLines;
var xx,dx,yy:real;
i,n,j,m:integer;
begin
n:=length(plots);
for i:=0 to n-1 do
begin
startLine;
m:=length(plots[i]);
for j:=0 to m-1 do lineTo(plots[i][j].x,plots[i][j].y);
end;
end;
procedure TForm2.FormCreate(Sender: TObject);
begin
plot:=TPlot.Create;
plot.SetDefault;
end;
procedure TForm2.PaintBox1Click(Sender: TObject);
begin
end;
procedure TForm2.PaintBox1Paint(Sender: TObject);
begin
plot.Canvas:=PaintBox1.Canvas;
plot.SetRect(PaintBox1.BoundsRect);
plot.draw();
end;
procedure TForm2.setData(const x, y: array of real);
var i,n:integer; p:TPlotPoints;
xmin,xmax,ymin,ymax:real;
begin
plot.clear;
n:=length(x); if length(y)<n then n:=length(y);
if n<1 then exit;
setlength(p,n);
xmin:=x[0];xmax:=xmin;
ymin:=y[0];ymax:=ymax;
for i:=0 to n-1 do
begin
p[i].x:=x[i];
p[i].y:=y[i];
if xmin>x[i] then xmin:=x[i];
if xmax<x[i] then xmax:=x[i];
if ymin>y[i] then ymin:=y[i];
if ymax<y[i] then ymax:=y[i];
end;
plot.addPoints(p);
plot.podgon(xmin,xmax,ymin,ymax);
end;
end.
|
unit uJxdCapEffect;
interface
uses
Windows, SysUtils, Graphics, Classes, uJxdCapEffectBasic, GDIPAPI, GDIPOBJ;
type
PArgbInfo = ^TArgbInfo;
TArgbInfo = packed record
FBlue,
FGreen,
FRed,
FAlpha: Byte;
end;
PBmpInfo = ^TBmpInfo;
TBmpInfo = record
FBmp: HBITMAP;
FPauseTime: Cardinal;
end;
TAryBmpInfos = array of TBmpInfo;
PEffectBitmapItem = ^TEffectBitmapItem;
TEffectBitmapItem = record
FID: Integer;
FBmpDC: HDC; //使用的内存DC
FCurIndex: Integer; //当前指向的项
FBmpCount: Integer; //图像数量
FShowRect: TGPRect; //显示位置
FNextChangedTime: Cardinal; //下次超时换图像时间
FBmpInfos: TAryBmpInfos; //BMP的信息
end;
TxdCapEffect = class(TxdCapEffectBasic)
public
constructor Create;
destructor Destroy; override;
//拍照
function SnapShot(var ABmp: TGPBitmap): Boolean;
//添加特效,返回特效ID; AForceAlpha: 强制指定的图像半透明,否则根据图像格式进行转变
function AddEffectFile(const AFileName: string; const AShowPos: TPoint; const AForceAlpha: Boolean = False): Integer; overload;
function AddEffectFile(const AImg: TGPBitmap; const AShowPos: TPoint; const AForceAlpha: Boolean = False): Integer; overload;
//修改特效显示位置
procedure ChangedEffectPos(const AID: Integer; const ANewPos: TPoint);
//删除特效
procedure DeleteEffect(const AID: Integer);
//实现接口
procedure DoOverlayEffer(Sender: TObject; MemDC: HDC; const AWidth, AHeight: Integer); override;
private
FLock: TRTLCriticalSection;
FEffectList: TList;
FCurID: Integer;
FIsShapShot: Boolean;
FShapShotBmp: TBitmap;
procedure FreeEffectItem(Ap: PEffectBitmapItem);
end;
implementation
uses
Forms;
{ TxdCapEffect }
function TxdCapEffect.AddEffectFile(const AFileName: string; const AShowPos: TPoint; const AForceAlpha: Boolean): Integer;
var
bmp: TGPBitmap;
begin
bmp := TGPBitmap.Create( AFileName );
try
Result := AddEffectFile( bmp, AShowPos, AForceAlpha );
finally
FreeAndNil( bmp );
end;
end;
function TxdCapEffect.AddEffectFile(const AImg: TGPBitmap; const AShowPos: TPoint; const AForceAlpha: Boolean): Integer;
var
G: TGPGraphics;
temp: TGPBitmap;
i, nW, nH, nCount, x, y: Integer;
guid: TGUID;
pItem: PEffectBitmapItem;
bmpData: TBitmapData;
P: PCardinal;
nSize: Integer;
pTimeItem: PPropertyItem;
pPauseTime: PInteger;
begin
Result := -1;
try
if AImg.GetPixelFormat = 0 then Exit;
nW := AImg.GetWidth;
nH := AImg.GetHeight;
if (nW = 0) or (nH = 0) then Exit;
AImg.GetFrameDimensionsList( @guid, 1 );
nCount := AImg.GetFrameCount( guid );
if nCount = 0 then Exit;
//新创建特效
New( pItem );
pItem^.FID := FCurID;
Inc( FCurID );
pItem^.FBmpDC := CreateCompatibleDC( 0 );
pItem^.FCurIndex := -1;
pItem^.FBmpCount := nCount;
pItem^.FShowRect := MakeRect(AShowPos.X, AShowPos.Y, nW, nH);
pItem^.FNextChangedTime := 0;
SetLength(pItem^.FBmpInfos, nCount);
//获取特效的HBitmap
temp := TGPBitmap.Create( nW, nH );
G := TGPGraphics.Create( temp );
for i := 0 to nCount - 1 do
begin
AImg.SelectActiveFrame( guid, i );
G.DrawImage( AImg, 0, 0, nW, nH );
if AForceAlpha then
begin
temp.LockBits( MakeRect(0, 0, nW, nH), ImageLockModeRead or ImageLockModeWrite, PixelFormat32bppARGB, bmpData);
try
P := bmpData.Scan0;
for y := 1 to bmpData.Height do
begin
for x := 1 to bmpData.Width do
begin
//计算不透明度,三种方法都试了
with TArgbInfo(P^) do
begin
// FAlpha := Max(FRed, Max(FGreen, FBlue));
// FAlpha := (FRed + FGreen + FBlue) div 3;
FAlpha := (306 * FRed + 601 * FGreen + 117 * FBlue) div 1024;
end;
Inc(P);
end;
end;
finally
temp.UnlockBits(bmpData);
end;
end; //end: if AForceAlpha then
temp.GetHBITMAP( 0, pItem^.FBmpInfos[i].FBmp );
end;
//获取特效存在时间
if pItem^.FBmpCount = 1 then
pItem^.FBmpInfos[0].FPauseTime := $FFFFFFFF
else
begin
nSize := AImg.GetPropertyItemSize( PropertyTagFrameDelay );
if nSize = 0 then Exit;
GetMem( pTimeItem, nSize );
try
AImg.GetPropertyItem( PropertyTagFrameDelay, nSize, pTimeItem );
pPauseTime := pTimeItem^.value;
for i := 0 to nCount - 1 do
begin
pItem^.FBmpInfos[i].FPauseTime := pPauseTime^ * 10;
Inc( pPauseTime );
end;
finally
FreeMem( pTimeItem );
end;
end;
EnterCriticalSection( FLock );
try
FEffectList.Add( pItem );
Result := pItem^.FID;
finally
LeaveCriticalSection( FLock );
end;
finally
FreeAndNil( temp );
FreeAndNil( G );
end;
end;
procedure TxdCapEffect.ChangedEffectPos(const AID: Integer; const ANewPos: TPoint);
var
i: Integer;
p: PEffectBitmapItem;
begin
EnterCriticalSection( FLock );
try
for i := 0 to FEffectList.Count - 1 do
begin
p := FEffectList[i];
if p^.FID = AID then
begin
p^.FShowRect.X := ANewPos.X;
p^.FShowRect.Y := ANewPos.Y;
Break;
end;
end;
finally
LeaveCriticalSection( FLock );
end;
end;
constructor TxdCapEffect.Create;
begin
FEffectList := TList.Create;
FCurID := GetTickCount;
FIsShapShot := False;
FShapShotBmp := nil;
InitializeCriticalSection( FLock );
end;
procedure TxdCapEffect.DeleteEffect(const AID: Integer);
var
i: Integer;
p: PEffectBitmapItem;
begin
EnterCriticalSection( FLock );
try
for i := 0 to FEffectList.Count - 1 do
begin
p := FEffectList[i];
if p^.FID = AID then
begin
FreeEffectItem( p );
FEffectList.Delete( i );
Break;
end;
end;
finally
LeaveCriticalSection( FLock );
end;
end;
destructor TxdCapEffect.Destroy;
begin
DeleteCriticalSection( FLock );
inherited;
end;
procedure TxdCapEffect.DoOverlayEffer(Sender: TObject; MemDC: HDC; const AWidth, AHeight: Integer);
var
i: Integer;
p: PEffectBitmapItem;
blend: TBlendFunction;
dwTime: Cardinal;
begin
if FEffectList.Count = 0 then Exit;
EnterCriticalSection( FLock );
try
dwTime := GetTickCount;
for i := 0 to FEffectList.Count - 1 do
begin
p := FEffectList[i];
if p^.FNextChangedTime = 0 then
begin
p^.FCurIndex := 0;
p^.FNextChangedTime := p^.FBmpInfos[p^.FCurIndex].FPauseTime + dwTime;
SelectObject( p^.FBmpDC, p^.FBmpInfos[p^.FCurIndex].FBmp );
end
else if dwTime >= p^.FNextChangedTime then
begin
p^.FCurIndex := (p^.FCurIndex + 1) mod p^.FBmpCount;
p^.FNextChangedTime := p^.FBmpInfos[p^.FCurIndex].FPauseTime + dwTime;
SelectObject( p^.FBmpDC, p^.FBmpInfos[p^.FCurIndex].FBmp );
end;
Blend.BlendOp := AC_SRC_OVER;
Blend.BlendFlags := 0;
Blend.AlphaFormat := AC_SRC_ALPHA ;
Blend.SourceConstantAlpha := $FF;
AlphaBlend( MemDC, p^.FShowRect.X, p^.FShowRect.Y, p^.FShowRect.Width, p^.FShowRect.Height,
p^.FBmpDC, 0, 0, p^.FShowRect.Width, p^.FShowRect.Height, blend );
if FIsShapShot then
begin
FIsShapShot := False;
if not Assigned(FShapShotBmp) then
begin
FShapShotBmp := TBitmap.Create;
FShapShotBmp.Width := AWidth;
FShapShotBmp.Height := AHeight;
end;
BitBlt( FShapShotBmp.Canvas.Handle, 0, 0, AWidth, AHeight, MemDC, 0, 0, SRCCOPY );
end;
end;
finally
LeaveCriticalSection( FLock );
end;
end;
procedure TxdCapEffect.FreeEffectItem(Ap: PEffectBitmapItem);
var
i: Integer;
begin
for i := Low(Ap^.FBmpInfos) to High(Ap^.FBmpInfos) do
DeleteObject( Ap^.FBmpInfos[i].FBmp );
DeleteObject( Ap^.FBmpDC );
Dispose( Ap );
end;
function TxdCapEffect.SnapShot(var ABmp: TGPBitmap): Boolean;
var
nMaxCount: Integer;
begin
Result := False;
if FIsShapShot then Exit;
nMaxCount := 0;
FIsShapShot := True;
Sleep( 5 );
while FIsShapShot and (nMaxCount < 200) do
begin
Inc( nMaxCount );
Sleep( 5 );
Application.ProcessMessages;
end;
Result := not FIsShapShot;
if Result then
begin
ABmp := TGPBitmap.Create( FShapShotBmp.Handle, FShapShotBmp.Palette );
FreeAndNil( FShapShotBmp );
end;
end;
end.
|
unit uthrImportarCarriers;
interface
uses
System.Classes, Dialogs, Windows, Forms, SysUtils, clUtil,
clCodigosEntregadores, clStatus, clAgentes, clEntrega,
Messages, Controls, System.DateUtils, System.StrUtils, clCliente;
type
TCSVEntrega = record
_agenteTFO: String;
_descricaoAgenteTFO: String;
_nossonumero: String;
_pedido: String;
_cliente: String;
_nota: String;
_consumidor: String;
_cuidados: String;
_logradouro: String;
_complemento: String;
_bairro: String;
_cidade: String;
_cep: String;
_telefone: String;
_expedicao: String;
_previsao: String;
_status: String;
_descricaoStatus: String;
_entregador: String;
_container: String;
_valorProduto: String;
_verba: String;
_altura: String;
_largura: String;
_comprimento: String;
_peso: String;
_volumes: String;
_databaixa: String;
_codcliente: String;
end;
type
thrImportarEntregas = class(TThread)
private
{ Private declarations }
entregador: TCodigosEntregadores;
entrega: TEntrega;
agentes: TAgente;
clientes: TCliente;
status: TStatus;
CSVEntrega: TCSVEntrega;
protected
procedure Execute; override;
procedure AtualizaLog;
procedure AtualizaProgress;
procedure TerminaProcesso;
function TrataLinha(sLinha: String): String;
end;
implementation
{
Important: Methods and properties of objects in visual components can only be
used in a method called using Synchronize, for example,
Synchronize(UpdateCaption);
and UpdateCaption could look like,
procedure thrImportarEntregas.UpdateCaption;
begin
Form1.Caption := 'Updated in a thread';
end;
or
Synchronize(
procedure
begin
Form1.Caption := 'Updated in thread via an anonymous method'
end
)
);
where an anonymous method is passed.
Similarly, the developer can call the Queue method with similar parameters as
above, instead passing another TThread class as the first parameter, putting
the calling thread in a queue with the other thread.
}
{ thrImportarEntregas }
uses
ufrmImportaentrega, uGlobais;
function thrImportarEntregas.TrataLinha(sLinha: String): String;
var
iConta: Integer;
sLin: String;
bFlag: Boolean;
begin
if Pos('"', sLinha) = 0 then
begin
Result := sLinha;
Exit;
end;
iConta := 1;
bFlag := False;
sLin := '';
while sLinha[iConta] >= ' ' do
begin
if sLinha[iConta] = '"' then
begin
if bFlag then
bFlag := False
else
bFlag := True;
end;
if bFlag then
begin
if sLinha[iConta] = ';' then
sLin := sLin + ' '
else
sLin := sLin + sLinha[iConta];
end
else
sLin := sLin + sLinha[iConta];
Inc(iConta);
end;
Result := sLin;
end;
procedure thrImportarEntregas.Execute;
var
ArquivoCSV: TextFile;
Contador, I, LinhasTotal, iRet: Integer;
Linha, campo, codigo, sMess, sData: String;
d: Real;
sDetalhe: TStringList;
sAgente: String;
sEntregador : String;
sCliente: String;
begin
entregador := TCodigosEntregadores.Create;
entrega := TEntrega.Create;
agentes := TAgente.Create;
status := TStatus.Create;
clientes := TCliente.Create;
LinhasTotal := TUtil.NumeroDeLinhasTXT(frmImportaEntregas.cxArquivo.Text);
// Carregando o arquivo ...
AssignFile(ArquivoCSV, frmImportaEntregas.cxArquivo.Text);
try
Reset(ArquivoCSV);
Readln(ArquivoCSV, Linha);
if Copy(Linha, 0, 59) <> 'Nr Rota;Rota;Motorista;Ordem Rota;Embarcador;Destinatario;' then
begin
MessageDlg
('Arquivo informado não é de planilha de entregas da Carriers.',
mtWarning, [mbOK], 0);
Abort;
end;
sDetalhe := TStringList.Create;
sDetalhe.StrictDelimiter := True;
sDetalhe.Delimiter := ';';
Contador := 2;
while not Eoln(ArquivoCSV) do
begin
Readln(ArquivoCSV, Linha);
sDetalhe.DelimitedText := Linha;
with CSVEntrega do
begin
entregador.Nome := sDetalhe[2];
sAgente := entregador.getField('COD_AGENTE','NOME');
sEntregador := entregador.getField('COD_ENTREGADOR','NOME');
_agenteTFO := sAgente;
_descricaoAgenteTFO := '';
_nossonumero := sDetalhe[18];
_pedido := sDetalhe[8];
cliente.Razao := Trim(sDetalhe[4]) + ' (CARRIERS)';
sCliente := cliente.getField('COD_CLIENTE','NOME');
_cliente := sCliente;
_nota := sDetalhe[7];
_consumidor := sDetalhe[5];
_cuidados := '';
_logradouro := sDetalhe[19];
_complemento := '';
_bairro := sDetalhe[20];
_cidade := sDetalhe[21];
_cep := sDetalhe[22];
_telefone := '';
_expedicao := sDetalhe[30];
_previsao := sDetalhe[30];
_status := '909';
_descricaoStatus := sDetalhe[23];
_entregador := sEntregador;
_container := '0';
_valorProduto := sDetalhe[27];
_verba := '0';
_altura := '0';
_largura := '0';
_comprimento := '0';
_peso := sDetalhe[26];
_volumes := sDetalhe[11];
_databaixa := sDetalhe[15];
_codcliente := '2';
end;
if not(entrega.getObject(CSVEntrega._nossonumero, 'NOSSONUMERO')) then
begin
entrega.Agente := 0;
entrega.entregador := 0;
entrega.NossoNumero := CSVEntrega._nossonumero;
entrega.Cliente := StrToInt(CSVEntrega._cliente);
entrega.NF := CSVEntrega._nota;
entrega.Consumidor := CSVEntrega._consumidor;
entrega.Endereco := CSVEntrega._logradouro;
entrega.Complemento := CSVEntrega._complemento;
entrega.Bairro := CSVEntrega._bairro;
entrega.Cidade := CSVEntrega._cidade;
entrega.Cep := CSVEntrega._cep;
entrega.Telefone := Copy(CSVEntrega._telefone,1,30);
entrega.Expedicao := StrToDate(CSVEntrega._expedicao);
entrega.PrevDistribuicao := StrToDate(CSVEntrega._previsao);
entrega.status := StrToInt(CSVEntrega._status);
if sDetalhe[17] = 'REALIZADA' then
begin
entrega.DataBaixa := StrToDate(CSVEntrega._databaixa);
entrega.Baixado := 'S';
end;
CSVEntrega._verba := ReplaceStr(CSVEntrega._verba, 'R$ ', '');
entrega.VerbaDistribuicao := StrToFloatDef(CSVEntrega._verba,0);
CSVEntrega._peso := ReplaceStr(CSVEntrega._peso, ' KG', '');
CSVEntrega._peso := ReplaceStr(CSVEntrega._peso, '.', ',');
entrega.PesoReal := StrToFloatDef(CSVEntrega._peso,0);
entrega.PesoCobrado := StrToFloatDef(CSVEntrega._peso,0);
entrega.Volumes := StrToInt(CSVEntrega._volumes);
entrega.VolumesExtra := 0;
entrega.ValorExtra := 0;
entrega.DiasAtraso := 0;
entrega.Container := CSVEntrega._container;
CSVEntrega._valorProduto := ReplaceStr(CSVEntrega._valorProduto, 'R$ ', '');
entrega.ValorProduto := StrToFloatDef(CSVEntrega._valorProduto,0);
entrega.Altura := StrToIntDef(CSVEntrega._altura, 0);
entrega.Largura := StrToIntDef(CSVEntrega._largura, 0);
entrega.Comprimento := StrToIntDef(CSVEntrega._comprimento, 0);
entrega.CodCliente := StrToInt(CSVEntrega._codcliente);
entrega.Rastreio := 'Entrega importada em ' + FormatDateTime('dd/mm/yyyy hh:mm:ss', Now) + ' por ' + uGlobais.sNomeUsuario;
if not(entrega.Insert) then
begin
sMensagem := 'Erro ao Incluir os dados do NN ' +
entrega.NossoNumero + ' !';
Synchronize(AtualizaLog);
end
else
begin
if sDetalhe[17] = 'REALIZADA' then
begin
if not(entrega.Update) then
begin
sMensagem := 'Erro ao Alterar os dados do NN ' +
entrega.NossoNumero + ' !';
Synchronize(AtualizaLog);
end;
end;
end;
end
else
begin
entrega.Cliente := StrToInt(CSVEntrega._cliente);
entrega.NF := CSVEntrega._nota;
entrega.Consumidor := CSVEntrega._consumidor;
entrega.Endereco := CSVEntrega._logradouro;
entrega.Complemento := CSVEntrega._complemento;
entrega.Bairro := CSVEntrega._bairro;
entrega.Cidade := CSVEntrega._cidade;
entrega.Cep := CSVEntrega._cep;
entrega.Telefone := Copy(CSVEntrega._telefone,1,30);
entrega.Expedicao := StrToDate(CSVEntrega._expedicao);
entrega.PrevDistribuicao := StrToDate(CSVEntrega._previsao);
entrega.status := StrToInt(CSVEntrega._status);
CSVEntrega._verba := ReplaceStr(CSVEntrega._verba, 'R$ ', '');
entrega.VerbaDistribuicao := StrToFloatDef(CSVEntrega._verba,0);
CSVEntrega._peso := ReplaceStr(CSVEntrega._peso, ' KG', '');
CSVEntrega._peso := ReplaceStr(CSVEntrega._peso, '.', ',');
entrega.PesoReal := StrToFloatDef(CSVEntrega._peso,0);
entrega.PesoCobrado := StrToFloatDef(CSVEntrega._peso,0);
entrega.Volumes := StrToInt(CSVEntrega._volumes);
entrega.Container := CSVEntrega._container;
CSVEntrega._valorProduto := ReplaceStr(CSVEntrega._valorProduto, 'R$ ', '');
entrega.ValorProduto := StrToFloatDef(CSVEntrega._valorProduto,0);
entrega.Altura := StrToIntDef(CSVEntrega._altura, 0);
entrega.Largura := StrToIntDef(CSVEntrega._largura, 0);
entrega.Comprimento := StrToIntDef(CSVEntrega._comprimento, 0);
entrega.CodCliente := StrToInt(CSVEntrega._codcliente);
if sDetalhe[17] = 'REALIZADA' then
begin
entrega.DataBaixa := StrToDate(CSVEntrega._databaixa);
entrega.Baixado := 'S';
end;
entrega.Rastreio := entrega.Rastreio + #13 +
'Entrega re-importada em ' + FormatDateTime('dd/mm/yyyy hh:mm:ss', Now) + ' por ' + uGlobais.sNomeUsuario;
if not(entrega.Update) then
begin
sMensagem := 'Erro ao Alterar os dados do NN ' +
entrega.NossoNumero + ' !';
Synchronize(AtualizaLog);
end;
end;
I := 0;
iConta := Contador;
iTotal := LinhasTotal;
dPosicao := (iConta / iTotal) * 100;
Inc(Contador, 1);
if not(Self.Terminated) then
begin
Synchronize(AtualizaProgress);
end
else
begin
entregador.Free;
entrega.Free;
agentes.Free;
status.Free;
Abort;
end;
end;
finally
CloseFile(ArquivoCSV);
Application.MessageBox('Importação concluída!', 'Importação de Entregas',
MB_OK + MB_ICONINFORMATION);
sMensagem := 'Importação terminada em ' +
FormatDateTime('dd/mm/yyyy hh:mm:ss', Now);
Synchronize(AtualizaLog);
Synchronize(TerminaProcesso);
entregador.Free;
entrega.Free;
agentes.Free;
status.Free;
end;
end;
procedure thrImportarEntregas.AtualizaLog;
begin
frmImportaEntregas.cxLog.Lines.Add(sMensagem);
frmImportaEntregas.cxLog.Refresh;
end;
procedure thrImportarEntregas.AtualizaProgress;
begin
frmImportaEntregas.cxProgressBar1.Position := dPosicao;
frmImportaEntregas.cxProgressBar1.Properties.Text := 'Registro ' +
IntToStr(iConta) + ' de ' + IntToStr(iTotal);
frmImportaEntregas.cxProgressBar1.Refresh;
if not(frmImportaEntregas.actImportaEntregaCancelar.Visible) then
begin
frmImportaEntregas.actImportaEntregaCancelar.Visible := True;
frmImportaEntregas.actImportaEntregaSair.Enabled := False;
frmImportaEntregas.actImportarEntregaImportar.Enabled := False;
end;
end;
procedure thrImportarEntregas.TerminaProcesso;
begin
frmImportaEntregas.actImportaEntregaCancelar.Visible := False;
frmImportaEntregas.actImportaEntregaSair.Enabled := True;
frmImportaEntregas.actImportarEntregaImportar.Enabled := True;
frmImportaEntregas.cxArquivo.Clear;
frmImportaEntregas.cxProgressBar1.Properties.Text := '';
frmImportaEntregas.cxProgressBar1.Position := 0;
frmImportaEntregas.cxProgressBar1.Clear;
end;
end.
|
unit mainForm;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ComCtrls, Vcl.ExtCtrls,
Vcl.ToolWin, Vcl.ImgList, Vcl.ExtDlgs, Vcl.Menus, aboutForm, System.StrUtils, System.Types, ShellApi;
type
Tfrm_main = class(TForm)
redit_main: TRichEdit;
tbar_main: TToolBar;
tbtn_wczytaj: TToolButton;
imgList: TImageList;
tbtn_zapisz: TToolButton;
tbtn_nowy: TToolButton;
sep1: TToolButton;
tbtn_bold: TToolButton;
tbtn_underline: TToolButton;
tbtn_italic: TToolButton;
sep2: TToolButton;
tbtn_alignLeft: TToolButton;
tbtn_alignCenter: TToolButton;
tbtn_alignRight: TToolButton;
sep3: TToolButton;
tbtn_font: TToolButton;
tbtn_zapiszJako: TToolButton;
tbtn_exit: TToolButton;
sep4: TToolButton;
dlg_openFile: TOpenTextFileDialog;
dlg_saveFile: TSaveTextFileDialog;
dlg_fontChange: TFontDialog;
pop_toolbarMenu: TPopupMenu;
btn_about: TMenuItem;
btn_themes: TMenuItem;
btn_KingKong: TMenuItem;
btn_ZonaGrzesia: TMenuItem;
btn_ImprezauDamiana: TMenuItem;
btn_ZaspanySebastian: TMenuItem;
btn_stats: TMenuItem;
N1: TMenuItem;
tbtn_help: TToolButton;
ToolButton2: TToolButton;
pop_helpMenu: TPopupMenu;
Plikpomocychm1: TMenuItem;
Plikpomocyhtml1: TMenuItem;
Plikpomocypdf1: TMenuItem;
procedure tbtn_nowyClick(Sender: TObject);
procedure tbtn_exitClick(Sender: TObject);
procedure tbtn_wczytajClick(Sender: TObject);
procedure tbtn_zapiszClick(Sender: TObject);
procedure tbtn_zapiszJakoClick(Sender: TObject);
procedure tbtn_boldClick(Sender: TObject);
procedure tbtn_italicClick(Sender: TObject);
procedure changeFontStyle(fsStyle: TFontStyle);
procedure tbtn_underlineClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure zapiszJako();
procedure tbtn_alignLeftClick(Sender: TObject);
procedure tbtn_alignCenterClick(Sender: TObject);
procedure tbtn_alignRightClick(Sender: TObject);
procedure redit_mainChange(Sender: TObject);
procedure tbtn_fontClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure btn_aboutClick(Sender: TObject);
procedure btn_KingKongClick(Sender: TObject);
procedure btn_ZonaGrzesiaClick(Sender: TObject);
procedure btn_ImprezauDamianaClick(Sender: TObject);
procedure btn_ZaspanySebastianClick(Sender: TObject);
procedure btn_statsClick(Sender: TObject);
procedure genStats();
procedure Plikpomocypdf1Click(Sender: TObject);
procedure Plikpomocychm1Click(Sender: TObject);
procedure Plikpomocyhtml1Click(Sender: TObject);
private
{ Private declarations }
reditChanged: boolean;
nazwaPliku: string;
function liczbaWystapien(const Tekst: String; const Znak: Char): Integer;
function liczbaLiter(const Tekst: String; czyWielkie: Boolean): Integer;
function malePolskieZnaki(Znak: Char): Boolean;
function wielkiePolskieZnaki(Znak: Char): Boolean;
function liczbaSlow(const Tekst: String): Integer;
public
{ Public declarations }
intBialeZnaki: Integer;
intMaleLitery: Integer;
intWielkieLitery: Integer;
intSlowa: Integer;
end;
var
frm_main: Tfrm_main;
implementation
{$R *.dfm}
uses splashScreen, dataVisualisation;
//////// USTAWIENIA WSTEPNE
procedure Tfrm_main.FormShow(Sender: TObject);
begin
frmSplashScreen.ShowModal;
end;
procedure Tfrm_main.genStats;
var plainText: String;
begin
plainText := redit_main.Text;
intBialeZnaki := liczbaWystapien(plainText, char(32));
intMaleLitery := liczbaLiter(plainText, false);
intWielkieLitery := liczbaLiter(plainText, true);
intSlowa := liczbaSlow(plainText);
end;
function Tfrm_main.liczbaLiter(const Tekst: String;
czyWielkie: Boolean): Integer;
var i: Integer; CHARS: set of char; polskiZnak: Boolean;
begin
Result:=0;
if czyWielkie then
begin
CHARS := ['A'..'Z'];
end
else
begin
CHARS := ['a'..'z'];
end;
for i := 1 to Length(Tekst) do
begin
if czyWielkie then
polskiZnak:= wielkiePolskieZnaki(Tekst[i])
else
polskiZnak:= malePolskieZnaki(Tekst[i]);
if (Tekst[i] in CHARS) or polskiZnak then
inc(Result);
end;
end;
function Tfrm_main.liczbaSlow(const Tekst: String): Integer;
var slowa: TStringDynArray;
i: Integer;
slowo: String;
begin
slowa := SplitString(Tekst, ' ');
Result:=0;
for slowo in slowa do
begin
inc(Result)
end;
end;
function Tfrm_main.liczbaWystapien(const Tekst: String;
const Znak: Char): Integer;
var i: Integer;
begin
Result:=0;
for i := 1 to Length(Tekst) do
begin
if Tekst[i] = Znak then
inc(Result);
end;
end;
function Tfrm_main.malePolskieZnaki(Znak: Char): Boolean;
begin
Result:=False;
case Znak of
'ą','ę','ć','ł','ń','ó','ś','ź','ż': Result := true;
end;
end;
function Tfrm_main.wielkiePolskieZnaki(Znak: Char): Boolean;
begin
Result:=False;
case Znak of
'Ą','Ę','Ć','Ł','Ń','Ó','Ś','Ź','Ż': Result := true;
end;
end;
procedure Tfrm_main.Plikpomocychm1Click(Sender: TObject);
begin
ShellExecute(Handle, nil, 'FajnyEdytorInstrukcja.chm', nil, nil, SW_SHOW);
end;
procedure Tfrm_main.Plikpomocyhtml1Click(Sender: TObject);
begin
ShellExecute(Handle, nil, 'FajnyEdytorInstrukcjaHTML\FajnyEdytorInstrukcja.html', nil, nil, SW_SHOW);
end;
procedure Tfrm_main.Plikpomocypdf1Click(Sender: TObject);
begin
ShellExecute(Handle, nil, 'FajnyEdytorInstrukcja.pdf', nil, nil, SW_SHOW);
end;
procedure Tfrm_main.btn_aboutClick(Sender: TObject);
begin
aboutForm.frmAbout.Show;
end;
procedure Tfrm_main.FormCreate(Sender: TObject);
begin
{chcemy a możliwe było odczytywanie i zapisywanie plików
tylko z rozszerzeniem heh}
dlg_saveFile.Filter := 'Text files (*.heh)|*.HEH|';
dlg_openFIle.Filter := 'Text files (*.heh)|*.HEH|';
end;
//////// UPDATE STANU
procedure Tfrm_main.redit_mainChange(Sender: TObject);
begin
reditChanged := True;
end;
/////// TWORZENIE NOWEGO PLIKU
procedure Tfrm_main.tbtn_nowyClick(Sender: TObject);
var intWybor: Integer;
begin
if reditChanged then
begin
intWybor := MessageDlg('Czy chcesz zapisać dokonane zmiany?', mtConfirmation, mbYesNo, 0);
if intWybor = mrYes then zapiszJako();
redit_main.Lines.Clear();
reditChanged := False;
end;
end;
/////// PRZYCISK ZAMKNIĘCIA APLIKACJI
procedure Tfrm_main.tbtn_exitClick(Sender: TObject);
begin
Application.Terminate();
end;
//////////////////////////////////////
//////////// SEKCJA WYGLĄDU CZCIONKI
procedure Tfrm_main.btn_ImprezauDamianaClick(Sender: TObject);
begin
redit_main.Font.Color:= clGreen;
redit_main.Color:= clRed;
end;
procedure Tfrm_main.btn_KingKongClick(Sender: TObject);
begin
redit_main.Font.Color:= clYellow;
redit_main.Color:= clBlack;
end;
procedure Tfrm_main.btn_statsClick(Sender: TObject);
begin
genStats;
dataVisualisation.frmDataVis.Show;
end;
procedure Tfrm_main.btn_ZaspanySebastianClick(Sender: TObject);
begin
redit_main.Font.Color:= clBlack;
redit_main.Color:= clSilver;
end;
procedure Tfrm_main.btn_ZonaGrzesiaClick(Sender: TObject);
begin
redit_main.Font.Color:= clWebSeashell;
redit_main.Color:= clWebMagenta;
end;
procedure Tfrm_main.changeFontStyle(fsStyle: TFontStyle);
begin
if fsStyle in redit_main.SelAttributes.Style then
redit_main.SelAttributes.Style := redit_main.SelAttributes.Style - [fsStyle]
else
redit_main.SelAttributes.Style := redit_main.SelAttributes.Style + [fsStyle];
end;
procedure Tfrm_main.tbtn_boldClick(Sender: TObject);
begin
changeFontStyle(fsBold);
end;
procedure Tfrm_main.tbtn_italicClick(Sender: TObject);
begin
changeFontStyle(fsItalic);
end;
procedure Tfrm_main.tbtn_underlineClick(Sender: TObject);
begin
changeFontStyle(fsUnderline);
end;
procedure Tfrm_main.tbtn_fontClick(Sender: TObject);
begin
if dlg_fontChange.Execute then
begin
redit_main.SelAttributes.Name := dlg_fontChange.Font.Name;
redit_main.SelAttributes.Size := dlg_fontChange.Font.Size;
end;
end;
/////////// KONIEC SEKCJI WYGLĄDU CZCIONKI
////////////////////////////////////////////
/////////////////////////////////////////////
////////// SEKCJA WYRÓNYWANIA TEKSTU
procedure Tfrm_main.tbtn_alignLeftClick(Sender: TObject);
begin
redit_main.Paragraph.Alignment := taLeftJustify;
end;
procedure Tfrm_main.tbtn_alignCenterClick(Sender: TObject);
begin
redit_main.Paragraph.Alignment := taCenter;
end;
procedure Tfrm_main.tbtn_alignRightClick(Sender: TObject);
begin
redit_main.Paragraph.Alignment := taRightJustify;
end;
///////// KONIEC SEKCJI WYRÓNYWANIA TEKSTU
///////////////////////////////////////////
////////////////////////////////////////////////////
/////////// SEKCJA WCZYTYWANIA I ZAPISYWANIA PLIKU
procedure Tfrm_main.tbtn_wczytajClick(Sender: TObject);
begin
dlg_openFile.InitialDir := GetCurrentDir;
if dlg_openFile.Execute(Self.Handle) then
nazwaPliku := dlg_openFile.FileName;
if nazwaPliku <> '' then
redit_main.Lines.LoadFromFile(nazwaPliku);
// else
// raise Exception.Create('HEH! Nie wybrano pliku.');
end;
procedure Tfrm_main.tbtn_zapiszClick(Sender: TObject);
begin
(*if dlg_saveFile.Execute then
redit_main.Lines.SaveToFile(dlg_saveFile.FileName, TEncoding.UTF8);
dlg_saveFile.Free(); *)
if dlg_saveFile.FileName <> '' then
redit_main.Lines.SaveToFile(dlg_saveFile.FileName + '.heh')
else if nazwaPliku <> '' then
redit_main.Lines.SaveToFile(nazwaPliku)
else
zapiszJako();
reditChanged := False;
end;
procedure Tfrm_main.tbtn_zapiszJakoClick(Sender: TObject);
begin
zapiszJako();
end;
procedure Tfrm_main.zapiszJako();
begin
(*if dlg_saveFile.Execute then
redit_main.Lines.SaveToFile(dlg_saveFile.FileName, TEncoding.UTF8);*)
if dlg_saveFile.Execute then
if FileExists(dlg_saveFile.FileName+'.heh') then
raise Exception.Create('HEH! Niestety plik już istnije.')
else
redit_main.Lines.SaveToFile(dlg_saveFile.FileName+'.heh');
end;
/////////// KONIEC SEKCJI WCZYTYWANIA I ZAPISYWANIA
////////////////////////////////////////////////////
end.
|
(******************************************************************************
* PasVulkan *
******************************************************************************
* Version see PasVulkan.Framework.pas *
******************************************************************************
* zlib license *
*============================================================================*
* *
* Copyright (C) 2016-2020, Benjamin Rosseaux (benjamin@rosseaux.de) *
* *
* This software is provided 'as-is', without any express or implied *
* warranty. In no event will the authors be held liable for any damages *
* arising from the use of this software. *
* *
* Permission is granted to anyone to use this software for any purpose, *
* including commercial applications, and to alter it and redistribute it *
* freely, subject to the following restrictions: *
* *
* 1. The origin of this software must not be misrepresented; you must not *
* claim that you wrote the original software. If you use this software *
* in a product, an acknowledgement in the product documentation would be *
* appreciated but is not required. *
* 2. Altered source versions must be plainly marked as such, and must not be *
* misrepresented as being the original software. *
* 3. This notice may not be removed or altered from any source distribution. *
* *
******************************************************************************
* General guidelines for code contributors *
*============================================================================*
* *
* 1. Make sure you are legally allowed to make a contribution under the zlib *
* license. *
* 2. The zlib license header goes at the top of each source file, with *
* appropriate copyright notice. *
* 3. This PasVulkan wrapper may be used only with the PasVulkan-own Vulkan *
* Pascal header. *
* 4. After a pull request, check the status of your pull request on *
http://github.com/BeRo1985/pasvulkan *
* 5. Write code which's compatible with Delphi >= 2009 and FreePascal >= *
* 3.1.1 *
* 6. Don't use Delphi-only, FreePascal-only or Lazarus-only libraries/units, *
* but if needed, make it out-ifdef-able. *
* 7. No use of third-party libraries/units as possible, but if needed, make *
* it out-ifdef-able. *
* 8. Try to use const when possible. *
* 9. Make sure to comment out writeln, used while debugging. *
* 10. Make sure the code compiles on 32-bit and 64-bit platforms (x86-32, *
* x86-64, ARM, ARM64, etc.). *
* 11. Make sure the code runs on all platforms with Vulkan support *
* *
******************************************************************************)
unit PasVulkan.Collections;
{$i PasVulkan.inc}
{$ifndef fpc}
{$legacyifend on}
{$endif}
{$define ExtraStringHashMap}
interface
uses SysUtils,
Classes,
SyncObjs,
TypInfo,
PasMP,
PasVulkan.Types,
PasVulkan.Math,
PasVulkan.Utils,
Generics.Collections;
type TpvDynamicArray<T>=record
public
Items:array of T;
Count:TpvSizeInt;
procedure Initialize;
procedure Finalize;
procedure Clear;
procedure Resize(const aCount:TpvSizeInt);
procedure Finish;
procedure Assign(const aFrom:{$ifdef fpc}{$endif}TpvDynamicArray<T>); overload;
procedure Assign(const aItems:array of T); overload;
function AddNew:TpvSizeInt; overload;
function Insert(const aIndex:TpvSizeInt;const aItem:T):TpvSizeInt; overload;
function Add(const aItem:T):TpvSizeInt; overload;
function Add(const aItems:array of T):TpvSizeInt; overload;
function Add(const aFrom:{$ifdef fpc}{$endif}TpvDynamicArray<T>):TpvSizeInt; overload;
function AddRangeFrom(const aFrom:{$ifdef fpc}{$endif}TpvDynamicArray<T>;const aStartIndex,aCount:TpvSizeInt):TpvSizeInt; overload;
function AssignRangeFrom(const aFrom:{$ifdef fpc}{$endif}TpvDynamicArray<T>;const aStartIndex,aCount:TpvSizeInt):TpvSizeInt; overload;
procedure Exchange(const aIndexA,aIndexB:TpvSizeInt); inline;
procedure Delete(const aIndex:TpvSizeInt);
end;
TpvDynamicStack<T>=record
public
Items:array of T;
Count:TpvSizeInt;
procedure Initialize;
procedure Finalize;
procedure Push(const aItem:T);
function Pop(out aItem:T):boolean;
end;
TpvDynamicQueue<T>=record
public
type TQueueItems=array of T;
public
Items:TQueueItems;
Head:TpvSizeInt;
Tail:TpvSizeInt;
Count:TpvSizeInt;
Size:TpvSizeInt;
procedure Initialize;
procedure Finalize;
procedure GrowResize(const aSize:TpvSizeInt);
procedure Clear;
function IsEmpty:boolean;
procedure EnqueueAtFront(const aItem:T);
procedure Enqueue(const aItem:T);
function Dequeue(out aItem:T):boolean; overload;
function Dequeue:boolean; overload;
function Peek(out aItem:T):boolean;
end;
{ TpvDynamicArrayList }
TpvDynamicArrayList<T>=class
public
type PT=^T;
TItemArray=array of T;
private
type TValueEnumerator=record
private
fDynamicArray:TpvDynamicArrayList<T>;
fIndex:TpvSizeInt;
function GetCurrent:T; inline;
public
constructor Create(const aDynamicArray:TpvDynamicArrayList<T>);
function MoveNext:boolean; inline;
property Current:T read GetCurrent;
end;
private
fItems:TItemArray;
fCount:TpvSizeInt;
fAllocated:TpvSizeInt;
procedure SetCount(const pNewCount:TpvSizeInt);
function GetItem(const pIndex:TpvSizeInt):T; inline;
procedure SetItem(const pIndex:TpvSizeInt;const pItem:T); inline;
protected
public
constructor Create;
destructor Destroy; override;
procedure Clear;
function AddNew:PT;
function Add(const pItem:T):TpvSizeInt; overload;
function Add(const pItems:TpvDynamicArrayList<T>):TpvSizeInt; overload;
procedure Insert(const pIndex:TpvSizeInt;const pItem:T);
procedure Delete(const pIndex:TpvSizeInt);
procedure Exchange(const pIndex,pWithIndex:TpvSizeInt); inline;
function GetEnumerator:TValueEnumerator;
function Memory:TpvPointer; inline;
property Count:TpvSizeInt read fCount write SetCount;
property Allocated:TpvSizeInt read fAllocated;
property ItemArray:TItemArray read fItems;
property Items[const pIndex:TpvSizeInt]:T read GetItem write SetItem; default;
end;
TpvBaseList=class
private
procedure SetCount(const pNewCount:TpvSizeInt);
function GetItem(const pIndex:TpvSizeInt):TpvPointer;
protected
fItemSize:TpvSizeInt;
fCount:TpvSizeInt;
fAllocated:TpvSizeInt;
fMemory:TpvPointer;
fSorted:boolean;
procedure InitializeItem(var pItem); virtual;
procedure FinalizeItem(var pItem); virtual;
procedure CopyItem(const pSource;var pDestination); virtual;
procedure ExchangeItem(var pSource,pDestination); virtual;
function CompareItem(const pSource,pDestination):TpvInt32; virtual;
public
constructor Create(const pItemSize:TpvSizeInt);
destructor Destroy; override;
procedure Clear; virtual;
procedure FillWith(const pSourceData;const pSourceCount:TpvSizeInt); virtual;
function IndexOf(const pItem):TpvSizeInt; virtual;
function Add(const pItem):TpvSizeInt; virtual;
procedure Insert(const pIndex:TpvSizeInt;const pItem); virtual;
procedure Delete(const pIndex:TpvSizeInt); virtual;
procedure Remove(const pItem); virtual;
procedure Exchange(const pIndex,pWithIndex:TpvSizeInt); virtual;
procedure Sort; virtual;
property Count:TpvSizeInt read fCount write SetCount;
property Allocated:TpvSizeInt read fAllocated;
property Memory:TpvPointer read fMemory;
property ItemPointers[const pIndex:TpvSizeInt]:TpvPointer read GetItem; default;
property Sorted:boolean read fSorted;
end;
TpvObjectGenericList<T:class>=class
private
type TValueEnumerator=record
private
fObjectList:TpvObjectGenericList<T>;
fIndex:TpvSizeInt;
function GetCurrent:T; inline;
public
constructor Create(const aObjectList:TpvObjectGenericList<T>);
function MoveNext:boolean; inline;
property Current:T read GetCurrent;
end;
private
fItems:array of T;
fCount:TpvSizeInt;
fAllocated:TpvSizeInt;
fOwnsObjects:boolean;
procedure SetCount(const pNewCount:TpvSizeInt);
function GetItem(const pIndex:TpvSizeInt):T;
procedure SetItem(const pIndex:TpvSizeInt;const pItem:T);
function GetPointerToItems:pointer;
public
constructor Create(const aOwnsObjects:boolean=true); reintroduce;
destructor Destroy; override;
procedure Clear;
function Contains(const pItem:T):Boolean;
function IndexOf(const pItem:T):TpvSizeInt;
function Add(const pItem:T):TpvSizeInt;
procedure Insert(const pIndex:TpvSizeInt;const pItem:T);
procedure Delete(const pIndex:TpvSizeInt);
function Extract(const pIndex:TpvSizeInt):T;
function ExtractIndex(const pIndex:TpvSizeInt):T;
procedure Remove(const pItem:T);
procedure Exchange(const pIndex,pWithIndex:TpvSizeInt);
function GetEnumerator:TValueEnumerator;
property Count:TpvSizeInt read fCount write SetCount;
property Allocated:TpvSizeInt read fAllocated;
property Items[const pIndex:TpvSizeInt]:T read GetItem write SetItem; default;
property OwnsObjects:boolean read fOwnsObjects write fOwnsObjects;
property PointerToItems:pointer read GetPointerToItems;
end;
TpvObjectList=TpvObjectGenericList<TObject>;
TpvGenericList<T>=class
private
type PT=^T;
TValueEnumerator=record
private
fGenericList:TpvGenericList<T>;
fIndex:TpvSizeInt;
function GetCurrent:T; inline;
public
constructor Create(const aGenericList:TpvGenericList<T>);
function MoveNext:boolean; inline;
property Current:T read GetCurrent;
end;
private
fItems:array of T;
fCount:TpvSizeInt;
fAllocated:TpvSizeInt;
fSorted:boolean;
function GetData:pointer;
procedure SetCount(const pNewCount:TpvSizeInt);
function GetItemPointer(const pIndex:TpvSizeInt):PT;
function GetItem(const pIndex:TpvSizeInt):T;
procedure SetItem(const pIndex:TpvSizeInt;const pItem:T);
protected
public
constructor Create;
destructor Destroy; override;
procedure Clear; virtual;
procedure Assign(const pFrom:TpvGenericList<T>);
function Contains(const pItem:T):Boolean;
function IndexOf(const pItem:T):TpvSizeInt;
function Add(const pItem:T):TpvSizeInt;
procedure Insert(const pIndex:TpvSizeInt;const pItem:T);
procedure Delete(const pIndex:TpvSizeInt);
procedure Remove(const pItem:T);
procedure Exchange(const pIndex,pWithIndex:TpvSizeInt);
function GetEnumerator:TValueEnumerator;
procedure Sort; overload;
procedure Sort(const aCompareFunction:TpvTypedSort<T>.TpvTypedSortCompareFunction); overload;
property Count:TpvSizeInt read fCount write SetCount;
property Allocated:TpvSizeInt read fAllocated;
property Items[const pIndex:TpvSizeInt]:T read GetItem write SetItem; default;
property ItemPointers[const pIndex:TpvSizeInt]:PT read GetItemPointer;
property Sorted:boolean read fSorted;
property Data:pointer read GetData;
end;
EpvHandleMap=class(Exception);
TpvCustomHandleMap=class
public
type TpvUInt8Array=array of TpvUInt8;
TpvUInt32Array=array of TpvUInt32;
private
fMultipleReaderSingleWriterLock:TPasMPMultipleReaderSingleWriterLock;
fDataSize:TpvSizeUInt;
fSize:TpvSizeUInt;
fIndexCounter:TpvUInt32;
fDenseIndex:TpvUInt32;
fFreeIndex:TpvUInt32;
fFreeArray:TpvUInt32Array;
{$ifdef Debug}
fGenerationArray:TpvUInt32Array;
{$endif}
fSparseToDenseArray:TpvUInt32Array;
fDenseToSparseArray:TpvUInt32Array;
fDataArray:TpvUInt8Array;
protected
procedure InitializeHandleData(var pData); virtual;
procedure FinalizeHandleData(var pData); virtual;
procedure CopyHandleData(const pSource;out pDestination); virtual;
public
constructor Create(const pDataSize:TpvSizeUInt); reintroduce;
destructor Destroy; override;
procedure Lock; inline;
procedure Unlock; inline;
procedure Clear;
procedure Defragment;
function AllocateHandle:TpvHandle;
procedure FreeHandle(const ppvHandle:TpvHandle);
procedure GetHandleData(const ppvHandle:TpvHandle;out pData);
procedure SetHandleData(const ppvHandle:TpvHandle;const pData);
function GetHandleDataPointer(const ppvHandle:TpvHandle):TpvPointer; inline;
property DataSize:TpvSizeUInt read fDataSize;
property Size:TpvSizeUInt read fSize;
property IndexCounter:TpvUInt32 read fIndexCounter;
end;
TpvHashMapEntityIndices=array of TpvInt32;
TpvHashMapUInt128=array[0..1] of TpvUInt64;
TpvHashMap<TpvHashMapKey,TpvHashMapValue>=class
public
const CELL_EMPTY=-1;
CELL_DELETED=-2;
ENT_EMPTY=-1;
ENT_DELETED=-2;
type PpvHashMapEntity=^TpvHashMapEntity;
TpvHashMapEntity=record
Key:TpvHashMapKey;
Value:TpvHashMapValue;
end;
TpvHashMapEntities=array of TpvHashMapEntity;
private
type TpvHashMapEntityEnumerator=record
private
fHashMap:TpvHashMap<TpvHashMapKey,TpvHashMapValue>;
fIndex:TpvSizeInt;
function GetCurrent:TpvHashMapEntity; inline;
public
constructor Create(const aHashMap:TpvHashMap<TpvHashMapKey,TpvHashMapValue>);
function MoveNext:boolean; inline;
property Current:TpvHashMapEntity read GetCurrent;
end;
TpvHashMapKeyEnumerator=record
private
fHashMap:TpvHashMap<TpvHashMapKey,TpvHashMapValue>;
fIndex:TpvSizeInt;
function GetCurrent:TpvHashMapKey; inline;
public
constructor Create(const aHashMap:TpvHashMap<TpvHashMapKey,TpvHashMapValue>);
function MoveNext:boolean; inline;
property Current:TpvHashMapKey read GetCurrent;
end;
TpvHashMapValueEnumerator=record
private
fHashMap:TpvHashMap<TpvHashMapKey,TpvHashMapValue>;
fIndex:TpvSizeInt;
function GetCurrent:TpvHashMapValue; inline;
public
constructor Create(const aHashMap:TpvHashMap<TpvHashMapKey,TpvHashMapValue>);
function MoveNext:boolean; inline;
property Current:TpvHashMapValue read GetCurrent;
end;
TpvHashMapEntitiesObject=class
private
fOwner:TpvHashMap<TpvHashMapKey,TpvHashMapValue>;
public
constructor Create(const aOwner:TpvHashMap<TpvHashMapKey,TpvHashMapValue>);
function GetEnumerator:TpvHashMapEntityEnumerator;
end;
TpvHashMapKeysObject=class
private
fOwner:TpvHashMap<TpvHashMapKey,TpvHashMapValue>;
public
constructor Create(const aOwner:TpvHashMap<TpvHashMapKey,TpvHashMapValue>);
function GetEnumerator:TpvHashMapKeyEnumerator;
end;
TpvHashMapValuesObject=class
private
fOwner:TpvHashMap<TpvHashMapKey,TpvHashMapValue>;
function GetValue(const Key:TpvHashMapKey):TpvHashMapValue; inline;
procedure SetValue(const Key:TpvHashMapKey;const aValue:TpvHashMapValue); inline;
public
constructor Create(const aOwner:TpvHashMap<TpvHashMapKey,TpvHashMapValue>);
function GetEnumerator:TpvHashMapValueEnumerator;
property Values[const Key:TpvHashMapKey]:TpvHashMapValue read GetValue write SetValue; default;
end;
private
fRealSize:TpvInt32;
fLogSize:TpvInt32;
fSize:TpvInt32;
fEntities:TpvHashMapEntities;
fEntityToCellIndex:TpvHashMapEntityIndices;
fCellToEntityIndex:TpvHashMapEntityIndices;
fDefaultValue:TpvHashMapValue;
fCanShrink:boolean;
fEntitiesObject:TpvHashMapEntitiesObject;
fKeysObject:TpvHashMapKeysObject;
fValuesObject:TpvHashMapValuesObject;
function HashData(const Data:TpvPointer;const DataLength:TpvUInt32):TpvUInt32;
function HashKey(const Key:TpvHashMapKey):TpvUInt32;
function CompareKey(const KeyA,KeyB:TpvHashMapKey):boolean;
function FindCell(const Key:TpvHashMapKey):TpvUInt32;
procedure Resize;
protected
function GetValue(const Key:TpvHashMapKey):TpvHashMapValue;
procedure SetValue(const Key:TpvHashMapKey;const Value:TpvHashMapValue);
public
constructor Create(const DefaultValue:TpvHashMapValue);
destructor Destroy; override;
procedure Clear;
function Add(const Key:TpvHashMapKey;const Value:TpvHashMapValue):PpvHashMapEntity;
function Get(const Key:TpvHashMapKey;const CreateIfNotExist:boolean=false):PpvHashMapEntity;
function TryGet(const Key:TpvHashMapKey;out Value:TpvHashMapValue):boolean;
function ExistKey(const Key:TpvHashMapKey):boolean;
function Delete(const Key:TpvHashMapKey):boolean;
property EntityValues[const Key:TpvHashMapKey]:TpvHashMapValue read GetValue write SetValue; default;
property Entities:TpvHashMapEntitiesObject read fEntitiesObject;
property Keys:TpvHashMapKeysObject read fKeysObject;
property Values:TpvHashMapValuesObject read fValuesObject;
property CanShrink:boolean read fCanShrink write fCanShrink;
end;
{$ifdef ExtraStringHashMap}
TpvStringHashMap<TpvHashMapValue>=class
private
const CELL_EMPTY=-1;
CELL_DELETED=-2;
ENT_EMPTY=-1;
ENT_DELETED=-2;
type TpvHashMapKey=RawByteString;
PpvHashMapEntity=^TpvHashMapEntity;
TpvHashMapEntity=record
Key:TpvHashMapKey;
Value:TpvHashMapValue;
end;
TpvHashMapEntities=array of TpvHashMapEntity;
private
type TpvHashMapEntityEnumerator=record
private
fHashMap:TpvStringHashMap<TpvHashMapValue>;
fIndex:TpvSizeInt;
function GetCurrent:TpvHashMapEntity; inline;
public
constructor Create(const aHashMap:TpvStringHashMap<TpvHashMapValue>);
function MoveNext:boolean; inline;
property Current:TpvHashMapEntity read GetCurrent;
end;
TpvHashMapKeyEnumerator=record
private
fHashMap:TpvStringHashMap<TpvHashMapValue>;
fIndex:TpvSizeInt;
function GetCurrent:TpvHashMapKey; inline;
public
constructor Create(const aHashMap:TpvStringHashMap<TpvHashMapValue>);
function MoveNext:boolean; inline;
property Current:TpvHashMapKey read GetCurrent;
end;
TpvHashMapValueEnumerator=record
private
fHashMap:TpvStringHashMap<TpvHashMapValue>;
fIndex:TpvSizeInt;
function GetCurrent:TpvHashMapValue; inline;
public
constructor Create(const aHashMap:TpvStringHashMap<TpvHashMapValue>);
function MoveNext:boolean; inline;
property Current:TpvHashMapValue read GetCurrent;
end;
TpvHashMapEntitiesObject=class
private
fOwner:TpvStringHashMap<TpvHashMapValue>;
public
constructor Create(const aOwner:TpvStringHashMap<TpvHashMapValue>);
function GetEnumerator:TpvHashMapEntityEnumerator;
end;
TpvHashMapKeysObject=class
private
fOwner:TpvStringHashMap<TpvHashMapValue>;
public
constructor Create(const aOwner:TpvStringHashMap<TpvHashMapValue>);
function GetEnumerator:TpvHashMapKeyEnumerator;
end;
TpvHashMapValuesObject=class
private
fOwner:TpvStringHashMap<TpvHashMapValue>;
function GetValue(const Key:TpvHashMapKey):TpvHashMapValue; inline;
procedure SetValue(const Key:TpvHashMapKey;const aValue:TpvHashMapValue); inline;
public
constructor Create(const aOwner:TpvStringHashMap<TpvHashMapValue>);
function GetEnumerator:TpvHashMapValueEnumerator;
property Values[const Key:TpvHashMapKey]:TpvHashMapValue read GetValue write SetValue; default;
end;
private
fRealSize:TpvInt32;
fLogSize:TpvInt32;
fSize:TpvInt32;
fEntities:TpvHashMapEntities;
fEntityToCellIndex:TpvHashMapEntityIndices;
fCellToEntityIndex:TpvHashMapEntityIndices;
fDefaultValue:TpvHashMapValue;
fCanShrink:boolean;
fEntitiesObject:TpvHashMapEntitiesObject;
fKeysObject:TpvHashMapKeysObject;
fValuesObject:TpvHashMapValuesObject;
private
function HashKey(const Key:TpvHashMapKey):TpvUInt32;
function FindCell(const Key:TpvHashMapKey):TpvUInt32;
procedure Resize;
protected
function GetValue(const Key:TpvHashMapKey):TpvHashMapValue;
procedure SetValue(const Key:TpvHashMapKey;const Value:TpvHashMapValue);
public
constructor Create(const DefaultValue:TpvHashMapValue);
destructor Destroy; override;
procedure Clear;
function Add(const Key:TpvHashMapKey;const Value:TpvHashMapValue):PpvHashMapEntity;
function Get(const Key:TpvHashMapKey;const CreateIfNotExist:boolean=false):PpvHashMapEntity;
function TryGet(const Key:TpvHashMapKey;out Value:TpvHashMapValue):boolean;
function ExistKey(const Key:TpvHashMapKey):boolean;
function Delete(const Key:TpvHashMapKey):boolean;
property EntityValues[const Key:TpvHashMapKey]:TpvHashMapValue read GetValue write SetValue; default;
property Entities:TpvHashMapEntitiesObject read fEntitiesObject;
property Keys:TpvHashMapKeysObject read fKeysObject;
property Values:TpvHashMapValuesObject read fValuesObject;
property CanShrink:boolean read fCanShrink write fCanShrink;
end;
{$else}
TpvStringHashMap<TpvHashMapValue>=class(TpvHashMap<RawByteString,TpvHashMapValue>);
{$endif}
TpvGenericSkipList<TKey,TValue>=class
public
type TPair=class
private
fSkipList:TpvGenericSkipList<TKey,TValue>;
fPrevious:TPair;
fNext:TPair;
fKey:TKey;
fValue:TValue;
function GetPrevious:TPair;
function GetNext:TPair;
public
constructor Create(const aSkipList:TpvGenericSkipList<TKey,TValue>;const aKey:TKey;const aValue:TValue); reintroduce;
constructor CreateEmpty(const aSkipList:TpvGenericSkipList<TKey,TValue>); reintroduce;
destructor Destroy; override;
property Previous:TPair read GetPrevious;
property Next:TPair read GetNext;
property Key:TKey read fKey write fKey;
property Value:TValue read fValue write fValue;
end;
TNode=class
private
fPrevious:TNode;
fNext:TNode;
fChildren:TNode;
fPair:TPair;
public
constructor Create(const aPrevious:TNode=nil;
const aNext:TNode=nil;
const aChildren:TNode=nil;
const aPair:TPair=nil); reintroduce;
destructor Destroy; override;
published
property Previous:TNode read fPrevious write fPrevious;
property Next:TNode read fNext write fNext;
property Children:TNode read fChildren write fChildren;
property Pair:TPair read fPair write fPair;
end;
TNodeArray=array of TNode;
TRandomGeneratorState=record
State:TpvUInt64;
Increment:TpvUInt64;
end;
private
type TValueEnumerator=record
private
fSkipList:TpvGenericSkipList<TKey,TValue>;
fPair:TPair;
function GetCurrent:TValue; inline;
public
constructor Create(const aSkipList:TpvGenericSkipList<TKey,TValue>);
function MoveNext:boolean; inline;
property Current:TValue read GetCurrent;
end;
private
fRandomGeneratorState:TRandomGeneratorState;
fDefaultValue:TValue;
fHead:TNode;
fPairs:TPair;
function GetRandomValue:TpvUInt32;
function GetFirstPair:TPair;
function GetLastPair:TPair;
function FindPreviousNode(const aNode:TNode;const aKey:TKey):TNode;
public
constructor Create(const aDefaultValue:TValue); reintroduce;
destructor Destroy; override;
function GetNearestPair(const aKey:TKey):TPair;
function GetNearestKey(const aKey:TKey):TKey;
function GetNearestValue(const aKey:TKey):TValue;
function Get(const aKey:TKey;out aValue:TValue):boolean;
function GetPair(const aKey:TKey):TPair;
function GetValue(const aKey:TKey):TValue;
procedure SetValue(const aKey:TKey;const aValue:TValue);
procedure Delete(const aKey:TKey);
function GetEnumerator:TValueEnumerator;
property FirstPair:TPair read GetFirstPair;
property LastPair:TPair read GetLastPair;
property Values[const aKey:TKey]:TValue read GetValue write SetValue; default;
end;
TpvInt64SkipList<TValue>=class
public
type TKey=TpvInt64;
TPair=class
private
fSkipList:TpvInt64SkipList<TValue>;
fPrevious:TPair;
fNext:TPair;
fKey:TKey;
fValue:TValue;
function GetPrevious:TPair;
function GetNext:TPair;
public
constructor Create(const aSkipList:TpvInt64SkipList<TValue>;const aKey:TKey;const aValue:TValue); reintroduce;
constructor CreateEmpty(const aSkipList:TpvInt64SkipList<TValue>); reintroduce;
destructor Destroy; override;
property Previous:TPair read GetPrevious;
property Next:TPair read GetNext;
property Key:TKey read fKey write fKey;
property Value:TValue read fValue write fValue;
end;
TNode=class
private
fPrevious:TNode;
fNext:TNode;
fChildren:TNode;
fPair:TPair;
public
constructor Create(const aPrevious:TNode=nil;
const aNext:TNode=nil;
const aChildren:TNode=nil;
const aPair:TPair=nil); reintroduce;
destructor Destroy; override;
published
property Previous:TNode read fPrevious write fPrevious;
property Next:TNode read fNext write fNext;
property Children:TNode read fChildren write fChildren;
property Pair:TPair read fPair write fPair;
end;
TNodeArray=array of TNode;
TRandomGeneratorState=record
State:TpvUInt64;
Increment:TpvUInt64;
end;
private
type TValueEnumerator=record
private
fSkipList:TpvInt64SkipList<TValue>;
fPair:TPair;
function GetCurrent:TValue; inline;
public
constructor Create(const aSkipList:TpvInt64SkipList<TValue>);
function MoveNext:boolean; inline;
property Current:TValue read GetCurrent;
end;
private
fRandomGeneratorState:TRandomGeneratorState;
fDefaultValue:TValue;
fHead:TNode;
fPairs:TPair;
function GetRandomValue:TpvUInt32;
function GetFirstPair:TPair;
function GetLastPair:TPair;
function FindPreviousNode(const aNode:TNode;const aKey:TKey):TNode;
public
constructor Create(const aDefaultValue:TValue); reintroduce;
destructor Destroy; override;
function GetNearestPair(const aKey:TKey):TPair;
function GetNearestKey(const aKey:TKey):TKey;
function GetNearestValue(const aKey:TKey):TValue;
function Get(const aKey:TKey;out aValue:TValue):boolean;
function GetPair(const aKey:TKey):TPair;
function GetValue(const aKey:TKey):TValue;
procedure SetValue(const aKey:TKey;const aValue:TValue);
procedure Delete(const aKey:TKey);
function GetEnumerator:TValueEnumerator;
property FirstPair:TPair read GetFirstPair;
property LastPair:TPair read GetLastPair;
property Values[const aKey:TKey]:TValue read GetValue write SetValue; default;
end;
implementation
uses Generics.Defaults;
{ TpvDynamicArray<T> }
procedure TpvDynamicArray<T>.Initialize;
begin
Items:=nil;
Count:=0;
end;
procedure TpvDynamicArray<T>.Finalize;
begin
Items:=nil;
Count:=0;
end;
procedure TpvDynamicArray<T>.Clear;
begin
Items:=nil;
Count:=0;
end;
procedure TpvDynamicArray<T>.Resize(const aCount:TpvSizeInt);
begin
if Count<>aCount then begin
Count:=aCount;
SetLength(Items,Count);
end;
end;
procedure TpvDynamicArray<T>.Finish;
begin
SetLength(Items,Count);
end;
procedure TpvDynamicArray<T>.Assign(const aFrom:TpvDynamicArray<T>);
begin
Items:=copy(aFrom.Items);
Count:=aFrom.Count;
end;
procedure TpvDynamicArray<T>.Assign(const aItems:array of T);
var Index:TpvSizeInt;
begin
Count:=length(aItems);
SetLength(Items,Count);
for Index:=0 to Count-1 do begin
Items[Index]:=aItems[Index];
end;
end;
function TpvDynamicArray<T>.Insert(const aIndex:TpvSizeInt;const aItem:T):TpvSizeInt;
begin
result:=aIndex;
if aIndex>=0 then begin
if aIndex<Count then begin
inc(Count);
if length(Items)<Count then begin
SetLength(Items,Count*2);
end;
Move(Items[aIndex],Items[aIndex+1],(Count-(aIndex+1))*SizeOf(T));
FillChar(Items[aIndex],SizeOf(T),#0);
end else begin
Count:=aIndex+1;
if length(Items)<Count then begin
SetLength(Items,Count*2);
end;
end;
Items[aIndex]:=aItem;
end;
end;
function TpvDynamicArray<T>.AddNew:TpvSizeInt;
begin
result:=Count;
if length(Items)<(Count+1) then begin
SetLength(Items,(Count+1)+((Count+1) shr 1));
end;
System.Initialize(Items[Count]);
inc(Count);
end;
function TpvDynamicArray<T>.Add(const aItem:T):TpvSizeInt;
begin
result:=Count;
if length(Items)<(Count+1) then begin
SetLength(Items,(Count+1)+((Count+1) shr 1));
end;
Items[Count]:=aItem;
inc(Count);
end;
function TpvDynamicArray<T>.Add(const aItems:array of T):TpvSizeInt;
var Index,FromCount:TpvSizeInt;
begin
result:=Count;
FromCount:=length(aItems);
if FromCount>0 then begin
if length(Items)<(Count+FromCount) then begin
SetLength(Items,(Count+FromCount)+((Count+FromCount) shr 1));
end;
for Index:=0 to FromCount-1 do begin
Items[Count]:=aItems[Index];
inc(Count);
end;
end;
end;
function TpvDynamicArray<T>.Add(const aFrom:TpvDynamicArray<T>):TpvSizeInt;
var Index:TpvSizeInt;
begin
result:=Count;
if aFrom.Count>0 then begin
if length(Items)<(Count+aFrom.Count) then begin
SetLength(Items,(Count+aFrom.Count)+((Count+aFrom.Count) shr 1));
end;
for Index:=0 to aFrom.Count-1 do begin
Items[Count]:=aFrom.Items[Index];
inc(Count);
end;
end;
end;
function TpvDynamicArray<T>.AddRangeFrom(const aFrom:{$ifdef fpc}{$endif}TpvDynamicArray<T>;const aStartIndex,aCount:TpvSizeInt):TpvSizeInt;
var Index:TpvSizeInt;
begin
result:=Count;
if aCount>0 then begin
if length(Items)<(Count+aCount) then begin
SetLength(Items,(Count+aCount)+((Count+aCount) shr 1));
end;
for Index:=0 to aCount-1 do begin
Items[Count]:=aFrom.Items[aStartIndex+Index];
inc(Count);
end;
end;
end;
function TpvDynamicArray<T>.AssignRangeFrom(const aFrom:{$ifdef fpc}{$endif}TpvDynamicArray<T>;const aStartIndex,aCount:TpvSizeInt):TpvSizeInt;
begin
Clear;
result:=AddRangeFrom(aFrom,aStartIndex,aCount);
end;
procedure TpvDynamicArray<T>.Exchange(const aIndexA,aIndexB:TpvSizeInt);
var Temp:T;
begin
Temp:=Items[aIndexA];
Items[aIndexA]:=Items[aIndexB];
Items[aIndexB]:=Temp;
end;
procedure TpvDynamicArray<T>.Delete(const aIndex:TpvSizeInt);
begin
if (Count>0) and (aIndex<Count) then begin
dec(Count);
System.Finalize(Items[aIndex]);
Move(Items[aIndex+1],Items[aIndex],SizeOf(T)*(Count-aIndex));
FillChar(Items[Count],SizeOf(T),#0);
end;
end;
{ TpvDynamicStack<T> }
procedure TpvDynamicStack<T>.Initialize;
begin
Items:=nil;
Count:=0;
end;
procedure TpvDynamicStack<T>.Finalize;
begin
Items:=nil;
Count:=0;
end;
procedure TpvDynamicStack<T>.Push(const aItem:T);
begin
if length(Items)<(Count+1) then begin
SetLength(Items,(Count+1)+((Count+1) shr 1));
end;
Items[Count]:=aItem;
inc(Count);
end;
function TpvDynamicStack<T>.Pop(out aItem:T):boolean;
begin
result:=Count>0;
if result then begin
dec(Count);
aItem:=Items[Count];
end;
end;
{ TpvDynamicQueue<T> }
procedure TpvDynamicQueue<T>.Initialize;
begin
Items:=nil;
Head:=0;
Tail:=0;
Count:=0;
Size:=0;
end;
procedure TpvDynamicQueue<T>.Finalize;
begin
Clear;
end;
procedure TpvDynamicQueue<T>.GrowResize(const aSize:TpvSizeInt);
var Index,OtherIndex:TpvSizeInt;
NewItems:TQueueItems;
begin
SetLength(NewItems,aSize);
OtherIndex:=Head;
for Index:=0 to Count-1 do begin
NewItems[Index]:=Items[OtherIndex];
inc(OtherIndex);
if OtherIndex>=Size then begin
OtherIndex:=0;
end;
end;
Items:=NewItems;
Head:=0;
Tail:=Count;
Size:=aSize;
end;
procedure TpvDynamicQueue<T>.Clear;
begin
while Count>0 do begin
dec(Count);
System.Finalize(Items[Head]);
inc(Head);
if Head>=Size then begin
Head:=0;
end;
end;
Items:=nil;
Head:=0;
Tail:=0;
Count:=0;
Size:=0;
end;
function TpvDynamicQueue<T>.IsEmpty:boolean;
begin
result:=Count=0;
end;
procedure TpvDynamicQueue<T>.EnqueueAtFront(const aItem:T);
var Index:TpvSizeInt;
begin
if Size<=Count then begin
GrowResize(Count+1);
end;
dec(Head);
if Head<0 then begin
inc(Head,Size);
end;
Index:=Head;
Items[Index]:=aItem;
inc(Count);
end;
procedure TpvDynamicQueue<T>.Enqueue(const aItem:T);
var Index:TpvSizeInt;
begin
if Size<=Count then begin
GrowResize(Count+1);
end;
Index:=Tail;
inc(Tail);
if Tail>=Size then begin
Tail:=0;
end;
Items[Index]:=aItem;
inc(Count);
end;
function TpvDynamicQueue<T>.Dequeue(out aItem:T):boolean;
begin
result:=Count>0;
if result then begin
dec(Count);
aItem:=Items[Head];
System.Finalize(Items[Head]);
FillChar(Items[Head],SizeOf(T),#0);
if Count=0 then begin
Head:=0;
Tail:=0;
end else begin
inc(Head);
if Head>=Size then begin
Head:=0;
end;
end;
end;
end;
function TpvDynamicQueue<T>.Dequeue:boolean;
begin
result:=Count>0;
if result then begin
dec(Count);
System.Finalize(Items[Head]);
FillChar(Items[Head],SizeOf(T),#0);
if Count=0 then begin
Head:=0;
Tail:=0;
end else begin
inc(Head);
if Head>=Size then begin
Head:=0;
end;
end;
end;
end;
function TpvDynamicQueue<T>.Peek(out aItem:T):boolean;
begin
result:=Count>0;
if result then begin
aItem:=Items[Head];
end;
end;
constructor TpvDynamicArrayList<T>.TValueEnumerator.Create(const aDynamicArray:TpvDynamicArrayList<T>);
begin
fDynamicArray:=aDynamicArray;
fIndex:=-1;
end;
function TpvDynamicArrayList<T>.TValueEnumerator.MoveNext:boolean;
begin
inc(fIndex);
result:=fIndex<fDynamicArray.fCount;
end;
function TpvDynamicArrayList<T>.TValueEnumerator.GetCurrent:T;
begin
result:=fDynamicArray.fItems[fIndex];
end;
constructor TpvDynamicArrayList<T>.Create;
begin
fItems:=nil;
fCount:=0;
fAllocated:=0;
inherited Create;
end;
destructor TpvDynamicArrayList<T>.Destroy;
begin
SetLength(fItems,0);
fCount:=0;
fAllocated:=0;
inherited Destroy;
end;
procedure TpvDynamicArrayList<T>.Clear;
begin
SetLength(fItems,0);
fCount:=0;
fAllocated:=0;
end;
procedure TpvDynamicArrayList<T>.SetCount(const pNewCount:TpvSizeInt);
begin
if pNewCount<=0 then begin
SetLength(fItems,0);
fCount:=0;
fAllocated:=0;
end else begin
if pNewCount<fCount then begin
fCount:=pNewCount;
if (fCount+fCount)<fAllocated then begin
fAllocated:=fCount+fCount;
SetLength(fItems,fAllocated);
end;
end else begin
fCount:=pNewCount;
if fAllocated<fCount then begin
fAllocated:=fCount+fCount;
SetLength(fItems,fAllocated);
end;
end;
end;
end;
function TpvDynamicArrayList<T>.GetItem(const pIndex:TpvSizeInt):T;
begin
result:=fItems[pIndex];
end;
procedure TpvDynamicArrayList<T>.SetItem(const pIndex:TpvSizeInt;const pItem:T);
begin
fItems[pIndex]:=pItem;
end;
function TpvDynamicArrayList<T>.AddNew:PT;
begin
inc(fCount);
if fAllocated<fCount then begin
fAllocated:=fCount+fCount;
SetLength(fItems,fAllocated);
end;
result:=@fItems[fCount-1];
end;
function TpvDynamicArrayList<T>.Add(const pItem:T):TpvSizeInt;
begin
result:=fCount;
inc(fCount);
if fAllocated<fCount then begin
fAllocated:=fCount+fCount;
SetLength(fItems,fAllocated);
end;
fItems[result]:=pItem;
end;
function TpvDynamicArrayList<T>.Add(const pItems:TpvDynamicArrayList<T>):TpvSizeInt;
var Index:TpvSizeInt;
begin
result:=fCount;
if pItems.Count>0 then begin
inc(fCount,pItems.Count);
if fAllocated<fCount then begin
fAllocated:=fCount+fCount;
SetLength(fItems,fAllocated);
end;
for Index:=0 to pItems.Count-1 do begin
fItems[result+index]:=pItems.fItems[Index];
end;
end;
end;
procedure TpvDynamicArrayList<T>.Insert(const pIndex:TpvSizeInt;const pItem:T);
begin
if pIndex>=0 then begin
if pIndex<fCount then begin
inc(fCount);
if fCount<fAllocated then begin
fAllocated:=fCount shl 1;
SetLength(fItems,fAllocated);
end;
Move(fItems[pIndex],fItems[pIndex+1],(fCount-pIndex)*SizeOf(T));
FillChar(fItems[pIndex],SizeOf(T),#0);
end else begin
fCount:=pIndex+1;
if fCount<fAllocated then begin
fAllocated:=fCount shl 1;
SetLength(fItems,fAllocated);
end;
end;
fItems[pIndex]:=pItem;
end;
end;
procedure TpvDynamicArrayList<T>.Delete(const pIndex:TpvSizeInt);
begin
Finalize(fItems[pIndex]);
Move(fItems[pIndex+1],fItems[pIndex],(fCount-pIndex)*SizeOf(T));
dec(fCount);
FillChar(fItems[fCount],SizeOf(T),#0);
if fCount<(fAllocated shr 1) then begin
fAllocated:=fAllocated shr 1;
SetLength(fItems,fAllocated);
end;
end;
procedure TpvDynamicArrayList<T>.Exchange(const pIndex,pWithIndex:TpvSizeInt);
var Temporary:T;
begin
Temporary:=fItems[pIndex];
fItems[pIndex]:=fItems[pWithIndex];
fItems[pWithIndex]:=Temporary;
end;
function TpvDynamicArrayList<T>.Memory:TpvPointer;
begin
result:=@fItems[0];
end;
function TpvDynamicArrayList<T>.GetEnumerator: TValueEnumerator;
begin
result:=TValueEnumerator.Create(self);
end;
constructor TpvBaseList.Create(const pItemSize:TpvSizeInt);
begin
inherited Create;
fItemSize:=pItemSize;
fCount:=0;
fAllocated:=0;
fMemory:=nil;
fSorted:=false;
end;
destructor TpvBaseList.Destroy;
begin
Clear;
inherited Destroy;
end;
procedure TpvBaseList.SetCount(const pNewCount:TpvSizeInt);
var Index,NewAllocated:TpvSizeInt;
Item:TpvPointer;
begin
if fCount<pNewCount then begin
NewAllocated:=RoundUpToPowerOfTwoSizeUInt(pNewCount);
if fAllocated<NewAllocated then begin
if assigned(fMemory) then begin
ReallocMem(fMemory,NewAllocated*fItemSize);
end else begin
GetMem(fMemory,NewAllocated*fItemSize);
end;
FillChar(TpvPointer(TpvPtrUInt(TpvPtrUInt(fMemory)+(TpvPtrUInt(fAllocated)*TpvPtrUInt(fItemSize))))^,(NewAllocated-fAllocated)*fItemSize,#0);
fAllocated:=NewAllocated;
end;
Item:=fMemory;
Index:=fCount;
inc(TpvPtrUInt(Item),Index*fItemSize);
while Index<pNewCount do begin
FillChar(Item^,fItemSize,#0);
InitializeItem(Item^);
inc(TpvPtrUInt(Item),fItemSize);
inc(Index);
end;
fCount:=pNewCount;
end else if fCount>pNewCount then begin
Item:=fMemory;
Index:=pNewCount;
inc(TpvPtrUInt(Item),Index*fItemSize);
while Index<fCount do begin
FinalizeItem(Item^);
FillChar(Item^,fItemSize,#0);
inc(TpvPtrUInt(Item),fItemSize);
inc(Index);
end;
fCount:=pNewCount;
if pNewCount<(fAllocated shr 2) then begin
if pNewCount=0 then begin
if assigned(fMemory) then begin
FreeMem(fMemory);
fMemory:=nil;
end;
fAllocated:=0;
end else begin
NewAllocated:=fAllocated shr 1;
if assigned(fMemory) then begin
ReallocMem(fMemory,NewAllocated*fItemSize);
end else begin
GetMem(fMemory,NewAllocated*fItemSize);
end;
fAllocated:=NewAllocated;
end;
end;
end;
fSorted:=false;
end;
function TpvBaseList.GetItem(const pIndex:TpvSizeInt):TpvPointer;
begin
if (pIndex>=0) and (pIndex<fCount) then begin
result:=TpvPointer(TpvPtrUInt(TpvPtrUInt(fMemory)+(TpvPtrUInt(pIndex)*TpvPtrUInt(fItemSize))));
end else begin
result:=nil;
end;
end;
procedure TpvBaseList.InitializeItem(var pItem);
begin
end;
procedure TpvBaseList.FinalizeItem(var pItem);
begin
end;
procedure TpvBaseList.CopyItem(const pSource;var pDestination);
begin
Move(pSource,pDestination,fItemSize);
end;
procedure TpvBaseList.ExchangeItem(var pSource,pDestination);
var a,b:PpvUInt8;
c8:TpvUInt8;
c32:TpvUInt32;
Index:TpvInt32;
begin
a:=@pSource;
b:=@pDestination;
for Index:=1 to fItemSize shr 2 do begin
c32:=PpvUInt32(a)^;
PpvUInt32(a)^:=PpvUInt32(b)^;
PpvUInt32(b)^:=c32;
inc(PpvUInt32(a));
inc(PpvUInt32(b));
end;
for Index:=1 to fItemSize and 3 do begin
c8:=a^;
a^:=b^;
b^:=c8;
inc(a);
inc(b);
end;
end;
function TpvBaseList.CompareItem(const pSource,pDestination):TpvInt32;
var a,b:PpvUInt8;
Index:TpvInt32;
begin
result:=0;
a:=@pSource;
b:=@pDestination;
for Index:=1 to fItemSize do begin
result:=a^-b^;
if result<>0 then begin
exit;
end;
inc(a);
inc(b);
end;
end;
procedure TpvBaseList.Clear;
var Index:TpvSizeInt;
Item:TpvPointer;
begin
Item:=fMemory;
Index:=0;
while Index<fCount do begin
FinalizeItem(Item^);
inc(TpvPtrInt(Item),fItemSize);
inc(Index);
end;
if assigned(fMemory) then begin
FreeMem(fMemory);
fMemory:=nil;
end;
fCount:=0;
fAllocated:=0;
fSorted:=false;
end;
procedure TpvBaseList.FillWith(const pSourceData;const pSourceCount:TpvSizeInt);
var Index:TpvSizeInt;
SourceItem,Item:TpvPointer;
begin
SourceItem:=@pSourceData;
if assigned(SourceItem) and (pSourceCount>0) then begin
SetCount(pSourceCount);
Item:=fMemory;
Index:=0;
while Index<fCount do begin
CopyItem(SourceItem^,Item^);
inc(TpvPtrInt(SourceItem),fItemSize);
inc(TpvPtrInt(Item),fItemSize);
inc(Index);
end;
end else begin
SetCount(0);
end;
fSorted:=false;
end;
function TpvBaseList.IndexOf(const pItem):TpvSizeInt;
var Index,LowerIndexBound,UpperIndexBound,Difference:TpvInt32;
begin
result:=-1;
if fSorted then begin
LowerIndexBound:=0;
UpperIndexBound:=fCount-1;
while LowerIndexBound<=UpperIndexBound do begin
Index:=LowerIndexBound+((UpperIndexBound-LowerIndexBound) shr 1);
Difference:=CompareItem(TpvPointer(TpvPtrUInt(TpvPtrUInt(fMemory)+(TpvPtrUInt(Index)*TpvPtrUInt(fItemSize))))^,pItem);
if Difference=0 then begin
result:=Index;
exit;
end else if Difference<0 then begin
LowerIndexBound:=Index+1;
end else begin
UpperIndexBound:=Index-1;
end;
end;
end else begin
Index:=0;
while Index<fCount do begin
if CompareItem(pItem,TpvPointer(TpvPtrUInt(TpvPtrUInt(fMemory)+(TpvPtrUInt(Index)*TpvPtrUInt(fItemSize))))^)=0 then begin
result:=Index;
break;
end;
inc(Index);
end;
end;
end;
function TpvBaseList.Add(const pItem):TpvSizeInt;
var Index,LowerIndexBound,UpperIndexBound,Difference:TpvInt32;
begin
if fSorted and (fCount>0) then begin
if CompareItem(TpvPointer(TpvPtrUInt(TpvPtrUInt(fMemory)+(TpvPtrUInt(fCount-1)*TpvPtrUInt(fItemSize))))^,pItem)<0 then begin
result:=fCount;
end else if CompareItem(pItem,TpvPointer(TpvPtrUInt(TpvPtrUInt(fMemory)+(TpvPtrUInt(0)*TpvPtrUInt(fItemSize))))^)<0 then begin
result:=0;
end else begin
LowerIndexBound:=0;
UpperIndexBound:=fCount-1;
while LowerIndexBound<=UpperIndexBound do begin
Index:=LowerIndexBound+((UpperIndexBound-LowerIndexBound) shr 1);
Difference:=CompareItem(TpvPointer(TpvPtrUInt(TpvPtrUInt(fMemory)+(TpvPtrUInt(Index)*TpvPtrUInt(fItemSize))))^,pItem);
if Difference=0 then begin
LowerIndexBound:=Index;
break;
end else if Difference<0 then begin
LowerIndexBound:=Index+1;
end else begin
UpperIndexBound:=Index-1;
end;
end;
result:=LowerIndexBound;
end;
if result>=0 then begin
Insert(result,pItem);
fSorted:=true;
end;
end else begin
result:=fCount;
SetCount(result+1);
CopyItem(pItem,TpvPointer(TpvPtrUInt(TpvPtrUInt(fMemory)+(TpvPtrUInt(result)*TpvPtrUInt(fItemSize))))^);
fSorted:=false;
end;
end;
procedure TpvBaseList.Insert(const pIndex:TpvSizeInt;const pItem);
begin
if pIndex>=0 then begin
if pIndex<fCount then begin
SetCount(fCount+1);
Move(TpvPointer(TpvPtrInt(TpvPtrUInt(fMemory)+(TpvPtrUInt(pIndex)*TpvPtrUInt(fItemSize))))^,TpvPointer(TpvPtrUInt(TpvPtrUInt(fMemory)+(TpvPtrUInt(pIndex+1)*TpvPtrUInt(fItemSize))))^,(fCount-(pIndex+1))*fItemSize);
FillChar(TpvPointer(TpvPtrInt(TpvPtrUInt(fMemory)+(TpvPtrUInt(pIndex)*TpvPtrUInt(fItemSize))))^,fItemSize,#0);
end else begin
SetCount(pIndex+1);
end;
CopyItem(pItem,TpvPointer(TpvPtrUInt(TpvPtrUInt(fMemory)+(TpvPtrUInt(pIndex)*TpvPtrUInt(fItemSize))))^);
end;
fSorted:=false;
end;
procedure TpvBaseList.Delete(const pIndex:TpvSizeInt);
var OldSorted:boolean;
begin
if (pIndex>=0) and (pIndex<fCount) then begin
OldSorted:=fSorted;
FinalizeItem(TpvPointer(TpvPtrUInt(TpvPtrUInt(fMemory)+(TpvPtrUInt(pIndex)*TpvPtrUInt(fItemSize))))^);
Move(TpvPointer(TpvPtrUInt(TpvPtruInt(fMemory)+(TpvPtrUInt(pIndex+1)*TpvPtrUInt(fItemSize))))^,TpvPointer(TpvPtrUInt(TpvPtrUInt(fMemory)+(TpvPtrUInt(pIndex)*TpvPtrUInt(fItemSize))))^,(fCount-pIndex)*fItemSize);
FillChar(TpvPointer(TpvPtrUInt(TpvPtrUInt(fMemory)+(TpvPtrUInt(fCount-1)*TpvPtrUInt(fItemSize))))^,fItemSize,#0);
SetCount(fCount-1);
fSorted:=OldSorted;
end;
end;
procedure TpvBaseList.Remove(const pItem);
var Index:TpvSizeInt;
begin
repeat
Index:=IndexOf(pItem);
if Index>=0 then begin
Delete(Index);
end else begin
break;
end;
until false;
end;
procedure TpvBaseList.Exchange(const pIndex,pWithIndex:TpvSizeInt);
begin
if (pIndex>=0) and (pIndex<fCount) and (pWithIndex>=0) and (pWithIndex<fCount) then begin
ExchangeItem(TpvPointer(TpvPtrUInt(TpvPtrUInt(fMemory)+(TpvPtrUInt(pIndex)*TpvPtrUInt(fItemSize))))^,TpvPointer(TpvPtrUInt(TpvPtrUInt(fMemory)+(TpvPtrUInt(pWithIndex)*TpvPtrUInt(fItemSize))))^);
fSorted:=false;
end;
end;
procedure TpvBaseList.Sort;
type PByteArray=^TByteArray;
TByteArray=array[0..$3fffffff] of TpvUInt8;
PStackItem=^TStackItem;
TStackItem=record
Left,Right,Depth:TpvInt32;
end;
var Left,Right,Depth,i,j,Middle,Size,Parent,Child,Pivot,iA,iB,iC:TpvInt32;
StackItem:PStackItem;
Stack:array[0..31] of TStackItem;
begin
if not fSorted then begin
if fCount>1 then begin
StackItem:=@Stack[0];
StackItem^.Left:=0;
StackItem^.Right:=fCount-1;
StackItem^.Depth:=IntLog2(fCount) shl 1;
inc(StackItem);
while TpvPtrUInt(TpvPointer(StackItem))>TpvPtrUInt(TpvPointer(@Stack[0])) do begin
dec(StackItem);
Left:=StackItem^.Left;
Right:=StackItem^.Right;
Depth:=StackItem^.Depth;
Size:=(Right-Left)+1;
if Size<16 then begin
// Insertion sort
iA:=Left;
iB:=iA+1;
while iB<=Right do begin
iC:=iB;
while (iA>=Left) and
(iC>=Left) and
(CompareItem(TpvPointer(TpvPtrUInt(TpvPtrUInt(fMemory)+(TpvPtrUInt(iA)*TpvPtrUInt(fItemSize))))^,
TpvPointer(TpvPtrUInt(TpvPtrUInt(fMemory)+(TpvPtrUInt(iC)*TpvPtrUInt(fItemSize))))^)>0) do begin
Exchange(iA,iC);
dec(iA);
dec(iC);
end;
iA:=iB;
inc(iB);
end;
end else begin
if (Depth=0) or (TpvPtrUInt(TpvPointer(StackItem))>=TpvPtrUInt(TpvPointer(@Stack[high(Stack)-1]))) then begin
// Heap sort
i:=Size div 2;
repeat
if i>0 then begin
dec(i);
end else begin
dec(Size);
if Size>0 then begin
Exchange(Left+Size,Left);
end else begin
break;
end;
end;
Parent:=i;
repeat
Child:=(Parent*2)+1;
if Child<Size then begin
if (Child<(Size-1)) and (CompareItem(TpvPointer(TpvPtrUInt(TpvPtrUInt(fMemory)+(TpvPtrUInt(Left+Child)*TpvPtrUInt(fItemSize))))^,
TpvPointer(TpvPtrUInt(TpvPtrUInt(fMemory)+(TpvPtrUInt(Left+Child+1)*TpvPtrUInt(fItemSize))))^)<0) then begin
inc(Child);
end;
if CompareItem(TpvPointer(TpvPtrUInt(TpvPtrUInt(fMemory)+(TpvPtrUInt(Left+Parent)*TpvPtrUInt(fItemSize))))^,
TpvPointer(TpvPtrUInt(TpvPtrUInt(fMemory)+(TpvPtrUInt(Left+Child)*TpvPtrUInt(fItemSize))))^)<0 then begin
Exchange(Left+Parent,Left+Child);
Parent:=Child;
continue;
end;
end;
break;
until false;
until false;
end else begin
// Quick sort width median-of-three optimization
Middle:=Left+((Right-Left) shr 1);
if (Right-Left)>3 then begin
if CompareItem(TpvPointer(TpvPtrUInt(TpvPtrUInt(fMemory)+(TpvPtrUInt(Left)*TpvPtrUInt(fItemSize))))^,
TpvPointer(TpvPtrUInt(TpvPtrUInt(fMemory)+(TpvPtrUInt(Middle)*TpvPtrUInt(fItemSize))))^)>0 then begin
Exchange(Left,Middle);
end;
if CompareItem(TpvPointer(TpvPtrUInt(TpvPtrUInt(fMemory)+(TpvPtrUInt(Left)*TpvPtrUInt(fItemSize))))^,
TpvPointer(TpvPtrUInt(TpvPtrUInt(fMemory)+(TpvPtrUInt(Right)*TpvPtrUInt(fItemSize))))^)>0 then begin
Exchange(Left,Right);
end;
if CompareItem(TpvPointer(TpvPtrUInt(TpvPtrUInt(fMemory)+(TpvPtrUInt(Middle)*TpvPtrUInt(fItemSize))))^,
TpvPointer(TpvPtrUInt(TpvPtrUInt(fMemory)+(TpvPtrUInt(Right)*TpvPtrUInt(fItemSize))))^)>0 then begin
Exchange(Middle,Right);
end;
end;
Pivot:=Middle;
i:=Left;
j:=Right;
repeat
while (i<Right) and (CompareItem(TpvPointer(TpvPtrUInt(TpvPtrUInt(fMemory)+(TpvPtrUInt(i)*TpvPtrUInt(fItemSize))))^,
TpvPointer(TpvPtrUInt(TpvPtrUInt(fMemory)+(TpvPtrUInt(Pivot)*TpvPtrUInt(fItemSize))))^)<0) do begin
inc(i);
end;
while (j>=i) and (CompareItem(TpvPointer(TpvPtrUInt(TpvPtrUInt(fMemory)+(TpvPtrUInt(j)*TpvPtrUInt(fItemSize))))^,
TpvPointer(TpvPtrUInt(TpvPtrUInt(fMemory)+(TpvPtrUInt(Pivot)*TpvPtrUInt(fItemSize))))^)>0) do begin
dec(j);
end;
if i>j then begin
break;
end else begin
if i<>j then begin
Exchange(i,j);
if Pivot=i then begin
Pivot:=j;
end else if Pivot=j then begin
Pivot:=i;
end;
end;
inc(i);
dec(j);
end;
until false;
if i<Right then begin
StackItem^.Left:=i;
StackItem^.Right:=Right;
StackItem^.Depth:=Depth-1;
inc(StackItem);
end;
if Left<j then begin
StackItem^.Left:=Left;
StackItem^.Right:=j;
StackItem^.Depth:=Depth-1;
inc(StackItem);
end;
end;
end;
end;
end;
fSorted:=true;
end;
end;
constructor TpvObjectGenericList<T>.TValueEnumerator.Create(const aObjectList:TpvObjectGenericList<T>);
begin
fObjectList:=aObjectList;
fIndex:=-1;
end;
function TpvObjectGenericList<T>.TValueEnumerator.MoveNext:boolean;
begin
inc(fIndex);
result:=fIndex<fObjectList.fCount;
end;
function TpvObjectGenericList<T>.TValueEnumerator.GetCurrent:T;
begin
result:=fObjectList.fItems[fIndex];
end;
constructor TpvObjectGenericList<T>.Create(const aOwnsObjects:boolean);
begin
inherited Create;
fItems:=nil;
fCount:=0;
fAllocated:=0;
fOwnsObjects:=aOwnsObjects;
end;
destructor TpvObjectGenericList<T>.Destroy;
begin
Clear;
inherited Destroy;
end;
procedure TpvObjectGenericList<T>.Clear;
var Index:TpvSizeInt;
begin
if fOwnsObjects then begin
for Index:=fCount-1 downto 0 do begin
FreeAndNil(fItems[Index]);
end;
end;
fItems:=nil;
fCount:=0;
fAllocated:=0;
end;
procedure TpvObjectGenericList<T>.SetCount(const pNewCount:TpvSizeInt);
var Index,NewAllocated:TpvSizeInt;
Item:TpvPointer;
begin
if fCount<pNewCount then begin
NewAllocated:=RoundUpToPowerOfTwoSizeUInt(pNewCount);
if fAllocated<NewAllocated then begin
SetLength(fItems,NewAllocated);
FillChar(fItems[fAllocated],(NewAllocated-fAllocated)*SizeOf(T),#0);
fAllocated:=NewAllocated;
end;
FillChar(fItems[fCount],(pNewCount-fCount)*SizeOf(T),#0);
fCount:=pNewCount;
end else if fCount>pNewCount then begin
if fOwnsObjects then begin
for Index:=fCount-1 downto pNewCount do begin
FreeAndNil(fItems[Index]);
end;
end;
fCount:=pNewCount;
if pNewCount<(fAllocated shr 2) then begin
if pNewCount=0 then begin
fItems:=nil;
fAllocated:=0;
end else begin
NewAllocated:=fAllocated shr 1;
SetLength(fItems,NewAllocated);
fAllocated:=NewAllocated;
end;
end;
end;
end;
function TpvObjectGenericList<T>.GetItem(const pIndex:TpvSizeInt):T;
begin
if (pIndex<0) or (pIndex>=fCount) then begin
raise ERangeError.Create('Out of index range');
end;
result:=fItems[pIndex];
end;
procedure TpvObjectGenericList<T>.SetItem(const pIndex:TpvSizeInt;const pItem:T);
begin
if (pIndex<0) or (pIndex>=fCount) then begin
raise ERangeError.Create('Out of index range');
end;
fItems[pIndex]:=pItem;
end;
function TpvObjectGenericList<T>.GetPointerToItems:pointer;
begin
result:=@fItems[0];
end;
function TpvObjectGenericList<T>.Contains(const pItem:T):Boolean;
var Index:TpvInt32;
begin
for Index:=0 to fCount-1 do begin
if fItems[Index]=pItem then begin
result:=true;
exit;
end;
end;
result:=false;
end;
function TpvObjectGenericList<T>.IndexOf(const pItem:T):TpvSizeInt;
var Index:TpvInt32;
begin
for Index:=0 to fCount-1 do begin
if fItems[Index]=pItem then begin
result:=Index;
exit;
end;
end;
result:=-1;
end;
function TpvObjectGenericList<T>.Add(const pItem:T):TpvSizeInt;
begin
result:=fCount;
inc(fCount);
if fAllocated<fCount then begin
fAllocated:=fCount+fCount;
SetLength(fItems,fAllocated);
end;
fItems[result]:=pItem;
end;
procedure TpvObjectGenericList<T>.Insert(const pIndex:TpvSizeInt;const pItem:T);
var OldCount:TpvSizeInt;
begin
if pIndex>=0 then begin
OldCount:=fCount;
if fCount<pIndex then begin
fCount:=pIndex+1;
end else begin
inc(fCount);
end;
if fAllocated<fCount then begin
fAllocated:=fCount shl 1;
SetLength(fItems,fAllocated);
end;
if OldCount<fCount then begin
FillChar(fItems[OldCount],(fCount-OldCount)*SizeOf(T),#0);
end;
if pIndex<OldCount then begin
System.Move(fItems[pIndex],fItems[pIndex+1],(OldCount-pIndex)*SizeOf(T));
FillChar(fItems[pIndex],SizeOf(T),#0);
end;
fItems[pIndex]:=pItem;
end;
end;
procedure TpvObjectGenericList<T>.Delete(const pIndex:TpvSizeInt);
var Old:T;
begin
if (pIndex<0) or (pIndex>=fCount) then begin
raise ERangeError.Create('Out of index range');
end;
Old:=fItems[pIndex];
dec(fCount);
FillChar(fItems[pIndex],SizeOf(T),#0);
if pIndex<>fCount then begin
System.Move(fItems[pIndex+1],fItems[pIndex],(fCount-pIndex)*SizeOf(T));
FillChar(fItems[fCount],SizeOf(T),#0);
end;
if fCount<(fAllocated shr 1) then begin
fAllocated:=fAllocated shr 1;
SetLength(fItems,fAllocated);
end;
if fOwnsObjects then begin
FreeAndNil(Old);
end;
end;
function TpvObjectGenericList<T>.Extract(const pIndex:TpvSizeInt):T;
var Old:T;
begin
if (pIndex<0) or (pIndex>=fCount) then begin
raise ERangeError.Create('Out of index range');
end;
Old:=fItems[pIndex];
dec(fCount);
FillChar(fItems[pIndex],SizeOf(T),#0);
if pIndex<>fCount then begin
System.Move(fItems[pIndex+1],fItems[pIndex],(fCount-pIndex)*SizeOf(T));
FillChar(fItems[fCount],SizeOf(T),#0);
end;
if fCount<(fAllocated shr 1) then begin
fAllocated:=fAllocated shr 1;
SetLength(fItems,fAllocated);
end;
result:=Old;
end;
function TpvObjectGenericList<T>.ExtractIndex(const pIndex:TpvSizeInt):T;
var Old:T;
begin
if (pIndex<0) or (pIndex>=fCount) then begin
raise ERangeError.Create('Out of index range');
end;
Old:=fItems[pIndex];
dec(fCount);
FillChar(fItems[pIndex],SizeOf(T),#0);
if pIndex<>fCount then begin
System.Move(fItems[pIndex+1],fItems[pIndex],(fCount-pIndex)*SizeOf(T));
FillChar(fItems[fCount],SizeOf(T),#0);
end;
if fCount<(fAllocated shr 1) then begin
fAllocated:=fAllocated shr 1;
SetLength(fItems,fAllocated);
end;
result:=Old;
end;
procedure TpvObjectGenericList<T>.Remove(const pItem:T);
var Index:TpvSizeInt;
begin
Index:=IndexOf(pItem);
if Index>=0 then begin
Delete(Index);
end;
end;
procedure TpvObjectGenericList<T>.Exchange(const pIndex,pWithIndex:TpvSizeInt);
var Temporary:T;
begin
if ((pIndex<0) or (pIndex>=fCount)) or ((pWithIndex<0) or (pWithIndex>=fCount)) then begin
raise ERangeError.Create('Out of index range');
end;
Temporary:=fItems[pIndex];
fItems[pIndex]:=fItems[pWithIndex];
fItems[pWithIndex]:=Temporary;
end;
function TpvObjectGenericList<T>.GetEnumerator:TpvObjectGenericList<T>.TValueEnumerator;
begin
result:=TValueEnumerator.Create(self);
end;
constructor TpvGenericList<T>.TValueEnumerator.Create(const aGenericList:TpvGenericList<T>);
begin
fGenericList:=aGenericList;
fIndex:=-1;
end;
function TpvGenericList<T>.TValueEnumerator.MoveNext:boolean;
begin
inc(fIndex);
result:=fIndex<fGenericList.fCount;
end;
function TpvGenericList<T>.TValueEnumerator.GetCurrent:T;
begin
result:=fGenericList.fItems[fIndex];
end;
constructor TpvGenericList<T>.Create;
begin
inherited Create;
fItems:=nil;
fCount:=0;
fAllocated:=0;
fSorted:=false;
end;
destructor TpvGenericList<T>.Destroy;
begin
SetLength(fItems,0);
fCount:=0;
fAllocated:=0;
fSorted:=false;
inherited Destroy;
end;
procedure TpvGenericList<T>.Clear;
begin
SetLength(fItems,0);
fCount:=0;
fAllocated:=0;
fSorted:=false;
end;
function TpvGenericList<T>.GetData:pointer;
begin
result:=@fItems[0];
end;
procedure TpvGenericList<T>.SetCount(const pNewCount:TpvSizeInt);
var Index,NewAllocated:TpvSizeInt;
Item:TpvPointer;
begin
if fCount<pNewCount then begin
NewAllocated:=RoundUpToPowerOfTwoSizeUInt(pNewCount);
if fAllocated<NewAllocated then begin
SetLength(fItems,NewAllocated);
FillChar(fItems[fAllocated],(NewAllocated-fAllocated)*SizeOf(T),#0);
fAllocated:=NewAllocated;
end;
for Index:=fCount to pNewCount-1 do begin
FillChar(fItems[Index],SizeOf(T),#0);
Initialize(fItems[Index]);
end;
fCount:=pNewCount;
end else if fCount>pNewCount then begin
for Index:=pNewCount to fCount-1 do begin
Finalize(fItems[Index]);
FillChar(fItems[Index],SizeOf(T),#0);
end;
fCount:=pNewCount;
if pNewCount<(fAllocated shr 2) then begin
if pNewCount=0 then begin
fItems:=nil;
fAllocated:=0;
end else begin
NewAllocated:=fAllocated shr 1;
SetLength(fItems,NewAllocated);
fAllocated:=NewAllocated;
end;
end;
end;
fSorted:=false;
end;
function TpvGenericList<T>.GetItemPointer(const pIndex:TpvSizeInt):TpvGenericList<T>.PT;
begin
if (pIndex<0) or (pIndex>=fCount) then begin
raise ERangeError.Create('Out of index range');
end;
result:=@fItems[pIndex];
end;
function TpvGenericList<T>.GetItem(const pIndex:TpvSizeInt):T;
begin
if (pIndex<0) or (pIndex>=fCount) then begin
raise ERangeError.Create('Out of index range');
end;
result:=fItems[pIndex];
end;
procedure TpvGenericList<T>.SetItem(const pIndex:TpvSizeInt;const pItem:T);
begin
if (pIndex<0) or (pIndex>=fCount) then begin
raise ERangeError.Create('Out of index range');
end;
fItems[pIndex]:=pItem;
end;
procedure TpvGenericList<T>.Assign(const pFrom:TpvGenericList<T>);
begin
fItems:=pFrom.fItems;
fCount:=pFrom.Count;
fAllocated:=pFrom.fAllocated;
fSorted:=pFrom.fSorted;
end;
function TpvGenericList<T>.Contains(const pItem:T):Boolean;
var Index,LowerIndexBound,UpperIndexBound,Difference:TpvInt32;
Comparer:IComparer<T>;
begin
Comparer:=TComparer<T>.Default;
result:=false;
if fSorted then begin
LowerIndexBound:=0;
UpperIndexBound:=fCount-1;
while LowerIndexBound<=UpperIndexBound do begin
Index:=LowerIndexBound+((UpperIndexBound-LowerIndexBound) shr 1);
Difference:=Comparer.Compare(fItems[Index],pItem);
if Difference=0 then begin
result:=true;
exit;
end else if Difference<0 then begin
LowerIndexBound:=Index+1;
end else begin
UpperIndexBound:=Index-1;
end;
end;
end else begin
for Index:=0 to fCount-1 do begin
if Comparer.Compare(fItems[Index],pItem)=0 then begin
result:=true;
exit;
end;
end;
end;
end;
function TpvGenericList<T>.IndexOf(const pItem:T):TpvSizeInt;
var Index,LowerIndexBound,UpperIndexBound,Difference:TpvInt32;
Comparer:IComparer<T>;
begin
Comparer:=TComparer<T>.Default;
result:=-1;
if fSorted then begin
LowerIndexBound:=0;
UpperIndexBound:=fCount-1;
while LowerIndexBound<=UpperIndexBound do begin
Index:=LowerIndexBound+((UpperIndexBound-LowerIndexBound) shr 1);
Difference:=Comparer.Compare(fItems[Index],pItem);
if Difference=0 then begin
result:=Index;
exit;
end else if Difference<0 then begin
LowerIndexBound:=Index+1;
end else begin
UpperIndexBound:=Index-1;
end;
end;
end else begin
for Index:=0 to fCount-1 do begin
if Comparer.Compare(fItems[Index],pItem)=0 then begin
result:=Index;
exit;
end;
end;
end;
end;
function TpvGenericList<T>.Add(const pItem:T):TpvSizeInt;
var Index,LowerIndexBound,UpperIndexBound,Difference:TpvInt32;
Comparer:IComparer<T>;
begin
Comparer:=TComparer<T>.Default;
if fSorted and (fCount>0) then begin
if Comparer.Compare(fItems[fCount-1],pItem)<0 then begin
result:=fCount;
end else if Comparer.Compare(pItem,fItems[0])<0 then begin
result:=0;
end else begin
LowerIndexBound:=0;
UpperIndexBound:=fCount-1;
while LowerIndexBound<=UpperIndexBound do begin
Index:=LowerIndexBound+((UpperIndexBound-LowerIndexBound) shr 1);
Difference:=Comparer.Compare(fItems[Index],pItem);
if Difference=0 then begin
LowerIndexBound:=Index;
break;
end else if Difference<0 then begin
LowerIndexBound:=Index+1;
end else begin
UpperIndexBound:=Index-1;
end;
end;
result:=LowerIndexBound;
end;
if result>=0 then begin
if result<fCount then begin
inc(fCount);
if length(fItems)<fCount then begin
SetLength(fItems,fCount*2);
end;
Move(fItems[result],fItems[result+1],(fCount-(result+1))*SizeOf(T));
FillChar(fItems[result],SizeOf(T),#0);
end else begin
fCount:=result+1;
if length(fItems)<fCount then begin
SetLength(fItems,fCount*2);
end;
end;
fItems[result]:=pItem;
end;
end else begin
result:=fCount;
inc(fCount);
if fAllocated<fCount then begin
fAllocated:=fCount+fCount;
SetLength(fItems,fAllocated);
end;
fItems[result]:=pItem;
end;
end;
procedure TpvGenericList<T>.Insert(const pIndex:TpvSizeInt;const pItem:T);
var OldCount:TpvSizeInt;
begin
if pIndex>=0 then begin
OldCount:=fCount;
if fCount<pIndex then begin
fCount:=pIndex+1;
end else begin
inc(fCount);
end;
if fAllocated<fCount then begin
fAllocated:=fCount shl 1;
SetLength(fItems,fAllocated);
end;
if OldCount<fCount then begin
FillChar(fItems[OldCount],(fCount-OldCount)*SizeOf(T),#0);
end;
if pIndex<OldCount then begin
System.Move(fItems[pIndex],fItems[pIndex+1],(OldCount-pIndex)*SizeOf(T));
FillChar(fItems[pIndex],SizeOf(T),#0);
end;
fItems[pIndex]:=pItem;
end;
fSorted:=false;
end;
procedure TpvGenericList<T>.Delete(const pIndex:TpvSizeInt);
begin
if (pIndex<0) or (pIndex>=fCount) then begin
raise ERangeError.Create('Out of index range');
end;
Finalize(fItems[pIndex]);
dec(fCount);
FillChar(fItems[pIndex],SizeOf(T),#0);
if pIndex<>fCount then begin
System.Move(fItems[pIndex+1],fItems[pIndex],(fCount-pIndex)*SizeOf(T));
FillChar(fItems[fCount],SizeOf(T),#0);
end;
if fCount<(fAllocated shr 1) then begin
fAllocated:=fAllocated shr 1;
SetLength(fItems,fAllocated);
end;
end;
procedure TpvGenericList<T>.Remove(const pItem:T);
var Index:TpvSizeInt;
begin
Index:=IndexOf(pItem);
if Index>=0 then begin
Delete(Index);
end;
end;
procedure TpvGenericList<T>.Exchange(const pIndex,pWithIndex:TpvSizeInt);
var Temporary:T;
begin
if ((pIndex<0) or (pIndex>=fCount)) or ((pWithIndex<0) or (pWithIndex>=fCount)) then begin
raise ERangeError.Create('Out of index range');
end;
Temporary:=fItems[pIndex];
fItems[pIndex]:=fItems[pWithIndex];
fItems[pWithIndex]:=Temporary;
fSorted:=false;
end;
function TpvGenericList<T>.GetEnumerator:TpvGenericList<T>.TValueEnumerator;
begin
result:=TValueEnumerator.Create(self);
end;
procedure TpvGenericList<T>.Sort;
begin
if not fSorted then begin
if fCount>1 then begin
TpvTypedSort<T>.IntroSort(@fItems[0],0,fCount-1);
end;
fSorted:=true;
end;
end;
procedure TpvGenericList<T>.Sort(const aCompareFunction:TpvTypedSort<T>.TpvTypedSortCompareFunction);
begin
if not fSorted then begin
if fCount>1 then begin
TpvTypedSort<T>.IntroSort(@fItems[0],0,fCount-1,aCompareFunction);
end;
fSorted:=true;
end;
end;
constructor TpvCustomHandleMap.Create(const pDataSize:TpvSizeUInt);
begin
inherited Create;
fMultipleReaderSingleWriterLock:=TPasMPMultipleReaderSingleWriterLock.Create;
fDataSize:=pDataSize;
fSize:=0;
fIndexCounter:=0;
fDenseIndex:=0;
fFreeIndex:=0;
fFreeArray:=nil;
{$ifdef Debug}
fGenerationArray:=nil;
{$endif}
fSparseToDenseArray:=nil;
fDenseToSparseArray:=nil;
fDataArray:=nil;
end;
destructor TpvCustomHandleMap.Destroy;
begin
Clear;
fMultipleReaderSingleWriterLock.Free;
inherited Destroy;
end;
procedure TpvCustomHandleMap.Lock;
begin
fMultipleReaderSingleWriterLock.AcquireWrite;
end;
procedure TpvCustomHandleMap.Unlock;
begin
fMultipleReaderSingleWriterLock.ReleaseWrite;
end;
procedure TpvCustomHandleMap.Clear;
var Index:TpvSizeUInt;
begin
fMultipleReaderSingleWriterLock.AcquireWrite;
try
Index:=0;
while Index<fSize do begin
FinalizeHandleData(TpvPointer(@fDataArray[Index*TpvSizeUInt(fDataSize)])^);
inc(Index);
end;
fSize:=0;
fIndexCounter:=0;
fDenseIndex:=0;
fFreeIndex:=0;
fFreeArray:=nil;
{$ifdef Debug}
fGenerationArray:=nil;
{$endif}
fSparseToDenseArray:=nil;
fDenseToSparseArray:=nil;
fDataArray:=nil;
finally
fMultipleReaderSingleWriterLock.ReleaseWrite;
end;
end;
procedure TpvCustomHandleMap.InitializeHandleData(var pData);
begin
end;
procedure TpvCustomHandleMap.FinalizeHandleData(var pData);
begin
FillChar(pData,fDataSize,#$00);
end;
procedure TpvCustomHandleMap.CopyHandleData(const pSource;out pDestination);
begin
Move(pSource,pDestination,fDataSize);
end;
procedure TpvCustomHandleMap.Defragment;
begin
end;
function TpvCustomHandleMap.AllocateHandle:TpvHandle;
var OldSize,NewSize:TpvSizeUInt;
begin
fMultipleReaderSingleWriterLock.AcquireWrite;
try
if fFreeIndex>0 then begin
dec(fFreeIndex);
result.Index:=fFreeArray[fFreeIndex];
{$ifdef Debug}
result.Generation:=fGenerationArray[result.Index] and $7fffffff;
{$endif}
end else begin
result.Index:=TPasMPInterlocked.Increment(fIndexCounter);
result.Generation:=0;
NewSize:=TpvSizeUInt(result.Index)+1;
{$ifdef Debug}
begin
OldSize:=length(fGenerationArray);
if OldSize<NewSize then begin
SetLength(fGenerationArray,NewSize*2);
FillChar(fGenerationArray[OldSize],TpvSizeUInt(NewSize-OldSize)*TpvSizeUInt(SizeOf(TpvUInt32)),#$ff);
end;
end;
{$endif}
begin
OldSize:=fSize;
if OldSize<NewSize then begin
fSize:=NewSize*2;
SetLength(fSparseToDenseArray,fSize);
SetLength(fDenseToSparseArray,fSize);
SetLength(fDataArray,fSize*fDataSize);
FillChar(fSparseToDenseArray[OldSize],TpvSizeUInt(NewSize-OldSize)*TpvSizeUInt(SizeOf(TpvUInt32)),#$ff);
FillChar(fDenseToSparseArray[OldSize],TpvSizeUInt(NewSize-OldSize)*TpvSizeUInt(SizeOf(TpvUInt32)),#$ff);
FillChar(fDataArray[OldSize*fDataSize],TpvSizeUInt(NewSize-OldSize)*TpvSizeUInt(fDataSize),#$00);
end;
end;
end;
{$ifdef Debug}
fGenerationArray[result.Index]:=result.Generation;
{$endif}
fSparseToDenseArray[result.Index]:=fDenseIndex;
fDenseToSparseArray[fDenseIndex]:=result.Index;
InitializeHandleData(TpvPointer(@fDataArray[fDenseIndex*TpvSizeUInt(fDataSize)])^);
inc(fDenseIndex);
finally
fMultipleReaderSingleWriterLock.ReleaseWrite;
end;
end;
procedure TpvCustomHandleMap.FreeHandle(const ppvHandle:TpvHandle);
var DenseIndex:TpvUInt32;
begin
fMultipleReaderSingleWriterLock.AcquireWrite;
try
{$ifdef Debug}
if (ppvHandle.Index<TpvInt64(length(fGenerationArray))) and
(ppvHandle.Generation=fGenerationArray[ppvHandle.Index]) then begin
fGenerationArray[ppvHandle.Index]:=(fGenerationArray[ppvHandle.Index]+1) or $80000000;
{$endif}
if TpvSizeUInt(length(fFreeArray))<=TpvSizeUInt(fFreeIndex) then begin
SetLength(fFreeArray,(TpvSizeUInt(fFreeIndex)+1)*2);
end;
fFreeArray[fFreeIndex]:=ppvHandle.Index;
inc(fFreeIndex);
dec(fDenseIndex);
DenseIndex:=fSparseToDenseArray[ppvHandle.Index];
if fDenseIndex<>DenseIndex then begin
Move(fDataArray[fDenseIndex*TpvSizeUInt(fDataSize)],fDataArray[DenseIndex*TpvSizeUInt(fDataSize)],fDataSize);
end;
FinalizeHandleData(TpvPointer(@fDataArray[fDenseIndex*TpvSizeUInt(fDataSize)])^);
fSparseToDenseArray[fDenseToSparseArray[DenseIndex]]:=DenseIndex;
{$ifdef Debug}
end else begin
raise EpvHandleMap.Create('Freeing non-used or already-freed handle');
end;
{$endif}
finally
fMultipleReaderSingleWriterLock.ReleaseWrite;
end;
end;
procedure TpvCustomHandleMap.GetHandleData(const ppvHandle:TpvHandle;out pData);
begin
fMultipleReaderSingleWriterLock.AcquireRead;
try
{$ifdef Debug}
if (ppvHandle.Index<TpvInt64(length(fGenerationArray))) and
(ppvHandle.Generation=fGenerationArray[ppvHandle.Index]) then begin
{$endif}
CopyHandleData(fDataArray[fSparseToDenseArray[ppvHandle.Index]*TpvSizeUInt(fDataSize)],pData);
{$ifdef Debug}
end else begin
raise EpvHandleMap.Create('Accessing non-used or already-freed handle');
end;
{$endif}
finally
fMultipleReaderSingleWriterLock.ReleaseRead;
end;
end;
procedure TpvCustomHandleMap.SetHandleData(const ppvHandle:TpvHandle;const pData);
begin
fMultipleReaderSingleWriterLock.AcquireRead;
try
{$ifdef Debug}
if (ppvHandle.Index<TpvInt64(length(fGenerationArray))) and
(ppvHandle.Generation=fGenerationArray[ppvHandle.Index]) then begin
{$endif}
CopyHandleData(pData,fDataArray[fSparseToDenseArray[ppvHandle.Index]*TpvSizeUInt(fDataSize)]);
{$ifdef Debug}
end else begin
raise EpvHandleMap.Create('Accessing non-used or already-freed handle');
end;
{$endif}
finally
fMultipleReaderSingleWriterLock.ReleaseRead;
end;
end;
function TpvCustomHandleMap.GetHandleDataPointer(const ppvHandle:TpvHandle):TpvPointer;
begin
{$ifdef Debug}
if (ppvHandle.Index<TpvInt64(length(fGenerationArray))) and
(ppvHandle.Generation=fGenerationArray[ppvHandle.Index]) then begin
{$endif}
result:=@fDataArray[fSparseToDenseArray[ppvHandle.Index]*TpvSizeUInt(fDataSize)];
{$ifdef Debug}
end else begin
result:=nil;
raise EpvHandleMap.Create('Accessing non-used or already-freed handle');
end;
{$endif}
end;
{$warnings off}
{$hints off}
constructor TpvHashMap<TpvHashMapKey,TpvHashMapValue>.TpvHashMapEntityEnumerator.Create(const aHashMap:TpvHashMap<TpvHashMapKey,TpvHashMapValue>);
begin
fHashMap:=aHashMap;
fIndex:=-1;
end;
function TpvHashMap<TpvHashMapKey,TpvHashMapValue>.TpvHashMapEntityEnumerator.GetCurrent:TpvHashMapEntity;
begin
result:=fHashMap.fEntities[fIndex];
end;
function TpvHashMap<TpvHashMapKey,TpvHashMapValue>.TpvHashMapEntityEnumerator.MoveNext:boolean;
begin
repeat
inc(fIndex);
if fIndex<fHashMap.fSize then begin
if (fHashMap.fEntityToCellIndex[fIndex]>=0) and (fHashMap.fCellToEntityIndex[fHashMap.fEntityToCellIndex[fIndex]]>=0) then begin
result:=true;
exit;
end;
end else begin
break;
end;
until false;
result:=false;
end;
constructor TpvHashMap<TpvHashMapKey,TpvHashMapValue>.TpvHashMapKeyEnumerator.Create(const aHashMap:TpvHashMap<TpvHashMapKey,TpvHashMapValue>);
begin
fHashMap:=aHashMap;
fIndex:=-1;
end;
function TpvHashMap<TpvHashMapKey,TpvHashMapValue>.TpvHashMapKeyEnumerator.GetCurrent:TpvHashMapKey;
begin
result:=fHashMap.fEntities[fIndex].Key;
end;
function TpvHashMap<TpvHashMapKey,TpvHashMapValue>.TpvHashMapKeyEnumerator.MoveNext:boolean;
begin
repeat
inc(fIndex);
if fIndex<fHashMap.fSize then begin
if (fHashMap.fEntityToCellIndex[fIndex]>=0) and (fHashMap.fCellToEntityIndex[fHashMap.fEntityToCellIndex[fIndex]]>=0) then begin
result:=true;
exit;
end;
end else begin
break;
end;
until false;
result:=false;
end;
constructor TpvHashMap<TpvHashMapKey,TpvHashMapValue>.TpvHashMapValueEnumerator.Create(const aHashMap:TpvHashMap<TpvHashMapKey,TpvHashMapValue>);
begin
fHashMap:=aHashMap;
fIndex:=-1;
end;
function TpvHashMap<TpvHashMapKey,TpvHashMapValue>.TpvHashMapValueEnumerator.GetCurrent:TpvHashMapValue;
begin
result:=fHashMap.fEntities[fIndex].Value;
end;
function TpvHashMap<TpvHashMapKey,TpvHashMapValue>.TpvHashMapValueEnumerator.MoveNext:boolean;
begin
repeat
inc(fIndex);
if fIndex<fHashMap.fSize then begin
if (fHashMap.fEntityToCellIndex[fIndex]>=0) and (fHashMap.fCellToEntityIndex[fHashMap.fEntityToCellIndex[fIndex]]>=0) then begin
result:=true;
exit;
end;
end else begin
break;
end;
until false;
result:=false;
end;
constructor TpvHashMap<TpvHashMapKey,TpvHashMapValue>.TpvHashMapEntitiesObject.Create(const aOwner:TpvHashMap<TpvHashMapKey,TpvHashMapValue>);
begin
inherited Create;
fOwner:=aOwner;
end;
function TpvHashMap<TpvHashMapKey,TpvHashMapValue>.TpvHashMapEntitiesObject.GetEnumerator:TpvHashMapEntityEnumerator;
begin
result:=TpvHashMapEntityEnumerator.Create(fOwner);
end;
constructor TpvHashMap<TpvHashMapKey,TpvHashMapValue>.TpvHashMapKeysObject.Create(const aOwner:TpvHashMap<TpvHashMapKey,TpvHashMapValue>);
begin
inherited Create;
fOwner:=aOwner;
end;
function TpvHashMap<TpvHashMapKey,TpvHashMapValue>.TpvHashMapKeysObject.GetEnumerator:TpvHashMapKeyEnumerator;
begin
result:=TpvHashMapKeyEnumerator.Create(fOwner);
end;
constructor TpvHashMap<TpvHashMapKey,TpvHashMapValue>.TpvHashMapValuesObject.Create(const aOwner:TpvHashMap<TpvHashMapKey,TpvHashMapValue>);
begin
inherited Create;
fOwner:=aOwner;
end;
function TpvHashMap<TpvHashMapKey,TpvHashMapValue>.TpvHashMapValuesObject.GetEnumerator:TpvHashMapValueEnumerator;
begin
result:=TpvHashMapValueEnumerator.Create(fOwner);
end;
function TpvHashMap<TpvHashMapKey,TpvHashMapValue>.TpvHashMapValuesObject.GetValue(const Key:TpvHashMapKey):TpvHashMapValue;
begin
result:=fOwner.GetValue(Key);
end;
procedure TpvHashMap<TpvHashMapKey,TpvHashMapValue>.TpvHashMapValuesObject.SetValue(const Key:TpvHashMapKey;const aValue:TpvHashMapValue);
begin
fOwner.SetValue(Key,aValue);
end;
constructor TpvHashMap<TpvHashMapKey,TpvHashMapValue>.Create(const DefaultValue:TpvHashMapValue);
begin
inherited Create;
fRealSize:=0;
fLogSize:=0;
fSize:=0;
fEntities:=nil;
fEntityToCellIndex:=nil;
fCellToEntityIndex:=nil;
fDefaultValue:=DefaultValue;
fCanShrink:=true;
fEntitiesObject:=TpvHashMapEntitiesObject.Create(self);
fKeysObject:=TpvHashMapKeysObject.Create(self);
fValuesObject:=TpvHashMapValuesObject.Create(self);
Resize;
end;
destructor TpvHashMap<TpvHashMapKey,TpvHashMapValue>.Destroy;
var Counter:TpvInt32;
begin
Clear;
for Counter:=0 to length(fEntities)-1 do begin
Finalize(fEntities[Counter].Key);
Finalize(fEntities[Counter].Value);
end;
SetLength(fEntities,0);
SetLength(fEntityToCellIndex,0);
SetLength(fCellToEntityIndex,0);
FreeAndNil(fEntitiesObject);
FreeAndNil(fKeysObject);
FreeAndNil(fValuesObject);
inherited Destroy;
end;
procedure TpvHashMap<TpvHashMapKey,TpvHashMapValue>.Clear;
var Counter:TpvInt32;
begin
for Counter:=0 to length(fEntities)-1 do begin
Finalize(fEntities[Counter].Key);
Finalize(fEntities[Counter].Value);
end;
if fCanShrink then begin
fRealSize:=0;
fLogSize:=0;
fSize:=0;
SetLength(fEntities,0);
SetLength(fEntityToCellIndex,0);
SetLength(fCellToEntityIndex,0);
Resize;
end else begin
for Counter:=0 to length(fCellToEntityIndex)-1 do begin
fCellToEntityIndex[Counter]:=ENT_EMPTY;
end;
for Counter:=0 to length(fEntityToCellIndex)-1 do begin
fEntityToCellIndex[Counter]:=CELL_EMPTY;
end;
end;
end;
function TpvHashMap<TpvHashMapKey,TpvHashMapValue>.HashData(const Data:TpvPointer;const DataLength:TpvUInt32):TpvUInt32;
// xxHash32
const PRIME32_1=TpvUInt32(2654435761);
PRIME32_2=TpvUInt32(2246822519);
PRIME32_3=TpvUInt32(3266489917);
PRIME32_4=TpvUInt32(668265263);
PRIME32_5=TpvUInt32(374761393);
Seed=TpvUInt32($1337c0d3);
v1Initialization=TpvUInt32(TpvUInt64(TpvUInt64(Seed)+TpvUInt64(PRIME32_1)+TpvUInt64(PRIME32_2)));
v2Initialization=TpvUInt32(TpvUInt64(TpvUInt64(Seed)+TpvUInt64(PRIME32_2)));
v3Initialization=TpvUInt32(TpvUInt64(TpvUInt64(Seed)+TpvUInt64(0)));
v4Initialization=TpvUInt32(TpvUInt64(TpvInt64(TpvInt64(Seed)-TpvInt64(PRIME32_1))));
HashInitialization=TpvUInt32(TpvUInt64(TpvUInt64(Seed)+TpvUInt64(PRIME32_5)));
var v1,v2,v3,v4:TpvUInt32;
p,e,Limit:PpvUInt8;
begin
p:=Data;
if DataLength>=16 then begin
v1:=v1Initialization;
v2:=v2Initialization;
v3:=v3Initialization;
v4:=v4Initialization;
e:=@PpvUInt8Array(Data)^[DataLength-16];
repeat
{$if defined(fpc) or declared(ROLDWord)}
v1:=ROLDWord(v1+(TpvUInt32(TpvPointer(p)^)*TpvUInt32(PRIME32_2)),13)*TpvUInt32(PRIME32_1);
{$else}
inc(v1,TpvUInt32(TpvPointer(p)^)*TpvUInt32(PRIME32_2));
v1:=((v1 shl 13) or (v1 shr 19))*TpvUInt32(PRIME32_1);
{$ifend}
inc(p,SizeOf(TpvUInt32));
{$if defined(fpc) or declared(ROLDWord)}
v2:=ROLDWord(v2+(TpvUInt32(TpvPointer(p)^)*TpvUInt32(PRIME32_2)),13)*TpvUInt32(PRIME32_1);
{$else}
inc(v2,TpvUInt32(TpvPointer(p)^)*TpvUInt32(PRIME32_2));
v2:=((v2 shl 13) or (v2 shr 19))*TpvUInt32(PRIME32_1);
{$ifend}
inc(p,SizeOf(TpvUInt32));
{$if defined(fpc) or declared(ROLDWord)}
v3:=ROLDWord(v3+(TpvUInt32(TpvPointer(p)^)*TpvUInt32(PRIME32_2)),13)*TpvUInt32(PRIME32_1);
{$else}
inc(v3,TpvUInt32(TpvPointer(p)^)*TpvUInt32(PRIME32_2));
v3:=((v3 shl 13) or (v3 shr 19))*TpvUInt32(PRIME32_1);
{$ifend}
inc(p,SizeOf(TpvUInt32));
{$if defined(fpc) or declared(ROLDWord)}
v4:=ROLDWord(v4+(TpvUInt32(TpvPointer(p)^)*TpvUInt32(PRIME32_2)),13)*TpvUInt32(PRIME32_1);
{$else}
inc(v4,TpvUInt32(TpvPointer(p)^)*TpvUInt32(PRIME32_2));
v4:=((v4 shl 13) or (v4 shr 19))*TpvUInt32(PRIME32_1);
{$ifend}
inc(p,SizeOf(TpvUInt32));
until {%H-}TpvPtrUInt(p)>{%H-}TpvPtrUInt(e);
{$if defined(fpc) or declared(ROLDWord)}
result:=ROLDWord(v1,1)+ROLDWord(v2,7)+ROLDWord(v3,12)+ROLDWord(v4,18);
{$else}
result:=((v1 shl 1) or (v1 shr 31))+
((v2 shl 7) or (v2 shr 25))+
((v3 shl 12) or (v3 shr 20))+
((v4 shl 18) or (v4 shr 14));
{$ifend}
end else begin
result:=HashInitialization;
end;
inc(result,DataLength);
e:=@PpvUInt8Array(Data)^[DataLength];
while ({%H-}TpvPtrUInt(p)+SizeOf(TpvUInt32))<={%H-}TpvPtrUInt(e) do begin
{$if defined(fpc) or declared(ROLDWord)}
result:=ROLDWord(result+(TpvUInt32(TpvPointer(p)^)*TpvUInt32(PRIME32_3)),17)*TpvUInt32(PRIME32_4);
{$else}
inc(result,TpvUInt32(TpvPointer(p)^)*TpvUInt32(PRIME32_3));
result:=((result shl 17) or (result shr 15))*TpvUInt32(PRIME32_4);
{$ifend}
inc(p,SizeOf(TpvUInt32));
end;
while {%H-}TpvPtrUInt(p)<{%H-}TpvPtrUInt(e) do begin
{$if defined(fpc) or declared(ROLDWord)}
result:=ROLDWord(result+(TpvUInt8(TpvPointer(p)^)*TpvUInt32(PRIME32_5)),11)*TpvUInt32(PRIME32_1);
{$else}
inc(result,TpvUInt8(TpvPointer(p)^)*TpvUInt32(PRIME32_5));
result:=((result shl 11) or (result shr 21))*TpvUInt32(PRIME32_1);
{$ifend}
inc(p,SizeOf(TpvUInt8));
end;
result:=(result xor (result shr 15))*TpvUInt32(PRIME32_2);
result:=(result xor (result shr 13))*TpvUInt32(PRIME32_3);
result:=result xor (result shr 16);
end;
function TpvHashMap<TpvHashMapKey,TpvHashMapValue>.HashKey(const Key:TpvHashMapKey):TpvUInt32;
var p:TpvUInt64;
begin
// We're hoping here that the compiler is here so smart, so that the compiler optimizes the
// unused if-branches away
{$ifndef ExtraStringHashMap}
if (SizeOf(TpvHashMapKey)=SizeOf(AnsiString)) and
(TypeInfo(TpvHashMapKey)=TypeInfo(AnsiString)) then begin
result:=HashData(PpvUInt8(@AnsiString(TpvPointer(@Key)^)[1]),length(AnsiString(TpvPointer(@Key)^))*SizeOf(AnsiChar));
end else if (SizeOf(TpvHashMapKey)=SizeOf(UTF8String)) and
(TypeInfo(TpvHashMapKey)=TypeInfo(UTF8String)) then begin
result:=HashData(PpvUInt8(@UTF8String(TpvPointer(@Key)^)[1]),length(UTF8String(TpvPointer(@Key)^))*SizeOf(AnsiChar));
end else if (SizeOf(TpvHashMapKey)=SizeOf(RawByteString)) and
(TypeInfo(TpvHashMapKey)=TypeInfo(RawByteString)) then begin
result:=HashData(PpvUInt8(@RawByteString(TpvPointer(@Key)^)[1]),length(RawByteString(TpvPointer(@Key)^))*SizeOf(AnsiChar));
end else if (SizeOf(TpvHashMapKey)=SizeOf(WideString)) and
(TypeInfo(TpvHashMapKey)=TypeInfo(WideString)) then begin
result:=HashData(PpvUInt8(@WideString(TpvPointer(@Key)^)[1]),length(WideString(TpvPointer(@Key)^))*SizeOf(WideChar));
end else if (SizeOf(TpvHashMapKey)=SizeOf(UnicodeString)) and
(TypeInfo(TpvHashMapKey)=TypeInfo(UnicodeString)) then begin
result:=HashData(PpvUInt8(@UnicodeString(TpvPointer(@Key)^)[1]),length(UnicodeString(TpvPointer(@Key)^))*SizeOf(UnicodeChar));
end else if (SizeOf(TpvHashMapKey)=SizeOf(String)) and
(TypeInfo(TpvHashMapKey)=TypeInfo(String)) then begin
result:=HashData(PpvUInt8(@String(TpvPointer(@Key)^)[1]),length(String(TpvPointer(@Key)^))*SizeOf(Char));
end else if TypeInfo(TpvHashMapKey)=TypeInfo(TpvUUID) then begin
result:=(TpvUUID(TpvPointer(@Key)^).DoubleWords[0]*73856093) xor
(TpvUUID(TpvPointer(@Key)^).DoubleWords[1]*19349669) xor
(TpvUUID(TpvPointer(@Key)^).DoubleWords[2]*83492791) xor
(TpvUUID(TpvPointer(@Key)^).DoubleWords[3]*50331653);
end else{$endif}begin
case SizeOf(TpvHashMapKey) of
SizeOf(UInt16):begin
// 16-bit big => use 16-bit integer-rehashing
result:=TpvUInt16(TpvPointer(@Key)^);
result:=(result or (((not result) and $ffff) shl 16));
dec(result,result shl 6);
result:=result xor (result shr 17);
dec(result,result shl 9);
result:=result xor (result shl 4);
dec(result,result shl 3);
result:=result xor (result shl 10);
result:=result xor (result shr 15);
end;
SizeOf(TpvUInt32):begin
// 32-bit big => use 32-bit integer-rehashing
result:=TpvUInt32(TpvPointer(@Key)^);
dec(result,result shl 6);
result:=result xor (result shr 17);
dec(result,result shl 9);
result:=result xor (result shl 4);
dec(result,result shl 3);
result:=result xor (result shl 10);
result:=result xor (result shr 15);
end;
SizeOf(TpvUInt64):begin
// 64-bit big => use 64-bit to 32-bit integer-rehashing
p:=TpvUInt64(TpvPointer(@Key)^);
p:=(not p)+(p shl 18); // p:=((p shl 18)-p-)1;
p:=p xor (p shr 31);
p:=p*21; // p:=(p+(p shl 2))+(p shl 4);
p:=p xor (p shr 11);
p:=p+(p shl 6);
result:=TpvUInt32(TpvPtrUInt(p xor (p shr 22)));
end;
else begin
result:=HashData(PpvUInt8(TpvPointer(@Key)),SizeOf(TpvHashMapKey));
end;
end;
end;
{$if defined(CPU386) or defined(CPUAMD64)}
// Special case: The hash value may be never zero
result:=result or (-TpvUInt32(ord(result=0) and 1));
{$else}
if result=0 then begin
// Special case: The hash value may be never zero
result:=$ffffffff;
end;
{$ifend}
end;
function TpvHashMap<TpvHashMapKey,TpvHashMapValue>.CompareKey(const KeyA,KeyB:TpvHashMapKey):boolean;
var Index:TpvInt32;
pA,pB:PpvUInt8Array;
begin
// We're hoping also here that the compiler is here so smart, so that the compiler optimizes the
// unused if-branches away
{$ifndef ExtraStringHashMap}
if (SizeOf(TpvHashMapKey)=SizeOf(AnsiString)) and
(TypeInfo(TpvHashMapKey)=TypeInfo(AnsiString)) then begin
result:=AnsiString(TpvPointer(@KeyA)^)=AnsiString(TpvPointer(@KeyB)^);
end else if (SizeOf(TpvHashMapKey)=SizeOf(UTF8String)) and
(TypeInfo(TpvHashMapKey)=TypeInfo(UTF8String)) then begin
result:=UTF8String(TpvPointer(@KeyA)^)=UTF8String(TpvPointer(@KeyB)^);
end else if (SizeOf(TpvHashMapKey)=SizeOf(RawByteString)) and
(TypeInfo(TpvHashMapKey)=TypeInfo(RawByteString)) then begin
result:=RawByteString(TpvPointer(@KeyA)^)=RawByteString(TpvPointer(@KeyB)^);
end else if (SizeOf(TpvHashMapKey)=SizeOf(WideString)) and
(TypeInfo(TpvHashMapKey)=TypeInfo(WideString)) then begin
result:=WideString(TpvPointer(@KeyA)^)=WideString(TpvPointer(@KeyB)^);
end else if (SizeOf(TpvHashMapKey)=SizeOf(UnicodeString)) and
(TypeInfo(TpvHashMapKey)=TypeInfo(UnicodeString)) then begin
result:=UnicodeString(TpvPointer(@KeyA)^)=UnicodeString(TpvPointer(@KeyB)^);
end else if (SizeOf(TpvHashMapKey)=SizeOf(String)) and
(TypeInfo(TpvHashMapKey)=TypeInfo(String)) then begin
result:=String(TpvPointer(@KeyA)^)=String(TpvPointer(@KeyB)^);
end else{$endif}begin
case SizeOf(TpvHashMapKey) of
SizeOf(TpvUInt8):begin
result:=UInt8(TpvPointer(@KeyA)^)=UInt8(TpvPointer(@KeyB)^);
end;
SizeOf(TpvUInt16):begin
result:=UInt16(TpvPointer(@KeyA)^)=UInt16(TpvPointer(@KeyB)^);
end;
SizeOf(TpvUInt32):begin
result:=TpvUInt32(TpvPointer(@KeyA)^)=TpvUInt32(TpvPointer(@KeyB)^);
end;
SizeOf(TpvUInt64):begin
result:=TpvUInt64(TpvPointer(@KeyA)^)=TpvUInt64(TpvPointer(@KeyB)^);
end;
{$ifdef fpc}
SizeOf(TpvHashMapUInt128):begin
result:=(TpvHashMapUInt128(TpvPointer(@KeyA)^)[0]=TpvHashMapUInt128(TpvPointer(@KeyB)^)[0]) and
(TpvHashMapUInt128(TpvPointer(@KeyA)^)[1]=TpvHashMapUInt128(TpvPointer(@KeyB)^)[1]);
end;
{$endif}
else begin
Index:=0;
pA:=@KeyA;
pB:=@KeyB;
while (Index+SizeOf(TpvUInt32))<SizeOf(TpvHashMapKey) do begin
if TpvUInt32(TpvPointer(@pA^[Index])^)<>TpvUInt32(TpvPointer(@pB^[Index])^) then begin
result:=false;
exit;
end;
inc(Index,SizeOf(TpvUInt32));
end;
while (Index+SizeOf(UInt8))<SizeOf(TpvHashMapKey) do begin
if UInt8(TpvPointer(@pA^[Index])^)<>UInt8(TpvPointer(@pB^[Index])^) then begin
result:=false;
exit;
end;
inc(Index,SizeOf(UInt8));
end;
result:=true;
end;
end;
end;
end;
function TpvHashMap<TpvHashMapKey,TpvHashMapValue>.FindCell(const Key:TpvHashMapKey):TpvUInt32;
var HashCode,Mask,Step:TpvUInt32;
Entity:TpvInt32;
begin
HashCode:=HashKey(Key);
Mask:=(2 shl fLogSize)-1;
Step:=((HashCode shl 1)+1) and Mask;
if fLogSize<>0 then begin
result:=HashCode shr (32-fLogSize);
end else begin
result:=0;
end;
repeat
Entity:=fCellToEntityIndex[result];
if (Entity=ENT_EMPTY) or ((Entity<>ENT_DELETED) and CompareKey(fEntities[Entity].Key,Key)) then begin
exit;
end;
result:=(result+Step) and Mask;
until false;
end;
procedure TpvHashMap<TpvHashMapKey,TpvHashMapValue>.Resize;
var NewLogSize,NewSize,Cell,Entity,Counter:TpvInt32;
OldEntities:TpvHashMapEntities;
OldCellToEntityIndex:TpvHashMapEntityIndices;
OldEntityToCellIndex:TpvHashMapEntityIndices;
begin
NewLogSize:=0;
NewSize:=fRealSize;
while NewSize<>0 do begin
NewSize:=NewSize shr 1;
inc(NewLogSize);
end;
if NewLogSize<1 then begin
NewLogSize:=1;
end;
fSize:=0;
fRealSize:=0;
fLogSize:=NewLogSize;
OldEntities:=fEntities;
OldCellToEntityIndex:=fCellToEntityIndex;
OldEntityToCellIndex:=fEntityToCellIndex;
fEntities:=nil;
fCellToEntityIndex:=nil;
fEntityToCellIndex:=nil;
SetLength(fEntities,2 shl fLogSize);
SetLength(fCellToEntityIndex,2 shl fLogSize);
SetLength(fEntityToCellIndex,2 shl fLogSize);
for Counter:=0 to length(fCellToEntityIndex)-1 do begin
fCellToEntityIndex[Counter]:=ENT_EMPTY;
end;
for Counter:=0 to length(fEntityToCellIndex)-1 do begin
fEntityToCellIndex[Counter]:=CELL_EMPTY;
end;
for Counter:=0 to length(OldEntityToCellIndex)-1 do begin
Cell:=OldEntityToCellIndex[Counter];
if Cell>=0 then begin
Entity:=OldCellToEntityIndex[Cell];
if Entity>=0 then begin
Add(OldEntities[Counter].Key,OldEntities[Counter].Value);
end;
end;
end;
for Counter:=0 to length(OldEntities)-1 do begin
Finalize(OldEntities[Counter].Key);
Finalize(OldEntities[Counter].Value);
end;
SetLength(OldEntities,0);
SetLength(OldCellToEntityIndex,0);
SetLength(OldEntityToCellIndex,0);
end;
function TpvHashMap<TpvHashMapKey,TpvHashMapValue>.Add(const Key:TpvHashMapKey;const Value:TpvHashMapValue):PpvHashMapEntity;
var Entity:TpvInt32;
Cell:TpvUInt32;
begin
result:=nil;
while fRealSize>=(1 shl fLogSize) do begin
Resize;
end;
Cell:=FindCell(Key);
Entity:=fCellToEntityIndex[Cell];
if Entity>=0 then begin
result:=@fEntities[Entity];
result^.Key:=Key;
result^.Value:=Value;
exit;
end;
Entity:=fSize;
inc(fSize);
if Entity<(2 shl fLogSize) then begin
fCellToEntityIndex[Cell]:=Entity;
fEntityToCellIndex[Entity]:=Cell;
inc(fRealSize);
result:=@fEntities[Entity];
result^.Key:=Key;
result^.Value:=Value;
end;
end;
function TpvHashMap<TpvHashMapKey,TpvHashMapValue>.Get(const Key:TpvHashMapKey;const CreateIfNotExist:boolean=false):PpvHashMapEntity;
var Entity:TpvInt32;
Cell:TpvUInt32;
Value:TpvHashMapValue;
begin
result:=nil;
Cell:=FindCell(Key);
Entity:=fCellToEntityIndex[Cell];
if Entity>=0 then begin
result:=@fEntities[Entity];
end else if CreateIfNotExist then begin
Initialize(Value);
result:=Add(Key,Value);
end;
end;
function TpvHashMap<TpvHashMapKey,TpvHashMapValue>.TryGet(const Key:TpvHashMapKey;out Value:TpvHashMapValue):boolean;
var Entity:TpvInt32;
begin
Entity:=fCellToEntityIndex[FindCell(Key)];
result:=Entity>=0;
if result then begin
Value:=fEntities[Entity].Value;
end else begin
Initialize(Value);
end;
end;
function TpvHashMap<TpvHashMapKey,TpvHashMapValue>.ExistKey(const Key:TpvHashMapKey):boolean;
begin
result:=fCellToEntityIndex[FindCell(Key)]>=0;
end;
function TpvHashMap<TpvHashMapKey,TpvHashMapValue>.Delete(const Key:TpvHashMapKey):boolean;
var Entity:TpvInt32;
Cell:TpvUInt32;
begin
result:=false;
Cell:=FindCell(Key);
Entity:=fCellToEntityIndex[Cell];
if Entity>=0 then begin
Finalize(fEntities[Entity].Key);
Finalize(fEntities[Entity].Value);
fEntityToCellIndex[Entity]:=CELL_DELETED;
fCellToEntityIndex[Cell]:=ENT_DELETED;
result:=true;
end;
end;
function TpvHashMap<TpvHashMapKey,TpvHashMapValue>.GetValue(const Key:TpvHashMapKey):TpvHashMapValue;
var Entity:TpvInt32;
Cell:TpvUInt32;
begin
Cell:=FindCell(Key);
Entity:=fCellToEntityIndex[Cell];
if Entity>=0 then begin
result:=fEntities[Entity].Value;
end else begin
result:=fDefaultValue;
end;
end;
procedure TpvHashMap<TpvHashMapKey,TpvHashMapValue>.SetValue(const Key:TpvHashMapKey;const Value:TpvHashMapValue);
begin
Add(Key,Value);
end;
{$ifdef ExtraStringHashMap}
constructor TpvStringHashMap<TpvHashMapValue>.TpvHashMapEntityEnumerator.Create(const aHashMap:TpvStringHashMap<TpvHashMapValue>);
begin
fHashMap:=aHashMap;
fIndex:=-1;
end;
function TpvStringHashMap<TpvHashMapValue>.TpvHashMapEntityEnumerator.GetCurrent:TpvHashMapEntity;
begin
result:=fHashMap.fEntities[fIndex];
end;
function TpvStringHashMap<TpvHashMapValue>.TpvHashMapEntityEnumerator.MoveNext:boolean;
begin
repeat
inc(fIndex);
if fIndex<fHashMap.fSize then begin
if (fHashMap.fEntityToCellIndex[fIndex]>=0) and (fHashMap.fCellToEntityIndex[fHashMap.fEntityToCellIndex[fIndex]]>=0) then begin
result:=true;
exit;
end;
end else begin
break;
end;
until false;
result:=false;
end;
constructor TpvStringHashMap<TpvHashMapValue>.TpvHashMapKeyEnumerator.Create(const aHashMap:TpvStringHashMap<TpvHashMapValue>);
begin
fHashMap:=aHashMap;
fIndex:=-1;
end;
function TpvStringHashMap<TpvHashMapValue>.TpvHashMapKeyEnumerator.GetCurrent:TpvHashMapKey;
begin
result:=fHashMap.fEntities[fIndex].Key;
end;
function TpvStringHashMap<TpvHashMapValue>.TpvHashMapKeyEnumerator.MoveNext:boolean;
begin
repeat
inc(fIndex);
if fIndex<fHashMap.fSize then begin
if (fHashMap.fEntityToCellIndex[fIndex]>=0) and (fHashMap.fCellToEntityIndex[fHashMap.fEntityToCellIndex[fIndex]]>=0) then begin
result:=true;
exit;
end;
end else begin
break;
end;
until false;
result:=false;
end;
constructor TpvStringHashMap<TpvHashMapValue>.TpvHashMapValueEnumerator.Create(const aHashMap:TpvStringHashMap<TpvHashMapValue>);
begin
fHashMap:=aHashMap;
fIndex:=-1;
end;
function TpvStringHashMap<TpvHashMapValue>.TpvHashMapValueEnumerator.GetCurrent:TpvHashMapValue;
begin
result:=fHashMap.fEntities[fIndex].Value;
end;
function TpvStringHashMap<TpvHashMapValue>.TpvHashMapValueEnumerator.MoveNext:boolean;
begin
repeat
inc(fIndex);
if fIndex<fHashMap.fSize then begin
if (fHashMap.fEntityToCellIndex[fIndex]>=0) and (fHashMap.fCellToEntityIndex[fHashMap.fEntityToCellIndex[fIndex]]>=0) then begin
result:=true;
exit;
end;
end else begin
break;
end;
until false;
result:=false;
end;
constructor TpvStringHashMap<TpvHashMapValue>.TpvHashMapEntitiesObject.Create(const aOwner:TpvStringHashMap<TpvHashMapValue>);
begin
inherited Create;
fOwner:=aOwner;
end;
function TpvStringHashMap<TpvHashMapValue>.TpvHashMapEntitiesObject.GetEnumerator:TpvHashMapEntityEnumerator;
begin
result:=TpvHashMapEntityEnumerator.Create(fOwner);
end;
constructor TpvStringHashMap<TpvHashMapValue>.TpvHashMapKeysObject.Create(const aOwner:TpvStringHashMap<TpvHashMapValue>);
begin
inherited Create;
fOwner:=aOwner;
end;
function TpvStringHashMap<TpvHashMapValue>.TpvHashMapKeysObject.GetEnumerator:TpvHashMapKeyEnumerator;
begin
result:=TpvHashMapKeyEnumerator.Create(fOwner);
end;
constructor TpvStringHashMap<TpvHashMapValue>.TpvHashMapValuesObject.Create(const aOwner:TpvStringHashMap<TpvHashMapValue>);
begin
inherited Create;
fOwner:=aOwner;
end;
function TpvStringHashMap<TpvHashMapValue>.TpvHashMapValuesObject.GetEnumerator:TpvHashMapValueEnumerator;
begin
result:=TpvHashMapValueEnumerator.Create(fOwner);
end;
function TpvStringHashMap<TpvHashMapValue>.TpvHashMapValuesObject.GetValue(const Key:TpvHashMapKey):TpvHashMapValue;
begin
result:=fOwner.GetValue(Key);
end;
procedure TpvStringHashMap<TpvHashMapValue>.TpvHashMapValuesObject.SetValue(const Key:TpvHashMapKey;const aValue:TpvHashMapValue);
begin
fOwner.SetValue(Key,aValue);
end;
constructor TpvStringHashMap<TpvHashMapValue>.Create(const DefaultValue:TpvHashMapValue);
begin
inherited Create;
fRealSize:=0;
fLogSize:=0;
fSize:=0;
fEntities:=nil;
fEntityToCellIndex:=nil;
fCellToEntityIndex:=nil;
fDefaultValue:=DefaultValue;
fCanShrink:=true;
fEntitiesObject:=TpvHashMapEntitiesObject.Create(self);
fKeysObject:=TpvHashMapKeysObject.Create(self);
fValuesObject:=TpvHashMapValuesObject.Create(self);
Resize;
end;
destructor TpvStringHashMap<TpvHashMapValue>.Destroy;
var Counter:TpvInt32;
begin
Clear;
for Counter:=0 to length(fEntities)-1 do begin
Finalize(fEntities[Counter].Key);
Finalize(fEntities[Counter].Value);
end;
SetLength(fEntities,0);
SetLength(fEntityToCellIndex,0);
SetLength(fCellToEntityIndex,0);
FreeAndNil(fEntitiesObject);
FreeAndNil(fKeysObject);
FreeAndNil(fValuesObject);
inherited Destroy;
end;
procedure TpvStringHashMap<TpvHashMapValue>.Clear;
var Counter:TpvInt32;
begin
for Counter:=0 to length(fEntities)-1 do begin
Finalize(fEntities[Counter].Key);
Finalize(fEntities[Counter].Value);
end;
if fCanShrink then begin
fRealSize:=0;
fLogSize:=0;
fSize:=0;
SetLength(fEntities,0);
SetLength(fEntityToCellIndex,0);
SetLength(fCellToEntityIndex,0);
Resize;
end else begin
for Counter:=0 to length(fCellToEntityIndex)-1 do begin
fCellToEntityIndex[Counter]:=ENT_EMPTY;
end;
for Counter:=0 to length(fEntityToCellIndex)-1 do begin
fEntityToCellIndex[Counter]:=CELL_EMPTY;
end;
end;
end;
function TpvStringHashMap<TpvHashMapValue>.HashKey(const Key:TpvHashMapKey):TpvUInt32;
// xxHash32
const PRIME32_1=TpvUInt32(2654435761);
PRIME32_2=TpvUInt32(2246822519);
PRIME32_3=TpvUInt32(3266489917);
PRIME32_4=TpvUInt32(668265263);
PRIME32_5=TpvUInt32(374761393);
Seed=TpvUInt32($1337c0d3);
v1Initialization=TpvUInt32(TpvUInt64(TpvUInt64(Seed)+TpvUInt64(PRIME32_1)+TpvUInt64(PRIME32_2)));
v2Initialization=TpvUInt32(TpvUInt64(TpvUInt64(Seed)+TpvUInt64(PRIME32_2)));
v3Initialization=TpvUInt32(TpvUInt64(TpvUInt64(Seed)+TpvUInt64(0)));
v4Initialization=TpvUInt32(TpvUInt64(TpvInt64(TpvInt64(Seed)-TpvInt64(PRIME32_1))));
HashInitialization=TpvUInt32(TpvUInt64(TpvUInt64(Seed)+TpvUInt64(PRIME32_5)));
var v1,v2,v3,v4,DataLength:TpvUInt32;
p,e,Limit:PpvUInt8;
begin
p:=TpvPointer(@Key[1]);
DataLength:=length(Key)*SizeOf(Key[1]);
if DataLength>=16 then begin
v1:=v1Initialization;
v2:=v2Initialization;
v3:=v3Initialization;
v4:=v4Initialization;
e:=@PpvUInt8Array(TpvPointer(@Key[1]))^[DataLength-16];
repeat
{$if defined(fpc) or declared(ROLDWord)}
v1:=ROLDWord(v1+(TpvUInt32(TpvPointer(p)^)*TpvUInt32(PRIME32_2)),13)*TpvUInt32(PRIME32_1);
{$else}
inc(v1,TpvUInt32(TpvPointer(p)^)*TpvUInt32(PRIME32_2));
v1:=((v1 shl 13) or (v1 shr 19))*TpvUInt32(PRIME32_1);
{$ifend}
inc(p,SizeOf(TpvUInt32));
{$if defined(fpc) or declared(ROLDWord)}
v2:=ROLDWord(v2+(TpvUInt32(TpvPointer(p)^)*TpvUInt32(PRIME32_2)),13)*TpvUInt32(PRIME32_1);
{$else}
inc(v2,TpvUInt32(TpvPointer(p)^)*TpvUInt32(PRIME32_2));
v2:=((v2 shl 13) or (v2 shr 19))*TpvUInt32(PRIME32_1);
{$ifend}
inc(p,SizeOf(TpvUInt32));
{$if defined(fpc) or declared(ROLDWord)}
v3:=ROLDWord(v3+(TpvUInt32(TpvPointer(p)^)*TpvUInt32(PRIME32_2)),13)*TpvUInt32(PRIME32_1);
{$else}
inc(v3,TpvUInt32(TpvPointer(p)^)*TpvUInt32(PRIME32_2));
v3:=((v3 shl 13) or (v3 shr 19))*TpvUInt32(PRIME32_1);
{$ifend}
inc(p,SizeOf(TpvUInt32));
{$if defined(fpc) or declared(ROLDWord)}
v4:=ROLDWord(v4+(TpvUInt32(TpvPointer(p)^)*TpvUInt32(PRIME32_2)),13)*TpvUInt32(PRIME32_1);
{$else}
inc(v4,TpvUInt32(TpvPointer(p)^)*TpvUInt32(PRIME32_2));
v4:=((v4 shl 13) or (v4 shr 19))*TpvUInt32(PRIME32_1);
{$ifend}
inc(p,SizeOf(TpvUInt32));
until {%H-}TpvPtrUInt(p)>{%H-}TpvPtrUInt(e);
{$if defined(fpc) or declared(ROLDWord)}
result:=ROLDWord(v1,1)+ROLDWord(v2,7)+ROLDWord(v3,12)+ROLDWord(v4,18);
{$else}
result:=((v1 shl 1) or (v1 shr 31))+
((v2 shl 7) or (v2 shr 25))+
((v3 shl 12) or (v3 shr 20))+
((v4 shl 18) or (v4 shr 14));
{$ifend}
end else begin
result:=HashInitialization;
end;
inc(result,DataLength);
e:=@PpvUInt8Array(TpvPointer(@Key[1]))^[DataLength];
while ({%H-}TpvPtrUInt(p)+SizeOf(TpvUInt32))<={%H-}TpvPtrUInt(e) do begin
{$if defined(fpc) or declared(ROLDWord)}
result:=ROLDWord(result+(TpvUInt32(TpvPointer(p)^)*TpvUInt32(PRIME32_3)),17)*TpvUInt32(PRIME32_4);
{$else}
inc(result,TpvUInt32(TpvPointer(p)^)*TpvUInt32(PRIME32_3));
result:=((result shl 17) or (result shr 15))*TpvUInt32(PRIME32_4);
{$ifend}
inc(p,SizeOf(TpvUInt32));
end;
while {%H-}TpvPtrUInt(p)<{%H-}TpvPtrUInt(e) do begin
{$if defined(fpc) or declared(ROLDWord)}
result:=ROLDWord(result+(TpvUInt8(TpvPointer(p)^)*TpvUInt32(PRIME32_5)),11)*TpvUInt32(PRIME32_1);
{$else}
inc(result,TpvUInt8(TpvPointer(p)^)*TpvUInt32(PRIME32_5));
result:=((result shl 11) or (result shr 21))*TpvUInt32(PRIME32_1);
{$ifend}
inc(p,SizeOf(TpvUInt8));
end;
result:=(result xor (result shr 15))*TpvUInt32(PRIME32_2);
result:=(result xor (result shr 13))*TpvUInt32(PRIME32_3);
result:=result xor (result shr 16);
{$if defined(CPU386) or defined(CPUAMD64)}
// Special case: The hash value may be never zero
result:=result or (-TpvUInt32(ord(result=0) and 1));
{$else}
if result=0 then begin
// Special case: The hash value may be never zero
result:=$ffffffff;
end;
{$ifend}
end;
function TpvStringHashMap<TpvHashMapValue>.FindCell(const Key:TpvHashMapKey):TpvUInt32;
var HashCode,Mask,Step:TpvUInt32;
Entity:TpvInt32;
begin
HashCode:=HashKey(Key);
Mask:=(2 shl fLogSize)-1;
Step:=((HashCode shl 1)+1) and Mask;
if fLogSize<>0 then begin
result:=HashCode shr (32-fLogSize);
end else begin
result:=0;
end;
repeat
Entity:=fCellToEntityIndex[result];
if (Entity=ENT_EMPTY) or ((Entity<>ENT_DELETED) and (fEntities[Entity].Key=Key)) then begin
exit;
end;
result:=(result+Step) and Mask;
until false;
end;
procedure TpvStringHashMap<TpvHashMapValue>.Resize;
var NewLogSize,NewSize,Cell,Entity,Counter:TpvInt32;
OldEntities:TpvHashMapEntities;
OldCellToEntityIndex:TpvHashMapEntityIndices;
OldEntityToCellIndex:TpvHashMapEntityIndices;
begin
NewLogSize:=0;
NewSize:=fRealSize;
while NewSize<>0 do begin
NewSize:=NewSize shr 1;
inc(NewLogSize);
end;
if NewLogSize<1 then begin
NewLogSize:=1;
end;
fSize:=0;
fRealSize:=0;
fLogSize:=NewLogSize;
OldEntities:=fEntities;
OldCellToEntityIndex:=fCellToEntityIndex;
OldEntityToCellIndex:=fEntityToCellIndex;
fEntities:=nil;
fCellToEntityIndex:=nil;
fEntityToCellIndex:=nil;
SetLength(fEntities,2 shl fLogSize);
SetLength(fCellToEntityIndex,2 shl fLogSize);
SetLength(fEntityToCellIndex,2 shl fLogSize);
for Counter:=0 to length(fCellToEntityIndex)-1 do begin
fCellToEntityIndex[Counter]:=ENT_EMPTY;
end;
for Counter:=0 to length(fEntityToCellIndex)-1 do begin
fEntityToCellIndex[Counter]:=CELL_EMPTY;
end;
for Counter:=0 to length(OldEntityToCellIndex)-1 do begin
Cell:=OldEntityToCellIndex[Counter];
if Cell>=0 then begin
Entity:=OldCellToEntityIndex[Cell];
if Entity>=0 then begin
Add(OldEntities[Counter].Key,OldEntities[Counter].Value);
end;
end;
end;
for Counter:=0 to length(OldEntities)-1 do begin
Finalize(OldEntities[Counter].Key);
Finalize(OldEntities[Counter].Value);
end;
SetLength(OldEntities,0);
SetLength(OldCellToEntityIndex,0);
SetLength(OldEntityToCellIndex,0);
end;
function TpvStringHashMap<TpvHashMapValue>.Add(const Key:TpvHashMapKey;const Value:TpvHashMapValue):PpvHashMapEntity;
var Entity:TpvInt32;
Cell:TpvUInt32;
begin
result:=nil;
while fRealSize>=(1 shl fLogSize) do begin
Resize;
end;
Cell:=FindCell(Key);
Entity:=fCellToEntityIndex[Cell];
if Entity>=0 then begin
result:=@fEntities[Entity];
result^.Key:=Key;
result^.Value:=Value;
exit;
end;
Entity:=fSize;
inc(fSize);
if Entity<(2 shl fLogSize) then begin
fCellToEntityIndex[Cell]:=Entity;
fEntityToCellIndex[Entity]:=Cell;
inc(fRealSize);
result:=@fEntities[Entity];
result^.Key:=Key;
result^.Value:=Value;
end;
end;
function TpvStringHashMap<TpvHashMapValue>.Get(const Key:TpvHashMapKey;const CreateIfNotExist:boolean=false):PpvHashMapEntity;
var Entity:TpvInt32;
Cell:TpvUInt32;
Value:TpvHashMapValue;
begin
result:=nil;
Cell:=FindCell(Key);
Entity:=fCellToEntityIndex[Cell];
if Entity>=0 then begin
result:=@fEntities[Entity];
end else if CreateIfNotExist then begin
Initialize(Value);
result:=Add(Key,Value);
end;
end;
function TpvStringHashMap<TpvHashMapValue>.TryGet(const Key:TpvHashMapKey;out Value:TpvHashMapValue):boolean;
var Entity:TpvInt32;
begin
Entity:=fCellToEntityIndex[FindCell(Key)];
result:=Entity>=0;
if result then begin
Value:=fEntities[Entity].Value;
end else begin
Initialize(Value);
end;
end;
function TpvStringHashMap<TpvHashMapValue>.ExistKey(const Key:TpvHashMapKey):boolean;
begin
result:=fCellToEntityIndex[FindCell(Key)]>=0;
end;
function TpvStringHashMap<TpvHashMapValue>.Delete(const Key:TpvHashMapKey):boolean;
var Entity:TpvInt32;
Cell:TpvUInt32;
begin
result:=false;
Cell:=FindCell(Key);
Entity:=fCellToEntityIndex[Cell];
if Entity>=0 then begin
Finalize(fEntities[Entity].Key);
Finalize(fEntities[Entity].Value);
fEntityToCellIndex[Entity]:=CELL_DELETED;
fCellToEntityIndex[Cell]:=ENT_DELETED;
result:=true;
end;
end;
function TpvStringHashMap<TpvHashMapValue>.GetValue(const Key:TpvHashMapKey):TpvHashMapValue;
var Entity:TpvInt32;
Cell:TpvUInt32;
begin
Cell:=FindCell(Key);
Entity:=fCellToEntityIndex[Cell];
if Entity>=0 then begin
result:=fEntities[Entity].Value;
end else begin
result:=fDefaultValue;
end;
end;
procedure TpvStringHashMap<TpvHashMapValue>.SetValue(const Key:TpvHashMapKey;const Value:TpvHashMapValue);
begin
Add(Key,Value);
end;
{$endif}
constructor TpvGenericSkipList<TKey,TValue>.TValueEnumerator.Create(const aSkipList:TpvGenericSkipList<TKey,TValue>);
begin
fSkipList:=aSkipList;
fPair:=fSkipList.fPairs;
end;
function TpvGenericSkipList<TKey,TValue>.TValueEnumerator.GetCurrent:TValue;
begin
result:=fPair.fValue;
end;
function TpvGenericSkipList<TKey,TValue>.TValueEnumerator.MoveNext:boolean;
begin
fPair:=fPair.fNext;
result:=fPair<>fSkipList.fPairs;
end;
constructor TpvGenericSkipList<TKey,TValue>.TPair.Create(const aSkipList:TpvGenericSkipList<TKey,TValue>;const aKey:TKey;const aValue:TValue);
begin
inherited Create;
fSkipList:=aSkipList;
fPrevious:=self;
fNext:=self;
fKey:=aKey;
fValue:=aValue;
end;
constructor TpvGenericSkipList<TKey,TValue>.TPair.CreateEmpty(const aSkipList:TpvGenericSkipList<TKey,TValue>);
begin
inherited Create;
fSkipList:=aSkipList;
fPrevious:=self;
fNext:=self;
Initialize(fKey);
Initialize(fValue);
end;
destructor TpvGenericSkipList<TKey,TValue>.TPair.Destroy;
begin
fPrevious.fNext:=fNext;
fNext.fPrevious:=fPrevious;
fPrevious:=self;
fNext:=self;
Finalize(fKey);
Finalize(fValue);
inherited Destroy;
end;
function TpvGenericSkipList<TKey,TValue>.TPair.GetPrevious:TPair;
begin
if fPrevious<>fSkipList.fPairs then begin
result:=fPrevious;
end else begin
result:=nil;
end;
end;
function TpvGenericSkipList<TKey,TValue>.TPair.GetNext:TPair;
begin
if fNext<>fSkipList.fPairs then begin
result:=fNext;
end else begin
result:=nil;
end;
end;
constructor TpvGenericSkipList<TKey,TValue>.TNode.Create(const aPrevious:TNode=nil;
const aNext:TNode=nil;
const aChildren:TNode=nil;
const aPair:TPair=nil);
begin
inherited Create;
fPrevious:=aPrevious;
fNext:=aNext;
fChildren:=aChildren;
fPair:=aPair;
end;
destructor TpvGenericSkipList<TKey,TValue>.TNode.Destroy;
begin
if assigned(fPair) and not assigned(fChildren) then begin
fPair.Free;
end;
inherited Destroy;
end;
constructor TpvGenericSkipList<TKey,TValue>.Create(const aDefaultValue:TValue);
begin
inherited Create;
fRandomGeneratorState.State:=0;
fRandomGeneratorState.Increment:=(TpvPtrUInt(TpvPointer(self)) shl 1) or 1;
GetRandomValue;
inc(fRandomGeneratorState.State,(TpvPtrUInt(TpvPointer(self)) shr 19) or (TpvPtrUInt(Pointer(self)) shl 13));
GetRandomValue;
fDefaultValue:=aDefaultValue;
fHead:=TNode.Create;
fPairs:=TPair.CreateEmpty(self);
end;
destructor TpvGenericSkipList<TKey,TValue>.Destroy;
var Node,TemporaryHead,CurrentNode,NextNode:TNode;
begin
Node:=fHead;
while assigned(Node) do begin
TemporaryHead:=Node;
Node:=Node.fChildren;
CurrentNode:=TemporaryHead;
while assigned(CurrentNode) do begin
NextNode:=CurrentNode.fNext;
CurrentNode.Free;
CurrentNode:=NextNode;
end;
end;
while fPairs.fNext<>fPairs do begin
fPairs.fNext.Free;
end;
fPairs.Free;
inherited Destroy;
end;
function TpvGenericSkipList<TKey,TValue>.GetRandomValue:TpvUInt32;
var RandomGeneratorState:TpvUInt64;
{$ifndef fpc}
RandomGeneratorXorShifted,RandomGeneratorRotation:TpvUInt32;
{$endif}
begin
RandomGeneratorState:=fRandomGeneratorState.State;
fRandomGeneratorState.State:=(RandomGeneratorState*TpvUInt64(6364136223846793005))+fRandomGeneratorState.Increment;
{$ifdef fpc}
result:=RORDWord(TpvUInt32(((RandomGeneratorState shr 18) xor RandomGeneratorState) shr 27),RandomGeneratorState shr 59);
{$else}
RandomGeneratorXorShifted:=((RandomGeneratorState shr 18) xor RandomGeneratorState) shr 27;
RandomGeneratorRotation:=RandomGeneratorState shr 59;
result:=(RandomGeneratorXorShifted shr RandomGeneratorRotation) or (RandomGeneratorXorShifted shl (32-RandomGeneratorRotation));
{$endif}
end;
function TpvGenericSkipList<TKey,TValue>.GetFirstPair:TPair;
begin
result:=fPairs.fNext;
if result=fPairs then begin
result:=nil;
end;
end;
function TpvGenericSkipList<TKey,TValue>.GetLastPair:TPair;
begin
result:=fPairs.fPrevious;
if result=fPairs then begin
result:=nil;
end;
end;
function TpvGenericSkipList<TKey,TValue>.FindPreviousNode(const aNode:TNode;const aKey:TKey):TNode;
var NextNode:TNode;
Comparer:IComparer<TKey>;
begin
Comparer:=TComparer<TKey>.Default;
result:=aNode;
while assigned(result) do begin
NextNode:=result.fNext;
if assigned(NextNode) and (Comparer.Compare(NextNode.fPair.fKey,aKey)<=0) then begin
result:=NextNode;
end else begin
break;
end;
end;
end;
function TpvGenericSkipList<TKey,TValue>.GetNearestPair(const aKey:TKey):TPair;
var CurrentNode,PreviousNode:TNode;
Pair,BestPair:TPair;
begin
BestPair:=fPairs.Next;
CurrentNode:=fHead;
while assigned(CurrentNode) do begin
PreviousNode:=FindPreviousNode(CurrentNode,aKey);
Pair:=PreviousNode.fPair;
if assigned(Pair) then begin
BestPair:=Pair;
end;
CurrentNode:=PreviousNode.fChildren;
end;
if assigned(BestPair) and (BestPair<>fPairs) then begin
result:=BestPair;
end else begin
result:=nil;
end;
end;
function TpvGenericSkipList<TKey,TValue>.GetNearestKey(const aKey:TKey):TKey;
var Pair:TPair;
begin
Pair:=GetNearestPair(aKey);
if assigned(Pair) then begin
result:=Pair.fKey;
end else begin
result:=aKey;
end;
end;
function TpvGenericSkipList<TKey,TValue>.GetNearestValue(const aKey:TKey):TValue;
var Pair:TPair;
begin
Pair:=GetNearestPair(aKey);
if assigned(Pair) then begin
result:=Pair.fValue;
end else begin
result:=fDefaultValue;
end;
end;
function TpvGenericSkipList<TKey,TValue>.Get(const aKey:TKey;out aValue:TValue):boolean;
var CurrentNode,PreviousNode:TNode;
Pair:TPair;
Comparer:IComparer<TKey>;
begin
Comparer:=TComparer<TKey>.Default;
CurrentNode:=fHead;
while assigned(CurrentNode) do begin
PreviousNode:=FindPreviousNode(CurrentNode,aKey);
Pair:=PreviousNode.fPair;
if assigned(Pair) and (Comparer.Compare(Pair.fKey,aKey)=0) then begin
aValue:=Pair.fValue;
result:=true;
exit;
end;
CurrentNode:=PreviousNode.fChildren;
end;
result:=false;
end;
function TpvGenericSkipList<TKey,TValue>.GetPair(const aKey:TKey):TPair;
var CurrentNode,PreviousNode:TNode;
Pair:TPair;
Comparer:IComparer<TKey>;
begin
Comparer:=TComparer<TKey>.Default;
CurrentNode:=fHead;
while assigned(CurrentNode) do begin
PreviousNode:=FindPreviousNode(CurrentNode,aKey);
Pair:=PreviousNode.fPair;
if assigned(Pair) and (Comparer.Compare(Pair.fKey,aKey)=0) then begin
result:=Pair;
exit;
end;
CurrentNode:=PreviousNode.fChildren;
end;
result:=nil;
end;
function TpvGenericSkipList<TKey,TValue>.GetValue(const aKey:TKey):TValue;
var CurrentNode,PreviousNode:TNode;
Pair:TPair;
Comparer:IComparer<TKey>;
begin
Comparer:=TComparer<TKey>.Default;
CurrentNode:=fHead;
while assigned(CurrentNode) do begin
PreviousNode:=FindPreviousNode(CurrentNode,aKey);
Pair:=PreviousNode.fPair;
if assigned(Pair) and (Comparer.Compare(Pair.fKey,aKey)=0) then begin
result:=Pair.fValue;
exit;
end;
CurrentNode:=PreviousNode.fChildren;
end;
result:=fDefaultValue;
end;
procedure TpvGenericSkipList<TKey,TValue>.SetValue(const aKey:TKey;const aValue:TValue);
var AllocatedPreviousNodes,CountPreviousNodes:TpvInt32;
RandomGeneratorValue:TpvUInt32;
CurrentNode,PreviousNode,NewNode:TNode;
Pair,OtherPair:TPair;
PreviousNodes:TNodeArray;
Comparer:IComparer<TKey>;
begin
Comparer:=TComparer<TKey>.Default;
PreviousNodes:=nil;
try
CurrentNode:=fHead;
AllocatedPreviousNodes:=0;
CountPreviousNodes:=0;
while assigned(CurrentNode) do begin
PreviousNode:=FindPreviousNode(CurrentNode,aKey);
if AllocatedPreviousNodes<=CountPreviousNodes then begin
AllocatedPreviousNodes:=(CountPreviousNodes+1) shl 1;
SetLength(PreviousNodes,AllocatedPreviousNodes);
end;
PreviousNodes[CountPreviousNodes]:=PreviousNode;
inc(CountPreviousNodes);
CurrentNode:=PreviousNode.fChildren;
end;
dec(CountPreviousNodes);
PreviousNode:=PreviousNodes[CountPreviousNodes];
if assigned(PreviousNode.fPair) and (Comparer.Compare(PreviousNode.fPair.fKey,aKey)=0) then begin
PreviousNode.fPair.fValue:=aValue;
end else begin
if assigned(PreviousNode.fPair) and (PreviousNode.fPair.fNext<>fPairs) then begin
OtherPair:=PreviousNode.fPair.fNext;
end else begin
if Comparer.Compare(fPairs.fPrevious.fKey,aKey)<0 then begin
OtherPair:=fPairs;
end else begin
OtherPair:=fPairs.fNext;
end;
end;
Pair:=TPair.Create(self,aKey,aValue);
Pair.fPrevious:=OtherPair.fPrevious;
Pair.fNext:=OtherPair;
Pair.fPrevious.fNext:=Pair;
OtherPair.fPrevious:=Pair;
NewNode:=TNode.Create(PreviousNode,PreviousNode.fNext,nil,Pair);
if assigned(PreviousNode.fNext) then begin
PreviousNode.fNext.fPrevious:=NewNode;
end;
PreviousNode.fNext:=NewNode;
RandomGeneratorValue:=0;
repeat
if RandomGeneratorValue=0 then begin
RandomGeneratorValue:=GetRandomValue;
end;
if (RandomGeneratorValue and 1)=0 then begin
break;
end else begin
RandomGeneratorValue:=RandomGeneratorValue shr 1;
if CountPreviousNodes>0 then begin
dec(CountPreviousNodes);
PreviousNode:=PreviousNodes[CountPreviousNodes];
end else begin
fHead:=TNode.Create(nil,nil,fHead);
PreviousNode:=fHead;
end;
NewNode:=TNode.Create(PreviousNode,PreviousNode.fNext,NewNode,Pair);
if assigned(PreviousNode.fNext) then begin
PreviousNode.fNext.fPrevious:=NewNode;
end;
PreviousNode.fNext:=NewNode;
end;
until false;
end;
finally
PreviousNodes:=nil;
end;
end;
procedure TpvGenericSkipList<TKey,TValue>.Delete(const aKey:TKey);
var CurrentNode,PreviousNode:TNode;
Pair:TPair;
Comparer:IComparer<TKey>;
begin
Comparer:=TComparer<TKey>.Default;
CurrentNode:=fHead;
while assigned(CurrentNode) do begin
PreviousNode:=FindPreviousNode(CurrentNode,aKey);
if assigned(PreviousNode) then begin
Pair:=PreviousNode.fPair;
if assigned(Pair) and (Comparer.Compare(Pair.fKey,aKey)=0) then begin
CurrentNode:=PreviousNode;
repeat
CurrentNode.fPrevious.fNext:=CurrentNode.fNext;
if assigned(CurrentNode.fNext) then begin
CurrentNode.fNext.fPrevious:=CurrentNode.fPrevious;
end;
PreviousNode:=CurrentNode;
CurrentNode:=CurrentNode.fChildren;
PreviousNode.Free;
until not assigned(CurrentNode);
break;
end;
end;
CurrentNode:=PreviousNode.fChildren;
end;
end;
function TpvGenericSkipList<TKey,TValue>.GetEnumerator:TValueEnumerator;
begin
result:=TValueEnumerator.Create(self);
end;
constructor TpvInt64SkipList<TValue>.TValueEnumerator.Create(const aSkipList:TpvInt64SkipList<TValue>);
begin
fSkipList:=aSkipList;
fPair:=fSkipList.fPairs;
end;
function TpvInt64SkipList<TValue>.TValueEnumerator.GetCurrent:TValue;
begin
result:=fPair.fValue;
end;
function TpvInt64SkipList<TValue>.TValueEnumerator.MoveNext:boolean;
begin
fPair:=fPair.fNext;
result:=fPair<>fSkipList.fPairs;
end;
constructor TpvInt64SkipList<TValue>.TPair.Create(const aSkipList:TpvInt64SkipList<TValue>;const aKey:TKey;const aValue:TValue);
begin
inherited Create;
fSkipList:=aSkipList;
fPrevious:=self;
fNext:=self;
fKey:=aKey;
fValue:=aValue;
end;
constructor TpvInt64SkipList<TValue>.TPair.CreateEmpty(const aSkipList:TpvInt64SkipList<TValue>);
begin
inherited Create;
fSkipList:=aSkipList;
fPrevious:=self;
fNext:=self;
Initialize(fKey);
Initialize(fValue);
end;
destructor TpvInt64SkipList<TValue>.TPair.Destroy;
begin
fPrevious.fNext:=fNext;
fNext.fPrevious:=fPrevious;
fPrevious:=self;
fNext:=self;
Finalize(fKey);
Finalize(fValue);
inherited Destroy;
end;
function TpvInt64SkipList<TValue>.TPair.GetPrevious:TPair;
begin
if fPrevious<>fSkipList.fPairs then begin
result:=fPrevious;
end else begin
result:=nil;
end;
end;
function TpvInt64SkipList<TValue>.TPair.GetNext:TPair;
begin
if fNext<>fSkipList.fPairs then begin
result:=fNext;
end else begin
result:=nil;
end;
end;
constructor TpvInt64SkipList<TValue>.TNode.Create(const aPrevious:TNode=nil;
const aNext:TNode=nil;
const aChildren:TNode=nil;
const aPair:TPair=nil);
begin
inherited Create;
fPrevious:=aPrevious;
fNext:=aNext;
fChildren:=aChildren;
fPair:=aPair;
end;
destructor TpvInt64SkipList<TValue>.TNode.Destroy;
begin
if assigned(fPair) and not assigned(fChildren) then begin
fPair.Free;
end;
inherited Destroy;
end;
constructor TpvInt64SkipList<TValue>.Create(const aDefaultValue:TValue);
begin
inherited Create;
fRandomGeneratorState.State:=0;
fRandomGeneratorState.Increment:=(TpvPtrUInt(TpvPointer(self)) shl 1) or 1;
GetRandomValue;
inc(fRandomGeneratorState.State,(TpvPtrUInt(TpvPointer(self)) shr 19) or (TpvPtrUInt(Pointer(self)) shl 13));
GetRandomValue;
fDefaultValue:=aDefaultValue;
fHead:=TNode.Create;
fPairs:=TPair.CreateEmpty(self);
end;
destructor TpvInt64SkipList<TValue>.Destroy;
var Node,TemporaryHead,CurrentNode,NextNode:TNode;
begin
Node:=fHead;
while assigned(Node) do begin
TemporaryHead:=Node;
Node:=Node.fChildren;
CurrentNode:=TemporaryHead;
while assigned(CurrentNode) do begin
NextNode:=CurrentNode.fNext;
CurrentNode.Free;
CurrentNode:=NextNode;
end;
end;
while fPairs.fNext<>fPairs do begin
fPairs.fNext.Free;
end;
fPairs.Free;
inherited Destroy;
end;
function TpvInt64SkipList<TValue>.GetRandomValue:TpvUInt32;
var RandomGeneratorState:TpvUInt64;
{$ifndef fpc}
RandomGeneratorXorShifted,RandomGeneratorRotation:TpvUInt32;
{$endif}
begin
RandomGeneratorState:=fRandomGeneratorState.State;
fRandomGeneratorState.State:=(RandomGeneratorState*TpvUInt64(6364136223846793005))+fRandomGeneratorState.Increment;
{$ifdef fpc}
result:=RORDWord(TpvUInt32(((RandomGeneratorState shr 18) xor RandomGeneratorState) shr 27),RandomGeneratorState shr 59);
{$else}
RandomGeneratorXorShifted:=((RandomGeneratorState shr 18) xor RandomGeneratorState) shr 27;
RandomGeneratorRotation:=RandomGeneratorState shr 59;
result:=(RandomGeneratorXorShifted shr RandomGeneratorRotation) or (RandomGeneratorXorShifted shl (32-RandomGeneratorRotation));
{$endif}
end;
function TpvInt64SkipList<TValue>.GetFirstPair:TPair;
begin
result:=fPairs.fNext;
if result=fPairs then begin
result:=nil;
end;
end;
function TpvInt64SkipList<TValue>.GetLastPair:TPair;
begin
result:=fPairs.fPrevious;
if result=fPairs then begin
result:=nil;
end;
end;
function TpvInt64SkipList<TValue>.FindPreviousNode(const aNode:TNode;const aKey:TKey):TNode;
var NextNode:TNode;
begin
result:=aNode;
while assigned(result) do begin
NextNode:=result.fNext;
if assigned(NextNode) and (NextNode.fPair.fKey<=aKey) then begin
result:=NextNode;
end else begin
break;
end;
end;
end;
function TpvInt64SkipList<TValue>.GetNearestPair(const aKey:TKey):TPair;
var CurrentNode,PreviousNode:TNode;
Pair,BestPair:TPair;
begin
BestPair:=fPairs.Next;
CurrentNode:=fHead;
while assigned(CurrentNode) do begin
PreviousNode:=FindPreviousNode(CurrentNode,aKey);
Pair:=PreviousNode.fPair;
if assigned(Pair) then begin
BestPair:=Pair;
end;
CurrentNode:=PreviousNode.fChildren;
end;
if assigned(BestPair) and (BestPair<>fPairs) then begin
result:=BestPair;
end else begin
result:=nil;
end;
end;
function TpvInt64SkipList<TValue>.GetNearestKey(const aKey:TKey):TKey;
var Pair:TPair;
begin
Pair:=GetNearestPair(aKey);
if assigned(Pair) then begin
result:=Pair.fKey;
end else begin
result:=aKey;
end;
end;
function TpvInt64SkipList<TValue>.GetNearestValue(const aKey:TKey):TValue;
var Pair:TPair;
begin
Pair:=GetNearestPair(aKey);
if assigned(Pair) then begin
result:=Pair.fValue;
end else begin
result:=fDefaultValue;
end;
end;
function TpvInt64SkipList<TValue>.Get(const aKey:TKey;out aValue:TValue):boolean;
var CurrentNode,PreviousNode:TNode;
Pair:TPair;
begin
CurrentNode:=fHead;
while assigned(CurrentNode) do begin
PreviousNode:=FindPreviousNode(CurrentNode,aKey);
Pair:=PreviousNode.fPair;
if assigned(Pair) and (Pair.fKey=aKey) then begin
aValue:=Pair.fValue;
result:=true;
exit;
end;
CurrentNode:=PreviousNode.fChildren;
end;
result:=false;
end;
function TpvInt64SkipList<TValue>.GetPair(const aKey:TKey):TPair;
var CurrentNode,PreviousNode:TNode;
Pair:TPair;
begin
CurrentNode:=fHead;
while assigned(CurrentNode) do begin
PreviousNode:=FindPreviousNode(CurrentNode,aKey);
Pair:=PreviousNode.fPair;
if assigned(Pair) and (Pair.fKey=aKey) then begin
result:=Pair;
exit;
end;
CurrentNode:=PreviousNode.fChildren;
end;
result:=nil;
end;
function TpvInt64SkipList<TValue>.GetValue(const aKey:TKey):TValue;
var CurrentNode,PreviousNode:TNode;
Pair:TPair;
begin
CurrentNode:=fHead;
while assigned(CurrentNode) do begin
PreviousNode:=FindPreviousNode(CurrentNode,aKey);
Pair:=PreviousNode.fPair;
if assigned(Pair) and (Pair.fKey=aKey) then begin
result:=Pair.fValue;
exit;
end;
CurrentNode:=PreviousNode.fChildren;
end;
result:=fDefaultValue;
end;
procedure TpvInt64SkipList<TValue>.SetValue(const aKey:TKey;const aValue:TValue);
var AllocatedPreviousNodes,CountPreviousNodes:TpvInt32;
RandomGeneratorValue:TpvUInt32;
CurrentNode,PreviousNode,NewNode:TNode;
Pair,OtherPair:TPair;
PreviousNodes:TNodeArray;
begin
PreviousNodes:=nil;
try
CurrentNode:=fHead;
AllocatedPreviousNodes:=0;
CountPreviousNodes:=0;
while assigned(CurrentNode) do begin
PreviousNode:=FindPreviousNode(CurrentNode,aKey);
if AllocatedPreviousNodes<=CountPreviousNodes then begin
AllocatedPreviousNodes:=(CountPreviousNodes+1) shl 1;
SetLength(PreviousNodes,AllocatedPreviousNodes);
end;
PreviousNodes[CountPreviousNodes]:=PreviousNode;
inc(CountPreviousNodes);
CurrentNode:=PreviousNode.fChildren;
end;
dec(CountPreviousNodes);
PreviousNode:=PreviousNodes[CountPreviousNodes];
if assigned(PreviousNode.fPair) and (PreviousNode.fPair.fKey=aKey) then begin
PreviousNode.fPair.fValue:=aValue;
end else begin
if assigned(PreviousNode.fPair) and (PreviousNode.fPair.fNext<>fPairs) then begin
OtherPair:=PreviousNode.fPair.fNext;
end else begin
if fPairs.fPrevious.fKey<aKey then begin
OtherPair:=fPairs;
end else begin
OtherPair:=fPairs.fNext;
end;
end;
Pair:=TPair.Create(self,aKey,aValue);
Pair.fPrevious:=OtherPair.fPrevious;
Pair.fNext:=OtherPair;
Pair.fPrevious.fNext:=Pair;
OtherPair.fPrevious:=Pair;
NewNode:=TNode.Create(PreviousNode,PreviousNode.fNext,nil,Pair);
if assigned(PreviousNode.fNext) then begin
PreviousNode.fNext.fPrevious:=NewNode;
end;
PreviousNode.fNext:=NewNode;
RandomGeneratorValue:=0;
repeat
if RandomGeneratorValue=0 then begin
RandomGeneratorValue:=GetRandomValue;
end;
if (RandomGeneratorValue and 1)=0 then begin
break;
end else begin
RandomGeneratorValue:=RandomGeneratorValue shr 1;
if CountPreviousNodes>0 then begin
dec(CountPreviousNodes);
PreviousNode:=PreviousNodes[CountPreviousNodes];
end else begin
fHead:=TNode.Create(nil,nil,fHead);
PreviousNode:=fHead;
end;
NewNode:=TNode.Create(PreviousNode,PreviousNode.fNext,NewNode,Pair);
if assigned(PreviousNode.fNext) then begin
PreviousNode.fNext.fPrevious:=NewNode;
end;
PreviousNode.fNext:=NewNode;
end;
until false;
end;
finally
PreviousNodes:=nil;
end;
end;
procedure TpvInt64SkipList<TValue>.Delete(const aKey:TKey);
var CurrentNode,PreviousNode:TNode;
Pair:TPair;
begin
CurrentNode:=fHead;
while assigned(CurrentNode) do begin
PreviousNode:=FindPreviousNode(CurrentNode,aKey);
if assigned(PreviousNode) then begin
Pair:=PreviousNode.fPair;
if assigned(Pair) and (Pair.fKey=aKey) then begin
CurrentNode:=PreviousNode;
repeat
CurrentNode.fPrevious.fNext:=CurrentNode.fNext;
if assigned(CurrentNode.fNext) then begin
CurrentNode.fNext.fPrevious:=CurrentNode.fPrevious;
end;
PreviousNode:=CurrentNode;
CurrentNode:=CurrentNode.fChildren;
PreviousNode.Free;
until not assigned(CurrentNode);
break;
end;
end;
CurrentNode:=PreviousNode.fChildren;
end;
end;
function TpvInt64SkipList<TValue>.GetEnumerator:TValueEnumerator;
begin
result:=TValueEnumerator.Create(self);
end;
end.
|
unit uWash;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Menus, uOperator, uLogin, uSelectUser, uData, ComCtrls, db, AppEvnts;
type
TfrmMain = class(TForm)
pgView: TPageControl;
tabOperator: TTabSheet;
tabDirector: TTabSheet;
tabAdmin: TTabSheet;
tabReports: TTabSheet;
StatusBar1: TStatusBar;
ApplicationEvents: TApplicationEvents;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure ApplicationEventsException(Sender: TObject; E: Exception);
private
{ Private declarations }
frmOperator: TfrmOperator;
frmLogin: TfrmLogin;
frmSelectUser: TfrmSelectUser;
function getUserInfo(name: string): TField;
function getOperatorInfo(name: string): TField;
public
{ Public declarations }
property UserInfo[name:string]:TField read getUserInfo;
property OperatorInfo[name:string]:TField read getOperatorInfo;
function Login(exitOnCancel: boolean): TmodalResult;
function SelectUser(exitOnCancel: boolean): TmodalResult;
procedure LoadFormByUserType(ut_id: integer);
end;
var
frmMain: TfrmMain;
implementation
uses uAccessRightRule;
{$R *.dfm}
procedure TfrmMain.ApplicationEventsException(Sender: TObject; E: Exception);
begin
ShowMessage(Sender.UnitName + ' ' + Sender.ClassName + #13#10 + E.Message)
end;
procedure TfrmMain.FormCreate(Sender: TObject);
var dbName: string;
begin
dbName := ParamStr(1);
if not data.ConnectDB(dbName) then
begin
messageBox(handle, PWideChar('Ошибка подключения к базе ' +
dbName), 'Ошибка', MB_OK or MB_ICONERROR);
Application.Terminate;
exit;
end;
StatusBar1.Panels[0].Text := dbName;
data.OpenDictionary;
frmLogin := TfrmLogin.Create(self);
Login(true);
frmSelectUser := TfrmSelectUser.Create(self);
SelectUser(true);
SetWindowAccessState(UserInfo['UT_ID'].AsInteger, self);
LoadFormByUserType(UserInfo['UT_ID'].AsInteger);
end;
procedure TfrmMain.FormDestroy(Sender: TObject);
begin
freeAndNil(frmLogin);
freeAndNil(frmSelectUser);
freeAndNil(frmOperator);
end;
function TfrmMain.getOperatorInfo(name: string): TField;
begin
result := frmSelectUser.cdsOperator.FieldByName(name);
end;
function TfrmMain.getUserInfo(name: string): TField;
begin
result := frmSelectUser.cdsUser.FieldByName(name);
end;
function TfrmMain.Login(exitOnCancel: boolean): TmodalResult;
begin
frmLogin.txtUserPassword.Text := '';
result := mrNone;
while result <> mrOK do
begin
result := frmLogin.ShowModal;
case result of
mrCancel: if exitOnCancel then
begin
Application.Terminate;
abort;
end
else begin
break
end;
mrNo: messageBox(handle, 'Неверный логин/паоль.', 'Ошибка', MB_OK or MB_ICONERROR);
end;
end;
end;
function TfrmMain.SelectUser(exitOnCancel: boolean): TmodalResult;
begin
result := mrNone;
while result <> mrOK do
begin
result := frmSelectUser.ShowModal;
case result of
mrCancel: if exitOnCancel then
begin
Application.Terminate;
abort;
end
else begin
break
end;
end;
end;
end;
procedure TfrmMain.LoadFormByUserType(ut_id: integer);
begin
case ut_id of
1: ;
2: if not Assigned(frmOperator) then
begin
frmOperator := TfrmOperator.Create(self);
frmOperator.Dock(tabOperator, tabOperator.ClientRect);
self.Caption := frmOperator.Caption + ' ' +
OperatorInfo['OP_NAME'].AsString;
frmOperator.ShowOperatorWashList(OperatorInfo['OP_ID'].AsInteger);
end;
end;
end;
end.
|
{
ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi
Copyright (c) 2016, Isaque Pinheiro
All rights reserved.
GNU Lesser General Public License
Versão 3, 29 de junho de 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
A todos é permitido copiar e distribuir cópias deste documento de
licença, mas mudá-lo não é permitido.
Esta versão da GNU Lesser General Public License incorpora
os termos e condições da versão 3 da GNU General Public License
Licença, complementado pelas permissões adicionais listadas no
arquivo LICENSE na pasta principal.
}
{ @abstract(ORMBr Framework.)
@created(20 Jul 2016)
@author(Isaque Pinheiro <isaquepsp@gmail.com>)
@author(Skype : ispinheiro)
ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi.
}
{$INCLUDE ..\ormbr.inc}
unit ormbr.types.blob;
interface
uses
DB,
Classes,
SysUtils,
{$IFDEF HAS_FMX}
FMX.Graphics,
{$ELSE}
// Delphi > 2010 adicionar em:
// Option->Delphi Compiler->Unit scope names, "Vcl", "Vcl.Imaging"
// FMX.Graphics,
//Graphics,
// GIFImg,
// JPEG,
// PngImage,
// pnglang,
{$IF COMPILERVERSION > 23}
// AnsiStrings,
{$IFEND}
{$ENDIF}
// CodeBase64 e DecodeBase64
{$IFDEF HAS_NET_ENCODING}
System.NetEncoding,
{$ELSE IFDEF HAS_SOAP_ENCODING}
Soap.EncdDecd,
{$ELSE}
encddecd,
{$IFEND}
ZLib;
type
TBlob = record
private
FBase64String: String;
FBase64Bytes: TBytes;
FBlobField: TBlobField;
function StreamToByteArray(AStream: TStream): TBytes;
{$IFNDEF HAS_FMX}
{ function FindGraphicClass(const ABuffer; const ABufferSize: Int64;
out AGraphicClass: TGraphicClass): Boolean; overload;
function FindGraphicClass(AStream: TStream;
out AGraphicClass: TGraphicClass): Boolean; overload;}
{$ENDIF}
procedure CompressStream(ASource, ATarget: TStream);
procedure DecompressStream(ASource, ATarget: TStream);
procedure BuildBlobFieldToStream(const ACompression: Boolean = False);
function GetEncodeBase64: String;
function GetDecodeBase64(const Value: String): Boolean;
public
procedure SetBlobField(const Value: TBlobField; const ACompression: Boolean = False);
procedure SetBytes(const Value: TBytes);
procedure LoadFromFile(const AFileName: string; const ACompression: Boolean = False);
procedure SaveToFile(const FileName: string);
{$IFNDEF HAS_FMX}
//procedure ToPicture(APicture: TPicture; const ACompression: Boolean = False);
{$ENDIF}
// procedure ToBitmap(ABitmap: TBitmap; const ACompression: Boolean = False);
function ToBytes: TBytes;
function ToBytesString: string; overload;
function ToStringBytes(const AString: string): Boolean; overload;
function ToString: String;
function ToSize: Integer;
end;
implementation
const
MinGraphicSize = 44;
{ TBlob }
procedure TBlob.SetBlobField(const Value: TBlobField; const ACompression: Boolean);
begin
if Value.IsBlob then
begin
FBlobField := Value;
// Gera Stream do BlobField e armazena em var interna
BuildBlobFieldToStream(ACompression);
end
else
raise Exception.Create(Format('Column [%s] must have blob value', [Value.FieldName]));
end;
procedure TBlob.SetBytes(const Value: TBytes);
begin
FBase64Bytes := Value;
// Codifica os Bytes em string
FBase64String := ToBytesString;
end;
function TBlob.ToBytesString: string;
begin
Result := GetEncodeBase64;
end;
function TBlob.ToString: String;
begin
Result := FBase64String;
end;
function TBlob.ToStringBytes(const AString: string): Boolean;
begin
Result := GetDecodeBase64(AString);
end;
procedure TBlob.BuildBlobFieldToStream(const ACompression: Boolean);
var
LSourceStream: TMemoryStream;
LTargetStream: TMemoryStream;
begin
if not Assigned(FBlobField) then
Exit;
LSourceStream := TMemoryStream.Create;
try
TBlobField(FBlobField).SaveToStream(LSourceStream);
LSourceStream.Position := 0;
if ACompression then
begin
LTargetStream := TMemoryStream.Create;
try
CompressStream(LSourceStream, LTargetStream);
FBase64Bytes := StreamToByteArray(LTargetStream);
finally
LTargetStream.Free;
end;
end
else
FBase64Bytes := StreamToByteArray(LSourceStream);
FBase64String := ToBytesString;
finally
LSourceStream.Free;
end;
end;
function TBlob.StreamToByteArray(AStream: TStream): TBytes;
begin
if Assigned(AStream) then
begin
AStream.Position := 0;
SetLength(Result, AStream.Size);
AStream.Read(Pointer(Result)^, AStream.Size);
end
else
SetLength(Result, 0);
end;
{$IFNDEF HAS_FMX}
{procedure TBlob.ToPicture(APicture: TPicture; const ACompression: Boolean);
var
LGraphic: TGraphic;
LSourceStream: TMemoryStream;
LTargetStream: TMemoryStream;
LGraphicClass: TGraphicClass;
begin
LGraphic := nil;
LSourceStream := TMemoryStream.Create;
try
if Length(FBase64Bytes) = 0 then
begin
APicture.Assign(nil);
Exit;
end;
LSourceStream.Write(FBase64Bytes, ToSize);
if ACompression then
begin
LTargetStream := TMemoryStream.Create;
try
DecompressStream(LSourceStream, LTargetStream);
if not FindGraphicClass(LTargetStream.Memory^, LTargetStream.Size, LGraphicClass) then
raise EInvalidGraphic.Create('Invalid image');
LGraphic := LGraphicClass.Create;
LTargetStream.Position := 0;
LGraphic.LoadFromStream(LTargetStream);
finally
LTargetStream.Free;
end;
end
else
begin
if not FindGraphicClass(LSourceStream.Memory^, LSourceStream.Size, LGraphicClass) then
raise EInvalidGraphic.Create('Invalid image');
LGraphic := LGraphicClass.Create;
LSourceStream.Position := 0;
LGraphic.LoadFromStream(LSourceStream);
end;
APicture.Assign(LGraphic);
finally
LSourceStream.Free;
LGraphic.Free;
end;
end; }
{$ENDIF}
function TBlob.ToSize: Integer;
begin
Result := Length(FBase64Bytes);
end;
{$IFNDEF HAS_FMX}
{function TBlob.FindGraphicClass(const ABuffer; const ABufferSize: Int64;
out AGraphicClass: TGraphicClass): Boolean;
var
LLongWords: Array[Byte] of LongWord absolute ABuffer;
LWords: Array[Byte] of Word absolute ABuffer;
begin
AGraphicClass := nil;
Result := False;
if ABufferSize < MinGraphicSize then
Exit;
case LWords[0] of
$4D42: AGraphicClass := TBitmap;
$D8FF: AGraphicClass := TJPEGImage;
$4949: if LWords[1] = $002A then AGraphicClass := TWicImage; //i.e., TIFF
$4D4D: if LWords[1] = $2A00 then AGraphicClass := TWicImage; //i.e., TIFF
else
if Int64(ABuffer) = $A1A0A0D474E5089 then
AGraphicClass := TPNGImage
else
if LLongWords[0] = $9AC6CDD7 then
AGraphicClass := TMetafile
else
if (LLongWords[0] = 1) and (LLongWords[10] = $464D4520) then
AGraphicClass := TMetafile
else
{$if CompilerVersion > 23
if AnsiStrings.AnsiStrLComp(PAnsiChar(@ABuffer), PAnsiChar('GIF'), 3) = 0 then
{$else
if AnsiStrLComp(PAnsiChar(@ABuffer), PAnsiChar('GIF'), 3) = 0 then
{$ifend
AGraphicClass := TGIFImage
else
if LWords[1] = 1 then
AGraphicClass := TIcon;
end;
Result := (AGraphicClass <> nil);
end;
function TBlob.FindGraphicClass(AStream: TStream;
out AGraphicClass: TGraphicClass): Boolean;
var
LBuffer: PByte;
LCurPos: Int64;
LBytesRead: Integer;
begin
if AStream is TCustomMemoryStream then
begin
LBuffer := TCustomMemoryStream(AStream).Memory;
LCurPos := AStream.Position;
Inc(LBuffer, LCurPos);
Result := FindGraphicClass(LBuffer^, AStream.Size - LCurPos, AGraphicClass);
Exit;
end;
GetMem(LBuffer, MinGraphicSize);
try
LBytesRead := AStream.Read(LBuffer^, MinGraphicSize);
AStream.Seek(-LBytesRead, soCurrent);
Result := FindGraphicClass(LBuffer^, LBytesRead, AGraphicClass);
finally
FreeMem(LBuffer);
end;
end; }
{$ENDIF}
procedure TBlob.LoadFromFile(const AFileName: string;
const ACompression: Boolean = False);
var
LSourceStream: TMemoryStream;
LTargetStream: TMemoryStream;
begin
LSourceStream := TMemoryStream.Create;
try
LSourceStream.LoadFromFile(AFileName);
LSourceStream.Position := 0;
if ACompression then
begin
LTargetStream := TMemoryStream.Create;
try
CompressStream(LSourceStream, LTargetStream);
FBase64Bytes := StreamToByteArray(LTargetStream);
finally
LTargetStream.Free;
end
end
else
FBase64Bytes := StreamToByteArray(LSourceStream);
FBase64String := ToBytesString;
finally
LSourceStream.Free;
end
end;
{procedure TBlob.ToBitmap(ABitmap: TBitmap; const ACompression: Boolean);
var
LSourceStream: TMemoryStream;
LTargetStream: TMemoryStream;
begin
LSourceStream := TMemoryStream.Create;
try
if Length(FBase64Bytes) = 0 then
begin
ABitmap.Assign(nil);
Exit;
end;
LSourceStream.Write(FBase64Bytes, ToSize);
if ACompression then
begin
LTargetStream := TMemoryStream.Create;
try
DecompressStream(LSourceStream, LTargetStream);
LTargetStream.Position := 0;
ABitmap.LoadFromStream(LTargetStream);
finally
LTargetStream.Free;
end;
end
else
begin
LSourceStream.Position := 0;
ABitmap.LoadFromStream(LSourceStream);
end;
finally
LSourceStream.Free;
end;
end; }
function TBlob.ToBytes: TBytes;
begin
Result := FBase64Bytes;
end;
procedure TBlob.SaveToFile(const FileName: string);
var
LStream: TBytesStream;
begin
LStream := TBytesStream.Create(FBase64Bytes);
try
LStream.SaveToFile(FileName);
finally
LStream.Free;
end;
end;
/// <summary>
/// clNone - Não especifica nenhuma compressão; os dados são meramente copiados para o fluxo de saída.
/// clFastest - Especifica a compressão mais rápida, resultando em um arquivo maior.
/// clDefault - Compromisso entre velocidade e quantidade de compressão.
/// clMax - Especifica a compressão máxima, resultando em um tempo maior para realizar a operação.
/// </summary>
procedure TBlob.CompressStream(ASource, ATarget: TStream);
var
LStream: TCompressionStream;
begin
LStream := TCompressionStream.Create(clDefault, ATarget);
try
LStream.CopyFrom(ASource, ASource.Size);
LStream.CompressionRate;
finally
LStream.Free;
end;
end;
procedure TBlob.DecompressStream(ASource, ATarget: TStream) ;
var
LStream: TDecompressionStream;
LRead: Integer;
LBuffer: Array [0..1023] of Char;
begin
// ASource.Seek(0, soFromBeginning);
// ATarget.Seek(0, soFromBeginning);
LStream := TDecompressionStream.Create(ASource);
try
repeat
LRead := LStream.Read(LBuffer, SizeOf(LBuffer));
if LRead <> 0 then
ATarget.Write(LBuffer, LRead);
until LRead <= 0;
finally
LStream.Free;
end;
end;
{$IFDEF HAS_NET_ENCODING}
function TBlob.GetEncodeBase64: String;
var
LNetEncoding: TBase64Encoding;
begin
LNetEncoding := TBase64Encoding.Create;
try
Result := LNetEncoding.EncodeBytesToString(FBase64Bytes, ToSize);
finally
LNetEncoding.Free;
end;
end;
function TBlob.GetDecodeBase64(const Value: String): Boolean;
var
LNetEncoding: TBase64Encoding;
begin
Result := False;
LNetEncoding := TBase64Encoding.Create;
try
FBase64Bytes := LNetEncoding.DecodeStringToBytes(Value);
FBase64String := Value;
Result := True;
finally
LNetEncoding.Free;
end;
end;
{$ENDIF}
{$IFDEF HAS_SOAP_ENCODING}
function TBlob.GetEncodeBase64: String;
begin
Result := EncodeBase64(FBase64Bytes, ToSize);
end;
function TBlob.GetDecodeBase64(const Value: String): Boolean;
begin
Result := False;
FBase64Bytes := DecodeBase64(AString);
FBase64String := Value;
Result := True;
end;
{$ENDIF}
{$IFDEF HAS_ENCDDECD}
function TBlob.GetEncodeBase64: String;
begin
Result := EncodeBase64(FBase64Bytes, ToSize);
end;
function TBlob.GetDecodeBase64(const Value: String): Boolean;
begin
Result := False;
FBase64Bytes := DecodeBase64(AString);
FBase64String := Value;
Result := True;
end;
{$ENDIF}
end.
|
unit UREST;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, REST.JSON, System.JSON, Vcl.StdCtrls,
clHttpRequest, clTcpClient, clTcpClientTls, clHttp, Vcl.ExtCtrls, Vcl.ComCtrls,
IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdHTTP;
type
TfrmREST = class(TForm)
pnlMaster: TPanel;
cmbCountry: TComboBox;
cmbState: TComboBox;
cmbCity: TComboBox;
http: TclHttp;
httpReq: TclHttpRequest;
mmoToken: TMemo;
btnGet: TButton;
pnlAuthenticate: TPanel;
pnlDropDown: TPanel;
lblCountry: TLabel;
lblState: TLabel;
lblCity: TLabel;
lblTitle: TLabel;
lblToken: TLabel;
procedure FormShow(Sender: TObject);
procedure btnGetClick(Sender: TObject);
procedure cmbStateChange(Sender: TObject);
procedure cmbCountrySelect(Sender: TObject);
procedure cmbStateSelect(Sender: TObject);
procedure cmbCityClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
frmREST: TfrmREST;
implementation
{$R *.dfm}
procedure TfrmREST.btnGetClick(Sender: TObject);
var
LITEM, lJsonValue: TJSONValue;
token: WideString;
country: TStringStream;
begin
ShowMessage(mmoToken.Lines.Text.Length.ToString);
token := 'Bearer ' + mmoToken.Text;
httpReq.Header.Accept := 'application/json';
httpReq.Header.Authorization := token;
country := TStringStream.Create();
http.SendRequest('GET', 'https://www.universal-tutorial.com/api/countries/',
httpReq, country);
lJsonValue := TJsonObject.ParseJSONValue(country.DataString);
if lJsonValue <> nil then
try
begin
for LITEM in lJsonValue as TJSONArray do
begin
cmbCountry.Items.Add(((LITEM as TJsonObject).Get('country_name')
.JsonValue as TJSONString).Value);
end;
end;
finally
lJsonValue.Free;
end;
end;
procedure TfrmREST.cmbCityClick(Sender: TObject);
begin
lblCity.Caption:='City : '+cmbCity.Text;
end;
procedure TfrmREST.cmbCountrySelect(Sender: TObject);
var
cntryName: String;
LITEM, lJsonValue: TJSONValue;
c_response: TStringStream;
token: WideString;
begin
cntryName := cmbCountry.Text;
lblCountry.Caption:='Country : '+cntryName;
token := 'Bearer ' + mmoToken.Text;
httpReq.Header.Accept := 'application/json';
httpReq.Header.Authorization := token;
c_response := TStringStream.Create();
http.SendRequest('GET', 'https://www.universal-tutorial.com/api/states/' +
cntryName, httpReq, c_response);
lJsonValue := TJsonObject.ParseJSONValue(c_response.DataString);
if lJsonValue <> nil then
try
begin
for LITEM in lJsonValue as TJSONArray do
begin
cmbState.Items.Add(((LITEM as TJsonObject).Get('state_name')
.JsonValue as TJSONString).Value);
end;
end;
finally
lJsonValue.Free;
end;
end;
procedure TfrmREST.cmbStateChange(Sender: TObject);
begin
Update;
end;
procedure TfrmREST.cmbStateSelect(Sender: TObject);
var
stName: String;
LITEM, lJsonValue: TJSONValue;
s_response: TStringStream;
token: WideString;
begin
stName := cmbState.Text;
lblState.Caption:='State : '+stName;
token := 'Bearer ' + mmoToken.Text;
httpReq.Header.Accept := 'application/json';
httpReq.Header.Authorization := token;
s_response := TStringStream.Create();
http.SendRequest('GET', 'https://www.universal-tutorial.com/api/cities/' +
stName, httpReq, s_response);
lJsonValue := TJsonObject.ParseJSONValue(s_response.DataString);
if lJsonValue <> nil then
try
begin
for LITEM in lJsonValue as TJSONArray do
begin
cmbCity.Items.Add(((LITEM as TJsonObject).Get('city_name')
.JsonValue as TJSONString).Value);
end;
end;
finally
lJsonValue.Free;
end;
end;
procedure TfrmREST.FormShow(Sender: TObject);
var
token_responce: TStringStream;
begin
httpReq.Header.Accept := 'application/json';
httpReq.HeaderSource.AddPair('api-token','z1dYuraUVWBAnyO5F-0Pp0kLhjRcKfDnYkByhvKBBVjR21qRA_aOL3BPqU9u05RoSg');
httpReq.HeaderSource.AddPair('user-email','test12kct@gmail.com');
token_responce := TStringStream.Create();
http.SendRequest('GET','https://www.universal-tutorial.com/api/getaccesstoken', httpReq,token_responce);
mmoToken.Lines.Text:=token_responce.DataString;
end;
end.
|
type
arr=record
score:extended;
name:string;
end;
var
a:array[0..100000] of arr;
n,m,i,j:longint;
ch:char;
s:string;
sc:extended;
procedure quicksort(m,n:longint);
var
i,j:longint;
x:extended;
temp:arr;
begin
x:=a[(m+n) div 2].score;
i:=m;
j:=n;
repeat
while a[i].score<x do i:=i+1;
while a[j].score>x do j:=j-1;
if i<=j then
begin
temp:=a[i];
a[i]:=a[j];
a[j]:=temp;
i:=i+1;
j:=j-1;
end;
until i>j;
if m<j then quicksort(m,j);
if i<n then quicksort(i,n);
end;
function find(m,n:longint):longint;
var
x:longint;
begin
if (m>n)or(m=n)and(a[m].score<>sc) then exit(0);
if a[m].score=sc then exit(m);
if a[n].score=sc then exit(n);
x:=(m+n) div 2;
if a[x].score=sc then exit(x);
if a[x].score>sc then exit(find(m+1,x-1)) else exit(find(x+1,n-1));
end;
begin
readln(n);
for i:=1 to n do
begin
s:='';
repeat
read(ch);
if ch<>' ' then s:=s+ch;
until ch=' ';
readln(a[i].score);
a[i].name:=s;
end;
quicksort(1,n);
readln(m);
for i:=1 to m do
begin
readln(sc);
j:=find(1,n);
if j=0 then writeln('No Such User')
else writeln(a[j].name,' ',j);
end;
end. |
{----------------------------------------------------------------------
DEVIUM Content Management System
Copyright (C) 2004 by DEIV Development Team.
http://www.deiv.com/
$Header: /devium/Devium\040CMS\0402/Source/PhotoGallery/pgAlbumListForm.pas,v 1.1 2004/05/06 07:15:42 paladin Exp $
------------------------------------------------------------------------}
unit pgAlbumListForm;
interface
uses
Forms, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxEdit, DB,
cxDBData, Classes, ActnList, Menus, TB2Item, cxGridLevel,
cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxClasses,
cxControls, cxGridCustomView, cxGrid, ComCtrls, TB2Dock, TB2Toolbar,
Controls, DBClient;
type
TAlbumListForm = class(TForm)
TBDock1: TTBDock;
TBToolbar1: TTBToolbar;
TBPopupMenu1: TTBPopupMenu;
StatusBar: TStatusBar;
TBSubmenuItem1: TTBSubmenuItem;
TBSeparatorItem1: TTBSeparatorItem;
TBItem1: TTBItem;
TBItem2: TTBItem;
TBItem3: TTBItem;
ActionList: TActionList;
cxGrid1DBTableView1: TcxGridDBTableView;
cxGrid1Level1: TcxGridLevel;
cxGrid1: TcxGrid;
is_visible: TcxGridDBColumn;
last_update: TcxGridDBColumn;
title: TcxGridDBColumn;
AlbumEdit: TAction;
AlbumDel: TAction;
AlbumAdd: TAction;
TBItem4: TTBItem;
TBItem5: TTBItem;
TBItem6: TTBItem;
TBItem7: TTBItem;
TBSeparatorItem2: TTBSeparatorItem;
SortUp: TAction;
SortDown: TAction;
TBSeparatorItem3: TTBSeparatorItem;
TBItem8: TTBItem;
TBItem9: TTBItem;
TBItem10: TTBItem;
procedure AlbumAddExecute(Sender: TObject);
procedure AlbumEditExecute(Sender: TObject);
procedure AlbumDelExecute(Sender: TObject);
procedure cxGrid1DBTableView1DblClick(Sender: TObject);
procedure AlbumEditUpdate(Sender: TObject);
procedure SortUpUpdate(Sender: TObject);
procedure SortUpExecute(Sender: TObject);
procedure SortDownExecute(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
FGalleryId: Integer;
function GetNextSortOrder(DataSet: TDataSet; FieldName: String): Integer;
procedure ReSortDataSet(DataSet: TClientDataSet; FieldName: String;
ADelta: Integer);
public
property GalleryId: Integer read FGalleryId write FGalleryId;
end;
function GetAlbumListForm(GalleryId: Integer): Integer;
implementation
uses pgMainForm, pgDataModule, pgAlbumForm, Windows, SysUtils, Math;
{$R *.dfm}
function GetAlbumListForm;
var
Form: TAlbumListForm;
begin
Form := TAlbumListForm.Create(Application);
try
Form.GalleryId := GalleryId;
Result := Form.ShowModal;
finally
Form.Free;
end;
end;
procedure TAlbumListForm.AlbumAddExecute(Sender: TObject);
var
SortOrder: Integer;
begin
with DM.Albums do
begin
SortOrder := GetNextSortOrder(DM.Albums, 'sort_order');
Append;
FieldValues['sort_order'] := SortOrder;
FieldValues['gallery_id'] := FGalleryId;
if GetAlbumForm = mrOK then
Post
else
Cancel;
end;
end;
procedure TAlbumListForm.AlbumEditExecute(Sender: TObject);
var
OldName: String;
s1, s2: String;
begin
with DM.Albums do
begin
OldName := FieldValues['name'];
Edit;
if GetAlbumForm = mrOK then
begin
Post;
if OldName <> FieldValues['name'] then
begin
s1 := DM.GetFilesPath(DM.Albums);
s2 := DM.GetFilesPath(DM.List) + OldName;
RenameFile(s2, s1);
DM.RenDir(s2, s1);
end;
end
else
Cancel;
end;
end;
procedure TAlbumListForm.AlbumDelExecute(Sender: TObject);
begin
if MessageBox(Handle, 'Вы точно уверенны что хотите это сделать?' + #13#10 +
'Удаление альбомаприбедет к удалению всех фотографий.',
PChar(Caption),
MB_YESNO + MB_ICONQUESTION) = IDNO then Exit;
{ TODO : }
while DM.Photos.Locate('album_id', DM.Albums['id'], []) do
DM.Photos.Delete;
DM.Albums.Delete;
end;
procedure TAlbumListForm.cxGrid1DBTableView1DblClick(Sender: TObject);
begin
AlbumEdit.Execute;
end;
procedure TAlbumListForm.AlbumEditUpdate(Sender: TObject);
begin
TAction(Sender).Enabled := DM.Albums.RecordCount > 0;
end;
procedure TAlbumListForm.SortUpUpdate(Sender: TObject);
begin
TAction(Sender).Enabled := DM.Albums.RecordCount > 1;
end;
procedure TAlbumListForm.SortUpExecute(Sender: TObject);
begin
ReSortDataSet(DM.Albums, 'sort_order', -15);
end;
procedure TAlbumListForm.SortDownExecute(Sender: TObject);
begin
ReSortDataSet(DM.Albums, 'sort_order', 15);
end;
procedure TAlbumListForm.FormCreate(Sender: TObject);
begin
cxGrid1DBTableView1.DataController.DataSource := DM.dsAlbums;
end;
function TAlbumListForm.GetNextSortOrder(DataSet: TDataSet; FieldName: String): Integer;
var
SavePlace: TBookmark;
begin
Result := 0;
with DataSet do
begin
DisableControls;
SavePlace := GetBookmark;
try
First;
while not EOF do
begin
Result := Max(Result, FieldValues[FieldName]);
Next;
end;
GotoBookmark(SavePlace);
finally
FreeBookmark(SavePlace);
end;
EnableControls;
end;
Result := Result + 10;
end;
procedure TAlbumListForm.ReSortDataSet(DataSet: TClientDataSet; FieldName: String;
ADelta: Integer);
var
SavePlace: TBookmark;
n: Integer;
OldIndexFieldNames: String;
begin
with DataSet do
begin
DisableControls;
Edit;
DataSet[FieldName] := DataSet[FieldName] + ADelta;
Post;
OldIndexFieldNames := IndexFieldNames;
IndexFieldNames := FieldName;
SavePlace := GetBookmark;
try
n := RecordCount;
Last;
while not BOF do
begin
Edit;
FieldValues[FieldName] := n * 10;
Post;
Dec(n);
Prior;
end;
GotoBookmark(SavePlace);
finally
FreeBookmark(SavePlace);
end;
IndexFieldNames := OldIndexFieldNames;
EnableControls;
end;
end;
end.
|
unit Main;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls, uListAll,
uAbout;
type
TMainForm = class(TForm)
LeftPanel: TPanel;
Label1: TLabel;
LabelAll: TLabel;
Label6: TLabel;
LabelAbout: TLabel;
ScrollBox: TScrollBox;
procedure OnMenuMouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
procedure OnMenuMouseLeave(Sender: TObject);
procedure LabelAllClick(Sender: TObject);
procedure LabelGoodClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure LabelAboutClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
procedure HideFrames;
procedure OpenListAll;
procedure OpenAbout;
end;
var
MainForm: TMainForm;
ListAllFrame: TListAllFrame;
AboutFrame: TAboutFrame;
implementation
{$R *.dfm}
procedure TMainForm.FormShow(Sender: TObject);
begin
OpenListAll;
end;
procedure TMainForm.HideFrames;
// Скрыть все фрэймы
begin
if Assigned(AboutFrame) then
FreeAndNil(AboutFrame);
if Assigned(ListAllFrame) then
FreeAndNil(ListAllFrame);
LabelAll.Font.Color := clHighlightText;
LabelAbout.Font.Color := clHighlightText;
end;
procedure TMainForm.LabelAboutClick(Sender: TObject);
begin
OpenAbout();
end;
procedure TMainForm.LabelAllClick(Sender: TObject);
begin
OpenListAll;
end;
procedure TMainForm.LabelGoodClick(Sender: TObject);
begin
HideFrames();
end;
procedure TMainForm.OnMenuMouseLeave(Sender: TObject);
// Уход мыши с лэйблов
begin
if Sender is TLabel then
TLabel(Sender).Font.Style := [fsBold];
end;
procedure TMainForm.OnMenuMouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
// Движение мыши над меню из лайблов слева
begin
if Sender is TLabel then
TLabel(Sender).Font.Style := [fsBold, fsUnderline];
end;
procedure TMainForm.OpenAbout;
// Открыть фрэйм "О программе"
begin
HideFrames();
LabelAbout.Font.Color := clHighlight;
AboutFrame := TAboutFrame.Create(nil);
AboutFrame.Parent := ScrollBox;
AboutFrame.Image.Visible := True;
AboutFrame.Memo.Visible := False;
AboutFrame.Image.Left := 0;
AboutFrame.Timer.Enabled := True;
AboutFrame.Show;
end;
procedure TMainForm.OpenListAll;
// Открыть список всех кандидатов
begin
HideFrames();
LabelAll.Font.Color := clHighlight;
ListAllFrame := TListAllFrame.Create(nil);
ListAllFrame.Parent := ScrollBox;
ListAllFrame.LoadMainTable;
ListAllFrame.Show;
end;
end.
|
PROGRAM SumValues(INPUT, OUTPUT);
FUNCTION CharToInt(VAR Ch: CHAR): INTEGER;
BEGIN {CharToInt}
IF (Ch >= '0') AND (Ch <= '9')
THEN
BEGIN
IF Ch = '0' THEN CharToInt := 0 ELSE
IF Ch = '1' THEN CharToInt := 1 ELSE
IF Ch = '2' THEN CharToInt := 2 ELSE
IF Ch = '3' THEN CharToInt := 3 ELSE
IF Ch = '4' THEN CharToInt := 4 ELSE
IF Ch = '5' THEN CharToInt := 5 ELSE
IF Ch = '6' THEN CharToInt := 6 ELSE
IF Ch = '7' THEN CharToInt := 7 ELSE
IF Ch = '8' THEN CharToInt := 8 ELSE
IF Ch = '9' THEN CharToInt := 9
END
ELSE
CharToInt := -1
END; {CharToInt}
FUNCTION ReadDigit(VAR F: TEXT): INTEGER;
VAR
Ch: CHAR;
BEGIN {ReadDigit}
IF (NOT(EOLN(F))) AND (NOT(EOF(F)))
THEN
BEGIN
READ(F, Ch);
ReadDigit := CharToInt(Ch)
END
ELSE
ReadDigit := -1
END; {ReadDigit}
FUNCTION SumChar(VAR F: TEXT): INTEGER;
VAR
Ch: CHAR;
Sum: INTEGER;
BEGIN {SumChar}
Sum := 0;
IF (NOT(EOLN(F))) AND (NOT(EOF(F)))
THEN
BEGIN
WHILE (NOT(EOLN(F))) AND (NOT(EOF(F)))
DO
Sum := Sum + ReadDigit(F);
SumChar := Sum
END
ELSE
SumChar := 0
END; {SumChar}
BEGIN {SumValues}
WRITELN(SumChar(INPUT))
END. {SumValues}
|
unit MiniDialogGenerateRandomPoints;
interface
uses
Winapi.Windows,
Winapi.Messages,
System.SysUtils,
System.Variants,
System.Classes,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Vcl.StdCtrls,
Vcl.Samples.Spin,
GraphDefine,
Pengine.Vector;
type
TmdlgGenerateRandomPoints = class(TForm)
lbCount: TLabel;
seCount: TSpinEdit;
btnGenerate: TButton;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
private
FGraph: TGraphEditable;
protected
procedure UpdateActions; override;
public
procedure Execute(AGraph: TGraphEditable);
end;
var
mdlgGenerateRandomPoints: TmdlgGenerateRandomPoints;
implementation
{$R *.dfm}
{ TForm1 }
procedure TmdlgGenerateRandomPoints.Execute(AGraph: TGraphEditable);
begin
FGraph := AGraph;
ModalResult := mrCancel;
Position := poMainFormCenter;
Show;
end;
procedure TmdlgGenerateRandomPoints.FormClose(Sender: TObject; var Action: TCloseAction);
begin
if ModalResult = mrOk then
begin
with TGraphEditable.TRandomPointGenerator.Create(FGraph) do
begin
try
Count := seCount.Value;
Bounds := Bounds2(-300, 300);
Generate;
finally
Free;
end;
end;
end;
end;
procedure TmdlgGenerateRandomPoints.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
if Key = VK_ESCAPE then
Close;
end;
procedure TmdlgGenerateRandomPoints.UpdateActions;
begin
inherited;
end;
end.
|
{ Subroutine STRING_F_BITS32 (S, BITS)
*
* Convert the 32 bit word in BITS into a 32 character string of ones or
* zeroes in S. The string length is truncated to the maximum
* of S.
}
module string_f_bits32;
define string_f_bits32;
%include 'string2.ins.pas';
procedure string_f_bits32 ( {32 digit binary string from 32 bit integer}
in out s: univ string_var_arg_t; {output string}
in bits: sys_int_min32_t); {input integer, uses low 32 bits}
val_param;
var
i: sys_int_max_t; {integer of right format for convert routine}
stat: sys_err_t; {error code}
begin
i := bits & 16#FFFFFFFF; {into format for convert routine}
string_f_int_max_base ( {make string from integer}
s, {output string}
i, {input integer}
2, {number base}
32, {output field width}
[string_fi_leadz_k, {write leading zeros}
string_fi_unsig_k], {input number is unsigned}
stat);
sys_error_abort (stat, 'string', 'internal', nil, 0);
end;
|
unit uSystem;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, TeEngine, Series, ExtCtrls, TeeProcs, Chart;
type
TPopulation = record
victims, predators: double;
end;
TForm1 = class(TForm)
Label1: TLabel;
txtGenVictims: TEdit;
Label2: TLabel;
txtBeginVictims: TEdit;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
Label7: TLabel;
txtPredatorDeath: TEdit;
txtBeginPredator: TEdit;
txtPredatorCanEatVictim: TEdit;
txtPeriod: TEdit;
btCalc: TButton;
btExit: TButton;
Chart1: TChart;
txtVictimDeath: TEdit;
Label8: TLabel;
Series1: TLineSeries;
Series2: TLineSeries;
procedure btCalcClick(Sender: TObject);
procedure btExitClick(Sender: TObject);
private
{ Private declarations }
period: single;
beginVictims, beginPredators: double;
genVictims: double;
kills: double;
victimDeath, predatorDeath: double;
population: array of TPopulation;
procedure Draw();
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
function strToFloatEx(s: string): double;
var sett: TFormatSettings;
begin
if pos(',', s) > 0 then sett.DecimalSeparator := ','
else sett.DecimalSeparator := '.';
result := strToFloat(s, sett);
end;
procedure TForm1.btCalcClick(Sender: TObject);
var i, j: integer; v, p: double;
begin
beginVictims := strToFloatEx(txtBeginVictims.Text);
beginPredators := strToFloatEx(txtBeginPredator.Text);
genVictims := strToFloatEx(txtGenVictims.Text);
kills := strToFloatEx(txtPredatorCanEatVictim.Text);
predatorDeath := strToFloatEx(txtPredatorDeath.Text);
victimDeath := strToFloatEx(txtVictimDeath.Text);
period := strToFloatEx(txtPeriod.Text);
setLength(population, trunc(period));
population[0].victims := beginVictims;
population[0].predators := beginPredators;
i := 1;
while i <= length(population) - 1 do
begin
j := i - 1;
v := population[j].victims + genVictims * population[j].victims -
victimDeath * population[j].predators * population[j].victims;
p := population[j].predators + kills *
population[j].predators * population[j].victims -
predatorDeath * population[j].predators;
population[i].victims := v;
population[i].predators := p;
inc(i)
end;
Draw();
end;
procedure TForm1.btExitClick(Sender: TObject);
begin
close;
end;
procedure TForm1.Draw;
var i: integer;
begin
Series2.Clear;
Series1.Clear;
Series1.Title := 'Жертвы';
Series2.Title := 'Хищники';
for i := 0 to length(population) - 1 do
begin
Series1.AddXY(i, population[i].victims,
floatToStr(i), clGreen);
Series2.AddXY(i, population[i].predators,
floatToStr(i), clRed);
end;
end;
end.
|
unit unitSettings;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, XMLConf, FileUtil, Forms, Controls, Graphics, Dialogs,
INIFiles, ExtCtrls, CheckLst, StdCtrls, ComCtrls, XMLPropStorage;
type
TSettingsRecord = record
filterList: TStringList;
closeOnEnter : Boolean;
addNewVarToPath : Boolean;
useHardcodedPathes : Boolean;
userVariables:Boolean;//use USER vs SYSTEM variables
end;
{ TfrmSettings }
TfrmSettings = class(TForm)
btnOk: TButton;
btnCancel: TButton;
checkOnChange: TCheckGroup;
edtFilter: TLabeledEdit;
private
{ private declarations }
function SetFilterListText(S: String):TStringList;
public
{ public declarations }
function loadSettings:TSettingsRecord;
function getSettingsFromUI:TSettingsRecord;
procedure setSettingsToUI(settings:TSettingsRecord);
procedure saveSettings(settings:TSettingsRecord);
end;
const
GENERAL : String = 'General';
FILTER_LIST : String = 'filterList';
ADD_NEW_VAR_TO_PATH : String = 'addNewVarToPath';
CLOSE_ON_ERROR : String = 'closeOnEnter';
USE_HARDCODED_PATHES: String = 'useHardcodedPathes';
SETTINGS_FN:String='EnvMan4j.ini';
var
frmSettings: TfrmSettings;
implementation
{$R *.lfm}
function TfrmSettings.SetFilterListText(S: String):TStringList;
begin
Result := TStringList.Create;
Result.Delimiter:=';';
Result.DelimitedText:= S;
end;
function TfrmSettings.loadSettings:TSettingsRecord;
var
ini : TINIFile;
begin
ini := TINIFile.Create(SETTINGS_FN);
Result.filterList := SetFilterListText(ini.ReadString(GENERAL,FILTER_LIST,'_HOME;_WORK'));
Result.addNewVarToPath:=ini.ReadBool(GENERAL,ADD_NEW_VAR_TO_PATH,true);
Result.closeOnEnter:=ini.ReadBool(GENERAL,CLOSE_ON_ERROR,true);
Result.useHardcodedPathes:=ini.ReadBool(GENERAL,USE_HARDCODED_PATHES,false);
Result.userVariables:= true;
end;
function TfrmSettings.getSettingsFromUI:TSettingsRecord;
begin
Result.filterList := SetFilterListText(edtFilter.Text);
Result.closeOnEnter:=checkOnChange.Checked[0];
Result.addNewVarToPath:=checkOnChange.Checked[1];
Result.useHardcodedPathes:=checkOnChange.Checked[2];
end;
procedure TfrmSettings.setSettingsToUI(settings:TSettingsRecord);
begin
edtFilter.Text := settings.filterList.DelimitedText;
checkOnChange.Checked[0]:=settings.closeOnEnter;
checkOnChange.Checked[1]:=settings.addNewVarToPath;
checkOnChange.Checked[2]:=settings.useHardcodedPathes;
end;
procedure TfrmSettings.saveSettings(settings:TSettingsRecord);
var
ini : TINIFile;
filterListString : String;
begin
ini := TINIFile.Create(SETTINGS_FN);
ini.WriteString(GENERAL,FILTER_LIST,settings.filterList.DelimitedText);
ini.WriteBool(GENERAL,ADD_NEW_VAR_TO_PATH,settings.addNewVarToPath);
ini.WriteBool(GENERAL,CLOSE_ON_ERROR,settings.closeOnEnter);
ini.WriteBool(GENERAL,USE_HARDCODED_PATHES,settings.useHardcodedPathes);
end;
end.
|
{
Build a list of used scripts in selected records and generate report.
Also check for script's existence in loaded BSAs or game's Data\Scripts folder.
}
unit UserScript;
var
slScripts: TStringList;
function Initialize: integer;
begin
slScripts := TStringList.Create;
end;
function Process(e: IInterface): integer;
var
s: string;
i: integer;
sl: TStringList;
begin
if ElementType(e) = etMainRecord then
if ElementExists(e, 'VMAD') then
Process(ElementBySignature(e, 'VMAD'))
else
Exit;
if Name(e) = 'scriptName' then begin
s := GetEditValue(e);
i := slScripts.IndexOf(s);
if i = -1 then begin
// new script
sl := TStringList.Create;
sl.Sorted := True;
sl.Duplicates := dupIgnore;
sl.Add(FullPath(e));
slScripts.AddObject(s, sl);
end else
// existing script
TStringList(slScripts.Objects[i]).Add(FullPath(e));
end;
// recursively process all child elements
for i := 0 to ElementCount(e) - 1 do
Process(ElementByIndex(e, i));
end;
function Finalize: integer;
var
i: integer;
slRep: TStringList;
s, fname: string;
begin
if slScripts.Count > 0 then begin
slRep := TStringList.Create;
slScripts.Sort;
for i := 0 to slScripts.Count - 1 do begin
s := slScripts[i];
if not ResourceExists('Scripts\' + s + '.pex') then
s := s + ' - MISSING!';
slRep.Add(s);
slRep.Add(StringOfChar('-', 60));
slRep.Add(TStringList(slScripts.Objects[i]).Text);
end;
fname := ProgramPath + 'Edit Scripts\Scripts report.txt';
AddMessage('Saving report to ' + fname);
slRep.SaveToFile(fname);
slRep.Free;
end else
AddMessage('No scripts found.');
for i := 0 to slScripts.Count - 1 do
TStringList(slScripts.Objects[i]).Free;
slScripts.Free;
end;
end.
|
{ ***************************************************************************
Dannyrooh Fernandes | https://github.com/dannyrooh | Licença MIT
Recuperar o conteúdo de uma URL
08/2021 - created
*************************************************************************** }
unit Http.Util;
interface
uses
IdHttp,
IdSSLOpenSSL,
System.Classes,
System.SysUtils;
type
THttpUtil = class
const
MSG_ERRO_CONEXAO = 'Verifique a sua conexão com a internet!';
private
function getResponse(url: string): TBytes;
function bytesToString(value: TBytes): string;
public
class function Get(url: string): string;
end;
implementation
{ THttpHtil }
function THttpUtil.bytesToString(value: TBytes): string;
begin
var lEncoding : TEncoding := nil;
var lSize := TEncoding.GetBufferEncoding(value, lEncoding);
result := lEncoding.GetString(value, lSize, Length(value) - lSize);
end;
class function THttpUtil.Get(url: string): string;
var
ctx: THttpUtil;
response: TBytes;
begin
ctx := THttpUtil.Create;
try
try
response := ctx.getResponse( url );
except
on e: Exception do
raise Exception.Create(MSG_ERRO_CONEXAO);
end;
result := ctx.bytesToString(response);
finally
FreeAndNil(ctx);
end;
end;
function THttpUtil.getResponse(url: string): TBytes;
begin
var http := TIdHTTP.Create(nil);
//tratamento para evitar erro de SSL3
var handler := TIdSSLIOHandlerSocketOpenSSL.Create(http);
handler.SSLOptions.SSLVersions := [sslvTLSv1, sslvTLSv1_1, sslvTLSv1_2];
http.IOHandler := handler;
var response := TMemoryStream.Create;
try
http.Get(url,response);
if response.Size > 0 then
begin
SetLength(result, response.Size );
response.Position := 0;
response.ReadBuffer(Pointer(result)^, response.Size);
end;
finally
FreeAndNil(handler);
FreeAndNil(http);
FreeAndNil(response);
end;
end;
end.
|
{*******************************************************************************
Title: T2Ti ERP
Description: Controller do lado Cliente relacionado ās tabelas
[PCP_OP_CABECALHO] e [PCP_OP_DETALHE]
The MIT License
Copyright: Copyright (C) 2014 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
t2ti.com@gmail.com
@author Albert Eije (t2ti.com@gmail.com)
@version 2.0
*******************************************************************************}
unit PcpOpController;
interface
uses
Classes, Dialogs, SysUtils, DBClient, DB, Windows, Forms, Controller, Rtti,
Atributos, VO, Generics.Collections, PcpOpCabecalhoVO, PcpOpDetalheVO, PcpInstrucaoOpVO,
PcpServicoVO, PcpServicoColaboradorVO, PcpServicoEquipamentoVO;
type
TPcpOpController = class(TController)
private
class var FDataSet: TClientDataSet;
public
class procedure Consulta(pFiltro: String; pPagina: String; pConsultaCompleta: Boolean = False);
class function ConsultaLista(pFiltro: String): TObjectList<TPcpOpCabecalhoVO>;
class function ConsultaObjeto(pFiltro: String): TPcpOpCabecalhoVO;
class procedure Insere(pObjeto: TPcpOpCabecalhoVO);
class function Altera(pObjeto: TPcpOpCabecalhoVO): Boolean;
class function Exclui(pId: Integer): Boolean;
class function ExcluiInstrucao(pId: Integer): Boolean;
class function ExcluiItem(pId: Integer): Boolean;
class function ExcluiServico(pId: Integer): Boolean;
class function ExcluiColaborador(pId: Integer): Boolean;
class function ExcluiEquipamento(pId: Integer): Boolean;
class function GetDataSet: TClientDataSet; override;
class procedure SetDataSet(pDataSet: TClientDataSet); override;
class procedure TratarListaRetorno(pListaObjetos: TObjectList<TVO>);
end;
implementation
uses
UDataModule, T2TiORM;
class procedure TPcpOpController.Consulta(pFiltro: String; pPagina: String; pConsultaCompleta: Boolean);
var
Retorno: TObjectList<TPcpOpCabecalhoVO>;
begin
try
Retorno := TT2TiORM.Consultar<TPcpOpCabecalhoVO>(pFiltro, pPagina, pConsultaCompleta);
TratarRetorno<TPcpOpCabecalhoVO>(Retorno);
finally
end;
end;
class function TPcpOpController.ConsultaLista(pFiltro: String): TObjectList<TPcpOpCabecalhoVO>;
begin
try
Result := TT2TiORM.Consultar<TPcpOpCabecalhoVO>(pFiltro, '-1', True);
finally
end;
end;
class function TPcpOpController.ConsultaObjeto(pFiltro: String): TPcpOpCabecalhoVO;
begin
try
Result := TT2TiORM.ConsultarUmObjeto<TPcpOpCabecalhoVO>(pFiltro, True);
finally
end;
end;
class procedure TPcpOpController.Insere(pObjeto: TPcpOpCabecalhoVO);
var
UltimoID, IDDetalhe, IDServico: Integer;
InstrucoesEnumerator: TEnumerator<TPcpInstrucaoOpVO>;
PcpOpDetalheEnumerator: TEnumerator<TPcpOpDetalheVO>;
PcpServicoEnumerator: TEnumerator<TpcpServicoVO>;
PcpServicoColaboradorEnumerator: TEnumerator<TPcpServicoColaboradorVO>;
PcpServicoEquipamentoEnumerator: TEnumerator<TPcpServicoEquipamentoVO>;
begin
try
UltimoID := TT2TiORM.Inserir(pObjeto);
// Instrucoes
InstrucoesEnumerator := pObjeto.ListaPcpInstrucaoOpVO.GetEnumerator;
try
with InstrucoesEnumerator do
begin
while MoveNext do
begin
Current.IdPcpOpCabecalho := UltimoID;
TT2TiORM.Inserir(Current);
end;
end;
finally
FreeAndNil(InstrucoesEnumerator);
end;
// Detalhe
PcpOpDetalheEnumerator := pObjeto.ListaPcpOpDetalheVO.GetEnumerator;
try
with PcpOpDetalheEnumerator do
begin
while MoveNext do
begin
Current.IdPcpOpCabecalho := UltimoID;
IDDetalhe := TT2TiORM.Inserir(Current);
PcpServicoEnumerator := TPcpOpDetalheVO(Current).ListaPcpServicoVO.GetEnumerator;
try
with PcpServicoEnumerator do
begin
while MoveNext do
begin
Current.IdPcpOpDetalhe := IDDetalhe;
IDServico := TT2TiORM.Inserir(Current);
PcpServicoColaboradorEnumerator := TPcpServicoVO(Current).ListaPcpColabradorVO.GetEnumerator;
try
with PcpServicoColaboradorEnumerator do
begin
while MoveNext do
begin
Current.IdPcpServico := IDServico;
TT2TiORM.Inserir(Current);
end;
end;
finally
FreeAndNil(PcpServicoColaboradorEnumerator);
end;
PcpServicoEquipamentoEnumerator := TPcpServicoVO(Current).ListaPcpServicoEquipamentoVO.GetEnumerator;
try
with PcpServicoEquipamentoEnumerator do
begin
while MoveNext do
begin
Current.IdPcpServico := IDServico;
TT2TiORM.Inserir(Current);
end;
end;
finally
FreeAndNil(PcpServicoEquipamentoEnumerator);
end;
end;
end;
finally
FreeAndNil(PcpServicoEnumerator);
end;
end;
end;
finally
FreeAndNil(PcpOpDetalheEnumerator);
end;
Consulta('ID = ' + IntToStr(UltimoID), '0');
finally
end;
end;
class function TPcpOpController.Altera(pObjeto: TPcpOpCabecalhoVO): Boolean;
begin
try
Result := TT2TiORM.Alterar(pObjeto);
finally
end;
end;
class function TPcpOpController.Exclui(pId: Integer): Boolean;
var
ObjetoLocal: TPcpOpCabecalhoVO;
begin
try
ObjetoLocal := TPcpOpCabecalhoVO.Create;
ObjetoLocal.Id := pId;
Result := TT2TiORM.Excluir(ObjetoLocal);
TratarRetorno(Result);
finally
FreeAndNil(ObjetoLocal)
end;
end;
class function TPcpOpController.ExcluiColaborador(pId: Integer): Boolean;
var
ObjetoLocal: TPcpServicoColaboradorVO;
begin
try
ObjetoLocal := TPcpServicoColaboradorVO.Create;
ObjetoLocal.Id := pId;
Result := TT2TiORM.Excluir(ObjetoLocal);
TratarRetorno(Result);
finally
FreeAndNil(ObjetoLocal)
end;
end;
class function TPcpOpController.ExcluiEquipamento(pId: Integer): Boolean;
var
ObjetoLocal: TPcpServicoEquipamentoVO;
begin
try
ObjetoLocal := TPcpServicoEquipamentoVO.Create;
ObjetoLocal.Id := pId;
Result := TT2TiORM.Excluir(ObjetoLocal);
TratarRetorno(Result);
finally
FreeAndNil(ObjetoLocal)
end;
end;
class function TPcpOpController.ExcluiInstrucao(pId: Integer): Boolean;
var
ObjetoLocal: TPcpInstrucaoOpVO;
begin
try
ObjetoLocal := TPcpInstrucaoOpVO.Create;
ObjetoLocal.Id := pId;
Result := TT2TiORM.Excluir(ObjetoLocal);
TratarRetorno(Result);
finally
FreeAndNil(ObjetoLocal)
end;
end;
class function TPcpOpController.ExcluiItem(pId: Integer): Boolean;
var
ObjetoLocal: TPcpOpDetalheVO;
begin
try
ObjetoLocal := TPcpOpDetalheVO.Create;
ObjetoLocal.Id := pId;
Result := TT2TiORM.Excluir(ObjetoLocal);
TratarRetorno(Result);
finally
FreeAndNil(ObjetoLocal)
end;
end;
class function TPcpOpController.ExcluiServico(pId: Integer): Boolean;
var
ObjetoLocal: TPcpServicoVO;
begin
try
ObjetoLocal := TPcpServicoVO.Create;
ObjetoLocal.Id := pId;
Result := TT2TiORM.Excluir(ObjetoLocal);
TratarRetorno(Result);
finally
FreeAndNil(ObjetoLocal)
end;
end;
class function TPcpOpController.GetDataSet: TClientDataSet;
begin
Result := FDataSet;
end;
class procedure TPcpOpController.SetDataSet(pDataSet: TClientDataSet);
begin
FDataSet := pDataSet;
end;
class procedure TPcpOpController.TratarListaRetorno(pListaObjetos: TObjectList<TVO>);
begin
try
TratarRetorno<TPcpOpCabecalhoVO>(TObjectList<TPcpOpCabecalhoVO>(pListaObjetos));
finally
FreeAndNil(pListaObjetos);
end;
end;
initialization
Classes.RegisterClass(TPcpOpController);
finalization
Classes.UnRegisterClass(TPcpOpController);
end.
|
(*
* Copyright (c) 2011, Ciobanu Alexandru
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the <organization> nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*)
(*
This sample implements a new "collection" based on an input string split by a given character.
Each element of this "pseudo-collection" is a split part of the string.
NOTE: This collection is "read-only". We don't implement any higher level interfaces such as IList<T>. This means
that we don't need an internal versioning scheme and don't need to fear of thread safety issues.
*)
unit SplitStringEnumerable;
interface
uses
SysUtils,
Collections.Base;
type
{ A new collection. Derive it from TEnexCollection. Since the elements in our new collection
are strings (parts of a given initial string) we need to type the generic base as TEnexCollection<string>.}
TSplitStringCollection = class(TSequence<string>)
private type
{
This is the enumerator. It's a private type in TSplitStringCollection. Noone but this collection
can instantiate it for ... safety reasons: usually the state is specific and only the collection code
might be aware of that.
We derive it from TEnumerator<T>. This type implements IEnumerator<T> and provides some base plumbing code.
}
TEnumerator = class(TAbstractEnumerator<string>)
private
LNowIndex, LPrevIndex, FLength: NativeInt;
public
{ The contructor. The collection will pass itself here. The enumerator needs to know who is it talking to. }
constructor Create(const AOwner: TSplitStringCollection);
{ This method is called prior to anything else. We must return TRUE if the element was obtained, and store that element
somewhere that GetCurrent can obtain. }
function TryMoveNext(out ACurrent: string): Boolean; override;
end;
private
FInputString: string;
FSeparator: Char;
FCount: NativeInt;
protected
{ Now this is tricky. This function is used by all other function and users to check the length
of the output collection. We don't know ahead of time ... So we will probably calculate the number of times the separator
is present in the input string and store that as the count.
Note that we have overridden thsi method. The deafult implemenation in TEnexCollection<T> will request an enumerator and start
enumerating till the end of the collection (thus generating the count) -- not very optimal!
}
function GetCount(): NativeInt; override;
public
{ The first constructor is pretty obvious -- requires a string to be split and a character to split by. }
constructor Create(const AString: string; const ASeparator: Char = ' '); overload;
{ The second contructor also requires a set of comparison rules (the comparer and equality comparer). These rules will be needed for
Extended operations such as Max() or Min(). The inherited code from TEnexCollection<string> expects us to provide a rules set so we ask the user
if he has something specific. The first constructor will simply call this cionstructor but request the default rules set (TRules<string>.Default). }
constructor Create(const ARules: TRules<string>; const AString: string; const ASeparator: Char = ' '); overload;
{ This method will simply check the count to be greater than zero ... that's it. But we need to override it to ensure we have an optimized
"check for emptiness". Other Enex code will call this method and we can't afford to let the default implementation (it's slow too!). }
function Empty(): Boolean; override;
{ Even though TEnexCollection<T> provides a Count proprty that calls GetCount() it's better to map to a field if we have one for
performance reasons.
}
property Count: NativeInt read FCount;
{ This is THE MOST IMPORTANT thing you need to provide in your collection. Even GetCount() and Empty() have default implementations in TEnexCollection<T>.
All those implementations rely on the fact that they extract an enumerator and start playing with it. SO WE ABSOLUTELY MUST provide it ... It's defined as
abstract anyway so you can't avoid it.
}
function GetEnumerator(): IEnumerator<string>; override;
end;
{ This is the "facade" function. It takes a string and a separator and returns an interface
reference to a new TSplitStringCollection class that you can play with. }
function SplitString(const AString: string; const ASeparator: Char = ' '): ISequence<string>;
/// <summary>Runs the current sample.</summary>
procedure RunSample();
implementation
procedure RunSample();
var
LWord, LInput: string;
LGroup: IGrouping<Integer, string>;
begin
WriteLn;
WriteLn('=============== [SplitStringEnumerable] ============ ');
WriteLn;
{ Assign some dummy text }
LInput := 'Johnny had a bad taste in women!';
{ And now let's enjoy the split action. We will split using the default SPACE character effectively
getting each word. }
WriteLn('Splitting "', LInput ,'": ');
for LWord in SplitString(LInput) do
WriteLn(' # ', LWord);
WriteLn;
{ And now we will group all words in the string by length. Note that we have 3 "operations involved":
1. SplitString(LInput) itself which creates the input enumerable.
2. Op.GroupBy<Integer>(selector) which groups all elements in the input collection by a given "rule".
In current case the rule is the length of the string. This means that the output of this
operation is a collection of collections.
3. Ordered(comparison) which compares a given group to another. This will sort the output in length asceding order.
}
WriteLn('Write all words groupped by their length:');
for LGroup in SplitString(LInput).
Op.GroupBy<Integer>(function(S: String): Integer begin Exit(Length(S)) end).
Ordered(function(const L, R: IGrouping<Integer, string>): Integer begin Exit(L.Key - R.Key) end) do
begin
{ Write the group key (the length) }
Write(' # ', LGroup.Key, ' characters: ');
{ Now iterate all the words groupped by this length and write them to the console. }
for LWord in LGroup do
Write(LWord, ' ');
{ Add a new line for the next group. }
WriteLn;
end;
end;
function SplitString(const AString: string; const ASeparator: Char): ISequence<string>;
begin
{ The code is absolutely stupid }
Result := TSplitStringCollection.Create(AString, ASeparator);
end;
{ TSplitStringCollection }
constructor TSplitStringCollection.Create(const AString: string; const ASeparator: Char);
begin
{ Call the more general constructor. Pass a default rule set along ... }
Create(TRules<string>.Default, AString, ASeparator);
end;
constructor TSplitStringCollection.Create(const ARules: TRules<string>; const AString: string; const ASeparator: Char);
var
LChar: Char;
begin
{ This is the core constructor. Step 1 is to call the inherited constructor ans pass the rule set to it.
It will prepare the collection basics. }
inherited Create(ARules);
{ The next step is to store the variables }
FInputString := AString;
FSeparator := ASeparator;
{ Now we need to check how many split points we will have }
if Length(AString) > 0 then
begin
FCount := 1;
for LChar in AString do
if LChar = ASeparator then
Inc(FCount);
{ Well, that was simple :) }
end;
end;
function TSplitStringCollection.Empty: Boolean;
begin
{ As promised ... simply check that FCount is bigger than zero }
Result := FCount > 0;
end;
function TSplitStringCollection.GetCount: NativeInt;
begin
{ Just return the count }
Result := FCount;
end;
function TSplitStringCollection.GetEnumerator: IEnumerator<string>;
begin
{ Create an enumerator instance and return it as an interface reference. }
Result := TEnumerator.Create(Self);
end;
{ TSplitStringCollection.TEnumerator }
constructor TSplitStringCollection.TEnumerator.Create(const AOwner: TSplitStringCollection);
begin
{ Store reference to our collection! }
inherited Create(AOwner);
{ Initialize indexes. }
LPrevIndex := 1;
LNowIndex := 1;
{ This if to minimize length calls }
FLength := Length(AOwner.FInputString);
end;
function TSplitStringCollection.TEnumerator.TryMoveNext(out ACurrent: string): Boolean;
var
LOwner: TSplitStringCollection;
begin
{ Store a strong type to our owner collection. "Owner" is a property exposed by the base enumerator }
LOwner := TSplitStringCollection(Owner);
{ This is the function that will actually do the work! Wow, we have written so much
in simple preparation. The code in this method will actually split the string: }
{ Start with a "we are at the end of the world" attitude. }
Result := false;
while LNowIndex <= FLength do
begin
{ Check if the current character is a separator }
if LOwner.FInputString[LNowIndex] = LOwner.FSeparator then
begin
{ Yes, we will cut over the required part and place it for the taking }
ACurrent := System.Copy(LOwner.FInputString, LPrevIndex, (LNowIndex - LPrevIndex));
{ Adjust previous idex so we know where to cut from. }
LPrevIndex := LNowIndex + 1;
{ We have found the next piece. We might as well just break. }
Result := true;
end;
{ Increment the current index. }
Inc(LNowIndex);
{ If we found a piece exit at this iteration }
if Result then
Exit;
end;
{ Special case! We got here so there is a last split available }
if LPrevIndex < LNowIndex then
begin
{ Copy the last peice and mark the result as OK. }
ACurrent := Copy(LOwner.FInputString, LPrevIndex, FLength - LPrevIndex + 1);
LPrevIndex := LNowIndex + 1;
Result := true;
end;
end;
end.
|
unit RobotUnit;
// verzia 221012
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, Graphics, Dialogs, ExtCtrls;
type
TRobot = class
private
FX, FY, FH: Real;
FDown: Boolean;
FPC: TColor;
FPW: Integer;
public
Value: Integer;
constructor Create;
constructor Create(NewX, NewY: Real; Angle: Real = 0);
procedure Fd(D: Real); virtual;
procedure Rt(Angle: Real); virtual;
procedure Lt(Angle: Real); virtual;
procedure SetH(Angle: Real); virtual;
procedure SetXY(NewX, NewY: Real); virtual;
procedure SetX(NewX: Real); virtual;
procedure SetY(NewY: Real); virtual;
procedure MoveXY(NewX, NewY: Real); virtual;
procedure PU; virtual;
procedure PD; virtual;
procedure SetPen(Down: Boolean); virtual;
procedure SetPC(NewColor: TColor); virtual;
procedure SetPW(NewWidth: Integer); virtual;
procedure Point(NewWidth: Real = 0); virtual;
procedure Text(NewText: string); virtual;
procedure Towards(AnyX, AnyY: Real); virtual;
procedure Fill(NewColor: TColor); virtual;
function Dist(AnyX, AnyY: Real): Real; virtual;
function IsNear(AnyX, AnyY: Real): Boolean; virtual;
procedure Draw; virtual;
property X: Real read FX write SetX;
property Y: Real read FY write SetY;
property H: Real read FH write SetH;
property IsPD: Boolean read FDown write SetPen;
property PC: TColor read FPC write SetPC;
property PW: Integer read FPW write SetPW;
end;
//////////////////////////////////////////////////////////////////////////////////////////
const
Rad = Pi/180;
Deg = 180/Pi;
procedure CS(NewColor: TColor = clWhite);
procedure Wait(MilliSec: Integer);
procedure SetImage(Image: TImage = nil);
//////////////////////////////////////////////////////////////////////////////////////////
implementation
var
MyImage: TImage = nil;
//////////////////////////////////////////////////////////////////////////////////////////
constructor TRobot.Create;
begin
SetImage;
Create(MyImage.Width / 2, MyImage.Height / 2);
end;
constructor TRobot.Create(NewX, NewY, Angle: Real);
begin
SetImage;
FX := NewX;
FY := NewY;
FH := Angle;
FPC := clBlack;
FPW := 1;
FDown := True;
end;
procedure TRobot.Rt(Angle: Real);
begin
SetH(FH + Angle);
end;
procedure TRobot.Lt(Angle: Real);
begin
SetH(FH - Angle);
end;
procedure TRobot.SetH(Angle: Real);
begin
FH := Angle;
while FH < 0 do
FH := FH + 360;
while FH >= 360 do
FH := FH - 360;
end;
procedure TRobot.Fd(D: Real);
begin
SetXY(FX + Sin(FH * Rad) * D, FY - Cos(FH * Rad) * D);
end;
procedure TRobot.SetXY(NewX, NewY: Real);
begin
if not FDown then
MoveXY(NewX, NewY)
else
with MyImage.Canvas do
begin
Brush.Style := bsSolid;
Pen.Color := FPC;
Pen.Width := FPW;
Line(Round(FX), Round(FY), Round(NewX), Round(NewY));
FX := NewX;
FY := NewY;
end;
end;
procedure TRobot.MoveXY(NewX, NewY: Real);
begin
FX := NewX;
FY := NewY;
MyImage.Canvas.MoveTo(Round(FX), Round(FY));
end;
procedure TRobot.PU;
begin
FDown := False;
end;
procedure TRobot.PD;
begin
FDown := True;
end;
procedure TRobot.SetPen(Down: Boolean);
begin
if Down then
PD
else
PU;
end;
procedure TRobot.SetPC(NewColor: TColor);
begin
FPC := NewColor;
end;
procedure TRobot.SetPW(NewWidth: Integer);
begin
FPW := NewWidth;
end;
procedure TRobot.SetX(NewX: Real);
begin
SetXY(NewX, FY);
end;
procedure TRobot.SetY(NewY: Real);
begin
SetXY(FX, NewY);
end;
//////////////////////////////////////////////////////////////////////////////////////////
procedure TRobot.Point(NewWidth: Real);
var
AnyX, AnyY, R1, R2: Integer;
begin
NewWidth := Round(Abs(NewWidth));
if NewWidth = 0 then
NewWidth := FPW;
R1 := (Trunc(NewWidth) + 1) div 2;
R2 := Trunc(NewWidth) - R1 + 1;
with MyImage.Canvas do
begin
AnyX := Round(FX);
AnyY := Round(FY);
Brush.Color := FPC;
Brush.Style := bsSolid;
Pen.Color := FPC;
Pen.Style := psSolid;
Pen.Width := 1;
Ellipse(AnyX - R1, AnyY - R1, AnyX + R2, AnyY + R2);
end;
end;
procedure TRobot.Fill(NewColor: TColor);
var
AnyX, AnyY: Integer;
begin
with MyImage.Canvas do
begin
AnyX := Round(FX);
AnyY := Round(FY);
Brush.Color := NewColor;
Brush.Style := bsSolid;
FloodFill(AnyX, AnyY, Pixels[AnyX, AnyY], fsSurface);
end;
end;
procedure TRobot.Towards(AnyX, AnyY: Real);
var
Angle: Real;
begin
AnyX := AnyX - FX;
AnyY := FY - AnyY;
if AnyY = 0 then
if AnyX = 0 then
Angle := 0
else if AnyX < 0 then
Angle := 270
else
Angle := 90
else if AnyY > 0 then
if AnyX >= 0 then
Angle := ArcTan(AnyX / AnyY) * Deg
else
Angle := 360 - ArcTan(- AnyX / AnyY) * Deg
else if AnyX >= 0 then
Angle := 180 - ArcTan(- AnyX / AnyY) * Deg
else
Angle := 180 + ArcTan(AnyX / AnyY) * Deg;
SetH(Angle);
end;
function TRobot.Dist(AnyX, AnyY: Real): Real;
begin
Result := Sqrt(Sqr(AnyX - FX) + Sqr(AnyY - FY));
end;
function TRobot.IsNear(AnyX, AnyY: Real): Boolean;
begin
Result := Sqr(AnyX - FX) + Sqr(AnyY - FY) < 144;
end;
procedure TRobot.Text(NewText: string);
begin
MyImage.Canvas.Font.Color := FPC;
MyImage.Canvas.Brush.Style := bsClear;
MyImage.Canvas.TextOut(Round(FX), Round(FY), NewText);
end;
procedure TRobot.Draw;
begin
Point;
end;
//////////////////////////////////////////////////////////////////////////////////////////
procedure CS(NewColor: TColor);
begin
SetImage;
with MyImage, Canvas do
begin
Brush.Color := NewColor;
Brush.Style := bsSolid;
FillRect(ClientRect);
end;
end;
procedure Wait(MilliSec: Integer);
begin
if MyImage <> nil then
MyImage.Parent.Repaint;
Sleep(MilliSec);
end;
//////////////////////////////////////////////////////////////////////////////////////
procedure SetImage(Image: TImage);
var
I, N: Integer;
Form: TForm;
begin
if MyImage <> nil then
Exit;
if Image = nil then
begin
Form := Application.MainForm;
if Form = nil then
begin
N := Application.ComponentCount;
I := 0;
while (I < N) and not (Application.Components[I] is TForm) do
Inc(I);
if I = N then
begin
ShowMessage('vadná aplikácia - Robot nenašiel formulár');
Halt;
end;
Form := TForm(Application.Components[I]);
end;
N := Form.ControlCount;
I := 0;
while (I < N) and not (Form.Controls[I] is TImage) do
Inc(I);
if I >= N then
begin
ShowMessage('vadná aplikácia - Robot nenašiel grafickú plochu');
Halt;
end;
Image := TImage(Form.Controls[I]);
end;
with Image, Canvas do
begin
Brush.Color := clWhite;
Brush.Style := bsSolid;
FillRect(ClientRect);
end;
if Image.Owner is TForm then
TForm(Image.Owner).DoubleBuffered := True;
MyImage := Image;
end;
end.
|
unit Navigator;
//TODO: Undo list
//TODO: Clipboard
//TODO: Drag'n'Drop: nodes expanding, scrolling, reordering by dnd
//TODO: Insertion/Importing and Exporting of hives
//TODO: Mass operations on nodes (setting compression for all (or selected - as :nodetext) streams of all selected nodes, for example)
//TODO: Collapsing on '/' button
interface
uses
Windows, CommCtrl, Messages, AvL, avlNatCompare, avlTreeViewEx, DataNode, NodeTag;
type
TCompFunc = function(const S1, S2: string): Integer;
TNavigator = class(TSimplePanel)
ToolBar: TToolBar;
NodeTree: TTreeViewEx;
NaviMenu, SortMenu: TMenu;
private
FOnModify: TOnEvent;
FOnNodeSelected: TOnEvent;
FSortRecursive: Boolean;
FTBImages: TImageList;
FNodeImages: TImageList;
FRootNode: TDataNode;
FDragNode, FMenuNode: Integer;
FDragImage: HImageList;
function AddNode(Parent, After: Integer; Node: TDataNode): Integer;
procedure DeleteNode(Node: Integer);
function GetSelNode: TDataNode;
function NewNode(Parent: Integer; InsertAfter: Integer = Integer(TVI_LAST)): Integer;
procedure NodeProperties(Node: Integer);
procedure NodeSort(Node: TDataNode; Recursive, Ascending: Boolean; CompFunc: TCompFunc);
procedure NodeTreeKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure NodeTreeMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
procedure NodeTreeMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure NodeTreeMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure RefreshNode(Node: Integer);
procedure Resize(Sender: TObject);
procedure WMCommand(var Msg: TWMCommand); message WM_COMMAND;
procedure WMNotify(var Msg: TWMNotify); message WM_NOTIFY;
procedure SetRootNode(const Value: TDataNode);
procedure SortNode(Node: Integer; Recursive, Ascending: Boolean; CompFunc: TCompFunc);
procedure SwapNodes(Node1, Node2: Integer);
procedure ToggleNode(Node: Integer; Mode: TExpandMode = emToggle);
public
constructor Create(AParent: TWinControl);
destructor Destroy; override;
procedure UpdateTree;
procedure Clear;
property RootNode: TDataNode read FRootNode write SetRootNode;
property SelNode: TDataNode read GetSelNode;
property OnModify: TOnEvent read FOnModify write FOnModify;
property OnNodeSelected: TOnEvent read FOnNodeSelected write FOnNodeSelected;
end;
implementation
uses
MainForm;
type
TTBButtons = (tbAdd, tbAddChild, tbProperties, tbMoveUp, tbMoveDown, tbDelete, tbSort, tbToggle);
const
SConfirmDelete = 'Delete node "%s"?';
TBButtons: array[TTBButtons] of record Caption: string; ImageIndex: Integer; end = (
(Caption: 'Add'; ImageIndex: 0),
(Caption: 'Add child'; ImageIndex: 1),
(Caption: 'Properties'; ImageIndex: 2),
(Caption: 'Move up'; ImageIndex: 3),
(Caption: 'Move down'; ImageIndex: 4),
(Caption: 'Delete'; ImageIndex: 5),
(Caption: 'Sort'; ImageIndex: 6),
(Caption: 'Toggle'; ImageIndex: 8));
IDRefresh = 9001;
IDAdd = IDRefresh + 2;
IDAddChild = IDAdd + 1;
IDRename = IDAddChild + 1;
IDProperties = IDRename + 1;
IDDelete = IDProperties + 1;
IDToggle = IDDelete + 1;
IDSort = IDToggle + 1;
MenuNavi: array[0..8] of PChar = ('9001',
'Refresh'#9'F5',
'-',
'Add'#9'F7',
'Add child'#9'F8',
'Rename'#9'F2',
'Properties'#9'F3',
'Delete'#9'Del',
'Toggle');
IDSortAlphaAsc = 10001;
IDSortAlphaDesc = IDSortAlphaAsc + 1;
IDSortNatAsc = IDSortAlphaDesc + 1;
IDSortNatDesc = IDSortNatAsc + 1;
IDSortRecursive = IDSortNatDesc + 2;
MenuSort: array[0..6] of PChar = ('10001',
'Alphabetical ascending',
'Alphabetical descending',
'Natural ascending',
'Natural descending',
'-',
'Recursive');
{ TNavigator }
constructor TNavigator.Create(AParent: TWinControl);
var
Btn: TTBButtons;
begin
inherited Create(AParent, '');
Border := 2;
ExStyle := 0;
FTBImages := TImageList.Create;
FTBImages.AddMasked(LoadImage(hInstance, 'TBNAVI', IMAGE_BITMAP, 0, 0, 0), clFuchsia);
FNodeImages := TImageList.Create;
FNodeImages.AddMasked(LoadImage(hInstance, 'TVNODES', IMAGE_BITMAP, 0, 0, 0), clFuchsia);
ToolBar := TToolBar.Create(Self, true);
ToolBar.Style := ToolBar.Style or TBSTYLE_TOOLTIPS or CCS_TOP;
ToolBar.ExStyle := ToolBar.ExStyle or TBSTYLE_EX_MIXEDBUTTONS;
ToolBar.Perform(TB_SETMAXTEXTROWS, 0, 0);
ToolBar.Perform(TB_AUTOSIZE, 0, 0);
ToolBar.Images := FTBImages;
for Btn := Low(TTBButtons) to High(TTBButtons) do
ToolBar.ButtonAdd(TBButtons[Btn].Caption, TBButtons[Btn].ImageIndex);
NodeTree := TTreeViewEx.Create(Self);
NodeTree.Style := NodeTree.Style or TVS_EDITLABELS or TVS_SHOWSELALWAYS;
//NodeTree.CanvasInit;
NodeTree.Images := FNodeImages;
NodeTree.SetPosition(0, ToolBar.Height);
NodeTree.OnKeyDown := NodeTreeKeyDown;
NodeTree.OnMouseMove := NodeTreeMouseMove;
NodeTree.OnMouseUp := NodeTreeMouseUp;
NodeTree.OnMouseDown := NodeTreeMouseDown;
SortMenu := TMenu.Create(Self, false, MenuSort);
NaviMenu := TMenu.Create(Self, false, MenuNavi);
InsertMenu(NaviMenu.Handle, IDSort, MF_BYCOMMAND or MF_POPUP, SortMenu.Handle, PChar(TBButtons[tbSort].Caption));
OnResize := Resize;
end;
destructor TNavigator.Destroy;
begin
FreeAndNil(FTBImages);
FreeAndNil(FNodeImages);
inherited;
end;
function TNavigator.AddNode(Parent, After: Integer; Node: TDataNode): Integer;
var
i: Integer;
begin
Result := NodeTree.ItemInsert(Parent, After, Node.Name, Node);
(Node.Tag as TNodeTag).TreeItem := Result;
for i := 0 to Node.Children.Count - 1 do
AddNode(Result, Integer(TVI_LAST), Node.Children[i]);
if (Node.Tag as TNodeTag).TreeItemExpanded then
NodeTree.ExpandItem(Result, emExpand);
if (Node.Tag as TNodeTag).Selected then
NodeTree.Selected := Result;
end;
procedure TNavigator.DeleteNode(Node: Integer);
begin
if Node = 0 then Exit;
if MessageBox(FormMain.Handle, PChar(Format(SConfirmDelete, [TDataNode(NodeTree.GetItemObject(Node)).Name])),
AppCaption, MB_YESNO or MB_ICONEXCLAMATION) = IDNO then Exit;
NodeTree.GetItemObject(Node).Free;
NodeTree.DeleteItem(Node);
if Assigned(FOnModify) then
FOnModify(Self);
end;
function TNavigator.NewNode(Parent: Integer; InsertAfter: Integer = Integer(TVI_LAST)): Integer;
var
Node: TDataNode;
begin
Result := 0;
if not Assigned(FRootNode) then Exit;
Node := TDataNode.Create;
if (Parent = 0) or (Parent = Integer(TVI_ROOT))
then Node.Parent := FRootNode
else Node.Parent := TDataNode(NodeTree.GetItemObject(Parent));
with Node.Parent.Children do
if InsertAfter = Integer(TVI_LAST)
then Add(Node)
else Insert(IndexOf(TDataNode(NodeTree.GetItemObject(InsertAfter))) + 1, Node);
Result := AddNode(Parent, InsertAfter, Node);
if Assigned(FOnModify) then
FOnModify(Self);
NodeTree.ExpandItem(Parent, emExpand);
NodeTree.Selected := Result;
NodeTree.SetFocus;
NodeTree.Perform(TVM_EDITLABEL, 0, Result);
end;
procedure TNavigator.UpdateTree;
var
i: Integer;
begin
NodeTree.BeginUpdate;
try
NodeTree.DeleteItem(Integer(TVI_ROOT));
if Assigned(FRootNode) then
for i := 0 to FRootNode.Children.Count - 1 do
AddNode(Integer(TVI_ROOT), Integer(TVI_LAST), FRootNode.Children[i]);
finally
NodeTree.EndUpdate;
end;
end;
procedure TNavigator.Resize(Sender: TObject);
begin
ToolBar.Perform(TB_AUTOSIZE, 0, 0);
NodeTree.SetSize(ClientWidth, ClientHeight - ToolBar.Height);
end;
procedure TNavigator.WMNotify(var Msg: TWMNotify);
const
ToggleImage: array[Boolean] of Integer = (8, 7);
NodeImage: array[Boolean] of Integer = (0, 2);
var
P: TPoint;
begin
if Assigned(NodeTree) and (Msg.NMHdr.hwndFrom = NodeTree.Handle) then
begin
if Msg.NMHdr.code = TVN_SELCHANGED then
begin
if Assigned(FOnNodeSelected) then
FOnNodeSelected(Self);
ToolBar.ButtonImageIndex[Integer(tbToggle)] := ToggleImage[NodeTree.ItemExpanded(NodeTree.Selected)];
if PNMTreeView(Msg.NMHdr).itemNew.lParam <> 0 then
(TDataNode(PNMTreeView(Msg.NMHdr).itemNew.lParam).Tag as TNodeTag).Selected := true;
end;
if Msg.NMHdr.code = TVN_ITEMEXPANDED then
with PNMTreeView(Msg.NMHdr)^ do
begin
if Integer(itemNew.hItem) = NodeTree.Selected then
ToolBar.ButtonImageIndex[Integer(tbToggle)] := ToggleImage[NodeTree.ItemExpanded(NodeTree.Selected)];
if itemNew.lParam <> 0 then
(TDataNode(itemNew.lParam).Tag as TNodeTag).TreeItemExpanded := action = TVE_EXPAND;
end;
if Msg.NMHdr.code = TVN_BEGINLABELEDIT then
begin
Msg.Result := 0;
SendMessage(NodeTree.Perform(TVM_GETEDITCONTROL, 0, 0), EM_SETLIMITTEXT, 255, 0);
end;
if Msg.NMHdr.code = TVN_ENDLABELEDIT then
with PTVDispInfo(Msg.NMHdr)^ do
if Assigned(item.pszText) and (item.lParam <> 0) then
begin
TDataNode(item.lParam).Name := item.pszText;
if Assigned(FOnModify) then
FOnModify(Self);
Msg.Result := 1;
end;
if Msg.NMHdr.code = TVN_BEGINDRAG then
begin
FDragNode := Integer(PNMTreeView(Msg.NMHdr).itemNew.hItem);
FDragImage := NodeTree.Perform(TVM_CREATEDRAGIMAGE, 0, FDragNode);
ImageList_BeginDrag(FDragImage, 0, 0, 0);
P := PNMTreeView(Msg.NMHdr).ptDrag;
ClientToScreen(NodeTree.Handle, P);
ImageList_DragEnter(GetDesktopWindow, P.X, P.Y);
SetCapture(NodeTree.Handle);
end;
if (Msg.NMHdr.code = TVN_GETDISPINFO) and (PTVDispInfo(Msg.NMHdr).item.lParam <> 0) then
with PTVDispInfo(Msg.NMHdr).item, TDataNode(PTVDispInfo(Msg.NMHdr).item.lParam).Tag as TNodeTag do
begin
if mask and TVIF_IMAGE <> 0 then
iImage := NodeImage[state and TVIS_EXPANDED = TVIS_EXPANDED];
if mask and TVIF_SELECTEDIMAGE <> 0 then
iSelectedImage := iImage + 1;
end;
end;
end;
procedure TNavigator.SetRootNode(const Value: TDataNode);
begin
FRootNode := Value;
UpdateTree;
end;
procedure TNavigator.WMCommand(var Msg: TWMCommand);
const
MenuCheck: array[Boolean] of UINT = (MF_UNCHECKED, MF_CHECKED);
var
Cursor: TPoint;
begin
if Assigned(ToolBar) and (Msg.Ctl = ToolBar.Handle) then
case TTBButtons(Msg.ItemID) of
tbAdd: NewNode(NodeTree.GetItemParent(NodeTree.Selected), NodeTree.Selected);
tbAddChild: NewNode(NodeTree.Selected);
tbProperties: NodeProperties(NodeTree.Selected);
tbMoveUp: SwapNodes(NodeTree.Selected, NodeTree.Perform(TVM_GETNEXTITEM, TVGN_PREVIOUS, NodeTree.Selected));
tbMoveDown: SwapNodes(NodeTree.Selected, NodeTree.Perform(TVM_GETNEXTITEM, TVGN_NEXT, NodeTree.Selected));
tbDelete: DeleteNode(NodeTree.Selected);
tbSort: begin
GetCursorPos(Cursor);
CheckMenuItem(SortMenu.Handle, IDSortRecursive, MenuCheck[FSortRecursive] or MF_BYCOMMAND);
FMenuNode := NodeTree.Selected;
SortMenu.Popup(Cursor.X, Cursor.Y);
end;
tbToggle: ToggleNode(NodeTree.Selected);
end;
if (Msg.Ctl = 0) and (Msg.NotifyCode in [0, 1]) then
case Msg.ItemID of
IDRefresh: RefreshNode(FMenuNode);
IDAdd: NewNode(NodeTree.GetItemParent(FMenuNode), NodeTree.Selected);
IDAddChild: NewNode(FMenuNode);
IDRename: NodeTree.Perform(TVM_EDITLABEL, 0, FMenuNode);
IDProperties: NodeProperties(FMenuNode);
IDDelete: DeleteNode(FMenuNode);
IDToggle: ToggleNode(FMenuNode);
IDSortAlphaAsc: SortNode(FMenuNode, FSortRecursive, true, CompareText);
IDSortAlphaDesc: SortNode(FMenuNode, FSortRecursive, false, CompareText);
IDSortNatAsc: SortNode(FMenuNode, FSortRecursive, true, CompareTextNatural);
IDSortNatDesc: SortNode(FMenuNode, FSortRecursive, false, CompareTextNatural);
IDSortRecursive: FSortRecursive := not FSortRecursive;
end;
end;
procedure TNavigator.NodeTreeKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
if Shift = [] then
case Key of
VK_F2: NodeTree.Perform(TVM_EDITLABEL, 0, NodeTree.Selected);
VK_F3: NodeProperties(NodeTree.Selected);
VK_F5: RefreshNode(NodeTree.Selected);
VK_F7: NewNode(NodeTree.GetItemParent(NodeTree.Selected), NodeTree.Selected);
VK_F8: NewNode(NodeTree.Selected);
VK_DELETE: DeleteNode(NodeTree.Selected);
end;
if Shift = [ssShift] then
case Key of
VK_F5: UpdateTree;
end;
if Shift = [ssCtrl] then
begin
case Key of
Ord('I'): NewNode(NodeTree.GetItemParent(NodeTree.Selected), NodeTree.Selected);
VK_UP: SwapNodes(NodeTree.Selected, NodeTree.Perform(TVM_GETNEXTITEM, TVGN_PREVIOUS, NodeTree.Selected));
VK_DOWN: SwapNodes(NodeTree.Selected, NodeTree.Perform(TVM_GETNEXTITEM, TVGN_NEXT, NodeTree.Selected));
VK_LEFT: ToggleNode(NodeTree.Selected, emCollapse);
VK_RIGHT: ToggleNode(NodeTree.Selected, emExpand);
end;
if Key in [VK_LEFT, VK_RIGHT, VK_UP, VK_DOWN] then
Key := 0;
end;
if Shift = [ssShift, ssCtrl] then
case Key of
Ord('I'): NewNode(NodeTree.Selected);
end;
end;
procedure TNavigator.RefreshNode(Node: Integer);
var
SelNode: TDataNode;
begin
SelNode := Self.SelNode;
if Node <> 0 then
begin
NodeTree.BeginUpdate;
try
AddNode(NodeTree.GetItemParent(Node), Node, TDataNode(NodeTree.GetItemObject(Node)));
NodeTree.DeleteItem(Node);
finally
NodeTree.EndUpdate;
end;
end
else UpdateTree;
if Assigned(SelNode) then
NodeTree.Selected := (SelNode.Tag as TNodeTag).TreeItem;
end;
procedure TNavigator.SwapNodes(Node1, Node2: Integer);
begin
if (Node1 = 0) or (Node2 = 0) or
(TDataNode(NodeTree.GetItemObject(Node1)).Parent <> TDataNode(NodeTree.GetItemObject(Node2)).Parent) then Exit;
with TDataNode(NodeTree.GetItemObject(Node1)).Parent.Children do
Swap(IndexOf(TDataNode(NodeTree.GetItemObject(Node1))), IndexOf(TDataNode(NodeTree.GetItemObject(Node2))));
if Assigned(FOnModify) then
FOnModify(Self);
RefreshNode(NodeTree.GetItemParent(Node1));
end;
function TNavigator.GetSelNode: TDataNode;
begin
if Assigned(FRootNode) then
Result := TDataNode(NodeTree.GetItemObject(NodeTree.Selected))
else Result := nil;
end;
procedure TNavigator.SortNode(Node: Integer; Recursive, Ascending: Boolean; CompFunc: TCompFunc);
begin
NodeSort(TDataNode(NodeTree.GetItemObject(Node)), Recursive, Ascending, CompFunc);
RefreshNode(Node);
if Assigned(FOnModify) then
FOnModify(Self);
end;
procedure TNavigator.NodeSort(Node: TDataNode; Recursive, Ascending: Boolean; CompFunc: TCompFunc);
var
i, Count, LastSwap: Integer;
begin
if not Assigned(Node) then Exit;
Count := Node.Children.Count;
while Count > 0 do
begin
LastSwap := 0;
for i := 1 to Count - 1 do
if (Ascending and (CompFunc(Node.Children[i - 1].Name, Node.Children[i].Name) > 0)) or
(not Ascending and (CompFunc(Node.Children[i - 1].Name, Node.Children[i].Name) < 0)) then
begin
Node.Children.Swap(i - 1, i);
LastSwap := i;
end;
Count := LastSwap;
end;
if Recursive then
for i := 0 to Node.Children.Count - 1 do
NodeSort(Node.Children[i], Recursive, Ascending, CompFunc);
end;
procedure TNavigator.ToggleNode(Node: Integer; Mode: TExpandMode);
const
Modes: array[Boolean] of TExpandMode = (emExpand, emCollapse);
begin
if Mode = emToggle then
Mode := Modes[NodeTree.ItemExpanded(Node)];
NodeTree.ExpandItem(Node, Mode);
Node := NodeTree.Perform(TVM_GETNEXTITEM, TVGN_CHILD, Node);
while Node <> 0 do
begin
ToggleNode(Node, Mode);
Node := NodeTree.Perform(TVM_GETNEXTITEM, TVGN_NEXT, Node);
end;
end;
procedure TNavigator.Clear;
begin
NodeTree.DeleteItem(Integer(TVI_ROOT));
FRootNode := nil;
end;
procedure TNavigator.NodeProperties(Node: Integer);
begin
ShowMessage('Under construction');
end;
procedure TNavigator.NodeTreeMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
var
P: TPoint;
begin
if FDragNode <> 0 then
begin
//ImageList_DragLeave(NodeTree.Handle);
NodeTree.Perform(TVM_SELECTITEM, TVGN_DROPHILITE, NodeTree.ItemAtPoint(X, Y));
//ImageList_DragEnter(NodeTree.Handle, X, Y);
P := Point(X, Y);
ClientToScreen(NodeTree.Handle, P);
ImageList_DragMove(P.X, P.Y);
end;
end;
procedure TNavigator.NodeTreeMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
function CheckNode(Target, Dropped: Integer): Boolean;
begin
Result := false;
while Target <> 0 do
if Target = Dropped then
Exit
else
Target := NodeTree.GetItemParent(Target);
Result := true;
end;
var
Node: Integer;
begin
if (Button = mbLeft) and (FDragNode <> 0) then
begin
Node := NodeTree.ItemAtPoint(X, Y);
if (X >= 0) and (Y >= 0) and (X <= NodeTree.Width) and (Y <= NodeTree.Height) and CheckNode(Node, FDragNode) then
begin
if Node <> 0 then
TDataNode(NodeTree.GetItemObject(Node)).Children.Add(TDataNode(NodeTree.GetItemObject(FDragNode)))
else
FRootNode.Children.Add(TDataNode(NodeTree.GetItemObject(FDragNode)));
UpdateTree;
if Assigned(FOnModify) then
FOnModify(Self);
end;
ImageList_DragLeave(NodeTree.Handle);
ImageList_EndDrag;
ImageList_Destroy(FDragImage);
FDragNode := 0;
ReleaseCapture;
end;
end;
procedure TNavigator.NodeTreeMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
Cur: TPoint;
begin
Cur := Point(X, Y);
ClientToScreen((Sender as TWinControl).Handle, Cur);
if Button = mbRight then
begin
FMenuNode := NodeTree.ItemAtPoint(X, Y);
NaviMenu.Popup(Cur.X, Cur.Y);
end;
end;
end. |
unit xxmFReg;
interface
uses xxm, Classes;
//$Rev$
//$Date$
type
TXxmFragmentClass=class of TXxmFragment;
TXxmFragmentRegistry=class(TObject)
private
Registry:TStringList;
public
constructor Create;
destructor Destroy; override;
procedure RegisterClass(FName:string;FType:TXxmFragmentClass);
function GetClass(FName:string):TXxmFragmentClass;
end;
var
XxmFragmentRegistry:TXxmFragmentRegistry;
const
XXmDefaultPage:string='default.xxm';
implementation
uses SysUtils;
{ TXxmFragmentRegistry }
constructor TXxmFragmentRegistry.Create;
begin
inherited Create;
Registry:=TStringList.Create;
Registry.Sorted:=true;
Registry.Duplicates:=dupIgnore;//dupError?setting?
Registry.CaseSensitive:=false;//setting?
end;
destructor TXxmFragmentRegistry.Destroy;
begin
//Registry.Clear;//?
Registry.Free;
inherited;
end;
procedure TXxmFragmentRegistry.RegisterClass(FName: string;
FType: TXxmFragmentClass);
begin
Registry.AddObject(FName,TObject(FType));
end;
function TXxmFragmentRegistry.GetClass(FName: string): TXxmFragmentClass;
var
i:integer;
begin
i:=Registry.IndexOf(FName);
if i=-1 then
if (FName='') or (FName[Length(FName)]='/') then
i:=Registry.IndexOf(FName+XxmDefaultPage)
else
i:=Registry.IndexOf(FName+'/'+XxmDefaultPage);
if i=-1 then Result:=nil else Result:=TXxmFragmentClass(Registry.Objects[i]);
end;
initialization
XxmFragmentRegistry:=TXxmFragmentRegistry.Create;
finalization
XxmFragmentRegistry.Free;
end.
|
unit unitHTMLStringsDisplayObject;
interface
uses Windows, Classes, SysUtils, Graphics, Forms, cmpMessageDisplay, OleCtrls, SHDocVw, ComObj, ActiveX, ShlObj, MSHTML, ShellAPI;
type
THTMLStringsDisplayObjectLink = class (TWinControlObjectLink)
private
fOrigObj : TStrings;
fRendering : boolean;
fNavigating : boolean;
fXanaLink : string;
procedure DoOnDocumentComplete (Sender: TObject; const pDisp: IDispatch; var URL: OleVariant);
procedure DoOnBeforeNavigate2 (Sender: TObject; const pDisp: IDispatch; var URL: OleVariant;
var Flags: OleVariant;
var TargetFrameName: OleVariant;
var PostData: OleVariant;
var Headers: OleVariant;
var Cancel: WordBool);
procedure DoOnNewWindow2 (Sender: TObject; var ppDisp: IDispatch; var Cancel: WordBool);
procedure RecalcHeight;
procedure LoadFromString (const st : string);
protected
class function DisplaysObject (obj : TObject) : Boolean; override;
procedure SetHeight(const Value: Integer); override;
procedure SetWidth(const Value: Integer); override;
procedure SetObj (const Value : TObject); override;
function GetBusy : boolean; override;
public
constructor Create (AOwner : TMessageDisplay; AObj : TObject; codepage : Integer); override;
destructor Destroy; override;
procedure Stop; override;
end;
implementation
uses cmpExWebBrowser;
resourcestring
rstCantSetHeight = 'Can''t set height of this object';
{ THTMLStringsDisplayObjectLink }
constructor THTMLStringsDisplayObjectLink.Create(AOwner: TMessageDisplay;
AObj: TObject; codepage : Integer);
var
ctrl : TExWebBrowser;
xanalink : string;
p : Integer;
begin
fOrigObj := AObj as TStrings;
ctrl := TEXWebBrowser.Create(AOwner.Owner);
inherited Create (AOwner, ctrl, codepage);
ctrl.OnDocumentComplete := DoOnDocumentComplete;
ctrl.UIProperties.EnableContextMenu := True;
ctrl.Width := AOwner.Parent.Width - Margin * 2 - GetSystemMetrics (SM_CXVSCROLL);
ctrl.Height := AOwner.Parent.Height;
if (fOrigObj.Count > 0) and (Copy (fOrigObj [0], 1, 16) = '<HTML><XanaLink>') then
begin
xanaLink := Copy (fOrigObj [0], 17, MaxInt);
p := Pos ('</XanaLink>', xanaLink);
if p > 0 then
xanaLink := Copy (xanaLink, 1, p - 1);
fXanaLink := xanaLink;
ctrl.OnNewWindow2 := DoOnNewWindow2;
ctrl.Navigate(xanaLink)
end
else
begin
ctrl.OnBeforeNavigate2 := DoOnBeforeNavigate2;
ctrl.OnNewWindow2 := DoOnNewWindow2;
ctrl.Offline := True;
LoadFromString (fOrigObj.Text)
end;
fRendering := True;
end;
destructor THTMLStringsDisplayObjectLink.Destroy;
begin
Obj.Free;
inherited;
end;
class function THTMLStringsDisplayObjectLink.DisplaysObject(
obj: TObject): Boolean;
var
s : TStrings;
i : Integer;
st, st1 : string;
begin
Result := False;
if obj is TStrings then
begin
s := TStrings (obj);
for i := 0 to s.Count - 1 do // Is it HTML ??
begin
st := Trim (s [i]);
if st = '' then // Ignore blank lines
Continue;
if Copy (st, 1, 2) = '<!' then // Ignore HTML Comments (eg. <!DOCTYPE
Continue;
st1 := Uppercase (Copy (st, 1, 5));
if st1 = '<HTML' then
Result := True;
if st1 = '<BODY' then
Result := True;
if st1 = '<HEAD' then
Result := True;
break
end
end
end;
procedure THTMLStringsDisplayObjectLink.DoOnBeforeNavigate2(
Sender: TObject; const pDisp: IDispatch; var URL, Flags, TargetFrameName,
PostData, Headers: OleVariant; var Cancel: WordBool);
var
urlStr : string;
begin
urlStr := url;
if urlStr <> 'about:blank' then
begin
cancel := True;
ShellExecute (HWND_DESKTOP, 'open', PChar (urlStr), nil, Nil, SW_NORMAL);
ctrl.Invalidate
end
end;
procedure THTMLStringsDisplayObjectLink.DoOnDocumentComplete(
Sender: TObject; const pDisp: IDispatch; var URL: OleVariant);
var
ctrl : TExWebBrowser;
doc : IHTMLDocument2;
elm : IHTMLElement2;
begin
try
ctrl := TExWebBrowser (obj);
if Supports (ctrl.Document, IHTMLDocument2, doc) then
begin
elm := doc.ActiveElement as IHTMLElement2; //body as IHTMLElement2;
if Assigned (elm) then
begin
ctrl.Width := elm.scrollWidth;
ctrl.Height := elm.scrollHeight;
Owner.RecalcBounds;
end
end
finally
fRendering := False;
end
end;
procedure THTMLStringsDisplayObjectLink.DoOnNewWindow2(Sender: TObject;
var ppDisp: IDispatch; var Cancel: WordBool);
var
ctrl : TExWebBrowser;
begin
ctrl := TExWebBrowser (obj);
cancel := not ctrl.UIProperties.OpenLinksInNewWindow
end;
function THTMLStringsDisplayObjectLink.GetBusy : boolean;
var
b : TExWebBrowser;
begin
// Application.ProcessMessages;
try
if Assigned (obj) then
begin
b := TExWebBrowser (obj);
result := b.Busy;
if result then
if b.ReadyState = READYSTATE_INTERACTIVE then
result := False;
end
else
result := False
except
result := True
end
end;
procedure THTMLStringsDisplayObjectLink.LoadFromString(const st: string);
begin
if fNavigating then exit;
fNavigating := True;
try
TExWebBrowser (obj).LoadFromString(st);
finally
fNavigating := False
end
end;
procedure THTMLStringsDisplayObjectLink.RecalcHeight;
var
ctrl : TExWebBrowser;
doc : IHTMLDocument2;
elm : IHTMLElement2;
begin
ctrl := TExWebBrowser (obj);
if Supports (ctrl.Document, IHTMLDocument2, doc) then
begin
elm := doc.body as IHTMLElement2;
if Assigned (elm) then
begin
ctrl.Height := elm.scrollHeight;
Owner.RecalcBounds
end
end
end;
procedure THTMLStringsDisplayObjectLink.SetHeight(const Value: Integer);
begin
end;
procedure THTMLStringsDisplayObjectLink.SetObj(const Value : TObject);
begin
fOrigObj := Value as TStrings;
Stop;
if fRendering or fNavigating or Busy then
begin
Windows.Beep (440, 10);
Exit
end;
ctrl.Width := Owner.MessageWidth;
ctrl.Height := Owner.ClientHeight;
fRendering := True;
LoadFromString (fOrigObj.Text);
end;
procedure THTMLStringsDisplayObjectLink.SetWidth(const Value: Integer);
begin
inherited;
RecalcHeight
end;
procedure THTMLStringsDisplayObjectLink.Stop;
var
n : Integer;
b : TExWebBrowser;
begin
if Busy then
if Assigned (obj) then
begin
b := TExWebBrowser (obj);
try
n := 0;
while b.ReadyState < READYSTATE_COMPLETE do
begin
Sleep (100);
if b.ReadyState = READYSTATE_INTERACTIVE then
Inc (n);
// Application.ProcessMessages;
if n > 2 then
break;
end;
if b.ReadyState = READYSTATE_INTERACTIVE then
b.Stop;
except
end;
Sleep (200);
end
end;
initialization
RegisterDisplayObjectLink (THTMLStringsDisplayObjectLink)
end.
|
{
This software is Copyright (c) 2016 by Doddy Hackman.
This is free software, licensed under:
The Artistic License 2.0
The Artistic License
Preamble
This license establishes the terms under which a given free software Package may be copied, modified, distributed, and/or redistributed. The intent is that the Copyright Holder maintains some artistic control over the development of that Package while still keeping the Package available as open source and free software.
You are always permitted to make arrangements wholly outside of this license directly with the Copyright Holder of a given Package. If the terms of this license do not permit the full use that you propose to make of the Package, you should contact the Copyright Holder and seek a different licensing arrangement.
Definitions
"Copyright Holder" means the individual(s) or organization(s) named in the copyright notice for the entire Package.
"Contributor" means any party that has contributed code or other material to the Package, in accordance with the Copyright Holder's procedures.
"You" and "your" means any person who would like to copy, distribute, or modify the Package.
"Package" means the collection of files distributed by the Copyright Holder, and derivatives of that collection and/or of those files. A given Package may consist of either the Standard Version, or a Modified Version.
"Distribute" means providing a copy of the Package or making it accessible to anyone else, or in the case of a company or organization, to others outside of your company or organization.
"Distributor Fee" means any fee that you charge for Distributing this Package or providing support for this Package to another party. It does not mean licensing fees.
"Standard Version" refers to the Package if it has not been modified, or has been modified only in ways explicitly requested by the Copyright Holder.
"Modified Version" means the Package, if it has been changed, and such changes were not explicitly requested by the Copyright Holder.
"Original License" means this Artistic License as Distributed with the Standard Version of the Package, in its current version or as it may be modified by The Perl Foundation in the future.
"Source" form means the source code, documentation source, and configuration files for the Package.
"Compiled" form means the compiled bytecode, object code, binary, or any other form resulting from mechanical transformation or translation of the Source form.
Permission for Use and Modification Without Distribution
(1) You are permitted to use the Standard Version and create and use Modified Versions for any purpose without restriction, provided that you do not Distribute the Modified Version.
Permissions for Redistribution of the Standard Version
(2) You may Distribute verbatim copies of the Source form of the Standard Version of this Package in any medium without restriction, either gratis or for a Distributor Fee, provided that you duplicate all of the original copyright notices and associated disclaimers. At your discretion, such verbatim copies may or may not include a Compiled form of the Package.
(3) You may apply any bug fixes, portability changes, and other modifications made available from the Copyright Holder. The resulting Package will still be considered the Standard Version, and as such will be subject to the Original License.
Distribution of Modified Versions of the Package as Source
(4) You may Distribute your Modified Version as Source (either gratis or for a Distributor Fee, and with or without a Compiled form of the Modified Version) provided that you clearly document how it differs from the Standard Version, including, but not limited to, documenting any non-standard features, executables, or modules, and provided that you do at least ONE of the following:
(a) make the Modified Version available to the Copyright Holder of the Standard Version, under the Original License, so that the Copyright Holder may include your modifications in the Standard Version.
(b) ensure that installation of your Modified Version does not prevent the user installing or running the Standard Version. In addition, the Modified Version must bear a name that is different from the name of the Standard Version.
(c) allow anyone who receives a copy of the Modified Version to make the Source form of the Modified Version available to others under
(i) the Original License or
(ii) a license that permits the licensee to freely copy, modify and redistribute the Modified Version using the same licensing terms that apply to the copy that the licensee received, and requires that the Source form of the Modified Version, and of any works derived from it, be made freely available in that license fees are prohibited but Distributor Fees are allowed.
Distribution of Compiled Forms of the Standard Version or Modified Versions without the Source
(5) You may Distribute Compiled forms of the Standard Version without the Source, provided that you include complete instructions on how to get the Source of the Standard Version. Such instructions must be valid at the time of your distribution. If these instructions, at any time while you are carrying out such distribution, become invalid, you must provide new instructions on demand or cease further distribution. If you provide valid instructions or cease distribution within thirty days after you become aware that the instructions are invalid, then you do not forfeit any of your rights under this license.
(6) You may Distribute a Modified Version in Compiled form without the Source, provided that you comply with Section 4 with respect to the Source of the Modified Version.
Aggregating or Linking the Package
(7) You may aggregate the Package (either the Standard Version or Modified Version) with other packages and Distribute the resulting aggregation provided that you do not charge a licensing fee for the Package. Distributor Fees are permitted, and licensing fees for other components in the aggregation are permitted. The terms of this license apply to the use and Distribution of the Standard or Modified Versions as included in the aggregation.
(8) You are permitted to link Modified and Standard Versions with other works, to embed the Package in a larger work of your own, or to build stand-alone binary or bytecode versions of applications that include the Package, and Distribute the result without restriction, provided the result does not expose a direct interface to the Package.
Items That are Not Considered Part of a Modified Version
(9) Works (including, but not limited to, modules and scripts) that merely extend or make use of the Package, do not, by themselves, cause the Package to be a Modified Version. In addition, such works are not considered parts of the Package itself, and are not subject to the terms of this license.
General Provisions
(10) Any use, modification, and distribution of the Standard or Modified Versions is governed by this Artistic License. By using, modifying or distributing the Package, you accept this license. Do not use, modify, or distribute the Package, if you do not accept this license.
(11) If your Modified Version has been derived from a Modified Version made by someone other than you, you are nevertheless required to ensure that your Modified Version complies with the requirements of this license.
(12) This license does not grant you the right to use any trademark, service mark, tradename, or logo of the Copyright Holder.
(13) This license includes the non-exclusive, worldwide, free-of-charge patent license to make, have made, use, offer to sell, sell, import and otherwise transfer the Package with respect to any patent claims licensable by the Copyright Holder that are necessarily infringed by the Package. If you institute patent litigation (including a cross-claim or counterclaim) against any party alleging that the Package constitutes direct or contributory patent infringement, then this Artistic License to you shall terminate on the date that such litigation is filed.
(14) Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
}
// Unit : DH Informator
// Version : 0.2
// (C) Doddy Hackman 2016
unit DH_Informator;
interface
uses Windows, SysUtils, WinInet;
type
T_DH_Informator = class
private
public
constructor Create;
destructor Destroy; override;
function get_os(): string;
function get_username(): string;
function get_computer_name(): string;
function get_ip_and_country(): string;
function get_my_ip(): string;
function get_my_country(): string;
function get_active_window(): string;
end;
implementation
constructor T_DH_Informator.Create;
begin
inherited Create;
//
end;
destructor T_DH_Informator.Destroy;
begin
inherited Destroy;
end;
// Functions auxiliars
const
user_agent =
'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:25.0) Gecko/20100101 Firefox/25.0';
// Edit
function toma(const pagina: string): UTF8String;
// Credits : Based on http://www.scalabium.com/faq/dct0080.htm
// Thanks to www.scalabium.com
var
nave1: HINTERNET;
nave2: HINTERNET;
check: DWORD;
code_uno: UTF8String;
code_dos: array [0 .. 1023] of byte;
code_final: string;
begin
if not(pagina = '') then
begin
try
begin
code_final := '';
Result := '';
nave1 := InternetOpen(user_agent, INTERNET_OPEN_TYPE_PRECONFIG,
nil, nil, 0);
nave2 := InternetOpenUrl(nave1, Pchar(pagina), nil, 0,
INTERNET_FLAG_RELOAD, 0);
repeat
begin
InternetReadFile(nave2, @code_dos, SizeOf(code_dos), check);
SetString(code_uno, PAnsiChar(@code_dos[0]), check);
code_final := code_final + code_uno;
end;
until check = 0;
InternetCloseHandle(nave2);
InternetCloseHandle(nave1);
Result := code_final;
end;
except
Result := 'Error';
end;
end
else
begin
Result := 'Error';
end;
end;
function regex(text: String; deaca: String; hastaaca: String): String;
begin
Delete(text, 1, AnsiPos(deaca, text) + Length(deaca) - 1);
SetLength(text, AnsiPos(hastaaca, text) - 1);
Result := text;
end;
// Functions
function T_DH_Informator.get_active_window(): string;
var
window: THandle;
title: string;
limit: Integer;
begin
try
begin
window := GetForegroundWindow;
limit := GetWindowTextLength(window) + 1;
SetLength(title, limit);
GetWindowText(window, Pchar(title), limit);
Result := title;
end;
except
begin
Result := '[-] Error';
end;
end;
end;
function T_DH_Informator.get_ip_and_country(): string;
var
code: string;
ip, country, flag, link_flag: string;
begin
code := toma('http://www.ip-tracker.org/locator/ip-lookup.php');
ip := regex(code, 'class="inputiny" id="txtOne" value="', '" size="80"');
country := regex(code, '<th>Country:</th><td> ', ' <img');
flag := regex(code, 'images/ip-flags/', '.png');
link_flag := 'http://www.ip-tracker.org/images/ip-flags/' + flag + '.png';
if (ip = '') then
begin
ip := '?';
end;
if (country = '') then
begin
country := '?';
end;
if (flag = '') then
begin
flag := '?';
end;
if (link_flag = '') then
begin
link_flag := '?';
end;
Result := '[ip]' + ip + '[ip][country]' + country + '[country][flag]' + flag +
'[flag][link_flag]' + link_flag + '[link_flag]';
end;
function T_DH_Informator.get_my_ip(): string;
var
code: string;
ip: string;
begin
code := toma('http://www.geoplugin.net/json.gp?ip=');
ip := regex(code, '"geoplugin_request":"', '",');
if not(ip = '') then
begin
Result := ip;
end
else
begin
Result := '?';
end;
end;
function T_DH_Informator.get_my_country(): string;
var
code: string;
ip: string;
country: string;
begin
ip := get_my_ip();
if not(ip = '?') then
begin
code := toma('http://www.geoplugin.net/json.gp?ip=' + ip);
country := regex(code, '"geoplugin_countryName":"', '",');
if not(country = '') then
begin
Result := country;
end
else
begin
Result := '?';
end;
end;
end;
function T_DH_Informator.get_os(): string;
var
os: string;
begin
os := '';
if (Win32MajorVersion = 5) and (Win32MinorVersion = 1) then
begin
os := 'Windows XP';
end
else if (Win32MajorVersion = 6) and (Win32MinorVersion = 0) then
begin
os := 'Windows Vista';
end
else if (Win32MajorVersion = 6) and (Win32MinorVersion = 1) then
begin
os := 'Windows 7';
end
else if (Win32MajorVersion = 6) and (Win32MinorVersion = 2) then
begin
os := 'Windows 8';
end
else
begin
os := 'Unknown';
end;
Result := os;
end;
function T_DH_Informator.get_username(): string;
var
username: string;
begin
username := GetEnvironmentVariable('USERNAME');
if not(username = '') then
begin
Result := username;
end
else
begin
Result := 'Error';
end;
end;
function T_DH_Informator.get_computer_name(): string;
var
name: string;
begin
name := GetEnvironmentVariable('COMPUTERNAME');
if not(name = '') then
begin
Result := name;
end
else
begin
Result := 'Error';
end;
end;
end.
// The End ?
|
unit DAO.Cadastro;
interface
uses DAO.Base, Model.Cadastro, Generics.Collections, System.Classes;
type
TCadastroDAO = class(TDAO)
public
function Insert(aCadastro: TCadastro): Boolean;
function Update(aCadastro: TCadastro): Boolean;
function Delete(iCodigo: Integer): Boolean;
function FindByFilter(sFiltro: String): TObjectList<TCadastro>;
end;
const
TABLENAME = 'cad_cadastro';
implementation
uses System.SysUtils, FireDAC.Comp.Client, Data.DB;
function TCadastroDAO.Insert(aCadastro: TCadastro): Boolean;
var
sSQL : String;
begin
Result := False;
aCadastro.Codigo := GetKeyValue(TABLENAME, 'ID_CADASTRO');
sSQL := 'INSERT INTO ' + TABLENAME + ' (' +
'ID_CADASTRO, COD_PESSOA, NOM_NOME_RAZAO, NOM_FANTASIA, DES_TIPO_DOC, NUM_CPF, NUM_CNPJ, NUM_RG, DES_EXPEDIDOR, UF_EXPEDIDOR, ' +
'DAT_EMISSAO_RG, DAT_NASCIMENTO, NOM_PAI, NOM_MAE, DES_NATURALIDADE, UF_NATURALIDADE, NUM_SUFRAMA, NUM_CNH, NUM_CNAE, NUM_CRT, ' +
'NUM_REGISTRO_CNH, UF_CNH, DAT_VALIDADE_CNH, DES_CATEGORIA_CNH, DAT_PRIMEIRA_CNH, NUM_PIS, NUM_CTPS, NUM_SERIE_CTPS, UF_CTPS, ' +
'DES_ESTADO_CIVIL, NUM_TITULO_ELEITOR, NUM_RESERVISTA, DAT_CADASTRO, COD_USUARIO_PROPRIETARIO, COD_SEXO, ID_STATUS, DES_LOG) ' +
'VALUES ' +
'(pID_CADASTRO, pCOD_PESSOA, pNOM_NOME_RAZAO, pNOM_FANTASIA, pDES_TIPO_DOC, pNUM_CPF, pNUM_CNPJ, pNUM_RG, pDES_EXPEDIDOR, ' +
'pUF_EXPEDIDOR, pDAT_EMISSAO_RG, pDAT_NASCIMENTO, pNOM_PAI, pNOM_MAE, pDES_NATURALIDADE, pUF_NATURALIDADE, pNUM_SUFRAMA, ' +
'pNUM_CNH, pNUM_CNAE, pNUM_CRT, pNUM_REGISTRO_CNH, pUF_CNH, pDAT_VALIDADE_CNH, pDES_CATEGORIA_CNH, pDAT_PRIMEIRA_CNH, ' +
'pNUM_PIS, NUM_CTPS, pNUM_SERIE_CTPS, pUF_CTPS, pDES_ESTADO_CIVIL, pNUM_TITULO_ELEITOR, pNUM_RESERVISTA, pDAT_CADASTRO, ' +
'pCOD_USUARIO_PROPRIETARIO, pCOD_SEXO, pID_STATUS, pDES_LOG);';
Connection.ExecSQL(sSQL,[aCadastro.Codigo, aCadastro.Pessoa, aCadastro.Nome, aCadastro.Alias, aCadastro.Nascimento,
aCadastro.NomePai, aCadastro.NomeMae, aCadastro.TipoDoc, aCadastro.CPFCNPJ, aCadastro.RG,
aCadastro.Expedidor, aCadastro.UFRG, aCadastro.DataRG, aCadastro.Naturalidade, aCadastro.UFNaturalidade,
aCadastro.CNH, aCadastro.RegistroCNH, aCadastro.ValidadeCNH, aCadastro.CategoriaCNH,
aCadastro.PrimeiraCNH, aCadastro.PIS, aCadastro.CTPS, aCadastro.SerieCTPS, aCadastro.UFCTPS,
aCadastro.UFCNH, aCadastro.EstadoCivil, aCadastro.TituloEleitor, aCadastro.ZonaEleitoral,
aCadastro.SecaoEleitoral, aCadastro.MunicipioEleitoral, aCadastro.UFEleitoral,
aCadastro.Reservista, aCadastro.Sexo, aCadastro.CNAE, aCadastro.CRT,
aCadastro.SUFRAMA, aCadastro.Responsavel, aCadastro.Cadastro,
aCadastro.Usuario, aCadastro.Status, aCadastro.Log],
[ftInteger, ftInteger, ftString, ftstring, ftDate, ftString, ftString, ftString, ftString, ftString,
ftString, ftString, ftDate, ftString, ftString, ftString, ftString, ftDate, ftString, ftString,
ftDate, ftString, ftString, ftString, ftString, ftString, ftString, ftstring, ftstring, ftstring,
ftstring, ftString, ftInteger, ftString, ftInteger, ftString, ftInteger, ftDateTime, ftInteger,
ftInteger, ftString]);
Result := True;
end;
function TCadastroDAO.Update(aCadastro: TCadastro): Boolean;
var
sSQL : String;
begin
Result := False;
sSQL := 'UPDATE ' + TABLENAME + 'SET ' +
'COD_PESSOA = pCOD_PESSOA, NOM_NOME_RAZAO = pNOM_NOME_RAZAO, NOM_FANTASIA = pNOM_FANTASIA, DES_TIPO_DOC = pDES_TIPO_DOC, ' +
'NUM_CPF = pNUM_CPF, NUM_CNPJ = pNUM_CNPJ, NUM_RG = pNUM_RG, DES_EXPEDIDOR = pDES_EXPEDIDOR, UF_EXPEDIDOR = pUF_EXPEDIDOR, ' +
'DAT_EMISSAO_RG = pDAT_EMISSAO_RG, DAT_NASCIMENTO = pDAT_NASCIMENTO, NOM_PAI = pNOM_PAI, NOM_MAE = pNOM_MAE, ' +
'DES_NATURALIDADE = pDES_NATURALIDADE, UF_NATURALIDADE = pUF_NATURALIDADE, NUM_SUFRAMA = pNUM_SUFRAMA, NUM_CNH = pNUM_CNH, ' +
'NUM_CNAE = pNUM_CNAE, NUM_CRT = pNUM_CRT, NUM_REGISTRO_CNH = pNUM_REGISTRO_CNH, UF_CNH = pUF_CNH, ' +
'DAT_VALIDADE_CNH = pDAT_VALIDADE_CNH, DES_CATEGORIA_CNH = pDES_CATEGORIA_CNH, DAT_PRIMEIRA_CNH = pDAT_PRIMEIRA_CNH, ' +
'NUM_PIS = pNUM_PIS, NUM_CTPS = pNUM_CTPS, NUM_SERIE_CTPS = pNUM_SERIE_CTPS, UF_CTPS = pUF_CTPS, ' +
'DES_ESTADO_CIVIL = pDES_ESTADO_CIVIL, NUM_TITULO_ELEITOR = pNUM_TITULO_ELEITOR, NUM_RESERVISTA = pNUM_RESERVISTA, ' +
'DAT_CADASTRO = pDAT_CADASTRO, COD_USUARIO_PROPRIETARIO = pCOD_USUARIO_PROPRIETARIO, COD_SEXO = pCOD_SEXO, ' +
'ID_STATUS = pID_STATUS, DES_LOG = pDES_LOG ' +
'WHERE ' +
'ID_CADASTRO = pID_CADASTRO;';
Connection.ExecSQL(sSQL,[aCadastro.Pessoa, aCadastro.Nome, aCadastro.Alias, aCadastro.Nascimento,
aCadastro.NomePai, aCadastro.NomeMae, aCadastro.TipoDoc, aCadastro.CPFCNPJ, aCadastro.RG,
aCadastro.Expedidor, aCadastro.UFRG, aCadastro.DataRG, aCadastro.Naturalidade, aCadastro.UFNaturalidade,
aCadastro.CNH, aCadastro.RegistroCNH, aCadastro.ValidadeCNH, aCadastro.CategoriaCNH,
aCadastro.PrimeiraCNH, aCadastro.PIS, aCadastro.CTPS, aCadastro.SerieCTPS, aCadastro.UFCTPS,
aCadastro.UFCNH, aCadastro.EstadoCivil, aCadastro.TituloEleitor, aCadastro.ZonaEleitoral,
aCadastro.SecaoEleitoral, aCadastro.MunicipioEleitoral, aCadastro.UFEleitoral,
aCadastro.Reservista, aCadastro.Sexo, aCadastro.CNAE, aCadastro.CRT,
aCadastro.SUFRAMA, aCadastro.Responsavel, aCadastro.Cadastro,
aCadastro.Usuario, aCadastro.Status, aCadastro.Log, aCadastro.Codigo],
[ftInteger, ftString, ftstring, ftDate, ftString, ftString, ftString, ftString, ftString,
ftString, ftString, ftDate, ftString, ftString, ftString, ftString, ftDate, ftString, ftString,
ftDate, ftString, ftString, ftString, ftString, ftString, ftString, ftstring, ftstring, ftstring,
ftstring, ftString, ftInteger, ftString, ftInteger, ftString, ftInteger, ftDateTime, ftInteger,
ftInteger, ftString, ftInteger]);
Result := True;
end;
function TCadastroDAO.Delete(iCodigo: Integer): Boolean;
var
sSQL : String;
begin
Result := False;
sSQL := 'DELETE FROM ' + TABLENAME + 'WHERE ID_CADASTRO = pID_CADASTRO;';
Connection.ExecSQL(sSQL,[iCodigo],[ftInteger]);
Result := True;
end;
function TCadastroDAO.FindByFilter(sFiltro: String): TObjectList<TCadastro>;
var
FDQuery: TFDQuery;
cadastros: TObjectList<TCadastro>;
begin
FDQuery := TFDQuery.Create(nil);
try
FDQuery.Connection := Connection;
FDQuery.SQL.Clear;
FDQuery.SQL.Add('SELECT * FROM ' + TABLENAME);
if not sFiltro.IsEmpty then
begin
FDQuery.SQL.Add('WHERE ' + sFiltro);
end;
FDQuery.Open();
cadastros := TObjectList<TCadastro>.Create();
while not FDQuery.Eof do
begin
{cadastros.Add(TCadastro.Create(FDQuery.FieldByName('ID_CADASTRO').AsInteger, FDQuery.FieldByName('COD_PESSOA').AsInteger,
FDQuery.FieldByName('NOM_NOME_RAZAO').AsString, FDQuery.FieldByName('NOM_FANTASIA').AsString,
FDQuery.FieldByName('DES_TIPO_DOC').AsString, FDQuery.FieldByName('NUM_CPF_CNPJ').AsString,
FDQuery.FieldByName('NUM_CNPJ').AsString, FDQuery.FieldByName('NUM_RG').AsString,
FDQuery.FieldByName('DES_EXPEDIDOR').AsString, FDQuery.FieldByName('UF_EXPEDIDOR').AsString,
FDQuery.FieldByName('DAT_EMISSAO_RG').AsDateTime, FDQuery.FieldByName('DAT_NASCIMENTO').AsDateTime,
FDQuery.FieldByName('NOM_PAI').AsString, FDQuery.FieldByName('NOM_MAE').AsString,
FDQuery.FieldByName('DES_NATURALIDADE').AsString, FDQuery.FieldByName('UF_NATURALIDADE').AsString,
FDQuery.FieldByName('NUM_SUFRAMA').AsString, FDQuery.FieldByName('NUM_CNH').AsString,
FDQuery.FieldByName('NUM_CNAE').AsString, FDQuery.FieldByName('NUM_CRT').AsInteger,
FDQuery.FieldByName('NUM_REGISTRO_CNH').AsString, FDQuery.FieldByName('UF_CNH').AsString,
FDQuery.FieldByName('DAT_VALIDADE_CNH').AsDateTime, FDQuery.FieldByName('DES_CATEGORIA_CNH').AsString,
FDQuery.FieldByName('DAT_PRIMEIRA_CNH').AsDateTime, FDQuery.FieldByName('NUM_PIS').AsString,
FDQuery.FieldByName('NUM_CTPS').AsString, FDQuery.FieldByName('NUM_SERIE_CTPS').AsString,
FDQuery.FieldByName('UF_CTPS').AsString, FDQuery.FieldByName('DES_ESTADO_CIVIL').AsString,
FDQuery.FieldByName('NUM_TITULO_ELEITOR').AsString, FDQuery.FieldByName('NUM_RESERVISTA').AsString,
FDQuery.FieldByName('DAT_CADASTRO').AsDateTime, FDQuery.FieldByName('COD_USUARIO_PROPRIETARIO').AsInteger,
FDQuery.FieldByName('COD_SEXO').AsInteger, FDQuery.FieldByName('ID_STATUS').AsInteger,
FDQuery.FieldByName('DES_LOG').AsString));}
FDQuery.Next;
end;
finally
FDQuery.Free;
end;
Result := cadastros;
end;
end.
|
unit Unit2;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls, Buttons;
type
TCall = record
Date: TDateTime;
Time, Price, Number, Code: word;
City: string[30];
end;
ATCall = array of TCall;
AByte = array of byte;
TAllMake = class
ABase: ATCall;
FBase: file of TCall;
N: byte;
Memo: TMemo;
constructor Create(Memo1: TMemo);
procedure OpenCreate(OpenDialog: TOpenDialog); // +
procedure Save(SaveDialog: TSaveDialog); // +
procedure Add(EDate, ECity, ETime, EPrice, ENumber, ECode: TLabeledEdit); // -
procedure Remove(Time: word);
function LineSearch(Text: string; i: byte = 0): AByte; // +
function BinarySearch(Time: word): AByte;
procedure QuickSort; // -
procedure MergeSort;
procedure PrintMemo(b: array of byte); overload;
procedure PrintMemo(); overload;
end;
implementation
constructor TAllMake.Create;
begin
Memo := Memo1;
SetLength(ABase, 0);
end;
procedure TAllMake.PrintMemo(b: array of byte);
var
i: word;
begin
try
if Length(b) <> 0 then
for i := 0 to High(b) do
Memo.Lines.Add('Дата:' + DateToStr(ABase[b[i]].Date) + ' Город: ' + ABase[b[i]].City + ' Время: ' + IntToStr(ABase[b[i]].Time));
except
else begin
ShowMessage('Это не Высоцкий! Укол в шею не поможет!');
Exit;
end;
end;
end;
procedure TAllMake.PrintMemo;
var
i: word;
begin
try
if Length(ABase) <> 0 then
for i := 0 to High(ABase) do
Memo.Lines.Add('Дата:' + DateToStr(ABase[i].Date) + ' Город: ' + ABase[i].City + ' Время: ' + IntToStr(ABase[i].Time));
except
else begin
ShowMessage('Это не Высоцкий! Укол в шею не поможет!');
Exit;
end;
end;
end;
procedure TAllMake.OpenCreate;
begin
if OpenDialog.Execute then
if FileExists(OpenDialog.FileName) then
begin
AssignFile(FBase, OpenDialog.FileName);
Reset(FBase);
//кусок кода, вызывающий магию, для отображения содержания файла в текстовое окошечко.
N := 0;
Memo.Clear;
SetLength(ABase, FileSize(FBase));
while N < FileSize(FBase) do
begin
Read(FBase, ABase[N]);
PrintMemo([N]);
Inc(N);
end
{ begin
SetLength(ABase, Length(ABase) + 1);
Read(FBase, ABase[High(ABase)]);
// MemoPrint (ABase[High(ABase)], Memo);// не забыть допилить или перепилить. Возможно так: MemoPrint([N])
N := N + 1;
end;
PrintMemo;}
end
else
begin
AssignFile(FBase, OpenDialog.FileName);
Rewrite(FBase);
end;
end;
procedure TAllMake.Save(SaveDialog: TSaveDialog);
var
i: byte;
begin
if Length(ABase) <> 0 then
if SaveDialog.Execute then
begin
AssignFile(FBase, SaveDialog.FileName);
Rewrite(FBase);
for i := 0 to High(ABase) do
Write(FBase, ABase[i]);
CloseFile(FBase);
end;
end;
procedure TAllMake.Add(EDate, ECity, ETime, EPrice, ENumber, ECode: TLabeledEdit); // положить на форму кнопки, подумать головой и... сесть...
begin
try
SetLength(ABase, Length(ABase) + 1);
with ABase[High(ABase)] do
begin
Date := StrToDate(EDate.Text);
City := ECity.Text;
Time := StrToInt(ETime.Text);
Price := StrToInt(EPrice.Text);
Number := StrToInt(ENumber.Text);
Code := StrToInt(ECode.Text);
PrintMemo ([High(ABase)]);
end;
except
else begin
ShowMessage('Что-то случилось. Закройте, забейте, забудьте. А лучше подышите воздухом: ведь он такой ванильный!');
end;
end;
end;
procedure TAllMake.Remove(Time: word);
var
i, j: word;
b: Abyte;
begin
b := BinarySearch(Time);
if Length(b) <> 0 then
begin
j := 0;
for i := b[j] to High(ABase) do
begin
ABase[i-j] := ABase[i];
if b[j] = i then
Inc(j);
end;
SetLength(ABase, Length(ABase)-j);
Memo.Clear;
PrintMemo;
end;
end;
function TAllMake.LineSearch(Text: string; i: byte = 0): AByte;
{var
i, j: word;}
begin
// получим вечный цикл, если отправим i > High(ABase)
for i := i to High(ABase) do // интересный взгляд на переменные.
if (ABase[i].City = Text) then
begin
SetLength(Result, Length(Result) + 1);
Result[High(Result)] := i;
end;
end;
function TAllMake.BinarySearch(Time: word): Abyte; // возвращает номер элемента массива или -1, если такого элемента нет.
var
i: word;
function Recursion(b, e: byte): byte;
var
m: byte;
begin
if b < e then
begin
m := b + (e - b) div 2; // ??? ???: m := (e + b) div 2; ?? ???????? ??????: "????? ??? ?????????"
// ?????: "????? b ? e ??????, ??? ??? ?? ????? ?????? ?????? ?????? ?? ?????????? ??? ??? ???????"
if Time <= ABase[m].Time then
Result := Recursion(b, m)
else
Result := Recursion(m + 1, e);
end
else
Result := b;
end;
begin
// тут не хватает копипаста вызова функции сортировки массива a[].
MergeSort; // теперь хватает
//
i := Recursion(0, High(ABase));
while ABase[i].Time = Time do
begin
SetLength(Result, Length(Result) + 1);
Result[High(Result)] := i;
Inc(i);
end;
// Result := Recursion(0, High(ABase));
// if ABase[Result].Time <> Time then
// Memo.Lines.Add('Нет такого');
end;
procedure TAllMake.QuickSort;
procedure Sort(b, e: word);
var
i, j, x: word;
w: TCall;
begin
i := b;
j := e;
x := ABase[(b + e) div 2].Time;
Repeat
while ABase[i].Time < x do
Inc(i);
while ABase[j].Time > x do
Dec(j);
if i <= j then // зачем эта проверка?
begin
w := ABase[i];
ABase[i] := ABase[j];
ABase[j] := w;
Inc(i);
Dec(j);
end;
until i > j;
if b < j then
Sort(b, j);
if i < e then
Sort(i, e);
end; //sort
begin
Sort(0, Length(ABase)-1);
end;
procedure TAllMake.MergeSort;
var
Atmp: ATCall; //Временный буфер
//Слияние
procedure merge(L, Spl, R : word);
var
i, j, k : word;
begin
i := L;
j := Spl + 1;
k := 0;
//Выбираем меньший из первых и добавляем в tmp
while (i <= Spl) and (j <= R) do
begin
if ABase[i].Time > ABase[j].Time then
begin
Atmp[k] := ABase[j];
Inc(j);
end
else
begin
Atmp[k] := ABase[i];
Inc(i);
end;
Inc(k);
end;
//Просто дописываем в tmp оставшиеся эл-ты
if i <= Spl then //Если первая часть не пуста
for j := i to Spl do
begin
Atmp[k] := ABase[j];
Inc(k);
end
else //Если вторая часть не пуста
for i := j to R do
begin
Atmp[k] := ABase[i];
Inc(k);
end;
//Перемещаем из tmp в arr
Move(Atmp[0], ABase[L], k*SizeOf(TCall));
end;
//Сортировка
procedure sort(L, R : word);
var
splitter : word;
begin
//Массив из 1-го эл-та упорядочен по определению
if L >= R then Exit;
splitter := (L + R) div 2; //Делим массив пополам
sort(L, splitter); //Сортируем каждую
sort(splitter + 1, R); //часть по отдельности
merge(L, splitter, R); //Производим слияние
end;
//Основная часть процедуры сортировки
begin
SetLength(Atmp, Length(ABase));
sort(0, Length(ABase) - 1);
SetLength(Atmp, 0);
end;
{ // || ||
procedure TAllMake.SortSlip; //пиление в процессе ||********************||
// ''\/\/\/\/\/\/\/\/\/\/''
procedure Slip(b, m, e: word);
var
c: ATCall;
i, j, k: word;
begin
i := b;
k := 0;
j := m + 1;
SetLength(c, e - b + 1);
while (i <= m) and (j <= e) do
if ABase[i].Time < ABase[j].Time then
begin c[k] := ABase[i]; Inc(i); Inc(k); end
else
begin c[k] := ABase[j]; Inc(j); Inc(k) end;
while i <= m do
begin c[k] := ABase[i]; Inc(i); Inc(k) end;
while j <= e do
begin c[k] := ABase[j]; Inc(j); Inc(k) end;
k := 0;
for i := b to e do
begin
Inc(k);
ABase[i] := c[k];
end;
end;
procedure Recursion (b, e: word);
var
m: word;
begin
if b <> e then
begin
m := (b + e) div 2;
Recursion(b, m);
Recursion(m + 1, e);
Slip(b, m, e);
end;
end;
begin
Recursion(0, High(ABase));
PrintMemo;
end; }
{
//////////////////////*temporatary*//////////////////////
function LineSearch(a: array of string[30]; Text: shortstring; i: byte = 0): boolean; overload
begin
SetLength(a, Length(a) + 1);
a[High(a)] := Text;
while a[i] <> Text do
Inc(i);
if i = High(a) then
begin
Length(a, Length(a) - 1);
Result := true;
end
else
Result := false;
end;
procedure SpecZadanie;
var
ACity: array of shortstring;
i: byte;
begin
SetLength(ACity, 1);
ACity[0] := ABase[0].City;
for i := 1 to High(ABase) do
if LineSearch(ACity, ABase[i].City) then
begin
SetLength(a, Length(a) + 1);
ACity[High(ACity)] := ABase[i].City;
PrintMemo(LineSearch(ABase[i].City, i));
end;
end; }
end.
|
unit uMain;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, System.UITypes, Vcl.Graphics, Vcl.Controls, Vcl.Forms,
Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, System.Actions, Vcl.ActnList,
Vcl.Menus, Vcl.StdActns, Vcl.ComCtrls, DateUtils, Vcl.ToolWin,
System.ImageList, Vcl.ImgList, Vcl.VirtualImageList, Vcl.BaseImageCollection,
Vcl.ImageCollection;
const
MAX_LENGTH_PATH = 55;
MAX_LINES_COUNT = 500;
MAX_AGE = 1440;
DEL_INTERVAL = 10;
DEF_PREF = 'log_';
type
TMForm = class(TForm)
btnStartStop: TButton;
btnReloadIni: TButton;
Panel1: TPanel;
triIcon: TTrayIcon;
pmTrayMenu: TPopupMenu;
alComm: TActionList;
acShowHide: TAction;
N1: TMenuItem;
acExit: TAction;
N2: TMenuItem;
N3: TMenuItem;
Panel2: TPanel;
btnHide: TButton;
MMenu: TMainMenu;
N4: TMenuItem;
N5: TMenuItem;
N6: TMenuItem;
acAbout: TAction;
N7: TMenuItem;
reLog: TRichEdit;
tmrClear: TTimer;
acPauseStart: TAction;
ImageCollection1: TImageCollection;
VirtualImageList1: TVirtualImageList;
ToolBar1: TToolBar;
ToolButton1: TToolButton;
ToolButton2: TToolButton;
acReReadSett: TAction;
ToolButton3: TToolButton;
acStop: TAction;
ToolButton4: TToolButton;
sbBar: TStatusBar;
N8: TMenuItem;
N9: TMenuItem;
acWriteLog: TAction;
procedure FormCreate(Sender: TObject);
procedure acExitExecute(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure tmrClearTimer(Sender: TObject);
procedure acPauseStartExecute(Sender: TObject);
procedure acShowHideExecute(Sender: TObject);
procedure acStopExecute(Sender: TObject);
procedure acReReadSettExecute(Sender: TObject);
procedure acAboutExecute(Sender: TObject);
procedure acWriteLogExecute(Sender: TObject);
private
{ Private declarations }
function ReadIniFiles: Boolean;
function GetInfo(sFileName: string): string;
procedure CreateDelTread;
function MinToTime(iMin: Integer): string;
procedure WriteToFile(sPath, sText: string);
procedure WriteLogFile(sText: string);
public
{ Public declarations }
procedure AddToLog(sValue: string; bAddDateTime: Boolean = True; fsStyle:
TFontStyles = []; Color: Integer = 0);
function IntToBool(iValue: Integer): Boolean;
end;
type
TAppSettings = record
sIniPath: string;
bShowWindows: Boolean;
bWriteLog: Boolean;
sPathLog: string;
sLogPref: string;
iStartInterval: Integer;
iDelInterval: Integer;
bShowConsole: Boolean;
end;
type
TDirSettings = record
Name: string;
Filter: string;
Age: Integer;
end;
type
TFilesSettings = record
Values: TStringList;
Settings: array of TDirSettings;
end;
TDelThread = class(TThread)
private
{ Private declarations }
procedure DelFiles(sPath, sFilter: string; iAge: Integer);
procedure WriteCount(iNum, iCount: Integer);
protected
procedure Execute; override;
end;
var
MForm: TMForm;
AppSett: TAppSettings;
FilesSett: TFilesSettings;
bSecondLoad: Boolean;
DelThread: TDelThread;
bPause: Boolean;
bStop: Boolean;
bLogExist: Boolean;
slToDel: TStringList;
implementation
uses
uDataModule, uAbout;
{$R *.dfm}
procedure TDelThread.DelFiles(sPath, sFilter: string; iAge: Integer);
var
j, iDelCount, Attr: Integer;
tsFA: TDateTime;
iMinuts: Integer;
sSumPath: string;
iDel, iNotDel: Integer;
function GetDirTime(const aPath: string): TDateTime;
var
H: Integer;
F: TFileTime;
S: TSystemTime;
begin
H := CreateFile(PChar(aPath), $0080, 0, nil, OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS, 0);
if H <> -1 then
begin
GetFileTime(H, @F, nil, nil);
FileTimeToLocalFileTime(F, F);
FileTimeToSystemTime(F, S);
Result := SystemTimeToDateTime(S);
CloseHandle(H);
end
else
Result := -1;
end;
function IsDirEmpty(const aPath: string): Boolean;
var
fs: TSearchRec;
aaPath: string;
begin
Result := True;
aaPath := IncludeTrailingPathDelimiter(aPath);
if FindFirst(aaPath + '*.*', faAnyFile, fs) = 0 then
repeat
if (fs.Name <> '.') and (fs.Name <> '..') then
begin
Result := False;
FindClose(fs);
Exit;
end;
until FindNext(fs) <> 0;
FindClose(fs);
end;
procedure EnumFiles(const aPath, aFilter: string; const aAttr: Integer; aSl:
TStringList);
var
Sr: TSearchRec;
Attr: Integer;
sPath, sExt: string;
begin
// Путь к папке. Добавляем к пути завершающий слеш, если его нет.
sPath := IncludeTrailingPathDelimiter(aPath);
// Добавляем атрибут папок.
Attr := aAttr or faDirectory;
try
if FindFirst(sPath + '*', Attr, Sr) = 0 then
repeat
// Если найдена папка, то выполняем для неё рекурсивный вызов.
if faDirectory = (Sr.Attr and faDirectory) then
begin
// Пропускаем ссылки на текущий и родительский каталоги.
if (Sr.Name = '.') or (Sr.Name = '..') then
Continue;
// Рекурсивный вызов.
tsFA := GetDirTime(Sr.Name);
iMinuts := MinutesBetween(tsFA, Now);
// Отсеиваем каталоги "моложе" чем iAge.
if (iMinuts >= iAge) then
begin
if not IsDirEmpty(sPath + Sr.Name) then
EnumFiles(sPath + Sr.Name + '\', aFilter, aAttr, aSl);
aSl.Add(IncludeTrailingPathDelimiter(sPath + Sr.Name));
end;
Continue;
end;
// Расширение найденного файла.
sExt := AnsiUpperCase(ExtractFileExt(Sr.Name));
// Принадлежит ли расширение списку заданных расширений.
sFilter := Copy(sFilter, Pos('.', sFilter), Length(sFilter) - Pos('.',
sFilter) + 1);
if (sExt <> AnsiUpperCase(sFilter)) and (Pos('*', sFilter) = 0) then
Continue;
// Добавляем найденный файл в список.
if FileExists(Sr.Name) then
FileAge(Sr.Name, tsFA)
else
tsFA := GetDirTime(Sr.Name);
iMinuts := MinutesBetween(tsFA, Now);
if (iMinuts >= iAge) or (faDirectory = (Sr.Attr and faDirectory))
then
begin
aSl.Add(sPath + Sr.Name);
end;
until FindNext(Sr) <> 0;
FindClose(Sr);
except
end;
end;
begin
iDel := 0;
iNotDel := 0;
if MForm.reLog.Lines.Count > MAX_LINES_COUNT then
MForm.reLog.Clear;
sSumPath := 'Очистка: ' + sPath;
if Length(sSumPath) > MAX_LENGTH_PATH then
MForm.sbBar.Panels.Items[2].Text := Copy(sSumPath, 1, MAX_LENGTH_PATH) +
'...'
else
MForm.sbBar.Panels.Items[2].Text := sSumPath;
MForm.AddToLog('', False);
MForm.AddToLog('Очистка пути ' + sPath + sFilter, True);
MForm.AddToLog('Возраст файлов и директорий от ' + MForm.MinToTime(iAge) +
' и старше', True);
SetCurrentDir(sPath);
{$IFDEF DEBUG}
// Sleep(3000);
{$ENDIF}
Attr := faAnyFile - faDirectory;
slToDel := TStringList.Create;
EnumFiles(sPath, sFilter, Attr, slToDel);
MForm.AddToLog('Найдено файлов и директорий: ' + IntTOStr(slToDel.Count),
True);
iDelCount := 0;
MForm.AddToLog('Старт очистки', True, [fsBold]);
for j := 0 to slToDel.Count - 1 do
begin
try
if not DirectoryExists(slToDel[j]) then
begin
if DeleteFile(slToDel[j]) then
Inc(iDel)
else
Inc(iNotDel);
end
else if RemoveDir(slToDel[j]) then
Inc(iDel)
else
Inc(iNotDel);
Inc(iDelCount);
if ((j mod 2000) = 0) and (j > 0) then
MForm.AddToLog('Очистка продолжается. Очищено файлов и директорий: ' +
IntToStr(iDel), True);
Sleep(AppSett.iDelInterval);
except
end;
end;
FreeAndNil(slToDel);
{ if FindFirst(sFilter, faAnyFile, searchResult) = 0 then
begin
repeat
if DelThread.Terminated then
Break;
if (searchResult.Attr and faDirectory) <> faDirectory then
begin
FileAge(searchResult.Name, tsFA);
iMinuts := MinutesBetween(tsFA, Now);
if iMinuts >= iAge then
begin
try
// DeleteFile(searchResult.name);
except
end;
Sleep(AppSett.iDelInterval);
Inc(iCount);
end;
end;
until FindNext(searchResult) <> 0;
FindClose(searchResult);
end; }
MForm.sbBar.Panels.Items[2].Text := '';
MForm.AddToLog('Очистка завершена. Очищено: ' + IntToStr(iDel), True, [fsBold],
$0041D739);
if iNotDel > 0 then
MForm.AddToLog('Не удалось удалить: ' + IntToStr(iNotDel), True, [fsBold],
clRed);
end;
procedure TDelThread.WriteCount(iNum, iCount: Integer);
begin
MForm.AddToLog('Разбор ' + IntTOStr(iNum) + ' из ' + IntToStr(iCount) +
' завершён', True);
end;
procedure TDelThread.Execute;
var
iNum: Integer;
begin
Sleep(AppSett.iDelInterval);
for iNum := Low(FilesSett.Settings) to High(FilesSett.Settings) do
begin
DelFiles(FilesSett.Settings[iNum].Name, FilesSett.Settings[iNum].Filter,
FilesSett.Settings[iNum].Age);
WriteCount(iNum + 1, Length(FilesSett.Settings));
Sleep(100);
if DelThread.Terminated then
Break;
end;
end;
// *****************************************************************************
// Перевод минут в дни
// *****************************************************************************
function TMForm.MinToTime(iMin: Integer): string;
const
SecPerDay = 86400;
SecPerHour = 3600;
SecPerMinute = 60;
var
iM, iH, iD, iSeconds: Integer;
begin
iSeconds := iMin * 60;
iD := iSeconds div SecPerDay;
iH := (iSeconds mod SecPerDay) div SecPerHour;
iM := ((iSeconds mod SecPerDay) mod SecPerHour) div SecPerMinute;
if iD > 0 then
Result := IntToStr(iD) + ' д.' + IntTOStr(iH) + ' ч.' + IntTOStr(iM) +
' м.'
else
begin
if iH > 0 then
Result := IntToStr(iH) + ' ч.' + IntTOStr(iM) + ' м.'
else
Result := IntToStr(iM) + ' м.';
end;
end;
function TMForm.IntToBool(iValue: Integer): Boolean;
begin
if iValue = 0 then
Result := False
else
Result := True;
end;
function TMForm.ReadIniFiles: Boolean;
var
sAppName: string;
begin
Result := False;
sAppName := Application.ExeName;
if DM.ReadIni(ExtractFilePath(sAppName)) then
begin
tmrClear.Enabled := True;
tmrClear.Interval := 60 * 1000 * AppSett.iStartInterval;
if bSecondLoad then
AddToLog('Настройки перечитаны', True, [fsBold], $0041D739)
else
begin
bSecondLoad := True;
AddToLog('Программа запущена', True, [], $0041D739);
AddToLog('Настройки загружены', True, [], $0041D739);
end;
Result := True;
end
else
begin
acStop.Execute;
AddToLog('Блок [Files] целевых директорий пуст. Выполните действия:', False,
[fsBold], clRed);
AddToLog(' 1. Проверьте настроечный файл ' + AppSett.sIniPath +
' на корректность заполнения параметров', False, [fsBold], clRed);
AddToLog(' 2. Измените настройки и перечитайте их с помощью кнопки "Перечитать настройки"',
False, [fsBold], clRed);
AddToLog(' 3. Нажмите кнопку "Продолжить работу"', False, [fsBold], clRed);
end;
end;
// *****************************************************************************
// Создание потока для очистки
// *****************************************************************************
procedure TMForm.CreateDelTread;
begin
if DelThread = nil then
DelThread := TDelThread.Create(False)
else
begin
DelThread.Terminate;
DelThread := TDelThread.Create(False);
end;
DelThread.Priority := tpNormal;
end;
procedure TMForm.tmrClearTimer(Sender: TObject);
begin
MForm.ReadIniFiles;
CreateDelTread;
end;
// *****************************************************************************
// Получить версию исполняемого файла
// *****************************************************************************
function TMForm.GetInfo(sFileName: string): string;
var
szName: array[0..255] of Char;
P: Pointer;
Value: Pointer;
Len: UINT;
GetTranslationString: string;
FFileName, FBuffer: PChar;
FValid: Boolean;
FSize, FHandle: DWORD;
begin
FFileName := nil;
FSize := 0;
FHandle := 0;
FBuffer := nil;
try
FFileName := StrPCopy(StrAlloc(Length(sFileName) + 1), sFileName);
FValid := False;
FSize := GetFileVersionInfoSize(FFileName, FHandle);
if FSize > 0 then
try
GetMem(FBuffer, FSize);
FValid := GetFileVersionInfo(FFileName, FHandle, FSize, FBuffer);
except // FValid := False;
raise;
end;
Result := '';
if FValid then
VerQueryValue(FBuffer, '\VarFileInfo\Translation', P, Len)
else
P := nil;
if P <> nil then
GetTranslationString := IntToHex(MakeLong(HiWord(Longint(P^)), LoWord(Longint
(P^))), 8);
if FValid then
begin
StrPCopy(szName, '\StringFileInfo\' + GetTranslationString +
'\FileVersion');
if VerQueryValue(FBuffer, szName, Value, Len) then
Result := StrPas(PChar(Value));
end;
finally
try
if FBuffer <> nil then
FreeMem(FBuffer, FSize);
except
end;
try
StrDispose(FFileName);
except
end;
end;
end;
procedure TMForm.WriteToFile(sPath, sText: string);
var
tfFile: TextFile;
begin
{$I-}
if not DirectoryExists(AppSett.sPathLog) then
ForceDirectories(AppSett.sPathLog);
{$I+}
AssignFile(tfFile, sPath);
// вот такое волшебное слово,
// отключаем Exception при ошибке ввода-вывода
{$I-}
Append(tfFile); // открываем файл для дописывания в конец
if IoResult <> 0 then // проверяем, что открылся
// а теперь включаем Exception при ошибке ввода-вывода
// поскольку всё равно ничего поделать не можем
{$I+}
try
ReWrite(tfFile);
except
end;
try
WriteLn(tfFile, sText); // пишем
CloseFile(tfFile); // закрываем
except
end;
end;
procedure TMForm.WriteLogFile(sText: string);
var
sPath: string;
begin
// if bLogExist then
begin
// if Pos('\', Copy(AppSett.sPathLog, Length(AppSett.sPathLog), 1)) = 0 then
// sPath := AppSett.sPathLog + '\'
// else
// sPath := AppSett.sPathLog;
sPath := IncludeTrailingPathDelimiter(AppSett.sPathLog);
WriteToFile(sPath + AppSett.sLogPref + FormatDateTime('yyyymmdd', Now) +
'.log', sText);
end;
end;
// *****************************************************************************
// Запись строки в лог
// *****************************************************************************
procedure TMForm.AddToLog(sValue: string; bAddDateTime: Boolean = True; fsStyle:
TFontStyles = []; Color: Integer = 0);
var
iDefColor: Integer;
fsDefStyle: TFontStyles;
begin
iDefColor := reLog.Font.Color;
fsDefStyle := reLog.Font.Style;
reLog.SelAttributes.Style := fsStyle;
reLog.SelAttributes.Color := Color;
if bAddDateTime then
sValue := '[' + DateTimeToStr(Now) + ']: ' + sValue;
reLog.Lines.Add(sValue);
reLog.SelAttributes.Style := fsDefStyle;
reLog.SelAttributes.Color := iDefColor;
SendMessage(reLog.Handle, WM_VSCROLL, SB_BOTTOM, 0);
sbBar.Panels.Items[1].Text := IntToStr(reLog.Lines.Count);
if acWriteLog.Checked then
WriteLogFile(sValue);
if AppSett.bShowConsole then
Writeln(sValue);
end;
procedure TMForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
CanClose := MessageBox(Application.Handle,
'Вы действительно хотите выйти из программы?', 'Предупреждение', MB_YESNO
or MB_ICONQUESTION) = ID_YES;
end;
procedure TMForm.FormCreate(Sender: TObject);
var
sAppName: string;
sVersion: string;
sParam: string;
begin
AllocConsole;
// SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_BLUE or
// FOREGROUND_GREEN or BACKGROUND_RED);
reLog.PlainText := True;
// Считываем параметр запуска и проверяем его корректность
sAppName := ParamStr(0);
sParam := ParamStr(1);
if not FileExists(sParam) or (Pos('\', sParam) = 0) then
AppSett.sIniPath := ExtractFilePath(sAppName) + 'dcleaner.ini'
else
AppSett.sIniPath := sParam;
Application.CreateForm(TDM, DM);
if ReadIniFiles then
begin
Application.ShowMainForm := AppSett.bShowWindows;
Self.Hide;
// Запуск первой после старта программы очистки диска.
CreateDelTread;
tmrClear.Enabled := True;
end;
acWriteLog.Checked := AppSett.bWriteLog;
N9.Checked := acWriteLog.Checked;
sAppName := Application.ExeName;
sVersion := 'v.' + GetInfo(sAppName);
AddToLog('Версия ПО: ' + ExtractFileName(sAppName) + ' ' + sVersion, False, [fsUnderline,
fsBold]);
sbBar.Panels.Items[0].Text := sVersion;
// AddToLog('Считывание настроек');
end;
procedure TMForm.FormDestroy(Sender: TObject);
begin
AddToLog('Программа остановлена', True);
FreeConsole;
end;
procedure TMForm.acAboutExecute(Sender: TObject);
begin
Application.CreateForm(TAboutF, AboutF);
AboutF.ShowModal;
end;
procedure TMForm.acExitExecute(Sender: TObject);
begin
Close;
end;
procedure TMForm.acShowHideExecute(Sender: TObject);
begin
if Application.ShowMainForm then
begin
Application.ShowMainForm := False;
Self.Hide;
AddToLog('Окно скрыто');
end
else
begin
Application.ShowMainForm := True;
Self.Show;
AddToLog('Окно показано');
end;
end;
procedure TMForm.acStopExecute(Sender: TObject);
begin
bStop := True;
tmrClear.Enabled := False;
if not bPause then
begin
bPause := True;
acPauseStart.Caption := 'Продолжить';
acPauseStart.ImageIndex := 1;
acPauseStart.Hint := 'Продолжить работу';
end;
(Sender as TAction).Enabled := False;
AddToLog('Работа программы остановлена', True, [fsBold]);
end;
procedure TMForm.acWriteLogExecute(Sender: TObject);
begin
if (Sender as TAction).Checked then
begin
AddToLog('Запись в лог на диск: выключена', True);
(Sender as TAction).Checked := False;
AppSett.bWriteLog := False;
DM.WriteIni(AppSett.sIniPath);
end
else
begin
AddToLog('Запись в лог на диск: включена', True);
(Sender as TAction).Checked := True;
AppSett.bWriteLog := True;
DM.WriteIni(AppSett.sIniPath);
end;
end;
procedure TMForm.acPauseStartExecute(Sender: TObject);
begin
acStop.Enabled := True;
if not bPause then
begin
bPause := True;
tmrClear.Enabled := False;
(Sender as TAction).Caption := 'Продолжить';
(Sender as TAction).ImageIndex := 1;
(Sender as TAction).Hint := 'Продолжить работу';
AddToLog('Работа программы приостановлена', True, [fsBold]);
end
else
begin
bPause := False;
tmrClear.Enabled := True;
(Sender as TAction).Caption := 'Пауза';
(Sender as TAction).ImageIndex := 0;
(Sender as TAction).Hint := 'Приостановить работу';
AddToLog('Работа программы продолжена', True, [fsBold]);
// Если перед стартом работа была остановлена
if bStop then
CreateDelTread;
bStop := False;
end;
end;
procedure TMForm.acReReadSettExecute(Sender: TObject);
begin
ReadIniFiles;
end;
end.
|
unit pfoEditorRecords;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, ActnList, cxCheckBox, cxDBEdit,
cxDropDownEdit, cxCalendar, cxMemo, cxMaskEdit, cxControls, cxContainer,
cxEdit, cxTextEdit, ExtCtrls, StdCtrls, cxButtons, ImgList, ExtDlgs,
cxButtonEdit, PluginManagerIntf;
type
TEditorRecord = class(TForm)
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
mbOK: TcxButton;
mbCancel: TcxButton;
Panel1: TPanel;
title: TcxDBTextEdit;
link: TcxDBMaskEdit;
description: TcxDBMemo;
CreateDate: TcxDBDateEdit;
is_visible: TcxDBCheckBox;
ActionList: TActionList;
ActionOK: TAction;
Label5: TLabel;
comment: TcxDBMemo;
PathSmallImage: TAction;
PathImage: TAction;
OpenPictureDialog: TOpenPictureDialog;
translit: TcxDBTextEdit;
Label6: TLabel;
Label7: TLabel;
Label8: TLabel;
ReSetName: TcxButton;
cxButton1: TcxButton;
cxButton2: TcxButton;
cxButton3: TcxButton;
ImageList1: TImageList;
ViewSmallImage: TAction;
ViewImage: TAction;
EditDescription: TAction;
EditComment: TAction;
cxButton4: TcxButton;
SmallImage: TcxDBButtonEdit;
OrigImage: TcxDBButtonEdit;
procedure ActionOKExecute(Sender: TObject);
procedure PathSmallImageExecute(Sender: TObject);
procedure PathImageExecute(Sender: TObject);
procedure EditDescriptionExecute(Sender: TObject);
procedure EditCommentExecute(Sender: TObject);
procedure ViewSmallImageExecute(Sender: TObject);
procedure ViewImageExecute(Sender: TObject);
private
FPluginManager: IPluginManager;
procedure SetPluginManager(const Value: IPluginManager);
public
property PluginManager: IPluginManager read FPluginManager write SetPluginManager;
end;
function GetEditorRecordForm(APluginManager: IPluginManager): Integer;
implementation
uses pfoDataModule, HTMLEditorIntf;
{$R *.dfm}
function GetEditorRecordForm;
var
Form: TEditorRecord;
begin
Form := TEditorRecord.Create(Application);
try
Form.PluginManager := APluginManager;
Result := form.ShowModal;
finally
Form.Free;
end;
end;
procedure TEditorRecord.ActionOKExecute(Sender: TObject);
begin
mbOk.SetFocus;
ModalResult := mrOK;
end;
procedure TEditorRecord.PathSmallImageExecute(Sender: TObject);
begin
if OpenPictureDialog.Execute then
begin
//Image.Picture.LoadFromFile(OpenPictureDialog.FileName);
//DM.table_portfolio.FieldByName('path_small_image').AsString := OpenPictureDialog.FileName;
end;
end;
procedure TEditorRecord.PathImageExecute(Sender: TObject);
begin
if OpenPictureDialog.Execute then
begin
//DM.table_portfolio.FieldByName('path_image').AsString := OpenPictureDialog.FileName;
end;
end;
// Редактирование описания
procedure TEditorRecord.EditDescriptionExecute(Sender: TObject);
var
Editor: IHTMLEditor;
s: String;
RemotePath, LocalPath: String;
FilesList: TStringList;
begin
if FPluginManager.GetPlugin(IHTMLEditor, Editor) then
begin
s := description.Text;
//----------------
LocalPath := DM.GetLocalPath(DM.Portfolio);
RemotePath := DM.GetRemotePath(LocalPath);
//----------------
Editor.RemotePath := RemotePath;
Editor.LocalPath := LocalPath;
FilesList := TStringList.Create;
try
Editor.FilesList := FilesList;
if Editor.Execute(s) then
begin
description.DataBinding.Field.Value := s;
if Trim(DM.Portfolio.FieldValues['path_small_image']) <> Trim(FilesList.Text) then
DM.Portfolio.FieldValues['path_small_image'] := Trim(FilesList.Text);
end;
finally
FilesList.Free;
end;
end;
end;
// Редактирование комментария
procedure TEditorRecord.EditCommentExecute(Sender: TObject);
begin
//
end;
// Предпросмотр большой картинки
procedure TEditorRecord.ViewSmallImageExecute(Sender: TObject);
begin
//
end;
// Предпросмотр маленькой картинки
procedure TEditorRecord.ViewImageExecute(Sender: TObject);
begin
//
end;
procedure TEditorRecord.SetPluginManager(const Value: IPluginManager);
begin
FPluginManager := Value;
end;
end.
|
unit Unit2;
interface
uses Math;
type
RefToStackElement = ^StackElement;
StackElement = record
value: char;
previos: RefToStackElement;
end;
Stack = class(TObject)
private
{ Private declarations }
last: RefToStackElement;
function createNewStackElement(value: char): RefToStackElement;
public
{ Public declarations }
Constructor Create();
procedure push_back(value: char);
function pop_back(): char;
function top(): char;
function empty(): boolean;
end;
calc = class(TObject)
private
{ Private declarations }
operates: set of char;
postfix_form: string;
function get_priority(c: char): longint;
public
{ Public declarations }
values: array['a'..'ÿ'] of extended;
function transform_in_rpr(s: string): string;
function get_result(): extended;
Constructor Create();
end;
implementation
Constructor Stack.Create();
begin
last := nil;
end;
function Stack.empty(): boolean;
begin
if (last = nil) then begin
empty := true;
end
else begin
empty := false;
end;
end;
function Stack.top(): char;
begin
if (last <> nil) then begin
top := last^.value;
end
else begin
top := '#';
end;
end;
function Stack.createNewStackElement(value: char): RefToStackElement;
var new_element: RefToStackElement;
begin
GetMem(new_element, sizeof(StackElement));
new_element^.value := value;
new_element^.previos := last;
createNewStackElement := new_element;
end;
procedure Stack.push_back(value: char);
var new_element: RefToStackElement;
begin
new_element := createNewStackElement(value);
last := new_element;
end;
function Stack.pop_back(): char;
var previos: RefToStackElement;
begin
pop_back := last^.value;
previos := last^.previos;
FreeMem(last);
last := previos;
end;
Constructor calc.Create();
var i: longint;
begin
operates := ['-', '+', '*', '/', '^', '(', ')'];
postfix_form := '';
end;
function calc.get_priority(c: char): longint;
begin
if ((c = '(') or (c = ')')) then begin
get_priority := 0;
end;
if ((c = '+') or (c = '-')) then begin
get_priority := 1;
end;
if ((c = '*') or (c = '/')) then begin
get_priority := 2;
end;
if (c = '^') then begin
get_priority := 3;
end;
end;
function calc.transform_in_rpr(s: string): string;
var i: longint;
myStack: Stack;
begin
postfix_form := '';
myStack := Stack.Create();
for i := 1 to length(s) do begin
if (not(s[i] in operates)) then begin
postfix_form := postfix_form + s[i];
end
else begin
if (myStack.empty = true) then begin
myStack.push_back(s[i]);
end
else begin
if (s[i] = '(') then begin
myStack.push_back(s[i]);
end
else begin
if (s[i] = ')') then begin
while (myStack.top() <> '(') do begin
postfix_form := postfix_form + myStack.pop_back();
end;
if (not(myStack.empty)) then begin
myStack.pop_back();
end;
end
else begin
while (not(myStack.empty())
and (get_priority(s[i]) <= get_priority(myStack.top()))) do begin
postfix_form := postfix_form + myStack.pop_back();
end;
myStack.push_back(s[i]);
end;
end;
end;
end;
end;
while (not(myStack.empty())) do begin
postfix_form := postfix_form + myStack.pop_back();
end;
myStack.Free();
transform_in_rpr := postfix_form;
end;
function calc.get_result(): extended;
var value1, value2, temp_result: extended;
myStack: Stack;
i: longint;
st: char;
begin
if (postfix_form = '') then begin
exit;
end;
myStack := Stack.Create;
st := Succ('z');
for i := 1 to length(postfix_form) do begin
if (not(postfix_form[i] in operates)) then begin
myStack.push_back(postfix_form[i]);
end
else begin
value2 := values[myStack.pop_back()];
value1 := values[myStack.pop_back()];
case (postfix_form[i]) of
'+': temp_result := value1 + value2;
'-': temp_result := value1 - value2;
'*': temp_result := value1 * value2;
'/': temp_result := value1 / value2;
'^': temp_result := power(value1, value2);
end;
values[st] := temp_result;
myStack.push_back(st);
inc(st);
end;
end;
get_result := values[myStack.pop_back()];
myStack.Free();
end;
end.
|
unit Model.Entity.Empresa;
interface
uses
System.Classes,
System.Generics.Collections,
System.JSON,
Rest.Json,
SimpleAttributes;
type
[Tabela('Empresa')]
TEmpresa = class
private
FId: Integer;
FData_criacao: TDate;
FSituacao: Boolean;
FRemovido: Boolean;
FRazao_social: String;
FNome_fantasia: String;
FCnpj: String;
FIe: String;
FIm: String;
FCep: String;
FCodigo_ibge: String;
FCodigo_municipal: String;
FPais: String;
FEstado: String;
FUf: String;
FCidade: String;
FBairro: String;
FEndereco: String;
FEndereco_numero: String;
FComplemento: String;
FTelefone: String;
FCelular: String;
FEmail: String;
public
constructor Create;
destructor Destroy; override;
published
[Campo('Id'), PK, AutoInc]
property Id: Integer read FId write FId;
[Campo('Data_criacao')]
property Data_criacao: TDate read FData_criacao write FData_criacao;
[Campo('Situacao')]
property Situacao: Boolean read FSituacao write FSituacao;
[Campo('Removido')]
property Removido: Boolean read FRemovido write FRemovido;
[Campo('Razao_social')]
property Razao_social: String read FRazao_social write FRazao_social;
[Campo('Nome_fantasia')]
property Nome_fantasia: String read FNome_fantasia write FNome_fantasia;
[Campo('Cnpj')]
property Cnpj: String read FCnpj write FCnpj;
[Campo('Ie')]
property Ie: String read FIe write FIe;
[Campo('Im')]
property Im: String read FIm write FIm;
[Campo('Cep')]
property Cep: String read FCep write FCep;
[Campo('Codigo_ibge')]
property Codigo_ibge: String read FCodigo_ibge write FCodigo_ibge;
[Campo('Codigo_municipal')]
property Codigo_municipal: String read FCodigo_municipal write FCodigo_municipal;
[Campo('Pais')]
property Pais: String read FPais write FPais;
[Campo('Estado')]
property Estado: String read FEstado write FEstado;
[Campo('Uf')]
property Uf: String read FUf write FUf;
[Campo('Cidade')]
property Cidade: String read FCidade write FCidade;
[Campo('Bairro')]
property Bairro: String read FBairro write FBairro;
[Campo('Endereco')]
property Endereco: String read FEndereco write FEndereco;
[Campo('Endereco_numero')]
property Endereco_numero: String read FEndereco_numero write FEndereco_numero;
[Campo('Complemento')]
property Complemento: String read FComplemento write FComplemento;
[Campo('Telefone')]
property Telefone: String read FTelefone write FTelefone;
[Campo('Celular')]
property Celular: String read FCelular write FCelular;
[Campo('Email')]
property Email: String read FEmail write FEmail;
function ToJSONObject: TJsonObject;
function ToJsonString: string;
end;
implementation
constructor TEmpresa.Create;
begin
end;
destructor TEmpresa.Destroy;
begin
inherited;
end;
function TEmpresa.ToJSONObject: TJsonObject;
begin
Result := TJson.ObjectToJsonObject(Self);
end;
function TEmpresa.ToJsonString: string;
begin
result := TJson.ObjectToJsonString(self);
end;
end.
|
unit PropSet;
////////////////////////////////////////////////////////////////////////////////
//
// Author: Jaap Baak
// https://github.com/transportmodelling/Utils
//
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
interface
////////////////////////////////////////////////////////////////////////////////
Uses
SysUtils,Types,IOUtils,BaseDir,Parse;
Type
TPropertySet = record
private
Type
TProperty = record
Name,Value: string;
end;
Var
FReadOnly: Boolean;
FNameValueSeparator: Char;
FPropertiesSeparator: Char;
FProperties: array of TProperty;
Function IndexOf(const Name: String): Integer;
Procedure SetNameValueSeparator(Separator: Char);
Procedure SetPropertiesSeparator(Separator: Char);
Function GetNames(Index: Integer): String; inline;
Function GetValues(const Name: String): String; inline;
Procedure SetValues(const Name,Value: String); inline;
Function GetValueFromIndex(Index: Integer): String;
Procedure SetValueFromIndex(Index: Integer; const Value: String);
Function GetAsString: String;
Procedure SetAsString(AsString: String);
Function GetAsStrings: TStringDynArray;
Procedure SetAsStrings(AsStrings: TStringDynArray);
Procedure Append(const AsString: String); overload;
public
Class Var BaseDirectory: TBaseDirectory;
Class Constructor Create;
public
Class Operator Initialize(out PropertySet: TPropertySet);
Class Operator Assign(var Left: TPropertySet; const [ref] Right: TPropertySet);
Class Operator Implicit(Properties: String): TPropertySet;
Class Operator Implicit(Properties: TPropertySet): String;
Class Operator Implicit(Properties: TStringDynArray): TPropertySet;
Class Operator Implicit(Properties: TPropertySet): TStringDynArray;
public
Property ReadOnly: Boolean read FReadOnly;
// Separator properties
Property NameValueSeparator: Char read FNameValueSeparator write SetNameValueSeparator;
Property PropertiesSeparator: Char read FPropertiesSeparator write SetPropertiesSeparator;
// Type casts
Property AsString: String read GetAsString write SetAsString;
Property AsStrings: TStringDynArray read GetAsStrings write SetAsStrings;
// Query content
Function Count: Integer; inline;
Function Contains(const Name: String): Boolean; overload;
Function Contains(const Name: String; var Value: String): Boolean; overload;
Function ContainsValue(const Name: String): Boolean; overload;
Function ContainsValue(const Name: String; var Value: String): Boolean; overload;
Property Names[Index: Integer]: String read GetNames;
Property Values[const Name: String]: string read GetValues write SetValues; default;
Property ValueFromIndex[Index: Integer]: String read GetValueFromIndex write SetValueFromIndex;
// Convert property values
Function ToStr(const Name,Default: String): String;
Function ToInt(const Name: String): Integer; overload;
Function ToInt(const Name: String; Default: Integer): Integer; overload;
Function ToFloat(const Name: String): Float64; overload;
Function ToFloat(const Name: String; Default: Float64): Float64; overload;
Function ToBool(const Name,FalseStr,TrueStr: String): Boolean; overload;
Function ToBool(const Name,FalseStr,TrueStr: String; Default: Boolean): Boolean; overload;
Function ToPath(const Name: String): String;
Function ToFileName(const Name: String): String; overload;
Function ToFileName(const Name,Extension: String): String; overload;
Function Parse(const Name: String; Delimiter: TDelimiter = Comma): TStringParser;
// Manage content
Constructor Create(ReadOnly: Boolean); overload;
Constructor Create(NameValueSeparator,PropertiesSeparator: Char; ReadOnly: Boolean = false); overload;
Constructor Create(const [ref] Properties: TPropertySet; ReadOnly: Boolean = false); overload;
Procedure Clear;
Procedure RemoveUnassigned;
Procedure Append(const Name,Value: String); overload;
Procedure Append(const Properties: TPropertySet; SkipUnassigned,SkipDuplicates: Boolean); overload;
Procedure Lock;
end;
////////////////////////////////////////////////////////////////////////////////
implementation
////////////////////////////////////////////////////////////////////////////////
Class Constructor TPropertySet.Create;
begin
BaseDirectory := ExtractFileDir(ParamStr(0));
end;
Class Operator TPropertySet.Initialize(out PropertySet: TPropertySet);
begin
PropertySet.FReadOnly := false;
PropertySet.FNameValueSeparator := '=';
PropertySet.FPropertiesSeparator := ';';
end;
Class Operator TPropertySet.Assign(var Left: TPropertySet; const [ref] Right: TPropertySet);
begin
Left.FReadOnly := Right.FReadOnly;
Left.FNameValueSeparator := Right.FNameValueSeparator;
Left.FPropertiesSeparator := Right.FPropertiesSeparator;
Left.FProperties := Copy(Right.FProperties);
end;
Class Operator TPropertySet.Implicit(Properties: String): TPropertySet;
begin
Result.AsString := Properties;
end;
Class Operator TPropertySet.Implicit(Properties: TPropertySet): String;
begin
Result := Properties.AsString;
end;
Class Operator TPropertySet.Implicit(Properties: TStringDynArray): TPropertySet;
begin
Result.AsStrings := Properties;
end;
Class Operator TPropertySet.Implicit(Properties: TPropertySet): TStringDynArray;
begin
Result := Properties.AsStrings;
end;
Constructor TPropertySet.Create(ReadOnly: Boolean);
begin
FReadOnly := ReadOnly;
Finalize(FProperties);
end;
Constructor TPropertySet.Create(NameValueSeparator,PropertiesSeparator: Char; ReadOnly: Boolean = false);
begin
FReadOnly := ReadOnly;
FNameValueSeparator := NameValueSeparator;
FPropertiesSeparator := PropertiesSeparator;
Finalize(FProperties);
end;
Constructor TPropertySet.Create(const [ref] Properties: TPropertySet; ReadOnly: Boolean = false);
begin
FReadOnly := ReadOnly;
FNameValueSeparator := Properties.FNameValueSeparator;
FPropertiesSeparator := Properties.FPropertiesSeparator;
FProperties := Copy(Properties.FProperties);
end;
Function TPropertySet.IndexOf(const Name: String): Integer;
begin
Result := -1;
for var Prop := low(FProperties) to high(FProperties) do
if SameText(FProperties[Prop].Name,Name) then
begin
Result := Prop;
Break;
end;
end;
Procedure TPropertySet.SetNameValueSeparator(Separator: Char);
begin
Clear;
FNameValueSeparator := Separator;
end;
Procedure TPropertySet.SetPropertiesSeparator(Separator: Char);
begin
Clear;
FPropertiesSeparator := Separator;
end;
Function TPropertySet.GetNames(Index: Integer): string;
begin
Result := FProperties[Index].Name;
end;
Function TPropertySet.GetValues(const Name: String): String;
begin
Contains(Name,Result);
end;
Procedure TPropertySet.SetValues(const Name,Value: String);
begin
if not FReadOnly then
begin
var Index := IndexOf(Name);
if Index >= 0 then
FProperties[Index].Value := Value
else
raise Exception.Create('Property does not exist (' + Name + ')');
end else
raise Exception.Create('Cannot modify a read only property set');
end;
Function TPropertySet.GetValueFromIndex(Index: Integer): String;
begin
Result := FProperties[Index].Value;
end;
Procedure TPropertySet.SetValueFromIndex(Index: Integer; const Value: String);
begin
if not FReadOnly then
FProperties[Index].Value := Value
else
raise Exception.Create('Cannot modify a read only property set');
end;
Function TPropertySet.GetAsString: String;
begin
if Length(FProperties) > 0 then
begin
Result := FProperties[0].Name + FNameValueSeparator + FProperties[0].Value;
for var Prop := 1 to Count-1 do
Result := Result + FPropertiesSeparator + ' ' + FProperties[Prop].Name + FNameValueSeparator + FProperties[Prop].Value;
end else Result := '';
end;
Procedure TPropertySet.SetAsString(AsString: string);
begin
FProperties := nil;
if AsString <> '' then
begin
var PropertySeparatorPos := Pos(FPropertiesSeparator,AsString);
while PropertySeparatorPos > 0 do
begin
Append(Copy(AsString,1,PropertySeparatorPos-1));
AsString := Trim(Copy(AsString,PropertySeparatorPos+1,MaxInt));
PropertySeparatorPos := Pos(FPropertiesSeparator,AsString);
end;
// Append last property
Append(AsString);
end;
end;
Function TPropertySet.GetAsStrings: TStringDynArray;
begin
SetLength(Result,Count);
for var Prop := 0 to Count-1 do
Result[Prop] := FProperties[Prop].Name + FNameValueSeparator + FProperties[Prop].Value;
end;
Procedure TPropertySet.SetAsStrings(AsStrings: TStringDynArray);
begin
FProperties := nil;
for var Prop := low(AsStrings) to high(AsStrings) do Append(AsStrings[Prop]);
end;
Function TPropertySet.Count: Integer;
begin
Result := Length(FProperties);
end;
Function TPropertySet.Contains(const Name: String): Boolean;
Var
Value: String;
begin
Result := Contains(Name,Value);
end;
Function TPropertySet.Contains(const Name: String; var Value: String): Boolean;
begin
Result := false;
Value := '';
for var Prop := low(FProperties) to high(FProperties) do
if SameText(FProperties[Prop].Name,Name) then
begin
Result := true;
Value := FProperties[Prop].Value;
Break;
end;
end;
Function TPropertySet.ContainsValue(const Name: String): Boolean;
Var
Value: String;
begin
Result := ContainsValue(Name,Value);
end;
Function TPropertySet.ContainsValue(const Name: String; var Value: String): Boolean;
begin
if Contains(Name,Value) then
Result := (Value <> '')
else
Result := false;
end;
Function TPropertySet.ToStr(const Name,Default: String): String;
begin
if not Contains(Name,Result) then Result := Default;
end;
Function TPropertySet.ToInt(const Name: String): Integer;
begin
try
Result := GetValues(Name).ToInteger;
except
raise Exception.Create('Invalid integer value (' + Name + ')');
end;
end;
Function TPropertySet.ToInt(const Name: String; Default: Integer): Integer;
Var
Value: String;
begin
if Contains(Name,Value) then
try
Result := GetValues(Name).ToInteger;
except
raise Exception.Create('Invalid integer value (' + Name + ')');
end
else
Result := Default;
end;
Function TPropertySet.ToFloat(const Name: String): Float64;
begin
try
Result := GetValues(Name).ToDouble;
except
raise Exception.Create('Invalid floating point value (' + Name + ')');
end;
end;
Function TPropertySet.ToFloat(const Name: String; Default: Float64): Float64;
Var
Value: String;
begin
if Contains(Name,Value) then
try
Result := GetValues(Name).ToDouble;
except
raise Exception.Create('Invalid floating point value (' + Name + ')');
end
else
Result := Default;
end;
Function TPropertySet.ToBool(const Name,FalseStr,TrueStr: String): Boolean;
begin
var Value := GetValues(Name);
if SameText(Value,FalseStr) then Result := false else
if SameText(Value,TrueStr) then Result := true else
raise Exception.Create('Invalid boolean value (' + Name + ')');
end;
Function TPropertySet.ToBool(const Name,FalseStr,TrueStr: String; Default: Boolean): Boolean;
Var
Value: String;
begin
if Contains(Name,Value) then
begin
if SameText(Value,FalseStr) then Result := false else
if SameText(Value,TrueStr) then Result := true else
raise Exception.Create('Invalid boolean value (' + Name + ')')
end else
Result := Default;
end;
Function TPropertySet.ToPath(const Name: String): String;
begin
if Contains(Name,Result) then
Result := BaseDirectory.AbsolutePath(Result)
else
Result := '';
end;
Function TPropertySet.ToFileName(const Name: String): String;
begin
// Set file name
if Contains(Name,Result) then
if Result <> '' then
Result := BaseDirectory.AbsolutePath(Result)
else
Result := ''
else
Result := '';
end;
Function TPropertySet.ToFileName(const Name,Extension: String): String;
begin
// Set file name
if Contains(Name,Result) then
if Result <> '' then
Result := ChangeFileExt(BaseDirectory.AbsolutePath(Result),Extension)
else
Result := ''
else
Result := '';
end;
Function TPropertySet.Parse(const Name: String; Delimiter: TDelimiter = Comma): TStringParser;
Var
Value: string;
begin
if Contains(Name,Value) then
Result := TStringParser.Create(Delimiter,Value)
else
Result := TStringParser.Create(Delimiter,'');
end;
Procedure TPropertySet.Clear;
begin
Finalize(FProperties);
end;
Procedure TPropertySet.RemoveUnassigned;
begin
var Index := 0;
for var Prop := low(FProperties) to high(FProperties) do
if FProperties[Prop].Value <> '' then
begin
if Index < Prop then FProperties[Index] := FProperties[Prop];
Inc(Index);
end;
SetLength(FProperties,Index);
end;
Procedure TPropertySet.Append(const AsString: String);
begin
if AsString <> '' then
begin
var NameValueSeparatorPos := Pos(FNameValueSeparator,AsString);
if NameValueSeparatorPos > 0 then
begin
var Name := Trim(Copy(AsString,1,NameValueSeparatorPos-1));
if Name <> '' then
if IndexOf(Name) < 0 then
begin
var Value := Trim(Copy(AsString,NameValueSeparatorPos+1,MaxInt));
Append(Name,Value);
end else
raise Exception.Create('Duplicate property (' + Name + ')')
else
raise Exception.Create('Missing Property Name');
end else
raise Exception.Create('Missing Name-Value separator (' + AsString + ')');
end;
end;
Procedure TPropertySet.Append(const Name,Value: String);
begin
if Name <> '' then
if IndexOf(Name) < 0 then
begin
var Index := Count;
SetLength(FProperties,Index+1);
FProperties[Index].Name := Name;
FProperties[Index].Value := Value;
end else
raise Exception.Create('Duplicate property (' + Name + ')')
else
raise Exception.Create('Missing Property Name');
end;
Procedure TPropertySet.Append(const Properties: TPropertySet; SkipUnassigned,SkipDuplicates: Boolean);
begin
var Index := Count;
SetLength(FProperties,Count+Properties.Count);
for var Prop := 0 to Properties.Count-1 do
begin
var PropertyIndex := IndexOf(Properties.Names[Prop]);
if ((not SkipUnassigned) or (Properties.FProperties[Prop].Value <> ''))
and ((not SkipDuplicates) or (PropertyIndex < 0)) then
if PropertyIndex < 0 then
begin
FProperties[Index] := Properties.FProperties[Prop];
Inc(Index);
end else
raise Exception.Create('Duplicate property (' + Properties.Names[Prop] + ')')
end;
SetLength(FProperties,Index);
end;
Procedure TPropertySet.Lock;
begin
FReadOnly := true;
end;
end.
|
unit Main;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs,
FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf,
FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async,
FireDAC.Phys, FireDAC.Phys.MySQL, FireDAC.Phys.MySQLDef, Data.DB,
FireDAC.Comp.Client, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf,
FireDAC.DApt, FireDAC.Comp.DataSet, Data.Bind.Controls, Data.Bind.EngExt,
Fmx.Bind.DBEngExt, System.Rtti, Fmx.Bind.Grid, System.Bindings.Outputs,
Fmx.Bind.Editors, Data.Bind.Components, Data.Bind.Grid, FMX.Layouts, FMX.Grid,
Fmx.Bind.Navigator, Data.Bind.DBScope, FireDAC.FMXUI.Wait, FireDAC.Comp.UI,
IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, FMX.StdCtrls,
FMX.Memo, FMX.Controls.Presentation, FMX.Edit, IdIPMCastBase, IdIPMCastClient,
IdAntiFreezeBase, Vcl.IdAntiFreeze,
IdGlobal, System.DateUtils;
type
TForm2 = class(TForm)
FDConnection1: TFDConnection;
FDQuery1: TFDQuery;
BindSourceDB1: TBindSourceDB;
BindingsList1: TBindingsList;
Grid1: TGrid;
LinkGridToDataSourceBindSourceDB1: TLinkGridToDataSource;
FDGUIxWaitCursor1: TFDGUIxWaitCursor;
bStart: TButton;
IdTCPClient1: TIdTCPClient;
bStop: TButton;
Memo1: TMemo;
eServer: TEdit;
Label1: TLabel;
Timer1: TTimer;
procedure bStartClick(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
procedure bStopClick(Sender: TObject);
procedure Memo1Change(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
TByteArray = packed array[1..65536] of Byte;
T3ByteArray = packed array[0..2] of Byte;
//Формат подзаписи EGTS_SR_TERM_IDENTITY сервиса EGTS_AUTH_SERVICE
TEGTS_SR_TERM_IDENTITY = packed record
TID : LongWord;
Flags : Byte; // MNE BSE NIDE SSRA (Алгоритм "Простой"=1) LNGCE IMSIE IMEIE HDIDE
//HDID (Home Dispatcher Identifier) O USHORT 2
//IMEI (International Mobile Equipment Identity) O STRING 15
//IMSI (International Mobile Subscriber Identity) O STRING 16
//LNGC (Language Code) O STRING 3
//NID (Network Identifier) O BINARY 3
BS : Word; // Размер буфера АС
//MSISDN (Mobile Station Integrated Services Digital Network Number) O STRING 15
end;
//Формат подзаписи EGTS_SR_POS_DATA сервиса EGTS_TELEDATA_SERVICE
TEGTS_SR_POS_DATA = packed record
NTM : LongWord;
LAT : LongWord;
LONG : LongWord;
FLG : Byte;
SPD : Byte;
DIRH_ALTS_SPD : Byte;
DIR : Byte;
ODM : T3ByteArray;
DIN : Byte;
SRC : Byte;
ALT : T3ByteArray;
SRCD : SmallInt;
end;
//Формат заголовка поля SFRD
TSFRD = packed record
RL : Word; // Длина RD - меняется в зависимости от типа
RN : Word;
RFL : Byte; // SSOD RSOD GRP RPP(2 бита) TMFE EVFE OBFE
OID : LongWord;
EVID : LongWord;
TM : LongWord;
SST : Byte; // Для сервиса EGTS_AUTH_SERVICE: EGTS_SR_TERM_IDENTITY=1
// Для сервиса EGTS_TELEDATA_SERVICE: EGTS_SR_POS_DATA = 16
RST : Byte; // Аналогично
end;
TRecSubRec = packed record
Rec : TSFRD;
SubRec : TEGTS_SR_POS_DATA;
end;
// Упрощение - сводная запись + заголовок подзаписи + 1 подзапись для координат
TRecSubRec_EGTS_SR_POS_DATA = packed record
RL : Word; // Длина RD - меняется в зависимости от типа
RN : Word;
RFL : Byte; // SSOD RSOD GRP RPP(2 бита) TMFE EVFE OBFE
OID : LongWord;
// EVID : LongWord;
// TM : LongWord;
SST : Byte; // Для сервиса EGTS_AUTH_SERVICE: EGTS_SR_TERM_IDENTITY=1
// Для сервиса EGTS_TELEDATA_SERVICE: EGTS_SR_POS_DATA = 16
RST : Byte; // Аналогично
// Заголовок подзаписи
SRT : Byte; // Тип подзаписи
SRL : Word; // Длина подзаписи
// Подзапись типа EGTS_SR_POS_DATA сервиса EGTS_TELEDATA_SERVICE
NTM : LongWord;
LAT : LongWord;
LONG : LongWord;
FLG : Byte;
SPD : Byte;
DIRH_ALTS_SPD : Byte;
DIR : Byte;
ODM : T3ByteArray;
DIN : Byte;
SRC : Byte;
ALT : T3ByteArray;
SRCD : SmallInt;
end;
TEGTS_Ar = packed array of TRecSubRec_EGTS_SR_POS_DATA;
// Состав пакета протокола Транспортного уровня
TProtocolRecord = packed record
prv : Byte;
skid : Byte;
prefix : Byte;
hl : Byte;
he : Byte;
fdl : Word;
pid : Word;
pt : Byte;
// pra : Word;
// rca : Word;
// ttl : Byte;
hcs : Byte;
sfrd : TEGTS_Ar;
sfrcs : Word;
end;
TAuto = record
device : Integer;
lrts : String;
end;
TAutoArray = array of TAuto;
const
// Типы сервисов
EGTS_AUTH_SERVICE = 1;
EGTS_TELEDATA_SERVICE =2;
// Список типов подзаписей сервиса EGTS_AUTH_SERVICE
EGTS_SR_RECORD_RESPONSE = 0;
EGTS_SR_TERM_IDENTITY = 1;
EGTS_SR_MODULE_DATA = 2;
EGTS_SR_VEHICLE_DATA = 3;
EGTS_SR_AUTH_INFO = 7;
EGTS_SR_SERVICE_INFO = 8;
EGTS_SR_RESULT_CODE = 9;
// Список типов подзаписей сервиса EGTS_TELEDATA_SERVICE
//EGTS_SR_RECORD_RESPONSE - совпадает с EGTS_AUTH_SERVICE
EGTS_SR_POS_DATA = 16;
EGTS_SR_EXT_POS_DATA = 17;
EGTS_SR_AD_SENSORS_DATA = 18;
EGTS_SR_COUNTERS_DATA = 19;
EGTS_SR_STATE_DATA = 20;
EGTS_SR_LOOPIN_DAТА = 22;
EGTS_SR_ABS_DIG_SENS_DATA = 23;
EGTS_SR_ABS_AN_SENS_DATA = 24;
EGTS_SR_ABS_CNTR_DATA = 25;
EGTS_SR_ABS_LOOPIN_DATA = 26;
EGTS_SR_LIQUID_LEVEL_SENSOR = 27;
EGTS_SR_PASSENGERS_COUNTERS = 28;
// Для счётчика
FILENAME_COUNTER = 'counter.cnt';
// Журнал
FILENAME_LOG = 'data.log';
// Команды журналу
Rewrite_Log = '#REWRITE_LOG';
var
Form2: TForm2;
EgtsAr : TEGTS_Ar;
Tcp : TProtocolRecord;
NullArr3 : T3ByteArray = (0,0,0);
TcpStream : TMemoryStream;
Counter: Word;
Auto : TAutoArray;
Buf, BufH : TIdBytes;
Executed : Boolean;
AllRData : String;
TF : TextFile;
implementation
{$R *.fmx}
procedure LoadCounter;
var
f : file of Word;
begin
if FileExists(FILENAME_COUNTER) then begin
AssignFile(f, FILENAME_COUNTER);
Reset(f);
Read(f, Counter);
CloseFile(f);
end else
Counter := 0;
end;
procedure SaveCounter;
var
f: file of Word;
begin
AssignFile(f, FILENAME_COUNTER);
Rewrite(f);
Write(f, Counter);
CloseFile(f);
end;
procedure Log(S : String);
var
H, M, Sec, Ms : Word;
begin
AssignFile(TF, FILENAME_LOG);
if S = Rewrite_Log then begin
DecodeTime(Now, H, M, Sec, Ms);
if (H = 0) and (M = 0) and (Sec*1000 < Form2.Timer1.Interval) then begin
DeleteFile(FILENAME_LOG + '.YESTERDAY');
Rename(TF, FILENAME_LOG + '.YESTERDAY');
end;
Exit;
end;
Form2.Memo1.Lines.Add(S);
// Запись в журнал
if FileExists(FILENAME_LOG) then begin
Append(TF);
end else begin
Rewrite(TF);
end;
Writeln(TF, S);
// Закрыть файл журнала
Flush(TF);
CloseFile(TF);
end;
const Crc16Table: array[0..255] of WORD = (
$0000, $1021, $2042, $3063, $4084, $50A5, $60C6, $70E7,
$8108, $9129, $A14A, $B16B, $C18C, $D1AD, $E1CE, $F1EF,
$1231, $0210, $3273, $2252, $52B5, $4294, $72F7, $62D6,
$9339, $8318, $B37B, $A35A, $D3BD, $C39C, $F3FF, $E3DE,
$2462, $3443, $0420, $1401, $64E6, $74C7, $44A4, $5485,
$A56A, $B54B, $8528, $9509, $E5EE, $F5CF, $C5AC, $D58D,
$3653, $2672, $1611, $0630, $76D7, $66F6, $5695, $46B4,
$B75B, $A77A, $9719, $8738, $F7DF, $E7FE, $D79D, $C7BC,
$48C4, $58E5, $6886, $78A7, $0840, $1861, $2802, $3823,
$C9CC, $D9ED, $E98E, $F9AF, $8948, $9969, $A90A, $B92B,
$5AF5, $4AD4, $7AB7, $6A96, $1A71, $0A50, $3A33, $2A12,
$DBFD, $CBDC, $FBBF, $EB9E, $9B79, $8B58, $BB3B, $AB1A,
$6CA6, $7C87, $4CE4, $5CC5, $2C22, $3C03, $0C60, $1C41,
$EDAE, $FD8F, $CDEC, $DDCD, $AD2A, $BD0B, $8D68, $9D49,
$7E97, $6EB6, $5ED5, $4EF4, $3E13, $2E32, $1E51, $0E70,
$FF9F, $EFBE, $DFDD, $CFFC, $BF1B, $AF3A, $9F59, $8F78,
$9188, $81A9, $B1CA, $A1EB, $D10C, $C12D, $F14E, $E16F,
$1080, $00A1, $30C2, $20E3, $5004, $4025, $7046, $6067,
$83B9, $9398, $A3FB, $B3DA, $C33D, $D31C, $E37F, $F35E,
$02B1, $1290, $22F3, $32D2, $4235, $5214, $6277, $7256,
$B5EA, $A5CB, $95A8, $8589, $F56E, $E54F, $D52C, $C50D,
$34E2, $24C3, $14A0, $0481, $7466, $6447, $5424, $4405,
$A7DB, $B7FA, $8799, $97B8, $E75F, $F77E, $C71D, $D73C,
$26D3, $36F2, $0691, $16B0, $6657, $7676, $4615, $5634,
$D94C, $C96D, $F90E, $E92F, $99C8, $89E9, $B98A, $A9AB,
$5844, $4865, $7806, $6827, $18C0, $08E1, $3882, $28A3,
$CB7D, $DB5C, $EB3F, $FB1E, $8BF9, $9BD8, $ABBB, $BB9A,
$4A75, $5A54, $6A37, $7A16, $0AF1, $1AD0, $2AB3, $3A92,
$FD2E, $ED0F, $DD6C, $CD4D, $BDAA, $AD8B, $9DE8, $8DC9,
$7C26, $6C07, $5C64, $4C45, $3CA2, $2C83, $1CE0, $0CC1,
$EF1F, $FF3E, $CF5D, $DF7C, $AF9B, $BFBA, $8FD9, $9FF8,
$6E17, $7E36, $4E55, $5E74, $2E93, $3EB2, $0ED1, $1EF0);
function GetCRC16(len : Word) : Word; // CCITT: полином x^16 + x^12 + x^5 + 1
var
i : integer;
crc : Word;
P : ^TByteArray absolute egtsAr;
data : Byte;
begin
crc := $FFFF;
for i := 1 to len do begin
data := P^[i];
crc := (crc shl 8) xor Crc16Table[(crc shr 8) xor data];
end;
result := crc;
end;
const Crc8Table: array[0..255] of Byte = (
$00, $31, $62, $53, $C4, $F5, $A6, $97,
$B9, $88, $DB, $EA, $7D, $4C, $1F, $2E,
$43, $72, $21, $10, $87, $B6, $E5, $D4,
$FA, $CB, $98, $A9, $3E, $0F, $5C, $6D,
$86, $B7, $E4, $D5, $42, $73, $20, $11,
$3F, $0E, $5D, $6C, $FB, $CA, $99, $A8,
$C5, $F4, $A7, $96, $01, $30, $63, $52,
$7C, $4D, $1E, $2F, $B8, $89, $DA, $EB,
$3D, $0C, $5F, $6E, $F9, $C8, $9B, $AA,
$84, $B5, $E6, $D7, $40, $71, $22, $13,
$7E, $4F, $1C, $2D, $BA, $8B, $D8, $E9,
$C7, $F6, $A5, $94, $03, $32, $61, $50,
$BB, $8A, $D9, $E8, $7F, $4E, $1D, $2C,
$02, $33, $60, $51, $C6, $F7, $A4, $95,
$F8, $C9, $9A, $AB, $3C, $0D, $5E, $6F,
$41, $70, $23, $12, $85, $B4, $E7, $D6,
$7A, $4B, $18, $29, $BE, $8F, $DC, $ED,
$C3, $F2, $A1, $90, $07, $36, $65, $54,
$39, $08, $5B, $6A, $FD, $CC, $9F, $AE,
$80, $B1, $E2, $D3, $44, $75, $26, $17,
$FC, $CD, $9E, $AF, $38, $09, $5A, $6B,
$45, $74, $27, $16, $81, $B0, $E3, $D2,
$BF, $8E, $DD, $EC, $7B, $4A, $19, $28,
$06, $37, $64, $55, $C2, $F3, $A0, $91,
$47, $76, $25, $14, $83, $B2, $E1, $D0,
$FE, $CF, $9C, $AD, $3A, $0B, $58, $69,
$04, $35, $66, $57, $C0, $F1, $A2, $93,
$BD, $8C, $DF, $EE, $79, $48, $1B, $2A,
$C1, $F0, $A3, $92, $05, $34, $67, $56,
$78, $49, $1A, $2B, $BC, $8D, $DE, $EF,
$82, $B3, $E0, $D1, $46, $77, $24, $15,
$3B, $0A, $59, $68, $FF, $CE, $9D, $AC);
function GetCRC8(S : String) : Byte; // CCITT: полином x^8 + x^5 + x^4 + 1
var
i : integer;
c : byte;
begin
c := $FF;
for i := 1 to length(S) do begin
c := CRC8Table[c xor Byte(S[i])];
end;
result := c;
end;
procedure TForm2.bStartClick(Sender: TObject);
var
i : Word;
begin
AllRData := '';
// Инициализация массива начальных данных
IdTCPClient1.Host := eServer.Text;
if not FDQuery1.Active then
FDQuery1.Active := true
else begin
FDQuery1.First;
FDQuery1.Refresh;
end;
i := 0;
while not FDQuery1.Eof do begin
SetLength(Auto, i+1);
Auto[i].device := FDQuery1.FieldByName('device').AsInteger; // время в секундах с 01.01.2010 00:00 по Гринвичу
Auto[i].lrts := FDQuery1.FieldByName('lrts').AsString;
Inc(i);
FDQuery1.Next;
end;
// Запуск таймера
Timer1.Enabled := True;
Log(DateTimeToStr(Now) + ' - Таймер включён');
bStart.Enabled := False;
bStop.Enabled := True;
end;
procedure TForm2.bStopClick(Sender: TObject);
begin
// Остановка таймера
// Log(AllRData);
Timer1.Enabled := False;
Log(DateTimeToStr(Now) + ' - Таймер остановлен');
bStart.Enabled := True;
bStop.Enabled := False;
if IdTCPClient1.Connected then
IdTCPClient1.Disconnect;
end;
procedure TForm2.FormCreate(Sender: TObject);
begin
bStartClick(self);
end;
procedure TForm2.Memo1Change(Sender: TObject);
const
MaxLineCount = 100;
begin
if Memo1.Lines.Count > MaxLineCount then
Memo1.Lines.Delete(0);
end;
procedure TForm2.Timer1Timer(Sender: TObject);
var
i, j, u, DataSize : Integer;
cs_str, tcpstr, s : String;
BufStream : array[0..16*1024] of Byte;
rhcs : Byte;
rsfrcs : Word;
function Check : Boolean;
var
DevIsFound : Boolean;
k : Integer;
begin
DevIsFound := False;
Result := False;
for k := 0 to High(Auto) do begin
if Auto[k].device = FDQuery1.FieldByName('device').AsInteger then begin
DevIsFound := True;
if Auto[k].lrts = FDQuery1.FieldByName('lrts').AsString then
Result := True
else
Auto[k].lrts := FDQuery1.FieldByName('lrts').AsString;
Break;
end;
end;
if not DevIsFound then begin
SetLength(Auto, High(Auto)+2);
Auto[High(Auto)].device := FDQuery1.FieldByName('device').AsInteger;
Auto[High(Auto)].lrts := FDQuery1.FieldByName('lrts').AsString;
end;
end;
begin
// Переименовать журнал и создать его заново, если начался новый день
Log(Rewrite_Log);
if Executed then
Exit;
try
if not FDQuery1.Active then
FDQuery1.Active := true
else begin
FDQuery1.First;
FDQuery1.Refresh;
end;
except // Блок try добавлен 15.01.2015
on E : Exception do begin
Log(E.ClassName + ' вызвана ошибка, с сообщением : ' + E.Message);
Log('Строка 462');
Exit;
end;
end;
// Запуск TCP клиента, установление соединения
Log('-------------------------------------------------------------------------');
try
if IdTCPClient1.Connected then begin
// Добавлено 14.01.2015
IdTCPClient1.Disconnect;
IdTCPClient1.IOHandler.DiscardAll;
IdTCPClient1.IOHandler.Close;
end;
IdTCPClient1.Connect;
Log(DateTimeToStr(Now) + ' - Соединение с сервером ' + IdTCPClient1.Host + ':' + IntToStr(IdTCPClient1.Port) + ' установлено');
except
// Добавлено 14.01.2015
on E : Exception do begin
Log(E.ClassName + ' вызвана ошибка, с сообщением : ' + E.Message);
Exit;
end;
end;
Log(DateTimeToStr(Now) + ' - Начало передачи блока данных');
try
Executed := True;
LoadCounter;
while not FDQuery1.Eof do begin
if Check then begin
FDQuery1.Next;
Continue;
end;
Inc(Counter);
// Формируем массив записей с подзаписью типа EGTS_SR_POS_DATA
i := 0;
SetLength(egtsAr, i+1);
with egtsAr[i] do begin
// Запись
RL := SizeOf(TEGTS_SR_POS_DATA) + SizeOf(SRT) + SizeOf(SRL); // !!!Длина RD - меняется в зависимости от типа
RN := Counter;
RFL := $81; // +SSOD -RSOD -GRP --RPP(2 бита) -TMFE -EVFE +OBFE
OID := 22000000 + FDQuery1.FieldByName('device').AsInteger;
SST := EGTS_TELEDATA_SERVICE;
RST := EGTS_TELEDATA_SERVICE; // Аналогично
// Заголовок подзаписи
SRT := EGTS_SR_POS_DATA; // Тип подзаписи. Для сервиса EGTS_AUTH_SERVICE: EGTS_SR_TERM_IDENTITY=1
// Для сервиса EGTS_TELEDATA_SERVICE: EGTS_SR_POS_DATA = 16
SRL := SizeOf(TEGTS_SR_POS_DATA); // !!! Длина подзаписи
// Подзапись типа EGTS_SR_POS_DATA
NTM := Round(FDQuery1.FieldByName('lrts').AsFloat / 1000) - 1262304000; // время в секундах с 01.01.2010 00:00 по Гринвичу
LAT := Round(FDQuery1.FieldByName('lat').AsInteger/90*$FFFFFFFF);
LONG := Round(FDQuery1.FieldByName('lng').AsInteger/180*$FFFFFFFF);
FLG := 0;
SPD := FDQuery1.FieldByName('speed').AsInteger;
DIRH_ALTS_SPD := 0;
DIR := 0;
ODM := NullArr3;
DIN := 0;
SRC := 0;
ALT := NullArr3;
SRCD := 0;
Inc(i);
end;
// Формируем запись для протокола TCP
with tcp do begin
prv := 1;
skid := 0;
prefix := 3; // Флаги
hl := 11; // длина заголовка, включая hcs
he := 0;
fdl := sizeof(TRecSubRec_EGTS_SR_POS_DATA)*i;
pid := Counter;
pt := 1; // тип пакета 1 - EGTS_PT_APPDATA (пакет, содержащий данные протокола Уровня поддержки услуг)
// pra := 0;
// rca := 0;
// ttl := 0;
cs_str :=
Char(prv)+Char(skid)+Char(prefix)+Char(hl)+Char(he)+
Char(fdl mod $100)+Char(fdl div $100)+
Char(pid mod $100)+Char(pid div $100)+Char(pt)
// +
// Char(pra mod $100)+Char(pra div $100)+
// Char(rca mod $100)+Char(rca div $100)+Char(ttl)
;
hcs := GetCRC8(cs_str); // контрольная сумма CRC-8
sfrd := egtsAr;
sfrcs := GetCRC16(sizeof(TRecSubRec_EGTS_SR_POS_DATA)*i);
end;
// Формируем поток данных для протокола TCP на основе записи
with tcp do begin
TcpStream := TMemoryStream.Create;
try
DataSize := 0;
// Формирование в потоке данных подзаписи типа EGTS_SR_POS_DATA
TcpStream.Write(prv, SizeOf(prv)); Inc(DataSize, SizeOf(prv));
TcpStream.Write(skid, SizeOf(skid)); Inc(DataSize, SizeOf(skid));
TcpStream.Write(prefix, SizeOf(prefix)); Inc(DataSize, SizeOf(prefix));
TcpStream.Write(hl, SizeOf(hl)); Inc(DataSize, SizeOf(hl));
TcpStream.Write(he, SizeOf(he)); Inc(DataSize, SizeOf(he));
TcpStream.Write(fdl, SizeOf(fdl)); Inc(DataSize, SizeOf(fdl));
TcpStream.Write(pid, SizeOf(pid)); Inc(DataSize, SizeOf(pid));
TcpStream.Write(pt, SizeOf(pt)); Inc(DataSize, SizeOf(pt));
// TcpStream.Write(pra, SizeOf(pra)); Inc(DataSize, SizeOf(pra));
// TcpStream.Write(rca, SizeOf(rca)); Inc(DataSize, SizeOf(rca));
// TcpStream.Write(ttl, SizeOf(ttl)); Inc(DataSize, SizeOf(ttl));
TcpStream.Write(hcs, SizeOf(hcs)); Inc(DataSize, SizeOf(hcs));
// Заголовок SFRD
for j := 0 to i-1 do begin
TcpStream.Write(sfrd[j], SizeOf(sfrd[j]));
Inc(DataSize, SizeOf(sfrd[j]));
end;
TcpStream.Write(sfrcs, SizeOf(sfrcs)); Inc(DataSize, SizeOf(sfrcs));
TcpStream.Position := 0;
TcpStream.Read(BufStream, TcpStream.Size);
tcpstr := '';
for u := 0 to TcpStream.Size - 1 do
tcpstr := tcpstr + IntToHex(BufStream[u], 2);
TcpStream.Position := 0;
Log('Сформирован пакет: ');
Log(tcpstr);
try
IdTCPClient1.IOHandler.Write(TcpStream); //tcp.hl + tcp.fdl + 2
except
on E : Exception do begin
Log(E.ClassName + ' вызвана ошибка, с сообщением : ' + E.Message);
Exit;
end;
end;
Log(
'Отправлен пакет: prv=' + IntToStr(prv) +
', skid=' + IntToStr(skid) +
', prefix=' + IntToStr(prefix) +
', hl=' + IntToStr(hl) +
', he=' + IntToStr(he) +
', fdl=' + IntToStr(fdl) +
', pid=' + IntToStr(pid) +
', hcs(полином 0x31)=0x' + ByteToHex(hcs) +
', sfrcs(полином 0x1021)=0x' + ByteToHex(sfrcs div $100) + ByteToHex(sfrcs)
);
// Log('Количество подзаписей типа EGTS_SR_POS_DATA: ' + IntToStr(i));
Log(
'Устройство: device=' + IntToStr(sfrd[0].OID) +
', lrts=' + FDQuery1.FieldByName('lrts').AsString
);
SaveCounter;
finally
TcpStream.Free;
end;
// Чтение ответа-подтверждения
try
SetLength(BufH, 0);
SetLength(Buf, 0);
IdTCPClient1.IOHandler.ReadBytes(BufH, 14, False);
s := '';
for j := 0 to Length(BufH)-1 do
s := s + ByteToHex(BufH[j]);
// AllRData := AllRData + s;
Log(
'Получено подтверждение о приёме на пакет: pid=' + IntToStr(BufH[12]*$100 + BufH[11]) +
'; Код исполнения: ' + IntToStr(BufH[13]) +
'; Длина записи: ' + IntToStr(BufH[6]*$100+BufH[5])
);
if BufH[6]*$100+BufH[5] > 1 then
IdTCPClient1.IOHandler.ReadBytes(Buf, BufH[6]*$100+BufH[5]-1, False);
for j := 0 to Length(Buf)-1 do
s := s + ByteToHex(Buf[j]);
// AllRData := AllRData + s;
Log(s);
// Проверка контрольной суммы HCS
cs_str := '';
for j := 0 to BufH[3]-2 do
cs_str := cs_str + Char(BufH[j]);
rhcs := GetCRC8(cs_str); // контрольная сумма CRC-8
if rhcs = BufH[BufH[3]-1] then
Log('Контрольная сумма HCS (CRC-8) совпадает и равна: 0x' + ByteToHex(rhcs))
else
Log('Контрольная сумма HCS = 0x' + ByteToHex(BufH[BufH[3]-1]) + ' ошибочна, должна быть: 0x' + ByteToHex(rhcs));
// IdTCPClient1.IOHandler.ReadBytes(Buf, -1, False);
except
Log('Первышено время жидания ответа на пакет: pid=' + IntToStr(pid));
end;
end;
FDQuery1.Next;
end;
finally
Log(DateTimeToStr(Now) + ' - Окончание передачи блока данных');
Memo1.GoToTextEnd;
Executed := False;
// Добавлено 14.01.2015
if IdTCPClient1.Connected then
IdTCPClient1.Disconnect;
end;
end;
end.
|
unit MaskEditor;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, maskgenerator, dsgnintf;
type
TCoolMaskEditor = class(TPropertyEditor)
private
FValue:string;
public
destructor destroy;override;
procedure Edit;override;
function GetAttributes: TPropertyAttributes;override;
function getname:string; override;
function getValue:string; override;
published
property Value:string read FValue write FValue;
end;
var
FormCreated:boolean=false;
implementation
uses
CoolForm;
function TCoolMaskEditor.getname:string;
begin
result:='Mask';
end;
function TCoolMaskEditor.getValue:string;
begin
result:='Mask';
end;
destructor TCoolMaskEditor.Destroy;
begin
if Formmaskgenerator<>nil then
begin
FormMaskGenerator.Free;
FormMaskGenerator:=nil;
FormCreated:=false;
end;
inherited;
end;
function TCoolMaskEditor.GetAttributes: TPropertyAttributes;
begin
// Make Delphi display the (...) button in the objectinspector
Result := [paDialog];
end;
procedure TCoolMaskEditor.Edit;
//******************* Unknown *************************
begin
// Create the maskeditorform if it doesn`t exist yet
if not assigned(FormMaskGenerator) then
begin
formMaskGenerator:=TFormMaskGenerator.Create(nil);
formMaskGenerator.OriginalRegionData:=nil;
formMaskGenerator.SaveOriginalRegionData;
FormCreated:=true;
end;
with formMaskGenerator do
begin
// Set the existing mask in the editor
formMaskGenerator.Rgn1:=hrgn(TRegionType(GetOrdValue).Fregion);
// copy the bitmap into the editor
Image1.picture.bitmap.Assign(TRegionType(GetOrdValue).owner.picture.bitmap);
opendialog1.filename:='';
Showmodal;
// get the new region from the editor
hrgn(TRegionType(GetOrdValue).Fregion):=formMaskGenerator.Rgn1;
// note: the editorform must not be freed here
// if done, delphi eats lines of the sourcecode of the form in which coolform is used
// (every line where a visible component is defined) ... rather strange
end;
end;
end.
|
unit LogSocket;
interface
uses
SysUtils, Classes, Windows, Types, IOCPSocket, BaseSocket, Logger, DefineUnit;
type
TLogSocket = class(TBaseSocket)
private
{* 日志写到SOCKET实现类 *}
FLogSocketHandler: TLogSocketHandler;
protected
{ *处理数据接口,每个子类在这编写命令处理,外部已有锁处理,这里不再加锁* }
procedure Execute(AData: PByte; const ALen: Cardinal); override;
public
procedure DoCreate; override;
destructor Destroy; override;
procedure WriteLogToClient(const LogType: TLogType; const LogMsg: string);
end;
implementation
uses OptionSet;
{ TLogSocket }
procedure TLogSocket.DoCreate;
begin
inherited;
LenType := IOCPSocket.ltNull;
FSocketFlag := sfLog;
OpenWriteBuffer;
WriteString(CSCrLf + CSCompanyName + ' ' + CSSoftwareName + ' Log output' + CSCrLf);
WriteString('Press ESC to exit...' + CSCrLf);
FlushWriteBuffer(ioWrite);
FLogSocketHandler := TLogSocketHandler.Create(GLogger);
FLogSocketHandler.OnLog := WriteLogToClient;
FLogSocketHandler.LogFilter := GIniOptions.LogSocket;
GLogger.LogHandlerMgr.Add(FLogSocketHandler);
end;
destructor TLogSocket.Destroy;
begin
GLogger.LogHandlerMgr.Delete(FLogSocketHandler);
FLogSocketHandler.Free;
inherited;
end;
procedure TLogSocket.Execute(AData: PByte; const ALen: Cardinal);
var
vkByte: Byte;
begin
inherited;
if ALen = 1 then
begin
vkByte := AData^;
if vkByte = VK_ESCAPE then
Disconnect //忽略所有输入,如果为ESC则退出
end
else
begin
OpenWriteBuffer;
WriteString(CSCompanyName + ' ' + CSSoftwareName + ' Log output' + CSCrLf);
WriteString('Press ESC to exit...' + CSCrLf);
FlushWriteBuffer(ioWrite);
end;
end;
procedure TLogSocket.WriteLogToClient(const LogType: TLogType;
const LogMsg: string);
var
s: string;
begin
s := LogMsg + CSCrLf;
try
if Connected then
begin
OpenWriteBuffer;
WriteString(s);
FlushWriteBuffer(ioWrite);
end;
except
;
end;
end;
end.
|
{*******************************************************************************
Title: T2Ti ERP
Description: VO relacionado à tabela [TRIBUT_CONFIGURA_OF_GT]
The MIT License
Copyright: Copyright (C) 2014 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
t2ti.com@gmail.com
@author Albert Eije (t2ti.com@gmail.com)
@version 2.0
*******************************************************************************}
unit TributConfiguraOfGtVO;
interface
uses
VO, Atributos, Classes, Constantes, Generics.Collections, SysUtils, DB,
TributGrupoTributarioVO, TributOperacaoFiscalVO, TributPisCodApuracaoVO,
TributCofinsCodApuracaoVO, TributIpiDipiVO, TributIcmsUfVO;
type
[TEntity]
[TTable('TRIBUT_CONFIGURA_OF_GT')]
TTributConfiguraOfGtVO = class(TVO)
private
FID: Integer;
FID_TRIBUT_GRUPO_TRIBUTARIO: Integer;
FID_TRIBUT_OPERACAO_FISCAL: Integer;
FTributGrupoTributarioDescricao: String;
FTributOperacaoFiscalDescricao: String;
FTributGrupoTributarioVO: TTributGrupoTributarioVO;
FTributOperacaoFiscalVO: TTributOperacaoFiscalVO;
FTributPisCodApuracaoVO: TTributPisCodApuracaoVO; //0:1
FTributCofinsCodApuracaoVO: TTributCofinsCodApuracaoVO; //0:1
FTributIpiDipiVO: TTributIpiDipiVO; //0:1
FListaTributIcmsUfVO: TObjectList<TTributIcmsUfVO>; //0:N
public
constructor Create; override;
destructor Destroy; override;
[TId('ID', [ldGrid, ldLookup, ldCombobox])]
[TGeneratedValue(sAuto)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property Id: Integer read FID write FID;
[TColumn('ID_TRIBUT_GRUPO_TRIBUTARIO', 'Id Grupo Tributario', 80, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property IdTributGrupoTributario: Integer read FID_TRIBUT_GRUPO_TRIBUTARIO write FID_TRIBUT_GRUPO_TRIBUTARIO;
[TColumnDisplay('TRIBUT_GRUPO_TRIBUTARIO.DESCRICAO', 'Descrição Grupo Tributário', 400, [ldGrid, ldLookup], ftString, 'TributGrupoTributarioVO.TTributGrupoTributarioVO', True)]
property TributGrupoTributarioDescricao: String read FTributGrupoTributarioDescricao write FTributGrupoTributarioDescricao;
[TColumn('ID_TRIBUT_OPERACAO_FISCAL', 'Id Operacao Fiscal', 80, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property IdTributOperacaoFiscal: Integer read FID_TRIBUT_OPERACAO_FISCAL write FID_TRIBUT_OPERACAO_FISCAL;
[TColumnDisplay('TRIBUT_OPERACAO_FISCAL.DESCRICAO', 'Descrição Operação', 400, [ldGrid, ldLookup], ftString, 'TributOperacaoFiscalVO.TTributOperacaoFiscalVO', True)]
property TributOperacaoFiscalDescricao: String read FTributOperacaoFiscalDescricao write FTributOperacaoFiscalDescricao;
[TAssociation('ID', 'ID_TRIBUT_OPERACAO_FISCAL')]
property TributOperacaoFiscalVO: TTributOperacaoFiscalVO read FTributOperacaoFiscalVO write FTributOperacaoFiscalVO;
[TAssociation('ID', 'ID_TRIBUT_GRUPO_TRIBUTARIO')]
property TributGrupoTributarioVO: TTributGrupoTributarioVO read FTributGrupoTributarioVO write FTributGrupoTributarioVO;
[TAssociation('ID_TRIBUT_CONFIGURA_OF_GT', 'ID')]
property TributPisCodApuracaoVO: TTributPisCodApuracaoVO read FTributPisCodApuracaoVO write FTributPisCodApuracaoVO;
[TAssociation('ID_TRIBUT_CONFIGURA_OF_GT', 'ID')]
property TributCofinsCodApuracaoVO: TTributCofinsCodApuracaoVO read FTributCofinsCodApuracaoVO write FTributCofinsCodApuracaoVO;
[TAssociation('ID_TRIBUT_CONFIGURA_OF_GT', 'ID')]
property TributIpiDipiVO: TTributIpiDipiVO read FTributIpiDipiVO write FTributIpiDipiVO;
[TManyValuedAssociation('ID_TRIBUT_CONFIGURA_OF_GT', 'ID')]
property ListaTributIcmsUfVO: TObjectList<TTributIcmsUfVO>read FListaTributIcmsUfVO write FListaTributIcmsUfVO;
end;
implementation
constructor TTributConfiguraOfGtVO.Create;
begin
inherited;
FTributOperacaoFiscalVO := TTributOperacaoFiscalVO.Create;
FTributGrupoTributarioVO := TTributGrupoTributarioVO.Create;
FTributPisCodApuracaoVO := TTributPisCodApuracaoVO.Create;
FTributCofinsCodApuracaoVO := TTributCofinsCodApuracaoVO.Create;
FTributIpiDipiVO := TTributIpiDipiVO.Create;
FListaTributIcmsUfVO := TObjectList<TTributIcmsUfVO>.Create;
end;
destructor TTributConfiguraOfGtVO.Destroy;
begin
FreeAndNil(FTributOperacaoFiscalVO);
FreeAndNil(FTributGrupoTributarioVO);
FreeAndNil(FTributPisCodApuracaoVO);
FreeAndNil(FTributCofinsCodApuracaoVO);
FreeAndNil(FTributIpiDipiVO);
FreeAndNil(FListaTributIcmsUfVO);
inherited;
end;
initialization
Classes.RegisterClass(TTributConfiguraOfGtVO);
finalization
Classes.UnRegisterClass(TTributConfiguraOfGtVO);
end.
|
unit MuseumUnit;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, DataUnit,
FMX.StdCtrls, FMX.Objects, FMX.Controls.Presentation, FMX.ImgList, FMX.Layouts, FMX.ani,
Forms, FMX.Memo, FMX.ScrollBox;
type
TMuseumForm = class(TBarForm)
Main: TLayout;
controls: TLayout;
lBack: TLayout;
lNext: TLayout;
logoLayout: TLayout;
Logo: TGlyph;
SPanel: TPanel;
nextLayout: TLayout;
NextBtn: TSpeedButton;
SubName: TText;
SubText: TMemo;
SubLogo: TGlyph;
backLayout: TLayout;
BackBtn: TSpeedButton;
progress: TLayout;
Img: TGlyph;
procedure logoLayoutClick(Sender: TObject);
procedure BackBtnClick(Sender: TObject);
procedure NextBtnClick(Sender: TObject);
protected
procedure onCreate; override;
end;
var
MuseumForm: TMuseumForm;
implementation
{$R *.fmx}
uses
ResourcesManager, SoundManager;
var
dots: TArray<TGlyph>;
procedure TMuseumForm.BackBtnClick(Sender: TObject);
begin
SM.play(sClick);
dots[img.ImageIndex].ImageIndex:=0;
if img.ImageIndex>0 then
img.ImageIndex:=img.ImageIndex-1
else
img.ImageIndex:=img.Images.Count-1;
setItem(img.ImageIndex, SubText);
dots[img.ImageIndex].ImageIndex:=1;
end;
procedure TMuseumForm.NextBtnClick(Sender: TObject);
begin
SM.play(sClick);
dots[img.ImageIndex].ImageIndex:=0;
if img.ImageIndex<img.Images.Count-1 then
img.ImageIndex:=img.ImageIndex+1
else
img.ImageIndex:=0;
setItem(img.ImageIndex, SubText);
dots[img.ImageIndex].ImageIndex:=1;
end;
procedure TMuseumForm.logoLayoutClick(Sender: TObject);
begin
SM.play(sClick);
Close;
end;
procedure TMuseumForm.onCreate;
var
g, cl: TGlyph;
i: byte;
begin
layouts:=[main];
img.ImageIndex:=0;
setItem(img.ImageIndex, SubText);
setLength(dots, img.Images.Count);
g:=TGlyph.Create(self);
with g do
begin
Align:=TAlignLayout.Right;
Height:=30;
Width:=30;
Margins.Right:=10;
end;
for i:=img.Images.Count-1 downto 0 do
begin
cl:=g.Clone(self) as TGlyph;
cl.Images:=getImgList(rProgress);
cl.ImageIndex:=0;
dots[i]:=cl;
progress.AddObject(cl);
end;
g.Free;
dots[0].ImageIndex:=1;
end;
end.
|
unit uAttributesEverywhere;
interface
type
SampleAttribute = class(TCustomAttribute);
[Sample]
TStopLight = (Red, Yellow, Green);
[Sample]
TAttributesEverywhere = class
private
[Sample]
FSomeProperty: Extended;
procedure SetSomeProperty(const Value: Extended);
public
[Sample]
procedure DoThis([Sample]aString: string);
[Sample]
function DoThat([Sample]aObject: TObject): integer;
[Sample]
property SomeProperty: Extended read FSomeProperty write SetSomeProperty;
end;
procedure DoAttributesEverywhere;
type
FirstAttribute = class(TCustomAttribute);
SecondAttribute = class(TCustomAttribute);
ThirdAttribute = class(TCustomAttribute);
[First] [Second]
[Third]
TMultipleAttributes = class(TObject);
procedure DoMultipleAttributes;
implementation
uses
RTTI
;
procedure DoAttributesEverywhere;
var
Context: TRTTIContext;
TempClassType: TRttiType;
TempEnumType: TRttiOrdinalType;
TempAttribute: TCustomAttribute;
TempAttribute1: TCustomAttribute;
TempField: TRttiField;
TempMethod: TRttiMethod;
TempParam: TRttiParameter;
TempProperty: TRttiProperty;
begin
// Enum
TempEnumType := Context.GetType(TypeInfo(TStopLight)).AsOrdinal;
for TempAttribute in TempEnumType.GetAttributes do
begin
WriteLn(TempEnumType.Name, ' has the following attributes: ');
Write(' ', TempAttribute.ToString);
end;
WriteLn;
WriteLn;
// Class
TempClassType := Context.GetType(TAttributesEverywhere);
WriteLn('TAttributesEverywhere has the following attributes:');
for TempAttribute in TempClassType.GetAttributes do
begin
WriteLn(' Class Attribute: ', TempAttribute.ToString);
end;
WriteLn;
for TempField in TempClassType.GetFields do
begin
WriteLn('The ', TempField.Name, ' has the following attributes:');
for TempAttribute in TempField.GetAttributes do
begin
WriteLn(' ', TempAttribute.ToString);
end;
end;
WriteLn;
for TempMethod in TempClassType.GetMethods do
begin
for TempAttribute in TempMethod.GetAttributes do
begin
WriteLn('The ', TempMethod.Name, 'method has the ', TempAttribute.ToString, ' attribute.');
for TempParam in TempMethod.GetParameters do
begin
for TempAttribute1 in TempParam.GetAttributes do
begin
WriteLn(' The ', TempParam.Name, ' parameter has the ', TempAttribute1.ToString, ' attribute.');
end;
if TempMethod.ReturnType <> nil then
begin
Writeln(' The ', TempMethod.Name, ' method is a function that returns a ', TempMethod.ReturnType.Name, '.');
end else
begin
WriteLn(' The ', TempMethod.Name, ' method is a procedure.');
end;
end;
end;
end;
WriteLn;
for TempProperty in TempClassType.GetProperties do
begin
for TempAttribute in TempProperty.GetAttributes do
begin
WriteLn('The ', TempProperty.Name, ' has the ', TempAttribute.ToString, ' property.');
end;
end;
end;
procedure DoMultipleAttributes;
var
Context: TRTTIContext;
TempType: TRttiType;
TempAttribute: TCustomAttribute;
begin
TempType := Context.GetType(TMultipleAttributes);
WriteLn(TMultipleAttributes.ClassName, ' has the following attributes: ');
for TempAttribute in TempType.GetAttributes do
begin
WriteLn(' ', TempAttribute.ToString);
end;
end;
{ TAttributesEverywhere }
function TAttributesEverywhere.DoThat(aObject: TObject): integer;
begin
Result := aObject.GetHashCode;
end;
procedure TAttributesEverywhere.DoThis(aString: string);
begin
WriteLn(aString);
end;
procedure TAttributesEverywhere.SetSomeProperty(const Value: Extended);
begin
FSomeProperty := Value;
end;
end.
|
{ Este exemplo foi baixado no site www.andrecelestino.com
Passe por lá a qualquer momento para conferir os novos artigos! :)
contato@andrecelestino.com }
unit UnitImportacaoExcel;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Grids, DBGrids, DB, DBClient, StdCtrls, ExtCtrls, Buttons;
type
TFrmImportacaoExcel = class(TForm)
cdsClientes: TClientDataSet;
cdsProdutos: TClientDataSet;
cdsUsuarios: TClientDataSet;
dsClientes: TDataSource;
dsProdutos: TDataSource;
dsUsuarios: TDataSource;
gridClientes: TDBGrid;
gridProdutos: TDBGrid;
gridUsuarios: TDBGrid;
btnImportar: TBitBtn;
Bevel: TBevel;
cdsClientesCodigo: TIntegerField;
cdsClientesNome: TStringField;
cdsProdutosCodigo: TIntegerField;
cdsProdutosDescricao: TStringField;
cdsUsuariosCodigo: TIntegerField;
cdsUsuariosNome: TStringField;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
procedure btnImportarClick(Sender: TObject);
private
procedure ImportarPlanilha(var ArquivoExcel: OLEVariant; var DataSet: TClientDataSet; const Planilha: integer);
end;
var
FrmImportacaoExcel: TFrmImportacaoExcel;
implementation
uses
ComObj;
{$R *.dfm}
procedure TFrmImportacaoExcel.btnImportarClick(Sender: TObject);
var
Excel: OLEVariant;
CaminhoArquivo: string;
begin
// carrega o arquivo XLSX que está na mesma pasta do executável
CaminhoArquivo := ExtractFilePath(Application.ExeName) + 'ArquivoExcel.xlsx';
// cria uma instância do Excel
Excel := CreateOleObject('Excel.Application');
try
Screen.Cursor := crHourGlass;
// evita que o Excel seja exibido na tela
Excel.Visible := False;
// abre o arquivo XLSX
Excel.Workbooks.Open(CaminhoArquivo);
// importação da primeira planilha (Clientes)
ImportarPlanilha(Excel, cdsClientes, 1);
// importação da segunda planilha (Produtos)
ImportarPlanilha(Excel, cdsProdutos, 2);
// importação da terceira planilha (Usuários)
ImportarPlanilha(Excel, cdsUsuarios, 3);
finally
if not VarIsEmpty(Excel) then
begin
Excel.Quit;
Excel := Unassigned;
end;
Screen.Cursor := crDefault;
end;
end;
procedure TFrmImportacaoExcel.ImportarPlanilha(var ArquivoExcel: OLEVariant;
var DataSet: TClientDataSet; const Planilha: integer);
var
Linha: integer;
begin
// ativa a planilha
ArquivoExcel.Workbooks[1].WorkSheets[Planilha].Activate;
// linha da planilha que contém os valores
Linha := 2;
// limpa o conteúdo existente no DataSet
DataSet.EmptyDataSet;
// desabilita os controles (para evitar o efeito de navegação enquanto insere os registros
DataSet.DisableControls;
// loop para inserção de cada linha até que encontre uma linha em branco
while not (ArquivoExcel.WorkBooks[1].Sheets[3].Cells[Linha, 1].Value = varEmpty) do
begin
DataSet.Append;
DataSet.Fields[0].AsInteger := ArquivoExcel.WorkBooks[1].Sheets[Planilha].Cells[Linha, 1];
DataSet.Fields[1].AsString := ArquivoExcel.WorkBooks[1].Sheets[Planilha].Cells[Linha, 2];
DataSet.Post;
Inc(Linha); // move para a próxima linha
end;
// move para o primeiro registro após todas as inserções
DataSet.First;
// habilita os controles para navegação
DataSet.EnableControls;
end;
end.
|
unit HttpXmlDataSet;
interface
uses
SysUtils, DBClient, xmlxform, IdHttp, Classes;
type
EHttpXMLError=class(Exception)
end;
THttpXMLDataSet=class(TClientDataSet)
private
transform:TXMLTransform;
http:TIdHTTP;
fURL:String;
fOpened:boolean;
fTransformationFile:String;
FProxyPort: integer;
FProxyServer: String;
FProxyUsername: String;
FProxyPassword: String;
function getOpened(): boolean;
procedure setOpened(opened: boolean);
function getURL(): String;
procedure setURL(url: String);
function getTransformationFile(): String;
procedure setTransformationFile(transformationFile: String);
procedure SetProxyPort(const Value: integer);
procedure SetProxyServer(const Value: String);
procedure SetProxyPassword(const Value: String);
procedure SetProxyUsername(const Value: String);
public
constructor Create(AOwner: TComponent); override;
procedure Open();
published
property Opened: boolean read getOpened write setOpened;
property URL: String read getURL write setURL;
property transformationFile: String read getTransformationFile write setTransformationFile;
property ProxyServer: String read FProxyServer write SetProxyServer;
property ProxyPort: integer read FProxyPort write SetProxyPort;
property ProxyUsername: String read FProxyUsername write SetProxyUsername;
property ProxyPassword: String read FProxyPassword write SetProxyPassword;
end;
procedure Register;
implementation
constructor THttpXMLDataSet.Create(AOwner:TComponent);
begin
inherited;
transform:=TXMLTransform.Create(self);
http:=TIdHTTP.Create(Self);
http.ProxyParams.ProxyServer := ProxyServer;
http.ProxyParams.ProxyPort := ProxyPort;
http.ProxyParams.ProxyUsername := ProxyUsername;
http.ProxyParams.ProxyPassword := ProxyPassword;
end;
procedure THttpXMLDataSet.Open;
var
data:String;
begin
fOpened:=true;
data:=http.Get(URL);
if (data='') then
raise EHttpXMLError.Create('Ошибка получения информации с сервера.'#10#13'Проверьте соединение с интернетом.');
try
XMLData:=transform.TransformXML(data,transformationFile);
inherited Open;
except on E:Exception do
begin
raise EHttpXMLError.Create('Ошибка обработки информации с сервера:'#10#13+E.Message);
exit;
end;
end;
end;
function THttpXMLDataSet.getOpened:boolean;
begin
Result:=fOpened;
end;
procedure THttpXMLDataSet.setOpened(opened:boolean);
begin
if (fOpened<>opened) then
begin
if (opened=true) then
Open
else
begin
Close;
fOpened:=false;
end;
end
end;
function THttpXMLDataSet.getURL:String;
begin
Result:=fURL;
end;
procedure THttpXMLDataSet.setURL(url:String);
begin
fURL:=url;
end;
function THttpXMLDataSet.getTransformationFile:String;
begin
Result:=fTransformationFile;
end;
procedure THttpXMLDataSet.setTransformationFile(transformationFile:String);
begin
self.fTransformationFile:=transformationFile;
end;
procedure Register;
begin
RegisterComponents('Samples', [THttpXMLDataSet]);
end;
procedure THttpXMLDataSet.SetProxyPort(const Value: integer);
begin
FProxyPort := Value;
if (http <> nil) then
http.ProxyParams.ProxyPort := Value;
end;
procedure THttpXMLDataSet.SetProxyServer(const Value: String);
begin
FProxyServer := Value;
if (http <> nil) then
http.ProxyParams.ProxyServer := Value;
end;
procedure THttpXMLDataSet.SetProxyPassword(const Value: String);
begin
FProxyPassword := Value;
if (http <> nil) then
http.ProxyParams.ProxyPassword := Value;
end;
procedure THttpXMLDataSet.SetProxyUsername(const Value: String);
begin
FProxyUsername := Value;
if (http <> nil) then
http.ProxyParams.ProxyUsername := Value;
end;
end.
|
{ *******************************************************************************
Title: T2TiPDV
Description: DataModule
The MIT License
Copyright: Copyright (C) 2014 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
t2ti.com@gmail.com
@author Albert Eije
@version 2.0
******************************************************************************* }
unit UDataModule;
interface
uses
SysUtils, Forms, ACBrBase, ACBrECF, DBXMySql, FMTBcd, DBClient, DB, SqlExpr,
Classes, WideStrings, StdCtrls, Controls, Windows, ACBrPAF, ACBrSpedFiscal,
ACBrSintegra, Dialogs, Inifiles, DBXFirebird, DBXMsSQL, ACBrECFClass, ACBrEAD;
type
TFDataModule = class(TDataModule)
ACBrECF: TACBrECF;
ACBrPAF: TACBrPAF;
ACBrSintegra: TACBrSintegra;
ACBrSpedFiscal: TACBrSPEDFiscal;
ACBrEAD: TACBrEAD;
procedure ACBrECFMsgPoucoPapel(Sender: TObject);
procedure ACBrPAFPAFGetKeyRSA(var Chave: AnsiString);
private
{ Private declarations }
public
{ Public declarations }
RemoteAppPath, BancoPAF: String;
end;
var
FDataModule: TFDataModule;
implementation
uses USplash, Biblioteca, UNotaFiscal;
{$R *.dfm}
procedure TFDataModule.ACBrECFMsgPoucoPapel(Sender: TObject);
begin
//
end;
procedure TFDataModule.ACBrPAFPAFGetKeyRSA(var Chave: AnsiString);
begin
Chave := '-----BEGIN RSA PRIVATE KEY-----' + sLineBreak +
'MIICXQIBAAKBgQCodI47bNyjNmKa8A1BMDr0jR3ZpnQhHnF/y9Z5G/wwUsZKYZL6' + sLineBreak +
'CzN7PylrtasCDDMLGDWwQbVP8JnduJwOTl2EvrYKSfUVkrf/YlKS7cRCWGbDXHF+' + sLineBreak +
'LZ4Eshb1JAQTluiY/zk28FdBcUXpUA8Memvkstp69CPBULVXGSjToded9wIDAQAB' + sLineBreak +
'AoGAdDZUmTJ01DQEupa4ziwTv/pKiYiHvQFfk6ZwA4UG6d9w5IeD+fQYRAJC9QeT' + sLineBreak +
'PgpkfFbrUvlBuDBoNcnR/xyY7oiBovZdX8qYA2b2tMZKbU6P0FQHqcK0HZJqJ0Y9' + sLineBreak +
'hQ4SmK8v4LbRSD+rzUHCyZ23pzD91eMKGtC7goUleiQo4WECQQDTJ80z7hXHTP+o' + sLineBreak +
'Zb6+74amIP73+IIXcHZwzIhsLhbEXlEjlsmxYNrY3QE4Op+FWZJUtvbMKL2ve7tw' + sLineBreak +
'/Ro/OAqlAkEAzDs1/zfRYyTMgBc00ehCP2QlQzOUF6O2lA0ay4NkJhgAadIgM7HZ' + sLineBreak +
'FHUQVMzdSvLnE5KpF2ycPo2vT/nmlUWPawJAAyrKqie9DeM6xnTYOpbvJxjBmkiQ' + sLineBreak +
'8vcN371BopXCY6mif+0oE1AHmE8gUI6Yi/B/AGRKKV/HEJXDhvtU5HPbvQJBALku' + sLineBreak +
'dyeTVSiwlT0PzbUHBAq2o5LrkbxdlY9o0oL2ADkKSlWpUcmN2WfTPZumpoDu/teg' + sLineBreak +
'g/HZaVLO5cd+sLVo/UECQQCfsxvunOswXJHp6JmLMSyN0rzvE4Mwy6PdART1KLtL' + sLineBreak +
'CNQllWVutMNQOccb+f1afqoGOOj161UYPvLEYgpysOlN' + sLineBreak +
'-----END RSA PRIVATE KEY-----';
end;
end.
|
unit DataAccess;
interface
uses
AdoDB,DB,AdoInt,Windows,Classes,Contnrs,WinSock,SyncObjs,SysUtils,
ExtCtrls,DataAccessProvider,Provider,DBClient,Dialogs;
const
dbtAccess = $00000000;
dbtSqlServer = $00000001;
dbtOracle = $00000002;
dbtInterbase = $00000003;
dbtDb2 = $00000004;
dbtMySql = $00000005;
{DBMS_ID}
SQLSERVER_DBMS_ID ='SqlServer';
ACCESS_DBMS_ID ='Access';
ORACLE_DBMS_ID ='Oracle';
INTERBASE_DBMS_ID ='Interbase';
DB2_DBMS_ID ='Db2';
MYSQL_DBMS_ID ='MySql';
type
TConnectInPoolStatus=(psNone,psUse,psUnUse);
EDataAccessException=class(Exception);
EUnSupportException=class(Exception);
TConnectStringBulider=class(TPersistent)
private
FUser: string;
FPassword: string;
FDatabase: string;
FDataSource: string;
FDbType: Integer;
FConnStr:string;
function GetConnectionString: string;
function GetWorkStation: string;
procedure SetConnectionString(const Value: string);
procedure SetDatabaseType(const Value: Integer);
function GetDBMSDescription: string;
function GetDBMSID: string;
procedure SetDataSource(const Value: string);
function GetDatabase: string;
function GetConnectName: string;
protected
procedure Parser;
public
procedure Assign(Source: TPersistent);override;
property User:string read FUser write FUser;
property Password:string read FPassword write FPassword;
property Database:string read GetDatabase write FDatabase;
property DataSource:string read FDataSource write SetDataSource;
property DbType:Integer read FDbType write SetDatabaseType;
property WorkStation:string read GetWorkStation;
property ConnectionString:string read GetConnectionString write SetConnectionString;
property DBMSID:string read GetDBMSID;
property DBMSDescription:string read GetDBMSDescription;
property ConnectName:string read GetConnectName;
end;
TCommandStatement=class(TADOCommand);
TTableStatement=class(TADOTable);
TStoredStatement=class(TADOStoredProc);
TDataSetStatement=class(TADODataSet);
TQueryStatement=class(TADOQuery);
IConnection =interface
['{ACBF57C8-F868-4946-88BD-862FDE3E5DFB}']
function GetDbType:Integer;
function GetProvider:IConnectProvider;
function GetCommandTimeOut:Integer;
function GetConnectTimeOut:Integer;
procedure SetCommandTimeOut(const Value:Integer);
procedure SetConnectTimeOut(const Value:Integer);
function GetConnected: Boolean;
procedure SetConnected(const Value: Boolean);
function GetInTransaction:Boolean;
function BeginTrans:Integer;
procedure CommitTrans;
procedure RollbackTrans;
function GoBackPool:Boolean;
procedure UpdateStatementConnection(DataSet:TCustomADODataSet);
procedure UpdateCommandConnection(Command:TADOCommand);
function CreateCommand:TCommandStatement;
function CreateTable:TTableStatement;
function CreateStoredproc:TStoredStatement;
function CreateDataSet:TDataSetStatement;overload;
function CreateDataSet(CursorType:TCursorType;LockType:TAdoLockType):TDataSetStatement;overload;
function CreateDataSet(const Sql:string):TDataSetStatement;overload;
function CreateQuery(CursorType:TCursorType;LockType:TAdoLockType):TQueryStatement;overload;
function CreateQuery:TQueryStatement;overload;
function CreateQuery(const Sql:string):TQueryStatement;overload;
property Connected:Boolean read GetConnected write SetConnected;
property InTransaction:Boolean read GetInTransaction;
property DbType:Integer read GetDbType;
property Provider:IConnectProvider read GetProvider;
property CommandTimeOut:Integer read GetCommandTimeOut write SetCommandTimeOut;
property ConnectTimeOut:Integer read GetConnectTimeOut write SetConnectTimeOut;
end;
IConnectionContext = interface
['{BCD4B8B9-25AF-496F-A40A-992DBD4A5882}']
function GetConnection:IConnection;
function ConnectString:string;
function ConnectName:string;
procedure Close(Connect:IConnection);
end;
IConnectionContextManager=interface
['{D88DFCF9-A575-489D-AF34-BC0FEE82CFBD}']
function GetConnectionContext(ConnectName:string):IConnectionContext;
procedure RegisterConnectionContext(
const ConnectName:string;
const ConnectionStr:string;
const DBType:Integer;
const MinConnection:Integer=1;
const MaxConnection:Integer=5;
const CommandTimeOut:Integer=30;
const ConnectTimeOut:Integer=15);
procedure UnRegisterConnectionContext(const ConnectName:string);
procedure UnRegisterAllConnectionContext;
end;
TConnection=class(TInterfacedObject,IConnection)
private
Connect:TADOConnection;
FDBType:Integer;
FCommandTimeOut:Integer;
FConnectTimeOut:Integer;
FInPoolStatus: TConnectInPoolStatus;
FProvider:IConnectProvider;
FActiveCount: Integer;
function GetCommandTimeOut: Integer;
function GetConnectTimeOut: Integer;
procedure SetCommandTimeOut(const Value: Integer);
procedure SetConnectTimeOut(const Value: Integer);
protected
function GetDbType:Integer;
function GetProvider:IConnectProvider;
function GetConnected: Boolean;
procedure SetConnected(const Value: Boolean);
function GetInTransaction:Boolean;
function BeginTrans:Integer;
procedure CommitTrans;
procedure RollbackTrans;
function GoBackPool:Boolean;
procedure UpdateStatementConnection(DataSet:TCustomADODataSet);
procedure UpdateCommandConnection(Command:TADOCommand);
function CreateCommand:TCommandStatement;
function CreateTable:TTableStatement;
function CreateStoredproc:TStoredStatement;
function CreateDataSet:TDataSetStatement;overload;
function CreateDataSet(CursorType:TCursorType;LockType:TAdoLockType):TDataSetStatement;overload;
function CreateDataSet(const Sql:string):TDataSetStatement;overload;
function CreateQuery(CursorType:TCursorType;LockType:TAdoLockType):TQueryStatement;overload;
function CreateQuery:TQueryStatement;overload;
function CreateQuery(const Sql:string):TQueryStatement;overload;
property Connected:Boolean read GetConnected write SetConnected;
property InTransaction:Boolean read GetInTransaction;
property DbType:Integer read GetDbType;
property Provider:IConnectProvider read GetProvider;
property CommandTimeOut:Integer read GetCommandTimeOut write SetCommandTimeOut;
property ConnectTimeOut:Integer read GetConnectTimeOut write SetConnectTimeOut;
property InPoolStatus:TConnectInPoolStatus read FInPoolStatus write FInPoolStatus;
property ActiveCount:Integer read FActiveCount write FActiveCount;
public
constructor Create;
destructor Destroy;override;
//property RinpakConnection:TAdoConnection read Connect;
end;
TConnectionFactorys=class(TObject)
private
FList: TObjectList;
function GetConnects(Index: Integer): TConnection;
function Getcount: Integer;
protected
property List:TObjectList read FList;
public
constructor Create;
destructor Destroy;override;
function Add(Conn:TConnection):Integer;
property Count:Integer read Getcount;
property Connects[Index:Integer]:TConnection read GetConnects;default;
end;
TConnectionContext=class(TInterfacedObject,IConnectionContext)
private
FMinConnect: Integer;
FMaxConnect: Integer;
FConnections: TConnectionFactorys;
FConnectName:string;
ConnectBulider:TConnectStringBulider;
FLock:TCriticalSection;
FConnectTimeOut: Integer;
FCommandTimeOut: Integer;
FHandle:Cardinal;
FTimeOut:Cardinal;
FTimer:TTimer;
FReleaseed:Boolean;
protected
procedure DoTimer(Sender:TObject);
procedure PrepareFreeConnection;
procedure Lock;
procedure UnLock;
function GetUnUseCount:Integer;
function Search(const NuUse:Boolean=False):TConnection;
function GetConnection:IConnection;
procedure Close(Connect:IConnection);
function ConnectString:string;
function ConnectName:string;
procedure Initialize(
UniqueName:string;
const ConnectionStr:string;
const DBType:Integer;
const MinConnection:Integer=1;
const MaxConnection:Integer=10;
const CommandTimeOut:Integer=120;
const ConnectTimeOut:Integer=15);
property Connections:TConnectionFactorys read FConnections;
property MinConnect:Integer read FMinConnect write FMinConnect;
property MaxConnect:Integer read FMaxConnect write FMaxConnect;
property CommandTimeOut:Integer read FCommandTimeOut write FCommandTimeOut;
property ConnectTimeOut:Integer read FConnectTimeOut write FConnectTimeOut;
public
constructor Create;
destructor Destroy;override;
end;
TConnectionContextManager=class(TInterfacedObject,IConnectionContextManager)
private
FLock:TCriticalSection;
FConnectContexts: TInterfaceList;
protected
procedure Lock;
procedure UnLock;
function Find(const ConnectName:string):IConnectionContext;overload;
function GetConnectionContext(ConnectName:string):IConnectionContext;
procedure RegisterConnectionContext(
const ConnectName:string;
const ConnectionStr:string;
const DBType:Integer;
const MinConnection:Integer=1;
const MaxConnection:Integer=5;
const CommandTimeOut:Integer=30;
const ConnectTimeOut:Integer=15);
procedure UnRegisterConnectionContext(const ConnectName:string);
procedure UnRegisterAllConnectionContext;
property ConnectContexts:TInterfaceList read FConnectContexts;
public
constructor Create;
destructor Destroy;override;
end;
function ConnectionContextMgr:IConnectionContextManager;
implementation
uses Math, ComObj,SqlServerProvider,ActiveX,FuncUtils,FrameCommon;
var
ContextMgr:IConnectionContextManager=nil;
function ConnectionContextMgr:IConnectionContextManager;
begin
if ContextMgr=nil then
ContextMgr:=TConnectionContextManager.Create;
Result:=ContextMgr;
end;
{ TConnectStringBulider }
procedure TConnectStringBulider.Assign(Source: TPersistent);
var
Conn:TConnectStringBulider;
begin
if Source is TConnectStringBulider then
begin
Conn:=Source as TConnectStringBulider;
FUser:=Conn.User;
FPassword:=Conn.Password;
FDatabase:=Conn.Database;
FDataSource:=Conn.DataSource;
FDbType:=Conn.DbType;
end;
end;
function TConnectStringBulider.GetConnectionString: string;
const
MySqlConntion='DRIVER={MySQL ODBC 3.51 Driver};DESC=;'
+'DATABASE=%s;SERVER=%s;UID=%s;PASSWORD=%s;PORT=3306;OPTION=;STMT=;';
DB2Connection='Provider=IBMDADB2.1;Password=%s;Persist Security Info=True;'
+'User ID=%s;Data Source=%s;Location=%s';
AccessConnection ='Provider=Microsoft.Jet.OLEDB.4.0;User ID=%s;'
+'Data Source=%s;Persist Security Info=True;Jet OLEDB:Database Password=%s';
SqlServerConnection='Provider=SQLOLEDB.1;Password=%s'
+';Persist Security Info=True;User ID=%s'
+';Initial Catalog=%s;Data Source=%S'
+';Use Encryption for Data=False;'
+'Tag with column collation when possible=False;'
+'Use Procedure for Prepare=1;'
+'Auto Translate=True;'
+'Packet Size=4096;'
+'Workstation ID=%s';
OracleConnection='Provider=MSDAORA.1;Password=%S;'
+'User ID=%S;Data Source=%S;Persist Security Info=True';
begin
Result:='';
case DbType of
dbtAccess:Result:=Format(AccessConnection,[User,DataSource,Password]);
dbtSqlServer:
Result:=Format(SqlServerConnection,[Password,User,Database,DAtaSource,WorkStation]);
dbtOracle:Result:=Format(OracleConnection,[Password,User,Database]);
dbtInterbase:raise EUnSupportException.Create('不支持的数据库类型');
dbtDB2:Result:=Format(DB2Connection,[Password,User,Database,DataSource]);
dbtMySql:Result:=Format(MySqlConntion,[Database,DataSource,User,Password]);
else
raise EUnSupportException.Create('不支持的数据库类型');
end;
FConnStr:=Result;
end;
function TConnectStringBulider.GetConnectName: string;
begin
Result:=WorkStation+'.'+DBMSID+'.'+Database;
end;
function TConnectStringBulider.GetDatabase: string;
var
FileName:string;
I:Integer;
begin
if DbType=dbtAccess then
begin
FileName:=ExtractFileName(DataSource);
I:=Pos('.',FileName);
if I>0 then
Result:=Copy(FileName,1,I-1)
else Result:=FileName;
end else Result := FDatabase;
end;
function TConnectStringBulider.GetDBMSDescription: string;
begin
case DbType of
dbtAccess:Result:=ACCESS_DBMS_ID;
dbtSqlServer:Result:=SQLSERVER_DBMS_ID;
dbtOracle:Result:=ORACLE_DBMS_ID;
dbtInterbase:Result:=INTERBASE_DBMS_ID;
dbtDb2:Result:=DB2_DBMS_ID;
dbtMySql:Result:=MYSQL_DBMS_ID;
else Result:='UnKnown';
end;
end;
function TConnectStringBulider.GetDBMSID: string;
begin
case DbType of
dbtAccess:Result:=ACCESS_DBMS_ID;
dbtSqlServer:Result:=SQLSERVER_DBMS_ID;
dbtOracle:Result:=ORACLE_DBMS_ID;
dbtInterbase:Result:=INTERBASE_DBMS_ID;
dbtDb2:Result:=DB2_DBMS_ID;
dbtMySql:Result:=MYSQL_DBMS_ID;
else Result:='UnKnown';
end;
end;
function TConnectStringBulider.GetWorkStation: string;
const
Len=200;
var
Data:TWSAData;
Buffer:PChar;
begin
GetMem(Buffer,Len);
try
try
Winsock.WSAStartup($101,Data);
Winsock.gethostname(Buffer,Len);
Result:=Buffer;
Winsock.WSACleanup;
except
end;
finally
FreeMem(Buffer,Len);
end;
end;
procedure TConnectStringBulider.Parser;
var
List:TStringList;
procedure ParserString;
var
I,Len:Integer;
Value:string;
C:Char;
begin
Len:=Length(FConnStr);
I:=1;
while (I<=Len) do
begin
C:=FConnStr[I];
if (C<>';') then
Value:=Value+C
else if (C=';') then
begin
List.Add(Value);
Value:='';
end;
Inc(I);
end;
if Value<>'' then
List.Add(Value);
end;
procedure ParserSqlServer;
var
Value:string;
begin
ParserString;
User:=List.Values['User ID'];
Database:=List.Values['Initial Catalog'];
DataSource:=List.Values['Data Source'];
Password:=List.Values['Password'];
Value:=List.Values['Persist Security Info'];
end;
procedure ParserMySql;
begin
ParserString;
User:=List.Values['UID'];
Database:=List.Values['DATABASE'];
DataSource:=List.Values['SERVER'];
Password:=List.Values['PASSWORD'];
end;
procedure ParserAccess;
begin
ParserString;
User:=List.Values['User ID'];
DataSource:=List.Values['Data Source'];
Password:=List.Values['Jet OLEDB:Database Password'];
end;
procedure ParserDB2;
begin
ParserString;
User:=List.Values['User ID'];
Database:=List.Values['Data Source'];
DataSource:=List.Values['Location='];
Password:=List.Values['Password'];
end;
procedure ParserOracle;
begin
ParserString;
User:=List.Values['User ID'];
Database:=List.Values['Data Source'];
DataSource:=List.Values['Location='];
Password:=List.Values['Password'];
end;
begin
if(FConnStr='')then Exit;
List:=TStringList.Create;
try
case DbType of
dbtAccess: ParserAccess;
dbtSqlServer:ParserSqlServer;
dbtOracle:ParserOracle;
dbtInterbase:;
dbtDB2:ParserDB2;
dbtMySql:ParserMySql;
end;
finally
List.Free;
end;
end;
procedure TConnectStringBulider.SetConnectionString(const Value: string);
begin
if ConnectionString<>Value then
FConnStr:=Value;
Parser;
end;
procedure TConnectStringBulider.SetDatabaseType(const Value: Integer);
begin
if FDbType<>Value then
FDbType := Value;
Parser;
end;
procedure TConnectStringBulider.SetDataSource(const Value: string);
begin
FDataSource := Value;
end;
{ TConnection }
function TConnection.BeginTrans: Integer;
begin
Result:=Connect.BeginTrans;
end;
procedure TConnection.CommitTrans;
begin
Connect.CommitTrans;
end;
constructor TConnection.Create;
begin
inherited;
Connect:=TADOConnection.Create(nil);
Connect.LoginPrompt:=False;
FInPoolStatus:=psNone;
FActiveCount:=0;
end;
function TConnection.CreateCommand: TCommandStatement;
begin
Result:=TCommandStatement.Create(nil);
Result.CommandTimeout:=CommandTimeOut;
Result.Connection:=Connect;
end;
function TConnection.CreateDataSet(const Sql: string): TDataSetStatement;
var
rstData :TADODataSet ;
begin
rstData:=TADODataSet.Create(nil);
rstData.CommandText:=Sql;
rstData.CommandTimeout:=CommandTimeOut;
rstData.Connection:=Connect;
rstData.Open;
{Result:=TDataSetStatement.Create(nil);
REsult.CommandText:=Sql;
Result.CommandTimeout:=CommandTimeOut;
Result.Connection:=Connect;
Result.Open;
}
ShowMessage(rstData.Fields[0].FieldName);
end;
function TConnection.CreateDataSet(CursorType: TCursorType;
LockType: TAdoLockType): TDataSetStatement;
begin
Result:=TDataSetStatement.Create(nil);
Result.CursorType:=CursorType;
Result.LockType:=LockType;
Result.CommandTimeout:=CommandTimeOut;
Result.Connection:=Connect;
end;
function TConnection.CreateDataSet: TDataSetStatement;
begin
Result:=TDataSetStatement.Create(nil);
Result.CommandTimeout:=CommandTimeOut;
Result.Connection:=Connect;
end;
function TConnection.CreateQuery(const Sql: string): TQueryStatement;
begin
Result:=TQueryStatement.Create(nil);
Result.EnableBCD:=FAlse;
Result.SQL.Text:=Sql;
Result.CommandTimeout:=CommandTimeOut;
Result.Connection:=Connect;
end;
function TConnection.CreateQuery(CursorType: TCursorType;
LockType: TAdoLockType): TQueryStatement;
begin
Result:=TQueryStatement.Create(nil);
Result.CursorType:=CursorType;
Result.LockType:=LockType;
Result.EnableBCD:=FAlse;
Result.CommandTimeout:=CommandTimeOut;
Result.Connection:=Connect;
end;
function TConnection.CreateQuery: TQueryStatement;
begin
Result:=TQueryStatement.Create(nil);
Result.EnableBCD:=FAlse;
Result.CommandTimeout:=CommandTimeOut;
Result.Connection:=Connect;
end;
function TConnection.CreateStoredproc: TStoredStatement;
begin
Result:=TStoredStatement.Create(nil);
Result.CommandTimeout:=CommandTimeOut;
Result.Connection:=Connect;
end;
function TConnection.CreateTable: TTableStatement;
begin
Result:=TTableStatement.Create(nil);
Result.CommandTimeout:=CommandTimeOut;
Result.Connection:=Connect;
end;
destructor TConnection.Destroy;
begin
Connect.Free;
if FProvider<>nil then
FProvider:=nil;
inherited;
end;
function TConnection.GetCommandTimeOut: Integer;
begin
Result:=FCommandTimeOut;
end;
function TConnection.GetConnected: Boolean;
begin
Result:=Connect.Connected;
end;
function TConnection.GetConnectTimeOut: Integer;
begin
Result:=FConnectTimeOut;
end;
function TConnection.GetDbType: Integer;
begin
Result:=FDBType;
end;
function TConnection.GetInTransaction: Boolean;
begin
Result:=Connect.InTransaction;
end;
function TConnection.GetProvider: IConnectProvider;
begin
case FDBType of
dbtSqlServer:
begin
if FProvider=nil then
FProvider:=TSQLServerProvider.Create;
Result:=FProvider;
end;
else Result:=nil;
end;
end;
function TConnection.GoBackPool:Boolean;
begin
Dec(FActiveCount);
if FActiveCount=0 then
Self.InPoolStatus:=psUnUse;
Result:=(Self.InPoolStatus=psNone)or(Self.InPoolStatus=psUnUse);
end;
procedure TConnection.RollbackTrans;
begin
Connect.RollbackTrans;
end;
procedure TConnection.SetCommandTimeOut(const Value: Integer);
begin
FCommandTimeOut:=Value;
Connect.CommandTimeout:=Value;
end;
procedure TConnection.SetConnected(const Value: Boolean);
begin
Connect.Connected:=Value;
end;
procedure TConnection.SetConnectTimeOut(const Value: Integer);
begin
FConnectTimeOut:=Value;
Connect.ConnectionTimeout:=Value;
end;
procedure TConnection.UpdateCommandConnection(Command: TADOCommand);
begin
Command.Connection:=Connect;
Command.CommandTimeout:=CommandTimeOut;
end;
procedure TConnection.UpdateStatementConnection(DataSet: TCustomADODataSet);
begin
DataSet.Connection:=Connect;
if DataSet is TADOTable then
begin
TAdoTAble(DataSet).CommandTimeout:=CommandTimeOut;
end else if DataSet is TADODataSet then
begin
TADODataSet(DataSet).CommandTimeout:=CommandTimeOut;
end else if Dataset is TADOStoredProc then
begin
TADOStoredProc(DataSet).CommandTimeout:=CommandTimeOut;
end else if DataSet is TADOQuery then
begin
TADOQuery(DataSet).CommandTimeout:=CommandTimeOut;
end;
end;
{ TConnectionContext }
procedure TConnectionContext.Close(Connect: IConnection);
begin
lock;
try
if Connect<>nil then
begin
if Connect.GoBackPool then
ReleaseSemaphore(FHandle,1,nil);
end;
finally
unLock;
end;
end;
function TConnectionContext.ConnectName: string;
begin
lock;
try
Result:=FConnectName;
finally
UnLock;
end;
end;
function TConnectionContext.ConnectString: string;
begin
lock;
try
Result:=ConnectBulider.ConnectionString;
finally
unlock;
end;
end;
constructor TConnectionContext.Create;
begin
inherited Create;
FReleaseed:=False;
FMinConnect:=1;
FMaxConnect:=5;
FConnectTimeOut:=15;
FCommandTimeOut:=30;
FLock:=TCriticalSection.Create;
ConnectBulider:=TConnectStringBulider.Create;
FConnections:=TConnectionFactorys.Create;
FTimeOut:=500;
FTimer:=TTimer.Create(nil);
FTimer.Interval:=$CDFE600;{1小时}
FTimer.OnTimer:=DoTimer;
end;
destructor TConnectionContext.Destroy;
begin
FTimer.Free;
if FHandle<>0 then
CloseHandle(FHandle);
PrepareFreeConnection;
FLock.Free;
Connections.Free;
ConnectBulider.Free;
inherited;
end;
procedure TConnectionContext.DoTimer(Sender: TObject);
var
IdleCount,Index,ReleaseC:LongInt;
Connect:TConnection;
function GetIdleCount:Integer;
var
Conn:TConnection;
Index:Integer;
begin
Result:=0;
for Index:=0 to FConnections.Count-1 do
begin
Conn:=Connections[Index];
if((Conn.InPoolStatus=psUnUse)or(Conn.InPoolStatus=psNone))and(Conn.Connected)then
Inc(Result);
end;
end;
begin
Lock;
try
FReleaseed:=True;
try
IdleCount:=GetIdleCount;
if(IdleCount>=10)then
begin
try
ReleaseC:=0;
if(IdleCount mod 2 =0)then
begin
for Index:=FConnections.Count-1 downto 0 do
begin
if(ReleaseC=IdleCount-5)then Break;
Connect:=FConnections.GetConnects(Index);
if(Connect.InPoolStatus=psNone)or(Connect.InPoolStatus=psUnUse)then
begin
if Connect.Connected then
begin
Connect.Connected:=False;
Inc(ReleaseC);
end;
end;
end;
end else
begin
for Index:=0 to FConnections.Count-1 do
begin
if(ReleaseC=IdleCount-5)then Break;
Connect:=FConnections.GetConnects(Index);
if(Connect.InPoolStatus=psNone)or(Connect.InPoolStatus=psUnUse)then
begin
if Connect.Connected then
begin
Connect.Connected:=False;
Inc(ReleaseC);
end;
end;
end;
end;
except
end;
end;
finally
FReleaseed:=False;
end;
finally
UnLock;
end;
end;
function TConnectionContext.GetConnection: IConnection;
const
Search_Error=$0000000F;
Connection_Error=$00000008;
PoolCount_Error =$00000800;
MaxPoolCount =$00001388;
AutoPoolStep =$00000005;
var
Conn:TConnection;
FConnStr,ErrorMsg:string;
Return:Cardinal;
ErrorCode:LongInt;
OldCount:LongInt;
function CreateInstance:TConnection;
begin
CoInitialize(nil);
Result:=TConnection.Create;
Result.Connect.ConnectionString:=FConnStr;
try
Result.CommandTimeOut:=CommandTimeOut;
Result.ConnectTimeOut:=ConnectTimeOut;
REsult.FDBType:=ConnectBulider.DbType;
Result.Connected:=True;
Result.InPoolStatus:=psUse;
Result.ActiveCount:=Result.ActiveCount+1;
except
on E:Exception do
begin
ErrorMsg:=e.Message ;
ErrorCode:=Connection_Error;
FreeAndNIl(Result);
end;
end;
end;
begin
Lock;
try
//while FReleaseed do ;
ErrorCode:=0;
Result:=nil;
FConnStr:=ConnectString;
Assert(FConnStr<>'','ConnectionString is null!');
Conn:=Search;
if (Conn<>nil)then
begin
try
if not Conn.Connected then
begin
Conn.Connect.ConnectionString:=FConnStr;
Conn.Connected:=True;
end;
Conn.InPoolStatus:=psUse;
Conn.ActiveCount:=Conn.ActiveCount+1;
Result:=Conn as IConnection;
except
on E:Exception do
begin
ErrorMsg:=e.Message ;
ErrorCode:=Connection_Error;
end;
end;
end else ErrorCode:=Search_Error;
{
Return:=WaitForSingleObject(FHandle,FTimeOut);
case Return of
WAIT_FAILED,WAIT_ABANDONED,WAIT_TIMEOUT:
begin
Conn:=Search;
if(Conn<>nil)then
begin
try
if not Conn.Connected then
begin
Conn.Connect.ConnectionString:=FConnStr;
Conn.Connected:=True;
end;
Conn.InPoolStatus:=psUse;
Conn.ActiveCount:=Conn.ActiveCount+1;
Result:=Conn as IConnection;
except
on E:Exception do
begin
ErrorCode:=Return;
end;
end;
end else
ErrorCode:=Return;
end;
WAIT_OBJECT_0:
begin
Conn:=Search;
if (Conn<>nil)then
begin
try
if not Conn.Connected then
begin
Conn.Connect.ConnectionString:=FConnStr;
Conn.Connected:=True;
end;
Conn.InPoolStatus:=psUse;
Conn.ActiveCount:=Conn.ActiveCount+1;
Result:=Conn as IConnection;
except
on E:Exception do
begin
ErrorCode:=Connection_Error;
end;
end;
end else ErrorCode:=Search_Error;
end;
end;
}
if(Result<>nil)then Exit;
if(Connections.Count<MaxConnect)then
begin
Conn:=CreateInstance;
if Conn<>nil then
begin
Connections.Add(Conn);
Result:=Conn as IConnection;
Result._AddRef;
end;
end else ErrorCode:=PoolCount_Error;
if Result=nil then
begin
case ErrorCode of
Connection_Error:;
PoolCount_Error,Search_Error,WAIT_FAILED,WAIT_ABANDONED,WAIT_TIMEOUT:
begin
if(FMaxConnect<MaxPoolCount)then
begin
CloseHandle(FHandle);
OldCount:=GetUnUseCount+AutoPoolStep;
FMaxConnect:=FMaxConnect+AutoPoolStep;
FHandle:=CreateSemaphore(nil,OldCount,FMaxConnect,nil);
Conn:=CreateInstance;
if Conn<>nil then
begin
Connections.Add(Conn);
Result:=Conn as IConnection;
Result._AddRef;
end;
end;
end;
end;
end;
finally
UnLock;
end;
end;
function TConnectionContext.GetUnUseCount: Integer;
var
Conn:TConnection;
Index:Integer;
begin
Result:=0;
for Index:=0 to FConnections.Count-1 do
begin
Conn:=Connections[Index];
if(Conn.InPoolStatus=psUnUse)or(Conn.InPoolStatus=psNone)then
Inc(Result);
end;
end;
procedure TConnectionContext.Initialize(UniqueName: string;
const ConnectionStr: string; const DBType, MinConnection,
MaxConnection,CommandTimeOut,ConnectTimeOut:Integer);
begin
FConnectName:=UniqueName;
ConnectBulider.ConnectionString:=ConnectionStr;
ConnectBulider.DbType:=DBType;
if MinConnection>0 then
FMinConnect:=MinConnection;
if MaxConnection>0then
FMaxConnect:=MaxConnection;
Self.CommandTimeOut:=CommandTimeOut;
Self.ConnectTimeOut:=ConnectTimeOut;
FHandle:=CreateSemaphore(nil,FMaxConnect,MaxConnection,PChar(UniqueName));
end;
procedure TConnectionContext.Lock;
begin
FLock.Enter;
end;
procedure TConnectionContext.PrepareFreeConnection;
var
I:Integer;
begin
for I:=0 to Connections.Count-1 do
Connections[I]._Release;
end;
function TConnectionContext.Search(const NuUse:Boolean=False): TConnection;
var
Conn:TConnection;
Index:Integer;
begin
Result:=nil;
for Index:=0 to FConnections.Count-1 do
begin
Conn:=Connections[Index];
if(Conn.InPoolStatus=psUnUse)or(Conn.InPoolStatus=psNone)then
begin
Result:=Conn;
Exit;
end;
end;
if Result=nil then
begin
for Index:=0 to FConnections.Count-1 do
begin
Conn:=Connections[Index];
if not Conn.InTransaction then
begin
Result:=Conn;
Exit;
end;
end;
end;
end;
procedure TConnectionContext.UnLock;
begin
FLock.Leave;
end;
{ TConnectionContextManager }
constructor TConnectionContextManager.Create;
begin
inherited ;
FConnectContexts:=TInterfaceList.Create;
FLock:=TCriticalSection.Create;
end;
destructor TConnectionContextManager.Destroy;
begin
FConnectContexts.Free;
FLock.Free;
inherited;
end;
function TConnectionContextManager.Find(
const ConnectName: string): IConnectionContext;
var
Context:IConnectionContext;
I:Integer;
begin
Lock;
try
for I:=0 to ConnectContexts.Count -1 do
begin
Context:=ConnectContexts[I] as IConnectionContext;
if SameText(ConnectName,Context.ConnectName)then
begin
Result:=Context;
Exit;
end;
end;
Result:=nil;
finally
UnLock;
end;
end;
function TConnectionContextManager.GetConnectionContext(
ConnectName: string): IConnectionContext;
begin
Result:=Find(ConnectName);
end;
procedure TConnectionContextManager.Lock;
begin
FLock.Enter;
end;
procedure TConnectionContextManager.RegisterConnectionContext(
const ConnectName, ConnectionStr: string; const DBType, MinConnection,
MaxConnection,CommandTimeOut,ConnectTimeOut:Integer);
var
Context:TConnectionContext;
begin
Lock;
try
if Find(ConnectName)<>nil then Exit;
Context:=TConnectionContext.Create;
Context.Initialize(
ConnectName,
ConnectionStr,
DBType,
MinConnection,
MaxConnection,
CommandTimeOut,
ConnectTimeOut);
ConnectContexts.Add(Context as IConnectionContext);
finally
UnLock;
end;
end;
procedure TConnectionContextManager.UnLock;
begin
FLock.Leave;
end;
procedure TConnectionContextManager.UnRegisterAllConnectionContext;
begin
Lock;
try
FConnectContexts.Clear;
finally
UnLock;
end;
end;
procedure TConnectionContextManager.UnRegisterConnectionContext(
const ConnectName: string);
var
Context:IConnectionContext;
begin
Lock;
try
Context:=Find(ConnectName);
if Context <> nil then
ConnectContexts.Remove(Context);
finally
UnLock;
end;
end;
{ TConnectionFactorys }
function TConnectionFactorys.Add(Conn: TConnection): Integer;
begin
Result:=FList.Add(Conn);
end;
constructor TConnectionFactorys.Create;
begin
inherited Create;
FList:=TObjectList.Create(FAlse);
end;
destructor TConnectionFactorys.Destroy;
begin
FList.Free;
inherited;
end;
function TConnectionFactorys.GetConnects(Index: Integer): TConnection;
begin
Result:=TConnection(list.Items[Index]);
end;
function TConnectionFactorys.Getcount: Integer;
begin
Result:=FList.Count;
end;
initialization
ConnectionContextMgr;
finalization
//if ContextMgr<>nil then
//ContextMgr:=nil;
end.
|
{----------------------------------------------------------------------
DEVIUM Content Management System
Copyright (C) 2004 by DEIV Development Team.
http://www.deiv.com/
$Header: /devium/Devium\040CMS\0402/Source/ControlPanel/Devium.dpr,v 1.2 2004/04/06 09:29:07 paladin Exp $
------------------------------------------------------------------------}
unit pgAddParamsForm;
interface
uses
Forms, Classes, Controls, ExtCtrls, StdCtrls, cxControls, cxContainer,
cxEdit, cxTextEdit, cxMaskEdit, cxButtonEdit, cxDropDownEdit,
cxLookAndFeelPainters, cxButtons, cxRadioGroup, Graphics, cxCheckBox,
ActnList;
type
TAddParamsForm = class(TForm)
Panel2: TPanel;
SmallSize: TcxComboBox;
Label2: TLabel;
Label3: TLabel;
BigSize: TcxComboBox;
Panel1: TPanel;
OK: TcxButton;
Cancel: TcxButton;
CenterCrop: TcxCheckBox;
ActionList: TActionList;
ActionOK: TAction;
procedure ActionOKExecute(Sender: TObject);
procedure FormCreate(Sender: TObject);
end;
function GetAddParamsForm(var SmallSize, BigSize: Integer;
var CenterCrop: Boolean): Integer;
implementation
uses SysUtils;
{$R *.dfm}
function GetAddParamsForm(var SmallSize, BigSize: Integer;
var CenterCrop: Boolean): Integer;
var
Form: TAddParamsForm;
begin
Form := TAddParamsForm.Create(Application);
try
Result := Form.ShowModal;
if Result = mrOK then
begin
SmallSize := StrToInt(Form.SmallSize.Text);
BigSize := StrToInt(Form.BigSize.Text);
CenterCrop := Form.CenterCrop.Checked;
end;
finally
Form.Free;
end;
end;
{ TAddParamsForm }
procedure TAddParamsForm.ActionOKExecute(Sender: TObject);
begin
OK.SetFocus;
ModalResult := mrOK;
end;
procedure TAddParamsForm.FormCreate(Sender: TObject);
begin
SmallSize.ItemIndex := 0;
BigSize.ItemIndex := 0;
end;
end.
|
{*******************************************************************************
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/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.
*******************************************************************************}
unit wbScript;
interface
uses
wbInterface,
CocoaBase;
type
IwbScriptAction = interface
['{2BF2E3A4-2F5D-4EA1-987A-96CEE26A3902}']
function Process(const aElement: IwbElement): Boolean;
end;
TDynActions = array of IwbScriptAction;
TwbScriptScanProgress = procedure(aTotalCount, aCount: Integer) of object;
IwbScript = interface
['{C9010A7A-79BE-4FE3-BD03-645A494E9644}']
procedure LoadFromFile(const aFileName: string);
procedure LoadFromString(const s: string);
procedure ScanForTargets(out aElements: TDynElements; out aActions: TDynActions; aProgress: TwbScriptScanProgress);
end;
function wbCreateScript(const aFiles: TDynFiles): IwbScript;
type
TwbModifyType = (
mtOffset,
mtFactor,
mtInclude,
mtExclude
);
TwbTermHandle = TGUID;
TwbOperator = (
opOr,
opAnd,
opPlus,
opMinus,
opConcat,
opMul,
opFloatDiv,
opDiv,
opMod
);
TwbUnaryOperator = (
uoNot,
uoMinus
);
TwbLiteralType = (
ltString,
ltInteger,
ltFloat,
ltFormID
);
IwbExpressionBuilder = interface
['{99BE0457-49F3-40FA-8D4D-05FC1476AE00}']
function BeginTerm: TwbTermHandle;
function BeginUnaryTerm(aUnaryOperator: TwbUnaryOperator): TwbTermHandle;
function BeginDeRefTerm: TwbTermHandle;
procedure EndTerm(const aHandle: TwbTermHandle);
procedure SetOperator(aOperator: TwbOperator);
procedure AddLiteral(aLiteralType: TwbLiteralType; aValue: PTokenRecord);
procedure AddFieldRef(aName: PTokenRecord);
procedure AddMatch(aSignature: PTokenRecord; const aExpression: IwbExpressionBuilder);
end;
IwbStatementBuilder = interface
['{19F099D8-422A-43EB-9C4A-9C950EC559C5}']
end;
IwbRuleBuilder = interface
['{87F3D163-743E-4CBD-AD45-08BD7E85D1E9}']
end;
IwbStatementContainer = interface
['{B501F899-6891-4914-9313-AFEA4F6F0D97}']
procedure AddStatement(const aStatementBuilder: IwbStatementBuilder);
end;
IwbMatchRuleBuilder = interface(IwbRuleBuilder)
['{C01362D2-1D87-44C2-BE16-9DEE9FE37A1B}']
end;
IwbChangeRuleBuilder = interface(IwbRuleBuilder)
['{DF5F7B4E-5FFC-4BE8-A76A-2EF1EA02F55E}']
end;
IwbScriptBuilder = interface
['{20C6A5BF-9368-4E29-A988-9CA12E3D6661}']
procedure AddRule(const aRuleBuilder: IwbRuleBuilder);
function CreateStatementBlock: IwbStatementBuilder;
function CreateWithStatement(aIsEach: Boolean; const aExpression: IwbExpressionBuilder; const aStatement: IwbStatementBuilder): IwbStatementBuilder;
function CreateSetStatement(const aField, aExpression: IwbExpressionBuilder): IwbStatementBuilder;
function CreateModifyStatement(const aField: IwbExpressionBuilder; aModifyType: TwbModifyType; const aExpression: IwbExpressionBuilder): IwbStatementBuilder;
function CreateExpressionBuilder: IwbExpressionBuilder;
end;
implementation
uses
Math,
Windows, Classes, SysUtils, Direct3D9, D3DX9, wbHelpers{,
wbScriptParse};
type
IwbScriptRule = interface
['{688B619A-FBB0-4602-971D-577991C1CC38}']
function NeedRefsFor(const aFile: IwbFile): Boolean;
function ShouldScan(const aContainer: IwbContainerElementRef): Boolean;
function Match(const aElement: IwbElement; var aScanRefBy: Boolean; var aAction: IwbScriptAction): Boolean;
end;
IwbScriptRuleInternal = interface(IwbScriptRule)
['{63539910-5259-4B01-92C7-13D327E7ED77}']
function IsEmpty: Boolean;
procedure AddAction(const aAction: IwbScriptAction);
end;
TwbScript = class(TInterfacedObject, IwbScript)
private
scFiles : TDynFiles;
scFilesMap : TStringList;
scRules : array of IwbScriptRule;
protected
procedure LoadScript(const aScript: TStrings);
function NeedRefsFor(const aFile: IwbFile): Boolean;
function ShouldScan(const aContainer: IwbContainerElementRef): Boolean;
function Match(const aElement: IwbElement; var aScanRefBy: Boolean; var aAction: IwbScriptAction): Boolean;
procedure BuildAllRefs;
procedure ResetAllTags;
{---IwbScript---}
procedure LoadFromFile(const aFileName: string);
procedure LoadFromString(const s: string);
procedure ScanForTargets(out aElements: TDynElements; out aActions:TDynActions; aProgress: TwbScriptScanProgress);
public
constructor Create(const aFiles: TDynFiles);
destructor Destroy; override;
end;
TwbAddRefrAction = class(TInterfacedObject, IwbScriptAction)
private
araMainRecord : IwbMainRecord;
araPos : TD3DXVector3;
araRot : TD3DXVector3;
araScale : Single;
araEDIDPrefix : string;
araEDIDSuffix : string;
protected
{---IwbScriptAction---}
function Process(const aElement: IwbElement): Boolean;
public
constructor Create(const aMainRecord: IwbMainRecord; const aPos, aRot: TD3DXVector3; const aScale: Single; const aEDIDPrefix, aEDIDSuffix: string);
end;
TwbDeleteRefrAction = class(TInterfacedObject, IwbScriptAction)
private
protected
{---IwbScriptAction---}
function Process(const aElement: IwbElement): Boolean;
public
constructor Create;
end;
TwbSetElementAction = class(TInterfacedObject, IwbScriptAction)
private
seaElement : string;
seaValue : string;
seaMasterFile : IwbFile;
protected
{---IwbScriptAction---}
function Process(const aElement: IwbElement): Boolean;
public
constructor Create(const aElement, aValue: string; const aMasterFile: IwbFile);
end;
TwbMatchRefrRule = class(TInterfacedObject, IwbScriptRule, IwbScriptRuleInternal)
private
mrrMainRecord : IwbMainRecord;
mrrActions : TDynActions;
protected
{---IwbScriptRule---}
function NeedRefsFor(const aFile: IwbFile): Boolean;
function ShouldScan(const aContainer: IwbContainerElementRef): Boolean;
function Match(const aElement: IwbElement; var aScanRefBy: Boolean; var aAction: IwbScriptAction): Boolean;
{---IwbScriptRuleInternal---}
function IsEmpty: Boolean;
procedure AddAction(const aAction: IwbScriptAction);
public
constructor Create(const aMainRecord: IwbMainRecord);
end;
TwbNullRule = class(TInterfacedObject, IwbScriptRule, IwbScriptRuleInternal)
protected
{---IwbScriptRule---}
function NeedRefsFor(const aFile: IwbFile): Boolean;
function ShouldScan(const aContainer: IwbContainerElementRef): Boolean;
function Match(const aElement: IwbElement; var aScanRefBy: Boolean; var aAction: IwbScriptAction): Boolean;
{---IwbScriptRuleInternal---}
function IsEmpty: Boolean;
procedure AddAction(const aAction: IwbScriptAction);
public
constructor Create;
end;
IwbActionHub = interface(IwbScriptAction)
['{227AA3F7-75EA-4751-AA5E-014AB065E011}']
procedure AddActions(const aActions: TDynActions);
end;
TwbActionHub = class(TInterfacedObject, IwbScriptAction, IwbActionHub)
private
ahActions: TDynActions;
protected
{---IwbScriptAction---}
function Process(const aElement: IwbElement): Boolean;
{---IwbActionHub---}
procedure AddActions(const aActions: TDynActions);
public
class procedure Add(var aAction: IwbScriptAction; const aActions: TDynActions);
constructor Create(const aAction: IwbScriptAction);
end;
function wbCreateScript(const aFiles: TDynFiles): IwbScript;
begin
Result := TwbScript.Create(aFiles);
end;
{ TwbScript }
procedure TwbScript.BuildAllRefs;
var
i : Integer;
_File : IwbFile;
OldAction : string;
begin
OldAction := wbCurrentAction;
try
for i := Low(scFiles) to High(scFiles) do begin
_File := scFiles[i];
if not (csRefsBuild in _File.ContainerStates) and NeedRefsFor(_File) then begin
wbCurrentAction := 'Building reference information for ' + _File.Name;
if Assigned(wbProgressCallback) then
wbProgressCallback('[' + FormatDateTime('nn:ss', Now - wbStartTime) + '] ' + wbCurrentAction);
_File.BuildRef;
end;
end;
finally
wbCurrentAction := OldAction;
end;
end;
constructor TwbScript.Create(const aFiles: TDynFiles);
var
i: Integer;
begin
scFiles := aFiles;
scFilesMap := TStringList.Create;
for i := Low(scFiles) to High(scFiles) do
scFilesMap.AddObject(afiles[i].FileName, TObject(Pointer(scFiles[i])));
scFilesMap.Sorted := True;
inherited Create;
end;
destructor TwbScript.Destroy;
begin
FreeAndNil(scFilesMap);
inherited;
end;
procedure TwbScript.LoadFromFile(const aFileName: string);
var
Strings: TStringList;
begin
Strings := TStringList.Create;
try
Strings.LoadFromFile(aFileName);
LoadScript(Strings);
finally
Strings.Free;
end;
end;
procedure TwbScript.LoadFromString(const s: string);
var
Strings: TStringList;
begin
Strings := TStringList.Create;
try
Strings.Text := s;
LoadScript(Strings);
finally
Strings.Free;
end;
end;
procedure TwbScript.LoadScript(const aScript: TStrings);
var
i : Integer;
CurrentLine : Integer;
s, t : string;
CurrentRule : IwbScriptRuleInternal;
Temp : TStringList;
_File : IwbFile;
MainRecord : IwbMainRecord;
Position : TD3DXVector3;
Rotation : TD3DXVector3;
Scale : Single;
EDIDPrefix : string;
EDIDSuffix : string;
begin
//very very simple parser for now.
Temp := TStringList.Create;
try
CurrentLine := 0;
while CurrentLine < aScript.Count do try
s := Trim(aScript[CurrentLine]);
i := Pos('#', s);
if i > 0 then
s := Trim(Copy(s, 1, Pred(i)));
if s <> '' then
if Assigned(CurrentRule) then begin
if UpperCase(s) = 'END MATCH' then begin
if not CurrentRule.IsEmpty then begin
SetLength(scRules, Succ(Length(scRules)));
scRules[High(scRules)] := CurrentRule;
end;
CurrentRule := nil;
Inc(CurrentLine);
Continue;
end;
if UpperCase(Copy(s, 1, Length('SET '))) = 'SET ' then begin
Delete(s, 1, Length('SET '));
Temp.Delimiter := ' ';
Temp.StrictDelimiter := True;
Temp.DelimitedText := s;
Temp.StrictDelimiter := False;
for i := Pred(Temp.Count) downto 0 do
if Temp[i] = '' then
Temp.Delete(i);
if Temp.Count <> 3 then
raise Exception.Create('Expected format for SET is: SET <ElementName> TO <Value>');
if UpperCase(Temp[1]) <> 'TO' then
raise Exception.Create('Expected format for SET is: SET <ElementName> TO <Value>');
t := Temp[0];
s := Temp[2];
if (Length(s) > 11) and (s[Length(s)-6] = ':') and (LowerCase(Copy(s, Length(s) - 10, 3)) = '.es') then begin
i := Pos(':', s);
Temp.Clear;
Temp.Add(Copy(s, 1, Pred(i)));
Temp.Add(Copy(s, Succ(i), High(Integer)));
if (Temp[0] = '') or (Length(Temp[1]) <> 6) then
raise Exception.Create('Expected format for record references is FileName:FormID');
if scFilesMap.Find(Temp[0], i) then
_File := IwbFile(Pointer(scFilesMap.Objects[i]))
else
_File := nil;
if Assigned(_File) then
MainRecord := _File.RecordByFormID[ Cardinal(StrToInt('$'+Temp[1]) and $00FFFFFF) or (Cardinal(_File.LoadOrder) shl Cardinal(24)) , True]
else
MainRecord := nil;
if Assigned(MainRecord) then
CurrentRule.AddAction(TwbSetElementAction.Create(t, IntToHex64(MainRecord.LoadOrderFormID, 8), _File));
end else
CurrentRule.AddAction(TwbSetElementAction.Create(Temp[0], Temp[2], nil));
end else if UpperCase(Copy(s, 1, Length('DELETE'))) = 'DELETE' then begin
CurrentRule.AddAction(TwbDeleteRefrAction.Create);
end else begin
if UpperCase(Copy(s, 1, Length('ADD REFR '))) <> 'ADD REFR ' then
raise Exception.Create('ADD REFR or END MATCH expected');
Delete(s, 1, Length('ADD REFR '));
s := Trim(s);
Temp.CommaText := s;
for i := 0 to Pred(Temp.Count) do
Temp[i] := Trim(Temp[i]);
if Temp.Count < 8 then
raise Exception.Create('Expected format for ADD REFR is FileName:FormID,PosX,PosY,PosZ,RotX,RotY,RotZ,Scale[,EDIDPrefix[,EDIDSuffix]]');
with Position do begin
x := StrToFloat(Temp[1]);
y := StrToFloat(Temp[2]);
z := StrToFloat(Temp[3]);
end;
with Rotation do begin
x := (StrToFloat(Temp[4]) * Pi) / 180;
y := (StrToFloat(Temp[5]) * Pi) / 180;
z := (StrToFloat(Temp[6]) * Pi) / 180;
end;
Scale := StrToFloat(Temp[7]);
EDIDPrefix := '';
if Temp.Count >= 9 then
EDIDPrefix := Temp[8];
EDIDSuffix := '';
if Temp.Count >= 10 then
EDIDSuffix := Temp[9];
Temp.Delimiter := ':';
Temp.DelimitedText := Temp[0];
if Temp.Count <> 2 then
raise Exception.Create('Expected format for ADD REFR is FileName:FormID,PosX,PosY,PosZ,RotX,RotY,RotZ,Scale[,EDIDPrefix[,EDIDSuffix]]');
if scFilesMap.Find(Temp[0], i) then
_File := IwbFile(Pointer(scFilesMap.Objects[i]))
else
_File := nil;
if Assigned(_File) then
MainRecord := _File.RecordByFormID[ Cardinal(StrToInt('$'+Temp[1]) and $00FFFFFF) or (Cardinal(_File.LoadOrder) shl Cardinal(24)) , True]
else
MainRecord := nil;
if Assigned(MainRecord) then
CurrentRule.AddAction(TwbAddRefrAction.Create(MainRecord, Position, Rotation, Scale, EDIDPrefix, EDIDSuffix));
end;
end else begin
if UpperCase(Copy(s, 1, Length('MATCH REFR WHERE NAME = '))) <> 'MATCH REFR WHERE NAME = ' then
raise Exception.Create('MATCH REFR WHERE NAME = expected');
Delete(s, 1, Length('MATCH REFR WHERE NAME = '));
s := Trim(s);
Temp.CommaText := s;
if Temp.Count <> 1 then
raise Exception.Create('Expected format for MATCH REFR WHERE NAME = is FileName:FormID');
Temp.Delimiter := ':';
Temp.DelimitedText := Temp[0];
if Temp.Count <> 2 then
raise Exception.Create('Expected format for MATCH REFR WHERE NAME = is FileName:FormID');
if scFilesMap.Find(Temp[0], i) then
_File := IwbFile(Pointer(scFilesMap.Objects[i]))
else
_File := nil;
if Assigned(_File) then
MainRecord := _File.RecordByFormID[ Cardinal(StrToInt('$'+Temp[1]) and $00FFFFFF) or (Cardinal(_File.LoadOrder) shl Cardinal(24)) , True]
else
MainRecord := nil;
if Assigned(MainRecord) then
CurrentRule := TwbMatchRefrRule.Create(MainRecord)
else
CurrentRule := TwbNullRule.Create;
end;
Inc(CurrentLine);
except
on E: Exception do begin
E.Message := 'Line '+IntToStr(CurrentLine)+': '+ E.Message;
raise;
end;
end;
finally
Temp.Free;
end;
end;
function TwbScript.Match(const aElement: IwbElement; var aScanRefBy: Boolean;var aAction: IwbScriptAction): Boolean;
var
i : Integer;
ScanRefBy : Boolean;
begin
aScanRefBy := False;
Result := False;
for i := Low(scRules) to High(scRules) do begin
ScanRefBy := False;
Result := scRules[i].Match(aElement, ScanRefBy, aAction) or Result;
aScanRefBy := aScanRefBy or ScanRefBy;
end;
end;
function TwbScript.NeedRefsFor(const aFile: IwbFile): Boolean;
var
i : Integer;
begin
Result := False;
for i := Low(scRules) to High(scRules) do begin
Result := scRules[i].NeedRefsFor(aFile);
if Result then
Exit;
end;
end;
procedure TwbScript.ResetAllTags;
var
i: Integer;
begin
for i := Low(scFiles) to High(scFiles) do
scFiles[i].ResetTags;
end;
procedure TwbScript.ScanForTargets(out aElements: TDynElements; out aActions: TDynActions; aProgress: TwbScriptScanProgress);
var
StartTick : Cardinal;
TotalCount : Integer;
Count : Integer;
procedure ScanRecord(aMainRecord: IwbMainRecord);
var
i : Integer;
ScanRefBy : Boolean;
begin
aMainRecord := aMainRecord.WinningOverride;
if not aMainRecord.IsTagged then begin
Inc(TotalCount);
aMainRecord.Tag;
if Match(aMainRecord, ScanRefBy, aActions[Count]) then begin
aElements[Count] := aMainRecord;
Inc(Count);
if High(aElements) < Count then begin
SetLength(aElements, Length(aElements) * 2);
SetLength(aActions , Length(aElements));
end;
end else
aActions[Count] := nil;
if ScanRefBy then
for i := 0 to Pred(aMainRecord.ReferencedByCount) do
ScanRecord(aMainRecord.ReferencedBy[i]);
end;
end;
procedure FindRecords(const aElement: IwbElement);
var
MainRecord : IwbMainRecord;
Container : IwbContainerElementRef;
i : Integer;
begin
if Assigned(aProgress) then
if StartTick + 500 < GetTickCount then begin
aProgress(TotalCount, Count);
StartTick := GetTickCount;
end;
if Supports(aElement, IwbMainRecord, MainRecord) then
ScanRecord(MainRecord)
else if Supports(aElement, IwbContainerElementRef, Container) then
if ShouldScan(Container) then
for i := 0 to Pred(Container.ElementCount) do
FindRecords(Container.Elements[i]);
end;
var
i: Integer;
begin
StartTick := GetTickCount;
TotalCount := 0;
Count := 0;
aElements := nil;
aActions := nil;
SetLength(aElements, 1024);
SetLength(aActions, 1024);
BuildAllRefs;
ResetAllTags;
for i := Low(scFiles) to High(scFiles) do
FindRecords(scFiles[i]);
SetLength(aElements, Count);
SetLength(aActions, Count);
end;
function TwbScript.ShouldScan(const aContainer: IwbContainerElementRef): Boolean;
var
i : Integer;
begin
Result := False;
for i := Low(scRules) to High(scRules) do begin
Result := scRules[i].ShouldScan(aContainer);
if Result then
Exit;
end;
end;
{ TwbAddRefrAction }
constructor TwbAddRefrAction.Create(const aMainRecord: IwbMainRecord;
const aPos, aRot: TD3DXVector3; const aScale: Single; const aEDIDPrefix, aEDIDSuffix: string);
begin
araMainRecord := aMainRecord;
araPos := aPos;
araRot := aRot;
araScale := aScale;
araEDIDPrefix := aEDIDPrefix;
araEDIDSuffix := aEDIDSuffix;
end;
function NormalizeRotation(const aRot: TD3DXVector3): TD3DXVector3;
function NormalizeAxis(const aValue: Single): Single;
begin
Result := aValue;
while Result < (-Pi) do
Result := Result + (2*Pi);
while Result > Pi do
Result := Result - (2*Pi);
end;
begin
Result.x := NormalizeAxis(aRot.x);
Result.y := NormalizeAxis(aRot.y);
Result.z := NormalizeAxis(aRot.z);
end;
// elevation = x
// bank = y
// heading = z
function QuatFromEuler(const aEuler: TD3DXVector3): TD3DXQuaternion;
var
c1, c2, c3 : Single;
s1, s2, s3 : Single;
c1c2, s1s2 : Single;
begin
with aEuler do begin
c1 := Cos(x/2);
c2 := Cos(y/2);
c3 := Cos(z/2);
s1 := Sin(x/2);
s2 := Sin(y/2);
s3 := Sin(z/2);
end;
c1c2 := c1 * c2;
s1s2 := s1 * s2;
with Result do begin
w := c1c2 * c3 + s1s2 * s3;
x := s1 * c2 * c3 - c1 * s2 * s3;
y := c1 * s2 * c3 + s1 * c2 * s3;
z := c1c2 * s3 - s1s2 * c3;
end;
end;
function EulerFromQuat(const aQuat: TD3DXQuaternion): TD3DXVector3;
var
sqw, sqx, sqy, sqz : Single;
_Unit : Single;
Test : Single;
begin
with aQuat do begin
sqw := Sqr(w);
sqx := Sqr(x);
sqy := Sqr(y);
sqz := Sqr(z);
Test := x*z - w*y;
_Unit := sqw + sqx + sqy + sqz;
if Test > 0.49992 * _Unit then begin
Result.x := -ArcTan2( 2.0 * x*y - 2.0 * w*z , sqw - sqx + sqy - sqz );
Result.y := -Pi/2;
Result.z := 0.0;
end else if Test < -0.49992 * _Unit then begin
Result.x := -ArcTan2( 2.0 * w*z - 2.0 * x*y , sqw - sqx + sqy - sqz );
Result.y := Pi/2;
Result.z := 0.0;
end else begin
Result.x := -ArcTan2( -2.0 * x*w - 2.0 * y*z , sqw - sqx - sqy + sqz );
Result.y := -ArcSin( ( 2.0 * Test ) / _Unit );
Result.z := -ArcTan2( -2.0 * x*y - 2.0 * w*z , sqw + sqx - sqy - sqz );
end;
end;
end;
function QuatMultQuat(const a, b: TD3DXQuaternion): TD3DXQuaternion;
begin
with Result do begin
w := a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z;
x := a.w * b.x + a.x * b.w - a.y * b.z + a.z * b.y;
y := a.w * b.y + a.x * b.z + a.y * b.w - a.z * b.x;
z := a.w * b.z - a.x * b.y + a.y * b.x + a.z * b.w;
end;
end;
function QuatMultVec3(const q: TD3DXQuaternion; const v: TD3DXVector3): TD3DXVector3;
var
t2, t3, t4, t5, t6, t7, t8, t9, t10: Single;
begin
with q do begin
t2 := w * x;
t3 := w * y;
t4 := w * z;
t5 := -x * x;
t6 := x * y;
t7 := x * z;
t8 := -y * y;
t9 := y * z;
t10 := -z * z;
end;
with Result do begin
x := 2 * ( ( t8 + t10 ) * v.x + ( t6 + t4 ) * v.y + ( t7 - t3 ) * v.z ) + v.x;
y := 2 * ( ( t6 - t4 ) * v.x + ( t5 + t10 ) * v.y + ( t9 + t2 ) * v.z ) + v.y;
z := 2 * ( ( t7 + t3 ) * v.x + ( t9 - t2 ) * v.y + ( t5 + t8 ) * v.z ) + v.z;
end;
end;
function TwbAddRefrAction.Process(const aElement: IwbElement): Boolean;
var
MainRecord : IwbMainRecord;
MainRef : IwbContainerElementRef;
NameRec : IwbContainerElementRef;
DataRec : IwbContainerElementRef;
Position : TD3DXVector3;
Rotation : TD3DXVector3;
Scale : Single;
Matrix : TD3DXMatrix;
// Matrix2 : TD3DXMatrix;
// Matrix3 : TD3DXMatrix;
Quat : TD3DXQuaternion;
Quat2 : TD3DXQuaternion;
Quat3 : TD3DXQuaternion;
// t : Single;
Pos : TD3DXVector3;
Rot : TD3DXVector3;
Temp : TD3DXVector3;
// q1,q2,q3,q4: Single;
// Test2 : array [0..3,0..3,0..3,0..3] of TD3DXVector3;
// i,j,k,l : Integer;
GroupRecord: IwbGroupRecord;
NewRecord : IwbMainRecord;
begin
Result := False;
if Supports(aElement, IwbMainRecord, MainRecord) and
Supports(aElement, IwbContainerElementRef, MainRef) and
Supports(MainRecord.RecordBySignature['DATA'], IwbContainerElementRef, DataRec) and
(DataRec.ElementCount = 2) then begin
with Position, (DataRec.Elements[0] as IwbContainerElementRef) do begin
if ElementCount >= 1 then
X := StrToFloatDef(Elements[0].Value, 0);
if ElementCount >= 2 then
Y := StrToFloatDef(Elements[1].Value, 0);
if ElementCount >= 3 then
Z := StrToFloatDef(Elements[2].Value, 0);
end;
with Rotation, (DataRec.Elements[1] as IwbContainerElementRef) do begin
if ElementCount >= 1 then
X := StrToFloatDef(Elements[0].Value, 0);
if ElementCount >= 2 then
Y := StrToFloatDef(Elements[1].Value, 0);
if ElementCount >= 3 then
Z := StrToFloatDef(Elements[2].Value, 0);
end;
Rot := NormalizeRotation(Rot);
if Supports(MainRecord.RecordBySignature['XSCL'], IwbContainerElementRef, DataRec) then
Scale := StrToFloatDef(DataRec.Value, 1)
else
Scale := 1;
Pos := araPos;
if Scale <> 1 then begin
D3DXMatrixScaling(Matrix, Scale, Scale, Scale);
D3DXVec3TransformCoord(Temp, Pos, Matrix);
Pos := Temp;
end;
Quat := QuatFromEuler(Rotation);
Temp := QuatMultVec3(Quat, Pos);
Pos := Temp;
D3DXVec3Add(Temp, Pos, Position);
Pos := Temp;
Quat2 := QuatFromEuler(araRot);
Quat3 := QuatMultQuat(Quat, Quat2);
Rot := EulerFromQuat(Quat3);
Scale := Scale * araScale;
{
with Rotation do
Quat := QuatFromEuler(D3DXVector3(x, y, z));
D3DXMatrixRotationQuaternion(Matrix, Quat);
D3DXVec3TransformCoord(Temp, Pos, Matrix);
Pos := Temp;
D3DXVec3Add(Temp, Pos, Position);
Pos := Temp;
with araRot do
Quat2 := QuatFromEuler(D3DXVector3(x, y, z));
D3DXQuaternionMultiply(Quat3, Quat, Quat2);
Rot := EulerFromQuat(Quat3);
Scale := Scale * araScale;
}
if Supports(MainRecord.Container, IwbGroupRecord, GroupRecord) then begin
GroupRecord._File.AddMasterIfMissing(araMainRecord.MasterOrSelf._File.FileName);
NewRecord := GroupRecord.Add('REFR', True) as IwbMainRecord;
NewRecord.IsPersistent := MainRecord.IsPersistent;
NewRecord.IsVisibleWhenDistant := MainRecord.IsVisibleWhenDistant;
if ((araEDIDPrefix <> '') or (araEDIDSuffix <> '')) and (MainRecord.EditorID <> '') then
NewRecord.EditorID := araEDIDPrefix + MainRecord.EditorID + araEDIDSuffix;
NameRec := NewRecord.Add('NAME', True) as IwbContainerElementRef;
NameRec.EditValue := IntToHex64(araMainRecord.LoadOrderFormID, 8);
DataRec := NewRecord.Add('DATA', True) as IwbContainerElementRef;
with Pos, (DataRec.Elements[0] as IwbContainerElementRef) do begin
Assert(ElementCount = 3);
Elements[0].EditValue := FloatToStr(x);
Elements[1].EditValue := FloatToStr(y);
Elements[2].EditValue := FloatToStr(z);
end;
with Rot, (DataRec.Elements[1] as IwbContainerElementRef) do begin
Assert(ElementCount = 3);
Elements[0].EditValue := FloatToStr(x);
Elements[1].EditValue := FloatToStr(y);
Elements[2].EditValue := FloatToStr(z);
end;
if Scale <> 1 then begin
DataRec := NewRecord.Add('XSCL', True) as IwbContainerElementRef;
DataRec.EditValue := FloatToStr(Scale);
end;
end;
end;
end;
{ TwbMatchRefrRule }
procedure TwbMatchRefrRule.AddAction(const aAction: IwbScriptAction);
begin
SetLength(mrrActions, Succ(Length(mrrActions)));
mrrActions[High(mrrActions)] := aAction;
end;
constructor TwbMatchRefrRule.Create(const aMainRecord: IwbMainRecord);
begin
mrrMainRecord := aMainRecord;
end;
function TwbMatchRefrRule.IsEmpty: Boolean;
begin
Result := Length(mrrActions) < 1;
end;
function TwbMatchRefrRule.Match(const aElement: IwbElement; var aScanRefBy: Boolean; var aAction: IwbScriptAction): Boolean;
var
MainRecord : IwbMainRecord;
begin
Result := False;
aScanRefBy := False;
if Supports(aElement, IwbMainRecord, MainRecord) then begin
if MainRecord.LoadOrderFormID = mrrMainRecord.LoadOrderFormID then
aScanRefBy := True
else begin
Result := (MainRecord.BaseRecordID = mrrMainRecord.LoadOrderFormID);
if Result then
TwbActionHub.Add(aAction, mrrActions);
end;
end;
end;
function TwbMatchRefrRule.NeedRefsFor(const aFile: IwbFile): Boolean;
begin
Result := aFile.LoadOrder >= mrrMainRecord._File.LoadOrder;
end;
function TwbMatchRefrRule.ShouldScan(const aContainer: IwbContainerElementRef): Boolean;
var
_File: IwbFile;
begin
Result :=
aContainer.Equals(mrrMainRecord.Container) or
(Supports(aContainer, IwbFile, _File) and (_File.Equals(mrrMainRecord._File)));
end;
{ TwbNullRule }
procedure TwbNullRule.AddAction(const aAction: IwbScriptAction);
begin
// nothing
end;
constructor TwbNullRule.Create;
begin
inherited Create;
end;
function TwbNullRule.IsEmpty: Boolean;
begin
Result := True;
end;
function TwbNullRule.Match(const aElement: IwbElement; var aScanRefBy: Boolean; var aAction: IwbScriptAction): Boolean;
begin
Result := False;
aScanRefBy := False;
end;
function TwbNullRule.NeedRefsFor(const aFile: IwbFile): Boolean;
begin
Result := False;
end;
function TwbNullRule.ShouldScan(const aContainer: IwbContainerElementRef): Boolean;
begin
Result := False;
end;
{ TwbActionHub }
class procedure TwbActionHub.Add(var aAction: IwbScriptAction; const aActions: TDynActions);
var
ActionHub: IwbActionHub;
begin
if not Supports(aAction, IwbActionHub, ActionHub) then
case Length(aActions) of
0: Exit;
1: if not Assigned(aAction) then begin
aAction := aActions[0];
Exit;
end;
else
ActionHub := TwbActionHub.Create(aAction);
aAction := ActionHub;
end;
ActionHub.AddActions(aActions);
end;
procedure TwbActionHub.AddActions(const aActions: TDynActions);
var
OldLength : Integer;
i : Integer;
begin
if Length(aActions) < 1 then
Exit;
OldLength := Length(ahActions);
SetLength(ahActions, OldLength + Length(aActions));
for i := Low(aActions) to High(aActions) do
ahActions[i + OldLength] := aActions[i];
end;
constructor TwbActionHub.Create(const aAction: IwbScriptAction);
begin
if Assigned(aAction) then begin
SetLength(ahActions, 1);
ahActions[0] := aAction;
end;
inherited Create;
end;
function TwbActionHub.Process(const aElement: IwbElement): Boolean;
var
i: Integer;
begin
Result := False;
for i := Low(ahActions) to High(ahActions) do
Result := ahActions[i].Process(aElement) or Result;
end;
{ TwbDeleteRefrAction }
constructor TwbDeleteRefrAction.Create;
begin
//...
end;
function TwbDeleteRefrAction.Process(const aElement: IwbElement): Boolean;
var
MainRecord : IwbMainRecord;
REFRs : TDynMainRecords;
BaseRecord : IwbContainerElementRef;
i : Integer;
begin
Result := False;
if Supports(aElement, IwbMainRecord, MainRecord) and (MainRecord.Signature = 'REFR') then begin
REFRs := wbGetSiblingREFRsWithin(MainRecord, 300);
for i := Low(REFRs) to High(REFRs) do
if Supports(REFRs[i].BaseRecord, IwbContainerElementRef, BaseRecord) then
if (BaseRecord.ElementValues['Record Header\Signature'] = 'LIGH') and
not BaseRecord.ElementExists['Model'] then begin
REFRs[i].DeleteInto(MainRecord._File);
Result := True;
end;
end;
end;
{ TwbSetElementAction }
constructor TwbSetElementAction.Create(const aElement, aValue: string; const aMasterFile: IwbFile);
begin
seaElement := aElement;
seaValue := aValue;
seaMasterFile := aMasterFile;
inherited Create;
end;
function TwbSetElementAction.Process(const aElement: IwbElement): Boolean;
var
MainRecord : IwbMainRecord;
// REFRs : TDynMainRecords;
// BaseRecord : IwbContainerElementRef;
// i : Integer;
begin
Result := False;
if Supports(aElement, IwbMainRecord, MainRecord) then begin
if Assigned(seaMasterFile) then
MainRecord._File.AddMasterIfMissing(seaMasterFile.FileName);
MainRecord.ElementEditValues[seaElement] := seaValue;
Result := True;
end;
end;
//var
// Quat : TD3DXQuaternion;
// Euler : TD3DXVector3;
initialization
{
Quat.y := -0.048730;
Quat.x := 0.671283;
Quat.w := 0.736597;
Quat.z := 1.179320;
Euler := EulerFromQuat(Quat);
Euler.x := Euler.x / Pi * 180;
Euler.y := Euler.y / Pi * 180;
Euler.z := Euler.z / Pi * 180;
Euler := EulerFromQuat(Quat);
}
end.
|
unit ftSyncClient;
interface
uses
unNamedPipe
,Classes
,ftTypes
,ExtCtrls
,hcQueryIntf
,CodeSiteLogging
,ftCodeSiteHelper
,Contnrs
,ADODB
;
type
TftStatusUpdateMethod = procedure of object;
TftSyncMonitorStatus = (smsStarted = 1, smsSucceeded = 2, smsInProgress = 3, smsIdle = 4, smsRetrying = 5, smsFailed = 6);
TftSyncStatus = (ssIdle,ssDataSyncing,ssProgrammabilitySyncing,ssError,ssTimeOut,ssGetStatus,ssNone);
const
SyncStatusNames :array[TftSyncstatus] of string = ('Idle','Data Syncing','Programmability Syncing','Error','TimeOut','Get Status','None');
SyncMonitorStatusNames :array[TftSyncMonitorStatus] of string = ('Sync Started','Sync Finished','Syncing','Idle','Retrying','Failed');
type
TftSyncClient = class(TComponent)
private
FDataSyncTimeOut :Cardinal;
FThread :TThread; //used to indicate if SyncClient needs to use Synchronize() when triggering status events
FPercentComplete :TftPercentRange;
FOnPercentageUpdate :TNotifyEvent;
FOnRequestSent :TNotifyEvent;
FOnStatusUpdate :TNotifyEvent;
FOnSyncFinished :TNotifyEvent;
FOnSyncStarted :TNotifyEvent;
FOnSyncFailed :TNotifyEvent;
FPendingStatus :TftSyncStatus; //request sent that is pending an OK from the service to acknowledge it ssIdle used to determine when next command can be sent
FStatus :TftSyncStatus;
procedure RequestDataSyncStatusUpdate;
function RequestDataSync :Boolean;
function RequestProgrammabilitySync :Boolean;
procedure PipeError(Sender: TObject; Pipe: THandle; PipeContext: TPipeContext; ErrorCode: Integer);
function WaitforFinish(const StatusUpdateMethod :TftStatusUpdateMethod; TimeOutInSeconds :Cardinal): Boolean;
procedure RequestProgSyncStatusUpdate;
function ParsePercentage(const Value: AnsiString): TftPercentRange;
procedure ShowPercentage;
procedure SetPercentageComplete(Value: TftPercentRange);
function GetPipeDisconnect :TOnPipeDisconnect;
function GetPipeError: TOnPipeError;
function GetPipeMessage: TOnPipeMessage;
function GetPipeSent: TOnPipeSent;
protected
FLastSyncAttempt :TDateTime; //when last sync request was made
FSyncRequired :Boolean;
FSyncMonitorStatus :TftSyncMonitorStatus;
FFactoryPool :TObject;
FPipeClient :TPipeClient;
FCodeSite :TCodeSiteLogger;
FLastStatusMessage :AnsiString; //last message returned from the FabwareService
procedure DoSyncStarted;
procedure DoSyncFinished;
procedure DoSyncFailed;
procedure PerformDataSync;
function SendMessage(aMessage :AnsiString) :boolean; virtual;
procedure PipeMessage(Sender: TObject; Pipe: THandle; Stream: TStream); virtual;
procedure SetStatus(Value :TftSyncStatus);
public
constructor Create(aOwner :TComponent); override;
procedure DisableTimer;
function SyncData(TimeOutInSeconds :Cardinal) :Boolean;
function SyncProgrammability(TimeOutInSeconds :Cardinal) :Boolean;
//settings
property DataSyncTimeOut :cardinal read FDataSyncTimeOut write FDataSyncTimeOut;
//status info
property Status :TftSyncStatus read FStatus;
property SyncMonitorStatus :TftSyncMonitorStatus read FSyncMonitorStatus;
property LastStatusMessage :AnsiString read FLastStatusMessage;
property Percentage :TftPercentRange read FPercentComplete;
property Thread :TThread read FThread write FThread;
//events
property OnStatusUpdate :TNotifyEvent read FOnStatusUpdate write FOnStatusUpdate;
property OnRequestSent :TNotifyEvent read FOnRequestSent write FOnRequestSent;
property OnPercentageUpdate :TNotifyEvent read FOnPercentageUpdate write FOnPercentageUpdate;
property OnSyncFinished :TNotifyEvent read FOnSyncFinished write FOnSyncFinished;
property OnSyncStarted :TNotifyEvent read FOnSyncStarted write FOnSyncStarted;
property OnSyncFailed :TNotifyEvent read FOnSyncFailed write FOnSyncFailed;
property OnPipeDisconnect: TOnPipeDisconnect read GetPipeDisconnect;
property OnPipeMessage: TOnPipeMessage read GetPipeMessage;
property OnPipeSent: TOnPipeSent read GetPipeSent;
property OnPipeError: TOnPipeError read GetPipeError;
end;
implementation
uses
SysUtils
,StrUtils
,Forms
;
constructor TftSyncClient.Create(aOwner: TComponent);
begin
inherited;
FCodeSite := TCodeSiteLogger.Create(Self);
FCodeSite.Category := 'SyncClient';
FPipeClient := TPipeClient.Create(Self);
FPipeClient.OnPipeMessage := PipeMessage;
FPipeClient.OnPipeError := PipeError;
FPipeClient.ServerName := '.';
FPipeClient.PipeName := 'FabwareServicePipe';
FPipeClient.Name := 'pcFabware';
FDataSyncTimeOut := 60000;
FSyncMonitorStatus := smsIdle;
end;
procedure TftSyncClient.PipeError(Sender: TObject; Pipe: THandle;
PipeContext: TPipeContext; ErrorCode: Integer);
const
INT_PipeDisconnected = 233;
begin
//if the error code is anything other than a 233 Pipe Disconnect then update the status
if ErrorCode <> INT_PipeDisconnected then
begin
FLastStatusMessage := AnsiString(Format('Error :%d was returned.',[ErrorCode]));
SetStatus(ssError);
end;
end;
function TftSyncClient.SendMessage(aMessage: AnsiString) :boolean;
{
Routine to send a message to the server application. Result
indicates whether the message was successfully sent.
}
var
GotReply :boolean;
begin
if (FPipeClient.Connected) or (FPipeClient.Connect()) then
begin
FPipeClient.Write(aMessage[1],Length(aMessage));
FPipeClient.FlushPipeBuffers;
GotReply := FPipeClient.WaitForReply(30 * MSecsPerSec); //WaitForReply on XPSP3 is returning False quite often so always return True
FPipeClient.Disconnect;
Result := True;
FCodeSite.SendFmtMsg('Sending: %s',[aMessage]);
FCodeSite.SendFmtMsg('WaitForReply returned: %s',[ifthen(GotReply,'True','False')]);
end
else //must not be able to connect
begin
FLastStatusMessage := 'Could not connect to FabwareService';
SetStatus(ssError);
Result := False;
end;
end;
procedure TftSyncClient.SetStatus(Value: TftSyncStatus);
begin
FStatus := Value;
if Assigned(FOnStatusUpdate) then
FOnStatusUpdate(Self);
end;
procedure TftSyncClient.PerformDataSync;
begin
SyncData(FDataSyncTimeOut);
end;
procedure TftSyncClient.DisableTimer;
const STR_DisableTimer :AnsiString = 'pause timer'#13#10;
begin
FCodeSite.EnterMethod( Self, 'DisableTimer' );
SendMessage(STR_DisableTimer);
FCodeSite.ExitMethod( Self, 'DisableTimer' );
end;
function TftSyncClient.SyncData(TimeOutInSeconds: Cardinal) :Boolean;
begin
if (FThread <> nil) then
TThread.Synchronize(FThread,DoSyncStarted)
else
DoSyncStarted;
FDataSyncTimeOut := TimeOutInSeconds;
Result := RequestDataSync;
if Result then
FSyncRequired := False;
end;
procedure TftSyncClient.DoSyncStarted;
begin
if assigned(FOnSyncStarted) then
FOnSyncStarted(Self);
end;
function TftSyncClient.GetPipeDisconnect: TOnPipeDisconnect;
begin
Result := FPipeClient.OnPipeDisconnect;
end;
function TftSyncClient.GetPipeError: TOnPipeError;
begin
Result := FPipeClient.OnPipeError;
end;
function TftSyncClient.GetPipeMessage: TOnPipeMessage;
begin
Result := FPipeClient.OnPipeMessage;
end;
function TftSyncClient.GetPipeSent: TOnPipeSent;
begin
Result := FPipeClient.OnPipeSent;
end;
procedure TftSyncClient.DoSyncFailed;
begin
if assigned(FOnSyncFailed) then
FOnSyncFailed(Self);
end;
procedure TftSyncClient.DoSyncFinished;
begin
if assigned(FOnSyncFinished) then
FOnSyncFinished(Self);
end;
function TftSyncClient.SyncProgrammability(TimeOutInSeconds: Cardinal) :Boolean;
begin
Result := (RequestProgrammabilitySync) and WaitForFinish(RequestProgSyncStatusUpdate,TimeOutInSeconds);
end;
function TftSyncClient.WaitforFinish(const StatusUpdateMethod :TftStatusUpdateMethod; TimeOutInSeconds :Cardinal) :Boolean;
{
Routine to parse the status buffer returned by the service to determine if the
current operation is completed successfully or with an error.
}
var
Done :Boolean;
begin
FCodeSite.EnterMethod( Self, 'WaitforFinish' );
Result := False;
Done := False;
while not Done do
begin
FCodeSite.SendFmtMsg('PendingStatus: %s',[SyncStatusNames[FPendingStatus]]);
FCodeSite.SendFmtMsg('CurrentStatus: %s',[SyncStatusNames[FStatus]]);
if FPendingStatus = ssNone then
StatusUpdateMethod;
Application.ProcessMessages;
Done := (FStatus = ssIdle) or (FStatus = ssError);
FCodeSite.SendFmtMsg( 'Done is %s',[IfThen(Done,'True','False')] );
if not(Done) and (TimeOutInSeconds = 0) then
begin
Done := True;
SetStatus(ssTimeOut);
end
else
if not Done then
begin
Sleep(1000); //sleep for 1 second
Dec(TimeOutInSeconds,1);
//if we haven't got a response within a 5 second window, perform another status request.
if (TimeOutInSeconds mod 5 = 0) and (FStatus = ssDataSyncing) then
RequestDataSyncStatusUpdate;
end
else
Result := True;
end;
FCodeSite.SendFmtMsg( 'Result is %s',[IfThen(Result,'True','False')] );
FCodeSite.ExitMethod( Self, 'WaitforFinish' );
end;
function TftSyncClient.ParsePercentage(const Value :AnsiString) :TftPercentRange;
var
J,
I: Integer;
begin
//count the number of numeric digits
J := 0;
for I := 1 to 3 do
begin
if CharInSet(Value[I],['0'..'9']) then
Inc(J);
end;
if J = 0 then
Result := 0
else
Result := TftPercentRange(StrToInt(Copy(Value,1,J)));
end;
procedure TftSyncClient.PipeMessage(Sender: TObject; Pipe: THandle; Stream: TStream);
{
After each command the SyncServer returns an OK. We key on this to perform our
state transitions. ssNone is used as a pseudo state to allow our WaitForFinish
routine to know when to request additional Status Updates from the server.
The status update messages from the server contain a percentage value at the
start of each line, but I don't use this as it does not appear to be accurate.
}
const
STR_Idle :AnsiString = 'Not Currently Running';
STR_OK :AnsiString = 'OK'#13#10;
var
aStringStream :TStringStream;
begin
FCodeSite.EnterMethod( Self, 'PipeMessage' );
aStringStream := TStringStream.Create;
try
aStringStream.CopyFrom(Stream,Stream.Size);
FLastStatusMessage := AnsiString(aStringStream.DataString);
FCodeSite.SendFmtMsg('Received : %s',[FLastStatusMessage] );
// Logger.FactoryPool := FFactoryPool;
// Logger.LogEvent(ecSynchronization,s0,v2,'',Format('Received : %s',[FLastStatusMessage]));
if (STR_OK = FLastStatusMessage) then
begin
case FPendingStatus of
ssIdle: ;
ssGetStatus:
FLastStatusMessage := 'Status Requested';
ssDataSyncing:
FLastStatusMessage := 'Data Sync Has Started';
ssProgrammabilitySyncing:
FLastStatusMessage := 'Programmability Sync has Started';
ssError: ;
ssTimeOut: ;
end;
SetStatus(FPendingStatus);
FPendingStatus := ssNone; //allow next request
end
else
if (copy(FLastStatusMessage,1,4) = '100%') then
begin
SetStatus(FStatus);
FPendingStatus := ssNone; //allow next request
ShowPercentage;
end
else
if (Pos(STR_Idle,FLastStatusMessage) <> 0) then
SetStatus(ssIdle)
else //just make sure the event is triggered with the current status
begin
SetStatus(FStatus);
FPendingStatus := ssNone; //allow next request
ShowPercentage;
end;
finally
aStringStream.Free;
end;
FCodeSite.SendFmtMsg('PendingStatus: %s',[SyncStatusNames[FPendingStatus]]);
FCodeSite.SendFmtMsg('CurrentStatus: %s',[SyncStatusNames[FStatus]]);
FCodeSite.ExitMethod( Self, 'PipeMessage' );
end;
procedure TftSyncClient.ShowPercentage;
var
CurrentPercentComplete :TftPercentRange;
begin
//get the percentage complete
CurrentPercentComplete := ParsePercentage(FLastStatusMessage);
FCodeSite.SendFmtMsg('Percentage Complete: %d',[CurrentPercentComplete]);
if (CurrentPercentComplete > FPercentComplete) then
SetPercentageComplete(CurrentPercentComplete);
end;
procedure TftSyncClient.SetPercentageComplete(Value :TftPercentRange);
begin
FPercentComplete := Value;
if Assigned(FOnPercentageUpdate) then
FOnPercentageUpdate(Self);
end;
function TftSyncClient.RequestDataSync :Boolean;
const
STR_SyncDataCommand :AnsiString = 'synchronize'#13#10;
begin
FCodeSite.EnterMethod( Self, 'RequestDataSync' );
FPendingStatus := ssDataSyncing;
SetPercentageComplete(0);
Result := SendMessage(STR_SyncDataCommand);
FCodeSite.SendFmtMsg('PendingStatus: %s',[SyncStatusNames[FPendingStatus]]);
FCodeSite.SendFmtMsg('CurrentStatus: %s',[SyncStatusNames[FStatus]]);
FCodeSite.ExitMethod( Self, 'RequestDataSync' );
FLastSyncAttempt := Now;
end;
function TftSyncClient.RequestProgrammabilitySync :Boolean;
const
STR_SyncProgrammabilityCommand :AnsiString = 'synchronize programmability'#13#10;
begin
FCodeSite.EnterMethod( Self, 'RequestProgrammabilitySync' );
FPendingStatus := ssProgrammabilitySyncing;
SetPercentageComplete(0);
Result := SendMessage(STR_SyncProgrammabilityCommand);
FCodeSite.SendFmtMsg('PendingStatus: %s',[SyncStatusNames[FPendingStatus]]);
FCodeSite.SendFmtMsg('CurrentStatus: %s',[SyncStatusNames[FStatus]]);
FCodeSite.ExitMethod( Self, 'RequestProgrammabilitySync' );
end;
procedure TftSyncClient.RequestProgSyncStatusUpdate;
const
STR_GetProgrammabilitySyncStatus :AnsiString = 'get status buffer programmability'#13#10;
begin
FCodeSite.EnterMethod( Self, 'RequestProgSyncStatusUpdate' );
FPendingStatus := ssGetStatus;
SendMessage(STR_GetProgrammabilitySyncStatus);
FCodeSite.SendFmtMsg('PendingStatus: %s',[SyncStatusNames[FPendingStatus]]);
FCodeSite.SendFmtMsg('CurrentStatus: %s',[SyncStatusNames[FStatus]]);
FCodeSite.ExitMethod( Self, 'RequestProgSyncStatusUpdate' );
end;
procedure TftSyncClient.RequestDataSyncStatusUpdate;
const
STR_GetDataSyncStatus :AnsiString = 'get status buffer'#13#10;
begin
FCodeSite.EnterMethod( Self, 'RequestDataSyncStatusUpdate' );
FPendingStatus := ssGetStatus;
SendMessage(STR_GetDataSyncStatus);
FCodeSite.SendFmtMsg('PendingStatus: %s',[SyncStatusNames[FPendingStatus]]);
FCodeSite.SendFmtMsg('CurrentStatus: %s',[SyncStatusNames[FStatus]]);
FCodeSite.ExitMethod( Self, 'RequestDataSyncStatusUpdate' );
end;
end.
|
Unit SVGA;
Interface
Uses crt, DOS, graph;
Type DacPalette256 = Array [0..255] Of Array [0..2] Of Byte;
(* These are the currently supported modes *)
Const
SVGA320X200X256 = 0; (* 320x200x256 Standard VGA *)
SVGA640X400X256 = 1; (* 640x400x256 Svga *)
SVGA640X480X256 = 2; (* 640x480x256 Svga *)
SVGA800X600X256 = 3; (* 800x600x256 Svga *)
SVGA1024X768X256 = 4; (* 1024x768x256 Svga *)
TRANS_COPY_PIX = 8;
Var
svga_colors: DacPalette256;
SVGA_Mode,MaxX, MaxY, MaxColor: Integer;
Procedure SetVGAPalette256 (PalBuf : DacPalette256);
Procedure Initialize;
Implementation
(* Setvgapalette sets the entire 256 color palette *)
(* PalBuf contains RGB values for all 256 colors *)
(* R,G,B values range from 0 to 63 *)
Procedure SetVGAPalette256 (PalBuf : DacPalette256);
Var
Reg : Registers;
Begin
reg. AX := $1012;
reg. BX := 0;
reg. CX := 256;
reg. ES := Seg (PalBuf);
reg. DX := Ofs (PalBuf);
Intr ($10, reg);
End;
{$F+}
function DetectVGA256 : integer;
{ Detects VGA or MCGA video cards }
var
DetectedDriver : integer;
SuggestedMode : integer;
begin
DetectGraph(DetectedDriver, SuggestedMode);
if svga_mode =-1 then
if (DetectedDriver = VGA) or (DetectedDriver = MCGA) then
begin
Writeln('Which video mode would you like to use?');
Writeln(' 0) 320x200x256');
Writeln(' 1) 640x400x256');
Writeln(' 2) 640x480x256');
Writeln(' 3) 800x600x256');
Writeln(' 4) 1024x768x256');
Write('> ');
Readln(SuggestedMode);
DetectVGA256 := SuggestedMode;
end
else
DetectVGA256 := grError { Couldn't detect hardware }
else
Detectvga256 := SVGA_Mode;
end; { DetectVGA256 }
{$F-}
Var
AutoDetectPointer : pointer;
Procedure Initialize;
{ Initialize graphics and report any errors that may occur }
Var
InGraphicsMode : Boolean; { Flags initialization of graphics mode }
PathToDriver : String; { Stores the DOS path to *.BGI & *.CHR }
graphdriver,graphmode,errorcode:integer;
Begin
{ when using Crt and graphics, turn off Crt's memory-mapped writes
DirectVideo := False; }
PathToDriver := 'z:\tp70\bgi';
Repeat
AutoDetectPointer := @DetectVGA256;
GraphDriver := InstallUserDriver ('Svga256', AutoDetectPointer);
GraphDriver := Detect;
InitGraph (GraphDriver, GraphMode, PathToDriver);
ErrorCode := GraphResult; { preserve error return }
If ErrorCode <> grOK Then { error? }
Begin
WriteLn ('Graphics error: ', GraphErrorMsg (ErrorCode) );
If ErrorCode = grFileNotFound Then { Can't find driver file }
Begin
WriteLn ('Enter full path to BGI driver or type <Ctrl-Break> to quit:');
ReadLn (PathToDriver);
WriteLn;
End
Else
Halt (1); { Some other error: terminate }
End;
Until ErrorCode = grOK;
Randomize; { init random number generator }
MaxColor := GetMaxColor; { Get the maximum allowable drawing color }
MaxX := GetMaxX; { Get screen resolution values }
MaxY := GetMaxY;
End; { Initialize }
Var
svga_oldExit: pointer;
Procedure svga_Exit; Far;
Begin
ExitProc := svga_oldExit;
CloseGraph;
End;
Begin
svga_oldExit := ExitProc;
ExitProc := @svga_exit;
svga_mode:=-1;
Maxx:=-1; maxy:=-1; maxcolor:=-1;
End. |
(******************************************************************************
* PasVulkan *
******************************************************************************
* Version see PasVulkan.Framework.pas *
******************************************************************************
* zlib license *
*============================================================================*
* *
* Copyright (C) 2016-2020, Benjamin Rosseaux (benjamin@rosseaux.de) *
* *
* This software is provided 'as-is', without any express or implied *
* warranty. In no event will the authors be held liable for any damages *
* arising from the use of this software. *
* *
* Permission is granted to anyone to use this software for any purpose, *
* including commercial applications, and to alter it and redistribute it *
* freely, subject to the following restrictions: *
* *
* 1. The origin of this software must not be misrepresented; you must not *
* claim that you wrote the original software. If you use this software *
* in a product, an acknowledgement in the product documentation would be *
* appreciated but is not required. *
* 2. Altered source versions must be plainly marked as such, and must not be *
* misrepresented as being the original software. *
* 3. This notice may not be removed or altered from any source distribution. *
* *
******************************************************************************
* General guidelines for code contributors *
*============================================================================*
* *
* 1. Make sure you are legally allowed to make a contribution under the zlib *
* license. *
* 2. The zlib license header goes at the top of each source file, with *
* appropriate copyright notice. *
* 3. This PasVulkan wrapper may be used only with the PasVulkan-own Vulkan *
* Pascal header. *
* 4. After a pull request, check the status of your pull request on *
http://github.com/BeRo1985/pasvulkan *
* 5. Write code which's compatible with Delphi >= 2009 and FreePascal >= *
* 3.1.1 *
* 6. Don't use Delphi-only, FreePascal-only or Lazarus-only libraries/units, *
* but if needed, make it out-ifdef-able. *
* 7. No use of third-party libraries/units as possible, but if needed, make *
* it out-ifdef-able. *
* 8. Try to use const when possible. *
* 9. Make sure to comment out writeln, used while debugging. *
* 10. Make sure the code compiles on 32-bit and 64-bit platforms (x86-32, *
* x86-64, ARM, ARM64, etc.). *
* 11. Make sure the code runs on all platforms with Vulkan support *
* *
******************************************************************************)
unit PasVulkan.Hash.SHA3;
{$i PasVulkan.inc}
{$ifndef fpc}
{$ifdef conditionalexpressions}
{$if CompilerVersion>=24.0}
{$legacyifend on}
{$ifend}
{$endif}
{$endif}
interface
uses SysUtils,
Classes,
Math,
Vulkan,
PasVulkan.Types;
type TpvHashSHA3=class
public
type TState=array[0..24] of TpvUInt64;
PState=^TState;
TMessageDigest=array[0..63] of TpvUInt8;
PMessageDigest=^TMessageDigest;
private
const KECCAKF_ROUNDS=24;
keccakf_rndc:array[0..23] of TpvUInt64=
(
TpvUInt64($0000000000000001),TpvUInt64($0000000000008082),TpvUInt64($800000000000808a),
TpvUInt64($8000000080008000),TpvUInt64($000000000000808b),TpvUInt64($0000000080000001),
TpvUInt64($8000000080008081),TpvUInt64($8000000000008009),TpvUInt64($000000000000008a),
TpvUInt64($0000000000000088),TpvUInt64($0000000080008009),TpvUInt64($000000008000000a),
TpvUInt64($000000008000808b),TpvUInt64($800000000000008b),TpvUInt64($8000000000008089),
TpvUInt64($8000000000008003),TpvUInt64($8000000000008002),TpvUInt64($8000000000000080),
TpvUInt64($000000000000800a),TpvUInt64($800000008000000a),TpvUInt64($8000000080008081),
TpvUInt64($8000000000008080),TpvUInt64($0000000080000001),TpvUInt64($8000000080008008)
);
keccakf_rotc:array[0..23] of TpvInt32=(1,3,6,10,15,21,28,36,45,55,2,14,27,41,56,8,25,43,62,18,39,61,20,44);
keccakf_piln:array[0..23] of TpvInt32=(10,7,11,17,18,3,5,16,8,21,24,4,15,23,19,13,12,2,20,14,22,9,6,1);
private
fState:TState;
fStatePosition:TpvSizeInt;
fBlockSize:TpvSizeInt;
fMessageDigestSize:TpvSizeInt;
{$if not declared(ROLQWord)}
class function ROLQWord(const aValue:TpvUInt64;const aBits:TpvSizeUInt):TpvUInt64; static; inline;
{$ifend}
public
class procedure ProcessState(var aState:TState); static;
public
constructor Create(const aMessageDigestSize:TpvSizeInt); reintroduce;
destructor Destroy; override;
procedure Update(const aData:pointer;const aDataLength:TpvSizeInt);
procedure Final(const aMessageDigest:pointer);
class procedure Process(const aData:pointer;const aDataLength:TpvSizeInt;const aMessageDigest:pointer;const aMessageDigestSize:TpvSizeInt); static;
end;
TpvHashShake=class(TpvHashSHA3)
public
procedure XOF;
procedure Out(const aOutput:pointer;const aOutputLength:TpvSizeInt);
end;
TpvHashShake128=class(TpvHashShake)
public
constructor Create; reintroduce;
end;
TpvHashShake256=class(TpvHashShake)
public
constructor Create; reintroduce;
end;
implementation
{ TpvHashSHA3 }
{$if not declared(ROLQWord)}
class function TpvHashSHA3.ROLQWord(const aValue:TpvUInt64;const aBits:TpvSizeUInt):TpvUInt64;
begin
result:=(aValue shl aBits) or (aValue shr (64-aBits));
end;
{$ifend}
class procedure TpvHashSHA3.Process(const aData:pointer;const aDataLength:TpvSizeInt;const aMessageDigest:pointer;const aMessageDigestSize:TpvSizeInt);
var Instance:TpvHashSHA3;
begin
Instance:=TpvHashSHA3.Create(aMessageDigestSize);
try
Instance.Update(aData,aDataLength);
Instance.Final(aMessageDigest);
finally
FreeAndNil(Instance);
end;
end;
class procedure TpvHashSHA3.ProcessState(var aState:TState);
var i,j,k,r:TpvSizeInt;
t:TpvUInt64;
bc:array[0..4] of TpvUInt64;
{$ifdef BigEndian}
v:PpvUInt8Array;
{$endif}
begin
{$ifdef BigEndian}
for i:=0 to 24 do begin
v:=pointer(@aState[i]);
aState[i]:=(TpvUInt64(v^[0]) shl 0) or (TpvUInt64(v^[1]) shl 8) or
(TpvUInt64(v^[2]) shl 16) or (TpvUInt64(v^[3]) shl 24) or
(TpvUInt64(v^[4]) shl 32) or (TpvUInt64(v^[5]) shl 40) or
(TpvUInt64(v^[6]) shl 48) or (TpvUInt64(v^[7]) shl 56);
end;
{$endif}
for r:=0 to KECCAKF_ROUNDS-1 do begin
for i:=0 to 4 do begin
bc[i]:=aState[i] xor aState[i+5] xor aState[i+10] xor aState[i+15] xor aState[i+20];
end;
for i:=0 to 4 do begin
t:=bc[(i + 4) mod 5] xor ROLQWord(bc[(i+1) mod 5],1);
j:=0;
while j<25 do begin
aState[i+j]:=aState[i+j] xor t;
inc(j,5);
end;
end;
t:=aState[1];
for i:=0 to 23 do begin
j:=keccakf_piln[i];
bc[0]:=aState[j];
aState[j]:=ROLQWord(t,keccakf_rotc[i]);
t:=bc[0];
end;
j:=0;
while j<25 do begin
for i:=0 to 4 do begin
bc[i]:=aState[i+j];
end;
for i:=0 to 4 do begin
aState[i+j]:=aState[i+j] xor ((not bc[(i+1) mod 5]) and bc[(i+2) mod 5]);
end;
inc(j,5);
end;
aState[0]:=aState[0] xor keccakf_rndc[r];
end;
{$ifdef BigEndian}
for i:=0 to 24 do begin
v:=pointer(@aState[i]);
t:=aState[i];
v^[0]:=(t shr 0) and $ff;
v^[1]:=(t shr 8) and $ff;
v^[2]:=(t shr 16) and $ff;
v^[3]:=(t shr 24) and $ff;
v^[4]:=(t shr 32) and $ff;
v^[5]:=(t shr 40) and $ff;
v^[6]:=(t shr 48) and $ff;
v^[7]:=(t shr 56) and $ff;
end;
{$endif}
end;
constructor TpvHashSHA3.Create(const aMessageDigestSize:TpvSizeInt);
begin
inherited Create;
FillChar(fState,SizeOf(TState),#0);
fMessageDigestSize:=aMessageDigestSize;
fBlockSize:=200-(fMessageDigestSize shl 1);
fStatePosition:=0;
end;
destructor TpvHashSHA3.Destroy;
begin
inherited Destroy;
end;
procedure TpvHashSHA3.Update(const aData:pointer;const aDataLength:TpvSizeInt);
var DataPosition,WorkStatePosition:TpvSizeInt;
Current:PpvUInt8;
begin
WorkStatePosition:=fStatePosition;
for DataPosition:=0 to aDataLength-1 do begin
Current:=@PpvUInt8Array(@fState)^[WorkStatePosition];
Current^:=Current^ xor PpvUInt8Array(aData)^[DataPosition];
inc(WorkStatePosition);
if WorkStatePosition>=fBlockSize then begin
ProcessState(fState);
WorkStatePosition:=0;
end;
end;
fStatePosition:=WorkStatePosition;
end;
procedure TpvHashSHA3.Final(const aMessageDigest:pointer);
begin
PpvUInt8Array(@fState)^[fStatePosition]:=PpvUInt8Array(@fState)^[fStatePosition] xor $06;
PpvUInt8Array(@fState)^[fBlockSize-1]:=PpvUInt8Array(@fState)^[fBlockSize-1] xor $80;
ProcessState(fState);
Move(fState,aMessageDigest^,fMessageDigestSize);
end;
{ TpvHashShake }
procedure TpvHashShake.XOF;
begin
PpvUInt8Array(@fState)^[fStatePosition]:=PpvUInt8Array(@fState)^[fStatePosition] xor $1f;
PpvUInt8Array(@fState)^[fBlockSize-1]:=PpvUInt8Array(@fState)^[fBlockSize-1] xor $80;
ProcessState(fState);
fStatePosition:=0;
end;
procedure TpvHashShake.Out(const aOutput:pointer;const aOutputLength:TpvSizeInt);
var OutputPosition,WorkStatePosition:TpvSizeInt;
begin
WorkStatePosition:=fStatePosition;
for OutputPosition:=0 to aOutputLength-1 do begin
if WorkStatePosition>=fBlockSize then begin
ProcessState(fState);
WorkStatePosition:=0;
end;
PpvUInt8Array(aOutput)^[OutputPosition]:=PpvUInt8Array(@fState)^[WorkStatePosition];
inc(WorkStatePosition);
end;
fStatePosition:=WorkStatePosition;
end;
{ TpvHashShake128 }
constructor TpvHashShake128.Create;
begin
inherited Create(16);
end;
{ TpvHashShake256 }
constructor TpvHashShake256.Create;
begin
inherited Create(32);
end;
end.
|
unit uTestTriangle;
interface
uses
DUnitX.TestFramework;
type
[TestFixture('Equilateral')]
EquilateralTests = class(TObject)
public
[Test]
// [Ignore('Comment the "[Ignore]" statement to run the test')]
procedure True_if_all_sides_are_equal;
[Test]
[Ignore]
procedure False_if_any_side_is_unequal;
[Test]
[Ignore]
procedure False_if_no_sides_are_equal;
[Test]
[Ignore]
procedure All_zero_sides_are_illegal_so_the_triangle_is_not_equilateral;
[Test]
[Ignore]
procedure Sides_may_be_floats;
end;
[TestFixture('Isosceles')]
IsoscelesTests = class(TObject)
public
[Test]
[Ignore]
procedure True_if_last_two_sides_are_equal;
[Test]
[Ignore]
procedure True_if_first_two_sides_are_equal;
[Test]
[Ignore]
procedure True_if_first_and_last_sides_are_equal;
[Test]
[Ignore]
procedure Equilateral_triangles_are_also_isosceles;
[Test]
[Ignore]
procedure False_if_no_sides_are_equal;
[Test]
[Ignore]
procedure Sides_that_violate_triangle_inequality_are_not_isosceles_even_if_two_are_equal;
[Test]
[Ignore]
procedure Sides_may_be_floats;
end;
[TestFixture('Scalene')]
ScaleneTests = class(TObject)
public
[Test]
[Ignore]
procedure True_if_no_sides_are_equal;
[Test]
[Ignore]
procedure False_if_all_sides_are_equal;
[Test]
[Ignore]
procedure False_if_two_sides_are_equal;
[Test]
[Ignore]
procedure Sides_that_violate_triangle_inequality_are_not_scalene_even_if_they_are_all_different;
[Test]
[Ignore]
procedure Sides_may_be_floats;
end;
implementation
uses uTriangle;
{$region 'EquilateralTests'}
procedure EquilateralTests.True_if_all_sides_are_equal;
begin
Assert.AreEqual(true, Triangle.Sides(Equilateral, 2, 2, 2));
end;
procedure EquilateralTests.False_if_any_side_is_unequal;
begin
Assert.AreEqual(false, Triangle.Sides(Equilateral, 2, 3, 2));
end;
procedure EquilateralTests.False_if_no_sides_are_equal;
begin
Assert.AreEqual(false, Triangle.Sides(Equilateral, 5, 4, 6));
end;
procedure EquilateralTests.All_zero_sides_are_illegal_so_the_triangle_is_not_equilateral;
begin
Assert.AreEqual(false, Triangle.Sides(Equilateral, 0, 0, 0));
end;
procedure EquilateralTests.Sides_may_be_floats;
begin
Assert.AreEqual(true, Triangle.Sides(Equilateral, 0.5, 0.5, 0.5));
end;
{$endregion}
{$region'IsoscelesTests'}
procedure IsoscelesTests.True_if_last_two_sides_are_equal;
begin
Assert.AreEqual(true, Triangle.Sides(Isosceles, 3, 4, 4));
end;
procedure IsoscelesTests.True_if_first_two_sides_are_equal;
begin
Assert.AreEqual(true, Triangle.Sides(Isosceles, 4, 4, 3));
end;
procedure IsoscelesTests.True_if_first_and_last_sides_are_equal;
begin
Assert.AreEqual(true, Triangle.Sides(Isosceles, 4, 3, 4));
end;
procedure IsoscelesTests.Equilateral_triangles_are_also_isosceles;
begin
Assert.AreEqual(true, Triangle.Sides(Isosceles, 4, 4, 4));
end;
procedure IsoscelesTests.False_if_no_sides_are_equal;
begin
Assert.AreEqual(false, Triangle.Sides(Isosceles, 2, 3, 4));
end;
procedure IsoscelesTests.Sides_that_violate_triangle_inequality_are_not_isosceles_even_if_two_are_equal;
begin
Assert.AreEqual(false, Triangle.Sides(Isosceles, 1, 1, 3));
end;
procedure IsoscelesTests.Sides_may_be_floats;
begin
Assert.AreEqual(true, Triangle.Sides(Isosceles, 0.5, 0.4, 0.5));
end;
{$endregion}
{$region 'ScaleneTests'}
procedure ScaleneTests.True_if_no_sides_are_equal;
begin
Assert.AreEqual(true, Triangle.Sides(Scalene, 5, 4, 6));
end;
procedure ScaleneTests.False_if_all_sides_are_equal;
begin
Assert.AreEqual(false, Triangle.Sides(Scalene, 4, 4, 4));
end;
procedure ScaleneTests.False_if_two_sides_are_equal;
begin
Assert.AreEqual(false, Triangle.Sides(Scalene, 4, 4, 3));
end;
procedure ScaleneTests.Sides_that_violate_triangle_inequality_are_not_scalene_even_if_they_are_all_different;
begin
Assert.AreEqual(false, Triangle.Sides(Scalene, 7, 3, 2));
end;
procedure ScaleneTests.Sides_may_be_floats;
begin
Assert.AreEqual(true, Triangle.Sides(Scalene, 0.5, 0.4, 0.6));
end;
{$endregion}
initialization
TDUnitX.RegisterTestFixture(EquilateralTests);
TDUnitX.RegisterTestFixture(IsoscelesTests);
TDUnitX.RegisterTestFixture(ScaleneTests);
end. |
unit Data.Repositories.CustomersRepository;
interface
uses
Data.Repositories.Repository
, Data.Repositories.ICustomersRepository
, Data.Entities.Customer
;
type
TCustomersRepository = class sealed (TRepository<TCustomer, Integer>, ICustomersRepository)
end;
implementation
uses
Spring.Container;
initialization
GlobalContainer.RegisterType<TCustomersRepository>.Implements<ICustomersRepository>;
end.
|
// Copyright 2018 by John Kouraklis and Contributors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
unit Casbin.Parser.Types;
interface
uses
Casbin.Core.Base.Types, Casbin.Parser.AST.Types, Casbin.Core.Logger.Types;
type
TParseType = (ptModel, ptPolicy, ptConfig);
TParserStatus = (psIdle, psRunning, psError);
IParser = interface (IBaseInterface)
['{6BC39E48-976B-43F3-BB42-18796CE21985}']
function getErrorMessage: string;
function getLogger: ILogger;
function getNodes: TNodeCollection;
function getParseType: TParseType;
function getStatus: TParserStatus;
procedure setLogger(const aValue: ILogger);
procedure parse;
property ErrorMessage: string read getErrorMessage;
property Logger: ILogger read getLogger write setLogger;
property Nodes: TNodeCollection read getNodes;
property ParseType: TParseType read getParseType;
property Status: TParserStatus read getStatus;
end;
implementation
end.
|
(*
* Copyright (c) 2008-2011, Ciobanu Alexandru
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the <organization> nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*)
unit Tests.Internal.Basics;
interface
uses
SysUtils,
TestFramework,
Generics.Defaults,
Collections.Base;
type
TClassOfException = class of Exception;
{ Our test case }
TTestCaseEx = class(TTestCase)
protected
procedure CheckException(const AExType: TClassOfException; const AProc: TProc; const Msg : String);
end;
type
TTestBase = class(TTestCaseEx)
published
procedure TestRefCountedObjectLife();
procedure TestRefCountedObjectExtractReference();
procedure TestRefCountedObjectKeepObjectAlive();
procedure TestRefCountedObjectReleaseObject();
procedure TestRefCountedObjectExceptions();
end;
ICheck = interface
procedure CheckNotConstructing();
procedure CheckRefCountEquals(const Cnt: Integer);
end;
TTestRefCountedObject = class(TRefCountedObject, ICheck)
private
FTest: TTestBase;
public
constructor Create(const Test: TTestBase);
procedure CheckNotConstructing();
procedure CheckRefCountEquals(const Cnt: Integer);
destructor Destroy(); override;
end;
TTestRules = class(TTestCaseEx)
published
procedure Test_Create;
procedure Test_Custom;
procedure Test_Default;
end;
type
TInsensitiveStringComparer = class(TStringComparer)
public
function Compare(const Left, Right: string): Integer; override;
function Equals(const Left, Right: string): Boolean;
reintroduce; overload; override;
function GetHashCode(const Value: string): Integer;
reintroduce; overload; override;
end;
var
StringCaseInsensitiveComparer: TInsensitiveStringComparer;
implementation
{ TTestCaseEx }
procedure TTestCaseEx.CheckException(const AExType: TClassOfException; const AProc: TProc; const Msg: String);
var
bWasEx : Boolean;
begin
bWasEx := False;
try
{ Cannot self-link }
AProc();
except
on E : Exception do
begin
if E is AExType then
bWasEx := True;
end;
end;
Check(bWasEx, Msg);
end;
var
TestDestroy: Integer;
{ TTestBase }
procedure TTestBase.TestRefCountedObjectKeepObjectAlive;
var
Obj, Obj1, Obj2: TTestRefCountedObject;
I1, I2: ICheck;
begin
{ ------------ No Interfaces, No destroy ----------- }
TestDestroy := 0;
Obj := TTestRefCountedObject.Create(Self);
Obj1 := TTestRefCountedObject.Create(Self);
Obj2 := TTestRefCountedObject.Create(Self);
{ Register for keep-alive }
Obj.KeepObjectAlive(Obj1);
Obj.KeepObjectAlive(Obj2);
Obj.Free;
Check(TestDestroy = 1, 'Only Obj expected to be gone!');
{ ------------ Interfaces, No chain -------------}
TestDestroy := 0;
Obj := TTestRefCountedObject.Create(Self);
I1 := Obj1;
I2 := Obj2;
{ Should not allow Obj1 and 2 to be killed! }
Obj.KeepObjectAlive(Obj1);
Obj.KeepObjectAlive(Obj2);
I1 := nil;
I2 := nil;
Check(TestDestroy = 0, 'Expected no deaths while keeping alive!');
Obj.Free;
Check(TestDestroy = 3, 'Expected all objects to be killed!');
{ ------------ Interfaces, Chain -------------}
TestDestroy := 0;
Obj := TTestRefCountedObject.Create(Self);
Obj1 := TTestRefCountedObject.Create(Self);
Obj2 := TTestRefCountedObject.Create(Self);
I1 := Obj1;
I2 := Obj2;
{ Should not allow Obj1 and 2 to be killed! }
Obj.KeepObjectAlive(Obj1);
Obj1.KeepObjectAlive(Obj2);
I1 := nil;
I2 := nil;
Check(TestDestroy = 0, 'Expected no deaths while keeping alive!');
Obj.Free;
Check(TestDestroy = 3, 'Expected all objects to be killed!');
{ ------------ Test nil's ------------ }
TestDestroy := 0;
Obj := TTestRefCountedObject.Create(Self);
Obj.KeepObjectAlive(nil);
Obj.KeepObjectAlive(nil);
Obj.KeepObjectAlive(nil);
Obj.Free;
Check(TestDestroy = 1, 'Expected Obj to die properly!');
end;
procedure TTestBase.TestRefCountedObjectLife;
var
Obj: TTestRefCountedObject;
I, I1: ICheck;
begin
{ First types of checks }
Obj := TTestRefCountedObject.Create(Self);
Obj.CheckNotConstructing();
Obj.CheckRefCountEquals(0);
Obj.Free;
{ Interface checks }
I := TTestRefCountedObject.Create(Self);
I.CheckNotConstructing();
I.CheckRefCountEquals(1);
I1 := I;
I.CheckRefCountEquals(2);
I1 := nil;
I.CheckRefCountEquals(1);
I := nil;
end;
procedure TTestBase.TestRefCountedObjectReleaseObject;
var
Obj, Obj1, Obj2: TTestRefCountedObject;
I1, I2: ICheck;
begin
{ ------------ No Interfaces, No destroy ----------- }
TestDestroy := 0;
Obj := TTestRefCountedObject.Create(Self);
Obj1 := TTestRefCountedObject.Create(Self);
Obj2 := TTestRefCountedObject.Create(Self);
{ Register for keep-alive }
Obj.KeepObjectAlive(Obj1);
Obj.KeepObjectAlive(Obj2);
Obj.ReleaseObject(Obj1);
Obj.ReleaseObject(Obj2);
Obj.Free;
Check(TestDestroy = 1, 'Only Obj expected to be gone!');
{ ------------ No Interfaces, Destroy ----------- }
TestDestroy := 0;
Obj := TTestRefCountedObject.Create(Self);
{ Register for keep-alive }
Obj.KeepObjectAlive(Obj1);
Obj.KeepObjectAlive(Obj2);
Obj.ReleaseObject(Obj1, true);
Obj.ReleaseObject(Obj2, true);
Obj.Free;
Check(TestDestroy = 3, 'Only Obj, Obj1, Obj2 expected to be gone!');
{ ------------ Interfaces, Destroy ----------- }
TestDestroy := 0;
Obj := TTestRefCountedObject.Create(Self);
Obj1 := TTestRefCountedObject.Create(Self);
Obj2 := TTestRefCountedObject.Create(Self);
I1 := Obj1;
I2 := Obj2;
{ Register for keep-alive }
Obj.KeepObjectAlive(Obj1);
Obj.KeepObjectAlive(Obj2);
I1 := nil;
I2 := nil;
Obj.ReleaseObject(Obj1);
Obj.ReleaseObject(Obj2);
Check(TestDestroy = 2, 'Only Obj1, Obj2 expected to be gone!');
Obj.Free;
Check(TestDestroy = 3, 'All Obj, Obj1, Obj2 expected to be gone!');
{ ------------ Lots of Interfaces, Destroy ----------- }
TestDestroy := 0;
Obj := TTestRefCountedObject.Create(Self);
Obj1 := TTestRefCountedObject.Create(Self);
Obj2 := TTestRefCountedObject.Create(Self);
I1 := Obj1;
I2 := Obj2;
{ Register for keep-alive }
Obj.KeepObjectAlive(Obj1);
Obj.KeepObjectAlive(Obj2);
Obj.KeepObjectAlive(Obj1);
Obj.KeepObjectAlive(Obj2);
Obj.KeepObjectAlive(Obj1);
Obj.KeepObjectAlive(Obj2);
I1 := nil;
I2 := nil;
Obj.ReleaseObject(Obj1);
Obj.ReleaseObject(Obj2);
Check(TestDestroy = 0, 'Nothing should be gone!');
Obj.ReleaseObject(Obj1);
Obj.ReleaseObject(Obj2);
Check(TestDestroy = 0, 'Nothing should be gone!');
Obj.Free;
Check(TestDestroy = 3, 'All Obj, Obj1, Obj2 expected to be gone!');
end;
procedure TTestBase.TestRefCountedObjectExceptions;
var
Obj: TTestRefCountedObject;
begin
Obj := TTestRefCountedObject.Create(self);
CheckException(ECannotSelfReferenceException,
procedure() begin
Obj.KeepObjectAlive(Obj);
end,
'ECannotSelfReferenceException not thrown in KeepObjectAlive()'
);
CheckException(ECannotSelfReferenceException,
procedure() begin
Obj.ReleaseObject(Obj);
end,
'ECannotSelfReferenceException not thrown in ReleaseObject()'
);
Obj.Free;
end;
procedure TTestBase.TestRefCountedObjectExtractReference;
var
Obj: TTestRefCountedObject;
I: ICheck;
begin
Obj := TTestRefCountedObject.Create(Self);
Check(Obj.ExtractReference = nil, 'Expected nil!');
I := Obj;
Check(Obj.ExtractReference <> nil, 'Expected not nil!');
I := nil;
end;
{ TTestRefCountedObject }
procedure TTestRefCountedObject.CheckNotConstructing;
begin
FTest.Check(not Constructing, 'Should not be checked as Constructing!');
end;
procedure TTestRefCountedObject.CheckRefCountEquals(const Cnt: Integer);
begin
FTest.Check(RefCount = Cnt, 'RefCount is not what it was expected to be!');
end;
constructor TTestRefCountedObject.Create(const Test: TTestBase);
begin
Test.Check(Constructing, 'Should be checked as Constructing!');
Test.Check(RefCount = 1, 'Ref count should be 1');
Test.Check(ExtractReference = nil, 'No reference should be expected in ctor!');
FTest := Test;
end;
destructor TTestRefCountedObject.Destroy;
begin
FTest.Check(not Constructing, 'Should not be checked as Constructing!');
Inc(TestDestroy);
inherited;
end;
{ TTestRules }
procedure TTestRules.Test_Create;
var
LStrRules: TRules<string>;
begin
CheckException(EArgumentNilException,
procedure()
begin
TRules<string>.Create(nil, TEqualityComparer<string>.Default)
end,
'EArgumentNilException not thrown in TRules<string>.Create (nil, xxx).'
);
CheckException(EArgumentNilException,
procedure()
begin
TRules<string>.Create(TComparer<string>.Default, nil)
end,
'EArgumentNilException not thrown in TRules<string>.Create (xxx, nil).'
);
LStrRules := TRules<string>.Create(TComparer<string>.Default, StringCaseInsensitiveComparer);
LStrRules := TRules<string>.Create(StringCaseInsensitiveComparer, TEqualityComparer<string>.Default);
end;
procedure TTestRules.Test_Custom;
var
LStrRules: TRules<string>;
begin
CheckException(EArgumentNilException,
procedure()
begin
TRules<string>.Custom(nil)
end,
'EArgumentNilException not thrown in TRules<string>.Custom (nil).'
);
LStrRules := TRules<string>.Custom(StringCaseInsensitiveComparer);
end;
procedure TTestRules.Test_Default;
var
LStrRules: TRules<string>;
begin
LStrRules := TRules<string>.Default;
end;
{ TInsensitiveStringComparer }
function TInsensitiveStringComparer.Compare(const Left, Right: string): Integer;
begin
Result := CompareText(Left, Right);
end;
function TInsensitiveStringComparer.Equals(const Left, Right: string): Boolean;
begin
Result := SameText(Left, Right);
end;
function TInsensitiveStringComparer.GetHashCode(const Value: string): Integer;
var
Upped: string;
begin
Upped := AnsiUpperCase(Value);
Result := BobJenkinsHash(PChar(Upped)^, SizeOf(Char) * Length(Upped), 0);
end;
initialization
StringCaseInsensitiveComparer := TInsensitiveStringComparer.Create;
RegisterTests('Internal.Support', [
TTestBase.Suite,
TTestRules.Suite
]);
finalization
StringCaseInsensitiveComparer.Free;
end.
|
unit EditAncestor;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, ExtCtrls, AdoDB, StdCtrls, Contnrs, Buttons, Data.DB;
type
TfrmEditAncestor = class(TForm)
Panel3: TPanel;
PageControl1: TPageControl;
tbsGenel: TTabSheet;
Panel2: TPanel;
Panel1: TPanel;
btnCancel: TBitBtn;
btnSave: TBitBtn;
btnReset: TBitBtn;
LblAangemaakDoor: TLabel;
lblAangemaaktOp: TLabel;
procedure btnSaveClick(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
procedure FormKeyPress(Sender: TObject; var Key: Char);
procedure btnResetClick(Sender: TObject);
private
{ Private declarations }
protected
ID: Integer;
TTable: TADOTable;
MasterKey: String;
TableObjectList: TObjectList;
procedure loadDetailsTables; virtual;
procedure loadValues; virtual;
procedure saveValues; virtual;
procedure cancelValues; virtual;
procedure Eenmaal; virtual;
procedure fillCmb(cmb:TComboBox; cmbTable:TADOTable; FieldName, def:String);
public
procedure loadDetails; virtual;
constructor Create(Owner: TComponent; ID: Integer; AdoTable: TADOTable); overload;
constructor Create(Owner: TComponent; ID: Integer; AdoTable: TADOTable; Key: String); overload;
end;
var
frmEditAncestor: TfrmEditAncestor;
implementation
uses Main, DateUtils;
{$R *.dfm}
{ TfrmEditAncestor }
constructor TfrmEditAncestor.Create(Owner: TComponent; ID: Integer; AdoTable: TADOTable);
begin
inherited Create(Owner);
TableObjectList := TObjectList.Create;
TTable := AdoTable;
Eenmaal;
Self.Id := Id;
if Id = 0 then begin
TTable.Insert;
loadValues;
end
else if Id = -1 then begin
end
else begin
loadValues;
loadDetailsTables;
loadDetails;
TTable.Edit;
end;
btnReset.Visible := not(Id = 0);
end;
constructor TfrmEditAncestor.Create(Owner: TComponent; ID: Integer;
AdoTable: TADOTable; Key: String);
begin
inherited Create(Owner);
TableObjectList := TObjectList.Create;
TTable := AdoTable;
Eenmaal;
Self.Id := Id;
MasterKey := Key;
if Id = 0 then begin
TTable.Insert;
loadValues;
end
else begin
loadValues;
loadDetailsTables;
loadDetails;
TTable.Edit;
end;
btnReset.Visible := not(Id = 0);
end;
procedure TfrmEditAncestor.loadValues;
begin
LblAangemaakDoor.Caption := 'Aangemaakt door: ' + TTable.FieldByName('AangemaaktDoor').AsString ;
lblAangemaaktOp.Caption := 'Aangemaakt op: ' + TTable.FieldByName('AangemaaktOp').AsString;
end;
procedure TfrmEditAncestor.saveValues;
var I: Integer;
begin
for I := 0 to TableObjectList.Count -1 do begin
TADOTable(TableObjectList.Items[I]).UpdateBatch;
end;
TTable.UpdateBatch;
end;
procedure TfrmEditAncestor.btnSaveClick(Sender: TObject);
begin
if TTable.FieldByName('AangemaaktDoor').AsString = '' then begin
TTable.FieldByName('AangemaaktDoor').AsString := TfrmMain(Owner).user;
TTable.FieldByName('AangemaaktOp').AsDateTime := Date;
end;
saveValues;
end;
procedure TfrmEditAncestor.btnCancelClick(Sender: TObject);
begin
cancelValues;
end;
procedure TfrmEditAncestor.cancelValues;
var I: Integer;
begin
for I := 0 to TableObjectList.Count -1 do begin
try
TADOTable(TableObjectList.Items[I]).CancelBatch;
except
on E: Exception do
//
end;
end;
TTable.Cancel;
end;
procedure TfrmEditAncestor.loadDetails;
var I: Integer;
begin
for I := 0 to TableObjectList.Count -1 do begin
TADOTable(TableObjectList.Items[I]).Filtered := False;
TADOTable(TableObjectList.Items[I]).Filter := Masterkey+ '= '+ IntToStr(Id);
TADOTable(TableObjectList.Items[I]).Filtered := True;
end;
// verder vullen bij kind
// frameDagen.lvwItems.Clear;
end;
procedure TfrmEditAncestor.loadDetailsTables;
begin
//vullen bij kind
// TDagen := TfrmMain.GetTableDagen;
// TableObjectList.Add(TDagen);
// frameDagen.FTable := TDagen;
end;
procedure TfrmEditAncestor.FormKeyPress(Sender: TObject; var Key: Char);
begin
if key = #27 then begin
TTable.Cancel;
Close
end;
end;
procedure TfrmEditAncestor.btnResetClick(Sender: TObject);
begin
TTable.Cancel;
loadValues;
loadDetailsTables;
loadDetails;
TTable.edit;
end;
procedure TfrmEditAncestor.Eenmaal;
begin
//
end;
procedure TfrmEditAncestor.fillCmb(cmb: TComboBox; cmbTable:TADOTable; FieldName, def:String);
var I: Integer;
begin
for I := 0 to cmbTable.RecordCount -1 do begin
cmb.AddItem(cmbTable.FieldByName(FieldName).AsString, Pointer(cmbTable.FieldByName('Id').AsInteger));
if(cmbTable.FieldByName(FieldName).AsString = def) then begin
cmb.ItemIndex := I;
end;
end;
end;
end.
|
//
// Name: ThreadedPanel.pas
// Desc: ThreadedPanel Component
// A base class which can derived off. A panel with an associated thread
// attached. If the Thread is enabled, the Timer function is called, at a
// given interval. This componenet replaces any need for use of the TTimer
// component.
//
// Author: David Verespey
//
// Revision History:
//
// 09/01/96 Start Program
//
//
unit ThreadedPanel;
interface
uses
Windows, Messages, SysUtils, Classes,
Graphics, Controls, Forms, Dialogs, EmptyPanel;
type
TThreadedPanel = class;
TTimerThread = class(TThread)
OwnerTimer: TThreadedPanel;
procedure Execute; override;
procedure DoTimer;
end;
TThreadedPanel = class(TEmptyPanel)
private
protected
// Keep everything protected so that any derived object can also see these
FEnabled: Boolean;
FInterval: Word;
FTimerThread: TTimerThread;
FThreadPriority: TThreadPriority;
procedure UpdateTimer; virtual;
procedure SetEnabled(Value: Boolean); override;
procedure SetInterval(Value: Word);
procedure SetThreadPriority(Value: TThreadPriority);
procedure Timer; dynamic; // This is the function to override to get the panel to do somthing
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property Enabled: Boolean
read FEnabled
write SetEnabled;
property Interval: Word
read FInterval
write SetInterval;
property ThreadPriority: TThreadPriority
read FThreadPriority
write SetThreadPriority;
end;
implementation
// Actual thread
procedure TTimerThread.Execute;
begin
Priority := OwnerTimer.FThreadPriority;
FreeOnTerminate:=True;
repeat
if not terminated then
Sleep(OwnerTimer.FInterval);
if not terminated then
Synchronize(DoTimer);
until Terminated;
end;
// call back to panel
procedure TTimerThread.DoTimer;
begin
OwnerTimer.Timer;
end;
// Create the thread here
constructor TThreadedPanel.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FEnabled := True;
FInterval := 1000;
FThreadPriority := tpNormal;
FTimerThread := TTimerThread.Create(True);
FTimerThread.FreeOnTerminate:=True;
FTimerThread.OwnerTimer := Self;
end;
// Clean up and delete the thread
destructor TThreadedPanel.Destroy;
begin
fTimerThread.Terminate;
inherited Destroy;
end;
// Start of stop the thread
procedure TThreadedPanel.UpdateTimer;
begin
if (FInterval <> 0) and FEnabled {and Assigned(FOnTimer)} then
begin
FTimerThread.Resume;
end
else
begin
FTimerThread.Suspend;
end;
end;
// Set enabled or not
procedure TThreadedPanel.SetEnabled(Value: Boolean);
begin
FEnabled := Value;
UpdateTimer;
end;
// How often the thread should execute
procedure TThreadedPanel.SetInterval(Value: Word);
begin
if Value <> FInterval then
begin
FInterval := Value;
UpdateTimer;
end;
end;
// threads priority
procedure TThreadedPanel.SetThreadPriority(Value: TThreadPriority);
begin
if Value <> FThreadPriority then
begin
FThreadPriority := Value;
UpdateTimer;
end;
end;
// The function to override this bas class does nothing
procedure TThreadedPanel.Timer;
begin
end;
end.
|
// Ведение протокола
//
unit log_unit;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls;
type
TLog = class(TForm)
log_memo: TMemo;
Button1: TButton;
Button2: TButton;
logBegin: TCheckBox;
logTrans: TCheckBox;
logEnd: TCheckBox;
logInput: TCheckBox;
logAction: TCheckBox;
logt0: TCheckBox;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
procedure add_log( str : String );
//
// Начало работы автомата
//
procedure add_begin( aut, state, event : integer );
//
// Переход между состояниями
//
procedure add_trans( aut, old_state, new_state : integer );
//
// Окончание работы автомата
//
procedure add_end( aut, state, event : integer );
//
// Опрос входной переменной
//
procedure add_input( num : integer; str : string; ret : boolean);
//
// Выполнение действия
//
procedure add_action( num : integer; str : string );
//
// Сообщение об ошибке
//
procedure add_error( aut : integer; err : string );
//
// Вывод строки в протокол
//
procedure add( str : String );
end;
var
Log: TLog;
implementation
{$R *.DFM}
procedure TLog.Button1Click(Sender: TObject);
begin
Hide;
end;
procedure TLog.add( str : String );
begin
log_memo.Lines.Add(TimeToStr(Time) + ' ' + str);
end;
procedure TLog.add_log( str : String );
begin
add( '# ' + str );
end;
procedure TLog.add_begin( aut, state, event : integer );
begin
if ( event = 0 ) and ( not logt0.Checked ) then exit;
if logBegin.Checked then
add( '{ A' + IntToStr( aut ) + ': в состоянии ' + IntToStr( state ) +
' запущен с событием e' + IntToStr( event ) );
end;
procedure TLog.add_trans( aut, old_state, new_state : integer );
begin
if logTrans.Checked then
add( 'T A' + IntToStr( aut ) + ': перешел из состояния ' +
IntToStr( old_state ) + ' в состояние ' + IntToStr(new_state) );
end;
procedure TLog.add_end( aut, state, event : integer );
begin
if ( event = 0 ) and ( not logt0.Checked ) then exit;
if logEnd.Checked then
add( '} A' + IntToStr( aut ) + ': завершил обработку события e' +
IntToStr( event ) + ' в состоянии ' + IntToStr( state ));
end;
procedure TLog.add_input( num : integer; str : string; ret : boolean);
var s : String;
begin
if ret then s := 'true' else s := 'false';
if logInput.Checked then
add( '> x' + IntToStr( num ) + ' - ' + str + ' - вернул ' + s );
end;
procedure TLog.add_action( num : integer; str : string );
begin
if logAction.Checked then
add( '* z' + IntToStr( num ) + ' - ' + str );
end;
procedure TLog.add_error( aut : integer; err : string );
begin
add( '! A' + IntToStr( aut ) + ': ОШИБКА: ' + err );
end;
procedure TLog.Button2Click(Sender: TObject);
begin
log_memo.Clear;
end;
end.
|
unit UItemID;
interface
type
TItemID = class
private
id:integer;
public
function get():integer;
constructor Create(id: integer);
end;
implementation
{ ItemID }
constructor TItemID.Create(id: integer);
begin
self.id:=id;
end;
function TItemID.get: integer;
begin
result:=id;
end;
end.
|
unit ScriptCompileMain;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, SmartFields;
type
TForm1 = class(TForm)
Button1: TButton;
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
FMySmart: TSmartEngine;
procedure SetMySmart(const Value: TSmartEngine);
{ Private declarations }
property MySmart: TSmartEngine read FMySmart write SetMySmart;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
begin
FMySmart.SaveAndCompile('exam.pp','exam.bin');
ShowMessage('Done');
end;
procedure TForm1.SetMySmart(const Value: TSmartEngine);
begin
FMySmart := Value;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
FMySmart := TSmartEngine.Create(Self);
end;
end.
|
{******************************************************************************}
{ }
{ EasyIp communication Library }
{ User end client unit }
{ }
{ Copyright 2017-2018 Artem Rudenko }
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{******************************************************************************}
unit eiClient;
interface
uses
eiTypes,
eiConstants,
eiExceptions,
eiProtocol,
eiHelpers,
eiChannel,
Classes,
SysUtils,
Windows,
DsgnIntf;
type
TEasyIpClient = class(TCustomClient, IEasyIpClient)
private
FChannel: IEasyIpChannel;
FOnException: TExceptionEvent;
FProtocol: IEasyIpProtocol;
function DispatchException(E: Exception): bool;
function GetChannel: IEasyIpChannel;
function GetHost: string;
function GetPort: int;
function GetProtocol: IEasyIpProtocol;
function GetTimeout: int;
procedure InitInterfaces(const _host: string);
procedure SetDebug(const value: string);
procedure SetHost(const value: string);
procedure SetPort(const value: int);
procedure SetTimeout(const value: int);
property Channel: IEasyIpChannel read GetChannel;
property Debug: string write SetDebug;
property Protocol: IEasyIpProtocol read GetProtocol;
public
constructor Create(const _host: string); reintroduce; overload;
constructor Create(AOwner: TComponent); overload; override;
destructor Destroy; override;
procedure BitOperation(const offset: short; const dataType: DataTypeEnum; const mask: ushort; const bitMode: BitModeEnum);
function BlockRead(const offset: short; const dataType: DataTypeEnum; const length: byte): DynamicWordArray;
procedure BlockWrite(const offset: short; const value: DynamicWordArray; const dataType: DataTypeEnum);
function WordRead(const offset: short; const dataType: DataTypeEnum): short;
procedure WordWrite(const offset: short; const value: short; const dataType: DataTypeEnum);
function InfoRead: EasyIpInfoPacket;
published
property Host: string read GetHost write SetHost;
property Port: int read GetPort write SetPort default EASYIP_PORT;
property Timeout: int read GetTimeout write SetTimeout default CHANNEL_DEFAULT_TIMEOUT;
property OnException: TExceptionEvent read FOnException write FOnException;
end;
TEasyIpClientEditor = class(TComponentEditor)
function GetVerbCount: Integer; override;
function GetVerb(Index: Integer): string; override;
procedure ExecuteVerb(Index: Integer); override;
procedure Edit; override;
end;
procedure Register();
implementation
procedure Register();
begin
RegisterComponents('AESoft', [TEasyIpClient]);
RegisterComponentEditor(TEasyIpClient, TEasyIpClientEditor);
end;
constructor TEasyIpClient.Create(const _host: string);
begin
inherited Create(nil);
Debug := Format(DEBUG_MESSAGE_CREATE, [ClassName]);
InitInterfaces(_host);
end;
constructor TEasyIpClient.Create(AOwner: TComponent);
begin
inherited;
Debug := Format(DEBUG_MESSAGE_CREATE, [ClassName]);
InitInterfaces('');
end;
destructor TEasyIpClient.Destroy;
begin
inherited;
FChannel := nil;
FProtocol := nil;
Debug := Format(DEBUG_MESSAGE_DESTROY, [ClassName]);
end;
procedure TEasyIpClient.BitOperation(const offset: short; const dataType: DataTypeEnum; const mask: ushort; const bitMode: BitModeEnum);
var
sendedPacket: EasyIpPacket;
returnedPacket: EasyIpPacket;
arrayLength: int;
dataLength: int;
begin
dataLength := 1;
Protocol.Mode := pmBit;
Protocol.BitMode := bitMode;
Protocol.DataOffset := offset;
Protocol.DataType := dataType;
Protocol.DataLength := dataLength;
sendedPacket := Protocol.Packet;
arrayLength := dataLength * SHORT_SIZE;
CopyMemory(@sendedPacket.Data, @mask, arrayLength);
try
returnedPacket := Channel.Execute(sendedPacket);
except
on E: Exception do
if DispatchException(E) then
raise;
end;
end;
function TEasyIpClient.BlockRead(const offset: short; const dataType: DataTypeEnum; const length: byte): DynamicWordArray;
var
returnedPacket: EasyIpPacket;
returnArray: DynamicWordArray;
arrayLength: int;
begin
Protocol.Mode := pmRead;
Protocol.DataOffset := offset;
Protocol.DataType := dataType;
Protocol.DataLength := length;
try
returnedPacket := Channel.Execute(Protocol.Packet);
except
on E: Exception do
if DispatchException(E) then
raise;
end;
arrayLength := returnedPacket.RequestDataSize * SHORT_SIZE;
SetLength(returnArray, length);
CopyMemory(returnArray, @returnedPacket.Data, arrayLength);
Result := returnArray;
end;
procedure TEasyIpClient.BlockWrite(const offset: short; const value: DynamicWordArray; const dataType: DataTypeEnum);
var
sendedPacket: EasyIpPacket;
returnedPacket: EasyIpPacket;
arrayLength: int;
dataLength: int;
begin
dataLength := length(value);
Protocol.Mode := pmWrite;
Protocol.DataOffset := offset;
Protocol.DataType := dataType;
Protocol.DataLength := dataLength;
sendedPacket := Protocol.Packet;
arrayLength := dataLength * SHORT_SIZE;
CopyMemory(@sendedPacket.Data, value, arrayLength);
try
returnedPacket := Channel.Execute(sendedPacket);
except
on E: Exception do
if DispatchException(E) then
raise;
end;
end;
function TEasyIpClient.DispatchException(E: Exception): bool;
begin
Debug := E.Message;
if Assigned(FOnException) then
begin
FOnException(Self, E);
Result := False;
end
else
Result := True;
end;
function TEasyIpClient.GetChannel: IEasyIpChannel;
begin
Result := FChannel;
end;
function TEasyIpClient.GetHost: string;
begin
Result := Channel.Host;
end;
function TEasyIpClient.GetPort: int;
begin
Result := Channel.Port;
end;
function TEasyIpClient.GetProtocol: IEasyIpProtocol;
begin
Result := FProtocol;
end;
function TEasyIpClient.GetTimeout: int;
begin
Result := Channel.Timeout;
end;
function TEasyIpClient.InfoRead: EasyIpInfoPacket;
var
returnedPacket: EasyIpPacket;
returnPacket: EasyIpInfoPacket;
begin
Protocol.Mode := pmInfo;
try
returnedPacket := Channel.Execute(Protocol.Packet);
except
on E: Exception do
if DispatchException(E) then
raise;
end;
returnPacket := TPacketAdapter.ToEasyIpInfoPacket(returnedPacket);
Result := returnPacket;
end;
procedure TEasyIpClient.InitInterfaces(const _host: string);
begin
FChannel := TEasyIpChannel.Create(_host, EASYIP_PORT);
FProtocol := TEasyIpProtocol.Create();
end;
procedure TEasyIpClient.SetDebug(const value: string);
begin
OutputDebugString(PChar(value));
end;
procedure TEasyIpClient.SetHost(const value: string);
begin
Channel.Host := value;
end;
procedure TEasyIpClient.SetPort(const value: int);
begin
Channel.Port := value;
end;
procedure TEasyIpClient.SetTimeout(const value: int);
begin
Channel.Timeout := value;
end;
function TEasyIpClient.WordRead(const offset: short; const dataType: DataTypeEnum): short;
var
readed: DynamicWordArray;
begin
readed := BlockRead(offset, dataType, 1);
Result := readed[0];
end;
procedure TEasyIpClient.WordWrite(const offset, value: short; const dataType: DataTypeEnum);
var
writed: DynamicWordArray;
begin
SetLength(writed, 1);
writed[0] := value;
BlockWrite(offset, writed, dataType);
end;
procedure TEasyIpClientEditor.Edit;
begin
inherited;
end;
procedure TEasyIpClientEditor.ExecuteVerb(Index: Integer);
begin
inherited;
case Index of
0: ;
1: MessageBox(0,
'This is a client library for simple access to devices'#13 +
'wich support EasyIp protocol by network',
'About',
MB_OK or MB_ICONINFORMATION);
end;
end;
function TEasyIpClientEditor.GetVerb(Index: Integer): string;
begin
case Index of
0:
Result := 'EasyIp Client (© A.Rudenko)';
1:
Result := '&About this component...';
end;
end;
function TEasyIpClientEditor.GetVerbCount: Integer;
begin
Result := 2;
end;
end.
|
{
List old version plugins for Skyrim.
}
unit UserScript;
const
CheckVersion = 1.7;
function Initialize: integer;
var
i: integer;
plugin, tes4: IInterface;
s: string;
v: single;
begin
for i := 0 to FileCount - 1 do begin
plugin := FileByIndex(i);
s := GetFileName(plugin);
// skip old official files
if
(GetLoadOrder(Plugin) = 0) or
SameText(s, 'Skyrim.esm') or
SameText(s, 'Dawnguard.esm')
then
Continue;
tes4 := ElementByIndex(plugin, 0);
if GetElementNativeValues(tes4, 'HEDR\Version') < CheckVersion then
AddMessage(Format('Old version %s plugin %s', [GetElementEditValues(tes4, 'HEDR\Version'), s]));
end;
// nothing else to do, terminate
Result := 1;
end;
end. |
unit UEncryption;
interface
uses
StdCtrls, Classes, Vcl.Dialogs, Vcl.Controls, System.SysUtils;
type
TEncryption = class(TMemo)
protected
FKey: String;
FLog: TextFile;
FChanged: Boolean;
public
constructor Create(C: TComponent);
procedure Encrypt(); virtual; abstract;
procedure Decrypt(); virtual; abstract;
procedure SetKey(Value: String); virtual; abstract;
procedure OpenFile(var Open: TOpenDialog; var Save: TSaveDialog);
procedure SaveFile(var Save: TSaveDialog);
published
property Key: String read FKey write SetKey;
property Log: TextFile read FLog write FLog;
property Changed: Boolean read FChanged write FChanged;
end;
implementation
constructor TEncryption.Create(C: TComponent);
begin
inherited Create(C);
Top := 10;
Left := 5;
Width := 355;
Height := 170;
ScrollBars := ssVertical;
end;
procedure TEncryption.OpenFile(var Open: TOpenDialog; var Save: TSaveDialog);
var texto: String;
begin
if (Changed) then
if (MessageDlg('Discard changes?',
mtWarning, [mbYes, mbNo], 0)=mrNo) then begin
SaveFile(Save);
Exit;
end;
if (Open.Execute()) then begin
AssignFile(Log, Open.FileName);
Reset(Log);
Clear;
try
while not Eof(Log) do begin
Readln(Log, texto);
Lines.Add(texto);
end;
finally
CloseFile(Log);
end;
end;
end;
procedure TEncryption.SaveFile(var Save: TSaveDialog);
var line: Integer;
begin
if (Lines.Count=0) then
MessageDlg('The textbox is empty!', mtError, [mbOK], 0)
else
if (Save.Execute()) then begin
if (Save.FileName='') then Exit;
if FileExists(Save.FileName) then
if ((MessageDlg('File Exists! Overwrite?',
mtWarning, [mbYes, mbNo], 0)=mrNo)) then Exit;
AssignFile(Log, Save.FileName);
Rewrite(Log);
try
for line := 0 to Lines.Count -1 do
Writeln(Log, Lines[line]);
finally
CloseFile(Log);
Changed := False;
end;
end;
end;
end.
|
// Copyright 2018 by John Kouraklis and Contributors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
unit Casbin.Model.Sections.Default;
interface
uses
Casbin.Model.Sections.Types, System.Generics.Collections, System.Types;
type
TSectionDefault = record
Header: string; //PALOFF
Tag: TStringDynArray; //PALOFF
end;
const
defaultSection: TSectionDefault = (Header: 'default'; Tag: []);
requestDefinition: TSectionDefault = (Header: 'request_definition';
Tag: ['r']);
policyDefinition: TSectionDefault = (Header: 'policy_definition';
Tag: ['p']);
roleDefinition: TSectionDefault = (Header: 'role_definition';
Tag: ['g', 'g2']);
policyEffectDefinition: TSectionDefault = (Header: 'policy_effect';
Tag: ['e']);
matchersDefinition: TSectionDefault = (Header: 'matchers';
Tag: ['m']);
function createDefaultSection(const aSection: TSectionType): TSection;
implementation
uses
Casbin.Exception.Types;
function createDefaultSection(const aSection: TSectionType): TSection;
begin
case aSection of
stDefault: begin
result:=TSection.Create;
result.EnforceTag:=True;
result.Header:=defaultSection.Header;
result.Required:=True;
result.Tag:=defaultSection.Tag;
result.&Type:=stDefault;
end;
stRequestDefinition: begin
result:=TSection.Create;
result.EnforceTag:=True;
result.Header:=requestDefinition.Header;
result.Required:=True;
result.Tag:=requestDefinition.Tag;
result.&Type:=stRequestDefinition;
end;
stPolicyDefinition: begin
result:=TSection.Create;
result.EnforceTag:=True;
result.Header:=policyDefinition.Header;
result.Required:=True;
result.Tag:=policyDefinition.Tag;
result.&Type:=stPolicyDefinition;
end;
stPolicyEffect: begin
result:=TSection.Create;
result.EnforceTag:=True;
result.Header:=policyEffectDefinition.Header;
result.Required:=True;
result.Tag:=policyEffectDefinition.Tag;
result.&Type:=stPolicyEffect;
end;
stMatchers: begin
result:=TSection.Create;
result.EnforceTag:=True;
result.Header:=matchersDefinition.Header;
result.Required:=True;
result.Tag:=matchersDefinition.Tag;
result.&Type:=stMatchers;
end;
stRoleDefinition: begin
result:=TSection.Create;
result.EnforceTag:=True;
result.Header:=roleDefinition.Header;
result.Required:=False;
result.Tag:=roleDefinition.Tag;
result.&Type:=stRoleDefinition;
end;
else
raise ECasbinException.Create('Wrong secton type');
end;
end;
end.
|
unit uEdtRole;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uBaseForm, StdCtrls, Buttons, DBIntf;
type
TFrmEdtRole = class(TBaseForm)
Label1: TLabel;
Label2: TLabel;
edt_RoleName: TEdit;
edt_Description: TEdit;
btn_OK: TBitBtn;
btn_Cancel: TBitBtn;
procedure btn_OKClick(Sender: TObject);
private
FRec: IDataRecord;
public
constructor Create(AOwner: TComponent; Rec: IDataRecord); reintroduce;
property ResultData: IDataRecord read FRec;
end;
var
FrmEdtRole: TFrmEdtRole;
implementation
uses SysSvc, _sys;
{$R *.dfm}
procedure TFrmEdtRole.btn_OKClick(Sender: TObject);
begin
inherited;
if edt_RoleName.Text = '' then
begin
sys.Dialogs.Warning('角色名称不能为空!');
edt_RoleName.SetFocus;
exit;
end;
FRec.FieldValues['RoleName'] := self.edt_RoleName.Text;
FRec.FieldValues['Description'] := self.edt_Description.Text;
self.ModalResult := mrOK;
end;
constructor TFrmEdtRole.Create(AOwner: TComponent; Rec: IDataRecord);
begin
inherited Create(AOwner);
if Assigned(Rec) then
begin
FRec := Rec;
self.edt_RoleName.Text := FRec.FieldValueAsString('RoleName');
self.edt_Description.Text := FRec.FieldValueAsstring('Description');
end
else FRec := SysService as IDataRecord;
end;
end.
|
{$include kode.inc}
unit syn_s2_master_volume;
//----------------------------------------------------------------------
interface
//----------------------------------------------------------------------
uses
kode_const,
kode_control,
kode_debug,
kode_editor,
kode_plugin,
kode_voicemanager,
kode_widget,
syn_s2_const;
type
s2_master_volume_proc = class
private
FManager : KVoiceManager;
//FManager : KVoiceManager;
FPlugin : Pointer;
//FType : LongInt;
//FSrc : LongInt;
//FAmt : Single;
FLevel : Single;
public
constructor create(AManager:KVoiceManager; AUser:LongInt=0);
procedure noteOn(ANote,AVel:Single);
procedure noteOff(ANote,AVel:Single);
procedure pitchBend(ABend:Single);
procedure process(outs:PSingle);
procedure control(AIndex:LongInt; AValue:Single);
end;
//----------
s2_master_volume_ctrl = class(KControlGroup)
private
WLevel : KWidget;
public
constructor create(AName:PChar; APlugin:KPlugin; AUser:LongInt=0);
destructor destroy; override;
function appendParameters(APlugin:KPlugin; AOffset:LongInt=0) : LongInt; override;
procedure appendWidgets(AOwner:KWidget; AXpos,AYpos:LongInt); override;
procedure connectWidgets(AEditor:KEditor; APlugin:KPlugin); override;
//procedure control(AIndex:LongInt; AValue:Single);
end;
//----------------------------------------------------------------------
implementation
//----------------------------------------------------------------------
uses
kode_color,
kode_parameter,
kode_rect,
//kode_voicemanager,
kode_widget_slider,
kode_widget_text,
syn_s2,
syn_s2_voice,
syn_s2_widgets;
//----------
constructor s2_master_volume_proc.create(AManager:KVoiceManager; AUser:LongInt=0);
begin
end;
//----------
procedure s2_master_volume_proc.noteOn(ANote,AVel:Single);
begin
end;
//----------
procedure s2_master_volume_proc.noteOff(ANote,AVel:Single);
begin
end;
//----------
procedure s2_master_volume_proc.pitchBend(ABend:Single);
begin
end;
//----------
procedure s2_master_volume_proc.process(outs:PSingle);
begin
outs[0] *= FLevel;
outs[1] *= FLevel;
end;
//----------
procedure s2_master_volume_proc.control(AIndex:LongInt; AValue:Single);
begin
//if AIndex = 0 then KTrace(['FLevel = ',AValue,KODE_CR]);
case AIndex of
0 : FLevel := AValue;
end;
end;
//----------------------------------------------------------------------
// control
//----------------------------------------------------------------------
constructor s2_master_volume_ctrl.create(AName:PChar; APlugin:KPlugin; AUser:LongInt=0);
begin
inherited;
FCount := 1;
end;
//----------
destructor s2_master_volume_ctrl.destroy;
begin
inherited;
end;
//----------
function s2_master_volume_ctrl.appendParameters(APlugin:KPlugin; AOffset:LongInt=0) : LongInt;
begin
FOffset := AOffset;
plugin.appendParameter(KParamPow.create( 'Level', 0.1, 3 ));
result := 1;
end;
//----------
procedure s2_master_volume_ctrl.appendWidgets(AOwner:KWidget; AXpos,AYpos:LongInt);
begin
AOwner.appendWidgetW( KWidget_Text.create( rect( AXpos, AYpos+(0*18), 128,16 ), FName, KLightGrey, KDarkGrey ));
WLevel := AOwner.appendWidgetW( s2_slider_orange.create( rect( AXpos, AYpos+(1*18), 128,16 ), 'level', 0 ));
end;
//----------
procedure s2_master_volume_ctrl.connectWidgets(AEditor:KEditor; APlugin:KPlugin);
begin
AEditor.connect( WLevel, APlugin.getParameter(FOffset+0) );
end;
//----------------------------------------------------------------------
end.
|
{ *******************************************************************************
Title: T2Ti ERP
Description: Tela principal do PAF-ECF - Caixa.
The MIT License
Copyright: Copyright (C) 2014 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
t2ti.com@gmail.com</p>
@author Albert Eije (T2Ti.COM)
@version 2.0
******************************************************************************* }
unit UCaixa;
interface
uses
Windows, Dialogs, pngimage, ExtCtrls, Classes, Messages, SysUtils, Variants,
Generics.Collections, Graphics, Controls, Forms, jpeg, StdCtrls, Buttons, Biblioteca,
Enter, Menus, JvListComb, Mask, JvExMask, JvToolEdit, JvBaseEdits,
JvExControls, JvExStdCtrls, JvgListBox, JvLabel, JvListBox, UConfiguracao;
type
TMoveControl = class(TControl);
TFCaixa = class(TForm)panelPrincipal: TPanel;
imagePrincipal: TImage;
Bobina: TJvListBox;
panelMenuPrincipal: TPanel;
imagePanelMenuPrincipal: TImage;
labelMenuPrincipal: TJvLabel;
listaMenuPrincipal: TJvgListBox;
panelMenuOperacoes: TPanel;
imagePanelMenuOperacoes: TImage;
labelMenuOperacoes: TJvLabel;
listaMenuOperacoes: TJvgListBox;
panelSubMenu: TPanel;
imagePanelSubMenu: TImage;
listaGerente: TJvgListBox;
panelTitulo: TPanel;
panelBotoes: TPanel;
panelF1: TPanel;
labelF1: TLabel;
imageF1: TImage;
panelF7: TPanel;
labelF7: TLabel;
imageF7: TImage;
panelF2: TPanel;
labelF2: TLabel;
imageF2: TImage;
panelF3: TPanel;
labelF3: TLabel;
imageF3: TImage;
panelF4: TPanel;
labelF4: TLabel;
imageF4: TImage;
panelF5: TPanel;
labelF5: TLabel;
imageF5: TImage;
panelF6: TPanel;
labelF6: TLabel;
imageF6: TImage;
panelF8: TPanel;
labelF8: TLabel;
imageF8: TImage;
panelF9: TPanel;
labelF9: TLabel;
imageF9: TImage;
panelF10: TPanel;
labelF10: TLabel;
imageF10: TImage;
panelF11: TPanel;
labelF11: TLabel;
imageF11: TImage;
panelF12: TPanel;
labelF12: TLabel;
imageF12: TImage;
editCodigo: TEdit;
editQuantidade: TJvCalcEdit;
imageProduto: TJvImageListBox;
MREnter1: TMREnter;
editUnitario: TJvCalcEdit;
editTotalItem: TJvCalcEdit;
editSubTotal: TJvCalcEdit;
Relogio: TStaticText;
labelOperador: TStaticText;
labelCaixa: TStaticText;
labelDescricaoProduto: TStaticText;
LabelDescontoAcrescimo: TStaticText;
edtCOO: TStaticText;
edtNVenda: TStaticText;
labelTotalGeral: TStaticText;
labelMensagens: TStaticText;
PopupMenu1: TPopupMenu;
CarregarImagemdeFundo1: TMenuItem;
EditarPropriedades1: TMenuItem;
procedure ControlMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
procedure ControlMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure ControlMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure ConfiguraResolucao;
procedure GravarAlteracoes;
procedure ScreenActiveControlChange(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure FormDestroy(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure CarregarImagemdeFundo1Click(Sender: TObject);
procedure EditarPropriedades1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
FCaixa: TFCaixa;
RetanguloFoco: TShape;
MoveX, MoveY: Integer;
Mover: Boolean;
implementation
uses UDataModule, EcfPosicaoComponentesVO, EcfConfiguracaoController, UPropriedades;
{$R *.dfm}
{ TODO -oExercício -cPAF-ECF : Verifique se todos os controles da janela estão sendo tratados. Faça as devidas correções. }
{$Region 'Infra'}
procedure TFCaixa.FormCreate(Sender: TObject);
begin
Screen.OnActiveControlChange := ScreenActiveControlChange;
//
RetanguloFoco := TShape.Create(self);
RetanguloFoco.Shape := stRectangle;
RetanguloFoco.Visible := False;
RetanguloFoco.Brush.Style := bsClear;
RetanguloFoco.Pen.Style := psDot;
RetanguloFoco.Pen.Color := clRed;
RetanguloFoco.Pen.Width := 1;
//
ConfiguraResolucao;
end;
procedure TFCaixa.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Screen.OnActiveControlChange := nil;
end;
procedure TFCaixa.FormDestroy(Sender: TObject);
begin
Screen.OnActiveControlChange := nil;
end;
procedure TFCaixa.ScreenActiveControlChange(Sender: TObject);
begin
with RetanguloFoco do
begin
Parent := Screen.ActiveControl.Parent;
Top := Screen.ActiveControl.Top - 2;
Height := Screen.ActiveControl.Height + 4;
Left := Screen.ActiveControl.Left - 2;
Width := Screen.ActiveControl.Width + 4;
Visible := True;
end;
//
ActiveControl.BringToFront;
ActiveControl.Repaint;
end;
{$EndRegion}
{$Region 'Controle do Mouse'}
procedure TFCaixa.ControlMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
(Sender as TWinControl).SetFocus;
MoveX := X;
MoveY := Y;
Mover := True;
TMoveControl(Sender).MouseCapture := True;
ScreenActiveControlChange(Sender);
end;
procedure TFCaixa.ControlMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
begin
if Mover then begin
with Sender As TControl Do
Begin
Left := X - MoveX + Left;
Top := Y - MoveY + Top;
End;
end;
ScreenActiveControlChange(Sender);
end;
procedure TFCaixa.ControlMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
if Mover then begin
Mover := False;
TMoveControl(Sender).MouseCapture := False;
end;
ScreenActiveControlChange(Sender);
if (Sender is TControl) then
(Sender as TControl).Repaint;
end;
{$EndRegion}
{$Region 'Controle do Teclado'}
procedure TFCaixa.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
if (ssAlt in Shift) and (Key = VK_DOWN) then // Ctrl+abaixo
ActiveControl.Top := ActiveControl.Top + 1;
if (ssAlt in Shift) and (Key = VK_UP) then // Ctrl+acima
ActiveControl.Top := ActiveControl.Top - 1;
if (ssAlt in Shift) and (Key = VK_LEFT) then // Ctrl+esquerda
ActiveControl.Left := ActiveControl.Left - 1;
if (ssAlt in Shift) and (Key = VK_RIGHT) then // Ctrl+direita
ActiveControl.Left := ActiveControl.Left + 1;
//
ScreenActiveControlChange(Sender);
//
if Key = VK_F12 then
begin
if Application.MessageBox('Deseja salvar as alterações antes de fechar a janela?', 'Pergunta do Sistema', Mb_YesNo + Mb_IconQuestion) = IdYes then
begin
GravarAlteracoes;
end;
Close;
end;
//
if Key = VK_F2 then
begin
panelMenuPrincipal.Visible := True;
panelMenuPrincipal.BringToFront;
panelSubMenu.Visible := True;
panelMenuPrincipal.SetFocus;
end;
//
if Key = VK_F3 then
begin
panelMenuOperacoes.Visible := True;
panelMenuOperacoes.BringToFront;
panelSubMenu.Visible := True;
panelMenuOperacoes.SetFocus;
end;
//
if Key = VK_ESCAPE then
begin
editCodigo.SetFocus;
panelMenuPrincipal.Visible := False;
panelMenuOperacoes.Visible := False;
panelSubMenu.Visible := False;
end;
end;
{$EndRegion}
{$Region 'Configuração dos Componentes'}
procedure TFCaixa.CarregarImagemdeFundo1Click(Sender: TObject);
var
i: Integer;
begin
if FDataModule.OpenDialog.Execute then
begin
imagePrincipal.Picture.LoadFromFile(FDataModule.OpenDialog.FileName);
for i := 0 to componentcount - 1 do
begin
if (components[i] is TControl) then
(components[i] as TControl).Repaint;
end;
end;
end;
procedure TFCaixa.EditarPropriedades1Click(Sender: TObject);
begin
FPropriedades.JvInspector.Clear;
FPropriedades.JvInspector.AddComponent(ActiveControl, ActiveControl.Name, True);
FPropriedades.ShowModal;
end;
procedure TFCaixa.GravarAlteracoes;
var
i: Integer;
ListaPosicoes: TObjectList<TEcfPosicaoComponentesVO>;
PosicaoComponente: TEcfPosicaoComponentesVO;
begin
try
ListaPosicoes := TObjectList<TEcfPosicaoComponentesVO>.Create;
for i := 0 to componentcount - 1 do
begin
if (components[i] is TControl) then
begin
PosicaoComponente := TEcfPosicaoComponentesVO.Create;
PosicaoComponente.IdEcfResolucao := UConfiguracao.ConfiguracaoVO.EcfResolucaoVO.Id;
PosicaoComponente.Nome := components[i].Name;
PosicaoComponente.Altura := (components[i] as TControl).Height;
PosicaoComponente.Esquerda := (components[i] as TControl).Left;
PosicaoComponente.Topo := (components[i] as TControl).Top;
PosicaoComponente.Largura := (components[i] as TControl).Width;
if (components[i] is TEdit) then
PosicaoComponente.TamanhoFonte := (components[i] as TEdit).Font.Size;
if (components[i] is TJvListBox) then
PosicaoComponente.TamanhoFonte := (components[i] as TJvListBox).Font.Size;
if (components[i] is TPanel) then
PosicaoComponente.TamanhoFonte := (components[i] as TPanel).Font.Size;
if (components[i] is TJvCalcEdit) then
PosicaoComponente.TamanhoFonte := (components[i] as TJvCalcEdit).Font.Size;
if (components[i] is TStaticText) then
PosicaoComponente.TamanhoFonte := (components[i] as TStaticText).Font.Size;
if (components[i] is TJvLabel) then
begin
PosicaoComponente.TamanhoFonte := (components[i] as TJvLabel).Font.Size;
PosicaoComponente.Texto := (components[i] as TJvLabel).Caption;
end;
if (components[i] is TLabel) then
begin
PosicaoComponente.TamanhoFonte := (components[i] as TLabel).Font.Size;
PosicaoComponente.Texto := (components[i] as TLabel).Caption;
end;
ListaPosicoes.Add(PosicaoComponente);
end;
end;
TEcfConfiguracaoController.GravarPosicaoComponentes(ListaPosicoes);
finally
FreeAndNil(ListaPosicoes);
end;
end;
procedure TFCaixa.ConfiguraResolucao;
var
i, j: Integer;
ListaPosicoes: TObjectList<TEcfPosicaoComponentesVO>;
PosicaoComponente: TEcfPosicaoComponentesVO;
NomeComponente: String;
begin
ListaPosicoes := UConfiguracao.ConfiguracaoVO.EcfResolucaoVO.ListaEcfPosicaoComponentesVO;
for j := 0 to componentcount - 1 do
begin
NomeComponente := components[j].Name;
for i := 0 to ListaPosicoes.Count - 1 do
begin
PosicaoComponente := ListaPosicoes.Items[i];
if PosicaoComponente.Nome = NomeComponente then
begin
(components[j] as TControl).Height := PosicaoComponente.Altura;
(components[j] as TControl).Left := PosicaoComponente.Esquerda;
(components[j] as TControl).Top := PosicaoComponente.Topo;
(components[j] as TControl).Width := PosicaoComponente.Largura;
if PosicaoComponente.TamanhoFonte <> 0 then
begin
if (components[j] is TEdit) then
(components[j] as TEdit).Font.Size := PosicaoComponente.TamanhoFonte;
if (components[j] is TJvListBox) then
(components[j] as TJvListBox).Font.Size := PosicaoComponente.TamanhoFonte;
if (components[j] is TJvLabel) then
(components[j] as TJvLabel).Font.Size := PosicaoComponente.TamanhoFonte;
if (components[j] is TPanel) then
(components[j] as TPanel).Font.Size := PosicaoComponente.TamanhoFonte;
if (components[j] is TJvCalcEdit) then
(components[j] as TJvCalcEdit).Font.Size := PosicaoComponente.TamanhoFonte;
end;
if (components[j] is TLabel) then
(components[j] as TLabel).Caption := PosicaoComponente.Texto;
break;
end;
end;
end;
FCaixa.Left := 0;
FCaixa.Top := 0;
FCaixa.Width := UConfiguracao.ConfiguracaoVO.EcfResolucaoVO.Largura;
FCaixa.Height := UConfiguracao.ConfiguracaoVO.EcfResolucaoVO.Altura;
FCaixa.AutoSize := true;
end;
{$EndRegion}
end.
|
{$include kode.inc}
unit _template;
//----------------------------------------------------------------------
interface
//----------------------------------------------------------------------
uses
kode_plugin,
kode_types;
type
myPlugin = class(KPlugin)
public
procedure on_create; override;
procedure on_destroy; override;
procedure on_stateChange(AState:LongWord); override;
procedure on_transportChange(ATransport:LongWord); override;
procedure on_midiEvent(AOffset:LongWord; AData1,AData2,AData3:Byte); override;
procedure on_parameterChange(AIndex:LongWord; AValue:Single); override;
procedure on_programChange(AIndex:LongWord); override;
procedure on_processBlock(AInputs,AOutputs:PPSingle; ASize:LongWord); override;
procedure on_processSample(AInputs,AOutputs:PPSingle); override;
procedure on_postProcess; override;
{$ifdef KODE_GUI}
function on_openEditor(AParent:Pointer) : Pointer; override;
procedure on_closeEditor; override;
procedure on_idleEditor; override;
{$endif}
end;
KPluginClass = myPlugin;
//----------------------------------------------------------------------
implementation
//----------------------------------------------------------------------
uses
_plugin_id,
{$ifdef KODE_GUI}
kode_editor,
{$endif}
kode_const,
kode_flags,
kode_utils;
//----------
procedure myPlugin.on_create;
begin
FName := 'template';
FAuthor := 'skei.audio';
FProduct := FName;
FVersion := 0;
FUniqueId := KODE_MAGIC_USER + _template_id;
FNumInputs := 2;
FNumOutputs := 2;
KSetFlag(FFlags,
kpf_perSample
//+ kpf_sendMidi
//+ kpf_receiveMidi
//+ kpf_isSynth
//+ kpf_autoUpdateSync
//+ kpf_reaper
);
{$ifdef KODE_GUI}
KSetFlag(FFlags,kpf_hasEditor);
FEditor := nil;
FEditorRect.setup(640,480);
{$endif}
//appendParameter( KParamFloat.create( 'param1', 0 ));
// .. init variables/members..
end;
//----------
procedure myPlugin.on_destroy;
begin
// cleanup
end;
//----------
procedure myPlugin.on_stateChange(AState:LongWord);
begin
case AState of
kps_open: begin end;
kps_close: begin end;
kps_sampleRate: begin end;
kps_blockSize: begin end;
kps_suspend: begin end;
kps_resume: begin end;
kps_start: begin end;
kps_stop: begin end;
kps_bypass: begin end;
kps_bypassOff: begin end;
end;
end;
//----------
{
kpt_changed
kpt_play, kpt_cycle, kpt_record
kpt_awrite, kpt_aread
kpt_pause
}
procedure myPlugin.on_transportChange(ATransport:LongWord);
begin
if ATransport and kpt_changed <> 0 then
begin
end;
end;
//----------
procedure myPlugin.on_midiEvent(AOffset:LongWord; AData1,AData2,AData3:Byte);
begin
end;
//----------
procedure myPlugin.on_parameterChange(AIndex:LongWord; AValue:Single);
var
v : single;
begin
case AIndex of
0: v := AValue;
end;
end;
//----------
procedure myPlugin.on_programChange(AIndex:LongWord);
begin
end;
//----------
procedure myPlugin.on_processBlock(AInputs,AOutputs:PPSingle; ASize:LongWord);
begin
end;
//----------
procedure myPlugin.on_processSample(AInputs,AOutputs:PPSingle);
var
spl0,spl1 : single;
begin
spl0 := AInputs[0]^;
spl1 := AInputs[1]^;
AOutputs[0]^ := spl0;
AOutputs[1]^ := spl1;
end;
//----------
procedure myPlugin.on_postProcess;
begin
end;
//----------
{$ifdef KODE_GUI}
function myPlugin.on_openEditor(AParent:Pointer) : Pointer;
var
editor : KEditor;
begin
editor := KEditor.create(self,FEditorRect,AParent);
//{$ifdef KODE_VST}
//editor.on_align;
//editor.paint(FEditorRect);
//{$endif}
//editor.show;
result := editor;
end;
{$endif}
//----------
{$ifdef KODE_GUI}
procedure myPlugin.on_closeEditor;
begin
FEditor.hide;
FEditor.destroy;
FEditor := nil;
end;
{$endif}
//----------
{$ifdef KODE_GUI}
procedure myPlugin.on_idleEditor;
begin
end;
{$endif}
//----------------------------------------------------------------------
end.
|
unit uUpdater;
interface
uses
System.Classes, SysUtils, WinApi.Windows, IdHTTP, Forms, ShellAPI,
Xml.xmldom, Xml.XMLIntf, Xml.Win.msxmldom, Xml.XMLDoc,
IdServerIOHandler, IdServerIOHandlerSocket,
IdIOHandler, IdIOHandlerSocket, IdIOHandlerStack, IdSSL, IdSSLOpenSSL;
const
strUpdaterExeName: string = 'Updater.exe';
strUpdaterDLUrl: string = 'https://github.com/Egaisbox/Updater/releases/download/Latest/Updater.exe';
VersionFileURL: string = 'https://github.com/Egaisbox/Version/releases/download/Latest/Version.xml';
// https://github.com/Egaisbox/Version/releases/download/Latest/Version.xml
VersionFileURLalt: string = 'https://github.com/EBres/Version/releases/download/Latest/Version.xml';
type
TUpdater = class(TThread)
private
fVersionURL: String;
fVersionAltURL: String;
fSilent: Boolean;
type TUpdateStructure = class
Version: String;
Forced:Boolean;
UrlList: TStringList;
end;
protected
procedure Execute; override;
class function DownloadFileToStream(URL: string; DestStream: TStream): Boolean;
function ParseVersionStream(VersionStream: TMemoryStream; UpStruct: TUpdateStructure): Boolean;
procedure CantLoadFile();
procedure NeedRestartForUpdateForced();
procedure NeedRestartForUpdate();
function ExtractFileNameFromURL(aURL: string): string;
published
class function GetCurrentVersion(): String;
property VersionURL: string write fVersionURL;
property VersionAltURL: string write fVersionAltURL;
property Silent: Boolean write fSilent;
end;
var
thUpdater: TUpdater;
procedure CheckUpdates();
procedure StartUpdater();
procedure CheckUpdater();
procedure StopUpdateProcess();
implementation
uses uMain, uLogic, uLog, uXML;
procedure CheckUpdates();
begin
Log('Запуск процесса проверки обновлений...');
thUpdater:=TUpdater.Create(true);
thUpdater.fVersionURL:= VersionFileURL;
thUpdater.fVersionAltURL:= VersionFileURLalt;
thUpdater.Silent:= False;
thUpdater.Priority:= tpLowest;
thUpdater.Resume;
end;
procedure CheckUpdater();
var
Stream: TMemoryStream;
begin
try
Stream := TMemoryStream.Create();
if not FileExists(strUpdaterExeName) then
begin
TUpdater.DownloadFileToStream(strUpdaterDLUrl, Stream);
Stream.SaveToFile(strUpdaterExeName);
end;
finally
Stream.Free;
end;
end;
procedure StartUpdater();
begin
try
CheckUpdater();
ShellExecute(Application.Handle, nil, 'updater.exe', nil, nil, SW_HIDE);
except
on e:Exception do begin
ErrorLog(e, 'StartUpdater', False);
end;
end;
end;
procedure StopUpdateProcess();
begin
if thUpdater <> nil then begin
if not thUpdater.Terminated then begin
thUpdater.Terminate();
thUpdater.WaitFor();
end;
FreeAndNil(thUpdater);
end;
end;
procedure TUpdater.Execute;
var
thStream:TMemoryStream;
r: TStringList;
UpStructure: TUpdateStructure;
index: Integer;
begin
try
//Sleep(60000);
thStream:= TMemoryStream.Create();
if DownloadFileToStream(fVersionURL, thStream) OR DownloadFileToStream(fVersionAltURL, thStream) then begin
Log('Файл версии загружен...');
UpStructure:= TUpdateStructure.Create();
UpStructure.UrlList:= TStringList.Create();
if ParseVersionStream(thStream, UpStructure) then begin
if UpStructure.Version <> GetCurrentVersion() then begin
Log('Актуальная версия: ' + UpStructure.Version);
if UpStructure.UrlList.Count > 0 then begin
Log('Файлов для обновления:', UpStructure.URLList.Count);
for index := 0 to UpStructure.URLList.Count - 1 do begin
thStream.Clear;
if DownloadFileToStream(UpStructure.URLList[index], thStream) then
thStream.SaveToFile(ExtractFileNameFromURL(UpStructure.URLList[index]));
end;
Log('Необходима перезагрузка программы для обновления');
if not Self.Terminated then begin
if UpStructure.Forced then
Synchronize(NeedRestartForUpdateForced)
else Synchronize(NeedRestartForUpdate);
CheckUpdater;
end else Log('Поток отменен');
bNeedUpdate:= True;
end;
end else begin
Log('Установлена актуальная версия программы...');
end
end else begin
Log('Ошибка парсинга файла обновления!');
Exit;
end;
end else begin
Synchronize(CantLoadFile);
end;
Log('Проверка обновлений завершена');
finally
thStream.Free;
if UpStructure <> nil then begin
UpStructure.UrlList.Free;
UpStructure.Free;
end;
end;
end;
procedure TUpdater.CantLoadFile();
begin
Log('Не удается загрузить файл для обновления...');
if not self.fSilent then
MessageBox(Application.Handle, PWideChar('Модуль обновления не смог загрузить необходимые файлы'
+ CrLf + 'Пожалуйста, проверьте настройки и доступность интернета.'),
PWideChar('Ошибка обновления'), MB_OK + MB_ICONWARNING + MB_APPLMODAL + MB_TOPMOST);
end;
function TUpdater.ParseVersionStream(VersionStream: TMemoryStream; UpStruct: TUpdateStructure): Boolean;
var
xmlDoc: IXMLDocument;
RootNode, VersionNode, ForceNode, FileListNode, FileNode: IXMLNode;
i: Integer;
begin
try
xmlDoc:= NewXMLDocument;
xmlDoc.LoadFromStream(VersionStream);
RootNode:=xmlDoc.ChildNodes.FindNode('Version');
VersionNode:= RootNode.ChildNodes.FindNode('Current');
UpStruct.Version:= VersionNode.Text;
ForceNode:= RootNode.ChildNodes.FindNode('Forced');
UpStruct.Forced:= StrToBool(ForceNode.Text);
FileListNode:= RootNode.ChildNodes.FindNode('Files');
for i := 0 to FileListNode.ChildNodes.Count - 1 do begin
FileNode:= FileListNode.ChildNodes.Get(i);
UpStruct.UrlList.Add(FileNode.Text);
end;
Result:= True;
finally
//
end;
end;
class function TUpdater.GetCurrentVersion(): String;
type
TVerInfo=packed record
Nevazhno: array[0..47] of byte; // ненужные нам 48 байт
Minor,Major,Build,Release: word; // а тут версия
end;
var
s:TResourceStream;
v:TVerInfo;
begin
result:='';
try
s:=TResourceStream.Create(HInstance,'#1',RT_VERSION); // достаём ресурс
if s.Size > 0 then begin
s.Read(v, SizeOf(v)); // читаем нужные нам байты
Result:= IntToStr(v.Major) + '.' + Format('%.3d', [v.Minor]);
end;
s.Free;
except;
end; end;
class function TUpdater.DownloadFileToStream(URL: string; DestStream: TStream): Boolean;
var
HTTP: TIdHTTP;
IdSSLIOHandlerSocket1: TIdSSLIOHandlerSocketOpenSSL;
Answer: String;
NewLocation:String;
begin
try
//Log('Загрузка: ' + URL);
HTTP := TIdHTTP.Create(nil);
// IdSSLIOHandlerSocket1:=TIdSSLIOHandlerSocketOpenSSL.Create(HTTP);
// IdSSLIOHandlerSocket1.SSLOptions.Method := sslvTLSv1;
// IdSSLIOHandlerSocket1.SSLOptions.Mode := sslmUnassigned;
// HTTP.IOHandler:=IdSSLIOHandlerSocket1;
// HTTP.Request.ContentType := 'text/html';
HTTP.Request.Accept := 'text/html, */*';
HTTP.Request.BasicAuthentication := False;
HTTP.Request.UserAgent := 'Mozilla/4.0 (compatible; MSIE 6.0; MSIE 5.5;) ';
//HTTP.RedirectMaximum := 15;
HTTP.HandleRedirects := True;
//HTTP.ConnectTimeout := 5;
try
HTTP.Get(URL, DestStream);
Result:= True;
except
on e: Exception do begin
if (e is EIDHttpProtocolException) then begin
if (e as EIDHttpProtocolException).ErrorCode = 302 then begin
NewLocation:= HTTP.Response.Location;
//Log('DL redirect to ' + NewLocation);
try
HTTP.Get(NewLocation, DestStream);
Result:= True;
except
on x: Exception do
ErrorLog(x, 'DownloadEx', False);
end;
end else begin
ErrorLog(e, 'Download', False);
end;
end else ErrorLog(e, 'Download', False);
end;
end;
finally
HTTP.Free;
end;
end;
function TUpdater.ExtractFileNameFromURL(aURL: string): string;
var
i: Integer;
begin
i := LastDelimiter('/', aURL);
Result := Copy(aURL, i + 1, Length(aURL) - (i));
end;
procedure TUpdater.NeedRestartForUpdateForced();
begin
//
end;
procedure TUpdater.NeedRestartForUpdate();
begin
if not Self.fSilent then
MessageBox(Application.Handle, PWideChar('Загружена новая версия программы.'
+ CrLf + 'Она будет установлена при следующем запуске.'
//+ CrLf
//+ CrLf + 'При необходимости используйте пункт меню'
//+ CrLf + '"?"->"Отменить обновление"'
),
PWideChar('Обновление программы'), MB_OK + MB_ICONINFORMATION + MB_APPLMODAL + MB_TOPMOST);
end;
end.
|
unit UxlIniFile;
interface
uses windows, UxlFunctions, UxlList;
type
TIniCache = class
private
FIniFile: widestring;
FList: TxlStrList;
FBuffer: pwidechar;
public
constructor Create (const s_inifile: widestring);
destructor Destroy (); override;
procedure Clear ();
procedure ReadSection (const s_section: widestring);
function GetString (const s_key, s_default: widestring): widestring;
function GetInteger (const s_key: widestring; i_default: integer): integer;
function GetBool (const s_key: widestring; b_default: boolean): boolean;
function GetFloat (const s_key: widestring; d_default: double): double;
procedure AddString (const s_key, s_value: widestring);
procedure AddInteger (const s_key: widestring; i_value: integer);
procedure AddBool (const s_key: widestring; b_value: boolean);
procedure AddFloat (const s_key: widestring; d_value: double);
procedure WriteSection (const s_section: widestring);
end;
TxlIniFile = class
private
Finifile: widestring;
FSection: widestring;
FCache: TIniCache;
public
constructor Create (const s_inifile: widestring);
destructor Destroy (); override;
function Cache(): TIniCache;
property Section: widestring read FSection write FSection;
function ReadString (const s_key, s_default: widestring): widestring;
function ReadInteger (const s_key: widestring; i_default: integer): integer;
function ReadBool (const s_key: widestring; b_default: boolean): boolean;
function ReadFloat (const s_key: widestring; d_default: double): double;
procedure WriteString (const s_key, s_value: widestring);
procedure WriteInteger (const s_key: widestring; i_value: integer);
procedure WriteBool (const s_key: widestring; b_value: boolean);
procedure WriteFloat (const s_key: widestring; d_value: double);
end;
type
TxlRegistry = class
private
FRootKey: HKey;
FCurrentKey: HKey;
FLazyWrite: boolean;
function f_GetBaseKey (): HKey;
public
constructor Create (const rootkey: hkey = 0);
destructor Destroy (); override;
function OpenKey(const s_Key: WideString; CanCreate: Boolean = true): Boolean;
procedure CloseKey ();
function CreateKey (const s_key: Widestring): boolean; // Does not change CurrentKey
function DeleteKey (const s_key: widestring): boolean;
function ReadString (const s_name: widestring): widestring;
function ReadInteger (const s_name: widestring): integer;
function ReadBool (const s_name: widestring): boolean;
function WriteString (const s_name, s_value: widestring): boolean;
function WriteInteger (const s_name: widestring; i_value: integer): boolean;
function WriteBool (const s_name: widestring; b_value: boolean): boolean;
function DeleteValue (const s_name: widestring): boolean;
property RootKey: HKey read FRootKey write FRootKey;
property LazyWrite: boolean read FLazyWrite write FLazyWrite;
end;
procedure SetFileAssociate (s_ext: widestring; b_associate: boolean; iconidx: integer = 0);
function CheckFileAssociate (s_ext: widestring): boolean;
implementation
uses UxlStrUtils;
const c_buffersize = 10000;
constructor TIniCache.Create (const s_inifile: widestring);
begin
FIniFile := s_inifile;
FList := TxlStrList.Create;
FList.KeyDeli := '=';
GetMem (FBuffer, c_buffersize * 2);
end;
destructor TIniCache.Destroy ();
begin
FreeMem (FBuffer, c_buffersize * 2);
FList.free;
inherited;
end;
procedure TIniCache.Clear ();
begin
FList.Clear;
end;
procedure TIniCache.ReadSection (const s_section: widestring);
var p: pwidechar;
s: widestring;
begin
GetPrivateProfileSectionW(pwidechar(s_section), FBuffer, c_buffersize, pwidechar(FIniFile));
p := FBuffer;
Clear;
while p^ <> #0 do
begin
s := pwidechar (p);
FList.Add (s);
inc (p, Length(s) + 1);
end;
end;
function TIniCache.GetString (const s_key, s_default: widestring): widestring;
begin
result := FList.ItemsByKey[s_key];
if result = '' then result := s_default;
end;
function TIniCache.GetInteger (const s_key: widestring; i_default: integer): integer;
begin
result := StrToIntDef (GetString(s_key, IntToStr(i_default)), i_default);
end;
function TIniCache.GetBool (const s_key: widestring; b_default: boolean): boolean;
begin
result := StrToBool (GetString(s_key, BoolToStr(b_default)));
end;
function TIniCache.GetFloat (const s_key: widestring; d_default: double): double;
begin
result := StrToFloatDef (GetString(s_key, FloatToStr(d_default)), d_default);
end;
procedure TIniCache.AddString (const s_key, s_value: widestring);
begin
FList.AddByKey (s_key, s_value);
end;
procedure TIniCache.AddInteger (const s_key: widestring; i_value: integer);
begin
AddString (s_key, IntToStr(i_value));
end;
procedure TIniCache.AddBool (const s_key: widestring; b_value: boolean);
begin
AddString (s_key, BoolToStr(b_value));
end;
procedure TIniCache.AddFloat (const s_key: widestring; d_value: double);
begin
AddString (s_key, FloatToStr(d_value));
end;
procedure TIniCache.WriteSection (const s_section: widestring);
var i, n: integer;
p: pwidechar;
s: widestring;
begin
p := FBuffer;
for i := FList.Low to FList.High do
begin
s := FList.Keys[i] + FList.KeyDeli + FList[i];
// if i = FList.High then
// s := s + #13#10;
n := Length(s)+1;
copymemory (p, pwidechar(s), n*2);
inc (p, n);
end;
p^ := #0;
WritePrivateProfileSectionW (pwidechar(s_section), FBuffer, pwidechar(FIniFile));
Clear;
end;
//-----------------------
constructor TxlIniFile.Create (const s_inifile: widestring);
begin
Finifile := s_inifile;
end;
destructor TxlIniFile.Destroy ();
begin
FCache.free;
inherited;
end;
function TxlIniFile.Cache(): TIniCache;
begin
if not assigned (FCache) then
FCache := TIniCache.Create (FIniFile);
result := FCache;
end;
function TxlIniFile.ReadString (const s_key, s_default: widestring): widestring;
var p: array [0..1001] of widechar;
n: integer;
begin
n := GetPrivateProfileStringW (pwidechar(Fsection), pwidechar(s_key), pwidechar(s_default), p, 500, pwidechar(Finifile));
p[n] := #0;
result := p;
end;
function TxlIniFile.ReadInteger (const s_key: widestring; i_default: integer): integer;
begin
result := GetPrivateProfileIntW (pwidechar(Fsection), pwidechar(s_key), i_default, pwidechar(Finifile));
end;
function TxlInifile.ReadFloat (const s_key: widestring; d_default: double): double;
begin
result := StrToFloatDef (readstring (s_key, FloatToStr(d_default)), d_default);
end;
function TxlIniFile.ReadBool (const s_key: widestring; b_default: boolean): boolean;
begin
result := IntToBool (ReadInteger(s_key, booltoint(b_default)));
end;
procedure TxlIniFile.WriteString (const s_key, s_value: widestring);
begin
WritePrivateProfileStringW (pwidechar(Fsection), pwidechar(s_key), pwidechar(s_value), pwidechar(Finifile));
end;
procedure TxlIniFile.WriteInteger (const s_key: widestring; i_value: integer);
begin
WriteString (s_key, IntToStr(i_value));
end;
procedure TxlIniFile.WriteBool (const s_key: widestring; b_value: boolean);
begin
WriteInteger (s_key, BoolToInt(b_value));
end;
procedure TxlInifile.WriteFloat (const s_key: widestring; d_value: double);
begin
WriteString (s_key, FloatToStr(d_value));
end;
//------------------------
constructor TxlRegistry.Create (const rootkey: hkey = 0);
begin
if rootkey <> 0 then
FRootKey := rootkey
else
FRootKey := HKEY_CURRENT_USER;
FLazyWrite := true;
FCurrentKey := 0;
end;
destructor TxlRegistry.Destroy ();
begin
CloseKey;
inherited;
end;
function TxlRegistry.OpenKey(const s_key: WideString; CanCreate: Boolean = true): Boolean;
var i: integer;
begin
CloseKey;
if CanCreate then
i := RegCreateKeyExW (f_GetBaseKey, PwideChar(S_key), 0, nil, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, nil, FCurrentKey, nil)
else
i := RegOpenKeyExW (f_GetBaseKey, pwidechar(s_key), 0, KEY_ALL_ACCESS, FCurrentKey);
result := i = ERROR_SUCCESS;
end;
procedure TxlRegistry.CloseKey ();
begin
if FCurrentKey = 0 then exit;
if FLazyWrite then
RegCloseKey (FCurrentKey)
else
RegFlushKey (FCurrentKey);
FCurrentKey := 0;
end;
function TxlRegistry.CreateKey (const s_key: Widestring): boolean;
var TempKey: HKey;
begin
CloseKey;
result := RegCreateKeyExW (f_GetBaseKey, PwideChar(S_key), 0, nil, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, nil, TempKey, nil) = ERROR_SUCCESS;
if result then RegCloseKey (TempKey);
end;
function TxlRegistry.DeleteKey (const s_key: widestring): boolean;
begin
result := RegDeleteKeyW (f_GetBaseKey, pwidechar(s_key)) = ERROR_SUCCESS;
end;
function TxlRegistry.ReadString (const s_name: widestring): widestring;
var p: pointer;
n: integer;
begin
result := '';
if FCurrentKey = 0 then exit;
if RegQueryValueExW (FCurrentKey, pwidechar(s_name), nil, nil, nil, @n) = ERROR_SUCCESS then
begin
GetMem (p, n);
if RegQueryValueExW (FCurrentKey, pwidechar(s_name), nil, nil, p, @n) = ERROR_SUCCESS then
result := pwidechar(p);
FreeMem (p, n);
end;
end;
function TxlRegistry.ReadInteger (const s_name: widestring): integer;
var n: integer;
begin
result := 0;
n := sizeof(result);
if FCurrentKey <> 0 then
RegQueryValueExW (FCurrentKey, pwidechar(s_name), nil, nil, @result, @n);
end;
function TxlRegistry.ReadBool (const s_name: widestring): boolean;
begin
result := IntToBool (ReadInteger(s_name));
end;
function TxlRegistry.WriteString (const s_name, s_value: widestring): boolean;
begin
if FCurrentKey = 0 then
result := false
else
result := RegSetValueExW (FCurrentKey, pwidechar(s_name), 0, REG_SZ, pwidechar(s_value), length(s_value) * 2) = ERROR_SUCCESS;
end;
function TxlRegistry.WriteInteger (const s_name: widestring; i_value: integer): boolean;
begin
if FCurrentKey = 0 then
result := false
else
result := RegSetValueExW (FCurrentKey, pwidechar(s_name), 0, REG_DWORD, @i_value, sizeof(i_value)) = ERROR_SUCCESS;
end;
function TxlRegistry.WriteBool (const s_name: widestring; b_value: boolean): boolean;
begin
result := WriteInteger (s_name, Ord(b_value));
end;
function TxlRegistry.DeleteValue (const s_name: widestring): boolean;
begin
if FCurrentKey = 0 then
result := false
else
result := RegDeleteValueW (FCurrentKey, pwidechar(s_name)) = ERROR_SUCCESS;
end;
function TxlRegistry.f_GetBaseKey (): HKey;
begin
if FCurrentKey = 0 then
result := FRootKey
else
result := FCurrentKey;
end;
//--------------------
procedure SHChangeNotify(wEventId: Longint; uFlags: UINT; dwItem1, dwItem2: Pointer); stdcall; external 'Shell32.dll' name 'SHChangeNotify';
const SHCNE_ASSOCCHANGED = $08000000;
SHCNF_FLUSHNOWAIT = $2000;
procedure SetFileAssociate (s_ext: widestring; b_associate: boolean; iconidx: integer = 0);
var s_key: widestring;
s_filetype: widestring;
begin
if s_ext[1] <> '.' then
begin
s_filetype := s_ext;
s_ext := '.' + s_ext;
end
else
s_filetype := MidStr (s_ext, 2);
with TxlRegistry.Create (HKey_Classes_Root) do
begin
if b_associate then
begin
OpenKey (s_ext, true);
s_key := ProgName + s_ext;
WriteString ('', s_key);
CloseKey;
OpenKey (s_key, true);
WriteString ('', ProgName + ' ' + UpperCase(s_filetype) + ' File');
CloseKey;
OpenKey (s_key + '\DefaultIcon', true);
WriteString ('', ProgExe + ',' + IntToStr(iconidx));
CloseKey;
OpenKey (s_key + '\shell\open\command', true);
WriteString ('', '"' + ProgExe + '" "%1"');
CloseKey;
SHChangeNotify(SHCNE_ASSOCCHANGED,SHCNF_FLUSHNOWAIT,nil,nil); // 立即刷新关联图标
end
else
begin
OpenKey (s_ext, true);
WriteString ('', '');
CloseKey;
end;
Free;
end;
end;
function CheckFileAssociate (s_ext: widestring): boolean;
var o_reg: TxlRegistry;
s_key, s_value: widestring;
begin
result := false;
o_reg := TxlRegistry.Create (HKey_Classes_Root);
if s_ext[1] <> '.' then s_ext := '.' + s_ext;
if not o_reg.OpenKey (s_ext, false) then exit;
s_key := o_reg.ReadString ('');
o_reg.CloseKey;
if s_key = '' then exit;
if not o_reg.OpenKey (s_key + '\shell\open\command', false) then exit;
s_value := o_reg.ReadString ('');
result := FirstPos (lowerCase(progExe), lowerCase(s_value)) > 0;
o_reg.CloseKey;
o_reg.Free;
end;
end.
|
unit AddForm;
//TODO: Configurable "pinned options", path history & pinned paths
//TODO: "Option presets"
//TODO: Focus url list on window activation
//TODO: Check integrity etc
//TODO: Better editor for urls/options
//TODO: Clear button
interface
uses
Windows, Messages, AvL, avlUtils, avlEventBus, Base64, Aria2;
type
TAddForm = class(TForm)
Options: array of TAria2Option;
URLs: array of string;
FileName: string;
SeparateURLs: Boolean;
private
LName, LPath, LOptions: TLabel;
EFileName: TEdit;
CBPath: TComboBox;
MURLs, MOptions: TMemo;
CSeparateURLs, CPause, CMetaPause: TCheckBox;
BtnOK, BtnCancel, BtnBrowse, BtnPath: TButton;
POptions: TSimplePanel;
FHandler: TOnEvent;
FMaxHistory: Integer;
procedure FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure FormShow(Sender: TObject);
procedure BrowseClick(Sender: TObject);
procedure OKClick(Sender: TObject);
procedure CancelClick(Sender: TObject);
procedure PathClick(Sender: TObject);
procedure LoadSettings(Sender: TObject; const Args: array of const);
public
constructor Create(AParent: TWinControl);
destructor Destroy; override;
procedure Show(const Caption, Filter: string; AddFile: Boolean; Handler: TOnEvent);
end;
var
FormAdd: TAddForm;
implementation
uses
Utils, MainForm;
const
SMaxPathHistory = 'MaxPathHistory';
SPersOptions = 'AddForm.Options';
SPersPathHistory = 'AddForm.PathHistory';
SPersSeparateURLs = 'AddForm.SeparateURLs';
SPersPause = 'AddForm.Pause';
SPersMetaPause = 'AddForm.MetaPause';
LNameCaption: array[Boolean] of string = ('Enter URLs (one per line):', 'Enter file name:');
{ TAddForm }
constructor TAddForm.Create(AParent: TWinControl);
var
Ctrl: TWinControl;
begin
inherited Create(AParent, '');
BorderStyle := bsDialog;
SetSize(400 + Width - ClientWidth, 350 + Height - ClientHeight);
Position := poScreenCenter;
OnShow := FormShow;
LName := TLabel.Create(Self, '');
LName.SetBounds(5, 5, ClientWidth div 2, 15);
CSeparateURLs := TCheckBox.Create(Self, 'Separate transfers');
CSeparateURLs.SetBounds(ClientWidth div 2 + 5, 5, ClientWidth div 2 - 10, 15);
EFileName := TEdit.Create(Self, '');
EFileName.SetBounds(5, 20, ClientWidth - 90, 24);
BtnBrowse := TButton.Create(Self, 'Browse');
BtnBrowse.SetBounds(ClientWidth - 80, 20, 75, 24);
BtnBrowse.OnClick := BrowseClick;
MURLs := TMemo.Create(Self, '');
MURLs.SetBounds(5, 20, ClientWidth - 10, 100);
MURLs.Style := MURLs.Style or WS_VSCROLL or WS_HSCROLL or ES_AUTOHSCROLL or ES_AUTOVSCROLL;
POptions := TSimplePanel.Create(Self, '');
POptions.Border := 2;
POptions.SetBounds(5, 125, ClientWidth - 10, ClientHeight - 180);
LPath := TLabel.Create(POptions, 'Download path:');
LPath.SetBounds(0, 0, POptions.Width, 15);
CBPath := TComboBox.Create(POptions, csDropDown);
CBPath.SetBounds(0, 15, POptions.Width - 80, 24);
BtnPath := TButton.Create(POptions, 'Browse');
BtnPath.SetBounds(POptions.Width - 75, 15, 75, 24);
BtnPath.OnClick := PathClick;
CPause := TCheckBox.Create(POptions, 'Pause');
CPause.SetBounds(0, 45, POptions.Width div 2, 15);
CMetaPause := TCheckBox.Create(POptions, 'Pause following transfers');
CMetaPause.SetBounds(CPause.Width + 5, 45, POptions.Width - CPause.Width - 5, 15);
LOptions := TLabel.Create(POptions, 'Options (one per line, key=value):');
LOptions.SetBounds(0, 65, POptions.Width, 15);
MOptions := TMemo.Create(POptions, '');
MOptions.SetBounds(0, 80, POptions.Width, POptions.Height - 80);
MOptions.Style := MOptions.Style or WS_VSCROLL or WS_HSCROLL or ES_AUTOHSCROLL or ES_AUTOVSCROLL;
BtnOK := TButton.Create(Self, 'OK');
BtnOK.SetBounds(ClientWidth - 160, ClientHeight - 30, 75, 25);
BtnOK.OnClick := OKClick;
BtnCancel := TButton.Create(Self, 'Cancel');
BtnCancel.SetBounds(ClientWidth - 80, ClientHeight - 30, 75, 25);
BtnCancel.OnClick := CancelClick;
Ctrl := Self;
repeat
Ctrl.OnKeyUp := FormKeyUp;
Ctrl := Ctrl.NextControl;
until (Ctrl.Parent <> Self) and (Ctrl.Parent <> POptions);
EventBus.AddListener(EvLoadSettings, LoadSettings);
end;
destructor TAddForm.Destroy;
begin
EventBus.RemoveListener(LoadSettings);
Finalize(Options);
Finalize(URLs);
inherited;
end;
procedure TAddForm.FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
if (Key = VK_RETURN) and ((ssCtrl in Shift) or not (Sender is TMemo)) then
OKClick(BtnOK);
if Key = VK_ESCAPE then
CancelClick(BtnCancel);
end;
procedure TAddForm.FormShow(Sender: TObject);
var
i: Integer;
SL: TStringList;
begin
if EFileName.Enabled then
begin
EFileName.SetFocus;
EFileName.SelectAll;
POptions.Top := EFileName.Top + EFileName.Height + 5;
end;
if MURLs.Enabled then //TODO: Auto-paste URLs
begin
MURLs.SetFocus;
MURLs.Perform(EM_SETSEL, 0, -1);
POptions.Top := MURLs.Top + MURLs.Height + 5;
end;
Height := Height - ClientHeight + POptions.Top + POptions.Height + 35;
BtnOK.Top := ClientHeight - 30;
BtnCancel.Top := ClientHeight - 30;
MOptions.Text := Base64Decode(FormMain.Server.Persistent[SPersOptions]);
SL := TStringList.Create;
try
SL.Text := Base64Decode(FormMain.Server.Persistent[SPersPathHistory]);
CBPath.Clear;
for i := 0 to SL.Count - 1 do
CBPath.ItemAdd(SL[i]);
CBPath.ItemIndex := 0;
finally
FreeAndNil(SL);
end;
CSeparateURLs.Checked := Boolean(StrToInt(FormMain.Server.Persistent[SPersSeparateURLs]));
CPause.Checked := Boolean(StrToInt(FormMain.Server.Persistent[SPersPause]));
CMetaPause.Checked := Boolean(StrToInt(FormMain.Server.Persistent[SPersMetaPause]));
end;
procedure TAddForm.BrowseClick(Sender: TObject);
var
FN: string;
begin
FN := EFileName.Text;
if OpenSaveDialog(Handle, true, '', '', BtnBrowse.TagEx, '', 0, OFN_FILEMUSTEXIST, FN) then
EFileName.Text := FN;
end;
procedure TAddForm.PathClick(Sender: TObject);
var
Path: string;
begin
Path := CBPath.Text;
if OpenDirDialog(Handle, '', true, Path) then
CBPath.Text := Path;
end;
procedure TAddForm.OKClick(Sender: TObject);
procedure AddOption(const K, V: string);
begin
if Trim(K) = '' then Exit;
SetLength(Options, Length(Options) + 1);
with Options[High(Options)] do
begin
Key := Trim(K);
Value := Trim(V);
end;
end;
var
i: Integer;
S: string;
begin
if EFileName.Visible then
FileName := EFileName.Text
else begin
SeparateURLs := CSeparateURLs.Checked;
SetLength(URLs, 0);
for i := 0 to MURLs.LineCount - 1 do
if MURLs.LineStrings[i] <> '' then
begin
SetLength(URLs, Length(URLs) + 1);
URLs[High(URLs)] := MURLs.LineStrings[i];
end;
end;
SetLength(Options, 0);
AddOption(soDir, CBPath.Text);
if CPause.Checked then
AddOption(soPause, svTrue);
if CMetaPause.Checked then
AddOption(soPauseMetadata, svTrue);
for i := 0 to MOptions.LineCount - 1 do
if MOptions.LineStrings[i] <> '' then
AddOption(First(MOptions.LineStrings[i], '='), Second(MOptions.LineStrings[i], '='));
FormMain.Server.Persistent[SPersOptions] := Base64Encode(MOptions.Text);
S := CBPath.Text;
CBPath.ItemInsert(S, 0);
for i := CBPath.ItemCount - 1 downto 1 do
if SameText(CBPath.Items[i], S) then
CBPath.ItemDelete(i);
while CBPath.ItemCount > FMaxHistory do
CBPath.ItemDelete(CBPath.ItemCount - 1);
S := '';
for i := 0 to CBPath.ItemCount - 1 do
S := S + CBPath.Items[i] + CRLF;
FormMain.Server.Persistent[SPersPathHistory] := Base64Encode(Trim(S));
FormMain.Server.Persistent[SPersSeparateURLs] := IntToStr(Byte(CSeparateURLs.Checked));
FormMain.Server.Persistent[SPersPause] := IntToStr(Byte(CPause.Checked));
FormMain.Server.Persistent[SPersMetaPause] := IntToStr(Byte(CMetaPause.Checked));
if Assigned(FHandler) then
FHandler(Self);
Close;
end;
procedure TAddForm.CancelClick(Sender: TObject);
begin
Close;
end;
procedure TAddForm.Show(const Caption, Filter: string; AddFile: Boolean; Handler: TOnEvent);
procedure SetActive(Ctrls: array of TWinControl; Active: Boolean);
var
i: Integer;
begin
for i := 0 to High(Ctrls) do
with Ctrls[i] do
begin
Visible := Active;
Enabled := Active;
end;
end;
begin
Self.Caption := Caption;
BtnBrowse.TagEx := Filter;
FHandler := Handler;
LName.Caption := LNameCaption[AddFile];
SetActive([EFileName, BtnBrowse], AddFile);
SetActive([MURLs, CSeparateURLs], not AddFile);
ShowModal;
end;
procedure TAddForm.LoadSettings(Sender: TObject; const Args: array of const);
begin
FMaxHistory := Settings.ReadInteger(SGeneral, SMaxPathHistory, 10);
end;
end.
|
unit u_blob_uploader;
interface
uses
WIndows, Messages, SysUtils, Classes, Controls, Forms, Dialogs, ComCtrls, StdCtrls, ExtCtrls, ShellAPI, httpsend;
type
TOnStartSendingFile = TProc<String,String>;
TOnFinishSendingFile = TProc<String,Boolean, String>;
TFormBinaryProgress = class(Tform)
private
_progressBar: TProgressBar;
_Label: TLabel;
public
Constructor Create(Aowner: TCOmponent); override;
Destructor Destroy; override;
end;
function SendFile(const FileName: String;
onStart: TOnStartSendingFile;
onFinish: TOnFinishSendingFile): Boolean;
function DownloadFile(const RemoteFile, LocalFileName: String;
onStart: TOnStartSendingFile;
onFinish: TOnFinishSendingFile): Boolean; overload;
function DownloadFile(const RemoteFile: String; LocalBuffer: TStream;
onStart: TOnStartSendingFile;
onFinish: TOnFinishSendingFile): Boolean; overload;
function RemoteExists(const RemoteFile: String): Boolean;
function DownloadImageAsStream(const RemoteFile: String): TMemoryStream;
function DownloadImageAsTempFile(const RemoteFile: String): String;
function UploadFile(const FileName: String): String; overload;
function UploadFile(const FileData: TStream; const FileExt: String): String; overload;
function RemoteDelete(const RemoteFile: String): Boolean;
function RemotePreview(const RemoteFile: String): Boolean;
function RemoteRename(const RemoteOldName, RemoteNewName: String): Boolean;
// Upload and replace old file
function RemoteReplaceFile(const FileName, RemoteOldFile: String; const ReturnNewName: Boolean = False): String;
implementation
uses u_utils;
var
ServerUploadURL,
ServerDownloadURL,
FileFieldName : string;
function InitTransferVars: Boolean;
begin
Result := False;
ServerUploadURL := GetOption( 'ServerUploadURL', true);
ServerDownloadURL := GetOption( 'ServerDownloadURL', true);
FileFieldName := GetOption( 'FileFieldName', true);
Result := (ServerUploadURL<>'')
and
(ServerDownloadURL<>'')
and
(FileFieldName<>'');
end;
function SendFile(const FileName: String;
onStart: TOnStartSendingFile;
onFinish: TOnFinishSendingFile): Boolean;
var
ss: TFileStream;
rs: TStrings;
response: String;
begin
Result := False;
response := '';
if Assigned(onStart) then
onStart(FileName, 'Start sending file');
if not InitTransferVars() then
begin
if Assigned(onFinish) then
onFinish(FileName, False, 'Invalid Binary Transfer settings.');
exit;
end;
try
if FileExists(FileName) then
begin
rs := TStringList.Create;
ss := TFileStream.Create(FileName, fmOpenRead);
try
ss.Position := 0;
rs.Clear;
Result := HttpPostFile( ServerUploadURL, FileFieldName, FileName, ss, rs);
response := rs[0];
Result := UpperCase(copy(response,1,2))='OK';
finally
rs.Free;
ss.Free;
end;
end
else
begin
if Assigned(onfinish) then
onfinish(FileName, False, 'Start sending file');
end
finally
if Assigned(onFinish) then
begin
if not Result then
onFinish(FileName, Result, 'Error sending file')
else
onFinish(FileName, Result, copy(response,3, length(response)-2));
end;
end;
end;
function DownloadFile(const RemoteFile, LocalFileName: String;
onStart: TOnStartSendingFile;
onFinish: TOnFinishSendingFile): Boolean;
var
ss: TMemoryStream;
rs: TStrings;
response: String;
begin
Result := False;
response := '';
if Assigned(onStart) then
onStart(RemoteFile, 'Start downloading file');
if not InitTransferVars() then
begin
if Assigned(onFinish) then
onFinish(RemoteFile, False, 'Invalid Binary Transfer settings.');
exit;
end;
try
ss := TMemoryStream.Create;
try
Result := HttpGetBinary(ServerDownloadURL+'?action=download&file='+RemoteFile, ss);
Result := Result and (ss.Size<>0);
if Result then
begin
try
ss.SaveToFile(LocalFileName);
except
onFinish(RemoteFile, Result, 'Cannot save file. Maybe local file is in use');
end;
end;
finally
ss.Free;
end;
finally
if Assigned(onFinish) then
begin
if not Result then
onFinish(RemoteFile, Result, 'Error downloading file')
else
onFinish(RemoteFile, Result, LocalFileName);
end;
end;
end;
function DownloadFile(const RemoteFile: String; LocalBuffer: TStream;
onStart: TOnStartSendingFile;
onFinish: TOnFinishSendingFile): Boolean;
var
ss: TMemoryStream;
rs: TStrings;
response: String;
begin
Result := False;
response := '';
LocalBuffer.Position := 0;
if Assigned(onStart) then
onStart(RemoteFile, 'Start downloading file');
if not InitTransferVars() then
begin
if Assigned(onFinish) then
onFinish(RemoteFile, False, 'Invalid Binary Transfer settings.');
exit;
end;
try
try
Result := HttpGetBinary(ServerDownloadURL+'?action=download&file='+RemoteFile, LocalBuffer);
Result := Result and (LocalBuffer.Size<>0);
except
if Assigned(onFinish) then
onFinish(RemoteFile, False, 'Binary Transfer failed.');
end;
finally
if Assigned(onFinish) then
begin
if not Result then
onFinish(RemoteFile, Result, 'Error downloading file')
else
onFinish(RemoteFile, Result, 'Binary Transfer finished.');
end;
end;
end;
function RemoteExists(const RemoteFile: String): Boolean;
var
rs: TStrings;
begin
Result := False;
if not InitTransferVars() then
exit;
rs := TStringList.Create;
ScreenBussy;
try
Result := HttpGetText( ServerDownloadURL+'?action=exists&file='+RemoteFile,rs);
// InputBox('','',ServerDownloadURL+'?action=exists&file='+RemoteFile);
if rs.Count>0 then
Result := Result and (uppercase(trim(rs[0]))='EXISTS');
finally
ScreenIdle;
rs.Free;
end;
end;
function DownloadImageAsStream(const RemoteFile: String): TMemoryStream;
begin
Result := nil;
if not RemoteExists(RemoteFile) then
exit;
ScreenBussy;
Result := TMemoryStream.Create;
try
if not DownloadFile(RemoteFile, Result,
procedure(a: String; b: String)
begin
ScreenBussy;
end,
procedure(a: String; b: boolean; c: String)
begin
ScreenIdle;
end) then
FreeAndNil(Result);
finally
ScreenIdle;
end;
end;
function DownloadImageAsTempFile(const RemoteFile: String): String;
var
ss: TMemoryStream;
rs: TStrings;
response: String;
b: boolean;
begin
Result := '';
response := '';
if not InitTransferVars() then
raise Exception.Create('Inisialisasi variabel Binary Transfer gagal.');
if not RemoteExists(RemoteFile) then
exit;
Result := TempFile(AppPath(false)+'temp', ExtractFileExt(RemoteFile));
if Result = '' then
exit;
ss := TMemoryStream.Create;
ScreenBussy;
try
b := HttpGetBinary(ServerDownloadURL+'?action=download&file='+RemoteFile, ss);
b := b and (ss.Size>0);
if b then
begin
ss.SaveToFile(Result);
end;
finally
ScreenIdle;
ss.Free;
end;
end;
function UploadFile(const FileName: String): String;
var
ss: TFileStream;
rs: TStrings;
response: String;
begin
Result := '';
response := '';
if not InitTransferVars() then
raise Exception.Create('Inisialisasi variabel Binary Transfer gagal.');
if FileExists(FileName) then
begin
rs := TStringList.Create;
ss := TFileStream.Create(FileName, fmOpenRead);
ScreenBussy;
try
ss.Position := 0;
rs.Clear;
if HttpPostFile( ServerUploadURL, FileFieldName, FileName, ss, rs) then
begin
// response := rs.Text;
response := rs[0];
if UpperCase(copy(response,1,2))='OK' then
begin
Result := copy(response,3,MaxInt);
while result[length(Result)] in [#13, #10] do
Result := Copy(Result,1,length(Result)-1);
end;
end;
finally
ScreenIdle;
rs.Free;
ss.Free;
end;
end
else
raise Exception.Create(FileName +' tidak ditemukan.');
end;
function UploadFile(const FileData: TStream; const FileExt: String): String;
var
tmp: String;
fs: TFileStream;
begin
Result := '';
tmp := TempFile(AppPath(false)+'temp', FileExt);
if tmp = '' then
exit;
try
FileData.Position := 0;
fs := TFileStream.Create(tmp, fmCreate);
fs.CopyFrom(FileData, FileData.Size);
fs.free;
Result := UploadFile(tmp);
if FileExists(tmp) then
DeleteFile(tmp);
except
raise;
end;
end;
function RemoteDelete(const RemoteFile: String): Boolean;
var
rs: TStrings;
begin
Result := False;
if not InitTransferVars() then
exit;
rs := TStringList.Create;
ScreenBussy;
try
Result := HttpGetText( ServerDownloadURL+'?action=delete&file='+RemoteFile,rs);
Result := Result and (uppercase(trim(rs[0]))='REMOVED');
finally
ScreenIdle;
rs.free;
end;
end;
{ TFormBinaryProgress }
constructor TFormBinaryProgress.Create(Aowner: TCOmponent);
begin
inherited Create(Aowner);
FormStyle := fsStayOnTop;
BorderStyle := bsToolWindow;
Width := 300;
Height:= 64;
Position := poDesktopCenter;
_progressBar := TProgressBar.Create(self);
with _progressBar do
begin
Parent := self;
Align := alTop;
Min := 0;
Max := 100;
AlignWithMargins := true;
Visible := true;
Style:= pbstMarquee;
end;
_Label := TLabel.Create(self);
with _progressBar do
begin
Parent := self;
Align := alBottom;
AlignWithMargins := true;
Height := 20;
Caption := 'Transfering Data...';
Visible := true;
end;
end;
destructor TFormBinaryProgress.Destroy;
begin
_progressBar.Free;
_Label.Free;
inherited Destroy;
end;
function RemotePreview(const RemoteFile: String): Boolean;
var
s: String;
begin
Result := False;
s := DownloadImageAsTempFile(RemoteFile);
if not FileExists(s) then
Warn('File tidak ditemukan!'#13'Pastikan server sedang berjalan.')
else
begin
Result := 32 < ShellExecute(Application.Handle, 'open', PChar(s), '', PChar(ExtractFileDir(s)), SW_SHOWNORMAL);
end;
end;
function RemoteRename(const RemoteOldName, RemoteNewName: String): Boolean;
var
rs: TStrings;
begin
Result := False;
if not InitTransferVars() then
exit;
rs := TStringList.Create;
ScreenBussy;
try
Result := HttpGetText( ServerDownloadURL+'?action=rename&file1='+RemoteOldName+'&file2='+RemoteNewName,rs);
Result := Result and (uppercase(trim(rs[0]))='RENAMED');
finally
ScreenIdle;
rs.free;
end;
end;
function RemoteReplaceFile(const FileName, RemoteOldFile: String; const ReturnNewName: Boolean = False): String;
var
t: String;
begin
Result := '';
if RemoteDelete(RemoteOldFile) then
begin
t := UploadFile(FileName);
if ReturnNewName then
Result := t
else
begin
if RemoteRename(t, RemoteOldFile) then
Result := RemoteOldFile;
end;
end;
end;
end.
|
unit UMyBackupXmlInfo;
interface
uses UChangeInfo, xmldom, XMLIntf, msxmldom, XMLDoc, UXmlUtil;
type
{$Region ' 本地备份 修改Xml ' }
{$Region ' 目标路径 ' }
TLocalDesItemWriteXml = class( TXmlChangeInfo )
public
DesPath : string;
protected
DesNodeIndex : Integer;
DesNode : IXMLNode;
public
constructor Create( _DesPath : string );
protected
function FindDesNode : Boolean;
end;
TLocalDesItemAddXml = class( TLocalDesItemWriteXml )
protected
procedure Update;override;
end;
TLocalDesItemRemoveXml = class( TLocalDesItemWriteXml )
protected
procedure Update;override;
end;
{$EndRegion}
{$Region ' 源路径 增删 ' }
TLocalBackupWriteXml = class( TLocalDesItemWriteXml )
public
BackupNodeList : IXMLNode;
public
function FindBackupNodeList : Boolean;
end;
TLocalBackupItemWriteXml = class( TLocalBackupWriteXml )
public
BackupPath : string;
protected
BackupNodeIndex : Integer;
BackupNode : IXMLNode;
public
procedure SetBackupPath( _BackupPath : string );
protected
function FindBackupNode : Boolean;
end;
TLocalBackupItemAddXml = class( TLocalBackupItemWriteXml )
public // 路径信息
IsFile : Boolean;
public // 可选状态
IsDisable, IsBackupNow : Boolean;
public // 自动同步
IsAutoSync : Boolean; // 是否自动同步
SyncTimeType, SyncTimeValue : Integer; // 同步间隔
LasSyncTime : TDateTime; // 上一次同步时间
public // 删除保留信息
IsKeepDeleted : Boolean;
KeepEditionCount : Integer;
public // 空间信息
FileCount : Integer;
ItemSize, CompletedSize : Int64; // 空间信息
public
procedure SetIsFile( _IsFile : Boolean );
procedure SetBackupStatus( _IsDisable, _IsBackupNow : Boolean );
procedure SetAutoSyncInfo( _IsAutoSync : Boolean; _LasSyncTime : TDateTime );
procedure SetSyncTimeInfo( _SyncTimeType, _SyncTimeValue : Integer );
procedure SetDeleteInfo( _IsKeepDeleted : Boolean; _KeepEditionCount : Integer );
procedure SetSpaceInfo( _FileCount : Integer; _ItemSize, _CompletedSize : Int64 );
protected
procedure Update;override;
end;
TLocalBackupItemRemoveXml = class( TLocalBackupItemWriteXml )
protected
procedure Update;override;
end;
{$EndRegion}
{$Region ' 源路径 修改状态 ' }
// 是否 禁止备份
TLocalBackupItemSetIsDisableXml = class( TLocalBackupItemWriteXml )
public
IsDisable : Boolean;
public
procedure SetIsDisable( _IsDisable : Boolean );
protected
procedure Update;override;
end;
// 是否 Backup Now 备份
TLocalBackupItemSetIsBackupNowXml = class( TLocalBackupItemWriteXml )
public
IsBackupNow : Boolean;
public
procedure SetIsBackupNow( _IsBackupNow : Boolean );
protected
procedure Update;override;
end;
{$EndRegion}
{$Region ' 源路径 同步信息 ' }
// 设置 上一次 同步时间
TLocalBackupItemSetLastSyncTimeXml = class( TLocalBackupItemWriteXml )
private
LastSyncTime : TDateTime;
public
procedure SetLastSyncTime( _LastSyncTime : TDateTime );
protected
procedure Update;override;
end;
// 设置 同步周期
TLocalBackupItemSetAutoSyncXml = class( TLocalBackupItemWriteXml )
private
IsAutoSync : Boolean;
SyncTimeValue, SyncTimeType : Integer;
public
procedure SetIsAutoSync( _IsAutoSync : Boolean );
procedure SetSyncInterval( _SyncTimeType, _SyncTimeValue : Integer );
protected
procedure Update;override;
end;
{$EndRegion}
{$EndRegion}
{$Region ' 网络备份 修改Xml ' }
{$Region ' 目标Pc ' }
TNetworkPcItemWriteXml = class( TXmlChangeInfo )
public
PcID : string;
protected
PcNodeIndex : Integer;
PcNode : IXMLNode;
public
constructor Create( _PcID : string );
protected
function FindPcNode : Boolean;
end;
TNetworkPcItemAddXml = class( TNetworkPcItemWriteXml )
protected
procedure Update;override;
end;
TNetworkPcItemRemoveXml = class( TNetworkPcItemWriteXml )
protected
procedure Update;override;
end;
{$EndRegion}
{$Region ' 源路径 增删 ' }
TNetworkBackupWriteXml = class( TNetworkPcItemWriteXml )
public
BackupNodeList : IXMLNode;
public
function FindBackupNodeList : Boolean;
end;
TNetworkBackupItemWriteXml = class( TNetworkBackupWriteXml )
public
BackupPath : string;
protected
BackupNodeIndex : Integer;
BackupNode : IXMLNode;
public
procedure SetBackupPath( _BackupPath : string );
protected
function FindBackupNode : Boolean;
end;
TNetworkBackupItemAddXml = class( TNetworkBackupItemWriteXml )
public // 路径信息
IsFile : Boolean;
public // 可选状态
IsDisable, IsBackupNow : Boolean;
public // 自动同步
IsAutoSync : Boolean; // 是否自动同步
SyncTimeType, SyncTimeValue : Integer; // 同步间隔
LasSyncTime : TDateTime; // 上一次同步时间
public // 删除保留信息
IsKeepDeleted : Boolean;
KeepEditionCount : Integer;
public // 空间信息
FileCount : Integer;
ItemSize, CompletedSize : Int64; // 空间信息
public
procedure SetIsFile( _IsFile : Boolean );
procedure SetBackupStatus( _IsDisable, _IsBackupNow : Boolean );
procedure SetAutoSync( _IsAutoSync : Boolean; _LasSyncTime : TDateTime );
procedure SetSyncInfo( _SyncTimeType, _SyncTimeValue : Integer );
procedure SetDeleteInfo( _IsKeepDeleted : Boolean; _KeepEditionCount : Integer );
procedure SetSpaceInfo( _FileCount : Integer; _ItemSize, _CompletedSize : Int64 );
protected
procedure Update;override;
end;
TNetworkBackupItemRemoveXml = class( TNetworkBackupItemWriteXml )
protected
procedure Update;override;
end;
{$EndRegion}
{$Region ' 源路径 修改状态 ' }
// 是否 禁止备份
TNetworkBackupItemSetIsDisableXml = class( TNetworkBackupItemWriteXml )
public
IsDisable : Boolean;
public
procedure SetIsDisable( _IsDisable : Boolean );
protected
procedure Update;override;
end;
// 是否 Backup Now 备份
TNetworkBackupItemSetIsBackupNowXml = class( TNetworkBackupItemWriteXml )
public
IsBackupNow : Boolean;
public
procedure SetIsBackupNow( _IsBackupNow : Boolean );
protected
procedure Update;override;
end;
{$EndRegion}
{$Region ' 源路径 同步信息 ' }
// 设置 上一次 同步时间
TNetworkBackupItemSetLastSyncTimeXml = class( TNetworkBackupItemWriteXml )
private
LastSyncTime : TDateTime;
public
procedure SetLastSyncTime( _LastSyncTime : TDateTime );
protected
procedure Update;override;
end;
// 设置 同步周期
TNetworkBackupItemSetAutoSyncXml = class( TNetworkBackupItemWriteXml )
private
IsAutoSync : Boolean;
SyncTimeValue, SyncTimeType : Integer;
public
procedure SetIsAutoSync( _IsAutoSync : Boolean );
procedure SetSyncInterval( _SyncTimeType, _SyncTimeValue : Integer );
protected
procedure Update;override;
end;
{$EndRegion}
{$EndRegion}
{$Region ' 本地备份 读取Xml ' }
// 读取 备份路径
TLocalBackupItemReadXml = class
private
DesPath : string;
BackupItemNode : IXMLNode;
public
constructor Create( _BackupItemNode : IXMLNode );
procedure SetDesPath( _DesPath : string );
procedure Update;
end;
// 读取 目标路径
TLocalBackupDesItemReadXml = class
private
DesItemNode : IXMLNode;
private
DesPath : string;
public
constructor Create( _DesItemNode : IXMLNode );
procedure Update;
private
procedure ReadBackupItemList;
end;
// 读取 本地备份 信息
TLocalBackupReadXmlHandle = class
public
procedure Update;
end;
{$EndRegion}
const
Xml_DesPath = 'dp';
Xml_BackupItemList = 'bil';
Xml_BackupPath = 'bp';
Xml_IsFile = 'if';
Xml_IsDisable = 'id';
Xml_IsBackupNow = 'ibn';
Xml_IsAutoSync = 'ias';
Xml_SyncTimeType = 'stt';
Xml_SyncTimeValue = 'stv';
Xml_LastSyncTime = 'lst';
Xml_IsKeepDeleted = 'ikd';
Xml_KeepEditionCount = 'kec';
Xml_FileCount = 'fc';
Xml_ItemSize = 'is';
Xml_CompeltedSize = 'cs';
implementation
uses UMyBackupApiInfo;
{ TLocalDesItemWriteXml }
constructor TLocalDesItemWriteXml.Create(_DesPath: string);
begin
DesPath := _DesPath;
end;
function TLocalDesItemWriteXml.FindDesNode: Boolean;
var
i : Integer;
SelectNode : IXMLNode;
begin
Result := False;
for i := 0 to LocalDesItemListXml.ChildNodes.Count - 1 do
begin
SelectNode := LocalDesItemListXml.ChildNodes[i];
if MyXmlUtil.GetChildValue( SelectNode, Xml_DesPath ) = DesPath then
begin
Result := True;
DesNodeIndex := i;
DesNode := SelectNode;
Break;
end;
end;
end;
{ TLocalDesItemAddXml }
procedure TLocalDesItemAddXml.Update;
begin
// 已存在
if FindDesNode then
Exit;
DesNode := MyXmlUtil.AddListChild( LocalDesItemListXml );
MyXmlUtil.AddChild( DesNode, Xml_DesPath, DesPath );
end;
{ TLocalDesItemRemoveXml }
procedure TLocalDesItemRemoveXml.Update;
begin
if not FindDesNode then
Exit;
LocalDesItemListXml.ChildNodes.Delete( DesNodeIndex );
end;
{ TLocalBackupItemWriteXml }
function TLocalBackupItemWriteXml.FindBackupNode: Boolean;
var
i : Integer;
SelectNode : IXMLNode;
begin
Result := False;
BackupNodeList := nil;
if not FindBackupNodeList then
Exit;
for i := 0 to BackupNodeList.ChildNodes.Count - 1 do
begin
SelectNode := BackupNodeList.ChildNodes[i];
if MyXmlUtil.GetChildValue( SelectNode, Xml_BackupPath ) = BackupPath then
begin
Result := True;
BackupNodeIndex := i;
BackupNode := SelectNode;
Break;
end;
end;
end;
procedure TLocalBackupItemWriteXml.SetBackupPath(_BackupPath: string);
begin
BackupPath := _BackupPath;
end;
{ TLocalBackupWriteXml }
function TLocalBackupWriteXml.FindBackupNodeList: Boolean;
begin
Result := FindDesNode;
if Result then
BackupNodeList := MyXmlUtil.AddChild( DesNode, Xml_BackupItemList );
end;
{ TLocalBackupItemAddXml }
procedure TLocalBackupItemAddXml.SetAutoSyncInfo(_IsAutoSync: Boolean;
_LasSyncTime: TDateTime);
begin
IsAutoSync := _IsAutoSync;
LasSyncTime := _LasSyncTime;
end;
procedure TLocalBackupItemAddXml.SetBackupStatus(_IsDisable,
_IsBackupNow: Boolean);
begin
IsDisable := _IsDisable;
IsBackupNow := _IsBackupNow;
end;
procedure TLocalBackupItemAddXml.SetDeleteInfo(_IsKeepDeleted: Boolean;
_KeepEditionCount: Integer);
begin
IsKeepDeleted := _IsKeepDeleted;
KeepEditionCount := _KeepEditionCount;
end;
procedure TLocalBackupItemAddXml.SetIsFile(_IsFile: Boolean);
begin
IsFile := _IsFile;
end;
procedure TLocalBackupItemAddXml.SetSpaceInfo(_FileCount: Integer; _ItemSize,
_CompletedSize: Int64);
begin
FileCount := _FileCount;
ItemSize := _ItemSize;
CompletedSize := _CompletedSize;
end;
procedure TLocalBackupItemAddXml.SetSyncTimeInfo(_SyncTimeType,
_SyncTimeValue: Integer);
begin
SyncTimeType := _SyncTimeType;
SyncTimeValue := _SyncTimeValue;
end;
procedure TLocalBackupItemAddXml.Update;
begin
if FindBackupNode or ( BackupNodeList = nil ) then
Exit;
BackupNode := MyXmlUtil.AddListChild( BackupNodeList );
MyXmlUtil.AddChild( BackupNode, Xml_BackupPath, BackupPath );
MyXmlUtil.AddChild( BackupNode, Xml_IsFile, IsFile );
MyXmlUtil.AddChild( BackupNode, Xml_IsDisable, IsDisable );
MyXmlUtil.AddChild( BackupNode, Xml_IsBackupNow, IsBackupNow );
MyXmlUtil.AddChild( BackupNode, Xml_IsAutoSync, IsAutoSync );
MyXmlUtil.AddChild( BackupNode, Xml_SyncTimeType, SyncTimeType );
MyXmlUtil.AddChild( BackupNode, Xml_SyncTimeValue, SyncTimeValue );
MyXmlUtil.AddChild( BackupNode, Xml_LastSyncTime, LasSyncTime );
MyXmlUtil.AddChild( BackupNode, Xml_IsKeepDeleted, IsKeepDeleted );
MyXmlUtil.AddChild( BackupNode, Xml_KeepEditionCount, KeepEditionCount );
MyXmlUtil.AddChild( BackupNode, Xml_FileCount, FileCount );
MyXmlUtil.AddChild( BackupNode, Xml_ItemSize, ItemSize );
MyXmlUtil.AddChild( BackupNode, Xml_CompeltedSize, CompletedSize );
end;
{ TLocalBackupItemRemoveXml }
procedure TLocalBackupItemRemoveXml.Update;
begin
if not FindBackupNode then
Exit;
BackupNodeList.ChildNodes.Delete( BackupNodeIndex );
end;
{ TLocalBackupItemSetIsDisableXml }
procedure TLocalBackupItemSetIsDisableXml.SetIsDisable(_IsDisable: Boolean);
begin
IsDisable := _IsDisable;
end;
procedure TLocalBackupItemSetIsDisableXml.Update;
begin
if not FindBackupNode then
Exit;
MyXmlUtil.AddChild( BackupNode, Xml_IsDisable, IsDisable );
end;
{ TLocalBackupItemSetIsBackupNowXml }
procedure TLocalBackupItemSetIsBackupNowXml.SetIsBackupNow(
_IsBackupNow: Boolean);
begin
IsBackupNow := _IsBackupNow;
end;
procedure TLocalBackupItemSetIsBackupNowXml.Update;
begin
if not FindBackupNode then
Exit;
MyXmlUtil.AddChild( BackupNode, Xml_IsBackupNow, IsBackupNow );
end;
{ TLocalBackupItemSetLastSyncTimeXml }
procedure TLocalBackupItemSetLastSyncTimeXml.SetLastSyncTime(
_LastSyncTime: TDateTime);
begin
LastSyncTime := _LastSyncTime;
end;
procedure TLocalBackupItemSetLastSyncTimeXml.Update;
begin
inherited;
if not FindBackupNode then
Exit;
MyXmlUtil.AddChild( BackupNode, Xml_LastSyncTime, LastSyncTime );
end;
{ TLocalBackupItemSetAutoSyncXml }
procedure TLocalBackupItemSetAutoSyncXml.SetIsAutoSync(_IsAutoSync: Boolean);
begin
IsAutoSync := _IsAutoSync;
end;
procedure TLocalBackupItemSetAutoSyncXml.SetSyncInterval(_SyncTimeType,
_SyncTimeValue: Integer);
begin
SyncTimeType := _SyncTimeType;
SyncTimeValue := _SyncTimeValue;
end;
procedure TLocalBackupItemSetAutoSyncXml.Update;
begin
inherited;
if not FindBackupNode then
Exit;
end;
{ TNetworkDesItemWriteXml }
constructor TNetworkPcItemWriteXml.Create(_PcID: string);
begin
PcID := _PcID;
end;
function TNetworkPcItemWriteXml.FindPcNode: Boolean;
var
i : Integer;
SelectNode : IXMLNode;
begin
Result := False;
for i := 0 to NetworkDesItemListXml.ChildNodes.Count - 1 do
begin
SelectNode := NetworkDesItemListXml.ChildNodes[i];
if MyXmlUtil.GetChildValue( SelectNode, Xml_DesPath ) = PcID then
begin
Result := True;
PcNodeIndex := i;
PcNode := SelectNode;
Break;
end;
end;
end;
{ TNetworkDesItemAddXml }
procedure TNetworkPcItemAddXml.Update;
begin
// 已存在
if FindPcNode then
Exit;
PcNode := MyXmlUtil.AddListChild( NetworkDesItemListXml );
MyXmlUtil.AddChild( PcNode, Xml_DesPath, PcID );
end;
{ TNetworkDesItemRemoveXml }
procedure TNetworkPcItemRemoveXml.Update;
begin
if not FindPcNode then
Exit;
NetworkDesItemListXml.ChildNodes.Delete( PcNodeIndex );
end;
{ TNetworkBackupItemWriteXml }
function TNetworkBackupItemWriteXml.FindBackupNode: Boolean;
var
i : Integer;
SelectNode : IXMLNode;
begin
Result := False;
BackupNodeList := nil;
if not FindBackupNodeList then
Exit;
for i := 0 to BackupNodeList.ChildNodes.Count - 1 do
begin
SelectNode := BackupNodeList.ChildNodes[i];
if MyXmlUtil.GetChildValue( SelectNode, Xml_BackupPath ) = BackupPath then
begin
Result := True;
BackupNodeIndex := i;
BackupNode := SelectNode;
Break;
end;
end;
end;
procedure TNetworkBackupItemWriteXml.SetBackupPath(_BackupPath: string);
begin
BackupPath := _BackupPath;
end;
{ TNetworkBackupWriteXml }
function TNetworkBackupWriteXml.FindBackupNodeList: Boolean;
begin
Result := FindPcNode;
if Result then
BackupNodeList := MyXmlUtil.AddChild( PcNode, Xml_BackupItemList );
end;
{ TNetworkBackupItemAddXml }
procedure TNetworkBackupItemAddXml.SetAutoSync(_IsAutoSync: Boolean;
_LasSyncTime: TDateTime);
begin
IsAutoSync := _IsAutoSync;
LasSyncTime := _LasSyncTime;
end;
procedure TNetworkBackupItemAddXml.SetBackupStatus(_IsDisable,
_IsBackupNow: Boolean);
begin
IsDisable := _IsDisable;
IsBackupNow := _IsBackupNow;
end;
procedure TNetworkBackupItemAddXml.SetDeleteInfo(_IsKeepDeleted: Boolean;
_KeepEditionCount: Integer);
begin
IsKeepDeleted := _IsKeepDeleted;
KeepEditionCount := _KeepEditionCount;
end;
procedure TNetworkBackupItemAddXml.SetIsFile(_IsFile: Boolean);
begin
IsFile := _IsFile;
end;
procedure TNetworkBackupItemAddXml.SetSpaceInfo(_FileCount: Integer; _ItemSize,
_CompletedSize: Int64);
begin
FileCount := _FileCount;
ItemSize := _ItemSize;
CompletedSize := _CompletedSize;
end;
procedure TNetworkBackupItemAddXml.SetSyncInfo(_SyncTimeType,
_SyncTimeValue: Integer);
begin
SyncTimeType := _SyncTimeType;
SyncTimeValue := _SyncTimeValue;
end;
procedure TNetworkBackupItemAddXml.Update;
begin
if FindBackupNode or ( BackupNodeList = nil ) then
Exit;
BackupNode := MyXmlUtil.AddListChild( BackupNodeList );
MyXmlUtil.AddChild( BackupNode, Xml_BackupPath, BackupPath );
MyXmlUtil.AddChild( BackupNode, Xml_IsFile, IsFile );
MyXmlUtil.AddChild( BackupNode, Xml_IsDisable, IsDisable );
MyXmlUtil.AddChild( BackupNode, Xml_IsBackupNow, IsBackupNow );
MyXmlUtil.AddChild( BackupNode, Xml_IsAutoSync, IsAutoSync );
MyXmlUtil.AddChild( BackupNode, Xml_SyncTimeType, SyncTimeType );
MyXmlUtil.AddChild( BackupNode, Xml_SyncTimeValue, SyncTimeValue );
MyXmlUtil.AddChild( BackupNode, Xml_LastSyncTime, LasSyncTime );
MyXmlUtil.AddChild( BackupNode, Xml_IsKeepDeleted, IsKeepDeleted );
MyXmlUtil.AddChild( BackupNode, Xml_KeepEditionCount, KeepEditionCount );
MyXmlUtil.AddChild( BackupNode, Xml_FileCount, FileCount );
MyXmlUtil.AddChild( BackupNode, Xml_ItemSize, ItemSize );
MyXmlUtil.AddChild( BackupNode, Xml_CompeltedSize, CompletedSize );
end;
{ TNetworkBackupItemRemoveXml }
procedure TNetworkBackupItemRemoveXml.Update;
begin
if not FindBackupNode then
Exit;
BackupNodeList.ChildNodes.Delete( BackupNodeIndex );
end;
{ TNetworkBackupItemSetIsDisableXml }
procedure TNetworkBackupItemSetIsDisableXml.SetIsDisable(_IsDisable: Boolean);
begin
IsDisable := _IsDisable;
end;
procedure TNetworkBackupItemSetIsDisableXml.Update;
begin
if not FindBackupNode then
Exit;
MyXmlUtil.AddChild( BackupNode, Xml_IsDisable, IsDisable );
end;
{ TNetworkBackupItemSetIsBackupNowXml }
procedure TNetworkBackupItemSetIsBackupNowXml.SetIsBackupNow(
_IsBackupNow: Boolean);
begin
IsBackupNow := _IsBackupNow;
end;
procedure TNetworkBackupItemSetIsBackupNowXml.Update;
begin
if not FindBackupNode then
Exit;
MyXmlUtil.AddChild( BackupNode, Xml_IsBackupNow, IsBackupNow );
end;
{ TNetworkBackupItemSetLastSyncTimeXml }
procedure TNetworkBackupItemSetLastSyncTimeXml.SetLastSyncTime(
_LastSyncTime: TDateTime);
begin
LastSyncTime := _LastSyncTime;
end;
procedure TNetworkBackupItemSetLastSyncTimeXml.Update;
begin
inherited;
if not FindBackupNode then
Exit;
MyXmlUtil.AddChild( BackupNode, Xml_LastSyncTime, LastSyncTime );
end;
{ TNetworkBackupItemSetAutoSyncXml }
procedure TNetworkBackupItemSetAutoSyncXml.SetIsAutoSync(_IsAutoSync: Boolean);
begin
IsAutoSync := _IsAutoSync;
end;
procedure TNetworkBackupItemSetAutoSyncXml.SetSyncInterval(_SyncTimeType,
_SyncTimeValue: Integer);
begin
SyncTimeType := _SyncTimeType;
SyncTimeValue := _SyncTimeValue;
end;
procedure TNetworkBackupItemSetAutoSyncXml.Update;
begin
inherited;
if not FindBackupNode then
Exit;
end;
{ TLocalBackupXmlReadHandle }
procedure TLocalBackupReadXmlHandle.Update;
var
i : Integer;
DesItemNode : IXMLNode;
LocalBackupDesItemReadXml : TLocalBackupDesItemReadXml;
begin
for i := 0 to LocalDesItemListXml.ChildNodes.Count - 1 do
begin
DesItemNode := LocalDesItemListXml.ChildNodes[i];
LocalBackupDesItemReadXml := TLocalBackupDesItemReadXml.Create( DesItemNode );
LocalBackupDesItemReadXml.Update;
LocalBackupDesItemReadXml.Free;
end;
end;
{ TLocalBackupDesItemReadXml }
constructor TLocalBackupDesItemReadXml.Create(_DesItemNode: IXMLNode);
begin
DesItemNode := _DesItemNode;
end;
procedure TLocalBackupDesItemReadXml.ReadBackupItemList;
var
BackupItemList : IXMLNode;
i : Integer;
BackupItemNode : IXMLNode;
LocalBackupItemReadXml : TLocalBackupItemReadXml;
begin
BackupItemList := MyXmlUtil.AddChild( DesItemNode, Xml_BackupItemList );
for i := 0 to BackupItemList.ChildNodes.Count - 1 do
begin
BackupItemNode := BackupItemList.ChildNodes[i];
LocalBackupItemReadXml := TLocalBackupItemReadXml.Create( BackupItemNode );
LocalBackupItemReadXml.SetDesPath( DesPath );
LocalBackupItemReadXml.Update;
LocalBackupItemReadXml.Free;
end;
end;
procedure TLocalBackupDesItemReadXml.Update;
var
LocalBackupDesItemReadHandle : TLocalBackupDesItemReadHandle;
begin
DesPath := MyXmlUtil.GetChildValue( DesItemNode, Xml_DesPath );
// 读取 目标路径
LocalBackupDesItemReadHandle := TLocalBackupDesItemReadHandle.Create( DesPath );
LocalBackupDesItemReadHandle.Update;
LocalBackupDesItemReadHandle.Free;
// 读取 目标路径 的源路径
ReadBackupItemList;
end;
{ TLocalBackupItemReadXml }
constructor TLocalBackupItemReadXml.Create(_BackupItemNode: IXMLNode);
begin
BackupItemNode := _BackupItemNode;
end;
procedure TLocalBackupItemReadXml.SetDesPath(_DesPath: string);
begin
DesPath := _DesPath;
end;
procedure TLocalBackupItemReadXml.Update;
var
BackupPath : string;
IsFile : Boolean;
IsDisable, IsBackupNow : Boolean;
IsAutoSync : Boolean; // 是否自动同步
SyncTimeType, SyncTimeValue : Integer; // 同步间隔
LasSyncTime : TDateTime; // 上一次同步时间
IsKeepDeleted : Boolean;
KeepEditionCount : Integer;
FileCount : Integer;
ItemSize, CompletedSize : Int64; // 空间信息
begin
BackupPath := MyXmlUtil.GetChildValue( BackupItemNode, Xml_BackupPath );
IsFile := MyXmlUtil.GetChildBoolValue( BackupItemNode, Xml_IsFile );
IsDisable := MyXmlUtil.GetChildBoolValue( BackupItemNode, Xml_IsDisable );
IsBackupNow := MyXmlUtil.GetChildBoolValue( BackupItemNode, Xml_IsBackupNow );
IsAutoSync := MyXmlUtil.GetChildBoolValue( BackupItemNode, Xml_IsAutoSync );
SyncTimeType := MyXmlUtil.GetChildIntValue( BackupItemNode, Xml_SyncTimeType );
SyncTimeValue := MyXmlUtil.GetChildIntValue( BackupItemNode, Xml_SyncTimeValue );
LasSyncTime := MyXmlUtil.GetChildFloatValue( BackupItemNode, Xml_LastSyncTime );
IsKeepDeleted := MyXmlUtil.GetChildBoolValue( BackupItemNode, Xml_IsKeepDeleted );
KeepEditionCount := MyXmlUtil.GetChildIntValue( BackupItemNode, Xml_KeepEditionCount );
FileCount := MyXmlUtil.GetChildIntValue( BackupItemNode, Xml_FileCount );
ItemSize := MyXmlUtil.GetChildInt64Value( BackupItemNode, Xml_ItemSize );
CompletedSize := MyXmlUtil.GetChildInt64Value( BackupItemNode, Xml_CompeltedSize );
end;
end.
|
unit UListenTcpThread;
interface
uses
Windows,
Classes,
SysUtils,
WinSock,
eiTypes,
eiExceptions,
eiConstants,
UServerTypes,
UBaseThread;
type
TListenTcpThread = class(TBaseSocketThread)
private
FLocalAddr: TSockAddrIn;
FReceiveEvent: TRequestEvent;
procedure DoReceiveEvent(clientAddr: TSockAddrIn; clientSocket: TSocket);
public
constructor Create(logger: ILogger; listenPort: int);
destructor Destroy; override;
procedure Cancel;
procedure Execute; override;
property OnReceive: TRequestEvent read FReceiveEvent write FReceiveEvent;
end;
implementation
procedure TListenTcpThread.Cancel;
var
shutResult: int;
begin
FCancel := true;
Terminate;
shutResult := shutdown(FSocket, 2);
if shutResult = SOCKET_ERROR then
begin
FLogger.Log(GetLastErrorString(), 'Shutdown failed: %s');
end;
closesocket(FSocket);
WSACleanup();
end;
constructor TListenTcpThread.Create(logger: ILogger; listenPort: int);
var
code: int;
begin
inherited Create(true);
FLogger := logger;
try
ZeroMemory(@FWsaData, SizeOf(TWsaData));
code := WSAStartup(WINSOCK_VERSION, FWsaData);
if code <> 0 then
raise ESocketException.Create(GetLastErrorString());
FSocket := Socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if FSocket = INVALID_SOCKET then
raise ESocketException.Create(GetLastErrorString());
ZeroMemory(@FLocalAddr, SizeOf(FLocalAddr));
FLocalAddr.sin_family := AF_INET;
FLocalAddr.sin_port := htons(listenPort);
FLocalAddr.sin_addr.s_addr := INADDR_ANY;
code := bind(FSocket, FLocalAddr, SizeOf(FLocalAddr));
if code < 0 then
raise ESocketException.Create(GetLastErrorString());
code := listen(FSocket, 4);
if code = SOCKET_ERROR then
raise ESocketException.Create(GetLastErrorString());
FStarted := True;
FLogger.Log('Listen thread created on ' + IntToStr(listenPort) + ' TCP port');
except
on Ex: Exception do
FLogger.Log(Ex.Message, elError);
end;
end;
destructor TListenTcpThread.Destroy;
begin
if not FCancel then
Cancel;
FLogger.Log('Base thread destroyed.');
FLogger.Log('Listen thread destroyed');
inherited;
end;
procedure TListenTcpThread.DoReceiveEvent(clientAddr: TSockAddrIn; clientSocket: TSocket);
var
request: RequestStruct;
begin
if Assigned(FReceiveEvent) then
begin
request.Socket := clientSocket;
request.Target := clientAddr;
SetLength(request.Buffer, 0);
FReceiveEvent(Self, request);
end;
end;
procedure TListenTcpThread.Execute;
var
len: int;
FClientAddr: TSockAddrIn;
clientSocket: TSocket;
begin
while not Terminated and FStarted do
begin
try
clientSocket := INVALID_SOCKET;
len := SizeOf(TSockAddrIn);
clientSocket := accept(FSocket, @FClientAddr, @len);
if clientSocket = INVALID_SOCKET then
raise ESocketException.Create(GetLastErrorString());
FLogger.Log('Request from ' + inet_ntoa(FClientAddr.sin_addr) + ' : ' + IntToStr(FClientAddr.sin_port));
DoReceiveEvent(FClientAddr, clientSocket);
except
on Ex: Exception do
FLogger.Log(Ex.Message, elError);
end;
end;
end;
end.
|
{ ----------------------------------------------------------------------------
Copyright (C) 2005-2010 Jeroen Commandeur and Paul-Jan Pauptit
This file is part of DeleD CE (Community Edition)
DeleD CE is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Deled CE 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 Deled CE. If not, see <http://www.gnu.org/licenses/>.
---------------------------------------------------------------------------- }
unit frmSplashScreenForm;
{$MODE Delphi}
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls;
type
{ TSplashScreenForm }
TSplashScreenForm = class(TForm)
imgSplash: TImage;
lblInfo: TLabel;
procedure FormCreate(Sender: TObject);
private
procedure FadeOut;
public
procedure Hide;
end;
// Convenience methods for hiding the actual splash screen handling (conditional on defines) from any user code
procedure ShowSplashScreen;
procedure HideSplashScreen;
procedure SetSplashScreenStatus(const aMessage: string);
implementation
{$R *.lfm}
//uses
// unit_VersionInfo;
var
splashScreen: TSplashScreenForm;
procedure ShowSplashScreen;
begin
splashScreen := TSplashScreenForm.Create(Application);
splashScreen.Show;
splashScreen.Update;
end;
procedure HideSplashScreen;
begin
if Assigned(splashScreen) then begin
splashScreen.Hide;
splashScreen := nil;
end;
end;
procedure SetSplashScreenStatus(const aMessage: string);
begin
if Assigned(splashScreen) then begin
splashScreen.lblInfo.Caption := 'Centolla OBS ' + ' - ' + aMessage;
splashScreen.Update;
end;
end;
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
procedure TSplashScreenForm.FormCreate(Sender: TObject);
begin
lblInfo.Caption :='Iniciando...';
ClientWidth := imgSplash.Width;
ClientHeight := imgSplash.Height;
AlphaBlend := TRUE;
end;
procedure TSplashScreenForm.FadeOut;
var startTime: cardinal;
difference: integer;
value: integer;
isVisible: Boolean;
begin
startTime := GetTickCount;
isVisible := TRUE;
while isVisible do begin
difference := GetTickCount - startTime;
value := 255 - difference div 2;
if value < 0 then begin
isVisible := FALSE;
value := 0;
end;
AlphaBlendValue := value;
end;
end;
procedure TSplashScreenForm.hide;
begin
FadeOut;
inherited Hide;
Release;
end;
end.
|
unit main;
{$mode objfpc}{$H+}
interface
uses
fpjson,
stemmingnazief_lib, logutil_lib,
Classes, SysUtils, fpcgi, HTTPDefs, fastplaz_handler, html_lib, database_lib;
type
TMainModule = class(TMyCustomWebModule)
private
Stemming: TStemmingNazief;
procedure BeforeRequestHandler(Sender: TObject; ARequest: TRequest);
public
constructor CreateNew(AOwner: TComponent; CreateMode: integer); override;
destructor Destroy; override;
procedure Get; override;
procedure Post; override;
end;
implementation
uses json_lib, common;
constructor TMainModule.CreateNew(AOwner: TComponent; CreateMode: integer);
begin
inherited CreateNew(AOwner, CreateMode);
BeforeRequest := @BeforeRequestHandler;
Stemming := TStemmingNazief.Create;
Stemming.StandardWordCheck := True;
Stemming.LoadDictionaryFromFile(Config.GetValue(
'stemming/dictionary_file', STEMMINGNAZIEF_DICTIONARY_FILE));
Stemming.LoadNonStandardWordFromFile(Config.GetValue(
'stemming/nonstandardword_file', WORD_NONSTANDARD_FILE));
end;
destructor TMainModule.Destroy;
begin
Stemming.Free;
inherited Destroy;
end;
// Init First
procedure TMainModule.BeforeRequestHandler(Sender: TObject; ARequest: TRequest);
begin
Response.ContentType := 'application/json';
end;
// GET Method Handler
procedure TMainModule.Get;
begin
//---
Response.Content := '{}';
end;
// POST Method Handler
// CURL example:
// curl -X POST -H "Authorization: Basic dW5hbWU6cGFzc3dvcmQ=" "yourtargeturl"
procedure TMainModule.Post;
var
authstring: string;
body: string;
Text, stemmed_text: string;
Result: TStringList;
begin
Result := TStringList.Create;
body := Request.Content;
Text := _POST['text'];
stemmed_text := Stemming.ParseSentence(Text);
stemmed_text := StringReplace(stemmed_text, #13, '', [rfReplaceAll]);
stemmed_text := StringReplace(stemmed_text, #10, '', [rfReplaceAll]);
authstring := Header['Authorization'];
Result.Add('{');
Result.Add('"code": 0,');
Result.Add('"response": {');
Result.Add('"word_count": ' + i2s(Stemming.WordCount) + ',');
Result.Add('"nonstandardword_count": ' + i2s(Stemming.NonStandardWordCount) + ',');
Result.Add('"unknownword_count": ' + i2s(Stemming.UnknownWordCount) + ',');
Result.Add('"text": ' + stemmed_text + ',');
Result.Add('"time":"' + i2s(TimeUsage) + 'ms"');
Result.Add('}');
Result.Add('}');
with TLogUtil.Create do
begin
Add(Text, 'stemming');
Free;
end;
//---
CustomHeader['stemming_token'] := 'tototo';
Response.Content := JsonFormatter(Result.Text);
Result.Free;
end;
end.
|
// Copyright 2018 by John Kouraklis and Contributors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
unit Casbin.Effect.Types;
interface
type
TEffectResult = (erAllow, erIndeterminate, erDeny);
TEffectCondition = (ecSomeAllow, ecNotSomeDeny, ecSomeAllowANDNotDeny,
ecPriorityORDeny, ecUnknown);
TEffectArray = array of TEffectResult;
const
effectConditions: array [0..7] of string =
(('some(where(p.eft==allow))'), //Go-Style
('some(where(p.eft=allow))'), //Delphi-Style
('!some(where(p.eft==deny))'), //Go-Style
('not(some(where(p.eft=deny)))'), //Delphi-Style
('some(where(p.eft==allow))&&!some(where(p.eft==deny))'), //Go-Style
('some(where(p.eft=allow))and(not(some(where(p.eft=deny))))'), //Delphi-Style
('priority(p.eft)||deny'), // Go-Style
('priority(p.eft)ordeny')); //Delphi-style
implementation
end.
|
unit UBuildPowerpoint;
interface
uses
Windows, Classes, SysUtils, UITypes, PowerPoint_TLB,
UProject, USlide;
procedure BuildPowerpointSUBS(presentation: PowerPointPresentation; project: TProject);
procedure BuildPowerpoint(strFileName: string; project: TProject);
function ReplaceSpecials(strText: string; project: TProject; slide: TSlide): string;
implementation
uses
Office_TLB, Types, RegularExpressionsCore, Forms, ShellApi,
USourceInfo, GNUGetText, USourceBook,
UUtils, UUtilsStrings, USlideLayout, USettings, USourcePPT, UTempActions,
UUtilsFeedback,
UOverview, USlideTemplate, URibbon, URegexReplaceProperties;
type
TTagAction = (taBold, taItalic, taUnderline, taSuperscript, taSubscript, taColor, taSize, taBullet, taCenter);
var
gl_StartColorScheme: ColorScheme;
gl_StartDesign: Design;
function ReplaceSpecials(strText: string; project: TProject; slide: TSlide): string;
var
regex: TRegexReplaceProperties;
begin
regex := TRegexReplaceProperties.Create(project.Properties);
try
Result := regex.ReplaceWithProperties(strText);
finally
regex.Free;
end;
if Assigned(slide) then begin
regex := TRegexReplaceProperties.Create(slide.Variables);
try
Result := regex.ReplaceWithProperties(Result);
finally
regex.Free;
end;
end;
Result := StringReplace(Result, '%aftercollecte%', project.AfterCollecte, [rfReplaceAll, rfIgnoreCase]);
end;
function ReplaceAutomaticSmallNumbers(strText: string): string;
var
regex: TPerlRegEx;
begin
regex := TPerlRegEx.Create();
try
regex.Subject := strText;
regex.Options := [preMultiLine];
regex.RegEx := '\d+';
regex.Replacement := '<14>$&<14>';
regex.ReplaceAll;
Result := regex.Subject;
finally
regex.Free;
end;
end;
function ReplaceAutomaticNormalNumbers(strText: string): string;
var
regex: TPerlRegEx;
begin
regex := TPerlRegEx.Create();
try
regex.Subject := strText;
regex.Options := [preMultiLine];
regex.RegEx := '^\s*<14>(\d+)<14>\s*$';
regex.Replacement := '$1';
regex.ReplaceAll;
Result := regex.Subject;
finally
regex.Free;
end;
end;
// each row
procedure LayoutTextRange( txtrange: PowerPoint_TLB.TextRange; strTag: string;
action: TTagAction; clFontColor: TColor; iFontSize: integer);
var
startRange, endRange, withRange: PowerPoint_TLB.TextRange;
iStart: integer;
iStartRange, iEndRange: integer;
begin
iStart := 0;
while iStart >= 0 do begin
startRange := txtrange.Find(strTag, iStart, msoFalse, msoFalse);
if Assigned(startRange) and (startRange.Length > 0) then begin
iStartRange := startRange.Start - txtrange.Start + 1 + 3;
endRange := txtrange.Find(strTag, iStartRange, msoFalse, msoFalse);
if assigned(endRange) and (endRange.Length > 0) then begin
iEndRange := endRange.Start - txtrange.Start;
iStart := endRange.Start - txtrange.Start + 3;
end else begin
iEndRange := txtrange.Length;
iStart := -1; // stop
end;
withRange := txtrange.Characters(iStartRange, iEndRange - iStartRange + 1 );
case action of
taBold: withRange.Font.Bold := msoTrue;
taItalic: withRange.Font.Italic := msoTrue;
taUnderline: withRange.Font.Underline := msoTrue;
taSuperscript: withRange.Font.Superscript := msoTrue;
taSubscript: withRange.Font.Subscript := msoTrue;
taColor: withRange.Font.Color.RGB := clFontColor;
taSize: withRange.Font.Size := iFontSize;
taBullet: begin
withRange.ParagraphFormat.Bullet.type_ := ppBulletUnnumbered;
withRange.ParagraphFormat.Bullet.Visible := msoTrue;
end;
taCenter: withRange.ParagraphFormat.Alignment := ppAlignCenter;
end;
end else begin
iStart := -1; // stop
end;
end;
while txtrange.Replace(strTag, '', 0, msoFalse, msoFalse) <> nil do ;
end;
procedure LayoutTextFrame( txtframe: PowerPoint_TLB.TextFrame);
var
txtRange: TextRange;
// i: integer;
begin
// i := 1;
// txtRange := txtframe.TextRange.Lines(i, 1);
// txtRange := txtframe.TextRange.Paragraphs(i, 1);
txtRange := txtframe.TextRange;
// while assigned(txtRange) and (txtRange.Start <= txtframe.TextRange.Length) do begin
LayoutTextRange( txtRange, '<b>', taBold, 0, 0 );
LayoutTextRange( txtRange, '<i>', taItalic, 0, 0 );
LayoutTextRange( txtRange, '<u>', taUnderline, 0, 0 );
LayoutTextRange( txtRange, '<^>', taSuperscript, 0, 0 );
LayoutTextRange( txtRange, '<v>', taSubscript, 0, 0 );
LayoutTextRange( txtRange, '<center>', taCenter, 0, 0 );
LayoutTextRange( txtRange, '<red>', taColor, TColors.Red, 0 );
LayoutTextRange( txtRange, '<blue>', taColor, TColors.Blue, 0 );
LayoutTextRange( txtRange, '<black>', taColor, TColors.Black, 0 );
LayoutTextRange( txtRange, '<white>', taColor, TColors.White, 0 );
LayoutTextRange( txtRange, '<grey>', taColor, TColors.Grey, 0 );
LayoutTextRange( txtRange, '<green>', taColor, TColors.Green, 0 );
LayoutTextRange( txtRange, '<14>', taSize, 0, 14 * 2 );
LayoutTextRange( txtRange, '<28>', taSize, 0, 28 * 2 );
LayoutTextRange( txtRange, '<32>', taSize, 0, 32 * 2 );
LayoutTextRange( txtRange, '<36>', taSize, 0, 36 * 2 );
LayoutTextRange( txtRange, '<40>', taSize, 0, 40 * 2 );
LayoutTextRange( txtRange, '<44>', taSize, 0, 44 * 2 );
LayoutTextRange( txtRange, '<48>', taSize, 0, 48 * 2 );
LayoutTextRange( txtRange, '<52>', taSize, 0, 52 * 2 );
LayoutTextRange( txtRange, '<+>', taBullet, 0, 0 );
// inc(i);
//txtRange := txtframe.TextRange.Lines(i, 1);
// txtRange := txtframe.TextRange.Paragraphs(i, 1);
// end;
end;
procedure BuildSlide(presentation: PowerPointPresentation;
slide: TSlide; project: TProject; iCurrentSlide: integer);
var
iNewPPTSlideCount, iPPTSlide: integer;
pptSlide, pptSourceSlide: PowerPointSlide;
pptShape: PowerPoint_TLB.Shape;
strContentDir, strFileName: string;
strContentText: string;
slideItemContent, slideItemArea: TSlideItem;
layoutItem: TLayoutItem;
iTextWidth: integer;
rcArea: TRect;
iAreaIndex: integer;
strArea: string;
rectDestination, rectSource: TRect;
dScaleWidth, dScaleHeight: single;
overview: TOverview;
iFontSizeNeeded: integer;
ribbon: TRibbon;
strRibbonFileName: string;
sourceInfo, sourceInfoContent: TSourceInfo;
template, templateSub: TSlideTemplate;
slideSub: TSlide;
begin
strContentDir := GetSettings.GetContentDir;
template := GetSlideTemplates.FindByName(slide.SlideTemplateName);
if not Assigned(template) then
Exit;
// calculate nr of PPT slides
slideItemContent := slide['content'];
if not Assigned(slideItemContent) then begin
beep;
Exit;
end;
iNewPPTSlideCount := slideItemContent.ContentSources.Count;
if iNewPPTSlideCount = 0 then begin
beep;
Exit;
end;
ribbon := TRibbon.create(project, strContentDir);
try
for iPPTSlide := 1 to iNewPPTSlideCount do begin
sourceInfoContent := slideItemContent.ContentSources[iPPTSlide-1];
if ((slideItemContent.ContentType in [ctExtSlide])
or (sourceInfoContent.ContentTypeOverride and (sourceInfoContent.SourceType = sitPPT))
or ((epAllowExternalPPTs in template.EditPossibilities) and (iPPTSlide > 1))) then begin
if iPPTSlide <= slideItemContent.ContentSources.Count then begin
if (sourceInfoContent.FileName <> '') and (sourceInfoContent.SourceType = sitPPT) then begin
pptSourceSlide := GetCachedPPTs.GetSlide(sourceInfoContent);
if Assigned(pptSourceSlide) then begin
pptSourceSlide.Copy;
presentation.Slides.Paste(presentation.Slides.Count + 1);
pptSlide := presentation.Slides.Item(presentation.Slides.Count);
pptSlide.Design := pptSourceSlide.Design;
pptSlide.ColorScheme := pptSourceSlide.ColorScheme;
end;
end;
end;
end else if (sourceInfoContent.SourceType = sitTemplate) and (sourceInfoContent.Text = 'SUBS') then begin
BuildPowerpointSUBS(presentation, project);
end else if (sourceInfoContent.SourceType = sitTemplate) then begin
templateSub := GetSlideTemplates.FindByName(ReplaceSpecials(sourceInfoContent.Text, project, slide));
if Assigned(templateSub) then begin
slideSub := templateSub.DoOnAdd(false);
try
if Assigned(slideSub) then begin
slideSub.InternalHideRibbon := true;
BuildSlide(presentation, slideSub, project, iCurrentSlide );
end;
finally
slideSub.Free;
end;
end;
end else begin
pptSlide := presentation.Slides.Add(presentation.Slides.Count + 1, ppLayoutBlank);
pptSlide.FollowMasterBackground := msoFalse;
pptSlide.Background.Fill.Solid;
pptSlide.Background.Fill.ForeColor.RGB := 0;
if gl_StartColorScheme = nil then
gl_StartColorScheme := pptSlide.ColorScheme
else
pptSlide.ColorScheme := gl_StartColorScheme;
if gl_StartDesign = nil then
gl_StartDesign := pptSlide.Design
else
pptSlide.Design := gl_StartDesign;
layoutItem := slide.Layout['ribbon'];
if Assigned(layoutItem) and not slide.InternalHideRibbon then begin
strRibbonFileName := ribbon.Build(iCurrentSlide, layoutItem.Area);
end;
for iAreaIndex := 0 to slide.Count -1 do begin
strArea := slide.KeyOfIndex[iAreaIndex];
slideItemArea := slide[strArea];
layoutItem := slide.Layout[strArea];
if Assigned(slideItemArea) and (slideItemArea.ContentSources.Count > 0) and Assigned(layoutItem) and layoutItem.Visible then begin
// use last available ContentText item
if iPPTSlide <= slideItemArea.ContentSources.Count then
sourceInfo := slideItemArea.ContentSources[iPPTSlide -1]
else
sourceInfo := slideItemArea.ContentSources[slideItemArea.ContentSources.Count -1];
if slideItemArea.ContentType in [ctPicture, ctPictureFit, ctRibbon] then begin
if slideItemArea.ContentType in [ctRibbon] then begin
strFileName := strRibbonFileName;
end else begin
if sourceInfo.SourceType = sitPPT then begin
strFileName := GetTempDir + 'shape-5A257AC3-73C8-472E-A424-85D08C0A43FD.png';
pptShape := GetCachedPPTs.GetShape(sourceInfo);
if Assigned(pptShape) then begin
pptShape.Export(strFileName, ppShapeFormatPNG, round(pptShape.Width), round(pptShape.Height), ppScaleToFit);
end else begin
continue;
end;
end else begin
strFileName := Getsettings.DirExplode(sourceInfo.FileName);
end;
end;
rectDestination := layoutItem.Area;
if slideItemArea.ContentType in [ctPictureFit, ctRibbon] then begin
rectSource := ReadImageSize(strFileName);
dScaleWidth := rectSource.Width / rectDestination.Width;
dScaleHeight := rectSource.Height / rectDestination.Height;
if dScaleWidth < dScaleHeight then begin
rectDestination.Left := layoutItem.Area.CenterPoint.X - trunc((rectSource.Width / dScaleHeight) / 2);
rectDestination.Right := rectDestination.Left + trunc((rectSource.Width / dScaleHeight) );
end else if dScaleWidth > dScaleHeight then begin
rectDestination.Top := layoutItem.Area.CenterPoint.Y - trunc((rectSource.Height / dScaleWidth) / 2);
rectDestination.Bottom := rectDestination.Top + trunc((rectSource.Height / dScaleWidth) );
end;
end;
if FileExists(strFileName) then begin
pptShape := pptSlide.Shapes.AddPicture(strFileName, msoFalse, msoTrue,
rectDestination.Left, rectDestination.Top,
rectDestination.Width, rectDestination.Height);
end;
end else if slideItemArea.ContentType in [ctText, ctTextMemo, ctOverview, ctOverviewSubs, ctSubtitle] then begin
if sourceInfo.SourceType = sitBook then begin
strContentText := GetCachedBooks.GetVerse(sourceInfo);
end else begin
strContentText := sourceInfo.Text;
end;
if slide.AutomaticSmallNumbers and (strArea = 'content') then begin
strContentText := ReplaceAutomaticSmallNumbers(strContentText);
strContentText := ReplaceAutomaticNormalNumbers(strContentText);
end;
iFontSizeNeeded := layoutItem.FontSize;
rcArea := layoutItem.Area;
if layoutItem.Autosize then begin
iTextWidth := layoutItem.TextWidth(strContentText);
case layoutItem.AreaAlignment of
alCenter: begin
rcArea.Left := layoutItem.Area.Left + iTextWidth div 2;
rcArea.Width := iTextWidth;
end;
alRight: begin
rcArea.Left := layoutItem.Area.Right - iTextWidth;
end;
end;
rcArea.Width := iTextWidth;
end;
if layoutItem.UseBackground then begin
pptShape := pptSlide.Shapes.AddShape(msoShapeRectangle,
rcArea.Left, rcArea.Top,
rcArea.Width, rcArea.Height);
pptShape.Fill.Solid;
pptShape.Fill.ForeColor.RGB := layoutItem.BackgroundColor;
pptShape.Line.Visible := msoFalse;
end else begin
pptShape := pptSlide.Shapes.AddTextbox(msoTextOrientationHorizontal,
rcArea.Left, rcArea.Top,
rcArea.Width, rcArea.Height);
// if layoutItem.Autosize then begin
// pptShape.TextFrame.AutoSize := ppAutoSizeShapeToFitText
// end else
pptShape.TextFrame.AutoSize := ppAutoSizeNone;
end;
if slideItemArea.ContentType in [ctOverview, ctOverviewSubs] then begin
overview := TOverview.create(project);
try
strContentText := overview.Build(iCurrentSlide, slide, slideItemArea.ContentType = ctOverviewSubs, iFontSizeNeeded);
finally
overview.Free;
end;
pptShape.TextFrame.Ruler.TabStops.Add(ppTabStopLeft, CTABSTOP1);
pptShape.TextFrame.Ruler.TabStops.Add(ppTabStopLeft, 170);
end;
pptShape.TextFrame.TextRange.Text := ReplaceSpecials(strContentText, project, slide);
pptShape.TextFrame.TextRange.Font.Color.RGB := layoutItem.FontColor;
pptShape.TextFrame.TextRange.Font.Name := GetSettings.FontName;
pptShape.TextFrame.TextRange.Font.Size := iFontSizeNeeded;
if layoutItem.Autosize then begin
pptShape.TextFrame.TextRange.ParagraphFormat.Alignment := ppAlignCenter;
end else begin
case layoutItem.AreaAlignment of
alLeft: pptShape.TextFrame.TextRange.ParagraphFormat.Alignment := ppAlignLeft;
alCenter: pptShape.TextFrame.TextRange.ParagraphFormat.Alignment := ppAlignCenter;
alRight: pptShape.TextFrame.TextRange.ParagraphFormat.Alignment := ppAlignRight;
end;
end;
// if (slideItem.ContentType <> ctOverview) and (slide.OverviewType in [otIgnore]) then begin
// pptShape.TextFrame.Ruler.Levels.Item(1).LeftMargin := 20;
// pptShape.TextFrame.Ruler.Levels.Item(1).FirstMargin := 0;
// end;
LayoutTextFrame(pptShape.TextFrame);
end;
end;
end;
end;
end;
finally
ribbon.Free;
end;
end;
procedure BuildPowerpointSUBS(presentation: PowerPointPresentation; project: TProject);
var
i: integer;
slide: TSlide;
slideOverview: TSlide;
template: TSlideTemplate;
begin
template := GetSlideTemplates.FindByName(CTEMPLATE_OVERVIEW_SUBS);
slideOverview := template.DoOnAdd(false);
try
for i := 0 to project.Slides.Count -1 do begin
slide := TSlide.Create(project.Slides[i]);
try
if slide.IsSubOverview then begin
slide.InternalHideRibbon := true;
BuildSlide(presentation, slide, project, i);
if slide.OverviewType in [otSong] then begin
BuildSlide(presentation, slideOverview, project, i+1);
end;
end;
finally
slide.Free;
end;
end;
finally
slideOverview.Free;
end;
end;
procedure BuildPowerpoint(strFileName: string; project: TProject);
var
app: PowerPointApplication;
presentation: PowerPointPresentation;
i: Integer;
slide, slideNext: TSlide;
slideOverview: TSlide;
template, templateNext: TSlideTemplate;
feedback: TFeedbackForm;
begin
SetWaitCursor();
feedback := TFeedbackForm.CreateNew(Application.MainForm);
try
feedback.PB_Max := project.Slides.Count;
feedback.Show;
feedback.MessageString := _('Create Powerpoint...');
app := CoPowerPointApplication.Create;
presentation := app.Presentations.Add(msoFalse);
gl_StartColorScheme := nil;
gl_StartDesign := nil;
project.AfterCollecte := '$$$';
// presentation.PageSetup.SlideSize := ppSlideSizeCustom;
presentation.PageSetup.SlideSize := ppSlideSizeOnScreen16x9; // 720x540
presentation.PageSetup.SlideWidth := 1920;
presentation.PageSetup.SlideHeight := 1080;
presentation.PageSetup.FirstSlideNumber := 1;
presentation.PageSetup.SlideOrientation := msoOrientationHorizontal;
presentation.PageSetup.NotesOrientation := msoOrientationVertical;
template := GetSlideTemplates.FindByName(CTEMPLATE_OVERVIEW);
slideOverview := template.DoOnAdd(false);
try
BuildSlide(presentation, slideOverview, project, -1);
for i := 0 to project.Slides.Count -1 do begin
feedback.PB_Position := i;
slide := TSlide.Create(project.Slides[i]);
try
if slide.IsSubOverview then begin
continue;
end;
templateNext := nil;
if (i+1) < project.Slides.Count -1 then begin
slideNext := TSlide.Create(project.Slides[i+1]);
try
templateNext := nil;
if Assigned(slideNext) then begin
templateNext := GetSlideTemplates.FindByName(slideNext.SlideTemplateName);
end;
finally
slideNext.Free;
end;
end;
BuildSlide(presentation, slide, project, i);
template := GetSlideTemplates.FindByName(slide.SlideTemplateName);
if not (Assigned(templateNext) and templateNext.NoPreviousOverview) and Assigned(template) and template.FollowedByOverview then begin
BuildSlide(presentation, slideOverview, project, i+1);
end;
finally
slide.Free;
end;
end;
finally
slideOverview.Free;
end;
finally
feedback.Free;
end;
presentation.SaveAs(strFileName, ppSaveAsPresentation, msoFalse );
presentation.Close;
presentation := nil;
app.Quit;
app := nil;
Application.ProcessMessages;
if FileExists(strFileName) then
ShellExecute(0, '', PChar(strFileName), '', '', SW_SHOWNORMAL);
end;
end.
|
{
ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi
Copyright (c) 2016, Isaque Pinheiro
All rights reserved.
GNU Lesser General Public License
Versão 3, 29 de junho de 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
A todos é permitido copiar e distribuir cópias deste documento de
licença, mas mudá-lo não é permitido.
Esta versão da GNU Lesser General Public License incorpora
os termos e condições da versão 3 da GNU General Public License
Licença, complementado pelas permissões adicionais listadas no
arquivo LICENSE na pasta principal.
}
{ @abstract(ORMBr Framework.)
@created(20 Jul 2016)
@author(Isaque Pinheiro <isaquepsp@gmail.com>)
@author(Skype : ispinheiro)
@abstract(Website : http://www.ormbr.com.br)
@abstract(Telagram : https://t.me/ormbr)
ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi.
}
unit ormbr.objects.manager;
interface
uses
DB,
Rtti,
Types,
Classes,
SysUtils,
Variants,
Generics.Collections,
/// ormbr
ormbr.criteria,
ormbr.types.mapping,
ormbr.mapping.classes,
ormbr.command.factory,
ormbr.factory.interfaces,
ormbr.mapping.explorer,
ormbr.objects.manager.abstract,
ormbr.mapping.explorerstrategy;
type
TObjectManager<M: class, constructor> = class sealed(TObjectManagerAbstract<M>)
private
FOwner: TObject;
FObjectInternal: M;
procedure FillAssociation(AObject: M);
protected
FConnection: IDBConnection;
/// <summary>
/// Fábrica de comandos a serem executados
/// </summary>
FDMLCommandFactory: TDMLCommandFactoryAbstract;
/// <summary>
/// Controle de paginação vindo do banco de dados
/// </summary>
FPageSize: Integer;
procedure ExecuteOneToOne(AObject: TObject; AProperty: TRttiProperty;
AAssociation: TAssociationMapping); override;
procedure ExecuteOneToMany(AObject: TObject; AProperty: TRttiProperty;
AAssociation: TAssociationMapping); override;
function FindSQLInternal(const ASQL: String): TObjectList<M>; override;
public
constructor Create(const AOwner: TObject; const AConnection: IDBConnection;
const APageSize: Integer); override;
destructor Destroy; override;
procedure InsertInternal(const AObject: M); override;
procedure UpdateInternal(const AObject: TObject; const AModifiedFields: TList<string>); override;
procedure DeleteInternal(const AObject: M); override;
procedure NextPacketList(const AObjectList: TObjectList<M>); override;
function SelectInternalAll: IDBResultSet; override;
function SelectInternalID(const AID: Variant): IDBResultSet; override;
function SelectInternal(const ASQL: String): IDBResultSet; override;
function SelectInternalWhere(const AWhere: string; const AOrderBy: string): string; override;
function GetDMLCommand: string; override;
function Find: TObjectList<M>; overload; override;
function Find(const AID: Variant): M; overload; override;
function FindWhere(const AWhere: string; const AOrderBy: string): TObjectList<M>; override;
function ExistSequence: Boolean; override;
function NextPacket: IDBResultSet; override;
end;
implementation
uses
ormbr.objectset.bind,
ormbr.types.database,
ormbr.objects.helper,
ormbr.mapping.attributes,
ormbr.mapping.rttiutils,
ormbr.session.abstract,
ormbr.rtti.helper;
{ TObjectManager<M> }
constructor TObjectManager<M>.Create(const AOwner: TObject; const AConnection: IDBConnection;
const APageSize: Integer);
begin
FOwner := AOwner;
FPageSize := APageSize;
if not (AOwner is TSessionAbstract<M>) then
raise Exception.Create('O Object Manager não deve ser instênciada diretamente, use as classes TSessionObject<M> ou TSessionDataSet<M>');
FConnection := AConnection;
FExplorer := TMappingExplorer.GetInstance;
FObjectInternal := M.Create;
/// <summary>
/// Fabrica de comandos SQL
/// </summary>
FDMLCommandFactory := TDMLCommandFactory.Create(FObjectInternal,
AConnection,
AConnection.GetDriverName);
end;
destructor TObjectManager<M>.Destroy;
begin
FExplorer := nil;
FDMLCommandFactory.Free;
FObjectInternal.Free;
inherited;
end;
procedure TObjectManager<M>.DeleteInternal(const AObject: M);
begin
FDMLCommandFactory.GeneratorDelete(AObject);
end;
function TObjectManager<M>.SelectInternalAll: IDBResultSet;
begin
Result := FDMLCommandFactory.GeneratorSelectAll(M, FPageSize);
end;
function TObjectManager<M>.SelectInternalID(const AID: Variant): IDBResultSet;
begin
Result := FDMLCommandFactory.GeneratorSelectID(M, AID);
end;
function TObjectManager<M>.SelectInternalWhere(const AWhere: string;
const AOrderBy: string): string;
begin
Result := FDMLCommandFactory.GeneratorSelectWhere(M, AWhere, AOrderBy, FPageSize);
end;
procedure TObjectManager<M>.FillAssociation(AObject: M);
var
LAssociationList: TAssociationMappingList;
LAssociation: TAssociationMapping;
begin
LAssociationList := FExplorer.GetMappingAssociation(AObject.ClassType);
if LAssociationList <> nil then
begin
for LAssociation in LAssociationList do
begin
if LAssociation.Multiplicity in [OneToOne, ManyToOne] then
ExecuteOneToOne(AObject, LAssociation.PropertyRtti, LAssociation)
else
if LAssociation.Multiplicity in [OneToMany, ManyToMany] then
ExecuteOneToMany(AObject, LAssociation.PropertyRtti, LAssociation);
end;
end;
end;
procedure TObjectManager<M>.ExecuteOneToOne(AObject: TObject; AProperty: TRttiProperty;
AAssociation: TAssociationMapping);
var
LResultSet: IDBResultSet;
begin
LResultSet := FDMLCommandFactory.GeneratorSelectOneToOne(AObject,
AProperty.PropertyType.AsInstance.MetaclassType,
AAssociation);
try
while LResultSet.NotEof do
begin
TBindObject.GetInstance.SetFieldToProperty(LResultSet,
AProperty.GetNullableValue(AObject).AsObject,
AAssociation);
end;
finally
LResultSet.Close;
end;
end;
procedure TObjectManager<M>.ExecuteOneToMany(AObject: TObject; AProperty: TRttiProperty;
AAssociation: TAssociationMapping);
var
LPropertyType: TRttiType;
LPropertyObject: TObject;
LResultSet: IDBResultSet;
begin
LPropertyType := AProperty.PropertyType;
LPropertyType := AProperty.GetTypeValue(LPropertyType);
LResultSet := FDMLCommandFactory.GeneratorSelectOneToMany(AObject,
LPropertyType.AsInstance.MetaclassType,
AAssociation);
try
while LResultSet.NotEof do
begin
/// <summary>
/// Instancia o objeto da lista
/// </summary>
LPropertyObject := LPropertyType.AsInstance.MetaclassType.Create;
/// <summary>
/// Preenche o objeto com os dados do ResultSet
/// </summary>
TBindObject.GetInstance.SetFieldToProperty(LResultSet, LPropertyObject, AAssociation);
/// <summary>
/// Adiciona o objeto a lista
/// </summary>
TRttiSingleton.GetInstance.MethodCall(AProperty.GetNullableValue(AObject).AsObject,'Add',[LPropertyObject]);
end;
finally
LResultSet.Close;
end;
end;
function TObjectManager<M>.ExistSequence: Boolean;
begin
Result := FDMLCommandFactory.ExistSequence;
end;
function TObjectManager<M>.GetDMLCommand: string;
begin
Result := FDMLCommandFactory.GetDMLCommand;
end;
function TObjectManager<M>.NextPacket: IDBResultSet;
begin
Result := FDMLCommandFactory.GeneratorNextPacket;
if Result.FetchingAll then
FFetchingRecords := True;
end;
procedure TObjectManager<M>.NextPacketList(const AObjectList: TObjectList<M>);
var
LResultSet: IDBResultSet;
begin
LResultSet := NextPacket;
try
while LResultSet.NotEof do
begin
AObjectList.Add(M.Create);
TBindObject.GetInstance.SetFieldToProperty(LResultSet, TObject(AObjectList.Last));
/// <summary>
/// Alimenta registros das associações existentes 1:1 ou 1:N
/// </summary>
FillAssociation(AObjectList.Last);
end;
finally
/// <summary>
/// Fecha o DataSet interno para limpar os dados dele da memória.
/// </summary>
LResultSet.Close;
end;
end;
function TObjectManager<M>.SelectInternal(const ASQL: String): IDBResultSet;
begin
Result := FDMLCommandFactory.GeneratorSelect(ASQL, FPageSize);
end;
procedure TObjectManager<M>.UpdateInternal(const AObject: TObject; const AModifiedFields: TList<string>);
begin
FDMLCommandFactory.GeneratorUpdate(AObject, AModifiedFields);
end;
procedure TObjectManager<M>.InsertInternal(const AObject: M);
begin
FDMLCommandFactory.GeneratorInsert(AObject);
end;
function TObjectManager<M>.FindSQLInternal(const ASQL: String): TObjectList<M>;
var
LResultSet: IDBResultSet;
begin
Result := TObjectList<M>.Create;
if ASQL = '' then
LResultSet := SelectInternalAll
else
LResultSet := SelectInternal(ASQL);
try
while LResultSet.NotEof do
begin
TBindObject.GetInstance.SetFieldToProperty(LResultSet, TObject(Result.Items[Result.Add(M.Create)]));
/// <summary>
/// Alimenta registros das associações existentes 1:1 ou 1:N
/// </summary>
FillAssociation(Result.Items[Result.Count -1]);
end;
finally
LResultSet.Close;
end;
end;
function TObjectManager<M>.Find: TObjectList<M>;
begin
Result := FindSQLInternal('');
end;
function TObjectManager<M>.Find(const AID: Variant): M;
var
LResultSet: IDBResultSet;
begin
LResultSet := SelectInternalID(AID);
try
if LResultSet.RecordCount = 1 then
begin
Result := M.Create;
TBindObject.GetInstance.SetFieldToProperty(LResultSet, TObject(Result));
/// <summary>
/// Alimenta registros das associações existentes 1:1 ou 1:N
/// </summary>
FillAssociation(Result);
end
else
Result := nil;
finally
/// <summary>
/// Fecha o DataSet interno para limpar os dados dele da memória.
/// </summary>
LResultSet.Close;
end;
end;
function TObjectManager<M>.FindWhere(const AWhere: string;
const AOrderBy: string): TObjectList<M>;
begin
Result := FindSQLInternal(SelectInternalWhere(AWhere, AOrderBy));
end;
end.
|
unit delphiDatadog.serviceCheck;
interface
uses
delphiDatadog.header;
type
TDataDogServiceCheck = class(TObject)
private
FName: string;
FHostname: string;
FStatus: TDataDogServiceStatus;
FRunId: Integer;
FTimeStamp: Cardinal;
FTags: TDataDogTags;
FMessageText: string;
FPort: Integer;
procedure SetHostname(const Value: string);
procedure SetPort(const Value: Integer);
public
constructor Create;
function ToStatsDString: string;
property Name: string read FName write FName;
property Hostname: string read FHostname write SetHostname;
property Port: Integer read FPort write SetPort;
property Status: TDataDogServiceStatus read FStatus write FStatus;
property MessageText: string read FMessageText write FMessageText;
property RunId: Integer read FRunId write FRunId;
property TimeStamp: Cardinal read FTimeStamp write FTimeStamp;
property Tags: TDataDogTags read FTags write FTags;
end;
implementation
uses
System.SysUtils, delphiDatadog.utils;
const
STAND_PORT = 8125;
STAND_HOST = 'localhost';
{ TDataDogServiceCheck }
constructor TDataDogServiceCheck.Create;
begin
FHostname := STAND_HOST;
FStatus := dssUndefined;
FPort := STAND_PORT;
end;
procedure TDataDogServiceCheck.SetHostname(const Value: string);
begin
if Value.IsEmpty then
FHostname := STAND_HOST
else
FHostname := Value;
end;
procedure TDataDogServiceCheck.SetPort(const Value: Integer);
begin
if Value = 0 then
FPort := STAND_PORT
else
FPort := Value;
end;
function TDataDogServiceCheck.ToStatsDString: string;
var
StatsString: TStringBuilder;
begin
StatsString := TStringBuilder.Create;
StatsString.Append(Format('_sc|%s|%d', [Name, Ord(Status)]));
if (Timestamp > 0) then
StatsString.Append(Format('|d:%d', [Timestamp]));
if not (HostName.IsEmpty) then
StatsString.Append(Format('|h:%s', [Hostname]));
StatsString.Append(DataTagsToText(Tags));
if (not MessageText.IsEmpty) then
StatsString.Append(Format('|m:%s', [EscapedMessage(MessageText)]));
Result := StatsString.ToString;
StatsString.Free;
end;
end.
|
unit qplugins_qworker;
{ 本单元是QWorker的插件宿主版实现,服务将被注册到/Services/QWorker
}
interface
uses classes, sysutils, syncobjs, qworker, qstring, qplugins, qplugins_params,
qplugins_base;
type
{$HPPEMIT '#pragma link "qplugins_qworker"'}
TJobCallback = class
private
FCallback: IQJobCallback;
FParams: IQParams;
public
constructor Create(ACallback: IQJobCallback; AParams: IQParams); overload;
end;
TQForJobManager = class(TInterfacedObject, IQForJobManager)
private
FManager: TQForJobs;
public
constructor Create(AMgr: TQForJobs); overload;
destructor Destroy; override;
procedure BreakIt; stdcall;
function GetStartIndex: Int64; stdcall;
function GetStopIndex: Int64; stdcall;
function GetBreaked: Boolean; stdcall;
function GetRuns: Int64; stdcall;
function GetTotalTime: Int64; stdcall;
function GetAvgTime: Int64; stdcall;
end;
TForJobCallback = class
private
FCallback: IQForJobCallback;
FParams: IQParams;
FManager: IQForJobManager;
public
constructor Create(ACallback: IQForJobCallback; AParams: IQParams);
overload;
end;
TQWorkerBaseService = class(TQService)
protected
procedure DoJob(AJob: PQJob);
end;
TQWorkerService = class(TQWorkerBaseService, IQWorkers)
protected
procedure DoSignalJob(AJob: PQJob);
procedure DoForJob(ALoopMgr: TQForJobs; AJob: PQJob; AIndex: NativeInt);
function Post(AJob: IQJobCallback; AParams: IQParams;
ARunInMainThread: Boolean): Int64; stdcall;
function Timer(AJob: IQJobCallback; AInterval: Cardinal; AParams: IQParams;
ARunInMainThread: Boolean): Int64; stdcall;
function Delay(AJob: IQJobCallback; AParams: IQParams; ADelay: Int64;
ARunInMainThread, AIsRepeat: Boolean): Int64; stdcall;
function At(AJob: IQJobCallback; AParams: IQParams; ATime: TDateTime;
AInterval: Cardinal; ARunInMainThread: Boolean): Int64; stdcall;
function Plan(AJob: IQJobCallback; AParams: IQParams; APlan: PWideChar;
ARunInMainThread: Boolean): Int64; stdcall;
procedure &For(AJob: IQForJobCallback; AParams: IQParams;
AStart, AStop: Int64; AMsgWait: Boolean); stdcall;
procedure Clear(AHandle: Int64; AWaitRunningDone: Boolean); stdcall;
function CreateJobGroup(AByOrder: Boolean): IQJobGroup; stdcall;
procedure SetWorkers(const AMinWorkers, AMaxWorkers: Integer); stdcall;
procedure PeekCurrentWorkers(var ATotal, AIdle, ABusy: Integer); stdcall;
function RegisterSignal(const ASignal: PWideChar): Integer; stdcall;
function WaitSignal(const ASignal: PWideChar; AJob: IQJobCallback;
ARunInMainThread: Boolean): Int64; stdcall;
procedure Signal(const ASignal: PWideChar; AParams: IQParams);
//
function _CreateJobGroup(AByOrder: Boolean): StandInterfaceResult; stdcall;
end;
TQJobGroupService = class(TQWorkerBaseService, IQJobGroup)
protected
FGroup: TQJobGroup;
FAfterDone: IQNotifyCallback;
FFreeAfterDone: Boolean;
procedure DoGroupDone(ASender: TObject);
procedure Cancel(AWaitRunningDone: Boolean = true); stdcall;
procedure Prepare; stdcall;
procedure Run(ATimeout: Cardinal = INFINITE); stdcall;
function Insert(AIndex: Integer; AJob: IQJobCallback; AParams: IQParams;
ARunInMainThread: Boolean): Boolean; stdcall;
function Add(AJob: IQJobCallback; AParams: IQParams; AInMainThread: Boolean)
: Boolean; stdcall;
function Wait(ABlockMessage: Boolean; ATimeout: Cardinal = INFINITE)
: TWaitResult; overload;
function GetCount: Integer; stdcall;
procedure SetAfterDone(AValue: IQNotifyCallback); stdcall;
function GetAfterDone: IQNotifyCallback; stdcall;
function GetByOrder: Boolean; stdcall;
function GetRuns: Integer; stdcall;
function GetMaxWorkers: Integer; stdcall;
procedure SetMaxWorkers(const AValue: Integer); stdcall;
function _GetAfterDone: StandInterfaceResult; stdcall;
public
constructor Create(AByOrder: Boolean); overload;
destructor Destroy; override;
end;
implementation
type
TSignalJobWaiter = class
protected
FCallback: IQJobCallback;
public
constructor Create(ACallback: IQJobCallback);
end;
{ TQWorkerService }
function TQWorkerService.At(AJob: IQJobCallback; AParams: IQParams;
ATime: TDateTime; AInterval: Cardinal; ARunInMainThread: Boolean): Int64;
begin
Result := Workers.At(DoJob, ATime, AInterval, TJobCallback.Create(AJob,
AParams), ARunInMainThread, jdfFreeAsObject);
end;
procedure TQWorkerService.Clear(AHandle: Int64; AWaitRunningDone: Boolean);
begin
Workers.ClearSingleJob(AHandle, AWaitRunningDone);
end;
function TQWorkerService.CreateJobGroup(AByOrder: Boolean): IQJobGroup;
begin
Result := TQJobGroupService.Create;
end;
function TQWorkerService.Delay(AJob: IQJobCallback; AParams: IQParams;
ADelay: Int64; ARunInMainThread, AIsRepeat: Boolean): Int64;
begin
Result := Workers.Delay(DoJob, ADelay, TJobCallback.Create(AJob, AParams),
ARunInMainThread, jdfFreeAsObject, AIsRepeat);
end;
procedure TQWorkerService.DoForJob(ALoopMgr: TQForJobs; AJob: PQJob;
AIndex: NativeInt);
var
ACallback: TForJobCallback;
begin
ACallback := TForJobCallback(AJob.Data);
if Assigned(ACallback.FCallback) then
ACallback.FCallback.DoJob(ACallback.FManager, AIndex, ACallback.FParams);
end;
procedure TQWorkerService.DoSignalJob(AJob: PQJob);
var
AWaiter: TSignalJobWaiter;
begin
AWaiter := TSignalJobWaiter(AJob.Source.Data);
AWaiter.FCallback.DoJob(IQParams(AJob.Data));
end;
procedure TQWorkerService.&For(AJob: IQForJobCallback; AParams: IQParams;
AStart, AStop: Int64; AMsgWait: Boolean);
var
ALooper: TQForJobs;
ACallback: TForJobCallback;
begin
ACallback := TForJobCallback.Create(AJob, AParams);
ALooper := TQForJobs.Create(AStart, AStop, ACallback, jdfFreeAsObject);
ACallback.FManager := TQForJobManager.Create(ALooper);
ALooper.Run(DoForJob, AMsgWait);
end;
procedure TQWorkerService.PeekCurrentWorkers(var ATotal, AIdle, ABusy: Integer);
begin
ATotal := Workers.Workers;
AIdle := Workers.IdleWorkers;
ABusy := Workers.BusyWorkers;
end;
function TQWorkerService.Plan(AJob: IQJobCallback; AParams: IQParams;
APlan: PWideChar; ARunInMainThread: Boolean): Int64;
begin
Result := Workers.Plan(DoJob, APlan, TJobCallback.Create(AJob, AParams),
ARunInMainThread, jdfFreeAsObject);
end;
function TQWorkerService.Post(AJob: IQJobCallback; AParams: IQParams;
ARunInMainThread: Boolean): Int64;
begin
Result := Workers.Post(DoJob, TJobCallback.Create(AJob, AParams),
ARunInMainThread, jdfFreeAsObject);
end;
function TQWorkerService.RegisterSignal(const ASignal: PWideChar): Integer;
begin
Result := Workers.RegisterSignal(ASignal);
end;
procedure TQWorkerService.SetWorkers(const AMinWorkers, AMaxWorkers: Integer);
begin
Workers.MaxWorkers := AMaxWorkers;
Workers.MinWorkers := AMinWorkers;
end;
procedure TQWorkerService.Signal(const ASignal: PWideChar; AParams: IQParams);
begin
Workers.Signal(ASignal, Pointer(AParams), jdfFreeAsInterface);
end;
function TQWorkerService.Timer(AJob: IQJobCallback; AInterval: Cardinal;
AParams: IQParams; ARunInMainThread: Boolean): Int64;
begin
Result := Workers.Post(DoJob, AInterval, TJobCallback.Create(AJob, AParams),
ARunInMainThread, jdfFreeAsObject);
end;
function TQWorkerService.WaitSignal(const ASignal: PWideChar;
AJob: IQJobCallback; ARunInMainThread: Boolean): Int64;
var
AWaiter: TSignalJobWaiter;
begin
if Assigned(AJob) then
begin
AWaiter := TSignalJobWaiter.Create(AJob);
Result := Workers.Wait(DoSignalJob, ASignal, ARunInMainThread, AWaiter,
jdfFreeAsObject);
end;
end;
function TQWorkerService._CreateJobGroup(AByOrder: Boolean)
: StandInterfaceResult;
begin
Result := PointerOf(CreateJobGroup(AByOrder));
end;
{ TJobCallback }
constructor TJobCallback.Create(ACallback: IQJobCallback; AParams: IQParams);
begin
inherited Create;
FCallback := ACallback;
FParams := AParams;
end;
{ TQJobGroupService }
function TQJobGroupService.Add(AJob: IQJobCallback; AParams: IQParams;
AInMainThread: Boolean): Boolean;
begin
Result := FGroup.Add(DoJob, TJobCallback.Create(AJob, AParams), AInMainThread,
jdfFreeAsObject);
end;
procedure TQJobGroupService.Cancel(AWaitRunningDone: Boolean);
begin
FGroup.Cancel(AWaitRunningDone);
end;
constructor TQJobGroupService.Create(AByOrder: Boolean);
begin
inherited Create;
FGroup := TQJobGroup.Create(AByOrder);
FGroup.AfterDone := DoGroupDone;
end;
destructor TQJobGroupService.Destroy;
begin
FreeAndNil(FGroup);
inherited;
end;
procedure TQJobGroupService.DoGroupDone(ASender: TObject);
begin
if Assigned(FAfterDone) then
FAfterDone.DoNotify(Self);
end;
function TQJobGroupService.GetAfterDone: IQNotifyCallback;
begin
Result := FAfterDone;
end;
function TQJobGroupService.GetByOrder: Boolean;
begin
Result := FGroup.ByOrder;
end;
function TQJobGroupService.GetCount: Integer;
begin
Result := FGroup.Count;
end;
function TQJobGroupService.GetMaxWorkers: Integer;
begin
Result := FGroup.MaxWorkers;
end;
function TQJobGroupService.GetRuns: Integer;
begin
Result := FGroup.Runs;
end;
function TQJobGroupService.Insert(AIndex: Integer; AJob: IQJobCallback;
AParams: IQParams; ARunInMainThread: Boolean): Boolean;
begin
Result := FGroup.Insert(AIndex, DoJob, TJobCallback.Create(AJob, AParams),
ARunInMainThread, jdfFreeAsObject);
end;
procedure TQJobGroupService.Prepare;
begin
FGroup.Prepare;
end;
procedure TQJobGroupService.Run(ATimeout: Cardinal);
begin
FGroup.Run(ATimeout);
end;
procedure TQJobGroupService.SetAfterDone(AValue: IQNotifyCallback);
begin
FAfterDone := AValue;
end;
procedure TQJobGroupService.SetMaxWorkers(const AValue: Integer);
begin
FGroup.MaxWorkers := AValue;
end;
function TQJobGroupService.Wait(ABlockMessage: Boolean; ATimeout: Cardinal)
: TWaitResult;
begin
if ABlockMessage then
Result := FGroup.WaitFor(ATimeout)
else
Result := FGroup.MsgWaitFor(ATimeout);
end;
function TQJobGroupService._GetAfterDone: StandInterfaceResult;
begin
Result := PointerOf(FAfterDone);
end;
{ TQForJobManager }
procedure TQForJobManager.BreakIt;
begin
FManager.BreakIt;
end;
constructor TQForJobManager.Create(AMgr: TQForJobs);
begin
inherited Create;
FManager := AMgr;
end;
destructor TQForJobManager.Destroy;
begin
FreeAndNil(FManager);
inherited;
end;
function TQForJobManager.GetAvgTime: Int64;
begin
Result := FManager.AvgTime;
end;
function TQForJobManager.GetBreaked: Boolean;
begin
Result := FManager.Breaked;
end;
function TQForJobManager.GetRuns: Int64;
begin
Result := FManager.Runs;
end;
function TQForJobManager.GetStartIndex: Int64;
begin
Result := FManager.StartIndex;
end;
function TQForJobManager.GetStopIndex: Int64;
begin
Result := FManager.StopIndex;
end;
function TQForJobManager.GetTotalTime: Int64;
begin
Result := FManager.TotalTime;
end;
{ TQWorkerBaseService }
procedure TQWorkerBaseService.DoJob(AJob: PQJob);
var
ACallback: TJobCallback;
begin
ACallback := TJobCallback(AJob.Data);
if Assigned(ACallback.FCallback) then
ACallback.FCallback.DoJob(ACallback.FParams);
end;
{ TForJobCallback }
constructor TForJobCallback.Create(ACallback: IQForJobCallback;
AParams: IQParams);
begin
inherited Create;
FCallback := ACallback;
FParams := AParams;
end;
{ TSignalJobWaiter }
constructor TSignalJobWaiter.Create(ACallback: IQJobCallback);
begin
inherited Create;
FCallback := ACallback;
end;
initialization
RegisterServices('/Services', [TQWorkerService.Create(IQWorkers, 'QWorker')]);
finalization
UnregisterServices('/Services', ['QWorker']);
end.
|
unit BlockBasics;
{$mode objfpc}{$H+}{$interfaces corba}
interface
uses
Classes, FifoBasics;
type
TDeviceRunFlags = (drfTerminated, drfRunning, drfBlockedByInput, drfBlockedByOutput);
TDeviceRunStatus = set of TDeviceRunFlags;
IDevice = interface
function GetName:string;
property DeviceName: string read GetName;
end;
TCConnector = class;
TCDevice = class(TComponent, IDevice)
private
function GetName: string;
protected
procedure ValidateContainer(AComponent: TComponent); override;
procedure ValidateInsert(AComponent: TComponent); override; abstract;
end;
IPort = interface(IDevice)
function GetConnector: TCConnector;
procedure SetConnector(Value: TCConnector);
end;
IInputPort = interface(IPort)
function GetIsEmpty: Boolean;
function Pop(out Samples; Qty: Word): Boolean;
function Pop(out Sample: Integer): Boolean;
property IsEmpty: Boolean read GetIsEmpty;
end;
IOutputPort = interface(IPort)
function GetIsFull: Boolean;
function Push(const Samples; Qty: Word): Boolean;
function Push(Sample: Integer): Boolean;
property IsFull: Boolean read GetIsFull;
end;
TCPort = class(TCDevice, IPort)
protected
FConnector: TCConnector;
function GetConnector: TCConnector;
procedure SetConnector(Value: TCConnector); virtual;
property Connector: TCConnector write SetConnector;
end;
TCInputPort = class(TCPort, IInputPort)
protected
function GetIsEmpty: Boolean;
public
function Pop(out P: Pointer): Boolean;
function Pop(out Samples; Qty: Word): Boolean;
function Pop(out Sample: Integer): Boolean; inline;
property IsEmpty: Boolean read GetIsEmpty;
end;
TCOutputPort = class(TCPort, IOutputPort)
protected
function GetIsFull: Boolean;
public
function Push(P: Pointer): Boolean;
function Push(const Samples; Qty: Word): Boolean;
function Push(Sample: Integer): Boolean; inline;
property IsFull: Boolean read GetIsFull;
end;
TCInputPortRef = class(TCInputPort, IOutputPort)
private
FInternalConnector: TCConnector;
//function GetConnector: TCConnector; override;
function GetIsFull: Boolean;
function Push(P: Pointer): Boolean;
function Push(const Samples; Qty: Word): Boolean;
function Push(Sample: Integer): Boolean;
protected
procedure SetConnector(Value: TCConnector); override;
end;
TCOutputPortRef = class(TCOutputPort, IInputPort)
private
FInternalConnector: TCConnector;
//function GetConnector: TCConnector; override;
function GetIsEmpty: Boolean;
function Pop(out P: Pointer): Boolean;
function Pop(out Samples; Qty: Word): Boolean;
function Pop(out Sample: Integer): Boolean;
protected
procedure SetConnector(Value: TCConnector); override;
end;
TCBlock = class(TCDevice)
private
FBlocks: array of TCBlock;
FInputPorts: array of TCInputPort;
FOutputPorts: array of TCOutputPort;
protected
FRunStatus: TDeviceRunStatus;
procedure ValidateInsert(AComponent: TComponent); override;
public
constructor Create(AOwner: TComponent); override;
function GetInputQty: Integer;
function GetOutputQty: Integer;
function GetInputIdx(const InputName: string): Integer;
function GetOutputIdx(const OutputName: string): Integer;
procedure Execute; virtual;
property RunStatus: TDeviceRunStatus read FRunStatus;
end;
TCConnector = class(TCDevice)
private
FOutputPort: TCOutputPort;
FInputPort: TCInputPort;
FSamples: TCFifo;
FDepth: Integer;
procedure SetOutputPort(Output: TCOutputPort);
procedure SetInputPort(Input:TCInputPort);
function GetIsEmpty: Boolean;
function GetIsFull: Boolean;
function Push(const Sample): Boolean;
function Pop(out Sample): Boolean;
procedure SetDepth(ADepth: Integer);
public
constructor Create(AOwner: TComponent); override;
property IsEmpty: Boolean read GetIsEmpty;
property IsFull: Boolean read GetIsFull;
published
property OutputPort: TCOutputPort read FOutputPort write SetOutputPort;
property InputPort: TCInputPort read FInputPort write SetInputPort;
property Depth: Integer read FDepth write SetDepth;
end;
TFuncName = string[31];
TFuncPrefix = string[63];
function FuncB(name: TFuncName): TFuncPrefix;
function FuncC(name: TFuncName): TFuncPrefix;
function FuncE(name: TFuncName): TFuncPrefix;
implementation
uses
LResources;
type
PPortData = ^TPortData;
TPortData = record
case Size: Word of
1: (AsByte: Byte);
2: (AsWord: Word);
4: (AsLongWord: LongWord);
6: (Raw: array[Word] of Byte);
end;
var
FuncLevel: TFuncName;
function FuncB(name: TFuncName): TFuncPrefix;
begin
Result := FuncLevel + '>>' + name + ': ';
FuncLevel += ' ';
end;
function FuncC(name: TFuncName): TFuncPrefix;
begin
Result := FuncLevel + name + ': ';
end;
function FuncE(name: TFuncName): TFuncPrefix;
begin
SetLength(FuncLevel, Length(FuncLevel) - 2);
Result := FuncLevel + '<<' + name + ': ';
end;
function InitComponentFromResource(Instance: TComponent; ClassType: TClass): Boolean;
var
FPResource: TFPResourceHandle;
ResName: String;
Stream: TStream;
Reader: TReader;
DestroyDriver: Boolean;
Driver: TAbstractObjectReader;
begin
Result := False;
Stream := nil;
ResName := ClassType.ClassName;
if Stream = nil then
begin
FPResource := FindResource(HInstance, PChar(ResName), RT_RCDATA);
if FPResource <> 0 then
Stream := TLazarusResourceStream.CreateFromHandle(HInstance, FPResource);
end;
if Stream = nil then
Exit;
DestroyDriver:=false;
try
Reader := CreateLRSReader(Stream, DestroyDriver);
try
Reader.ReadRootComponent(Instance);
finally
Driver := Reader.Driver;
Reader.Free;
if DestroyDriver then
Driver.Free;
end;
finally
Stream.Free;
end;
Result := True;
end;
function TCDevice.GetName: string;
begin
Result := Name;
end;
procedure TCDevice.ValidateContainer(AComponent: TComponent);
begin
//WriteLn(FuncB('TCDevice.ValidateContainer'), 'Name = ', Name, ', ClassName = ', ClassName, ', DeviceName = ', DeviceName, ', ComponentCount = ', ComponentCount);
//with AComponent do begin
// WriteLn(FuncC('TCDevice.ValidateContainer'), 'Name = ', Name, ', ClassName = ', ClassName, ', DeviceName = ', DeviceName, ', ComponentCount = ', ComponentCount);
//end;
if AComponent is TCBlock then with AComponent as TCBlock do begin
ValidateInsert(Self);
end;
//WriteLn(FuncE('TCDevice.ValidateContainer'), 'Name = ', Name, ', ClassName = ', ClassName, ', DeviceName = ', DeviceName, ', ComponentCount = ', ComponentCount);
end;
function TCPort.GetConnector: TCConnector;
begin
Result := FConnector;
end;
procedure TCPort.SetConnector(Value: TCConnector);
begin
FConnector := Value;
end;
function TCInputPort.GetIsEmpty: Boolean;
begin
Result := Assigned(FConnector) and FConnector.IsEmpty;
end;
function TCInputPort.Pop(out P: Pointer): Boolean;
begin
//WriteLn(FuncB('TCInputPort.Pop(Pointer)'), 'Name = ', Owner.Name, '.', Name);
if Assigned(FConnector) then begin
//WriteLn(FuncC('TCInputPort.Pop'), 'Connector = ', FConnector.Owner.Name, '.', FConnector.Name);
Result := FConnector.Pop(P);
end else begin
//WriteLn(FuncC('TCInputPort.Pop'), 'Connector not assigned');
Result := False
end;
//WriteLn(FuncE('TCInputPort.Pop'), 'Name = ', Owner.Name, '.', Name, ' P = ', hexStr(P));
end;
function TCInputPort.Pop(out Samples; Qty: Word): Boolean;
var
P: PPortData;
begin
//WriteLn(FuncB('TCInputPort.Pop'), 'Name = ', Owner.Name, '.', Name);
Result := Pop(P);
if Result then with P^ do begin
if Qty > Size then begin
Qty := Size
end;
Move(Raw, Samples, Qty);
Freemem(P);
end;
//WriteLn(FuncE('TCInputPort.Pop'), 'Name = ', Owner.Name, '.', Name);
end;
function TCInputPort.Pop(out Sample: Integer): Boolean;
begin
Result := Pop(Sample, SizeOf(Sample));
end;
function TCOutputPort.GetIsFull: Boolean;
begin
Result := Assigned(FConnector) and FConnector.IsFull;
end;
function TCOutputPort.Push(P: Pointer): Boolean;
begin
//WriteLn(FuncB('TCOutputPort.Push'), 'Name = ', Owner.Name, '.', Name, ' P = ', HexStr(P));
if Assigned(FConnector) then begin
//WriteLn(FuncC('TCOutputPort.Push'), 'Connector = ', FConnector.Owner.Name, '.', FConnector.Name);
Result := FConnector.Push(P);
end else begin
//WriteLn(FuncC('TCOutputPort.Push'), 'Connector not assigned');
Result := False;
end;
if Result then begin
end;
//WriteLn(FuncE('TCOutputPort.Push'));
end;
function TCOutputPort.Push(const Samples; Qty: Word): Boolean;
var
P: PPortData;
begin
//WriteLn(FuncB('TCOutputPort.Push'));
P := GetMem(Qty + SizeOf(P^.Size));
if not Assigned(P) then begin
Exit(False)
end;
with P^ do begin
Size := Qty;
Move(Samples, Raw, Qty);
end;
Result := Push(P);
//WriteLn(FuncE('TCOutputPort.Push'));
end;
function TCOutputPort.Push(Sample: Integer): Boolean;
begin
Result := Push(Sample, SizeOf(Sample));
end;
function TCInputPortRef.GetIsFull: Boolean;
begin
Result := Assigned(FConnector) and FConnector.IsFull;
end;
function TCInputPortRef.Push(P: Pointer): Boolean;
begin
//WriteLn(FuncB('TCInputPortRef.Push'), 'Name = ', Owner.Name, '.', Name, ' P = ', hexStr(P));
if Assigned(FInternalConnector) then begin
//WriteLn(FuncC('TCInputPortRef.Push'), 'Connector = ', FConnector.Owner.Name, '.', FConnector.Name);
Result := FInternalConnector.Push(P);
end else begin
//WriteLn(FuncC('TCInputPortRef.Push'), 'Connector not assigned');
Result := False;
end;
if Result then begin
end;
//WriteLn(FuncE('TCInputPortRef.Push'));
end;
function TCInputPortRef.Push(const Samples; Qty: Word): Boolean;
var
P: PPortData;
begin
//WriteLn(FuncB('TCInputPortRef.Push'));
P := GetMem(Qty + SizeOf(P^.Size));
if not Assigned(P) then begin
Exit(False)
end;
with P^ do begin
Size := Qty;
Move(Samples, Raw, Qty);
end;
Result := Push(P);
//WriteLn(FuncE('TCInputPortRef.Push'));
end;
function TCInputPortRef.Push(Sample: Integer): Boolean;
begin
Result := Push(Sample, SizeOf(Sample));
end;
procedure TCInputPortRef.SetConnector(Value: TCConnector);
begin
if Assigned(Value) then begin
if Value.Owner = Owner then begin
FInternalConnector := Value;
end else begin
FConnector := Value;
end;
end;
end;
function TCOutputPortRef.GetIsEmpty: Boolean;
begin
Result := Assigned(FConnector) and FConnector.IsEmpty;
end;
function TCOutputPortRef.Pop(out P: Pointer): Boolean;
begin
//WriteLn(FuncB('TCOutputPortRef.Pop(Pointer)'), 'Name = ', Owner.Name, '.', Name);
if Assigned(FInternalConnector) then begin
//WriteLn(FuncC('TCOutputPortRef.Pop'), 'Connector = ', FConnector.Owner.Name, '.', FConnector.Name);
Result := FInternalConnector.Pop(P);
end else begin
//WriteLn(FuncC('TCOutputPortRef.Pop'), 'Connector not assigned');
Result := False
end;
//WriteLn(FuncE('TCOutputPortRef.Pop'), 'Name = ', Owner.Name, '.', Name, ' P = ', hexStr(P));
end;
function TCOutputPortRef.Pop(out Samples; Qty: Word): Boolean;
var
P: PPortData;
begin
//WriteLn(FuncB('TCOutputPortRef.Pop'), 'Name = ', Owner.Name, '.', Name);
Result := Pop(P);
if Result then with P^ do begin
if Qty > Size then begin
Qty := Size
end;
Move(Raw, Samples, Qty);
Freemem(P);
end;
//WriteLn(FuncE('TCOutputPortRef.Pop'), 'Name = ', Owner.Name, '.', Name);
end;
function TCOutputPortRef.Pop(out Sample: Integer): Boolean;
begin
Result := Pop(Sample, SizeOf(Sample));
end;
procedure TCOutputPortRef.SetConnector(Value: TCConnector);
begin
//WriteLn(FuncB('TCOutputPortRef.SetConnector'), 'Name = ', Owner.Name, '.', Name, ', Connector = ', HexStr(Value));
if Assigned(Value) then begin
//WriteLn(FuncC('TCOutputPortRef.SetConnector'), 'Connector = ', Value.Owner, '.', Value.Name);
if Value.Owner = Owner then begin
FInternalConnector := Value;
end else begin
FConnector := Value;
end;
end;
//WriteLn(FuncE('TCOutputPortRef.SetConnector'), 'Name = ', Owner.Name, '.', Name);
end;
constructor TCBlock.Create(AOwner: TComponent);
//var
// cn: string;
begin
//if Assigned(AOwner) then begin
// cn := AOwner.ClassName;
//end else begin
// cn := 'nil';
//end;
//WriteLn(FuncB('TCBlock.Create'), 'AOwner.ClassName = ', cn);
inherited Create(AOwner);
if not InitComponentFromResource(Self, ClassType) then begin
WriteLn('Failed to initilize component ', AOwner.Name, '.', Name, ': ', ClassName);
end;
//WriteLn(FuncE('TCBlock.Create'), 'AOwner.ClassName = ', cn);
end;
function TCBlock.GetInputQty: Integer;
begin
Result := Length(FInputPorts);
end;
function TCBlock.GetOutputQty: Integer;
begin
Result := Length(FOutputPorts);
end;
function TCBlock.GetInputIdx(const InputName: string): Integer;
var
i: Integer;
begin
Result := -1;
for i := Low(FInputPorts) to High(FInputPorts) do begin
if FInputPorts[i].Name = InputName then begin
Exit(i);
end;
end;
end;
function TCBlock.GetOutputIdx(const OutputName: string): Integer;
var
i: Integer;
begin
Result := -1;
for i := Low(FOutputPorts) to High(FOutputPorts) do begin
if FOutputPorts[i].Name = OutputName then begin
Exit(i);
end;
end;
end;
procedure TCBlock.ValidateInsert(AComponent: TComponent);
var
l: Integer;
begin
//WriteLn(FuncB('TCBlock.ValidateInsert'), 'Name = ', Name, ', ClassName = ', ClassName);
//WriteLn(FuncC('TCBlock.ValidateInsert'), 'InputCount = ', Length(FInputPorts), ', OutputCount', Length(FOutputPorts), ', Blocks = ', Length(FBlocks));
//WriteLn(FuncC('TCBlock.ValidateInsert'), 'AComponent.ClassName = ', AComponent.ClassName);
if AComponent is TCInputPort then begin
l := Length(FInputPorts);
SetLength(FInputPorts, l + 1);
FInputPorts[l] := AComponent as TCInputPort;
//WriteLn(FuncC('TCBlock.ValidateInsert'), 'AComponent = ', hexStr(AComponent), ', FInputPorts[', l, '] = ', HexStr(FInputPorts[l]));
end else if AComponent is TCOutputPort then begin
l := Length(FOutputPorts);
SetLength(FOutputPorts, l + 1);
FOutputPorts[l] := AComponent as TCOutputPort;
//WriteLn(FuncC('TCBlock.ValidateInsert'), 'AComponent = ', hexStr(AComponent), ', FOutputPorts[', l, '] = ', HexStr(FOutputPorts[l]));
end else if AComponent is TCBlock then begin
l := Length(FBlocks);
SetLength(FBlocks, l + 1);
FBlocks[l] := AComponent as TCBlock;
//WriteLn(FuncC('TCBlock.ValidateInsert'), 'AComponent = ', hexStr(AComponent), ', FBlocks[', l, '] = ', HexStr(FBlocks[l]));
end;
//WriteLn(FuncC('TCBlock.ValidateInsert'), 'InputCount = ', Length(FInputPorts), ', OutputCount', Length(FOutputPorts), ', Blocks = ', Length(FBlocks));
//WriteLn(FuncE('TCBlock.ValidateInsert'), 'Name = ', Name, ', ClassName = ', ClassName);
end;
procedure TCBlock.Execute;
var
i: Integer;
BlockRunStatus: TDeviceRunStatus;
RunBlock: Boolean;
P: PPortData;
begin
//WriteLn(FuncB('TCBlock.Execute'), 'Name = ', Name, ', BlocksCount = ', Length(FBlocks));
BlockRunStatus := [drfTerminated];
FRunStatus := [drfRunning];
for i := Low(FInputPorts) to High(FInputPorts) do begin
if FInputPorts[i] is TCInputPortRef then with FInputPorts[i] as TCInputPortRef do begin
while Pop(P) do begin
Push(P);
end;
end;
end;
for i := Low(FBlocks) to High(FBlocks) do with FBlocks[i] do begin
RunBlock := False;
if not (drfTerminated in RunStatus) then begin
Exclude(BlockRunStatus, drfTerminated);
RunBlock := True;
end;
if drfRunning in RunStatus then begin
RunBlock := False;
end;
if drfBlockedByInput in RunStatus then begin
Include(BlockRunStatus, drfBlockedByInput);
RunBlock := False;
end;
if drfBlockedByOutput in RunStatus then begin
Include(BlockRunStatus, drfBlockedByOutput);
RunBlock := False;
end;
//WriteLn(FuncC('TCBlock.Execute'), 'Block[', i, '].DeviceName = ', Name, ', Terminated = ', drfTerminated in RunStatus, ', BlockedByInput = ', drfBlockedByInput in RunStatus, ', BlockedByOutput = ', drfBlockedByOutput in RunStatus);
if RunBlock then begin
Execute;
end;
end;
//WriteLn(FuncC('TCBlock.Execute'), 'Low(FOutputPorts) = ', Low(FOutputPorts), ', High(FOutputPorts) = ', High(FOutputPorts));
//WriteLn(FuncC('TCBlock.Execute'), 'Length(FOutputPorts) = ', Length(FOutputPorts));
for i := Low(FOutputPorts) to High(FOutputPorts) do begin
//WriteLn(FuncC('TCBlock.Execute'), 'OutputPort[', i, '] = ', FOutputPorts[i].Name, ' is ', FOutputPorts[i].ClassName);
if FOutputPorts[i] is TCOutputPortRef then with FOutputPorts[i] as TCOutputPortRef do begin
//WriteLn(FuncC('TCBlock.Execute'), 'OutputPort[', i, '] = ', Name);
while Pop(P) do begin
Push(P);
end;
end;
end;
FRunStatus := BlockRunStatus;
//WriteLn(FuncE('TCBlock.Execute'), 'Name = ', Name, ', BlocksCount = ', Length(FBlocks));
end;
function TCConnector.GetIsEmpty: Boolean;
begin
Result := FSamples.GetPendingQty = 0;
end;
function TCConnector.GetIsFull: Boolean;
begin
Result := FSamples.GetAvailableQty = 0;
end;
procedure TCConnector.SetDepth(ADepth: Integer);
var
OldSamples: TCFifo;
p: Pointer;
begin
if FDepth <> ADepth then begin
FDepth := ADepth;
OldSamples := FSamples;
FSamples := TCFifo.Create(FDepth);
if Assigned(OldSamples) then begin
while oldSamples.Pop(p) do begin
FSamples.Push(p);
end;
OldSamples.Free;
end;
end;
end;
constructor TCConnector.Create(AOwner: TComponent);
//var
//cn: string;
begin
//if Assigned(AOwner) then begin
//cn := AOwner.ClassName;
//end else begin
//cn := 'nil';
//end;
//WriteLn(FuncB('TCConnector.Create'), 'AOwner.ClassName = ', cn);
inherited Create(AOwner);
//WriteLn(FuncC('TCConnector.Create'), Name, '.InputPort = $', HexStr(PtrInt(FInputPort), 8));
//WriteLn(FuncC('TCConnector.Create'), Name, '.OutputPort = $', HexStr(PtrInt(FOutputPort), 8));
Depth := 127;
//WriteLn(FuncE('TCConnector.Create'), 'AOwner.ClassName = ', cn);
end;
procedure TCConnector.SetOutputPort(Output:TCOutputPort);
begin
FOutputPort := Output;
Output.Connector := Self;
end;
procedure TCConnector.SetInputPort(Input: TCInputPort);
begin
FInputPort := Input;
Input.Connector := Self;
end;
function TCConnector.Push(const Sample): Boolean;
begin
//WriteLn(FuncB('TCConnector.Push'), Owner.Name, '.', Name, ', Sample = ', Sample, ', Samples.FreeQty = ', FSamples.GetAvailableQty);
repeat
Result := FSamples.Push(Pointer(Sample));
//WriteLn(FuncC('TCConnector.Push'), 'Could push = ', Result);
if Result then with InputPort.Owner as TCBlock do begin
Exclude(FRunStatus, drfBlockedByInput);
end else with FInputPort.Owner as TCBlock do begin
//WriteLn(FuncC('TCConnector.Push'), Owner.Name, '.', Name, ' connected to ', FInputPort.Name, ' (Terminated = ', drfTerminated in RunStatus, ')');
if drfTerminated in FRunStatus then with FOutputPort.Owner as TCBlock do begin
Include(FRunStatus, drfTerminated);
Break;
end else begin
Execute;
end;
end;
until Result;
//WriteLn(FuncE('TCConnector.Push'), Owner.Name, '.', Name, ', Sample = ', Sample, ', Samples.Qty = ', FSamples.GetPendingQty);
end;
function TCConnector.Pop(out Sample): Boolean;
begin
//WriteLn(FuncB('TCConnector.Pop'), Owner.Name, '.', Name, ', Samples.Qty = ', FSamples.GetPendingQty);
repeat
Result := FSamples.Pop(Pointer(Sample));
//WriteLn(FuncC('TCConnector.Pop'), 'Could pop = ', Result);
if Result then with OutputPort.Owner as TCBlock do begin
Exclude(FRunStatus, drfBlockedByOutput);
end else with FOutputPort.Owner as TCBlock do begin
//WriteLn(FuncC('TCConnector.Pop'), Owner.Name, '.', Name, ' connected to ', FOutputPort.Name, ' (Terminated = ', drfTerminated in RunStatus, ')');
if drfTerminated in FRunStatus then with FInputPort.Owner as TCBlock do begin
Include(FRunStatus, drfTerminated);
Break;
end else begin
Execute;
end;
end;
until Result;
//WriteLn(FuncE('TCConnector.Pop'), Owner.Name, '.', Name, ', Sample = ', Sample, ', Samples.FreeQty = ', FSamples.GetAvailableQty);
end;
end.
|
unit ScreenFrm;
interface
uses
Winapi.Windows, Winapi.Messages, System.Classes, Vcl.Graphics,
Vcl.Forms, SHDocVw;
type
TScreenFrm = class(TForm)
private
FCursor: TPoint;
FWebBrowser: TWebBrowser;
procedure EventoOnMessage(var Msg : TMsg; var Handled : boolean);
procedure EventoFormShow(Sender: TObject);
procedure EventoFormHide(Sender: TObject);
procedure EventoFormActivate(Sender: TObject);
public
constructor Create(AOwner: TComponent); override;
end;
implementation
uses
Vcl.Controls;
{$R *.dfm}
{ TScreenFrm }
constructor TScreenFrm.Create(AOwner: TComponent);
begin
inherited;
FWebBrowser := TWebBrowser.Create(Self);
TWinControl(FWebBrowser).Parent := Self;
with FWebBrowser do begin
FWebBrowser.Align := alClient;
end;
BorderIcons := [];
BorderStyle := bsNone;
Caption := 'ScreenSaver';
Color := clBlack;
FormStyle := fsStayOnTop;
Name := 'frmScreen';
Visible := False;
OnShow := EventoFormShow;
OnHide := EventoFormHide;
OnActivate := EventoFormActivate;
end;
procedure TScreenFrm.EventoFormActivate(Sender: TObject);
begin
WindowState := wsMaximized;
end;
procedure TScreenFrm.EventoFormHide(Sender: TObject);
begin
Application.OnMessage := nil;
ShowCursor(true);
end;
procedure TScreenFrm.EventoFormShow(Sender: TObject);
begin
GetCursorPos(FCursor);
Application.OnMessage := EventoOnMessage;
ShowCursor(false);
FWebBrowser.Navigate('http://www.google.com');
end;
procedure TScreenFrm.EventoOnMessage(var Msg: TMsg; var Handled: boolean);
var
bDesativa: boolean;
begin
if Msg.message = WM_MOUSEMOVE then begin
bDesativa :=
(Abs(LOWORD(Msg.lParam) - FCursor.x) > 5) or
(Abs(HIWORD(Msg.lParam) - FCursor.y) > 5)
end
else begin
bDesativa :=
(Msg.message = WM_KEYDOWN) or (Msg.message = WM_ACTIVATE) or
(Msg.message = WM_ACTIVATEAPP) or (Msg.message = WM_NCACTIVATE);
end;
if bDesativa then begin
Close;
end;
end;
end.
|
unit addresslisthandlerunit;
{
obsolete
the addresslisthandler is a class which will deal with the general address list
functions, like allocating memory, adding/removing from the list, finding the
correct address if it's a pointer, etc...
}
{obsolete, handling is now done in addresslist}
{$mode DELPHI}
interface
uses
Classes, SysUtils, controls, stdctrls, comctrls, MemoryRecordUnit, symbolhandler, cefuncproc,newkernelhandler, addresslist;
resourcestring
rsALHAGroupWithTheName = 'A group with the name ';
rsALHAlreadyExists = ' already exists';
{
type TAddresslistHandler=class
private
FAddressList: TAddressList;
//procedure freezeInterval
//procedure UpdateValues
function GetCount: integer;
function GetRecord(Index: Integer): TMemoryRecord;
procedure PutRecord(Index: Integer; Item: TMemoryRecord);
public
procedure delete(t: TTreeview);
// procedure addaddress(description: string; address: PtrUInt; const offsets: array of dword; offsetcount: integer; vartype: TVariableType; length: integer; startbit: integer; unicode: boolean); overload;
//procedure addaddress(description: string; address: uint_ptr; const offsets: array of dword; offsetcount: integer; ispointer: boolean; vartype: integer; length: integer; startbit: integer; unicode, showashex: boolean); overload;
procedure CreateGroup(groupname: string);
procedure DeleteGroup(groupname:string);
constructor create(addresslist: TAddressList);
destructor destroy; override;
property Records[Index: Integer]: TMemoryRecord read GetRecord write PutRecord; default;
property Count: Integer read GetCount;
end;
}
implementation
{
function TAddresslistHandler.GetRecord(Index: Integer): TMemoryRecord;
begin
end;
procedure TAddresslistHandler.PutRecord(Index: Integer; Item: TMemoryRecord);
begin
end;
function TAddresslistHandler.GetCount: integer;
begin
end;
procedure TAddresslistHandler.delete(t: TTreeview);
begin
end;
procedure TAddresslistHandler.CreateGroup(groupname: string);
var memrec: TMemoryRecord;
i: integer;
begin
//first check if a group with this name already exists, if so, error
for i:=0 to FAddressList.Items.Count-1 do
begin
memrec:=TMemoryRecord(FAddressList.Items[i].data);
if memrec.isGroupHeader and (memrec.Description=groupname) then
raise exception.create(rsALHAGroupWithTheName+groupname+rsALHAlreadyExists);
end;
memrec:=TMemoryRecord.create(self);
memrec.Description:=groupname;
memrec.isGroupHeader:=true;
// memrec.treenode:=TTreenode.Create;
// memrec.treenode.Parent:=
end;
procedure TAddresslistHandler.DeleteGroup(groupname:string);
var memrec: TMemoryRecord;
i,j: integer;
begin
for i:=0 to FAddressList.Items.Count-1 do
begin
memrec:=TMemoryRecord(FAddressList.Items[i].data);
if memrec.isGroupHeader and (memrec.Description=groupname) then
begin
memrec.free;
end;
end;
end;
constructor TAddresslistHandler.create(addresslist: TAddressList);
begin
FAddressList:=addresslist;
end;
destructor TAddresslistHandler.destroy;
begin
while FAddressList.Items.Count>0 do
TMemoryRecord(FAddressList.Items[0].data).Free;
end; }
end.
|
unit uSubsystemHistorico;
interface
type
{ Subsystem }
TSubsystemHistorico = class
public
procedure RegistrarHistoricoDoCalculo(const Fidelidade: integer;
const Dolar, Preco, ValorVenda: real);
end;
implementation
uses
SysUtils;
{ TSubsystemHistorico }
procedure TSubsystemHistorico.RegistrarHistoricoDoCalculo(const Fidelidade: integer;
const Dolar, Preco, ValorVenda: real);
var
Arquivo: TextFile;
PathArquivo: string;
Desconto: string;
begin
// obtém o caminho e nome do arquivo de histórico
PathArquivo := ExtractFilePath(ParamStr(0)) + 'Historico.txt';
// associa a variável "Arquivo" com o arquivo "Historico.txt"
AssignFile(Arquivo, PathArquivo);
if FileExists(PathArquivo) then
// se o arquivo já existe, coloca-o em modo de edição
Append(Arquivo)
else
// caso contrário, cria o arquivo
Rewrite(Arquivo);
// obtém a descrição do desconto conforme fidelidade
case Fidelidade of
0: Desconto := 'Desconto de 2%';
1: Desconto := 'Desconto de 6%';
2: Desconto := 'Desconto de 10%';
3: Desconto := 'Desconto de 18%';
end;
// escreve os dados no arquivo "Historico.txt"
WriteLn(Arquivo, 'Data/Hora.........: ' + FormatDateTime('dd/mm/yyyy - hh:nn:ss', Now));
WriteLn(Arquivo, 'Cotação do Dólar..: ' + FormatFloat('###,###,##0.00', Dolar));
WriteLn(Arquivo, 'Conversão em R$...: ' + FormatFloat('###,###,##0.00', Dolar * Preco));
WriteLn(Arquivo, 'Fidelidade........: ' + Desconto);
WriteLn(Arquivo, 'Margem de venda...: 35%');
WriteLn(Arquivo, 'Preço final.......: ' + FormatFloat('###,###,##0.00', ValorVenda));
WriteLn(Arquivo, EmptyStr);
// fecha o arquivo
CloseFile(Arquivo);
end;
end. |
object UniMainModule: TUniMainModule
OldCreateOrder = False
OnCreate = UniGUIMainModuleCreate
RecallLastTheme = True
BrowserOptions = [boDisableMouseRightClick]
MonitoredKeys.Keys = <>
OnHandleRequest = UniGUIMainModuleHandleRequest
Height = 382
Width = 516
object ADOConnection1: TADOConnection
LoginPrompt = False
Mode = cmShareDenyNone
Provider = 'Microsoft.Jet.OLEDB.4.0'
Left = 32
Top = 8
end
object ADOQuery1: TADOQuery
Connection = ADOConnection1
CursorType = ctStatic
Parameters = <
item
Name = 'companyname'
Attributes = [paNullable]
DataType = ftWideString
NumericScale = 255
Precision = 255
Size = 510
Value = '%%'
end
item
Name = 'contactname'
Attributes = [paNullable]
DataType = ftWideString
NumericScale = 255
Precision = 255
Size = 510
Value = '%%'
end
item
Name = 'contacttitle'
Attributes = [paNullable]
DataType = ftWideString
NumericScale = 255
Precision = 255
Size = 510
Value = '%%'
end
item
Name = 'address'
Attributes = [paNullable]
DataType = ftWideString
NumericScale = 255
Precision = 255
Size = 510
Value = '%%'
end
item
Name = 'city'
Attributes = [paNullable]
DataType = ftWideString
NumericScale = 255
Precision = 255
Size = 510
Value = '%%'
end
item
Name = 'country'
Attributes = [paNullable]
DataType = ftWideString
NumericScale = 255
Precision = 255
Size = 510
Value = '%%'
end
item
Name = 'phone'
Attributes = [paNullable]
DataType = ftWideString
NumericScale = 255
Precision = 255
Size = 510
Value = '%%'
end
item
Name = 'postalcode'
Attributes = [paNullable]
DataType = ftWideString
NumericScale = 255
Precision = 255
Size = 510
Value = '%%'
end>
SQL.Strings = (
'select * from [Customers]'
'where '
'companyname like :companyname'
'and '
'contactname like :contactname'
'and '
'contacttitle like :contacttitle'
'and '
'address like :address'
'and '
'city like :city'
'and '
'country like :country'
'and '
'phone like :phone'
'and '
'postalcode like :postalcode'
''
''
''
''
''
''
''
''
'')
Left = 128
Top = 8
object ADOQuery1CustomerID: TWideStringField
FieldName = 'CustomerID'
Size = 5
end
object ADOQuery1CompanyName: TWideStringField
FieldName = 'CompanyName'
Size = 40
end
object ADOQuery1ContactName: TWideStringField
FieldName = 'ContactName'
Size = 30
end
object ADOQuery1ContactTitle: TWideStringField
FieldName = 'ContactTitle'
Size = 30
end
object ADOQuery1Address: TWideStringField
FieldName = 'Address'
Size = 60
end
object ADOQuery1City: TWideStringField
FieldName = 'City'
Size = 15
end
object ADOQuery1Region: TWideStringField
FieldName = 'Region'
Size = 15
end
object ADOQuery1PostalCode: TWideStringField
FieldName = 'PostalCode'
Size = 10
end
object ADOQuery1Country: TWideStringField
FieldName = 'Country'
Size = 15
end
object ADOQuery1Phone: TWideStringField
FieldName = 'Phone'
Size = 24
end
object ADOQuery1Fax: TWideStringField
FieldName = 'Fax'
Size = 24
end
end
object DataSource1: TDataSource
DataSet = ADOQuery2
Left = 344
Top = 8
end
object DataSource: TDataSource
DataSet = ADOQuery1
Left = 272
Top = 8
end
object ADOConnection2: TADOConnection
LoginPrompt = False
Mode = cmShareDenyNone
Provider = 'Microsoft.Jet.OLEDB.4.0'
Left = 32
Top = 64
end
object DataSource2: TDataSource
DataSet = ADOQuery3
Left = 272
Top = 64
end
object DataSource3: TDataSource
DataSet = ADOQuery4
Left = 352
Top = 64
end
object ADOQuery3: TADOQuery
Connection = ADOConnection1
CursorType = ctStatic
Parameters = <
item
Name = 'companyname'
Attributes = [paNullable]
DataType = ftWideString
NumericScale = 255
Precision = 255
Size = 510
Value = '%%'
end
item
Name = 'contactname'
Attributes = [paNullable]
DataType = ftWideString
NumericScale = 255
Precision = 255
Size = 510
Value = '%%'
end
item
Name = 'contacttitle'
Attributes = [paNullable]
DataType = ftWideString
NumericScale = 255
Precision = 255
Size = 510
Value = '%%'
end
item
Name = 'address'
Attributes = [paNullable]
DataType = ftWideString
NumericScale = 255
Precision = 255
Size = 510
Value = '%%'
end
item
Name = 'city'
Attributes = [paNullable]
DataType = ftWideString
NumericScale = 255
Precision = 255
Size = 510
Value = '%%'
end
item
Name = 'country'
Attributes = [paNullable]
DataType = ftWideString
NumericScale = 255
Precision = 255
Size = 510
Value = '%%'
end
item
Name = 'phone'
Attributes = [paNullable]
DataType = ftWideString
NumericScale = 255
Precision = 255
Size = 510
Value = '%%'
end
item
Name = 'postalcode'
Attributes = [paNullable]
DataType = ftWideString
NumericScale = 255
Precision = 255
Size = 510
Value = '%%'
end>
SQL.Strings = (
'select * from [Customers]'
'where '
'companyname like :companyname'
'and '
'contactname like :contactname'
'and '
'contacttitle like :contacttitle'
'and '
'address like :address'
'and '
'city like :city'
'and '
'country like :country'
'and '
'phone like :phone'
'and '
'postalcode like :postalcode'
''
''
''
''
''
''
''
''
'')
Left = 128
Top = 64
object WideStringField1: TWideStringField
FieldName = 'CustomerID'
Size = 5
end
object WideStringField2: TWideStringField
FieldName = 'CompanyName'
Size = 40
end
object WideStringField3: TWideStringField
FieldName = 'ContactName'
Size = 30
end
object WideStringField4: TWideStringField
FieldName = 'ContactTitle'
Size = 30
end
object WideStringField5: TWideStringField
FieldName = 'Address'
Size = 60
end
object WideStringField6: TWideStringField
FieldName = 'City'
Size = 15
end
object WideStringField7: TWideStringField
FieldName = 'Region'
Size = 15
end
object WideStringField8: TWideStringField
FieldName = 'PostalCode'
Size = 10
end
object WideStringField9: TWideStringField
FieldName = 'Country'
Size = 15
end
object WideStringField10: TWideStringField
FieldName = 'Phone'
Size = 24
end
object WideStringField11: TWideStringField
FieldName = 'Fax'
Size = 24
end
end
object ADOQuery2: TADOQuery
Connection = ADOConnection1
CursorType = ctStatic
Parameters = <>
SQL.Strings = (
'select distinct Country from [Customers]'
''
''
''
''
''
''
''
'')
Left = 200
Top = 8
end
object ADOQuery4: TADOQuery
Connection = ADOConnection1
CursorType = ctStatic
Parameters = <>
SQL.Strings = (
'select distinct Country from [Customers]'
''
''
''
''
''
''
''
'')
Left = 200
Top = 64
end
object ADOQuery5: TADOQuery
Connection = ADOConnection3
CursorType = ctStatic
Parameters = <
item
Name = 'companyname'
Attributes = [paNullable]
DataType = ftWideString
NumericScale = 255
Precision = 255
Size = 510
Value = '%%'
end
item
Name = 'contactname'
Attributes = [paNullable]
DataType = ftWideString
NumericScale = 255
Precision = 255
Size = 510
Value = '%%'
end
item
Name = 'contacttitle'
Attributes = [paNullable]
DataType = ftWideString
NumericScale = 255
Precision = 255
Size = 510
Value = '%%'
end
item
Name = 'address'
Attributes = [paNullable]
DataType = ftWideString
NumericScale = 255
Precision = 255
Size = 510
Value = '%%'
end
item
Name = 'city'
Attributes = [paNullable]
DataType = ftWideString
NumericScale = 255
Precision = 255
Size = 510
Value = '%%'
end
item
Name = 'country'
Attributes = [paNullable]
DataType = ftWideString
NumericScale = 255
Precision = 255
Size = 510
Value = '%%'
end
item
Name = 'phone'
Attributes = [paNullable]
DataType = ftWideString
NumericScale = 255
Precision = 255
Size = 510
Value = Null
end
item
Name = 'postalcode'
Attributes = [paNullable]
DataType = ftWideString
NumericScale = 255
Precision = 255
Size = 510
Value = Null
end>
SQL.Strings = (
'select * from [Customers]'
'where '
'companyname like :companyname'
'and '
'contactname like :contactname'
'and '
'contacttitle like :contacttitle'
'and '
'address like :address'
'and '
'city like :city'
'and '
'country like :country'
'and '
'phone like :phone'
'and '
'postalcode like :postalcode'
''
''
''
''
''
''
''
''
''
''
''
''
''
'')
Left = 120
Top = 128
object WideStringField12: TWideStringField
FieldName = 'CustomerID'
Size = 5
end
object WideStringField13: TWideStringField
FieldName = 'CompanyName'
Size = 40
end
object WideStringField14: TWideStringField
FieldName = 'ContactName'
Size = 30
end
object WideStringField15: TWideStringField
FieldName = 'ContactTitle'
Size = 30
end
object WideStringField16: TWideStringField
FieldName = 'Address'
Size = 60
end
object WideStringField17: TWideStringField
FieldName = 'City'
Size = 15
end
object WideStringField18: TWideStringField
FieldName = 'Region'
Size = 15
end
object WideStringField19: TWideStringField
FieldName = 'PostalCode'
Size = 10
end
object WideStringField20: TWideStringField
FieldName = 'Country'
Size = 15
end
object WideStringField21: TWideStringField
FieldName = 'Phone'
Size = 24
end
object WideStringField22: TWideStringField
FieldName = 'Fax'
Size = 24
end
end
object ADOConnection3: TADOConnection
LoginPrompt = False
Mode = cmShareDenyNone
Provider = 'Microsoft.Jet.OLEDB.4.0'
Left = 32
Top = 128
end
object DataSource5: TDataSource
DataSet = ADOQuery6
Left = 208
Top = 192
end
object DataSource4: TDataSource
DataSet = ADOQuery5
Left = 208
Top = 128
end
object ADOConnection4: TADOConnection
LoginPrompt = False
Mode = cmShareDenyNone
Provider = 'Microsoft.Jet.OLEDB.4.0'
Left = 40
Top = 200
end
object ADOQuery6: TADOQuery
Connection = ADOConnection1
CursorType = ctStatic
Parameters = <>
SQL.Strings = (
'select * from Customers')
Left = 136
Top = 200
end
end
|
{ This unit is used to send http requests to the discord api.
@author(Kaktushose (https://github.com/Kaktushose)) }
unit http;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, fphttpclient, opensslsockets, fpjson, jsonparser, logging;
type
{ @abstract(An enum describing all available http request methods.) }
RequestType = (GET, POST, PUT, DELETE);
{ @abstract(This class describes a http request. Instances of this class can be reused.) }
THttpRequest = class
private
FMethod : RequestType;
FRoute: string;
FBody: string;
procedure setRequestType(aRequestType : RequestType);
procedure setRoute(aRoute : string);
procedure setBody(aBody : string);
public
{ The @link(RequestType) to use. }
property Method: RequestType read FMethod write setRequestType;
{ The route of the request. }
property Route: string read FRoute write setRoute;
{ An optional body to attach to the request. }
property Body: string read FBody write setBody;
end;
{ @abstract(A simple http client that can make requests to the discord api.) }
THttpClient = class
private
url: string;
token: string;
log: TLogger;
public
{Send a @link(THttpRequest) to the discord api. }
function MakeRequest(aHttpRequest : THttpRequest) : TJSONObject;
{ Create a new client with the given bot token. }
constructor Create(aToken: string);
{ The destructor. }
destructor Destroy; override;
end;
implementation
function THttpClient.MakeRequest(aHttpRequest : THttpRequest) : TJSONObject;
var
requestUrl, method : string;
client: TFPHttpClient;
json : TJSONData;
begin
client := TFPHTTPClient.Create(nil);
client.AddHeader('Authorization', 'Bot ' + token);
client.AddHeader('Content-Type', 'application/json');
client.RequestBody := TRawByteStringStream.Create(aHttpRequest.Body);
WriteStr(method, aHttpRequest.Method);
requestUrl := url + aHttpRequest.Route;
log.Debug('Request: ' + method + ' ' + requestUrl);
try
try
case aHttpRequest.Method of
RequestType.GET:
json := GetJson(client.Get(requestUrl));
RequestType.POST:
json := GetJson(client.Post(requestUrl));
RequestType.PUT:
json := GetJson(client.Put(requestUrl));
RequestType.DELETE:
json := GetJson(client.Delete(requestUrl));
end;
log.Debug('Response code: ' + IntToStr(client.ResponseStatusCode));
Result := TJSONObject(json);
except
on e: Exception do
log.Error('Request failed!', e);
end;
finally
FreeAndNil(client);
end;
end;
constructor THttpClient.Create(aToken: string);
begin
inherited Create;
url := 'https://discord.com/api/v9/';
token := aToken;
log := TLogger.GetLogger(THttpClient);
end;
destructor THttpClient.Destroy;
begin
FreeAndNil(log);
inherited Destroy;
end;
procedure THttpRequest.setRequestType(aRequestType: RequestType);
begin
FMethod := aRequestType;
end;
procedure THttpRequest.setRoute(aRoute: string);
begin
FRoute := aRoute;
end;
procedure THttpRequest.setBody(aBody: string);
begin
FBody := aBody;
end;
end.
|
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, OverbyteIcsWndControl, OverbyteIcsHttpProt;
type
TForm1 = class(TForm)
Button1: TButton;
HttpCli1: THttpCli;
ListBox1: TListBox;
Edit1: TEdit;
Edit2: TEdit;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
const
UsuarioAutenticacaoHttp = 'usuario';
SenhaAutenticacaoHttp = 'senha';
var
TempoInicial, TempoFinal: TDateTime;
begin
try
try
Button1.Enabled := false;
HttpCli1.URL := Edit1.Text;
HttpCli1.NoCache := True;
HttpCli1.ServerAuth := httpAuthBasic;
HttpCli1.Username := UsuarioAutenticacaoHttp;
HttpCli1.Password := Edit2.Text;
self.Caption := IntToStr(HttpCli1.Timeout);
TempoInicial := Now;
HttpCli1.Get;
ListBox1.Items.Add('GET OK !');
ListBox1.Items.Add('StatusCode = ' + IntToStr(HttpCli1.StatusCode));
if (HttpCli1.StatusCode < 100) or (HttpCli1.StatusCode > 399) then
raise Exception.Create('tem coisa errada');
except
on E: Exception do
begin
ListBox1.Items.Add('GET Failed !');
ListBox1.Items.Add('StatusCode = ' + IntToStr(HttpCli1.StatusCode));
ListBox1.Items.Add('detalhe: ' + E.Message);
end;
end;
finally
Button1.Enabled := True;
TempoFinal := Now;
ListBox1.Items.Add(FormatDateTime('hh:nn:ss', TempoFinal - TempoInicial));
ListBox1.Items.Add('');
ListBox1.ItemIndex := ListBox1.Count - 1;
end;
end;
end.
|
{SWAG=OOP.SWG,MIKE SORTZ,Sorting using tCollection,SORTING,USING,TCOLLECTION}
unit TSortLst;
(*
Version 1.0 5/12/95 - Mike Stortz
Borland Pascal 7.0 has a very useful object called a TCollection that
allows you to sort items by any key you wish and that disposes
of any objects it owns when the collection itself is freed.
Inexplicably, these very useful behaviors were omitted from Delphi's
TStringList. But now...
This unit contains a class called "TSortableList" derived from
TStringList that supports the ability for you to define descendent classes
that sort the list any way you wish and has the option to "own" the objects
that are added to it, so that they are disposed with the list.
How to use a TSortableList that owns its objects:
1. Create a new TSortableList and tell it that it should own any objects
in it.
var
my_list : TSortableList;
begin
my_list := TSortableList.Create(True); { "True" = Owns objects }
my_list.Add('Aaa', TObject.Create); { In a TStringList, this... }
my_list.Add('Bbb', TObject.Create); { ...would be... }
my_list.Add('Ccc', TObject.Create); { ...very bad! }
my_list.Free; { All objects freed }
end;
How to sort on an arbitrary key:
Suppose you wanted a list of strings sorted by all but the first character
(i.e. this order -> "ZAble", "YBaker", "XCharlie").
1. Declare a descendent of TSortableList and override the Compare method.
The Compare method should return an integer such that the result is:
-1 if the item at index i1 is "less" than the item at i2
0 if the item at index i1 is "equal" than the item at i2
1 if the item at index i1 is "more" than the item at i2
TExList = class(TSortableList)
function Compare(i1, i2 : Integer) : Integer; override;
end;
2. Define the new compare method
function Compare(i1, i2 : Integer) : Integer;
begin
case Key of
1 :
Result := AnsiCompareText(Copy(Strings[i1], 2, 254),
Copy(Strings[i2], 2, 254));
else
Result := inherited Compare(i1, i2);
end;
end;
3. Specify the key you just defined.
var
my_list : TExList;
begin
my_list := TExList.Create;
my_list.Key := 1; { <<<<< New key is made active }
DoSomeStuff;
my_list.Free;
end;
There you go! I =strongly= suggest that any Key that you define Compare
methods for have a value of at least 1 and that all unhandled Key
values be passed to the inherited method, as above. A Key of 0 is
defined to be the default alphabetical sort.
Note that you can define a Key based on the objects in a list, like so:
function Compare(i1, i2 : Integer) : Integer;
begin
case Key of
1 :
Result := AnsiCompareText(TSomeObject(Objects[i1]).Text,
TSomeObject(Objects[i2].Text);
else
Result := inherited Compare(i1, i2);
end;
end;
Of course, it is your responsibility to be sure that the objects in
the list are the type that your Compare method assumes them to be.
=== Important ===
If you do have a list that is
a) sorted, and
b) determines its order via values derived from the objects that are
stored in the list,
watch out for changing objects in such a way as to change their sort order;
the TSortableList will not know that the list is now out of order and
calls to routines that depend on knowing this (such as Add) may fail to
work. Your best bet in this case is to set Sorted to False, make whatever
changes to the objects you wish, and then set Sorted back to True. This
will resort the list.
I also took the liberty of "protecting" the Find method against the
possibility that someone would call it when the list was not sorted --
in that case, it now calls IndexOf (which, somewhat recursively, would
call Find if the list =was= sorted). This is exactly what happened in
the example code for Find! If you look at the method list for
TStringList, you won't find Find -- but you can do a topic search for
it. The example code for Find works, but only by chance -- add another
string to either end of the list, and "Flowers" won't be found. What's
wrong with the example code is that the list's Sorted property is not set
to True; the reason it (accidently) works is because the item that
was being found ("Flowers") happened to be the middle item in the list,
which is where the search algorithm looks first.
If you have any comments, suggestions or even criticisms for
TSortableList, hey, tough! No, really, send me some mail at 71744,422.
I am particularly interested in bug reports.
*)
interface
Uses
Classes;
type
TSortableList = class(TStringList)
private
FOwnsObjects : Boolean;
FKey : Integer;
FAscending : Boolean;
procedure QuickSort(left, right: Integer);
function CallCompare(i1, i2 : Integer) : Integer;
procedure SetAscending(value : Boolean);
procedure SetKey(value : Integer);
protected
procedure PutObject(index : Integer; AObject : TObject); override;
function Compare(i1, i2 : Integer) : Integer; virtual;
public
constructor Create(owns_objects : Boolean);
procedure Clear; override;
procedure Delete(index : Integer); override;
function Find(const s : string; var index : Integer): Boolean; override;
procedure Sort; override;
property Ascending : Boolean read FAscending write SetAscending;
property Key : Integer read FKey write SetKey;
property OwnsObjects : Boolean read FOwnsObjects;
end;
implementation
Uses
SysUtils;
{ Private Methods }
procedure TSortableList.QuickSort(left, right: Integer);
var
i, j, pivot : Integer;
s : String;
begin
i := left;
j := right;
{ Rather than store the pivot value (which was assumed to be a string),
store the pivot index }
pivot := (left + right) shr 1;
repeat
while CallCompare(i, pivot) < 0 do
Inc(i);
while CallCompare(j, pivot) > 0 do
Dec(j);
if i <= j then
begin
Exchange(i, j);
{ If we just moved the pivot item, reset the pivot index }
if pivot = i then
pivot := j
else if pivot = j then
pivot := i;
Inc(i);
Dec(j);
end;
until i > j;
if left < j then
QuickSort(left, j);
if i < right then
QuickSort(i, right);
end;
function TSortableList.CallCompare(i1, i2 : Integer) : Integer;
begin
Result := Compare(i1, i2);
if not FAscending then
Result := -Result;
end;
procedure TSortableList.SetAscending(value : Boolean);
begin
if value <> FAscending then
begin
FAscending := value;
if Sorted then
begin
Sorted := False;
Sorted := True;
end
end;
end;
procedure TSortableList.SetKey(value : Integer);
begin
if value <> FKey then
begin
FKey := value;
if Sorted then
begin
Sorted := False;
Sorted := True;
end
end;
end;
{ Protected Methods }
function TSortableList.Compare(i1, i2 : Integer) : Integer;
begin
Result := AnsiCompareText(Strings[i1], Strings[i2]);
end;
{ Public Methods }
constructor TSortableList.Create(owns_objects : Boolean);
begin
inherited Create;
FOwnsObjects := owns_objects;
FKey := 0;
FAscending := True;
end;
procedure TSortableList.Clear;
var
index : Integer;
begin
Changing;
if FOwnsObjects then
for index := 0 to Count - 1 do
GetObject(index).Free;
inherited Clear;
Changed;
end;
procedure TSortableList.Delete(index: Integer);
begin
Changing;
if FOwnsObjects then
GetObject(index).Free;
inherited Delete(index);
Changed;
end;
function TSortableList.Find(const s : string; var index : Integer): Boolean;
begin
if not Sorted then
begin
index := IndexOf(s);
Result := (index <> -1);
end
else
Result := inherited Find(s, index);
end;
procedure TSortableList.PutObject(index: Integer; AObject: TObject);
begin
Changing;
if FOwnsObjects then
GetObject(index).Free;
inherited PutObject(index, AObject);
Changed;
end;
procedure TSortableList.Sort;
begin
if not Sorted and (Count > 1) then
begin
Changing;
QuickSort(0, Count - 1);
Changed;
end;
end;
end. |
unit er.model.concretephotos;
{$mode objfpc}{$H+}
{$LongStrings on}
interface
uses
Classes,
SysUtils,
ExtCtrls,
er.model.abstractphotos,
RegExpr;
type
TConcretePhotos = class ( TPhotoGetter )
procedure GetPhotos( Ref : string; ListOfUrls : TStrings ) ; override;
end;
implementation
procedure TConcretePhotos.GetPhotos(Ref: string; ListOfUrls: TStrings);
var
pageHTML : ansistring;
re : TRegExpr;
begin
try
pageHTML := http.SimpleGet( Ref ) ;
except
exit;
end;
{ Regular Expression for Validation }
re := TRegExpr.Create('http[s]{1}\:\/\/+[\w\d\.\/\-]{1,}\.jpg');
if re.Exec(pageHTML) then
begin
ListOfUrls.Add( StringReplace( re.Match[0],'src="', '', [rfReplaceAll, rfIgnoreCase] ) );
while re.ExecNext do
begin
ListOfUrls.Add( StringReplace( re.Match[0],'src="', '', [rfReplaceAll, rfIgnoreCase] ) );
end;
end;
ListOfUrls.SaveToFile('lista.txt');
end;
end.
|
unit USplashUI;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
System.Math, System.Threading, System.JSON,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Layouts, FMX.StdCtrls,
FMX.Controls.Presentation, FMX.Objects, FMX.TabControl, System.Actions, FMX.ActnList;
type
TFrmSplashUI = class(TForm)
layoutBase: TLayout;
ScrollBoxForm: TScrollBox;
LayoutCadastro: TLayout;
TabControlSplash: TTabControl;
TabSplash: TTabItem;
TabLogin: TTabItem;
LayoutSplash: TLayout;
LayoutPainel: TLayout;
ImageLogoApp: TImage;
ImageLogoEntidade: TImage;
LabelAppTitle: TLabel;
LabelCarregando: TLabel;
LabelVersion: TLabel;
ProgressBar: TProgressBar;
ActionListSplash: TActionList;
acMudarForm: TChangeTabAction;
TabPrincipal: TTabItem;
TabCadastro: TTabItem;
LayoutLogin: TLayout;
LayoutPrincipal: TLayout;
acIrFormLogin: TChangeTabAction;
acIrFormCadastro: TChangeTabAction;
acIrFormPrincipal: TChangeTabAction;
LayoutForm: TLayout;
procedure FormCreate(Sender: TObject);
procedure FormFocusChanged(Sender: TObject);
procedure FormVirtualKeyboardHidden(Sender: TObject; KeyboardVisible: Boolean;
const Bounds: TRect);
procedure FormVirtualKeyboardShown(Sender: TObject; KeyboardVisible: Boolean;
const Bounds: TRect);
procedure FormActivate(Sender: TObject);
private
{ Private declarations }
FWBounds : TRectF;
FNeedOffSet ,
FActivateLoaded : Boolean;
aLayoutLogin ,
aLayoutCadastro : TComponent;
procedure Carregar;
procedure CarregarFormulario;
procedure AtualizarEspecialidades;
procedure MudarForm(TabItem : TTabItem; Sender : TObject);
procedure AbrirLogin;
public
{ Public declarations }
procedure CalcContentBounds(Sender : TObject; var ContentBounds : TRectF);
procedure RestorePosition;
procedure UpdatePosition;
procedure AbrirCadastroUsuario;
procedure AbrirMenu;
end;
var
FrmSplashUI: TFrmSplashUI;
implementation
{$R *.fmx}
uses
UDados
{$IF DEFINED (ANDROID)}
, Androidapi.Helpers
, Androidapi.JNI.JavaTypes
, Androidapi.JNI.GraphicsContentViewText
{$ENDIF}
// {$IF DEFINED (IOS)}
// , ?
// , ?
// , ?
// {$ENDIF}
, app.Funcoes
, classes.HttpConnect
, classes.Constantes
, dao.Especialidade
, dao.Usuario
, ULogin
, UPrincipal
, UCadastroUsuario;
{ TFrmPadrao }
procedure TFrmSplashUI.AbrirCadastroUsuario;
begin
// TabControlSplash.ActiveTab := TabVazio;
//
// if Assigned(FrmLogin) then
// begin
// LayoutForm.RemoveObject(TLayout(aLayoutLogin));
//
// {$IF DEFINED (IOS)}
// FrmLogin.DisposeOf;
// {$ELSE}
// FrmLogin.Close;
// {$ENDIF}
// FrmLogin := nil;
// end;
//
if not Assigned(FrmCadastroUsuario) then
Application.CreateForm(TFrmCadastroUsuario, FrmCadastroUsuario);
aLayoutCadastro := FrmCadastroUsuario.FindComponent('layoutBase');
if Assigned(aLayoutCadastro) then
LayoutCadastro.AddObject(TLayout(aLayoutCadastro));
//TabControlSplash.ActiveTab := TabCadastro;
acIrFormCadastro.ExecuteTarget(Self);
end;
procedure TFrmSplashUI.AbrirLogin;
begin
if not Assigned(FrmLogin) then
Application.CreateForm(TFrmLogin, FrmLogin);
aLayoutLogin := FrmLogin.FindComponent('layoutBase');
if Assigned(aLayoutLogin) then
LayoutLogin.AddObject(TLayout(aLayoutLogin));
//TabControlSplash.ActiveTab := TabLogin;
acIrFormLogin.ExecuteTarget(Self);
end;
procedure TFrmSplashUI.AbrirMenu;
var
aLayoutPadrao : TComponent;
begin
// TabControlSplash.ActiveTab := TabVazio;
//
// if Assigned(FrmLogin) then
// begin
// LayoutForm.RemoveObject(TLayout(aLayoutLogin));
// {$IF DEFINED (IOS)}
// FrmLogin.DisposeOf;
// {$ELSE}
// FrmLogin.Close;
// {$ENDIF}
// FrmLogin := nil;
// end;
//
// if Assigned(FrmCadastroUsuario) then
// begin
// LayoutForm.RemoveObject(TLayout(aLayoutCadastro));
// {$IF DEFINED (IOS)}
// FrmCadastroUsuario.DisposeOf;
// {$ELSE}
// FrmCadastroUsuario.Close;
// {$ENDIF}
// FrmCadastroUsuario := nil;
// end;
//
if not Assigned(FrmPrincipal) then
Application.CreateForm(TFrmPrincipal, FrmPrincipal);
aLayoutPadrao := FrmPrincipal.FindComponent('layoutBase');
if Assigned(aLayoutPadrao) then
LayoutPrincipal.AddObject(TLayout(aLayoutPadrao));
//TabControlSplash.ActiveTab := TabPrincipal;
acIrFormPrincipal.ExecuteTarget(Self);
end;
procedure TFrmSplashUI.AtualizarEspecialidades;
var
aTaskE : ITask;
begin
aTaskE := TTask.Create(
procedure
var
aMsg : String;
aEsp : TEspecialidadeDao;
I : Integer;
begin
aMsg := 'Atualizando dados...';
try
aEsp := TEspecialidadeDao.GetInstance;
LabelCarregando.Text := aMsg;
ProgressBar.Max := High(aEsp.Lista);
ProgressBar.Value := 0;
for I := Low(aEsp.Lista) to High(aEsp.Lista) do
begin
if Assigned(aEsp.Lista[I]) then
begin
aEsp.Model := aEsp.Lista[I];
if not aEsp.Find(aEsp.Model.Codigo, False) then
aEsp.Insert()
else
aEsp.Update();
end;
ProgressBar.Value := (I + 1);
end;
finally
ProgressBar.Value := ProgressBar.Max;
CarregarFormulario;
end;
end
);
aTaskE.Start;
end;
procedure TFrmSplashUI.CalcContentBounds(Sender: TObject; var ContentBounds: TRectF);
begin
if (FNeedOffSet and (FWBounds.Top > 0)) then
ContentBounds.Bottom := Max(ContentBounds.Bottom, 2 * ClientHeight - FWBounds.Top);
end;
procedure TFrmSplashUI.Carregar;
var
aTask : ITask;
aKey : String;
begin
aKey := MD5(FormatDateTime('dd/mm/yyyy', Date));
aTask := TTask.Create(
procedure
var
aMsg : String;
IEsp : TEspecialidadeDao;
aJsonArray : TJSONArray;
aJsonObject : TJSONObject;
I : Integer;
aErr : Boolean;
begin
aMsg := 'Conectando...';
try
IEsp := TEspecialidadeDao.GetInstance;
aErr := False;
try
aJsonArray := DtmDados.HttpGetEspecialidade(aKey) as TJSONArray;
except
On E : Exception do
begin
aErr := True;
aMsg := 'Servidor da entidade não responde ...' + #13 + E.Message;
end;
end;
LabelCarregando.Text := aMsg;
if not aErr then
for I := 0 to aJsonArray.Count - 1 do
begin
aJsonObject := aJsonArray.Items[I] as TJSONObject;
IEsp.AddLista;
IEsp.Lista[I].Codigo := StrToInt(aJsonObject.GetValue('cd_especilidade').Value);
IEsp.Lista[I].Descricao := Trim(aJsonObject.GetValue('ds_especilidade').Value);
end;
finally
if not aErr then
AtualizarEspecialidades;
end;
end
);
aTask.Start;
end;
procedure TFrmSplashUI.CarregarFormulario;
var
aUsuario : TUsuarioDao;
begin
aUsuario := TUsuarioDao.GetInstance;
aUsuario.Load;
FActivateLoaded := True;
if aUsuario.IsAtivo then
AbrirMenu
else
AbrirLogin;
end;
procedure TFrmSplashUI.FormActivate(Sender: TObject);
var
aEspecilidades : TEspecialidadeDao;
begin
if (FActivateLoaded = False) then
begin
aEspecilidades := TEspecialidadeDao.GetInstance;
if DtmDados.IsConectado then
if (aEspecilidades.GetCount() = 0) then
Carregar
else
CarregarFormulario;
end;
end;
procedure TFrmSplashUI.FormCreate(Sender: TObject);
{$IF DEFINED (ANDROID)}
var
PkgInfo : JPackageInfo;
{$ENDIF}
begin
ProgressBar.Max := 0;
ProgressBar.Value := 0;
LabelVersion.Text := 'Versão ' + VERSION_NAME;
{$IF DEFINED (ANDROID)}
PkgInfo := SharedActivity.getPackageManager.getPackageInfo(SharedActivity.getPackageName, 0);
LabelVersion.Text := 'Versão ' + JStringToString(PkgInfo.versionName);
{$ENDIF}
TabControlSplash.ActiveTab := TabSplash;
ScrollBoxForm.OnCalcContentBounds := CalcContentBounds;
FActivateLoaded := False;
aLayoutLogin := nil;
aLayoutCadastro := nil;
end;
procedure TFrmSplashUI.FormFocusChanged(Sender: TObject);
begin
UpdatePosition;
end;
procedure TFrmSplashUI.FormVirtualKeyboardHidden(Sender: TObject; KeyboardVisible: Boolean;
const Bounds: TRect);
begin
FWBounds.Create(0, 0, 0, 0);
FNeedOffSet := False;
RestorePosition;
end;
procedure TFrmSplashUI.FormVirtualKeyboardShown(Sender: TObject; KeyboardVisible: Boolean;
const Bounds: TRect);
begin
FWBounds := TRectF.Create(Bounds);
FWBounds.TopLeft := ScreenToClient(FWBounds.TopLeft);
FWBounds.BottomRight := ScreenToClient(FWBounds.BottomRight);
UpdatePosition;
end;
procedure TFrmSplashUI.MudarForm(TabItem: TTabItem; Sender: TObject);
begin
acMudarForm.Tab := TabItem;
acMudarForm.ExecuteTarget(Sender);
end;
procedure TFrmSplashUI.RestorePosition;
begin
ScrollBoxForm.ViewportPosition := PointF(ScrollBoxForm.ViewportPosition.X, 0);
LayoutForm.Align := TAlignLayout.Client;
ScrollBoxForm.RealignContent;
end;
procedure TFrmSplashUI.UpdatePosition;
var
LFocused : TControl;
LFocusRect : TRectF;
begin
FNeedOffSet := False;
if Assigned(Focused) then
begin
LFocused := TControl(Focused.GetObject);
LFocusRect := LFocused.AbsoluteRect;
LFocusRect.Offset(ScrollBoxForm.ViewportPosition);
if (LFocusRect.IntersectsWith(TRectF.Create(FWBounds)) and (LFocusRect.Bottom > FWBounds.Top)) then
begin
FNeedOffSet := True;
LayoutForm.Align := TAlignLayout.Horizontal;
ScrollBoxForm.RealignContent;
Application.ProcessMessages;
ScrollBoxForm.ViewportPosition := PointF(ScrollBoxForm.ViewportPosition.X, LFocusRect.Bottom - FWBounds.Top);
end;
end;
if not FNeedOffSet then
RestorePosition;
end;
end.
|
unit MathVectors;
{$mode objfpc}{$H+}{$interfaces corba}
interface
uses
Classes, SysUtils, MathBasics;
type
TIVector = interface(TIMathObject)
function Add(const x:TIVector):TIVector;
function Sub(const x:TIVector):TIVector;
function Mul(const x:TIVector):TIVector;
property AsString:String;
property components[index:Integer]:TIMathObject; default;
end;
TCVector = class(TIVector)
private
_components: Array of TIMathObject;
function GetComponent(idx:Integer):TIMathObject;
procedure SetComponent(idx:Integer;const component:TIMathObject);
public
constructor Create(dim:Integer);
function Add(const x:TIVector):TIVector;
function Sub(const x:TIVector):TIVector;
function Mul(const x:TIVector):TIVector;
property AsString:String;
function IsIn(S:TIMathSet):Boolean;
property components[index:Integer]:TIMathObject read GetComponent write SetComponent; default;
destructor Destroy;
end;
implementation
constructor TCVector.Create(dim:Integer);
begin
SetLength(_components, dim);
end;
function TCVector.Add(const x:TIVector):TIVector;
var
i: Integer;
begin
end;
function TCVector.Sub(const x:TIVector):TIVector;
begin
end;
function TCVector.Mul(const x:TIVector):TIVector;
begin
end;
function TCVector.GetComponent(idx: Integer):TIMathObject;
begin
Result := _components[idx];
end;
procedure TCVector.SetComponent(idx: Integer; const component:TIMathObject);
begin
_components[idx] := component;
end;
function TCVector.IsIn(S: TIMathSet):Boolean;
begin
Result := S.Contains(TIVector(Self));
end;
destructor TCVector.Destroy;
begin
SetLength(_components, 0);
end;
end.
|
PROGRAM SortFile(INPUT, OUTPUT);
CONST
SwitchOn = '1';
SwitchOff = '2';
No = 'N';
Yes = 'Y';
VAR
F: TEXT;
Ch: CHAR;
PROCEDURE CopyFile(VAR F1, F2: TEXT);
VAR
Ch: CHAR;
BEGIN
RESET(F1);
REWRITE(F2);
WHILE NOT(EOLN(F1))
DO
BEGIN
READ(F1, Ch);
WRITE(F2, Ch)
END;
WRITELN(F2)
END;
PROCEDURE RecursiveSort(VAR F1: TEXT);
VAR
F2, F3: TEXT;
PROCEDURE Split(VAR F1, F2, F3: TEXT);
VAR
Ch, Switch: CHAR;
BEGIN {Split}
RESET(F1);
REWRITE(F2);
REWRITE(F3);
Switch := SwitchOn;
WHILE NOT(EOLN(F1))
DO
BEGIN
READ(F1, Ch);
IF Switch = SwitchOn
THEN
BEGIN
WRITE(F2, Ch);
Switch := SwitchOff;
END
ELSE
BEGIN
WRITE(F3, Ch);
Switch := SwitchOn;
END
END;
WRITELN(F2);
WRITELN(F3)
END; {Split}
PROCEDURE CopyLetter(VAR F1, F2: TEXT; VAR Ch2, Ch3, Sorted: CHAR);
BEGIN {CopyLetter}
WRITE(F1, Ch2);
IF EOLN(F2)
THEN
BEGIN
Sorted := Yes;
WRITE(F1, Ch3)
END
ELSE
READ(F2, Ch2)
END; {CopyLetter}
PROCEDURE Merge(VAR F1, F2, F3: TEXT);
VAR
Ch2, Ch3, Sorted : CHAR;
BEGIN {Merge}
RESET(F2);
RESET(F3);
REWRITE(F1);
Sorted := No;
IF NOT(EOLN(F2)) AND NOT(EOLN(F3))
THEN
BEGIN
READ(F2, Ch2);
READ(F3, Ch3);
WHILE Sorted = No
DO
BEGIN
IF Ch2 < Ch3
THEN
CopyLetter(F1, F2, Ch2, Ch3, Sorted)
ELSE
CopyLetter(F1, F3, Ch3, Ch2, Sorted)
END
END;
IF NOT(EOLN(F2)) OR NOT(EOLN(F3))
THEN
IF NOT(EOLN(F2))
THEN
CopyFile(F2, F1)
ELSE
CopyFile(F3, F1)
ELSE
WRITELN(F1)
END; {Merge}
BEGIN {RecursiveSort}
RESET(F1);
IF NOT(EOLN(F1))
THEN
BEGIN
READ(F1, Ch);
IF NOT(EOLN(F1))
THEN
BEGIN
Split(F1, F2, F3);
RecursiveSort(F2);
RecursiveSort(F3);
Merge(F1, F2, F3)
END
END
END; {RecursiveSort}
BEGIN {SortFile}
CopyFile(INPUT, F);
RecursiveSort(F);
CopyFile(F, OUTPUT)
END. {SortFile}
|
unit FHIRTagManager;
{
Copyright (c) 2011+, HL7 and Health Intersections Pty Ltd (http://www.healthintersections.com.au)
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
}
interface
uses
SysUtils, Classes, kCritSct,
AdvObjects, AdvGenerics,
FHIRTags;
type
TFHIRTagManager = class (TAdvObject)
private
FLock: TCriticalSection;
FTags: TFHIRTagList;
FTagsByKey: TAdvMap<TFHIRTag>;
FLastTagVersionKey: integer;
FLastTagKey: integer;
public
constructor Create(); override;
destructor Destroy; override;
property LastTagVersionKey: integer read FLastTagVersionKey write FLastTagVersionKey;
property LastTagKey: integer read FLastTagKey write FLastTagKey;
procedure crossLink;
function add(key : integer; category : TFHIRTagCategory; uri, code, display : String): TFHIRTag;
function GetTagByKey(key: integer): TFHIRTag;
function KeyForTag(category : TFHIRTagCategory; system, code: String): integer;
function findTag(category : TFHIRTagCategory; system, code : String) : TFHIRTag;
procedure registerTag(tag : TFHIRTag);
function NextTagVersionKey: integer;
function NextTagKey: integer;
end;
implementation
{ TFHIRTagManager }
procedure TFHIRTagManager.registerTag(tag: TFHIRTag);
begin
FTags.add(tag.Link);
FTagsByKey.add(inttostr(FLastTagKey), tag.Link);
end;
constructor TFHIRTagManager.Create;
begin
inherited create;
FLock := TCriticalSection.Create('session-manager');
FTags := TFHIRTagList.Create;
FTagsByKey := TAdvMap<TFHIRTag>.Create;
end;
procedure TFHIRTagManager.crossLink;
var
i : integer;
begin
FLock.Lock;
try
for i := 0 to FTags.Count - 1 do
FTagsByKey.add(inttostr(FTags[i].key), FTags[i].Link);
finally
FLock.Unlock;
end;
end;
destructor TFHIRTagManager.Destroy;
begin
FTagsByKey.free;
FTags.free;
FLock.Free;
inherited;
end;
function TFHIRTagManager.findTag(category: TFHIRTagCategory; system, code: String): TFHIRTag;
begin
FLock.Lock('findTag');
try
result := FTags.findTag(category, system, code);
finally
FLock.Unlock;
end;
end;
function TFHIRTagManager.add(key: integer; category: TFHIRTagCategory; uri, code, display: String): TFHIRTag;
begin
FLock.Lock;
try
result := FTags.addTag(key, category, uri, code, display);
finally
FLock.Unlock;
end;
end;
function TFHIRTagManager.GetTagByKey(key: integer): TFHIRTag;
begin
FLock.Lock('GetTagByKey');
try
if FTagsByKey.TryGetValue(inttostr(key), result) then
result := result.Link
else
result := nil;
finally
FLock.Unlock;
end;
end;
function TFHIRTagManager.KeyForTag(category : TFHIRTagCategory; system, code: String): integer;
var
p: TFHIRTag;
begin
FLock.Lock('KeyForTag');
try
p := FTags.findTag(category, system, code);
if (p = nil) then
result := 0
else
result := p.key;
finally
FLock.Unlock;
end;
end;
function TFHIRTagManager.NextTagVersionKey: integer;
begin
FLock.Lock('NextTagVersionKey');
try
inc(FLastTagVersionKey);
result := FLastTagVersionKey;
finally
FLock.Unlock;
end;
end;
function TFHIRTagManager.NextTagKey: integer;
begin
FLock.Lock('NextTagKey');
try
inc(FLastTagKey);
result := FLastTagKey;
finally
FLock.Unlock;
end;
end;
end.
|
unit soundsplay;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, MMSystem;
type
TEntranceSoundPlayer = class(TObject)
private
Fsound_notify: Pointer;
Fsound_chimny: Pointer;
Fsound_tada: Pointer;
procedure Setsound_chimny(const Value: Pointer);
procedure Setsound_notify(const Value: Pointer);
procedure Setsound_tada(const Value: Pointer);
public
constructor Create();
destructor Destroy();override;
procedure play(AResource: Pointer);
property sound_tada: Pointer read Fsound_tada write Setsound_tada;
property sound_chimny: Pointer read Fsound_chimny write Setsound_chimny;
property sound_notify: Pointer read Fsound_notify write Setsound_notify;
end;
implementation
{$R sounds.res}
{ TEntranceSoundPlayer }
constructor TEntranceSoundPlayer.Create;
begin
Fsound_tada := Pointer(FindResource(hInstance, 'tada', 'wave'));
if Fsound_tada <> nil then begin
Fsound_tada := Pointer(LoadResource(hInstance, HRSRC(Fsound_tada)));
if Fsound_tada <> nil then Fsound_tada := LockResource(HGLOBAL(Fsound_tada));
end;
Fsound_chimny := Pointer(FindResource(hInstance, 'chimny', 'wave'));
if Fsound_chimny <> nil then begin
Fsound_chimny := Pointer(LoadResource(hInstance, HRSRC(Fsound_chimny)));
if Fsound_chimny <> nil then Fsound_chimny := LockResource(HGLOBAL(Fsound_chimny));
end;
Fsound_notify := Pointer(FindResource(hInstance, 'notify', 'wave'));
if Fsound_notify <> nil then begin
Fsound_notify := Pointer(LoadResource(hInstance, HRSRC(Fsound_notify)));
if Fsound_notify <> nil then Fsound_notify := LockResource(HGLOBAL(Fsound_notify));
end;
end;
destructor TEntranceSoundPlayer.Destroy;
begin
UnlockResource(HGLOBAL(Fsound_tada));
UnlockResource(HGLOBAL(Fsound_chimny));
UnlockResource(HGLOBAL(Fsound_notify));
inherited;
end;
procedure TEntranceSoundPlayer.play(AResource: Pointer);
begin
sndPlaySound(AResource, SND_MEMORY
or SND_NODEFAULT or SND_ASYNC);
end;
procedure TEntranceSoundPlayer.Setsound_chimny(const Value: Pointer);
begin
Fsound_chimny := Value;
end;
procedure TEntranceSoundPlayer.Setsound_notify(const Value: Pointer);
begin
Fsound_notify := Value;
end;
procedure TEntranceSoundPlayer.Setsound_tada(const Value: Pointer);
begin
Fsound_tada := Value;
end;
end.
|
unit RRManagerArrangeReportColumnsFrame;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, RRManagerBaseGUI, ImgList, Buttons, ExtCtrls, ComCtrls, RRManagerReport,
ActnList, RRManagerBaseObjects;
type
// TfrmArrangeColumnReports = class(TFrame)
TfrmArrangeColumnsFrame = class(TBaseFrame)
lwColumns: TListView;
pnlButtons: TPanel;
sbtnUp: TSpeedButton;
sbtnDown: TSpeedButton;
sbtnAllDown: TSpeedButton;
sbtnAllUp: TSpeedButton;
imgList: TImageList;
actnList: TActionList;
actnUp: TAction;
actnDown: TAction;
actnAllUp: TAction;
actnAllDown: TAction;
procedure actnUpExecute(Sender: TObject);
procedure actnUpUpdate(Sender: TObject);
procedure actnDownExecute(Sender: TObject);
procedure actnDownUpdate(Sender: TObject);
procedure actnAllUpExecute(Sender: TObject);
procedure actnAllUpUpdate(Sender: TObject);
procedure actnAllDownExecute(Sender: TObject);
procedure actnAllDownUpdate(Sender: TObject);
procedure lwColumnsAdvancedCustomDrawItem(Sender: TCustomListView;
Item: TListItem; State: TCustomDrawState; Stage: TCustomDrawStage;
var DefaultDraw: Boolean);
private
FReportColumns: TReportColumns;
{ Private declarations }
procedure ReloadColumns;
function GetReport: TCommonReport;
procedure SetReportColumns(const Value: TReportColumns);
protected
procedure FillControls(ABaseObject: TBaseObject); override;
procedure ClearControls; override;
procedure RegisterInspector; override;
public
{ Public declarations }
procedure Save; override;
property Columns: TReportColumns read FReportColumns write SetReportColumns;
property Report: TCommonReport read GetReport;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
end;
implementation
{$R *.dfm}
{ TfrmArrangeColumnReports }
procedure TfrmArrangeColumnsFrame.ClearControls;
begin
inherited;
lwColumns.Items.Clear;
end;
constructor TfrmArrangeColumnsFrame.Create(AOwner: TComponent);
begin
inherited;
FReportColumns := TReportColumns.Create;
NeedCopyState := false;
end;
destructor TfrmArrangeColumnsFrame.Destroy;
begin
FReportColumns.Free;
inherited;
end;
procedure TfrmArrangeColumnsFrame.FillControls(ABaseObject: TBaseObject);
begin
end;
function TfrmArrangeColumnsFrame.GetReport: TCommonReport;
begin
Result := EditingObject as TCommonReport;
end;
procedure TfrmArrangeColumnsFrame.RegisterInspector;
begin
inherited;
end;
procedure TfrmArrangeColumnsFrame.SetReportColumns(
const Value: TReportColumns);
var i: integer;
cl: TReportColumn;
begin
if FReportColumns <> Value then
begin
// так сделано чтобы раз установленный порядок столбцов не менялся
// если просто присваивать, новые столбцы то старательно настроенная очередность - теряется
for i := FReportColumns.Count - 1 downto 0 do
if not Assigned(Value.ColByName(FReportColumns.Items[i].ColName)) then
FReportColumns.Delete(i);
for i := 0 to Value.Count - 1 do
if not Assigned(FReportColumns.ColByName(Value.Items[i].ColName)) then
begin
cl := TReportColumn.Create;
cl.Assign(Value.Items[i]);
FReportColumns.Add(cl);
end;
ReloadColumns;
end;
end;
procedure TfrmArrangeColumnsFrame.actnUpExecute(Sender: TObject);
var iIndex: integer;
begin
iIndex := lwColumns.Selected.Index - 1;
FReportColumns.Exchange(lwColumns.Selected.Index, lwColumns.Selected.Index - 1);
ReloadColumns;
lwColumns.Items[iIndex].Selected := true;
end;
procedure TfrmArrangeColumnsFrame.actnUpUpdate(Sender: TObject);
begin
actnUp.Enabled := Assigned(lwColumns.Selected) and (lwColumns.Selected.Index > 0);
end;
procedure TfrmArrangeColumnsFrame.actnDownExecute(Sender: TObject);
var iIndex: integer;
begin
iIndex := lwColumns.Selected.Index + 1;
FReportColumns.Exchange(lwColumns.Selected.Index, lwColumns.Selected.Index + 1);
ReloadColumns;
lwColumns.Items[iIndex].Selected := true;
end;
procedure TfrmArrangeColumnsFrame.actnDownUpdate(Sender: TObject);
begin
actnDown.Enabled := Assigned(lwColumns.Selected) and (lwColumns.Selected.Index < lwColumns.Items.Count - 1);
end;
procedure TfrmArrangeColumnsFrame.actnAllUpExecute(Sender: TObject);
begin
FReportColumns.Exchange(lwColumns.Selected.Index, 0);
ReloadColumns;
lwColumns.Items[0].Selected := true;
end;
procedure TfrmArrangeColumnsFrame.actnAllUpUpdate(Sender: TObject);
begin
actnAllUp.Enabled := Assigned(lwColumns.Selected) and (lwColumns.Selected.Index > 0);
end;
procedure TfrmArrangeColumnsFrame.actnAllDownExecute(Sender: TObject);
begin
FReportColumns.Exchange(lwColumns.Selected.Index, lwColumns.Items.Count - 1);
ReloadColumns;
lwColumns.Items[lwColumns.Items.Count - 1].Selected := true;
end;
procedure TfrmArrangeColumnsFrame.actnAllDownUpdate(Sender: TObject);
begin
actnAllDown.Enabled := Assigned(lwColumns.Selected) and (lwColumns.Selected.Index < lwColumns.Items.Count - 1);
end;
procedure TfrmArrangeColumnsFrame.ReloadColumns;
var i: integer;
begin
lwColumns.Items.BeginUpdate;
lwColumns.Items.Clear;
for i := 0 to FReportColumns.Count - 1 do
lwColumns.AddItem(FReportColumns.Items[i].RusColName, FReportColumns.Items[i]);
lwColumns.Items.EndUpdate;
end;
procedure TfrmArrangeColumnsFrame.lwColumnsAdvancedCustomDrawItem(
Sender: TCustomListView; Item: TListItem; State: TCustomDrawState;
Stage: TCustomDrawStage; var DefaultDraw: Boolean);
//var R: TRect;
begin
{if (TReportColumn(Item.Data).Order = 1000) and not(cdsSelected in State) then
begin
R := Item.DisplayRect(drBounds);
// новые обозначаем
Sender.Canvas.Font.Style := Sender.Canvas.Font.Style + [fsBold];
Sender.Canvas.TextOut(R.Left + 2, R.Top + 1, Item.Caption);
end;}
end;
procedure TfrmArrangeColumnsFrame.Save;
begin
if not Assigned(EditingObject) then
FEditingObject := AllReports.Items[AllReports.Count - 1];
Report.ArrangedColumns.Clear;
Report.ArrangedColumns.Assign(FReportColumns);
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.