text stringlengths 14 6.51M |
|---|
unit UBarcodeDemo;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls,
FMX.Objects, FMX.TMSCloudImage, FMX.TMSCloudBase, FMX.TMSCloudBaseFMX,
FMX.TMSCloudCustomBarcode, FMX.TMSCloudBarcode, FMX.ListBox, FMX.Edit, TypInfo;
type
TForm9 = class(TForm)
TMSFMXCloudBarcode1: TTMSFMXCloudBarcode;
Button1: TButton;
Button2: TButton;
Label1: TLabel;
Panel1: TPanel;
TMSFMXCloudImage1: TTMSFMXCloudImage;
Label2: TLabel;
Label3: TLabel;
Edit1: TEdit;
cbCodeType: TComboBox;
GroupBox1: TGroupBox;
Label4: TLabel;
Label5: TLabel;
Label6: TLabel;
cbType: TComboBox;
edWidth: TEdit;
edHeight: TEdit;
cbShowText: TCheckBox;
GroupBox2: TGroupBox;
Label7: TLabel;
cbSize: TComboBox;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure cbCodeTypeChange(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
procedure InitOptions;
end;
var
Form9: TForm9;
implementation
{$R *.fmx}
procedure TForm9.Button1Click(Sender: TObject);
var
bctype: TBarcodeType;
begin
if Edit1.Text = '' then
begin
ShowMessage('Please enter a value first');
exit;
end;
if cbCodeType.ItemIndex = 0 then
begin
case cbType.ItemIndex of
1: bctype := btC128a;
2: bctype := btC128b;
3: bctype := btC128c;
4: bctype := bti2of5;
else
bctype := btC39;
end;
TMSFMXCloudBarcode1.BarcodeOptions.ShowText := cbShowText.IsChecked;
TMSFMXCloudBarcode1.BarcodeOptions.Width := StrToInt(edWidth.Text);
TMSFMXCloudBarcode1.BarcodeOptions.Height := StrToInt(edHeight.Text);
TMSFMXCloudImage1.Width := TMSFMXCloudBarcode1.BarcodeOptions.Width;
TMSFMXCloudImage1.Height := TMSFMXCloudBarcode1.BarcodeOptions.Height;
TMSFMXCloudImage1.URL := TMSFMXCloudBarcode1.GetBarcodeURL(Edit1.Text, bctype);
end
else
begin
case cbSize.ItemIndex of
0: TMSFMXCloudBarcode1.QRcodeOptions.Size := qs42;
1: TMSFMXCloudBarcode1.QRcodeOptions.Size := qs105;
2: TMSFMXCloudBarcode1.QRcodeOptions.Size := qs210;
end;
TMSFMXCloudImage1.Width := StrToInt(StringReplace(GetEnumName(TypeInfo(TQRcodeSize),
Ord(TMSFMXCloudBarcode1.QRcodeOptions.Size)), 'qs', '', []));
TMSFMXCloudImage1.Height := TMSFMXCloudImage1.Width;
TMSFMXCloudImage1.URL := TMSFMXCloudBarcode1.GetQRCodeURL(Edit1.Text);
end;
end;
procedure TForm9.Button2Click(Sender: TObject);
var
sv: TSaveDialog;
begin
sv := TSaveDialog.Create(Self);
sv.FileName := 'barcode' + Edit1.Text + '.png';
if sv.Execute then
TMSFMXCloudImage1.Bitmap.SaveToFile(sv.FileName);
end;
procedure TForm9.cbCodeTypeChange(Sender: TObject);
begin
InitOptions;
end;
procedure TForm9.FormCreate(Sender: TObject);
begin
InitOptions;
end;
procedure TForm9.InitOptions;
begin
if cbCodeType.ItemIndex = 0 then
begin
cbType.Enabled := true;
edWidth.Enabled := true;
edHeight.Enabled := true;
cbShowText.Enabled := true;
cbSize.Enabled := false;
end
else
begin
cbType.Enabled := false;
edWidth.Enabled := false;
edHeight.Enabled := false;
cbShowText.Enabled := false;
cbSize.Enabled := true;
end;
end;
end.
|
{**************************************************************************\
*
* Module Name: PMFONT.H
*
* OS/2 Presentation Manager type declarations for Fonts.
*
* Copyright (c) International Business Machines Corporation 1981, 1988-1990
*
\**************************************************************************}
{| Version: 1.00
| Original translation: Peter Singer (PSi)
}
Unit PmFONT;
Interface
Uses
Os2Def;
TYPE
FOCAMETRICS = record { foca }
ulIdentity,
ulSize : ULONG;
szFamilyname,
szFacename : array[0..31] of char;
usRegistryId,
usCodePage,
yEmHeight,
yXHeight,
yMaxAscender,
yMaxDescender,
yLowerCaseAscent,
yLowerCaseDescent,
yInternalLeading,
yExternalLeading,
xAveCharWidth,
xMaxCharInc,
xEmInc,
yMaxBaselineExt,
sCharSlope,
sInlineDir,
sCharRot : SHORT;
usWeightClass,
usWidthClass : USHORT;
xDeviceRes,
yDeviceRes,
usFirstChar,
usLastChar,
usDefaultChar,
usBreakChar,
usNominalPointSize,
usMinimumPointSize,
usMaximumPointSize,
fsTypeFlags,
fsDefn,
fsSelectionFlags,
fsCapabilities,
ySubscriptXSize,
ySubscriptYSize,
ySubscriptXOffset,
ySubscriptYOffset,
ySuperscriptXSize,
ySuperscriptYSize,
ySuperscriptXOffset,
ySuperscriptYOffset,
yUnderscoreSize,
yUnderscorePosition,
yStrikeoutSize,
yStrikeoutPosition,
usKerningPairs,
sFamilyClass : SHORT;
pszDeviceNameOffset: PSZ;
end;
PFOCAMETRICS = ^FOCAMETRICS;
FONTDEFINITIONHEADER = record { fdh }
ulIdentity,
ulSize : ULONG;
fsFontdef,
fsChardef,
usCellSize,
xCellWidth,
yCellHeight,
xCellIncrement,
xCellA,
xCellB,
xCellC,
pCellBaseOffset: SHORT;
end;
PFONTDEFINITIONHEADER = ^FONTDEFINITIONHEADER;
CONST
FONTDEFFONT1 = $0047; { set width, height, inc. & base offset }
FONTDEFFONT2 = $0042; { set heigh=t & base offset }
FONTDEFFONT3 = $0042; { set height & base offset }
FONTDEFCHAR1 = $0081; { set char offset and width }
FONTDEFCHAR2 = $0081; { set char offset and width }
FONTDEFCHAR3 = $00b8; { set char offset, A, B, and C space }
SPACE_UNDEF = $8000; { space undefined = take default }
TYPE
FONTSIGNATURE = record { fs }
ulIdentity,
ulSize : ULONG;
achSignature: Array[0..11] of char;
end;
PFONTSIGNATURE = ^FONTSIGNATURE;
FOCAFONT = record { ff }
fsSignature : FONTSIGNATURE;
fmMetrics : FOCAMETRICS;
fdDefinitions: FONTDEFINITIONHEADER;
end;
PFOCAFONT = ^FOCAFONT;
CONST
FONT_SIGNATURE = $fffffffe; { Identity header start }
FONT_METRICS = $00000001; { Identity metrics }
FONT_DEFINITION= $00000002; { Identity definition }
FONT_ENDRECORD = $ffffffff; { Identity record end }
{ Options for QueryFonts }
QUERY_PUBLIC_FONTS = $0001;
QUERY_PRIVATE_FONTS = $0002;
CDEF_GENERIC = $0001;
CDEF_BOLD = $0002;
CDEF_ITALIC = $0004;
CDEF_UNDERSCORE = $0008;
CDEF_STRIKEOUT = $0010;
CDEF_OUTLINE = $0020;
implementation
end. |
PROGRAM TresEnRaya;
USES
CRT;
CONST
INI = 1;
FIN = 3;
TYPE
TTablero = ARRAY [INI..FIN, INI..FIN] OF char;
PROCEDURE Inicializar (VAR t: TTablero);
VAR
i, j: integer;
BEGIN
FOR i:= INI TO FIN DO
FOR j:= INI TO FIN DO
t[i,j] := '-';
END;
PROCEDURE Mostrar (t: TTablero);
VAR
i, j: integer;
BEGIN
writeln;
FOR i:= INI TO FIN DO BEGIN
FOR j:= INI TO FIN DO
write (t[i,j], ' ');
writeln;
END;
writeln;
END;
PROCEDURE JugarM (VAR t: TTablero);
VAR
i, j: integer;
valido: boolean;
BEGIN
REPEAT
writeln ('Dame coordenadas validas y vacias');
readln (i, j);
valido := (i >= INI) AND (i <= FIN) AND (j >= INI) AND (j <= FIN) AND (t[i,j] = '-');
UNTIL valido;
t[i,j] := 'X';
END;
PROCEDURE JugarA (VAR t: TTablero);
VAR
i, j: integer;
valido: boolean;
BEGIN
REPEAT
i:= RANDOM (FIN) + 1;
j:= RANDOM (FIN) + 1;
valido := (t[i,j] = '-');
UNTIL valido;
t[i,j] := 'O';
END;
FUNCTION VerificarH (t: TTablero; ficha: char): boolean;
VAR
i, j: integer;
ok: boolean;
BEGIN
i := INI;
REPEAT
j := INI;
ok := TRUE;
REPEAT
ok := (t[i, j] = ficha);
j := SUCC (j);
UNTIL (j = FIN + 1) OR (NOT ok);
i := SUCC(i);
UNTIL ( i = FIN + 1) OR (ok);
VerificarH := ok;
END;
FUNCTION VerificarV (t: TTablero; ficha: char): boolean;
VAR
i, j: integer;
ok: boolean;
BEGIN
j := INI;
REPEAT
i := INI;
ok := TRUE;
REPEAT
ok := (t[i, j] = ficha);
i := SUCC (i);
UNTIL (i = FIN + 1) OR (NOT ok);
j := SUCC(j);
UNTIL ( j = FIN + 1) OR (ok);
VerificarV := ok;
END;
FUNCTION VerificarDD (t: TTablero; ficha: char): boolean;
VAR
i, j: integer;
ok: boolean;
BEGIN
i := INI; j := INI; ok := TRUE;
REPEAT
ok := (t[i, j] = ficha);
i := SUCC (i);
j := SUCC (j);
UNTIL (i = FIN + 1) OR (NOT ok);
VerificarDD := ok;
END;
FUNCTION VerificarDI (t: TTablero; ficha: char): boolean;
VAR
i, j: integer;
ok: boolean;
BEGIN
i := INI; j := FIN; ok := TRUE;
REPEAT
ok := (t[i, j] = ficha);
i := SUCC (i);
j := PRED (j);
UNTIL (i = FIN + 1) OR (NOT ok);
VerificarDI := ok;
END;
FUNCTION Verificar (t: TTablero; ficha: char): boolean;
BEGIN
Verificar := VerificarH (t, ficha) OR VerificarV (t, ficha) OR VerificarDD (t, ficha) OR VerificarDI (t, ficha);
END;
PROCEDURE Juego;
VAR
tablero: TTablero;
jugadas: integer;
victoria: boolean;
BEGIN
jugadas := INI; victoria:= FALSE;
Inicializar (tablero);
Mostrar (tablero);
REPEAT
IF ODD (jugadas) THEN BEGIN
JugarM (tablero);
Mostrar (tablero);
IF (jugadas >= FIN*FIN DIV 2) THEN BEGIN
victoria := Verificar (tablero, 'X');
IF victoria THEN
writeln ('Enhorabuena, has ganado');
END;
END
ELSE BEGIN
JugarA (tablero);
Mostrar (tablero);
IF (jugadas >= FIN*FIN DIV 2) THEN BEGIN
victoria := Verificar (tablero, 'O');
IF victoria THEN
writeln ('Vaya, te ha ganado la maquina');
END;
END;
jugadas := SUCC(jugadas);
UNTIL (jugadas > FIN*FIN) OR victoria;
IF NOT victoria THEN
writeln ('Tablas!');
END;
BEGIN
Randomize;
Juego;
READKEY;
END.
|
unit FileClass;
{
Inno Setup
Copyright (C) 1997-2010 Jordan Russell
Portions by Martijn Laan
For conditions of distribution and use, see LICENSE.TXT.
TFile class
Better than File and TFileStream in that does more extensive error checking
and uses descriptive, localized system error messages.
TTextFileReader and TTextFileWriter support ANSI and UTF8 textfiles only.
$jrsoftware: issrc/Projects/FileClass.pas,v 1.31 2010/01/26 06:26:18 jr Exp $
}
{$I VERSION.INC}
{$IFDEF IS_D6}
{$WARN SYMBOL_PLATFORM OFF}
{$ENDIF}
interface
uses
Windows, SysUtils, Int64Em;
type
TFileCreateDisposition = (fdCreateAlways, fdCreateNew, fdOpenExisting,
fdOpenAlways, fdTruncateExisting);
TFileAccess = (faRead, faWrite, faReadWrite);
TFileSharing = (fsNone, fsRead, fsWrite, fsReadWrite);
TCustomFile = class
private
function GetCappedSize: Cardinal;
protected
function GetPosition: Integer64; virtual; abstract;
function GetSize: Integer64; virtual; abstract;
public
class procedure RaiseError(ErrorCode: DWORD);
class procedure RaiseLastError;
function Read(var Buffer; Count: Cardinal): Cardinal; virtual; abstract;
procedure ReadBuffer(var Buffer; Count: Cardinal);
procedure Seek(Offset: Cardinal);
procedure Seek64(Offset: Integer64); virtual; abstract;
procedure WriteAnsiString(const S: AnsiString);
procedure WriteBuffer(const Buffer; Count: Cardinal); virtual; abstract;
property CappedSize: Cardinal read GetCappedSize;
property Position: Integer64 read GetPosition;
property Size: Integer64 read GetSize;
end;
TFile = class(TCustomFile)
private
FHandle: THandle;
FHandleCreated: Boolean;
protected
function CreateHandle(const AFilename: String;
ACreateDisposition: TFileCreateDisposition; AAccess: TFileAccess;
ASharing: TFileSharing): THandle; virtual;
function GetPosition: Integer64; override;
function GetSize: Integer64; override;
public
constructor Create(const AFilename: String;
ACreateDisposition: TFileCreateDisposition; AAccess: TFileAccess;
ASharing: TFileSharing);
constructor CreateWithExistingHandle(const AHandle: THandle);
destructor Destroy; override;
function Read(var Buffer; Count: Cardinal): Cardinal; override;
procedure Seek64(Offset: Integer64); override;
procedure SeekToEnd;
procedure Truncate;
procedure WriteBuffer(const Buffer; Count: Cardinal); override;
property Handle: THandle read FHandle;
end;
TMemoryFile = class(TCustomFile)
private
FMemory: Pointer;
FSize: Integer64;
FPosition: Integer64;
function ClipCount(DesiredCount: Cardinal): Cardinal;
protected
procedure AllocMemory(const ASize: Cardinal);
function GetPosition: Integer64; override;
function GetSize: Integer64; override;
public
constructor Create(const AFilename: String);
constructor CreateFromMemory(const ASource; const ASize: Cardinal);
constructor CreateFromZero(const ASize: Cardinal);
destructor Destroy; override;
function Read(var Buffer; Count: Cardinal): Cardinal; override;
procedure Seek64(Offset: Integer64); override;
procedure WriteBuffer(const Buffer; Count: Cardinal); override;
property Memory: Pointer read FMemory;
end;
TTextFileReader = class(TFile)
private
FBufferOffset, FBufferSize: Cardinal;
FEof: Boolean;
FBuffer: array[0..4095] of AnsiChar;
{$IFDEF UNICODE}
FSawFirstLine: Boolean;
FUTF8: Boolean;
{$ENDIF}
function DoReadLine{$IFDEF UNICODE}(const UTF8: Boolean){$ENDIF}: AnsiString;
function GetEof: Boolean;
procedure FillBuffer;
public
function ReadLine: String;
{$IFDEF UNICODE}
function ReadAnsiLine: AnsiString;
{$ENDIF}
property Eof: Boolean read GetEof;
end;
TTextFileWriter = class(TFile)
private
FSeekedToEnd: Boolean;
procedure DoWrite(const S: AnsiString{$IFDEF UNICODE}; const UTF8: Boolean{$ENDIF});
protected
function CreateHandle(const AFilename: String;
ACreateDisposition: TFileCreateDisposition; AAccess: TFileAccess;
ASharing: TFileSharing): THandle; override;
public
procedure Write(const S: String);
procedure WriteLine(const S: String);
{$IFDEF UNICODE}
procedure WriteAnsi(const S: AnsiString);
procedure WriteAnsiLine(const S: AnsiString);
{$ENDIF}
end;
TFileMapping = class
private
FMemory: Pointer;
FMapSize: Cardinal;
FMappingHandle: THandle;
public
constructor Create(AFile: TFile; AWritable: Boolean);
destructor Destroy; override;
procedure Commit;
procedure ReraiseInPageErrorAsFileException;
property MapSize: Cardinal read FMapSize;
property Memory: Pointer read FMemory;
end;
EFileError = class(Exception)
private
FErrorCode: DWORD;
public
property ErrorCode: DWORD read FErrorCode;
end;
implementation
uses
CmnFunc2;
const
SGenericIOError = 'File I/O error %d';
{ TCustomFile }
function TCustomFile.GetCappedSize: Cardinal;
{ Like GetSize, but capped at $7FFFFFFF }
var
S: Integer64;
begin
S := GetSize;
if (S.Hi = 0) and (S.Lo and $80000000 = 0) then
Result := S.Lo
else
Result := $7FFFFFFF;
end;
class procedure TCustomFile.RaiseError(ErrorCode: DWORD);
var
S: String;
E: EFileError;
begin
S := Win32ErrorString(ErrorCode);
if S = '' then begin
{ In case there was no text for the error code. Shouldn't get here under
normal circumstances. }
S := Format(SGenericIOError, [ErrorCode]);
end;
E := EFileError.Create(S);
E.FErrorCode := ErrorCode;
raise E;
end;
class procedure TCustomFile.RaiseLastError;
begin
RaiseError(GetLastError);
end;
procedure TCustomFile.ReadBuffer(var Buffer; Count: Cardinal);
begin
if Read(Buffer, Count) <> Count then begin
{ Raise localized "Reached end of file" error }
RaiseError(ERROR_HANDLE_EOF);
end;
end;
procedure TCustomFile.Seek(Offset: Cardinal);
var
I: Integer64;
begin
I.Hi := 0;
I.Lo := Offset;
Seek64(I);
end;
procedure TCustomFile.WriteAnsiString(const S: AnsiString);
begin
WriteBuffer(S[1], Length(S));
end;
{ TFile }
constructor TFile.Create(const AFilename: String;
ACreateDisposition: TFileCreateDisposition; AAccess: TFileAccess;
ASharing: TFileSharing);
begin
inherited Create;
FHandle := CreateHandle(AFilename, ACreateDisposition, AAccess, ASharing);
if (FHandle = 0) or (FHandle = INVALID_HANDLE_VALUE) then
RaiseLastError;
FHandleCreated := True;
end;
constructor TFile.CreateWithExistingHandle(const AHandle: THandle);
begin
inherited Create;
FHandle := AHandle;
end;
destructor TFile.Destroy;
begin
if FHandleCreated then
CloseHandle(FHandle);
inherited;
end;
function TFile.CreateHandle(const AFilename: String;
ACreateDisposition: TFileCreateDisposition; AAccess: TFileAccess;
ASharing: TFileSharing): THandle;
const
AccessFlags: array[TFileAccess] of DWORD =
(GENERIC_READ, GENERIC_WRITE, GENERIC_READ or GENERIC_WRITE);
SharingFlags: array[TFileSharing] of DWORD =
(0, FILE_SHARE_READ, FILE_SHARE_WRITE, FILE_SHARE_READ or FILE_SHARE_WRITE);
Disps: array[TFileCreateDisposition] of DWORD =
(CREATE_ALWAYS, CREATE_NEW, OPEN_EXISTING, OPEN_ALWAYS, TRUNCATE_EXISTING);
begin
Result := CreateFile(PChar(AFilename), AccessFlags[AAccess],
SharingFlags[ASharing], nil, Disps[ACreateDisposition],
FILE_ATTRIBUTE_NORMAL, 0);
end;
function TFile.GetPosition: Integer64;
begin
Result.Hi := 0;
Result.Lo := SetFilePointer(FHandle, 0, @Result.Hi, FILE_CURRENT);
if (Result.Lo = $FFFFFFFF) and (GetLastError <> 0) then
RaiseLastError;
end;
function TFile.GetSize: Integer64;
begin
Result.Lo := GetFileSize(FHandle, @Result.Hi);
if (Result.Lo = $FFFFFFFF) and (GetLastError <> 0) then
RaiseLastError;
end;
function TFile.Read(var Buffer; Count: Cardinal): Cardinal;
begin
if not ReadFile(FHandle, Buffer, Count, DWORD(Result), nil) then
if FHandleCreated or (GetLastError <> ERROR_BROKEN_PIPE) then
RaiseLastError;
end;
procedure TFile.Seek64(Offset: Integer64);
begin
if (SetFilePointer(FHandle, Integer(Offset.Lo), @Offset.Hi,
FILE_BEGIN) = $FFFFFFFF) and (GetLastError <> 0) then
RaiseLastError;
end;
procedure TFile.SeekToEnd;
var
DistanceHigh: Integer;
begin
DistanceHigh := 0;
if (SetFilePointer(FHandle, 0, @DistanceHigh, FILE_END) = $FFFFFFFF) and
(GetLastError <> 0) then
RaiseLastError;
end;
procedure TFile.Truncate;
begin
if not SetEndOfFile(FHandle) then
RaiseLastError;
end;
procedure TFile.WriteBuffer(const Buffer; Count: Cardinal);
var
BytesWritten: DWORD;
begin
if not WriteFile(FHandle, Buffer, Count, BytesWritten, nil) then
RaiseLastError;
if BytesWritten <> Count then begin
{ I'm not aware of any case where WriteFile will return True but a short
BytesWritten count. (An out-of-disk-space condition causes False to be
returned.) But if that does happen, raise a generic-sounding localized
"The system cannot write to the specified device" error. }
RaiseError(ERROR_WRITE_FAULT);
end;
end;
{ TMemoryFile }
constructor TMemoryFile.Create(const AFilename: String);
var
F: TFile;
begin
inherited Create;
F := TFile.Create(AFilename, fdOpenExisting, faRead, fsRead);
try
AllocMemory(F.CappedSize);
F.ReadBuffer(FMemory^, FSize.Lo);
finally
F.Free;
end;
end;
constructor TMemoryFile.CreateFromMemory(const ASource; const ASize: Cardinal);
begin
inherited Create;
AllocMemory(ASize);
Move(ASource, FMemory^, FSize.Lo);
end;
constructor TMemoryFile.CreateFromZero(const ASize: Cardinal);
begin
inherited Create;
AllocMemory(ASize);
FillChar(FMemory^, FSize.Lo, 0);
end;
destructor TMemoryFile.Destroy;
begin
if Assigned(FMemory) then
LocalFree(HLOCAL(FMemory));
inherited;
end;
procedure TMemoryFile.AllocMemory(const ASize: Cardinal);
begin
FMemory := Pointer(LocalAlloc(LMEM_FIXED, ASize));
if FMemory = nil then
OutOfMemoryError;
FSize.Lo := ASize;
end;
function TMemoryFile.ClipCount(DesiredCount: Cardinal): Cardinal;
var
BytesLeft: Integer64;
begin
{ First check if FPosition is already past FSize, so the Dec6464 call below
won't underflow }
if Compare64(FPosition, FSize) >= 0 then begin
Result := 0;
Exit;
end;
BytesLeft := FSize;
Dec6464(BytesLeft, FPosition);
if (BytesLeft.Hi = 0) and (BytesLeft.Lo < DesiredCount) then
Result := BytesLeft.Lo
else
Result := DesiredCount;
end;
function TMemoryFile.GetPosition: Integer64;
begin
Result := FPosition;
end;
function TMemoryFile.GetSize: Integer64;
begin
Result := FSize;
end;
function TMemoryFile.Read(var Buffer; Count: Cardinal): Cardinal;
begin
Result := ClipCount(Count);
if Result <> 0 then begin
Move(Pointer(Cardinal(FMemory) + FPosition.Lo)^, Buffer, Result);
Inc64(FPosition, Result);
end;
end;
procedure TMemoryFile.Seek64(Offset: Integer64);
begin
if Offset.Hi and $80000000 <> 0 then
RaiseError(ERROR_NEGATIVE_SEEK);
FPosition := Offset;
end;
procedure TMemoryFile.WriteBuffer(const Buffer; Count: Cardinal);
begin
if ClipCount(Count) <> Count then
RaiseError(ERROR_HANDLE_EOF);
if Count <> 0 then begin
Move(Buffer, Pointer(Cardinal(FMemory) + FPosition.Lo)^, Count);
Inc64(FPosition, Count);
end;
end;
{ TTextFileReader }
procedure TTextFileReader.FillBuffer;
begin
if (FBufferOffset < FBufferSize) or FEof then
Exit;
FBufferSize := Read(FBuffer, SizeOf(FBuffer));
FBufferOffset := 0;
if FBufferSize = 0 then
FEof := True;
end;
function TTextFileReader.GetEof: Boolean;
begin
FillBuffer;
Result := FEof;
end;
function TTextFileReader.ReadLine: String;
{$IFDEF UNICODE}
var
S: AnsiString;
{$ENDIF}
begin
{$IFDEF UNICODE}
S := DoReadLine(True);
if FUTF8 then
Result := UTF8ToString(S)
else
Result := String(S);
{$ELSE}
Result := DoReadLine;
{$ENDIF}
end;
{$IFDEF UNICODE}
function TTextFileReader.ReadAnsiLine: AnsiString;
begin
Result := DoReadLine(False);
end;
{$ENDIF}
function TTextFileReader.DoReadLine{$IFDEF UNICODE}(const UTF8: Boolean){$ENDIF}: AnsiString;
var
I, L: Cardinal;
S: AnsiString;
begin
while True do begin
FillBuffer;
if FEof then begin
{ End of file reached }
if S = '' then begin
{ If nothing was read (i.e. we were already at EOF), raise localized
"Reached end of file" error }
RaiseError(ERROR_HANDLE_EOF);
end;
Break;
end;
I := FBufferOffset;
while I < FBufferSize do begin
if FBuffer[I] in [#10, #13] then
Break;
Inc(I);
end;
L := Length(S);
if Integer(L + (I - FBufferOffset)) < 0 then
OutOfMemoryError;
SetLength(S, L + (I - FBufferOffset));
Move(FBuffer[FBufferOffset], S[L+1], I - FBufferOffset);
FBufferOffset := I;
if FBufferOffset < FBufferSize then begin
{ End of line reached }
Inc(FBufferOffset);
if FBuffer[FBufferOffset-1] = #13 then begin
{ Skip #10 if it follows #13 }
FillBuffer;
if (FBufferOffset < FBufferSize) and (FBuffer[FBufferOffset] = #10) then
Inc(FBufferOffset);
end;
Break;
end;
end;
{$IFDEF UNICODE}
if not FSawFirstLine then begin
{ Handle UTF8 BOM if requested }
if UTF8 and (Length(S) > 2) and (S[1] = #$EF) and (S[2] = #$BB) and (S[3] = #$BF) then begin
Delete(S, 1, 3);
FUTF8 := True;
end;
FSawFirstLine := True;
end;
{$ENDIF}
Result := S;
end;
{ TTextFileWriter }
function TTextFileWriter.CreateHandle(const AFilename: String;
ACreateDisposition: TFileCreateDisposition; AAccess: TFileAccess;
ASharing: TFileSharing): THandle;
begin
{ faWrite access isn't enough; we need faReadWrite access since the Write
method may read. No, we don't have to do this automatically, but it helps
keep it from being a 'leaky abstraction'. }
if AAccess = faWrite then
AAccess := faReadWrite;
Result := inherited CreateHandle(AFilename, ACreateDisposition, AAccess,
ASharing);
end;
{$IFDEF UNICODE}
procedure TTextFileWriter.DoWrite(const S: AnsiString; const UTF8: Boolean);
{$ELSE}
procedure TTextFileWriter.DoWrite(const S: String);
{$ENDIF}
{ Writes a string to the file, seeking to the end first if necessary }
const
CRLF: array[0..1] of AnsiChar = (#13, #10);
{$IFDEF UNICODE}
UTF8Preamble: array[0..2] of AnsiChar = (#$EF, #$BB, #$BF);
{$ENDIF}
var
I: Integer64;
C: AnsiChar;
begin
if not FSeekedToEnd then begin
I := GetSize;
if (I.Lo <> 0) or (I.Hi <> 0) then begin
{ File is not empty. Figure out if we have to append a line break. }
Dec64(I, SizeOf(C));
Seek64(I);
ReadBuffer(C, SizeOf(C));
case C of
#10: ; { do nothing - file ends in LF or CRLF }
#13: begin
{ If the file ends in CR, make it into CRLF }
C := #10;
WriteBuffer(C, SizeOf(C));
end;
else
{ Otherwise, append CRLF }
WriteBuffer(CRLF, SizeOf(CRLF));
end;
{$IFDEF UNICODE}
end else if UTF8 then
WriteBuffer(UTF8Preamble, SizeOf(UTF8Preamble));
{$ELSE}
end;
{$ENDIF}
FSeekedToEnd := True;
end;
WriteBuffer(Pointer(S)^, Length(S));
end;
procedure TTextFileWriter.Write(const S: String);
begin
{$IFDEF UNICODE}
DoWrite(UTF8Encode(S), True);
{$ELSE}
DoWrite(S);
{$ENDIF}
end;
procedure TTextFileWriter.WriteLine(const S: String);
begin
Write(S + #13#10);
end;
{$IFDEF UNICODE}
procedure TTextFileWriter.WriteAnsi(const S: AnsiString);
begin
DoWrite(S, False);
end;
procedure TTextFileWriter.WriteAnsiLine(const S: AnsiString);
begin
WriteAnsi(S + #13#10);
end;
{$ENDIF}
{ TFileMapping }
type
NTSTATUS = Longint;
var
_RtlNtStatusToDosError: function(Status: NTSTATUS): ULONG; stdcall;
constructor TFileMapping.Create(AFile: TFile; AWritable: Boolean);
const
Protect: array[Boolean] of DWORD = (PAGE_READONLY, PAGE_READWRITE);
DesiredAccess: array[Boolean] of DWORD = (FILE_MAP_READ, FILE_MAP_WRITE);
begin
inherited Create;
{ Dynamically import RtlNtStatusToDosError since Windows 95 doesn't have it }
if not Assigned(_RtlNtStatusToDosError) and
(Win32Platform = VER_PLATFORM_WIN32_NT) then
_RtlNtStatusToDosError := GetProcAddress(GetModuleHandle('ntdll.dll'),
'RtlNtStatusToDosError');
FMapSize := AFile.CappedSize;
FMappingHandle := CreateFileMapping(AFile.Handle, nil, Protect[AWritable], 0,
FMapSize, nil);
if FMappingHandle = 0 then
TFile.RaiseLastError;
FMemory := MapViewOfFile(FMappingHandle, DesiredAccess[AWritable], 0, 0,
FMapSize);
if FMemory = nil then
TFile.RaiseLastError;
end;
destructor TFileMapping.Destroy;
begin
if Assigned(FMemory) then
UnmapViewOfFile(FMemory);
if FMappingHandle <> 0 then
CloseHandle(FMappingHandle);
inherited;
end;
procedure TFileMapping.Commit;
{ Flushes modified pages to disk. To avoid silent data loss, this should
always be called prior to destroying a writable TFileMapping instance -- but
_not_ from a 'finally' section, as this method will raise an exception on
failure. }
begin
if not FlushViewOfFile(FMemory, 0) then
TFile.RaiseLastError;
end;
procedure TFileMapping.ReraiseInPageErrorAsFileException;
{ In Delphi, when an I/O error occurs while accessing a memory-mapped file --
known as an "inpage error" -- the user will see an exception message of
"External exception C0000006" by default.
This method examines the current exception to see if it's an inpage error
that occurred while accessing our mapped view, and if so, it raises a new
exception of type EFileError with a more friendly and useful message, like
you'd see when doing non-memory-mapped I/O with TFile. }
var
E: TObject;
begin
E := ExceptObject;
if (E is EExternalException) and
(EExternalException(E).ExceptionRecord.ExceptionCode = EXCEPTION_IN_PAGE_ERROR) and
(Cardinal(EExternalException(E).ExceptionRecord.NumberParameters) >= Cardinal(2)) and
(Cardinal(EExternalException(E).ExceptionRecord.ExceptionInformation[1]) >= Cardinal(FMemory)) and
(Cardinal(EExternalException(E).ExceptionRecord.ExceptionInformation[1]) < Cardinal(Cardinal(FMemory) + FMapSize)) then begin
{ NT has a third parameter containing the NT status code of the error
condition that caused the exception. Convert that into a Win32 error code
and use it to generate our error message. }
if (Cardinal(EExternalException(E).ExceptionRecord.NumberParameters) >= Cardinal(3)) and
Assigned(_RtlNtStatusToDosError) then
TFile.RaiseError(_RtlNtStatusToDosError(EExternalException(E).ExceptionRecord.ExceptionInformation[2]))
else begin
{ Windows 9x/Me doesn't have a third parameter, and 95 doesn't have
RtlNtStatusToDosError, so use generic "The system cannot [read|write]
to the specified device" errors }
if EExternalException(E).ExceptionRecord.ExceptionInformation[0] = 0 then
TFile.RaiseError(ERROR_READ_FAULT)
else
TFile.RaiseError(ERROR_WRITE_FAULT);
end;
end;
end;
end.
|
unit uClienteEmailVO;
interface
uses
System.SysUtils, uTableName, uKeyField;
type
[TableName('Cliente_Email')]
TClienteEmailVO = class
private
FEmail: string;
FId: Integer;
FIdCliente: Integer;
FNotificar: Boolean;
procedure SetEmail(const Value: string);
procedure SetId(const Value: Integer);
procedure SetIdCliente(const Value: Integer);
procedure SetNotificar(const Value: Boolean);
public
[KeyField('CliEm_Id')]
property Id: Integer read FId write SetId;
[FieldName('CliEm_Cliente')]
property IdCliente: Integer read FIdCliente write SetIdCliente;
[FieldName('CliEm_Email')]
property Email: string read FEmail write SetEmail;
[FieldName('CliEm_Notificar')]
property Notificar: Boolean read FNotificar write SetNotificar;
end;
implementation
{ TClienteEmailVO }
procedure TClienteEmailVO.SetEmail(const Value: string);
begin
FEmail := Value;
end;
procedure TClienteEmailVO.SetId(const Value: Integer);
begin
FId := Value;
end;
procedure TClienteEmailVO.SetIdCliente(const Value: Integer);
begin
FIdCliente := Value;
end;
procedure TClienteEmailVO.SetNotificar(const Value: Boolean);
begin
FNotificar := Value;
end;
end.
|
{
Copyright © 1999 by Harris Software Ltd
Author:Kyley Harris
Kyley@HarrisSoftware.com
------------------------------------------------------------------------------}
unit uHssStringsCSV;
interface
uses
sysutils,
classes;
type
THssCustomStringsCSV = class(TStringList)
private
FCSVDelim: char;
procedure SetCSVString(const Value: string);
function GetCSVString: string;
protected
procedure SetCSVDelim(const Value: char);virtual;
procedure HssAddCSV(const Value:string);
property CSVString:string read GetCSVString write SetCSVString;
function Get(Index: Integer): string; override;
public
constructor Create;
property CSVDelim:char read FCSVDelim write SetCSVDelim;
end;
THssStringsCSV = class(THssCustomStringsCSV)
public
property CSVString;
end;
implementation
{ THssStringsCSV }
procedure THssCustomStringsCSV.SetCSVString(const Value: string);
begin
{ Clear the list }
Clear;
{ Add the string Via CSV format }
HssAddCSV(value);
end;
function THssCustomStringsCSV.Get(Index: Integer): string;
begin
if Index >= Count then
result := '' else
result := inherited Get(index);
end;
function THssCustomStringsCSV.GetCSVString: string;
begin
result := CommaText;
end;
procedure THssCustomStringsCSV.HssAddCSV(const Value: string);
var
i:integer;
sParam:string;
ch:Char;
InStr:Boolean;
begin
sParam := '';
InStr := false;
for i := 1 to length(Value) do
begin
ch := Value[i];
if ch =
'"' then
begin
inStr := not InStr;
if (inStr) and (i > 1) and (Value[i-1] = '"') then
begin
sParam := sParam+ch;
end;
end else
if ch = FCSVDelim then
begin
if Not InStr then
begin
inherited Add(Trim(sParam));
sParam := '';
end else
begin
sParam := sParam+ch;
end;
end
else { case }
begin
sParam := sParam+ch;
end;
end;
sParam := Trim(sParam);
if sParam <> '' then
inherited Add(sParam);
end;
constructor THssCustomStringsCSV.Create;
begin
inherited;
CSVDelim := ',';
end;
procedure THssCustomStringsCSV.SetCSVDelim(const Value: char);
begin
FCSVDelim := Value;
end;
end.
|
unit DamFind;
interface
uses
{$IFDEF FPC}
Forms, StdCtrls, Controls, ExtCtrls, Classes,
{$ELSE}
Vcl.Forms, Vcl.StdCtrls, Vcl.Controls, Vcl.ExtCtrls, System.Classes,
{$ENDIF}
DamUnit;
type
TFrmDamFind = class(TForm)
Label1: TLabel;
EdText: TEdit;
L: TListBox;
BoxDIO: TPanel;
BtnCancel: TButton;
BtnOK: TButton;
EdMessage: TMemo;
procedure EdTextChange(Sender: TObject);
procedure BtnOKClick(Sender: TObject);
procedure LClick(Sender: TObject);
procedure LDblClick(Sender: TObject);
procedure FormShow(Sender: TObject);
private
Dam: TDam;
end;
var
FrmDamFind: TFrmDamFind;
function DoFindDamMessage(objDam: TDam; out objMsg: TDamMsg): Boolean;
implementation
{$R *.dfm}
uses
{$IFDEF FPC}
SysUtils, Dialogs;
{$ELSE}
System.SysUtils, Vcl.Dialogs;
{$ENDIF}
function DoFindDamMessage(objDam: TDam; out objMsg: TDamMsg): Boolean;
begin
FrmDamFind := TFrmDamFind.Create(Application);
try
FrmDamFind.Dam := objDam;
Result := FrmDamFind.ShowModal = mrOk;
if Result then
objMsg := TDamMsg(FrmDamFind.L.Items.Objects[FrmDamFind.L.ItemIndex]);
finally
FrmDamFind.Free;
end;
end;
//
procedure TFrmDamFind.FormShow(Sender: TObject);
begin
//Anchors must be defined on show due to Lazarus incorrect form size behavior
EdText.Anchors := [akLeft,akRight,akTop];
L.Anchors := [akLeft,akRight,akTop,akBottom];
EdMessage.Anchors := [akLeft,akRight,akBottom];
BoxDIO.Anchors := [akBottom];
end;
procedure TFrmDamFind.EdTextChange(Sender: TObject);
var
C: TComponent;
Msg: TDamMsg;
FindText, MsgName: string;
begin
L.Items.BeginUpdate;
try
L.Items.Clear;
FindText := UpperCase(EdText.Text);
if FindText=EmptyStr then Exit;
for C in Dam.Owner do
begin
if C.GetParentComponent = Dam then
begin
Msg := TDamMsg(C); //should be TDamMsg object!
if UpperCase(Msg.Name).Contains(FindText)
or UpperCase(Msg.Message).Contains(FindText) then
begin
MsgName := Msg.Name;
if MsgName.StartsWith('_') then Delete(MsgName, 1, 1);
L.AddItem(MsgName, Msg);
end;
end;
end;
if L.Items.Count>0 then
L.ItemIndex := 0; //select first item
finally
L.Items.EndUpdate;
LClick(nil);
end;
end;
procedure TFrmDamFind.LClick(Sender: TObject);
var Msg: TDamMsg;
begin
if L.ItemIndex<>-1 then
begin
Msg := TDamMsg(L.Items.Objects[L.ItemIndex]);
EdMessage.Text := Msg.Message;
end else
EdMessage.Text := EmptyStr;
end;
procedure TFrmDamFind.LDblClick(Sender: TObject);
begin
BtnOK.Click;
end;
procedure TFrmDamFind.BtnOKClick(Sender: TObject);
begin
if L.ItemIndex=-1 then
begin
MessageDlg('Please, select one message!', mtError, [mbOK], 0);
Exit;
end;
ModalResult := mrOk;
end;
end.
|
unit uCadVeiculos;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, UFrmPadrao, Data.DB, Vcl.StdCtrls,
Vcl.ExtCtrls, ZDataset, Vcl.Mask,
Vcl.ComCtrls, Vcl.DBCtrls, Vcl.Buttons,uClientes,uDtmPrincipal,
RxToolEdit,uCadVeiculo,uEnun, ZAbstractRODataset, ZAbstractDataset, Vcl.Grids,
Vcl.DBGrids;
type
TfrmCadVeiculo = class(TfrmPadrao)
lblCodigo: TLabeledEdit;
edtModelo: TLabeledEdit;
edtChassi: TLabeledEdit;
btnCadastroCliente: TBitBtn;
edtFabricante: TLabeledEdit;
cbTipoCambio: TComboBox;
Label1: TLabel;
Label3: TLabel;
cbCombustivel: TComboBox;
lkbCliente: TDBLookupComboBox;
lblCliente: TLabel;
zqCliente: TZQuery;
dsCliente: TDataSource;
edtDataCadastro: TDateEdit;
Label4: TLabel;
edtRevisao: TDateEdit;
Label5: TLabel;
Label2: TLabel;
Label6: TLabel;
mkeAno: TMaskEdit;
mmObs: TMemo;
Placa: TLabel;
zqPrincipalVeic_Cod: TIntegerField;
zqPrincipalVeic_Marca_Modelo: TWideStringField;
zqPrincipalVeic_Placa: TWideStringField;
zqPrincipalVeic_Chassi: TWideStringField;
zqPrincipalVeic_Ano: TWideStringField;
zqPrincipalVeic_TipoCombustivel: TWideStringField;
zqPrincipalVeic_TipoCambio: TWideStringField;
zqPrincipalVeic_Fabricante: TWideStringField;
zqPrincipalVeic_DataCadastro: TDateTimeField;
zqPrincipalVeic_UltimaRevisao: TDateTimeField;
zqPrincipalVeic_Obs: TWideStringField;
zqPrincipalVeic_Cli_Cod: TIntegerField;
zqPrincipalVeic_Cor: TWideStringField;
edtCor: TLabeledEdit;
edtPlaca: TMaskEdit;
procedure btnCadastroClienteClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure btnAlterarClick(Sender: TObject);
procedure btnInserirClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure lkbClienteExit(Sender: TObject);
private
vVeiculo:TCadVeiculo;
function Apagar:Boolean; override;
function Gravar(EstadoDoCadastro:TEstadoCadastro):Boolean; override;
{ Private declarations }
public
{ Public declarations }
end;
var
frmCadVeiculo: TfrmCadVeiculo;
implementation
{$R *.dfm}
function TfrmCadVeiculo.Apagar: Boolean;
begin
if vVeiculo.Selecionar(zqPrincipal.FieldByName('veic_cod').AsInteger) then begin
Result:=vVeiculo.Apagar;
end;
end;
procedure TfrmCadVeiculo.btnCadastroClienteClick(Sender: TObject);
var frmCliente : TfrmCliente;
begin
inherited;
frmCliente := TfrmCliente.Create(self);
try
frmCliente.ShowModal;
finally
//lblCliente.text := frmCliente.lbeCodigo.text;
FreeAndNil(frmCliente);
end;
end;
procedure TfrmCadVeiculo.btnAlterarClick(Sender: TObject);
begin
if vVeiculo.Selecionar(zqPrincipal.FieldByName('veic_cod').AsInteger) then
begin
lblCodigo.Text :=IntToStr(vVeiculo.Codigo);
edtModelo.Text :=vVeiculo.Marca_Modelo;
edtPlaca.Text :=vVeiculo.Placa;
edtChassi.Text :=vVeiculo.Chassi;
mkeAno.Text :=vVeiculo.AnoDeFrabrica;
cbCombustivel.Text :=vVeiculo.TipoCumbustivel;
cbTipoCambio.Text :=vVeiculo.TipoCambio;
edtFabricante.Text := vVeiculo.Frabricante;
edtDataCadastro.Date :=vVeiculo.DataCadastro;
edtRevisao.Date :=vVeiculo.UltimaRevisao;
mmObs.Text :=vVeiculo.Obs;
lkbCliente.KeyValue :=vVeiculo.Cli_cod;
edtCor.Text :=vVeiculo.Cor;
end
else begin
btnCancelar.Click;
Abort;
end;
inherited;
end;
procedure TfrmCadVeiculo.btnInserirClick(Sender: TObject);
begin
inherited;
edtDataCadastro.Date:=Date;
lkbCliente.SetFocus;
end;
procedure TfrmCadVeiculo.FormClose(Sender: TObject; var Action: TCloseAction);
begin
inherited;
zqCliente.Close;
if Assigned(vVeiculo) then
FreeAndNil(vVeiculo);
end;
procedure TfrmCadVeiculo.FormCreate(Sender: TObject);
begin
inherited;
vVeiculo:=TCadVeiculo.Create(dtmPrincipal.ConexaoDB);
IndiceAtual := 'Veic_Marca_Modelo';
end;
procedure TfrmCadVeiculo.FormShow(Sender: TObject);
begin
inherited;
zqCliente.Open;
btnCadastroCliente.Enabled := false;
end;
function TfrmCadVeiculo.Gravar(EstadoDoCadastro: TEstadoCadastro): Boolean;
begin
if lblCodigo.Text<>EmptyStr then
vVeiculo.codigo:=StrToInt(lblCodigo.Text)
else
vVeiculo.codigo:=0;
vVeiculo.Marca_Modelo := edtModelo.Text;
vVeiculo.Placa := edtPlaca.Text;
vVeiculo.Chassi := edtChassi.Text;
vVeiculo.AnoDeFrabrica := mkeAno.Text;
vVeiculo.TipoCumbustivel := cbCombustivel.Text;
vVeiculo.TipoCambio := cbTipoCambio.Text;
vVeiculo.Frabricante := edtFabricante.Text;
vVeiculo.DataCadastro := edtDataCadastro.Date;
vVeiculo.UltimaRevisao := edtRevisao.Date;
vVeiculo.Obs := mmObs.Text;
vVeiculo.Cli_cod := lkbCliente.KeyValue;
vVeiculo.Cor := edtCor.Text;
if (EstadoDoCadastro=ecInserir) then
Result:=vVeiculo.Inserir
else if (EstadoDoCadastro=ecAlterar) then
Result:=vVeiculo.Atualizar;
end;
procedure TfrmCadVeiculo.lkbClienteExit(Sender: TObject);
begin
inherited;
if LkbCliente.KeyValue = NULL then
begin
btnCadastroCliente.Enabled := true;
btnCadastroCliente.SetFocus;
end
else
btnCadastroCliente.Enabled := false;
end;
end.
|
unit evdTypes;
{* Базовые типы, используемые форматом EVD. }
// Модуль: "w:\common\components\rtl\Garant\EVD\evdTypes.pas"
// Стереотип: "Interfaces"
// Элемент модели: "Types" MUID: (469D0AC7005E)
{$Include w:\common\components\rtl\Garant\EVD\evdDefine.inc}
interface
uses
l3IntfUses
;
const
CI_TOPIC = 65537;
{* для всех ссылок на документы }
CI_BLOB = 65538;
{* для ссылок на двоичные объекты }
CI_MULT = 65539;
{* для мультиссылок на документы/двоичные объекты }
CI_REF = 65540;
{* для ссылок на внешние интернет-ресурсы }
CI_FolderLink = 65544;
CI_ExternalOperation = 65545;
CI_PHARM_MULTI = 65547;
{* для мультиссылок на документы инфарма }
CI_PIC = 65541;
{* для ссылок на внешние картинки }
CI_SCRIPT = 65552;
CI_EDITION = 65543;
CI_SHELL_INTERNAL = 65554;
{* Ссылки с раскрывающихся блоков и т.п. Не должны передаваться на адаптер. [Requestlink:607263536] }
ev_NullAddressType = 0;
ev_defAddressType = CI_TOPIC;
ev_cUserCommentFlags = 2;
{* Флаги пользовательских комментариев }
ev_cCommentsFlag = 1;
{* Флаги комментариев юристов }
ev_cVersionCommentsFlag = 4;
{* Флаги версионных комментариев }
POSITION_TYPE_PARA_ID = 2147483648;
type
TevIndentType = (
{* Выравнивание объекта по горизонтали. }
ev_itLeft
{* по левому краю. }
, ev_itRight
{* по правому краю. }
, ev_itCenter
{* по центру. }
, ev_itWidth
{* по ширине. }
, ev_itPreformatted
{* "преформатированный". }
, ev_itNone
);//TevIndentType
TevPageOrientation = (
{* Ориентация страницы. }
ev_poPortrait
{* книжная. }
, ev_poLandscape
{* альбомная. }
);//TevPageOrientation
TevMergeStatus = (
{* признак объединения ячеек. }
ev_msNone
, ev_msHead
, ev_msContinue
);//TevMergeStatus
TevVerticalAligment = (
{* Выравнивание объекта по вертикали. }
ev_valTop
, ev_valCenter
, ev_valBottom
);//TevVerticalAligment
TevControlType = (
{* Тип контрола. }
ev_ctLabel
{* метка с курсором в виде рамки }
, ev_ctEdit
{* обычный редактор }
, ev_ctCombo
{* выпадающий список }
, ev_ctButton
{* кнопка }
, ev_ctSpinedit
{* редактор с возможностью редактирования чисел }
, ev_ctCheckEdit
{* редактор с CheckBox }
, ev_ctEllipsesEdit
{* редактор с кнопкой }
, ev_ctRadioEdit
{* редактор с RadioButton }
, ev_ctCalEdit
{* редактор с выпадающим календарём }
, ev_ctCollapsedPanel
{* сворачивающая панель }
, ev_ctStateButton
{* кнопка с изменением состояния }
, ev_ctEmailEdit
{* редактор для ввода E-mail адреса (с проверкой) }
, ev_ctMemoEdit
{* многострочное поле ввода (не используется) }
, ev_ctPictureLabel
{* текст примечания с картинкой }
, ev_ctTextParaLabel
{* метка с обычным курсором }
, ev_ctPhoneEdit
, ev_ctUnknown
{* неизвестный тип контрола }
);//TevControlType
TevReqKind = (
{* Тип реквизита. }
ev_rkSimple
{* обычный реквизит, допускающий редактировани (попадающий в модель) (ev_rkSimple). }
, ev_rkContext
{* контекстный атрибут, допускающий редактирование (попадающий в модель)(ev_rkContext). }
, ev_rkDescription
{* информационный атрибут (НЕ попадает в модель (ev_rkDescription). }
);//TevReqKind
TevSubPlace = (
ev_spNoWhere
, ev_spOnlyInContents
, ev_spInContentsAndOnSubPanel
, ev_spOnlyOnSubPanel
);//TevSubPlace
TevLinkViewKind = (
ev_lvkUnknown
{* Неизвестно }
, ev_lvkInternalValid
{* Внутри системы. Правильная }
, ev_lvkInternalInvalid
{* Внутри системы. На отсутствующую информацию }
, ev_lvkExternal
{* Наружу }
, ev_lvkInternalAbolished
{* Внутри системы. На утративший силу документ }
, ev_lvkInternalPreactive
{* Внутри системы. На не вступивший в силу документ }
, ev_lvkExternalENO
{* Внешнее приложение }
, ev_lvkInternalEdition
{* Редакция документа }
, ev_lvkScript
, ev_lvkShellInternal
);//TevLinkViewKind
TevSubHandle = (
{* Слои меток. }
None
, Sub
, Marker
, Bookmark
, Mark
);//TevSubHandle
TevDocumentPlace = (
{* Место в документе. }
ev_dpNone
{* Нигде. }
, ev_dpEnd
{* В конце. }
);//TevDocumentPlace
TevHFType = (
{* Тип колонтитула }
evd_hftOrdinal
, evd_hftLeft
, evd_hftRight
, evd_hftFirst
);//TevHFType
TevSegmentHandle = (
Superposition
, View
, Hyperlinks
, FoundWords
, Found
, Objects
, Mistakes
, Diff
);//TevSegmentHandle
TevNormalSegLayerHandleP = View .. Mistakes;
TevNormalSegLayerHandleSet = set of TevNormalSegLayerHandleP;
TevBlockViewKind = (
ev_bvkNone
, ev_bvkLeft
, ev_bvkRight
);//TevBlockViewKind
const
{* Слои меток. }
ev_sbtNone = None;
{* несуществующий слой меток. }
ev_sbtSub = Sub;
{* слой Sub'ов. }
ev_sbtMarker = Marker;
{* слой закладок. }
ev_sbtBookmark = Bookmark;
{* слой именованных закладок (зарезервированно). }
ev_sbtMark = Mark;
{* слой вспомогательных значков (зарезервированно). }
ev_sbtPara = 10;
{* параграф (псевдослой). }
ev_sbtDocumentPlace = 11;
{* место в документе (псевдослой) см. [TevDocumentPlace]. }
ev_sbtBySearcher = 14;
{* условие по Searcher'у (псевдослой). }
{* Метка входит в оглавление }
ev_spInContents = [ev_spOnlyInContents, ev_spInContentsAndOnSubPanel];
{* Слои сегментов оформления }
ev_slSuperposition = Superposition;
{* слой суперпозиции сегментов. }
ev_slView = View;
{* слой оформления. }
ev_slHyperlinks = Hyperlinks;
{* слой гиперссылок. }
ev_slFoundWords = FoundWords;
{* слой слов найденных по контексту. }
ev_slFound = Found;
{* слой найденных слов (зарезервированно). }
ev_slObjects = Objects;
{* слой объектов, вставленных в параграф. }
ev_slMistakes = Mistakes;
{* слой сегментов для покраски опечаток. }
ev_slDiff = Diff;
{* Разница двух сравниваемых документов }
implementation
uses
l3ImplUses
;
end.
|
{ RxAboutDialog
Copyright (C) 2005-2010 Lagunov Aleksey alexs@hotbox.ru and Lazarus team
original conception from rx library for Delphi (c)
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at your
option) any later version with the following modification:
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent modules,and
to copy and distribute the resulting executable under terms of your choice,
provided that you also meet, for each linked independent module, the terms
and conditions of the license of that module. An independent module is a
module which is not derived from or based on this library. If you modify
this library, you may extend this exception to your version of the library,
but you are not obligated to do so. If you do not wish to do so, delete this
exception statement from your version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License
for more details.
You should have received a copy of the GNU Library General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
}
unit RxAboutDialog;
{$mode objfpc}
interface
uses
Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs;
type
TRxAboutDialogOption = (radHelpButton, radLicenseTab, radShowImageLogo);
TRxAboutDialogOptions = set of TRxAboutDialogOption;
{ TRxAboutDialog }
TRxAboutDialog = class(TComponent)
private
FAdditionalInfo: TStrings;
FApplicationTitle: string;
FCaption: string;
FLicenseFileName: string;
FOptions: TRxAboutDialogOptions;
FPicture: TPicture;
procedure SetAdditionalInfo(const AValue: TStrings);
procedure SetPicture(const AValue: TPicture);
procedure SetRxAboutDialogOptions(const AValue: TRxAboutDialogOptions);
protected
{ Protected declarations }
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Execute;
published
property Options:TRxAboutDialogOptions read FOptions write SetRxAboutDialogOptions;
property ApplicationTitle:string read FApplicationTitle write FApplicationTitle;
property LicenseFileName:string read FLicenseFileName write FLicenseFileName;
property Caption:string read FCaption write FCaption;
property Picture: TPicture read FPicture write SetPicture;
property AdditionalInfo:TStrings read FAdditionalInfo write SetAdditionalInfo;
end;
implementation
uses rxAboutFormUnit, ButtonPanel, rxconst;
{ TRxAboutDialog }
procedure TRxAboutDialog.SetRxAboutDialogOptions(
const AValue: TRxAboutDialogOptions);
begin
if FOptions=AValue then exit;
FOptions:=AValue;
end;
procedure TRxAboutDialog.SetPicture(const AValue: TPicture);
begin
if FPicture=AValue then exit;
FPicture.Assign(AValue);
end;
procedure TRxAboutDialog.SetAdditionalInfo(const AValue: TStrings);
begin
FAdditionalInfo.Assign(AValue);
end;
constructor TRxAboutDialog.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FPicture := TPicture.Create;
FCaption:=sAbout;
FAdditionalInfo:= TStringList.Create;
end;
destructor TRxAboutDialog.Destroy;
begin
FAdditionalInfo.Free;
FPicture.Graphic := nil;
FPicture.Free;
inherited Destroy;
end;
procedure TRxAboutDialog.Execute;
var
rxAboutFormForm: TrxAboutFormForm;
begin
rxAboutFormForm:=TrxAboutFormForm.Create(Application);
rxAboutFormForm.Caption:=FCaption;
if radLicenseTab in FOptions then
rxAboutFormForm.LoadLicense(FLicenseFileName)
else
rxAboutFormForm.TabSheet3.TabVisible:=false;
if radHelpButton in FOptions then
rxAboutFormForm.ButtonPanel1.ShowButtons:=rxAboutFormForm.ButtonPanel1.ShowButtons + [pbHelp]
else
rxAboutFormForm.ButtonPanel1.ShowButtons:=rxAboutFormForm.ButtonPanel1.ShowButtons - [pbHelp];
if FApplicationTitle <> '' then
rxAboutFormForm.lblAppTitle.Caption:=FApplicationTitle;
if radShowImageLogo in FOptions then
begin
rxAboutFormForm.Image1.Picture.Assign(Picture);
end
else
begin
end;
rxAboutFormForm.Memo2.Lines.Assign(FAdditionalInfo);
try
rxAboutFormForm.ShowModal;
finally
rxAboutFormForm.Free;
end;
end;
end.
|
unit NewProgressBar;
{
Inno Setup
Copyright (C) 1997-2006 Jordan Russell
Portions by Martijn Laan
For conditions of distribution and use, see LICENSE.TXT.
TNewProgressBar component - a smooth TProgressBar for Delphi 2 and a 32 bit
TProgressBar for Delphi 2 and all platforms
Note: themed Vista and newer animate progress bars and don't immediately show changes.
This applies both to Position and State. For example if you set State while the
progress bar is still moving towards a new Position, the new State doesnt show until
the moving animation has finished.
$jrsoftware: issrc/Components/NewProgressBar.pas,v 1.10 2010/10/27 09:45:06 mlaan Exp $
}
interface
uses
Messages, Classes, Controls, ComCtrls;
type
TNewProgressBarState = (npbsNormal, npbsError, npbsPaused);
TNewProgressBarStyle = (npbstNormal, npbstMarquee);
TNewProgressBar = class(TWinControl)
private
FMin: LongInt;
FMax: LongInt;
FPosition: LongInt;
FState: TNewProgressBarState;
FStyle: TNewProgressBarStyle;
procedure SetMin(Value: LongInt);
procedure SetMax(Value: LongInt);
procedure SetPosition(Value: LongInt);
procedure SetState(Value: TNewProgressBarState);
procedure SetStyle(Value: TNewProgressBarStyle);
procedure WMEraseBkgnd(var Message: TWMEraseBkgnd); message WM_ERASEBKGND;
protected
procedure CreateParams(var Params: TCreateParams); override;
procedure CreateWnd; override;
public
constructor Create(AOwner: TComponent); override;
published
property Min: LongInt read FMin write SetMin;
property Max: LongInt read FMax write SetMax;
property Position: LongInt read FPosition write SetPosition default 0;
property State: TNewProgressBarState read FState write SetState default npbsNormal;
property Style: TNewProgressBarStyle read FStyle write SetStyle default npbstMarquee;
property Visible default True;
end;
procedure Register;
implementation
uses
Windows, CommCtrl;
var
XP, Vista: Boolean;
procedure Register;
begin
RegisterComponents('JR', [TNewProgressBar]);
end;
constructor TNewProgressBar.Create(AOwner: TComponent);
begin
inherited;
Width := 150;
Height := GetSystemMetrics(SM_CYVSCROLL);
FMin := 0;
FMax := 100;
end;
procedure TNewProgressBar.CreateParams(var Params: TCreateParams);
const
PBS_SMOOTH = 1;
PBS_MARQUEE = 8;
begin
InitCommonControls;
inherited;
CreateSubClass(Params, PROGRESS_CLASS);
Params.Style := Params.Style or PBS_SMOOTH;
if XP and (Style = npbstMarquee) then
Params.Style := Params.Style or PBS_MARQUEE;
end;
procedure TNewProgressBar.CreateWnd;
const
PBM_SETMARQUEE = WM_USER+10;
begin
inherited CreateWnd;
SendMessage(Handle, PBM_SETRANGE, 0, MAKELPARAM(0, 65535));
SetPosition(FPosition);
SetState(FState);
if XP then
SendMessage(Handle, PBM_SETMARQUEE, WPARAM(FStyle = npbstMarquee), 0);
end;
procedure TNewProgressBar.SetMin(Value: LongInt);
begin
FMin := Value;
SetPosition(FPosition);
end;
procedure TNewProgressBar.SetMax(Value: LongInt);
begin
FMax := Value;
SetPosition(FPosition);
end;
procedure TNewProgressBar.SetPosition(Value: LongInt);
begin
if Value < FMin then
Value := FMin
else if Value > FMax then
Value := FMax;
FPosition := Value;
if HandleAllocated and (FStyle <> npbstMarquee) then
SendMessage(Handle, PBM_SETPOS, MulDiv(Value - FMin, 65535, FMax - FMin), 0);
end;
procedure TNewProgressBar.SetState(Value: TNewProgressBarState);
const
PBST_NORMAL = $0001;
PBST_ERROR = $0002;
PBST_PAUSED = $0003;
PBM_SETSTATE = WM_USER+16;
States: array[TNewProgressBarState] of UINT = (PBST_NORMAL, PBST_ERROR, PBST_PAUSED);
begin
if Vista then begin
FState := Value;
if HandleAllocated then
SendMessage(Handle, PBM_SETSTATE, States[Value], 0);
end;
end;
procedure TNewProgressBar.SetStyle(Value: TNewProgressBarStyle);
begin
if XP and (FStyle <> Value) then begin
FStyle := Value;
RecreateWnd;
end;
end;
procedure TNewProgressBar.WMEraseBkgnd(var Message: TWMEraseBkgnd);
begin
{ Bypass TWinControl's default WM_ERASEBKGND handling.
On Windows Vista with COMCTL32 v6, a WM_ERASEBKGND message is sent every
time a progress bar's position changes. TWinControl.WMEraseBkgnd does a
FillRect on the whole client area, which results in ugly flickering.
Previous versions of Windows only sent a WM_ERASEBKGND message when a
progress bar moved backwards, so flickering was rarely apparent. }
DefaultHandler(Message);
end;
var
OSVersionInfo: TOSVersionInfo;
initialization
OSVersionInfo.dwOSVersionInfoSize := SizeOf(OSVersionInfo);
if GetVersionEx(OSVersionInfo) then begin
Vista := OSVersionInfo.dwMajorVersion >= 6;
XP := Vista or ((OSVersionInfo.dwMajorVersion = 5) and (OSVersionInfo.dwMinorVersion >= 1));
end;
end.
|
unit KSCParser;
{$reference 'System.Data.dll'}
uses System.Data, Types;
function CutFromText(s: string; delim1, delim2: string): string;
begin
var a, b: integer;
a:=s.IndexOf(delim1);
b:=s.IndexOf(delim2);
Result := Copy(s,a+delim1.Length+1,b-a-delim1.Length);
end;
function OutOfContext(s: string; delim1, delim2: string): string;
begin
var a, b: integer;
a:=s.IndexOf(delim1);
b:=s.LastIndexOf(delim2);
Result := Copy(s,a+delim1.Length,b-a-delim1.Length);
end;
function OutOfContext(s: string; delim1, delim2: char): string;
begin
var a, b: integer;
a:=s.IndexOf(delim1);
b:=s.LastIndexOf(delim2);
Result := Copy(s,a+2,b-a-1);
end;
function OutOfContext(self: string; delim1, delim2: string): string; extensionmethod := OutOfContext(self,delim1,delim2);
function OutOfContext(self: string; delim1, delim2: char): string; extensionmethod := OutOfContext(self,delim1,delim2);
function Contains(s: string; s2: string): boolean;
begin
Result:=false;
for var i:=1 to s.Length do
begin
if Copy(s,i,s2.Length) = s2 then Result:=true;
end;
end;
function Parse(s: string): object;
begin
Result:=(new System.Data.DataTable).Compute(s,'');
//Result:
end;
function Parse(a: sequence of KSCObject; s: string): object;
begin
var rslt:=s;
if a<>nil then
foreach var x in a do
if x.Name.Length>0 then rslt:=rslt.Replace(x.Name,x.ToString);
Result:=Parse(rslt);
end;
begin
end. |
unit fbkOUTLINETable;
interface
uses
Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf;
type
TfbkOUTLINERecord = record
PTopicID: Integer;
PProject: String[10];
PDescription: String[40];
PParentTopic: Integer;
PStatusID: Integer;
PComments: String[60];
End;
TfbkOUTLINEBuffer = class(TDataBuf)
protected
function PtrIndex(Index:integer):Pointer;override;
public
Data: TfbkOUTLINERecord;
function FieldNameToIndex(s:string):integer;override;
function FieldType(index:integer):TFieldType;override;
end;
TEIfbkOUTLINE = (fbkOUTLINEPrimaryKey, fbkOUTLINEByParent);
TfbkOUTLINETable = class( TDBISAMTableAU )
private
FDFTopicID: TIntegerField;
FDFProject: TStringField;
FDFDescription: TStringField;
FDFParentTopic: TIntegerField;
FDFStatusID: TIntegerField;
FDFComments: TStringField;
procedure SetPTopicID(const Value: Integer);
function GetPTopicID:Integer;
procedure SetPProject(const Value: String);
function GetPProject:String;
procedure SetPDescription(const Value: String);
function GetPDescription:String;
procedure SetPParentTopic(const Value: Integer);
function GetPParentTopic:Integer;
procedure SetPStatusID(const Value: Integer);
function GetPStatusID:Integer;
procedure SetPComments(const Value: String);
function GetPComments:String;
function GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string;
procedure SetEnumIndex(Value: TEIfbkOUTLINE);
function GetEnumIndex: TEIfbkOUTLINE;
protected
function CreateField( const FieldName : string ): TField;
procedure CreateFields;
procedure SetActive(Value: Boolean); override;
procedure LoadFieldDefs(AStringList:TStringList);override;
procedure LoadIndexDefs(AStringList:TStringList);override;
public
function GetDataBuffer:TfbkOUTLINERecord;
procedure StoreDataBuffer(ABuffer:TfbkOUTLINERecord);
property DFTopicID: TIntegerField read FDFTopicID;
property DFProject: TStringField read FDFProject;
property DFDescription: TStringField read FDFDescription;
property DFParentTopic: TIntegerField read FDFParentTopic;
property DFStatusID: TIntegerField read FDFStatusID;
property DFComments: TStringField read FDFComments;
property PTopicID: Integer read GetPTopicID write SetPTopicID;
property PProject: String read GetPProject write SetPProject;
property PDescription: String read GetPDescription write SetPDescription;
property PParentTopic: Integer read GetPParentTopic write SetPParentTopic;
property PStatusID: Integer read GetPStatusID write SetPStatusID;
property PComments: String read GetPComments write SetPComments;
published
property Active write SetActive;
property EnumIndex: TEIfbkOUTLINE read GetEnumIndex write SetEnumIndex;
end; { TfbkOUTLINETable }
procedure Register;
implementation
function TfbkOUTLINETable.GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string;
var
I: Integer;
NewName: string;
Done: Boolean;
function ComponentExists( AOwner: TComponent; const CompName: string ): Boolean;
var
I: Integer;
begin
Result := False;
for I := 0 To AOwner.ComponentCount - 1 do
begin
if AnsiCompareText( CompName, AOwner.Components[ I ].Name ) = 0 then
begin
Result := True;
Break;
end;
end;
end; { ComponentExists }
begin { TfbkOUTLINETable.GenerateNewFieldName }
NewName := DatasetName;
for I := 1 to Length( FieldName ) do
begin
if FieldName[ I ] in [ '0'..'9', '_', 'A'..'Z', 'a'..'z' ] then
NewName := NewName + FieldName[ I ];
end;
if ComponentExists( Owner, NewName ) then
begin
I := 1;
Done := False;
repeat
Inc( I );
if not ComponentExists( AOwner, NewName + IntToStr( I ) ) then
begin
Result := NewName + IntToStr( I );
Done := True;
end;
until Done;
end
else
Result := NewName;
end; { TfbkOUTLINETable.GenerateNewFieldName }
function TfbkOUTLINETable.CreateField( const FieldName : string ): TField;
begin
{ First, try to find an existing field object. FindField is the same }
{ as FieldByName, but does not raise an exception if the field object }
{ cannot be found. }
Result := FindField( FieldName );
if Result = nil then
begin
{ If an existing field object cannot be found... }
{ Instruct the FieldDefs object to create a new field object }
Result := FieldDefs.Find( FieldName ).CreateField( Owner );
{ The new field object must be given a name so that it may appear in }
{ the Object Inspector. The Delphi default naming convention is used.}
Result.Name := GenerateNewFieldName( Owner, Name, FieldName);
end;
end; { TfbkOUTLINETable.CreateField }
procedure TfbkOUTLINETable.CreateFields;
begin
FDFTopicID := CreateField( 'TopicID' ) as TIntegerField;
FDFProject := CreateField( 'Project' ) as TStringField;
FDFDescription := CreateField( 'Description' ) as TStringField;
FDFParentTopic := CreateField( 'ParentTopic' ) as TIntegerField;
FDFStatusID := CreateField( 'StatusID' ) as TIntegerField;
FDFComments := CreateField( 'Comments' ) as TStringField;
end; { TfbkOUTLINETable.CreateFields }
procedure TfbkOUTLINETable.SetActive(Value: Boolean);
begin
inherited SetActive(Value);
if Active then
CreateFields;
end; { TfbkOUTLINETable.SetActive }
procedure TfbkOUTLINETable.SetPTopicID(const Value: Integer);
begin
DFTopicID.Value := Value;
end;
function TfbkOUTLINETable.GetPTopicID:Integer;
begin
result := DFTopicID.Value;
end;
procedure TfbkOUTLINETable.SetPProject(const Value: String);
begin
DFProject.Value := Value;
end;
function TfbkOUTLINETable.GetPProject:String;
begin
result := DFProject.Value;
end;
procedure TfbkOUTLINETable.SetPDescription(const Value: String);
begin
DFDescription.Value := Value;
end;
function TfbkOUTLINETable.GetPDescription:String;
begin
result := DFDescription.Value;
end;
procedure TfbkOUTLINETable.SetPParentTopic(const Value: Integer);
begin
DFParentTopic.Value := Value;
end;
function TfbkOUTLINETable.GetPParentTopic:Integer;
begin
result := DFParentTopic.Value;
end;
procedure TfbkOUTLINETable.SetPStatusID(const Value: Integer);
begin
DFStatusID.Value := Value;
end;
function TfbkOUTLINETable.GetPStatusID:Integer;
begin
result := DFStatusID.Value;
end;
procedure TfbkOUTLINETable.SetPComments(const Value: String);
begin
DFComments.Value := Value;
end;
function TfbkOUTLINETable.GetPComments:String;
begin
result := DFComments.Value;
end;
procedure TfbkOUTLINETable.LoadFieldDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('TopicID, Integer, 0, N');
Add('Project, String, 10, N');
Add('Description, String, 40, N');
Add('ParentTopic, Integer, 0, N');
Add('StatusID, Integer, 0, N');
Add('Comments, String, 60, N');
end;
end;
procedure TfbkOUTLINETable.LoadIndexDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('PrimaryKey, TopicID, Y, Y, N, N');
Add('ByParent, ParentTopic;TopicID, N, N, N, N');
end;
end;
procedure TfbkOUTLINETable.SetEnumIndex(Value: TEIfbkOUTLINE);
begin
case Value of
fbkOUTLINEPrimaryKey : IndexName := '';
fbkOUTLINEByParent : IndexName := 'ByParent';
end;
end;
function TfbkOUTLINETable.GetDataBuffer:TfbkOUTLINERecord;
var buf: TfbkOUTLINERecord;
begin
fillchar(buf, sizeof(buf), 0);
buf.PTopicID := DFTopicID.Value;
buf.PProject := DFProject.Value;
buf.PDescription := DFDescription.Value;
buf.PParentTopic := DFParentTopic.Value;
buf.PStatusID := DFStatusID.Value;
buf.PComments := DFComments.Value;
result := buf;
end;
procedure TfbkOUTLINETable.StoreDataBuffer(ABuffer:TfbkOUTLINERecord);
begin
DFTopicID.Value := ABuffer.PTopicID;
DFProject.Value := ABuffer.PProject;
DFDescription.Value := ABuffer.PDescription;
DFParentTopic.Value := ABuffer.PParentTopic;
DFStatusID.Value := ABuffer.PStatusID;
DFComments.Value := ABuffer.PComments;
end;
function TfbkOUTLINETable.GetEnumIndex: TEIfbkOUTLINE;
var iname : string;
begin
iname := uppercase(indexname);
if iname = '' then result := fbkOUTLINEPrimaryKey;
if iname = 'BYPARENT' then result := fbkOUTLINEByParent;
end;
(********************************************)
(************ Register Component ************)
(********************************************)
procedure Register;
begin
RegisterComponents( 'Feedback Tables', [ TfbkOUTLINETable, TfbkOUTLINEBuffer ] );
end; { Register }
function TfbkOUTLINEBuffer.FieldNameToIndex(s:string):integer;
const flist:array[1..6] of string = ('TOPICID','PROJECT','DESCRIPTION','PARENTTOPIC','STATUSID','COMMENTS'
);
var x : integer;
begin
s := uppercase(s);
x := 1;
while (x <= 6) and (flist[x] <> s) do inc(x);
if x <= 6 then result := x else result := 0;
end;
function TfbkOUTLINEBuffer.FieldType(index:integer):TFieldType;
begin
result := ftUnknown;
case index of
1 : result := ftInteger;
2 : result := ftString;
3 : result := ftString;
4 : result := ftInteger;
5 : result := ftInteger;
6 : result := ftString;
end;
end;
function TfbkOUTLINEBuffer.PtrIndex(index:integer):Pointer;
begin
result := nil;
case index of
1 : result := @Data.PTopicID;
2 : result := @Data.PProject;
3 : result := @Data.PDescription;
4 : result := @Data.PParentTopic;
5 : result := @Data.PStatusID;
6 : result := @Data.PComments;
end;
end;
end.
|
unit TextEditorVisitor;
{* Тест, работающий с текстом документа через редактор, но не изменяющий его }
// Модуль: "w:\common\components\gui\Garant\Daily\TextEditorVisitor.pas"
// Стереотип: "TestCase"
// Элемент модели: "TTextEditorVisitor" MUID: (4BE425C70228)
{$Include w:\common\components\gui\sdotDefine.inc}
interface
{$If Defined(nsTest) AND NOT Defined(NoVCM)}
uses
l3IntfUses
, TextEditorVisitorPrim
;
type
TTextEditorVisitor = {abstract} class(TTextEditorVisitorPrim)
{* Тест, работающий с текстом документа через редактор, но не изменяющий его }
protected
function GetNormalFontSize: Integer; virtual;
{* Возвращает размер шрифта стиля "Нормальный". 0 - по-умолчанию }
function MaxHeight: Integer; virtual;
{* Если возвращается не 0, то будет организован цикл подбора высоты от FormExtent.Y до MaxHeight }
function GetFolder: AnsiString; override;
{* Папка в которую входит тест }
function GetModelElementGUID: AnsiString; override;
{* Идентификатор элемента модели, который описывает тест }
published
procedure DoIt;
{* Собственно тело теста }
end;//TTextEditorVisitor
{$IfEnd} // Defined(nsTest) AND NOT Defined(NoVCM)
implementation
{$If Defined(nsTest) AND NOT Defined(NoVCM)}
uses
l3ImplUses
, SysUtils
, evStyleInterface
, TestFrameWork
, vcmBase
{$If NOT Defined(NoVCL)}
, Forms
{$IfEnd} // NOT Defined(NoVCL)
, l3Base
//#UC START# *4BE425C70228impl_uses*
//#UC END# *4BE425C70228impl_uses*
;
procedure TTextEditorVisitor.DoIt;
{* Собственно тело теста }
//#UC START# *4BE131BC038E_4BE425C70228_var*
var
l_SI : TevStyleInterface;
l_Size : Integer;
l_NewSize : Integer;
l_MaxHeight : Integer;
//#UC END# *4BE131BC038E_4BE425C70228_var*
begin
//#UC START# *4BE131BC038E_4BE425C70228_impl*
l_SI := TevStyleInterface.Make;
try
l_NewSize := GetNormalFontSize;
l_Size := l_SI.Font.Size;
try
if (l_NewSize > 0) then
l_SI.Font.Size := l_NewSize;
l_MaxHeight := MaxHeight;
if (l_MaxHeight > 0) then
begin
f_FixedHeight := 0;
f_FixedHeight := FormExtent.Y;
if (f_FixedHeight < 0) then
f_FixedHeight := 300;
while (f_FixedHeight < l_MaxHeight) do
begin
try
VisitText;
except
ToLog('Form height = ' + IntToStr(f_FixedHeight));
raise;
end;//try..except
Inc(f_FixedHeight);
end;//f_FixedHeight < l_MaxHeight
end//l_MaxHeight > 0
else
VisitText;
finally
l_SI.Font.Size := l_Size;
end;//try..finally
finally
FreeAndNil(l_SI);
end;//try..finally
//#UC END# *4BE131BC038E_4BE425C70228_impl*
end;//TTextEditorVisitor.DoIt
function TTextEditorVisitor.GetNormalFontSize: Integer;
{* Возвращает размер шрифта стиля "Нормальный". 0 - по-умолчанию }
//#UC START# *4C07AC6F036D_4BE425C70228_var*
//#UC END# *4C07AC6F036D_4BE425C70228_var*
begin
//#UC START# *4C07AC6F036D_4BE425C70228_impl*
Result := 0;
//#UC END# *4C07AC6F036D_4BE425C70228_impl*
end;//TTextEditorVisitor.GetNormalFontSize
function TTextEditorVisitor.MaxHeight: Integer;
{* Если возвращается не 0, то будет организован цикл подбора высоты от FormExtent.Y до MaxHeight }
//#UC START# *4C0E56F000A4_4BE425C70228_var*
//#UC END# *4C0E56F000A4_4BE425C70228_var*
begin
//#UC START# *4C0E56F000A4_4BE425C70228_impl*
Result := 0;
//#UC END# *4C0E56F000A4_4BE425C70228_impl*
end;//TTextEditorVisitor.MaxHeight
function TTextEditorVisitor.GetFolder: AnsiString;
{* Папка в которую входит тест }
begin
Result := 'Everest';
end;//TTextEditorVisitor.GetFolder
function TTextEditorVisitor.GetModelElementGUID: AnsiString;
{* Идентификатор элемента модели, который описывает тест }
begin
Result := '4BE425C70228';
end;//TTextEditorVisitor.GetModelElementGUID
{$IfEnd} // Defined(nsTest) AND NOT Defined(NoVCM)
end.
|
unit ExtAIEvents;
interface
uses
Classes, SysUtils,
ExtAIMsgEvents, ExtAINetClient, ExtAISharedInterface;
// Events of the ExtAI
type
TExtAIEvents = class
private
fEvents: TExtAIMsgEvents;
public
constructor Create();
destructor Destroy(); override;
property Msg: TExtAIMsgEvents read fEvents;
end;
implementation
{ TExtAIEvents }
constructor TExtAIEvents.Create();
begin
Inherited Create;
fEvents := TExtAIMsgEvents.Create();
end;
destructor TExtAIEvents.Destroy();
begin
fEvents.Free;
Inherited;
end;
end.
|
unit MagazinePushFrame;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls,
System.Generics.Collections, task_1, Vcl.Grids;
type
TFrame2 = class(TFrame)
NameEdit: TLabeledEdit;
NumberEdit: TLabeledEdit;
PriceEdit: TLabeledEdit;
DescriptionEdit: TLabeledEdit;
private
public
obj: TMagazine;
function get_data: TDictionary<String, String>;
procedure ClearEdits;
function get_obj: TMagazine;
end;
implementation
{$R *.dfm}
function TFrame2.get_data;
var data: TDictionary<String, String>;
begin
data := TDictionary<String, String>.Create;
data.Add('name', self.NameEdit.Text);
data.Add('price', self.PriceEdit.Text);
data.Add('number', self.NumberEdit.Text);
data.Add('description', self.DescriptionEdit.Text);
result := data;
end;
procedure TFrame2.ClearEdits;
var i: Integer;
begin
for i := 0 to self.ComponentCount - 1 do
if self.Components[i] is TLabeledEdit then TLabeledEdit(self.Components[i]).Clear;
end;
function TFrame2.get_obj;
var data: TDictionary<String, String>;
begin
data := self.get_data;
result := TMagazine.__init__(data['name'],
StrToInt(data['price']),
StrToInt(data['number']),
data['description']);
end;
end.
|
unit uGame;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Objects,
FMX.Effects, FMX.StdCtrls, Math, FMX.Ani, FMX.Filter.Effects, FMX.Layouts,System.IOUtils,
System.IniFiles, FMX.Platform;
type
TGameForm = class(TForm)
BirdSprite: TImage;
GameLoop: TTimer;
TopPipe: TRectangle;
TopPipeCap: TRectangle;
ScoreLBL: TLabel;
GlowEffect1: TGlowEffect;
BackGroundImage: TImage;
Ground: TRectangle;
GroundB: TImage;
GroundA: TImage;
GameOverLBL: TLabel;
GOFloat: TFloatAnimation;
Image2: TImage;
MonochromeEffect1: TMonochromeEffect;
Label1: TLabel;
Rectangle1: TRectangle;
GetReadyLayout: TLayout;
Arc1: TArc;
Arc2: TArc;
Pie1: TPie;
Rectangle2: TRectangle;
GetReadyLBL: TLabel;
FloatAnimation1: TFloatAnimation;
GlowEffect3: TGlowEffect;
FMonkeyA: TImage;
FMonkeyB: TImage;
Rectangle3: TRectangle;
Label2: TLabel;
GOScoreLBL: TLabel;
Label4: TLabel;
BestScoreLBL: TLabel;
OKBTN: TButton;
ReplayBTN: TButton;
BigPipe: TLayout;
GroundBar: TImage;
GameOverLayout: TLayout;
Layout1: TLayout;
procedure GameLoopTimer(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Single);
procedure GetReadyLayoutClick(Sender: TObject);
procedure FormHide(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure ReplayBTNClick(Sender: TObject);
procedure OKBTNClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
EnemyList: TStringList;
GameTick: Integer;
Score: Integer;
GameLoopActive: Boolean;
IsGameOver: Boolean;
MonkeyAni: Boolean;
GroundAni: Boolean;
IniFileName: String;
BestScore: Integer;
JustOnce: Boolean;
BG_WRatio: Integer;
BG_HRatio: Integer;
procedure ResetGame;
procedure SetScore(I: Integer);
procedure GameOver;
function CheckBoundryCollision( R1, R2 : TRect; OffSetY : LongInt = 4; OffSetX : LongInt = 4): Boolean; {overload;}
function GetScreenScale: Single;
end;
const
BG_WIDTH=384;
BG_HEIGHT=576;
var
GameForm: TGameForm;
implementation
{$R *.fmx}
uses uMenu;
function TGameForm.GetScreenScale: Single;
var
ScreenSvc: IFMXScreenService;
begin
Result := 1;
if TPlatformServices.Current.SupportsPlatformService(IFMXScreenService, IInterface(ScreenSvc)) then
begin
Result := ScreenSvc.GetScreenScale;
end;
end;
procedure TGameForm.FormCreate(Sender: TObject);
begin
EnemyList := TStringList.Create;
GOFloat.StopValue := 0;
GOFloat.StartValue := GameForm.Height;
GameOverLayout.Position.Y := GameForm.Height;
IniFileName := System.IOUtils.TPath.GetDocumentsPath + System.SysUtils.PathDelim + 'Scores.dat';
end;
procedure TGameForm.FormDestroy(Sender: TObject);
begin
EnemyList.Free;
end;
procedure TGameForm.FormHide(Sender: TObject);
begin
GameLoop.Enabled := False;
MenuForm.Show;
end;
procedure TGameForm.FormMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Single);
begin
if GameLoopActive=True then
begin
if BirdSprite.Position.Y<75 then
begin
BirdSprite.Position.Y := 0;
end
else
begin
BirdSprite.Position.Y := BirdSprite.Position.Y-75;
end;
BirdSprite.RotationAngle := 0;
end;
end;
procedure TGameForm.FormShow(Sender: TObject);
var
IniFile: TMemIniFile;
begin
if JustOnce=False then
begin
try
IniFile := TMemIniFile.Create(IniFileName);
BestScore := IniFile.ReadInteger('Settings','Best',0);
IniFile.Free;
BestScoreLBL.Text := IntToStr(BestScore);
except on E: Exception do
begin
//E.Message;
end;
end;
JustOnce := True;
end;
end;
procedure TGameForm.ReplayBTNClick(Sender: TObject);
begin
GameOverLayout.Position.Y := GameForm.Height;
GameForm.ResetGame;
end;
procedure TGameForm.ResetGame;
var
I: Integer;
R: TLayout;
begin
IsGameOver := False;
MonkeyAni := False;
GameOverLayout.Visible := False;
BirdSprite.Position.X := 96;
BirdSprite.Position.Y := 248;
BirdSprite.RotationAngle := 0;
GetReadyLayout.Visible := True;
SetScore(0);
for I := EnemyList.Count-1 downto 0 do
begin
if Assigned(EnemyList.Objects[I]) then
begin
R := TLayout(EnemyList.Objects[I]);
R.DisposeOf;
EnemyList.Delete(I);
end;
end;
Application.ProcessMessages;
GameLoop.Enabled := True;
end;
procedure TGameForm.GameOver;
var
IniFile: TMemIniFile;
begin
IsGameOver := True;
GameLoopActive := False;
GameOverLayout.BringToFront;
GameOverLayout.Visible := True;
ScoreLBL.Visible := False;
//GOFloat.Enabled := True;
GOScoreLBL.Text := IntToStr(Score);
if Score>BestScore then
begin
BestScore := Score;
BestScoreLBL.Text := IntToStr(Score);
try
IniFile := TMemIniFile.Create(IniFileName);
IniFile.WriteInteger('Settings','Best',BestScore);
IniFile.Free;
except on E: Exception do
begin
//E.Message;
end;
end;
end;
end;
procedure TGameForm.GetReadyLayoutClick(Sender: TObject);
var
FormScale: Single;
begin
FormScale := GetScreenScale;
BG_WRatio := Trunc(FormScale);
BG_HRatio := Trunc(FormScale);
GetReadyLayout.Visible := False;
ScoreLBL.Visible := True;
GameLoopActive := True;
end;
procedure TGameForm.OKBTNClick(Sender: TObject);
begin
if IsGameOver=True then
begin
GameOverLayout.Position.Y := GameForm.Height;
GameOverLayout.Visible := False;
GameForm.Close;
MenuForm.Show;
end;
end;
procedure TGameForm.SetScore(I: Integer);
begin
Score := I;
ScoreLBL.Text := IntToStr(Score);
end;
procedure TGameForm.GameLoopTimer(Sender: TObject);
const
SpawnTime = 1.5;
var
R: TLayout;
I: Integer;
POffset,WOffset: Integer;
R1, R2: TRect;
GameOverCheck: Boolean;
begin
GameForm.BeginUpdate;
if GameLoopActive=True then
begin
GameOverCheck := False;
if (BirdSprite.Position.Y+BirdSprite.Height)>Ground.Position.Y then
begin
GameOverCheck := True;
end;
if GameTick=0 then
begin
if (Random<0.5) then
begin
WOffset := (200*BG_HRatio);
end
else
begin
WOffset := (250*BG_HRatio);
end;
if (Random<0.5) then
begin
POffset := (-125*BG_HRatio);
end
else
begin
POffset := (-25*BG_HRatio);
end;
R := TLayout(BigPipe.Clone(Self));
EnemyList.AddObject('',R);
R.Parent := GameForm;
R.Visible := True;
R.Position.X := GameForm.Width+R.Width;
R.Position.Y := (0-WOffset)+POffset;
R.Tag := 1;
R := TLayout(BigPipe.Clone(Self));
EnemyList.AddObject('',R);
R.Parent := GameForm;
R.Visible := True;
R.Position.X := GameForm.Width+R.Width;
R.Position.Y := (GameForm.Height-R.Height+WOffset)+POffset;
R.RotationAngle := 180;
R.Tag := 2;
end;
if GameTick>(SpawnTime*30) then
begin
GameTick := 0;
end
else
begin
Inc(GameTick);
end;
R1 := Rect(Trunc(BirdSprite.Position.X),Trunc(BirdSprite.Position.Y),Trunc(BirdSprite.Position.X+BirdSprite.Width),Trunc(BirdSprite.Position.Y+BirdSprite.Height));
for I := EnemyList.Count-1 downto 0 do
begin
if Assigned(EnemyList.Objects[I]) then
begin
R := TLayout(EnemyList.Objects[I]);
R.Position.X := R.Position.X-5;
R2 := Rect(Trunc(R.Position.X),Trunc(R.Position.Y),Trunc(R.Position.X+R.Width),Trunc(R.Position.Y+R.Height));
if CheckBoundryCollision(R1,R2)=True then
begin
GameOverCheck := True;
end
else
begin
if (((R.Position.X+(R.Width/2))<BirdSprite.Position.X) AND (R.Tag=1) AND (R.TagFloat=0)) then
begin
R.TagFloat := 1;
SetScore(Score+1);
end;
end;
if (R.Position.X<((R.Width*-1)-10)) then
begin
R.DisposeOf;
EnemyList.Delete(I);
end;
end;
end;
if BirdSprite.RotationAngle<90 then
BirdSprite.RotationAngle := BirdSprite.RotationAngle+5;
BirdSprite.Position.Y := BirdSprite.Position.Y+(Max(BirdSprite.RotationAngle,1)/5);
if MonkeyAni=False then
begin
BirdSprite.Bitmap.Assign(FMonkeyB.Bitmap);
MonkeyAni := True;
end
else
begin
BirdSprite.Bitmap.Assign(FMonkeyA.Bitmap);
MonkeyAni := False;
end;
if GameOverCheck=True then
GameOver;
end;
Ground.BringToFront;
ScoreLBL.BringToFront;
if GroundAni=True then
begin
GroundBar.Bitmap.Assign(GroundB.Bitmap);
GroundAni := False;
GroundBar.BringToFront;
end
else
begin
GroundBar.Bitmap.Assign(GroundA.Bitmap);
GroundAni := True;
GroundBar.BringToFront;
end;
if IsGameOver then
GameOverLayout.BringToFront;
GameForm.EndUpdate;
end;
{function CheckCollision(x1, y1, x2, y2, enemy_height, enemy_width: Integer): Boolean;
const
OFFSET_X = 4;
OFFSET_Y = 4;
begin
Result := True; }
{ if ((
(y1 + PLAYER_HEIGHT - (OFFSET_Y * 2)
<
(y1 + OFFSET_Y and y2 + ENEMY_HEIGHT - (OFFSET_Y * 2)
)
or
(
(x1 + PLAYER_WIDTH - (OFFSET_X * 2)
and
(x1 + OFFSET_X and x2 + ENEMY_WIDTH - (OFFSET_X * 2)
)) then
Result := False;}
//end;
function TGameForm.CheckBoundryCollision( R1, R2 : TRect; OffSetY : LongInt = 4; OffSetX : LongInt = 4): Boolean;
// Simple collision test based on rectangles.
begin
// Rectangle R1 can be the rectangle of the character (player)
// Rectangle R2 can be the rectangle of the enemy
// Simple collision test based on rectangles. We can also use the
// API function IntersectRect() but i believe this is much faster.
Result:=( NOT ((R1.Bottom - (OffSetY * 2) < R2.Top + OffSetY)
or(R1.Top + OffSetY > R2.Bottom - (OffSetY * 2))
or( R1.Right - (OffSetX * 2) < R2.Left + OffSetX)
or( R1.Left + OffSetX > R2.Right - (OffSetX * 2))));
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,
FMX.Controls.Presentation, FMX.ScrollBox, FMX.Memo,
DateUtils,
Quick.Commons,
Quick.Threads, FMX.StdCtrls, FMX.Layouts;
type
TMyJob = class
private
fId : Integer;
fName : string;
public
destructor Destroy; override;
property Id : Integer read fId write fId;
property Name : string read fName write fName;
procedure DoJob;
end;
TfrmMain = class(TForm)
meLog: TMemo;
Layout1: TLayout;
btnStart: TButton;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormActivate(Sender: TObject);
procedure btnStartClick(Sender: TObject);
private
{ Private declarations }
ScheduledTasks : TScheduledTasks;
public
{ Public declarations }
end;
var
frmMain: TfrmMain;
ScheduledDate : TDateTime;
ExpirationDate : TDateTime;
implementation
{$R *.fmx}
procedure Log(const msg : string; params : array of const);
begin
frmMain.meLog.Lines.Add(Format(msg,params));
end;
destructor TMyJob.Destroy;
begin
inherited;
end;
procedure TMyJob.DoJob;
var
a, b, i : Integer;
begin
log('[%s] task "%s" doing job...',[DateTimeToStr(Now()),fName]);
//Sleep(Random(1000));
a := Random(100);
b := Random(5) + 1;
i := a div b;
log('task "%s" result %d / %d = %d',[fName,a,b,i]);
end;
procedure TfrmMain.btnStartClick(Sender: TObject);
begin
ScheduledTasks.Start;
end;
procedure TfrmMain.FormActivate(Sender: TObject);
begin
//if not ScheduledTasks.IsStarted then ScheduledTasks.Start;
end;
procedure TfrmMain.FormClose(Sender: TObject; var Action: TCloseAction);
begin
ScheduledTasks.Free;
end;
procedure TfrmMain.FormCreate(Sender: TObject);
var
myjob : TMyJob;
begin
ScheduledTasks := TScheduledTasks.Create;
myjob := TMyJob.Create;
myjob.Id := 1;
myjob.Name := 'Run now and repeat every 1 second for 5 times';
scheduledtasks.AddTask_Sync('Task1',[myjob,1],True,
procedure(task : ITask)
begin
Log('task "%s" started',[TMyJob(task.Param[0]).Name]);
TMyJob(task.Param[0]).DoJob;
end
).OnException(
procedure(task : ITask; aException : Exception)
begin
Log('task "%s" failed (%s)',[TMyJob(task.Param[0]).Name,aException.Message]);
end
).OnTerminated_Sync(
procedure(task : ITask)
begin
Log('task "%s" finished',[TMyJob(task.Param[0]).Name]);
end
).OnExpired_Sync(
procedure(task : ITask)
begin
Log('task "%s" expired',[TMyJob(task.Param[0]).Name]);
end
).RepeatEvery(1,TTimeMeasure.tmSeconds,5);
myjob := TMyJob.Create;
myjob.Id := 2;
myjob.Name := 'Run now, repeat every 1 second forever';
scheduledtasks.AddTask_Sync('Task2',[myjob,32,true,3.2,myjob.ClassType],True,
procedure(task : ITask)
begin
Log('task "%s" started with params(Int=%d / Bool=%s / Float=%s /Class=%s)',[TMyJob(task.Param[0]).Name,task.Param[1].AsInteger,task.Param[2].AsString,task.Param[3].AsString,task.Param[4].AsString]);
TMyJob(task.Param[0]).DoJob;
end
).OnException(
procedure(task : ITask; aException : Exception)
begin
Log('task "%s" failed (%s)',[TMyJob(task.Param[0]).Name,aException.Message]);
end
).OnTerminated_Sync(
procedure(task : ITask)
begin
Log('task "%s" finished',[TMyJob(task.Param[0]).Name]);
end
).OnExpired_Sync(
procedure(task : ITask)
begin
Log('task "%s" expired',[TMyJob(task.Param[0]).Name]);
end
).StartAt(Now()
).RepeatEvery(1,TTimeMeasure.tmSeconds);
ScheduledDate := IncSecond(Now(),5);
ExpirationDate := IncSecond(ScheduledDate,10);
myjob := TMyJob.Create;
myjob.Id := 3;
myjob.Name := Format('Run at %s and repeat every 1 second until %s',[DateTimeToStr(ScheduledDate),DateTimeToStr(ExpirationDate)]);
scheduledtasks.AddTask_Sync('Task3',[myjob],True,
procedure(task : ITask)
begin
Log('task "%s" started',[TMyJob(task.Param[0]).Name]);
TMyJob(task.Param[0]).DoJob;
end
).OnException(
procedure(task : ITask; aException : Exception)
begin
Log('task "%s" failed (%s)',[TMyJob(task.Param[0]).Name,aException.Message]);
end
).OnTerminated_Sync(
procedure(task : ITask)
begin
Log('task "%s" finished',[TMyJob(task.Param[0]).Name]);
end
).OnExpired_Sync(
procedure(task : ITask)
begin
Log('task "%s" expired',[TMyJob(task.Param[0]).Name]);
end
).StartAt(ScheduledDate
).RepeatEvery(1,TTimeMeasure.tmSeconds,ExpirationDate);
Log('Running tasks in background!',[]);
end;
end.
|
unit UWIZSendPASC_EnterQuantity;
{$mode delphi}
{$modeswitch nestedprocvars}
{ Copyright (c) 2018 Sphere 10 Software (http://www.sphere10.com/)
Distributed under the MIT software license, see the accompanying file LICENSE
or visit http://www.opensource.org/licenses/mit-license.php.
Acknowledgements:
Ugochukwu Mmaduekwe - main developer
Herman Schoenfeld - designer
}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls,
ExtCtrls, Buttons, UCommon, UCommon.Collections, UWallet,
UFRMAccountSelect, UNode, UWizard, UWIZSendPASC, UWIZOperationFee_Custom, UWIZOperationPayload_Encryption,
UWIZOperationSigner_Select, UCoreObjects;
type
{ TWIZSendPASC_EnterQuantity }
TWIZSendPASC_EnterQuantity = class(TWizardForm<TExecuteOperationsModel>)
chkChooseFee: TCheckBox;
chkAttachPayload: TCheckBox;
chkallfunds: TCheckBox;
edtAmt: TEdit;
gbQuantity: TGroupBox;
lblQuantityNotice: TLabel;
procedure UpdateUI();
procedure chkallfundsChange(Sender: TObject);
public
procedure OnPresent; override;
procedure OnNext; override;
function Validate(out message: ansistring): boolean; override;
end;
implementation
{$R *.lfm}
uses
UAccounts, UUserInterface, USettings;
{ TWIZSendPASC_EnterQuantity }
procedure TWIZSendPASC_EnterQuantity.UpdateUI();
begin
if chkallfunds.Checked then
begin
edtAmt.Text := 'ALL BALANCE';
edtAmt.Enabled := False;
Model.SendPASC.SendPASCMode := akaAllBalance;
end
else
begin
edtAmt.Text := TAccountComp.FormatMoney(0);
edtAmt.Enabled := True;
Model.SendPASC.SendPASCMode := akaSpecifiedAmount;
end;
Model.Payload.HasPayload := IIF(chkAttachPayload.Checked, True, False);
end;
procedure TWIZSendPASC_EnterQuantity.chkallfundsChange(Sender: TObject);
begin
UpdateUI();
end;
procedure TWIZSendPASC_EnterQuantity.OnPresent;
begin
UpdateUI();
if Length(Model.Account.SelectedAccounts) > 1 then
begin
chkChooseFee.Checked := True;
chkChooseFee.Enabled := False;
end;
if edtAmt.Enabled then
edtAmt.SetFocus;
end;
procedure TWIZSendPASC_EnterQuantity.OnNext;
begin
Model.Payload.HasPayload := chkAttachPayload.Checked;
if chkallfunds.Checked then
Model.SendPASC.SingleAmountToSend := 0 // all balance
else
TAccountComp.TxtToMoney(edtAmt.Text, Model.SendPASC.SingleAmountToSend);
if chkChooseFee.Checked then
UpdatePath(ptInject, [TWIZOperationFee_Custom])
else
begin
Model.Fee.SingleOperationFee := TSettings.DefaultFee;
if Model.Payload.HasPayload then
UpdatePath(ptInject, [TWIZOperationPayload_Encryption])
else if Length(Model.Account.SelectedAccounts) > 1 then
UpdatePath(ptInject, [TWIZOperationSigner_Select])
else
begin
Model.Signer.SignerAccount := Model.Account.SelectedAccounts[0];
Model.Signer.OperationSigningMode := akaPrimary;
end;
end;
end;
function TWIZSendPASC_EnterQuantity.Validate(out message: ansistring): boolean;
var
LAmount: int64;
LIdx: integer;
LAccount: TAccount;
begin
Result := True;
if not chkallfunds.Checked then
begin
if not TAccountComp.TxtToMoney(edtAmt.Text, LAmount) then
begin
message := Format('Invalid Amount "%s"', [edtAmt.Text]);
Result := False;
Exit;
end;
if LAmount < 1 then
begin
message := 'You Must Send An Amount Greater Than Zero.';
Result := False;
Exit;
end;
for LIdx := Low(Model.Account.SelectedAccounts) to High(Model.Account.SelectedAccounts) do
begin
LAccount := Model.Account.SelectedAccounts[LIdx];
if LAccount.balance < LAmount then
begin
message := 'Insufficient Funds In One Or More Accounts.';
Result := False;
Exit;
end;
end;
end;
end;
end.
|
unit uIConverter;
interface
uses
System.Classes;
type
IConverter = interface
['{1E9EB0EC-68FC-4592-94C2-99CAE7C7345A}']
function Converter: string;
function GetTexto: string;
procedure SetTexto(const value: string);
property Texto: string read GetTexto write SetTexto;
end;
implementation
end.
|
unit Form.Main;
interface
{$SCOPEDENUMS ON}
uses
System.Types, System.Classes, FGX.Forms, FGX.Forms.Types, FGX.Controls, FGX.Controls.Types, FGX.Layout,
FGX.Layout.Types, FGX.Button.Types, FGX.Button, FGX.Memo;
type
TFormMain = class(TfgForm)
fgMemo1: TfgMemo;
fgButton1: TfgButton;
procedure fgButton1Tap(Sender: TObject);
procedure fgFormSafeAreaChanged(Sender: TObject; const AScreenInsets: TRectF);
private
{ Private declarations }
public
{ Public declarations }
end;
var
FormMain: TFormMain;
implementation
{$R *.xfm}
uses
System.SysUtils, FGX.Application, FGX.Dialogs, FGX.Log, FGX.ActiveNetworkInfo.Android;
procedure TFormMain.fgButton1Tap(Sender: TObject);
begin
fgMemo1.Lines.Clear;
fgMemo1.Lines.Add('CheckPermission: ' + BoolToStr(TActiveNetworkInfo.CheckPermission, True));
fgMemo1.Lines.Add('IsConnected: ' + BoolToStr(TActiveNetworkInfo.IsConnected, True));
fgMemo1.Lines.Add('IsWifi: ' + BoolToStr(TActiveNetworkInfo.IsWifi, True));
fgMemo1.Lines.Add('IsMobile: ' + BoolToStr(TActiveNetworkInfo.IsMobile, True));
end;
procedure TFormMain.fgFormSafeAreaChanged(Sender: TObject; const AScreenInsets: TRectF);
begin
Padding.Top := AScreenInsets.Top;
end;
end.
|
unit Model.Interceptor.Edit;
interface
uses
Vcl.StdCtrls,
Vcl.ExtCtrls,
System.Classes;
type
TEdit = class(Vcl.StdCtrls.TEdit)
private
FShape: TShape;
FMinLength: integer;
FLblError: TLabel;
procedure SetMinLength(const Value: integer);
protected
procedure Loaded; override;
procedure DoEnter; override;
procedure DoExit; override;
procedure Change; override;
public
constructor Create(AOwner : TComponent); override;
property MinLength : integer read FMinLength write SetMinLength;
end;
implementation
uses
Vcl.Graphics,
Vcl.Forms,
Vcl.Controls,
System.SysUtils;
{ TEdit }
procedure TEdit.Change;
begin
inherited;
end;
constructor TEdit.Create(AOwner: TComponent);
begin
inherited;
FShape := TShape.Create(Self);
FlblError := TLabel.Create(Self);
end;
procedure TEdit.DoEnter;
begin
FShape.Pen.Color := clBlue;
FLblError.Caption := '';
inherited;
end;
procedure TEdit.DoExit;
begin
inherited;
if length(Self.Text) > Pred(FMinLength) then
begin
FShape.Pen.Color := clBlack;
end
else
begin
FShape.Pen.Color := clRed;
FLblError.Caption := Format('O Campo deve ter no mínimo %d caracteres', [FMinLength]);
end;
end;
procedure TEdit.Loaded;
begin
inherited;
Self.BorderStyle := bsNone;
FShape.Name := 'Shape' + Self.Name;
FShape.Parent := Self.Parent;
FShape.Top := Self.Top - 2;
FShape.Width := Self.Width + 4;
FShape.Left := Self.Left - 2;
FShape.Height := Self.Height + 4;
FShape.Align := alNone;
FShape.Shape := stRoundRect;
FShape.Brush.Style := bsSolid;
FShape.Brush.Color := clWhite;
FShape.Pen.Color := clBlack;
FShape.Pen.Width := 1;
FShape.Visible := Self.Visible;
FShape.Enabled := Self.Enabled;
FlblError.Name := 'lbl' + Self.Name;
FLblError.Parent := Self.Parent;
FLblError.Top := Self.Top + 2;
FLblError.Left := Self.Left + Self.Width + 10;
FLblError.Font.Color := clRed;
FLblError.Caption := '';
end;
procedure TEdit.SetMinLength(const Value: integer);
begin
if Value > 0 then
FMinLength := Value;
end;
end.
|
unit fmuNodeAttributes;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, AtrPages, ToolCtrlsEh, ComCtrls, ToolWin,
GridsEh, DBGridEh, DB, FIBDataSet, pFIBDataSet, ActnList,
DBGridEhToolCtrls, DBAxisGridsEh, System.Actions, PrjConst,
EhLibVCL, System.UITypes, DBGridEhGrouping, DynVarsEh, FIBDatabase,
pFIBDatabase;
type
TapgNodeAttributes = class(TA4onPage)
dsAttributes: TpFIBDataSet;
srcAttributes: TDataSource;
dbgCustAttr: TDBGridEh;
tbAttributes: TToolBar;
btnAdd: TToolButton;
btnEdit: TToolButton;
btnDel: TToolButton;
ActListCustomers: TActionList;
actAdd: TAction;
actEdit: TAction;
actDel: TAction;
trRead: TpFIBTransaction;
trWrite: TpFIBTransaction;
procedure actAddExecute(Sender: TObject);
procedure actEditExecute(Sender: TObject);
procedure actDelExecute(Sender: TObject);
procedure dbgCustAttrDblClick(Sender: TObject);
private
procedure EnableControls;
public
procedure InitForm; override;
procedure OpenData; override;
procedure CloseData; override;
class function GetPageName: string; override;
end;
implementation
{$R *.dfm}
uses MAIN, AtrCommon, DM, NodesForma, NodeAttributeForma;
class function TapgNodeAttributes.GetPageName: string;
begin
Result := rsClmnAttributes;
end;
procedure TapgNodeAttributes.InitForm;
var
FullAccess: Boolean;
begin
FullAccess := (dmMain.AllowedAction(rght_Dictionary_Nodes));
tbAttributes.Visible := (dmMain.AllowedAction(rght_Dictionary_Nodes)) or FullAccess;
actAdd.Visible := tbAttributes.Visible;
actDel.Visible := tbAttributes.Visible;
actEdit.Visible := tbAttributes.Visible;
dsAttributes.DataSource := FDataSource;
end;
procedure TapgNodeAttributes.EnableControls;
begin
actEdit.Enabled := dsAttributes.RecordCount > 0;
actDel.Enabled := dsAttributes.RecordCount > 0;
end;
procedure TapgNodeAttributes.OpenData;
begin
dsAttributes.Open;
EnableControls;
end;
procedure TapgNodeAttributes.actAddExecute(Sender: TObject);
begin
if EditAttribute(FDataSource.DataSet['NODE_ID'], '') then
begin
dsAttributes.CloseOpen(true);
EnableControls;
UpdatePage;
end
end;
procedure TapgNodeAttributes.actDelExecute(Sender: TObject);
begin
if srcAttributes.DataSet.State in [dsInsert, dsEdit] then
srcAttributes.DataSet.Cancel
else
begin
if ((not dsAttributes.Active) or (dsAttributes.RecordCount = 0)) then
Exit;
if (not srcAttributes.DataSet.FieldByName('O_NAME').IsNull) then
begin
if (MessageDlg(Format(rsDeleteWithName, [srcAttributes.DataSet['O_NAME']]), mtConfirmation, [mbYes, mbNo], 0)
= mrYes) then
begin
srcAttributes.DataSet.Delete;
EnableControls;
UpdatePage;
end;
end;
end;
end;
procedure TapgNodeAttributes.actEditExecute(Sender: TObject);
begin
if ((not dsAttributes.Active) or (dsAttributes.RecordCount = 0)) then
Exit;
if (dsAttributes.FieldByName('O_NAME').IsNull) or (dsAttributes.FieldByName('NA_ID').IsNull) or
(FDataSource.DataSet.FieldByName('NODE_ID').IsNull) then
Exit;
if EditAttribute(FDataSource.DataSet['NODE_ID'], dsAttributes['O_NAME'], dsAttributes['NA_ID']) then
begin
dsAttributes.Refresh;
EnableControls;
UpdatePage;
end
end;
procedure TapgNodeAttributes.CloseData;
begin
dsAttributes.Close;
end;
procedure TapgNodeAttributes.dbgCustAttrDblClick(Sender: TObject);
begin
if (Sender as TDBGridEh).DataSource.DataSet.RecordCount > 0 then
begin
if actEdit.Enabled then
actEdit.Execute;
end
else
begin
if actAdd.Enabled then
actAdd.Execute;
end;
end;
end.
|
unit IdAboutDotNET;
interface
uses
System.Drawing, System.Collections, System.ComponentModel,
System.Windows.Forms, System.Data;
type
TfrmAbout = class(System.Windows.Forms.Form)
{$REGION 'Designer Managed Code'}
strict private
/// <summary>
/// Required designer variable.
/// </summary>
Components: System.ComponentModel.Container;
imgLogo: System.Windows.Forms.PictureBox;
bbtnOk: System.Windows.Forms.Button;
lblName: System.Windows.Forms.Label;
lblVersion: System.Windows.Forms.Label;
lblCopyright: System.Windows.Forms.Label;
lblPleaseVisitUs: System.Windows.Forms.Label;
lblURL: System.Windows.Forms.LinkLabel;
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
procedure InitializeComponent;
procedure lblURL_LinkClicked(sender: System.Object; e: System.Windows.Forms.LinkLabelLinkClickedEventArgs);
{$ENDREGION}
strict protected
/// <summary>
/// Clean up any resources being used.
/// </summary>
procedure Dispose(Disposing: Boolean); override;
protected
{ Private Declarations }
function GetProductName: string;
procedure SetProductName(const AValue: string);
function GetVersion: string;
procedure SetVersion(const AValue: string);
function LoadBitmap(AResName: string): Bitmap;
public
constructor Create;
//we have a method for providing a product name and version in case
//we ever want to make another prdocut.
class Procedure ShowAboutBox(const AProductName, AProductVersion : String);
class Procedure ShowDlg;
property ProductName : String read GetProductName write SetProductName;
property Version : String read GetVersion write SetVersion;
end;
[assembly: RuntimeRequiredAttribute(TypeOf(TfrmAbout))]
implementation
uses
IdDsnCoreResourceStrings, System.Diagnostics,
IdGlobal, System.Reflection, System.Resources, SysUtils;
const
ResourceBaseName = 'IdAboutNET';
{$R 'AboutIndyNET.resources'}
{$AUTOBOX ON}
{$REGION 'Windows Form Designer generated code'}
/// <summary>
/// Required method for Designer support -- do not modify
/// the contents of this method with the code editor.
/// </summary>
procedure TfrmAbout.InitializeComponent;
begin
Self.imgLogo := System.Windows.Forms.PictureBox.Create;
Self.bbtnOk := System.Windows.Forms.Button.Create;
Self.lblName := System.Windows.Forms.Label.Create;
Self.lblVersion := System.Windows.Forms.Label.Create;
Self.lblCopyright := System.Windows.Forms.Label.Create;
Self.lblPleaseVisitUs := System.Windows.Forms.Label.Create;
Self.lblURL := System.Windows.Forms.LinkLabel.Create;
Self.SuspendLayout;
//
// imgLogo
//
Self.imgLogo.Location := System.Drawing.Point.Create(0, 0);
Self.imgLogo.Name := 'imgLogo';
Self.imgLogo.Size := System.Drawing.Size.Create(431, 267);
Self.imgLogo.TabIndex := 0;
Self.imgLogo.TabStop := False;
//
// bbtnOk
//
Self.bbtnOk.Anchor := (System.Windows.Forms.AnchorStyles((System.Windows.Forms.AnchorStyles.Bottom
or System.Windows.Forms.AnchorStyles.Right)));
Self.bbtnOk.DialogResult := System.Windows.Forms.DialogResult.Cancel;
Self.bbtnOk.Location := System.Drawing.Point.Create(558, 338);
Self.bbtnOk.Name := 'bbtnOk';
Self.bbtnOk.TabIndex := 0;
Self.bbtnOk.Text := 'Button1';
//
// lblName
//
Self.lblName.Font := System.Drawing.Font.Create('Times New Roman', 14.25, System.Drawing.FontStyle.Bold,
System.Drawing.GraphicsUnit.Point, (Byte(0)));
Self.lblName.Location := System.Drawing.Point.Create(438, 16);
Self.lblName.Name := 'lblName';
Self.lblName.Size := System.Drawing.Size.Create(193, 72);
Self.lblName.TabIndex := 1;
Self.lblName.Text := 'Label1';
Self.lblName.TextAlign := System.Drawing.ContentAlignment.TopCenter;
//
// lblVersion
//
Self.lblVersion.Font := System.Drawing.Font.Create('Times New Roman', 9.75,
System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, (Byte(0)));
Self.lblVersion.Location := System.Drawing.Point.Create(438, 56);
Self.lblVersion.Name := 'lblVersion';
Self.lblVersion.Size := System.Drawing.Size.Create(195, 17);
Self.lblVersion.TabIndex := 2;
Self.lblVersion.Text := 'Label2';
Self.lblVersion.TextAlign := System.Drawing.ContentAlignment.TopCenter;
//
// lblCopyright
//
Self.lblCopyright.Font := System.Drawing.Font.Create('Times New Roman', 8,
System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, (Byte(0)));
Self.lblCopyright.Location := System.Drawing.Point.Create(438, 104);
Self.lblCopyright.Name := 'lblCopyright';
Self.lblCopyright.Size := System.Drawing.Size.Create(193, 75);
Self.lblCopyright.TabIndex := 3;
Self.lblCopyright.Text := 'Label3';
Self.lblCopyright.TextAlign := System.Drawing.ContentAlignment.TopCenter;
//
// lblPleaseVisitUs
//
Self.lblPleaseVisitUs.Anchor := (System.Windows.Forms.AnchorStyles(((System.Windows.Forms.AnchorStyles.Top
or System.Windows.Forms.AnchorStyles.Left) or System.Windows.Forms.AnchorStyles.Right)));
Self.lblPleaseVisitUs.Location := System.Drawing.Point.Create(8, 280);
Self.lblPleaseVisitUs.Name := 'lblPleaseVisitUs';
Self.lblPleaseVisitUs.Size := System.Drawing.Size.Create(623, 13);
Self.lblPleaseVisitUs.TabIndex := 4;
Self.lblPleaseVisitUs.Text := 'Label1';
Self.lblPleaseVisitUs.TextAlign := System.Drawing.ContentAlignment.TopCenter;
//
// lblURL
//
Self.lblURL.Anchor := (System.Windows.Forms.AnchorStyles(((System.Windows.Forms.AnchorStyles.Top
or System.Windows.Forms.AnchorStyles.Left) or System.Windows.Forms.AnchorStyles.Right)));
Self.lblURL.Location := System.Drawing.Point.Create(8, 296);
Self.lblURL.Name := 'lblURL';
Self.lblURL.Size := System.Drawing.Size.Create(623, 13);
Self.lblURL.TabIndex := 5;
Self.lblURL.TabStop := True;
Self.lblURL.Text := 'LinkLabel1';
Self.lblURL.TextAlign := System.Drawing.ContentAlignment.TopCenter;
Include(Self.lblURL.LinkClicked, Self.lblURL_LinkClicked);
//
// TfrmAbout
//
Self.AcceptButton := Self.bbtnOk;
Self.AutoScaleBaseSize := System.Drawing.Size.Create(5, 13);
Self.CancelButton := Self.bbtnOk;
Self.ClientSize := System.Drawing.Size.Create(637, 372);
Self.Controls.Add(Self.lblURL);
Self.Controls.Add(Self.lblPleaseVisitUs);
Self.Controls.Add(Self.lblCopyright);
Self.Controls.Add(Self.lblVersion);
Self.Controls.Add(Self.lblName);
Self.Controls.Add(Self.bbtnOk);
Self.Controls.Add(Self.imgLogo);
Self.FormBorderStyle := System.Windows.Forms.FormBorderStyle.FixedDialog;
Self.MaximizeBox := False;
Self.MinimizeBox := False;
Self.Name := 'TfrmAbout';
Self.ShowInTaskbar := False;
Self.StartPosition := System.Windows.Forms.FormStartPosition.CenterScreen;
Self.Text := 'WinForm';
Self.ResumeLayout(False);
end;
{$ENDREGION}
procedure TfrmAbout.Dispose(Disposing: Boolean);
begin
if Disposing then
begin
if Components <> nil then
Components.Dispose();
end;
inherited Dispose(Disposing);
end;
constructor TfrmAbout.Create;
var LBitmap : Bitmap;
begin
inherited Create;
//
// Required for Windows Form Designer support
//
InitializeComponent;
//
// TODO: Add any constructor code after InitializeComponent call
//
Self.Text := RSAAboutFormCaption;
lblCopyright.Text := RSAAboutBoxCopyright;
lblPleaseVisitUs.Text := RSAAboutBoxPleaseVisit;
lblURL.Text := RSAAboutBoxIndyWebsite;
lblURL.Links.Add(0,Length(RSAABoutBoxIndyWebsite),RSAAboutBoxIndyWebsite);
bbtnOk.Text := RSOk;
LBitmap := LoadBitmap('IndyCar.bmp');
LBitmap.MakeTransparent;
imgLogo.Image := LBitmap;
end;
procedure TfrmAbout.SetProductName(const AValue : String);
begin
Self.lblName.Text := AValue;
end;
procedure TfrmAbout.SetVersion(const AValue: string);
begin
Self.lblVersion.Text := AValue;
end;
function TfrmAbout.GetVersion: string;
begin
Result := Self.lblVersion.Text;
end;
function TfrmAbout.GetProductName: string;
begin
Result := Self.lblName.Text;
end;
class procedure TfrmAbout.ShowAboutBox(const AProductName,
AProductVersion: String);
begin
with TfrmAbout.Create do
try
Version := IndyFormat(RSAAboutBoxVersion, [AProductVersion]);
ProductName := AProductName;
Text := AProductName;
ShowDialog;
finally
Dispose;
end;
end;
class procedure TfrmAbout.ShowDlg;
begin
ShowAboutBox(RSAAboutBoxCompName, gsIdVersion);
end;
procedure TfrmAbout.lblURL_LinkClicked(sender: System.Object; e: System.Windows.Forms.LinkLabelLinkClickedEventArgs);
var
LDest : String;
begin
LDest := e.Link.LinkData as string;
System.Diagnostics.Process.Start(LDest);
e.Link.Visited := True;
end;
function TfrmAbout.LoadBitmap(AResName: string): Bitmap;
var
LR: System.Resources.ResourceManager;
begin
LR := System.Resources.ResourceManager.Create('AboutIndyNET', System.Reflection.Assembly.GetExecutingAssembly);
Result := (Bitmap(LR.GetObject('IndyCar.bmp')));
Result := Result;
end;
end.
|
unit TestServer;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, IdBaseComponent, IdComponent,
IdCustomTCPServer, IdCustomHTTPServer, IdHTTPServer, Vcl.XPMan, Vcl.StdCtrls,
IdContext;
type
TfmTestServer = class(TForm)
lbPort: TLabel;
ePort: TEdit;
cbPassSec: TCheckBox;
gbServer: TGroupBox;
eName: TEdit;
ePass: TEdit;
MemoServer: TMemo;
btnStart: TButton;
btnStop: TButton;
btnClear: TButton;
lbName: TLabel;
lbPass: TLabel;
XPManifest1: TXPManifest;
Server: TIdHTTPServer;
procedure btnClearClick(Sender: TObject);
procedure btnStartClick(Sender: TObject);
procedure btnStopClick(Sender: TObject);
procedure ServerConnect(AContext: TIdContext);
procedure ServerDisconnect(AContext: TIdContext);
procedure ServerCommandGet(AContext: TIdContext;
ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);
private
{ Private declarations }
public
{ Public declarations }
end;
var
fmTestServer: TfmTestServer;
user : integer;
implementation
{$R *.dfm}
procedure TfmTestServer.btnClearClick(Sender: TObject);
begin
MemoServer.Lines.Clear;
MemoServer.Lines.Add('Server 1.0');
end;
procedure TfmTestServer.btnStartClick(Sender: TObject);
begin
Server.DefaultPort:= StrToInt(ePort.Text);
Server.Active:= True;
MemoServer.Lines.Add('Status: '+DateToStr(date)+' | ' + TimeToStr(time)
+ ': Server started.');
btnStart.Enabled:= False;
btnStop.Enabled:= True;
lbPort.Enabled:= False;
ePort.Enabled:= False;
end;
procedure TfmTestServer.btnStopClick(Sender: TObject);
begin
Server.Active:= False;
MemoServer.Lines.Add('Status: ' + DateToStr(date)+' | ' + TimeToStr(time)
+ ': Server stopped.');
btnStart.Enabled:= True;
btnStop.Enabled:= False;
lbPort.Enabled:= True;
ePort.Enabled:= True;
end;
procedure TfmTestServer.ServerCommandGet(AContext: TIdContext;
ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);
var
Stream: TFileStream;
Size: String;
begin
if (cbPassSec.Checked= True) and ((ARequestInfo.AuthUsername <> eName.Text) or (ARequestInfo.AuthPassword <> ePass.Text))
then begin
AResponseInfo.ContentText:= 'Username and Password request...';
AResponseInfo.AuthRealm:= 'Scheff-Interface'; // õç ÷òî ýòî
end
else begin
if ARequestInfo.Document='/' then begin
AResponseInfo.ContentType:= 'text/html';
Stream:= TFileStream.Create('htdocs/index.html', fmOpenRead or fmShareDenyWrite);
AResponseInfo.ContentStream:=Stream;
SetLength(Size, Stream.Size);
Stream.Read(Size[1],Stream.Size);
MemoServer.Lines.Add(DateToStr(date) + ' | '
+ TimeToStr(time) + ': Client '
+ ARequestInfo.RemoteIP + ' has the file index.html ('
+ IntToStr(round(Stream.Size / 1024))
+ ' kb ) requested.' );
end;
end;
end;
procedure TfmTestServer.ServerConnect(AContext: TIdContext);
begin
user:= user + 1;
gbServer.Caption:= 'Protocol (User: ' + IntToStr(user) + '):';
end;
procedure TfmTestServer.ServerDisconnect(AContext: TIdContext);
begin
user:= user - 1;
gbServer.Caption:= 'Protocol (User: ' + IntToStr(user) + '):';
end;
end.
|
//***********************************************************
// InventorySystem
//
// Copyright (c) 2002 Failproof Manufacturing Systems
//
//***********************************************************
//
// 10/31/2002 Aaron Huge Initial creation
unit Logon;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls, Buttons, DataModule; //IniFiles;
type
TLogon_Form = class(TForm)
Panel2: TPanel;
Password_Label: TLabel;
bitBtnLogon: TBitBtn;
BitBtnCancel: TBitBtn;
Password_Edit: TEdit;
UserID_Label: TLabel;
UserID_Edit: TEdit;
procedure bitBtnLogonClick(Sender: TObject);
procedure EditKeyPress(Sender: TObject; var Key: Char);
private
{ Private declarations }
public
{ Public declarations }
function Execute: boolean;
end;
var
Logon_Form: TLogon_Form;
implementation
{$R *.DFM}
procedure TLogon_Form.bitBtnLogonClick(Sender: TObject);
begin
If (Trim(UserID_Edit.Text) = '') Or (Trim(Password_Edit.Text) = '') Then
Begin
MessageDlg('Either or both of the ID and Password boxes are blank.' +
#13 + 'Please try again.', mtInformation, [mbOK], 0);
UserID_Edit.SetFocus;
End
Else
Begin
If Data_Module.ValidateUser(Trim(UserID_Edit.Text), Trim(Password_Edit.Text)) Then
Begin
ModalResult := mrOK;
End
Else
Begin
UserID_Edit.Text := '';
Password_Edit.Text := '';
UserID_Edit.SetFocus;
MessageDlg('The user ID and/or password you entered is invalid.' +
#13 + 'Please try again.', mtInformation, [mbOK], 0);
End;
End;
end;
function TLogon_Form.Execute: boolean;
Begin
Result:= True;
UserID_Edit.Text := '';
Password_Edit.Text:='';
try
try
ShowModal;
except
On E:Exception do
showMessage('Unable to generate logon screen.'
+ #13 + 'ERROR:'
+ #13 + E.Message);
end;
finally
If ModalResult = mrCancel Then
Result:= False;
end;
end; //Execute
procedure TLogon_Form.EditKeyPress(Sender: TObject;
var Key: Char);
begin
If Key in ['a'..'z'] then Dec(Key,32); {Force Uppercase only!}
end;
end.
|
unit UDemo;
interface
uses
SysUtils, Types, UITypes, Classes,
Variants, FMX.Forms, FMX.Types, FMX.TMSBaseControl, FMX.TMSTableView,
FMX.TMSBitmapContainer, FMX.Objects, FMX.TMSBitmap, FMX.Controls,
FMX.TMSBarButton, FMX.TMSPopup, FMX.ListBox, FMX.StdCtrls;
type
TForm536 = class(TForm)
TMSFMXBitmapContainer1: TTMSFMXBitmapContainer;
Label1: TLabel;
ComboBox1: TComboBox;
ListBoxItem1: TListBoxItem;
ListBoxItem2: TListBoxItem;
Label2: TLabel;
CheckBox1: TCheckBox;
Label3: TLabel;
ComboBox2: TComboBox;
ListBoxItem3: TListBoxItem;
ListBoxItem4: TListBoxItem;
ListBoxItem5: TListBoxItem;
CheckBox2: TCheckBox;
Label4: TLabel;
ComboBox3: TComboBox;
Label5: TLabel;
ListBoxItem6: TListBoxItem;
ListBoxItem7: TListBoxItem;
ListBoxItem8: TListBoxItem;
Label6: TLabel;
CheckBox3: TCheckBox;
Label7: TLabel;
Label8: TLabel;
CheckBox4: TCheckBox;
TMSFMXTableView1: TTMSFMXTableView;
TMSFMXTableView2: TTMSFMXTableView;
GroupBox2: TGroupBox;
Panel1: TPanel;
GroupBox1: TGroupBox;
Label9: TLabel;
Label10: TLabel;
CheckBox5: TCheckBox;
Label11: TLabel;
CheckBox6: TCheckBox;
Label12: TLabel;
Image1: TImage;
Label13: TLabel;
Label14: TLabel;
Label15: TLabel;
Label16: TLabel;
Label17: TLabel;
Label18: TLabel;
TMSFMXBarButton1: TTMSFMXBarButton;
TMSFMXTableView3: TTMSFMXTableView;
TMSFMXBarButton2: TTMSFMXBarButton;
TMSFMXPopup1: TTMSFMXPopup;
procedure FormCreate(Sender: TObject);
procedure TMSFMXTableView1ItemCustomize(Sender: TObject;
AItem: TTMSFMXTableViewItem; AItemShape: TTMSFMXTableViewItemShape;
AItemControlShape: TControl);
procedure ComboBox1Change(Sender: TObject);
procedure CheckBox1Change(Sender: TObject);
procedure TMSFMXTableView1ApplyStyleLookup(Sender: TObject);
procedure ComboBox2Change(Sender: TObject);
procedure CheckBox2Change(Sender: TObject);
procedure ComboBox3Change(Sender: TObject);
procedure CheckBox3Change(Sender: TObject);
procedure CheckBox4Change(Sender: TObject);
procedure TMSFMXTableView1ItemBeforeDetail(Sender: TObject;
AItem: TTMSFMXTableViewItem);
procedure TMSFMXTableView1ItemAfterReturnDetail(Sender: TObject;
AItem: TTMSFMXTableViewItem);
procedure CheckBox5Change(Sender: TObject);
procedure CheckBox6Change(Sender: TObject);
procedure TMSFMXBarButton1Click(Sender: TObject);
procedure TMSFMXTableView2ItemSelected(Sender: TObject;
AItem: TTMSFMXTableViewItem);
procedure FormDestroy(Sender: TObject);
procedure TMSFMXTableView2ItemCustomize(Sender: TObject;
AItem: TTMSFMXTableViewItem; AItemShape: TTMSFMXTableViewItemShape;
AItemControlShape: TControl);
procedure TMSFMXTableView2MarkClick(Sender: TObject);
procedure TMSFMXTableView2ItemDelete(Sender: TObject;
AItem: TTMSFMXTableViewItem; var AllowDelete: Boolean);
procedure TMSFMXBarButton2Click(Sender: TObject);
procedure TMSFMXTableView3ItemCustomize(Sender: TObject;
AItem: TTMSFMXTableViewItem; AItemShape: TTMSFMXTableViewItemShape;
AItemControlShape: TControl);
procedure TMSFMXTableView3ItemSelected(Sender: TObject;
AItem: TTMSFMXTableViewItem);
private
{ Private declarations }
public
{ Public declarations }
function FindItemOnList(AItem: TTMSFMXTableViewItem; ID: Integer): TObject;
end;
TItem = class(TPersistent)
private
FId: Integer;
public
property ID: Integer read FId write FId;
end;
var
Form536: TForm536;
implementation
{$R *.fmx}
procedure TForm536.CheckBox1Change(Sender: TObject);
begin
TMSFMXTableView1.LookupBar := CheckBox1.IsChecked;
end;
procedure TForm536.CheckBox2Change(Sender: TObject);
begin
TMSFMXTableView1.ShowFilter := CheckBox2.IsChecked;
end;
procedure TForm536.CheckBox3Change(Sender: TObject);
begin
TMSFMXTableView1.AutoFilter := CheckBox3.IsChecked;
end;
procedure TForm536.CheckBox4Change(Sender: TObject);
begin
TMSFMXTableView2.EditButton := CheckBox4.IsChecked;
end;
procedure TForm536.CheckBox5Change(Sender: TObject);
var
I: Integer;
begin
for I := 0 to TMSFMXTableView2.Items.Count - 1 do
TMSFMXTableView2.Items[I].CanEditCaption := CheckBox5.IsChecked;
end;
procedure TForm536.CheckBox6Change(Sender: TObject);
var
I: Integer;
begin
for I := 0 to TMSFMXTableView2.Items.Count - 1 do
TMSFMXTableView2.Items[I].CanEditDescription := CheckBox6.IsChecked;
end;
procedure TForm536.ComboBox1Change(Sender: TObject);
begin
TMSFMXTableView1.LayoutMode := TTMSFMXTableViewLayoutMode(ComboBox1.ItemIndex);
end;
procedure TForm536.ComboBox2Change(Sender: TObject);
begin
case TMSFMXTableView1.CategoryType of
ctAlphaBetic: TMSFMXTableView1.GetLookupBar.Width := 45;
ctCustom: TMSFMXTableView1.GetLookupBar.Width := 25;
end;
TMSFMXTableView1.CategoryType := TTMSFMXTableViewCategoryType(ComboBox2.ItemIndex);
end;
procedure TForm536.ComboBox3Change(Sender: TObject);
begin
TMSFMXTableView1.Filtering := TTMSFMXTableViewFiltering(ComboBox3.ItemIndex);
end;
function TForm536.FindItemOnList(AItem: TTMSFMXTableViewItem;
ID: Integer): TObject;
var
I: Integer;
begin
Result := nil;
if Assigned(AItem.DataObject) then
begin
for I := 0 to (AItem.DataObject as TList).Count - 1 do
begin
if (TObject((AItem.DataObject as TList).Items[I]) as TItem).ID = ID then
begin
Result := TObject((AItem.DataObject as TList).Items[I]);
Break;
end;
end;
end;
end;
procedure TForm536.FormCreate(Sender: TObject);
var
I: Integer;
begin
GroupBox2.Enabled := False;
TMSFMXTableView1.BeginUpdate;
TMSFMXTableView1.BitmapContainer := TMSFMXBitmapContainer1;
TMSFMXTableView1.ItemOptions := [ioLeftRectangle, ioCenterRectangle, ioBulbRectangle, ioDetailRectangle, ioCaptionElement];
TMSFMXTableView1.Items.Clear;
TMSFMXTableView1.CategoryType := ctCustom;
TMSFMXTableView1.LookupBar := False;
with TMSFMXTableView1.Categories.Add do
begin
Caption := 'Yellow Fruit';
LookupText := 'Yellow';
end;
with TMSFMXTableView1.Categories.Add do
begin
Caption := 'Green Fruit';
LookupText := 'Green';
end;
with TMSFMXTableView1.Categories.Add do
begin
Caption := 'Blue Fruit';
LookupText := 'Blue';
end;
with TMSFMXTableView1.Categories.Add do
begin
Caption := 'Red Fruit';
LookupText := 'Red';
end;
with TMSFMXTableView1.Categories.Add do
begin
Caption := 'Orange Fruit';
LookupText := 'Orange';
end;
TMSFMXTableView1.Categories.Sort;
for I := 0 to TMSFMXBitmapContainer1.Items.Count - 1 do
begin
with TMSFMXTableView1.Items.Add do
begin
CategoryID := TMSFMXBitmapContainer1.Items[I].Tag;
Caption := TMSFMXBitmapContainer1.Items[I].Name;
BitmapName := Caption;
if (I = 3) or (I = 2) or (I = 7) then
begin
DetailView := TMSFMXTableView2;
Randomize;
BulbText := inttostr(Random(10) + 5);
DataObject := TList.Create;
end;
end;
end;
TMSFMXTableView1.Items.Sort;
TMSFMXTableView1.EndUpdate;
TMSFMXTableView2.ItemOptions := TMSFMXTableView2.ItemOptions + [ioRightRectangle];
end;
procedure TForm536.FormDestroy(Sender: TObject);
var
i, k: integer;
begin
for I := 0 to TMSFMXTableView1.Items.Count - 1 do
begin
if Assigned(TMSFMXTableView1.Items[I].DataObject) then
begin
for K := (TMSFMXTableView1.Items[I].DataObject as TList).Count - 1 downto 0 do
TObject(((TMSFMXTableView1.Items[I].DataObject as TList).Items[K])).Free;
TMSFMXTableView1.Items[I].DataObject.Free;
end;
end;
end;
procedure TForm536.TMSFMXBarButton1Click(Sender: TObject);
var
it: TTMSFMXTableViewItem;
shpr: TRectangle;
item: TItem;
begin
it := TMSFMXTableView2.SelectedItem;
if Assigned(it) then
begin
if Assigned((TMSFMXTableView1.SelectedItem.DataObject as TList)) then
begin
if (TMSFMXTableView1.SelectedItem.DataObject as TList).IndexOf(it.DataObject) = -1 then
begin
item := TItem.Create;
item.ID := it.Index;
(TMSFMXTableView1.SelectedItem.DataObject as TList).Add(item);
it.DataObject := item;
end;
shpr := it.ShapeRightRectangle;
if Assigned(shpr) then
shpr.Visible := True;
end;
end;
end;
procedure TForm536.TMSFMXBarButton2Click(Sender: TObject);
begin
TMSFMXPopup1.ShowPopup(Sender as TControl, False, TPlacement.plTopCenter);
end;
procedure TForm536.TMSFMXTableView1ApplyStyleLookup(Sender: TObject);
begin
TMSFMXTableView1.GetLookupBar.Width := 45;
end;
procedure TForm536.TMSFMXTableView1ItemAfterReturnDetail(Sender: TObject;
AItem: TTMSFMXTableViewItem);
begin
GroupBox1.Enabled := True;
GroupBox2.Enabled := False;
TMSFMXBarButton2.Text := 'Quantity';
end;
procedure TForm536.TMSFMXTableView1ItemBeforeDetail(Sender: TObject;
AItem: TTMSFMXTableViewItem);
var
cnt, i, c: Integer;
begin
GroupBox1.Enabled := False;
GroupBox2.Enabled := True;
TMSFMXTableView2.BeginUpdate;
TMSFMXTableView2.Items.Clear;
cnt := 0;
if AItem.BulbText <> '' then
cnt := strtoint(AItem.BulbText);
c := Random(10) + 1;
TMSFMXTableView2.HeaderText := 'Prices of ' + AItem.Caption;
for I := 0 to cnt - 1 do
begin
with TMSFMXTableView2.Items.Add do
begin
Caption := inttostr((I + 1) * c) + ' kg';
Description := 'Price : € ' + floattostr(((I + 1) * c) * 1.25);
CanEditCaption := CheckBox5.IsChecked;
CanEditDescription := CheckBox6.IsChecked;
DataObject := FindItemOnList(AItem, I);
end;
end;
TMSFMXTableView2.EndUpdate;
end;
procedure TForm536.TMSFMXTableView1ItemCustomize(Sender: TObject;
AItem: TTMSFMXTableViewItem; AItemShape: TTMSFMXTableViewItemShape;
AItemControlShape: TControl);
begin
AItem.ShapeCaption.Align := TAlignLayout.alClient;
AItem.ShapeLeftRectangle.Visible := True;
end;
procedure TForm536.TMSFMXTableView2ItemCustomize(Sender: TObject;
AItem: TTMSFMXTableViewItem; AItemShape: TTMSFMXTableViewItemShape;
AItemControlShape: TControl);
var
shpr: TRectangle;
begin
shpr := AItem.ShapeRightRectangle;
if Assigned(shpr) then
shpr.Visible := Assigned(AItem.DataObject);
end;
procedure TForm536.TMSFMXTableView2ItemDelete(Sender: TObject;
AItem: TTMSFMXTableViewItem; var AllowDelete: Boolean);
var
shpr: TRectangle;
i: integer;
it: TObject;
begin
if Assigned(AItem.DataObject) then
begin
i := (TMSFMXTableView1.SelectedItem.DataObject as TList).IndexOf(AItem.DataObject);
it := TObject((TMSFMXTableView1.SelectedItem.DataObject as TList).Items[i]);
(TMSFMXTableView1.SelectedItem.DataObject as TList).Remove(it);
it.Free;
AItem.DataObject := nil;
shpr := AItem.ShapeRightRectangle;
if Assigned(shpr) then
shpr.Visible := Assigned(AItem.DataObject);
end;
end;
procedure TForm536.TMSFMXTableView2ItemSelected(Sender: TObject;
AItem: TTMSFMXTableViewItem);
begin
Label16.Text := TMSFMXTableView1.SelectedItem.Caption;
label17.Text := AItem.Caption;
Label18.Text := AItem.Description;
TMSFMXBarButton1.Enabled := True;
TMSFMXBarButton2.Enabled := True;
end;
procedure TForm536.TMSFMXTableView2MarkClick(Sender: TObject);
var
it: TTMSFMXTableViewItem;
shpr: TRectangle;
item: TItem;
I: Integer;
begin
for I := 0 to TMSFMXTableView2.Items.Count - 1 do
begin
it := TMSFMXTableView2.Items[I];
if Assigned(it) and (it.Selected) then
begin
if Assigned((TMSFMXTableView1.SelectedItem.DataObject as TList)) then
begin
if (TMSFMXTableView1.SelectedItem.DataObject as TList).IndexOf(it.DataObject) = -1 then
begin
item := TItem.Create;
item.ID := it.Index;
(TMSFMXTableView1.SelectedItem.DataObject as TList).Add(item);
it.DataObject := item;
end;
shpr := it.ShapeRightRectangle;
if Assigned(shpr) then
shpr.Visible := True;
end;
end;
end;
end;
procedure TForm536.TMSFMXTableView3ItemCustomize(Sender: TObject;
AItem: TTMSFMXTableViewItem; AItemShape: TTMSFMXTableViewItemShape;
AItemControlShape: TControl);
begin
if Odd(AItem.Index) then
begin
AItemShape.Fill.Color := TAlphaColorRec.Lightgray;
AItemShape.DescriptionColor := TAlphaColorRec.Slategray;
end;
end;
procedure TForm536.TMSFMXTableView3ItemSelected(Sender: TObject;
AItem: TTMSFMXTableViewItem);
begin
TMSFMXBarButton2.Text := 'Quantity (' + AItem.Caption + ')';
TMSFMXPopup1.HidePopup;
end;
end.
|
unit Recording;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, ComCtrls, StdCtrls, Buttons, ToolWin, ImgList, CommCtrl,
INIFiles, ID3v2LibraryDefs;
type
TfrmRecording = class(TForm)
lblInfo: TLabel;
pbBuffer: TProgressBar;
SaveDialog: TSaveDialog;
Timer: TTimer;
lblVersion: TLabel;
lblBuffer: TLabel;
lblInfo2: TLabel;
StatusBar: TStatusBar;
tbButtons: TToolBar;
ilButtons: TImageList;
pnlInfo: TPanel;
imgInfo: TImage;
tbtnRecord: TToolButton;
tbtnPause: TToolButton;
tbtnStop: TToolButton;
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure TimerTimer(Sender: TObject);
procedure StreamInfo;
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure tbtnRecordClick(Sender: TObject);
procedure tbtnPauseClick(Sender: TObject);
procedure tbtnStopClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
procedure EnableDisable;
end;
const
VersionRecord : WideString = '0.1.0.2 beta';
var
frmRecording : TfrmRecording;
LastURL : AnsiString;
function GenreToByte(Genre: WideString): Byte;
implementation
uses General, uLNG, uComments, dynamic_BASS, BassPlayer, uFileFolder, uIcon, uTheme,
u_lang_ids, uToolTip, uINI, Convs;
const TotalGenre = 147;
ID3genre: array[0..TotalGenre] of string = (
'Blues', 'Classic Rock', 'Country', 'Dance', 'Disco', 'Funk', 'Grunge',
'Hip-Hop', 'Jazz', 'Metal', 'New Age', 'Oldies', 'Other', 'Pop', 'R&B',
'Rap', 'Reggae', 'Rock', 'Techno', 'Industrial', 'Alternative', 'Ska',
'Death Metal', 'Pranks', 'Soundtrack', 'Euro-Techno', 'Ambient',
'Trip-Hop', 'Vocal', 'Jazz+Funk', 'Fusion', 'Trance', 'Classical',
'Instrumental', 'Acid', 'House', 'Game', 'Sound Clip', 'Gospel',
'Noise', 'AlternRock', 'Bass', 'Soul', 'Punk', 'Space', 'Meditative',
'Instrumental Pop', 'Instrumental Rock', 'Ethnic', 'Gothic',
'Darkwave', 'Techno-Industrial', 'Electronic', 'Pop-Folk',
'Eurodance', 'Dream', 'Southern Rock', 'Comedy', 'Cult', 'Gangsta',
'Top 40', 'Christian Rap', 'Pop/Funk', 'Jungle', 'Native American',
'Cabaret', 'New Wave', 'Psychadelic', 'Rave', 'Showtunes', 'Trailer',
'Lo-Fi', 'Tribal', 'Acid Punk', 'Acid Jazz', 'Polka', 'Retro',
'Musical', 'Rock & Roll', 'Hard Rock', 'Folk', 'Folk-Rock',
'National Folk', 'Swing', 'Fast Fusion', 'Bebob', 'Latin', 'Revival',
'Celtic', 'Bluegrass', 'Avantgarde', 'Gothic Rock', 'Progressive Rock',
'Psychedelic Rock', 'Symphonic Rock', 'Slow Rock', 'Big Band',
'Chorus', 'Easy Listening', 'Acoustic', 'Humour', 'Speech', 'Chanson',
'Opera', 'Chamber Music', 'Sonata', 'Symphony', 'Booty Bass', 'Primus',
'Porn Groove', 'Satire', 'Slow Jam', 'Club', 'Tango', 'Samba',
'Folklore', 'Ballad', 'Power Ballad', 'Rhythmic Soul', 'Freestyle',
'Duet', 'Punk Rock', 'Drum Solo', 'Acapella', 'Euro-House', 'Dance Hall',
'Goa', 'Drum & Bass', 'Club-House', 'Hardcore', 'Terror', 'Indie',
'BritPop', 'Negerpunk', 'Polsk Punk', 'Beat', 'Christian Gangsta Rap',
'Heavy Metal', 'Black Metal', 'Crossover', 'Contemporary Christian',
'Christian Rock', 'Merengue', 'Salsa', 'Trash Metal', 'Anime', 'Jpop',
'Synthpop'
);
var
StreamFormat : TStreamFormat;
{$R *.dfm}
procedure TfrmRecording.EnableDisable;
begin
if StreamRecording = True then
begin
tbtnRecord.Enabled := False;
tbtnPause.Enabled := True;
tbtnStop.Enabled := True;
end
else
begin
tbtnRecord.Enabled := True;
tbtnPause.Enabled := False;
tbtnStop.Enabled := False;
end;
end;
procedure TfrmRecording.FormClose(Sender: TObject; var Action: TCloseAction);
begin
RecordingIsShow := False;
FRecording.Destroy;
end;
procedure TfrmRecording.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
if StreamRecording then
ShowMessage(LNG('FORM Recording', 'CloseFormError', 'You can''t close window until you stop recording'));
CanClose := not StreamRecording;
end;
procedure TfrmRecording.FormShow(Sender: TObject);
var
I: Integer;
sSuppFormats: WideString;
begin
Color := frmBgColor;
Icon := PluginSkin.Recording.Icon;
Caption := LNG('FORM Recording', 'Caption', 'Recording');
tbtnRecord.Hint := LNG('FORM Recording', 'Record', 'Record');
tbtnPause.Hint := LNG('FORM Recording', 'Pause', 'Pause');
tbtnStop.Hint := LNG('FORM Recording', 'Stop', 'Stop');
imgInfo.Picture.Assign(PluginSkin.Info.Image.Picture);
//32 bit support - transparent atd....
ilButtons.Handle := ImageList_Create(ilButtons.Width, ilButtons.Height, ILC_COLOR32 or ILC_MASK, ilButtons.AllocBy, ilButtons.AllocBy);
ilButtons.AddIcon(PluginTheme.State.PictureRecord.Icon);
ilButtons.AddIcon(PluginTheme.State.PicturePause.Icon);
ilButtons.AddIcon(PluginTheme.State.PictureStop.Icon);
lblInfo2.Caption := LNG('FORM Recording', 'NotRecording', 'Can''t record this format');
// lblSupportFormats.Caption := LNG('FORM Recording', 'SupportedFormats', 'Supported recording stream formats') + ': ' + #13;
I := 1;
StreamFormat.Name := '';
sSuppFormats := '';
repeat
StreamFormat := GetSupportStreamFormat(I);
if sSuppFormats<>'' then
begin
if StreamFormat.Format <> '' then
begin
sSuppFormats := sSuppFormats + ', ';
if ((I-1) mod 2)=0 then
sSuppFormats := sSuppFormats + #13+#10;
end;
end;
if StreamFormat.Format='' then
sSuppFormats := sSuppFormats + StreamFormat.Name
else
sSuppFormats := sSuppFormats + StreamFormat.Name + ' ('+StreamFormat.Format+')';
Inc(I);
until StreamFormat.Format = '';
CreateToolTips(Handle);
AddToolTip(pnlInfo.Handle, @ti, 1, PWideChar(sSuppFormats), PWideChar(LNG('FORM Recording', 'SupportedFormats', 'Supported recording stream formats') + ':'));
EnableDisable;
LastURL := '';
lblVersion.Caption := QIPPlugin.GetLang(LI_VERSION) + ' ' + VersionRecord;
AddComments(FRecording);
TimerTimer(nil);
RecordingIsShow := True;
end;
procedure TfrmRecording.TimerTimer(Sender: TObject);
var
Chan : DWORD;
Info : BASS_CHANNELINFO;
URL : AnsiString;
begin
// Zjištění streamovaného formátu
URL := PlayURL;
if URL <> LastURL then // zjisti pouze, pokud bude změněn stream
begin
LastURL := URL;
Chan := BASS_StreamCreateURL(PAnsiChar(URL), 0, BASS_STREAM_STATUS, nil, 0);
BASS_ChannelGetInfo(Chan, Info);
StreamFormat := GetSupportStreamFormat( fBassPlayer.GetCTypeString(Info.CType, Info.Plugin) );
BASS_StreamFree(Chan);
end;
// konec zjišťování
if not Radio_Playing then PlayURL := ''; // pokud nic nephřevámáme, tak nelze nahrávat
tbtnRecord.Enabled := not (StreamFormat.Format = '') and not StreamRecording; // můžem nahrávat ?
lblInfo2.Visible := StreamFormat.Format = '';
if pbBuffer.Max < RecordingBufferSize then pbBuffer.Max := RecordingBufferSize;
pbBuffer.Position := RecordingBufferSize;
if StreamRecording then
StatusBar.SimpleText := LNG('FORM Recording', 'Recording', 'Recording...')//(filesize: ' + FileSize( GetRecordTempFile ) +')'
else
StatusBar.SimpleText := '';
StreamInfo;
end;
procedure TfrmRecording.StreamInfo;
var
Info : BASS_RECORDINFO;
InfoFormat : WideString;
begin
if StreamFormat.Format = 'wav' then
begin
BASS_RecordGetInfo(Info);
case Info.formats of
WAVE_FORMAT_1M08 : InfoFormat := '11.025 kHz, Mono, 8-bit';
WAVE_FORMAT_1S08 : InfoFormat := '11.025 kHz, Stereo, 8-bit';
WAVE_FORMAT_1M16 : InfoFormat := '11.025 kHz, Mono, 16-bit';
WAVE_FORMAT_1S16 : InfoFormat := '11.025 kHz, Stereo, 16-bit';
WAVE_FORMAT_2M08 : InfoFormat := '22.05 kHz, Mono, 8-bit';
WAVE_FORMAT_2S08 : InfoFormat := '22.05 kHz, Stereo, 8-bit';
WAVE_FORMAT_2M16 : InfoFormat := '22.05 kHz, Mono, 16-bit';
WAVE_FORMAT_2S16 : InfoFormat := '22.05 kHz, Stereo, 16-bit';
WAVE_FORMAT_4M08 : InfoFormat := '44.1 kHz, Mono, 8-bit';
WAVE_FORMAT_4S08 : InfoFormat := '44.1 kHz, Stereo, 8-bit';
WAVE_FORMAT_4M16 : InfoFormat := '44.1 kHz, Mono, 16-bit';
WAVE_FORMAT_4S16 : InfoFormat := '44.1 kHz, Stereo, 16-bit';
end;
InfoFormat := StreamFormat.Name + '(' + InfoFormat + ')';
end
else
begin
InfoFormat := StreamFormat.Name;
end;
lblInfo.Caption := LNG('FORM Recording', 'Format', 'Format') + ': ' + InfoFormat;
end;
procedure TfrmRecording.tbtnPauseClick(Sender: TObject);
begin
// TButton(Sender).ShowHint := False;
StreamRecording := False;
QIPPlugin.RedrawSpecContact(UniqContactId);
EnableDisable;
// TButton(Sender).ShowHint := True;
end;
procedure TfrmRecording.tbtnRecordClick(Sender: TObject);
begin
// TButton(Sender).ShowHint := False;
FileStream := TFileStream.Create(GetRecordTempFile, fmCreate); // create the file
StreamRecording := True;
QIPPlugin.RedrawSpecContact(UniqContactId);
EnableDisable;
// TButton(Sender).ShowHint := True;
end;
procedure TfrmRecording.tbtnStopClick(Sender: TObject);
var
ID3v1 : Pointer;
INI : TIniFile;
FN : String;
begin
// TButton(Sender).ShowHint := False;
StreamRecording := False;
QIPPlugin.RedrawSpecContact(UniqContactId);
EnableDisable;
FBassPlayer.BASSPlayer_FileStreamFree;
INIGetProfileConfig(INI);
SaveDialog.InitialDir := UTF82WideString( INI.ReadString('Record', 'Dir', '') );
SaveDialog.Title := LNG('FORM Recording', 'SaveAudioFile', 'Save audio file');
SaveDialog.Filter := StreamFormat.Name + '|*.' + StreamFormat.Format + '|' + LNG('FORM Recording', 'AllFormats', 'All') + '|*.*';
SaveDialog.DefaultExt := StreamFormat.Format;
SaveDialog.FilterIndex := 1;
DateTimeToString(FN, 'yyyy-mm-dd_hh-nn-ss', Now);
SaveDialog.FileName := StringReplace(TStation(Stations.Objects[Radio_StationID]).Name, ' ', '_', [rfReplaceAll]) + '_' + FN;
if SaveDialog.Execute then
begin
CopyFile(PChar(GetRecordTempFile),PChar(SaveDialog.FileName),false);
(* { zápis do ID3 tagu }
ShowMessage('01');
InitID3v2Library(PluginDllPath);
ID3v1 := nil;
ShowMessage('02');
ID3v1_SetTitle(ID3v1, PAnsiChar('x'));
ShowMessage('03');
ID3v1_SetArtist(ID3v1, PAnsiChar('x'));
ID3v1_SetAlbum(ID3v1, PAnsiChar('x'));
ID3v1_SetYear(ID3v1, PAnsiChar(FN));
ID3v1_SetComment(ID3v1, PAnsiChar(TStation(Stations.Objects[Radio_StationID]).Name));
ID3v1_SetGenre(ID3v1, GenreToByte(TStation(Stations.Objects[Radio_StationID]).Genre));
ShowMessage('0x');
ID3v1_Save(ID3v1, PAnsiChar(SaveDialog.FileName));
{ID3v1.hlavicka := 'TAG';
StrLCopy(ID3v1.skladba, PChar(''), SizeOf(ID3v1.skladba));
StrLCopy(ID3v1.interpret, PChar(''), SizeOf(ID3v1.interpret));
StrLCopy(ID3v1.album, PChar(''), SizeOf(ID3v1.album));
StrLCopy(ID3v1.rok, PChar(FN), SizeOf(ID3v1.rok));
StrLCopy(ID3v1.komentar, PChar(TStation(Stations.Objects[Radio_StationID]).Name), SizeOf(ID3v1.komentar));
ID3v1.zanr := GenreToByte(TStation(Stations.Objects[Radio_StationID]).Genre);
WriteTag(SaveDialog.FileName, ID3v1); // nic to nezapíše? PROČ? }
FreeID3v2Library;
{ konec zápisu }*)
INI.WriteString('Record', 'Dir', WideString2UTF8( ExtractFileDir(SaveDialog.FileName)) );
end;
INI.Free;
DeleteFileIfExists(GetRecordTempFile);
// TButton(Sender).ShowHint := True;
end;
function GenreToByte(Genre: WideString): Byte;
// když není nelezen žánr, tak vrací 255
var
I: Integer;
begin
for I := 0 to TotalGenre do
begin
if Genre = ID3genre[I] then
begin
Result := I;
Break;
end;
Result := 255;
end;
end;
end.
|
unit URemoveGridLines;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
System.Math,FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, FMX.Grid,
FMX.Layouts, FMX.Edit;
procedure RemoveRows(strgrid : TStringGrid;StartRow,RemoveRows : integer);
implementation
procedure RemoveRows(strgrid : TStringGrid;StartRow,RemoveRows : integer);
var colindex,i,j: integer;
begin
if (strgrid.RowCount < 1 ) or ((StartRow + RemoveRows) > (strgrid.RowCount)) then exit;
j := StartRow;
for i := StartRow + RemoveRows to strgrid.RowCount -1 do
begin
for colindex := 1 to strgrid.ColumnCount -1 do
strgrid.cells[colindex,j] := strgrid.cells[colindex,j + RemoveRows];
Inc(j);
end;
strgrid.RowCount := strgrid.RowCount - RemoveRows;
end;
end.
|
{ GDAX/Coinbase-Pro client library
Copyright (c) 2018 mr-highball
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.
}
unit gdax.api.accounts;
{$i gdax.inc}
interface
uses
Classes, gdax.api.consts, gdax.api, gdax.api.types;
type
{ TGDAXAccountLedgerImpl }
TGDAXAccountLedgerImpl = class(TGDAXPagedApi,IGDAXAccountLedger)
strict private
FID: String;
FEntries: TLedgerEntryArray;
function GetAcctID: String;
function GetCount: Cardinal;
function GetEntries: TLedgerEntryArray;
function GetPaged: IGDAXPaged;
procedure SetAcctID(Const Value: String);
strict protected
function DoGet(Const AEndpoint: string; Const AHeaders: TStrings; out
Content: String; out Error: string): Boolean; override;
function DoLoadFromJSON(Const AJSON: string; out Error: string): Boolean;override;
function DoMove(Const ADirection: TGDAXPageDirection; out Error: String;
Const ALastBeforeID, ALastAfterID: Integer;
Const ALimit: TPageLimit=0): Boolean; override;
function GetEndpoint(Const AOperation: TRestOperation): string; override;
function DoGetSupportedOperations: TRestOperations; override;
public
property AcctID: String read GetAcctID write SetAcctID;
property Paged: IGDAXPaged read GetPaged;
property Entries: TLedgerEntryArray read GetEntries;
property Count: Cardinal read GetCount;
procedure ClearEntries;
end;
TGDAXAccountImpl = class(TGDAXRestApi,IGDAXAccount)
strict private
FID: String;
FCurrency: String;
FBalance: Extended;
FHolds: Extended;
FAvailable: Extended;
function GetAcctID: String;
procedure SetAcctID(Const AValue: String);
function GetCurrency: String;
procedure SetCurrency(Const AValue: String);
function GetBalance: Extended;
procedure SetBalance(Const AValue: Extended);
function GetHolds: Extended;
procedure SetHolds(Const AValue: Extended);
function GetAvailable: Extended;
procedure SetAvailable(Const AValue: Extended);
strict protected
function DoGetSupportedOperations: TRestOperations; override;
function GetEndpoint(Const AOperation: TRestOperation): string; override;
function DoLoadFromJSON(Const AJSON: string; out Error: string): Boolean;
override;
public
property AcctID: String read GetAcctID write SetAcctID;
property Currency: String read GetCurrency write SetCurrency;
/// <summary>
/// total funds in the account
/// </summary>
property Balance: Extended read GetBalance write SetBalance;
/// <summary>
/// funds on hold (not available for use)
/// </summary>
property Holds: Extended read GetHolds write SetHolds;
/// <summary>
/// funds available to withdraw* or trade
/// </summary>
property Available: Extended read GetAvailable write SetAvailable;
end;
{ TGDAXAccountsImpl }
TGDAXAccountsImpl = class(TGDAXRestApi,IGDAXAccounts)
strict private
FAccounts: TGDAXAccountList;
function GetAccounts: TGDAXAccountList;
strict protected
function DoGetSupportedOperations: TRestOperations; override;
function GetEndpoint(Const AOperation: TRestOperation): string; override;
function DoLoadFromJSON(Const AJSON: string;
out Error: string): Boolean;override;
public
property Accounts : TGDAXAccountList read GetAccounts;
constructor Create; override;
destructor Destroy; override;
end;
implementation
uses
SysUtils,
fpjson,
jsonparser;
{ TGDAXAccountImpl }
function TGDAXAccountImpl.DoGetSupportedOperations: TRestOperations;
begin
Result:=[roGet];
end;
function TGDAXAccountImpl.DoLoadFromJSON(Const AJSON: string;
out Error: string): Boolean;
var
LJSON:TJSONObject;
begin
Result := False;
//try and parse
LJSON := TJSONObject(GetJSON(AJSON));
try
if not Assigned(LJSON) then
begin
Error := E_BADJSON;
Exit;
end;
//extract id from json
if LJSON.Find('id') = nil then
begin
Error := Format(E_BADJSON_PROP, ['id']);
Exit;
end
else
FID := LJSON.Get('id');
//extract balance from json
if LJSON.Find('balance') = nil then
begin
Error := Format(E_BADJSON_PROP,['balance']);
Exit;
end
else
FBalance := StrToFloatDef(LJSON.Get('balance'),0);
//extract holds from json
if LJSON.Find('hold') = nil then
begin
Error := Format(E_BADJSON_PROP,['hold']);
Exit;
end
else
FHolds := StrToFloatDef(LJSON.Get('hold'),0);
//extract available from json
if LJSON.Find('available') = nil then
begin
Error := Format(E_BADJSON_PROP,['available']);
Exit;
end
else
FAvailable := StrToFloatDef(LJSON.Get('available'),0);
//extract currency from json
if LJSON.Find('currency') = nil then
begin
Error := Format(E_BADJSON_PROP,['currency']);
Exit;
end
else
FCurrency := LJSON.Get('currency');
Result := True;
finally
LJSON.Free;
end;
end;
function TGDAXAccountImpl.GetAcctID: String;
begin
Result := FID;
end;
function TGDAXAccountImpl.GetAvailable: Extended;
begin
Result := FAvailable;
end;
function TGDAXAccountImpl.GetBalance: Extended;
begin
Result := FBalance;
end;
function TGDAXAccountImpl.GetCurrency: String;
begin
Result := FCurrency;
end;
function TGDAXAccountImpl.GetEndpoint(Const AOperation: TRestOperation): string;
begin
Result:='';
if AOperation = roGet then
Result := Format(GDAX_END_API_ACCT,[FID]);
end;
function TGDAXAccountImpl.GetHolds: Extended;
begin
Result := FHolds;
end;
procedure TGDAXAccountImpl.SetAcctID(Const AValue: String);
begin
FID := AValue;
end;
procedure TGDAXAccountImpl.SetAvailable(Const AValue: Extended);
begin
FAvailable := AValue;
end;
procedure TGDAXAccountImpl.SetBalance(Const AValue: Extended);
begin
FBalance := AValue;
end;
procedure TGDAXAccountImpl.SetCurrency(Const AValue: String);
begin
FCurrency := AValue;
end;
procedure TGDAXAccountImpl.SetHolds(Const AValue: Extended);
begin
FHolds := AValue;
end;
{ TGDAXAccountsImpl }
constructor TGDAXAccountsImpl.Create;
begin
inherited;
FAccounts := TGDAXAccountList.Create;
end;
destructor TGDAXAccountsImpl.Destroy;
begin
FAccounts.Free;
inherited;
end;
function TGDAXAccountsImpl.DoGetSupportedOperations: TRestOperations;
begin
Result:=[roGet];
end;
function TGDAXAccountsImpl.DoLoadFromJSON(Const AJSON: string;
out Error: string): Boolean;
var
LJSON: TJSONArray;
I: Integer;
LAcct: IGDAXAccount;
begin
Result := False;
try
FAccounts.Clear;
LJSON := TJSONArray(GetJSON(AJSON));
if not Assigned(LJSON) then
raise Exception.Create(E_BADJSON);
try
//iterate items
for I := 0 to Pred(LJSON.Count) do
begin
LAcct := TGDAXAccountImpl.Create;
//if we can't load this via json, then terminate
if not LAcct.LoadFromJSON(
LJSON.Items[I].AsJSON,
Error
)
then
begin
Error := Format(E_BADJSON_PROP,['account index:'+IntToStr(I)]);
Exit;
end;
//otherwise we can add this to our list
FAccounts.Add(LAcct);
end;
Result := True;
finally
LJSON.Free;
end;
except on E: Exception do
Error := E.Message;
end;
end;
function TGDAXAccountsImpl.GetAccounts: TGDAXAccountList;
begin
Result := FAccounts;
end;
function TGDAXAccountsImpl.GetEndpoint(Const AOperation: TRestOperation): string;
begin
Result := GDAX_END_API_ACCTS;
end;
{ TGDAXAccountLedgerImpl }
function TGDAXAccountLedgerImpl.DoLoadFromJSON(Const AJSON: string;
out Error: string): Boolean;
var
I : Integer;
LJSON : TJSONArray;
LEntryJSON : String;
LEntry : TLedgerEntry;
begin
Result := False;
try
//clear entries on load
SetLength(FEntries,0);
LJSON := TJSONArray(GetJSON(AJSON));
if not Assigned(LJSON) then
raise Exception.Create(E_BADJSON);
try
//for all of the records returned, build a new ledger entry from json
for I := 0 to Pred(LJSON.Count) do
begin
SetLength(FEntries, Succ(Length(FEntries)));
LEntryJSON := LJSON.Items[I].AsJSON;
LEntry := TLedgerEntry.Create(LEntryJSON);
FEntries[High(FEntries)]:=LEntry;
end;
Result := True;
finally
LJSON.Free;
end;
except on E: Exception do
Error := E.Message;
end;
end;
function TGDAXAccountLedgerImpl.DoMove(Const ADirection: TGDAXPageDirection;
out Error: String; Const ALastBeforeID, ALastAfterID: Integer;
Const ALimit: TPageLimit): Boolean;
var
LEntries:TLedgerEntryArray;
I,J:Integer;
begin
//noting here in case someone runs across this (or I forget) but this method
//doesn't take into account possible duplicates being added to entries.
//a caller can request to move forward, which sets page identifiers, then
//request to move backwards from the last recorded spot (which result in
//re-adding entries), perhaps will change later to account for this, but
//as of now, not a big deal since caller can also specifically before and
//after specific id's
SetLength(LEntries,0);
if Length(FEntries)>0 then
LEntries := FEntries;
Result := inherited DoMove(ADirection, Error, ALastBeforeID, ALastAfterID,ALimit);
if not Result then
Exit;
//only if we have a local array that needs to be appended somewhere do we
//do this logic
if (Length(LEntries)>0) then
begin
//use length because we want the index "after" the highest entry
I := Length(LEntries);
SetLength(LEntries,Length(LEntries)+Length(FEntries));
if ADirection=pdBefore then
begin
if Length(FEntries)>0 then
begin
//slide old entries ahead of new entries
for J:=0 to High(LEntries) - I do
LEntries[I + J]:=LEntries[J];
//now move new entries to start
for J:=0 to High(FEntries) do
LEntries[J] := FEntries[J];
end;
//lastly, assign our merged array to private var
FEntries := LEntries;
end
else
begin
//move new entries to end and assign to private var
if Length(FEntries)>0 then
for J:=0 to High(FEntries) do
LEntries[I + J]:=FEntries[J];
FEntries := LEntries;
end;
end;
end;
function TGDAXAccountLedgerImpl.GetAcctID: String;
begin
Result := FID;
end;
function TGDAXAccountLedgerImpl.GetCount: Cardinal;
begin
Result := Length(FEntries);
end;
function TGDAXAccountLedgerImpl.GetEntries: TLedgerEntryArray;
begin
Result := FEntries;
end;
function TGDAXAccountLedgerImpl.GetPaged: IGDAXPaged;
begin
Result := Self as IGDAXPaged;
end;
function TGDAXAccountLedgerImpl.GetEndpoint(
Const AOperation: TRestOperation): string;
var
LMoving:String;
begin
Result:='';
//since this is a paged endpoint, we need to check for any move requests
//made by caller
LMoving := GetMovingParameters;
if not LMoving.IsEmpty then
LMoving:='?'+LMoving;
if AOperation=roGet then
Result := Format(GDAX_END_API_ACCT_HIST,[FID])+LMoving;
end;
function TGDAXAccountLedgerImpl.DoGetSupportedOperations: TRestOperations;
begin
Result:=[roGet];
end;
procedure TGDAXAccountLedgerImpl.ClearEntries;
begin
SetLength(FEntries,0);
end;
procedure TGDAXAccountLedgerImpl.SetAcctID(Const Value: String);
begin
FID := Value;
end;
function TGDAXAccountLedgerImpl.DoGet(Const AEndpoint: string;
Const AHeaders: TStrings; out Content: String; out Error: string): Boolean;
begin
if FID.IsEmpty then
begin
Error := Format(E_INVALID,['account id','a valid identifier']);
Exit;
end;
Result := inherited DoGet(AEndpoint, AHeaders, Content, Error);
end;
end.
|
unit ECC200procs;
{===============================================================================
DataMatrix Barcode standard ECC200.
(c) 2012 QBS Software Ltd
http://www.qbs.co.uk
================================================================================}
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, ECC200consts, dialogs;
var
nrow, ncol : integer;
barray : array of integer;
matrixsize : integer;
modulesize : integer;
_globalQZflag : boolean;
procedure MakeBitPlacementArray( matrixrows, matrixcols : integer);
procedure DrawFrame(x : integer; y : integer; acanvas : TCanvas);
procedure RandomBC(x : integer; y : integer; acanvas : TCanvas);
procedure DrawModule( x : integer; y : integer; acanvas : TCanvas);
procedure ECC200Code;
procedure PaintRandomBC(x , y , matrixrows : integer; destrect : TRect; quietzone : boolean; acanvas : TCanvas);
procedure DrawRandomBC(x , y , matrixrows : integer; destrect : TRect; acanvas : TCanvas);
procedure RenderBarcode( textdata : string; GS1 : Boolean ; FNCChar : char; xpos, ypos : integer; matrixrows : TMatrixsize; destrect : TRect; quietzone : boolean; acanvas : TCanvas);
procedure AscEncodeText( databits : TvarInt; dtext : string ; GS1 : Boolean ; FNCChar : char; maxindex : integer; var datalength : integer);
implementation
uses math, ECC200ReedSolomon;
procedure DrawModule( x : integer; y : integer; acanvas : TCanvas);
begin
acanvas.Rectangle(x, y,x+modulesize, y+modulesize);
end;
procedure DrawModulex( x : integer; y : integer; acanvas : TCanvas);
Var
Half : Integer;
begin
Half := modulesize div 2;
acanvas.Rectangle(x-Half, y-Half,x-Half+modulesize, y-Half+modulesize);
end;
procedure DrawFrame(x : integer; y : integer; acanvas : TCanvas);
var
k, n, savematrixsize : integer;
begin
aCanvas.Brush.Style := bsSolid;
aCanvas.Pen.Style := psSolid;
aCanvas.Brush.Color := clBlack;
aCanvas.Pen.Color := clBlack;
n := 0;
if matrixsize > 24 then n := 2;
for k := 0 to (matrixsize+1+n) do
begin
drawmodule( x + (k*modulesize),y, acanvas);
drawmodule( x,y - (k*modulesize), acanvas);
if ( k mod 2 ) =0 then
begin
drawmodule( x +(k*modulesize), y - ((matrixsize+1+n)*modulesize), acanvas);
drawmodule( x +(matrixsize+1+n)*modulesize, y - (k*modulesize), acanvas);
end;
end;
if matrixsize <= 24 then exit;
// put in aligment modules
savematrixsize := matrixsize;
matrixsize := (matrixsize div 2);
DrawFrame( x, y, acanvas);
DrawFrame( x + ((matrixsize+2)*modulesize), y, acanvas);
DrawFrame( x, y-((matrixsize+2)*modulesize), acanvas);
DrawFrame( x + ((matrixsize+2)*modulesize), y-((matrixsize+2)*modulesize), acanvas);
matrixsize := savematrixsize;
end;
procedure RandomBC(x : integer; y : integer; acanvas : TCanvas);
var
r : double;
row, col : integer;
begin
aCanvas.Brush.Style := bsSolid;
aCanvas.Pen.Style := psSolid;
aCanvas.Brush.Color := clBlack;
aCanvas.Pen.Color := clBlack;
for row := 1 to matrixsize do
for col := 1 to matrixsize do
begin
r := random;
if r < 0.5 then continue;
drawmodule( x + (row*modulesize),y - (col*modulesize), acanvas);
end;
end;
procedure PaintRandomBC(x , y , matrixrows : integer; destrect : TRect; quietzone : boolean; acanvas : TCanvas);
var
pixwid : integer;
StartY, Xoff : Integer;
begin
pixwid := destrect.Right-destrect.Left;
if pixwid > abs(destrect.Bottom-destrect.Top) then pixwid := abs(destrect.Bottom-destrect.Top);
modulesize := pixwid div ( matrixrows + 2 );
if modulesize < 2 then exit;
matrixsize := matrixrows;
StartY := (matrixrows + 1)* modulesize;
if quietzone then
begin
modulesize := pixwid div ( matrixrows + 4 );
xoff := modulesize;
end
else
begin
modulesize := pixwid div ( matrixrows + 2 );
xoff := 0;
end;
DrawFrame( x+xoff, StartY+y, acanvas);
RandomBC ( x+xoff, StartY+y, acanvas);
end;
function IsDigit( cc : char) : boolean;
begin
result := (cc>='0') and (cc<='9');
end;
procedure AscEncodeText( databits : TvarInt; dtext : string ; GS1:Boolean ; FNCChar : char; maxindex : integer; var datalength : integer);
var
tindex, i, dtlen : integer;
begin
dtlen := length(dtext);
i := 1;
tindex := 0;
while i <= dtlen do
begin
// In GS1 mode FNCChar will be encoded as FNC1 (232) code
if GS1 And (dtext[i]=FNCChar) Then
begin
databits[tindex] := ascFNC;
inc(tindex);
End
Else
// end GS1 support
if ord(dtext[i])<127 then
begin
if (i<dtlen) then
begin
if IsDigit(dtext[i]) and IsDigit(dtext[i+1]) then
begin
// combine digits into 1 byte
databits[tindex] := (ord(dtext[i])-ord('0') )*10 + ord(dtext[i+1])-ord('0') + 130;
inc(tindex);
if tindex = maxindex then break;
inc(i,2); // skipping
continue;
end;
end;
databits[tindex] := ord(dtext[i])+1;
inc(tindex);
end
else
begin
// chars 128-255 need a bump in front
if (maxindex-tindex)<2 then break; // no space for ascUpperShift+charcode
databits[tindex] := ascUpperShift;
inc(tindex);
databits[tindex] := ord(dtext[i])-127;
inc(tindex);
end;
if tindex = maxindex then break;
inc(i);
end;
// return the actual length
datalength := tindex;
end;
function GetBit16( inword : word; bitno : integer) : boolean;
begin
// assuming bit 0 = msb
result := ( (inword and $00FF) and ( 128 shr (bitno-1)) ) > 0;
end;
procedure DrawRandomBC(x , y , matrixrows : integer; destrect : TRect; acanvas : TCanvas);
var
pixwid : integer;
begin
pixwid := destrect.Right-destrect.Left;
if pixwid > abs(destrect.Bottom-destrect.Top) then pixwid := abs(destrect.Bottom-destrect.Top);
modulesize := pixwid div ( matrixrows + 2 );
if modulesize < 2 then exit;
matrixsize := matrixrows;
DrawFrame( x+modulesize, y+pixwid-modulesize, acanvas);
RandomBC( x+modulesize, y+pixwid-modulesize, acanvas);
end;
procedure BlankBC( xpos, ypos : integer; quietzone : boolean; nregions : integer; acanvas : TCanvas);
var
doff : integer;
nalign : integer;
begin
aCanvas.Brush.Style := bsSolid;
aCanvas.Pen.Style := psSolid;
aCanvas.Brush.Color := clWhite;
aCanvas.Pen.Color := clWhite;
nalign := 0;
if nregions = 4 then nalign := 2* modulesize;
if quietzone then
begin
doff := (matrixsize + 2 ) * modulesize;
acanvas.Rectangle( xpos-modulesize, ypos+(modulesize*2), xpos + doff + modulesize + nalign, ypos - doff-nalign );
end
else
begin
doff := (matrixsize + 1 ) * modulesize;
acanvas.Rectangle( xpos, ypos + modulesize, xpos + doff + modulesize + nalign, ypos - doff - nalign );
end;
end;
procedure RenderBarcode( textdata : string; GS1 : Boolean ; FNCChar : char; xpos, ypos : integer; matrixrows : TMatrixsize; destrect : TRect; quietzone : boolean; acanvas : TCanvas);
var
datastr : string;
dmbits : TVarInt;
i, j, z, k : integer;
nrow, ncol : integer;
databytes, eccbytes : integer;
drow, dcol, datalen{, blocknum} : integer;
pixwid, eccregions, {regionsize,} TempPad : integer;
StartY : Integer;
begin
matrixsize := PatternInfo[matrixrows].matrixdim;
databytes := PatternInfo[matrixrows].databytes;
eccbytes := PatternInfo[matrixrows].ECCbytes;
eccregions := PatternInfo[matrixrows].regions;
//regionsize := PatternInfo[matrixrows].regionsize;
nrow := matrixsize;
ncol := matrixsize;
if databytes = 0 then
begin
showmessage( 'Size not supported');
exit;
end;
pixwid := destrect.Right-destrect.Left;
if pixwid > abs(destrect.Bottom-destrect.Top) then pixwid := abs(destrect.Bottom-destrect.Top);
if quietzone then
begin
if eccregions = 4 then
modulesize := pixwid div ( matrixsize + 6 )
else
modulesize := pixwid div ( matrixsize + 4 )
end
else
begin
if eccregions = 4 then
modulesize := pixwid div ( matrixsize + 4 )
else
modulesize := pixwid div ( matrixsize + 2 );
end;
if modulesize < 2 then exit;
if quietzone then
begin
if eccregions = 4 then
StartY := (matrixsize + 4)* modulesize
else
StartY := (matrixsize + 2)* modulesize;
BlankBC( xpos+modulesize, ypos + StartY, quietzone, eccregions, acanvas);
DrawFrame( xpos+modulesize, ypos + StartY, acanvas);
end
else
begin
if eccregions = 4 then
StartY := (matrixsize + 2)* modulesize
else
StartY := (matrixsize + 1)* modulesize;
BlankBC( xpos, ypos + StartY,quietzone, eccregions, acanvas);
DrawFrame( xpos, ypos + StartY, acanvas);
end;
datastr := Textdata;
if trim(datastr) = '' then exit;
setlength(dmbits,databytes+eccbytes+1);
datalen := length(datastr); // overwritten in AscEncodeText
AscEncodeText( dmbits, datastr, GS1, FNCChar, databytes, datalen);
// pad databytes // Bruno
for i := (datalen) to (databytes-1) do
Begin
if i=DataLen Then
Begin
dmbits[i] := ascPad;
End Else
Begin
// From second pad, it must be 253 state randomized
TempPad := ascPad + ( ( 149 * (i+1) ) mod 253 ) + 1 ;
If TempPad<=254 then
dmbits[i] := TempPad
Else
dmbits[i] := TempPad-254
End;
End;
// puts eecbytes into dmbits
ReedSolomonD( dmbits, databytes, eccbytes, 256, 301);
dmbits[High(dmbits)]:=255;
// make interleaved blocks
{$ifdef INTERLEAVE}
if blocknum = 2 then
begin
setlength(dmbitscopy,databytes+eccbytes+1);
for i := 0 to databytes+eccbytes-1 do
begin
if (i mod 2) = 0 then
dmbitscopy[i div 2] := dmbits[i]
else
dmbitscopy[ ((databytes+eccbytes) div 2) + (i div 2)] := dmbits[i]
end;
for i := 0 to databytes+eccbytes-1 do dmbits[i] := dmbitscopy[i];
end;
{$endif}
// get a bit placement array in barray
MakeBitPlacementArray(nrow,ncol);
aCanvas.Brush.Color := clBlack;
aCanvas.Pen.Color := clBlack;
// make pattern by scanning placement array and extracting indicated bits
for i := 0 to nrow-1 do
begin
for j := 0 to ncol-1 do
begin
drow := j + 1;
dcol := ncol - (i + 1) +1;
if matrixsize > 24 then
begin
if drow > (ncol div 2) then inc(drow, 2);
if dcol > (ncol div 2) then inc(dcol, 2);
end;
z := barray[i*ncol+j];
k := (z div 10)-1;
if (k<0) or (k>high(dmbits)) then
continue;
if getBit16( dmbits[k], z mod 10 ) then
begin
if quietzone then inc(drow);
drawmodule( xpos + ( drow*modulesize), ypos + StartY - ( dcol*modulesize), aCanvas);
end;
end;
end;
end;
//================================= begin bit placement code ==================
procedure module( row : integer; col : integer; chr : integer; bit : integer);
begin
if (row < 0) then
begin
row := row + nrow;
col := col + 4 - ((nrow+4) mod 8);
end;
if (col < 0) then
begin
col := col + ncol;
row := row + 4 - ((ncol+4) mod 8);
end;
barray[row*ncol+col] := 10*chr + bit;
end;
procedure utah(row : integer; col : integer; chr : integer);
begin
module(row-2,col-2,chr,1);
module(row-2,col-1,chr,2);
module(row-1,col-2,chr,3);
module(row-1,col-1,chr,4);
module(row-1,col,chr,5);
module(row,col-2,chr,6);
module(row,col-1,chr,7);
module(row,col,chr,8);
end;
procedure corner1( chr : integer);
begin
module(nrow-1,0,chr,1);
module(nrow-1,1,chr,2);
module(nrow-1,2,chr,3);
module(0,ncol-2,chr,4);
module(0,ncol-1,chr,5);
module(1,ncol-1,chr,6);
module(2,ncol-1,chr,7);
module(3,ncol-1,chr,8);
end;
procedure corner2( chr : integer);
begin
module(nrow-3,0,chr,1);
module(nrow-2,0,chr,2);
module(nrow-1,0,chr,3);
module(0,ncol-4,chr,4);
module(0,ncol-3,chr,5);
module(0,ncol-2,chr,6);
module(0,ncol-1,chr,7);
module(1,ncol-1,chr,8);
end;
procedure corner3( chr : integer);
begin
module(nrow-3,0,chr,1);
module(nrow-2,0,chr,2);
module(nrow-1,0,chr,3);
module(0,ncol-2,chr,4);
module(0,ncol-1,chr,5);
module(1,ncol-1,chr,6);
module(2,ncol-1,chr,7);
module(3,ncol-1,chr,8);
end;
procedure corner4( chr : integer);
begin
module(nrow-1,0,chr,1);
module(nrow-1,ncol-1,chr,2);
module(0,ncol-3,chr,3);
module(0,ncol-2,chr,4);
module(0,ncol-1,chr,5);
module(1,ncol-3,chr,6);
module(1,ncol-2,chr,7);
module(1,ncol-1,chr,8);
end;
procedure ECC200Code;
var
row, col, chr : integer;
begin
// First, fill the barray[] with invalid entries
for row := 0 to nrow-1 do
for col := 0 to ncol-1 do
barray[row*ncol+col] := 0;
// Starting in the correct location for character #1, bit 8,...
chr := 1; row := 4; col := 0;
// main loop
repeat
// repeatedly first check for one of the special corner cases, then... */
if ((row = nrow) and (col = 0)) then
begin
corner1(chr);
inc(chr);
end;
if ((row = (nrow-2)) and (col = 0) and ((ncol mod 4)<>0)) then
begin
corner2(chr);
inc(chr);
end;
if ((row = (nrow-2)) and (col = 0) and ((ncol mod 8) = 4)) then
begin
corner3(chr);
inc(chr);
end;
if ((row = (nrow+4)) and (col = 2) and ((ncol mod 8)=0)) then
begin
corner4(chr);
inc(chr);
end;
// sweep upward diagonally, inserting successive characters,... */
repeat
if ((row < nrow) and (col >= 0) and (barray[row*ncol+col]=0)) then
begin
utah(row,col,chr);
inc(chr);
end;
row := row - 2; col := col + 2;
until not((row >= 0) and (col < ncol));
inc(row, 1); inc(col,3);
// & then sweep downward diagonally, inserting successive characters,... */
repeat
if ((row >= 0) and (col < ncol) and (barray[row*ncol+col]=0)) then
begin
utah(row,col,chr);
inc(chr);
end;
row := row + 2; col := col - 2;
until not ( ((row < nrow) and (col >= 0)) );
inc(row, 3); inc(col, 1);
// ... until the entire array is scanned */
until ( not ((row < nrow) or (col < ncol)));
// Lastly, if the lower righthand corner is untouched, fill in fixed pattern */
if (barray[nrow*ncol-1]=0) then
begin
barray[nrow*ncol-1] := chr*10 + 1;
barray[nrow*ncol-ncol-2] := chr*10 + 1;
end;
end;
procedure MakeBitPlacementArray( matrixrows, matrixcols : integer);
begin
nrow := matrixrows;
ncol := matrixcols;
setlength( barray, nrow*ncol);
ECC200Code;
end;
end.
|
// Filename : Hashtable.pas
// Version : 1.1 (Delphi)
// Date : July 4, 2003
// Author : Jeff Rafter
// Details : http://xml.defined.net/SAX/aelfred2
// License : Please read License.txt
unit Hashtable;
// !! This is meant to be upgraded !! -- I know it is awful.
interface
{$WEAKPACKAGEUNIT ON}
uses Classes;
type
TWideStringDynarray = array of WideString;
TPointerDynarray = array of Pointer;
THashtable = class(TObject)
private
Fkeys : TWideStringDynarray;
Felements : TPointerDynarray;
FwideStringElements : TWideStringDynarray;
Flength : Integer;
FwideStringTable : Boolean;
function indexOf(const a : TWideStringDynarray; const s : WideString) : Integer;
procedure ensureCapacity(const n : Integer);
function getCount: Integer;
public
constructor Create(); overload;
constructor Create(const size : Integer); overload;
constructor Create(const wideStringTable : boolean); overload;
destructor Destroy(); override;
function getKeys() : TWideStringDynarray;
function getElements() : TPointerDynarray;
function getWideStringElements() : TWideStringDynarray;
function getLength() : Integer;
procedure put(const key : WideString; const element : Pointer);
function get(const key : WideString) : Pointer;
procedure putWideString(const key : WideString; const element : WideString);
function getWideString(const key : WideString) : WideString;
function containsKey(const key : WideString) : Boolean;
function has(const key : WideString) : Boolean;
procedure clear();
property Count : Integer read getCount;
end;
implementation
function THashtable.getCount: Integer;
begin
Result:= Length(getKeys());
end;
{ THashtable }
constructor THashtable.Create;
begin
inherited Create();
Flength:= 0;
FwideStringTable:= false;
end;
constructor THashtable.Create(const size: Integer);
begin
inherited Create();
Flength:= 0;
FwideStringTable:= false;
ensureCapacity(size);
end;
constructor THashtable.Create(const wideStringTable: boolean);
begin
inherited Create();
Flength:= 0;
FwideStringTable:= wideStringTable;
end;
destructor THashtable.Destroy;
begin
inherited;
end;
function THashtable.getElements: TPointerDynarray;
begin
Result:= Felements;
end;
function THashtable.getKeys: TWideStringDynarray;
begin
Result:= Fkeys;
end;
procedure THashtable.putWideString(const key, element: WideString);
var index : Integer;
begin
index:= indexOf(Fkeys, key);
if (index <> -1) then
begin
FwideStringElements[index]:= element;
end else
begin
Inc(Flength);
ensureCapacity(Flength);
Fkeys[Flength-1]:= key;
FwideStringElements[Flength-1]:= element;
end;
end;
procedure THashtable.put(const key : WideString; const element : Pointer);
var index : Integer;
begin
index:= indexOf(Fkeys, key);
if (index <> -1) then
begin
Felements[index]:= element;
end else
begin
Inc(Flength);
ensureCapacity(Flength);
Fkeys[Flength-1]:= key;
Felements[Flength-1]:= element;
end;
end;
function THashtable.getWideString(const key: WideString): WideString;
var index : Integer;
begin
index:= indexOf(Fkeys, key);
if (index <> -1) then
Result:= FwideStringElements[index]
else
Result:= '';
end;
function THashtable.get(const key: WideString): Pointer;
var index : Integer;
begin
index:= indexOf(Fkeys, key);
if (index <> -1) then
Result:= Felements[index]
else
Result:= nil;
end;
function THashtable.indexOf(const a : TWideStringDynarray;
const s: WideString): Integer;
var I : Integer;
begin
if (a = nil) then
begin
Result:= -1;
Exit;
end;
for I:= 0 to Length(a)-1 do
begin
if (a[I] = s) then
begin
Result:= I;
Exit;
end;
end;
Result:= -1;
end;
procedure THashtable.ensureCapacity(const n: Integer);
var max : Integer;
begin
if ((n > 0) and (Length(Fkeys)=0)) then
begin
SetLength(Fkeys, n);
SetLength(FwideStringElements, n);
SetLength(Felements, n);
end;
max:= Length(Fkeys);
if (max >= n) then Exit;
while (max < n) do
max:= max * 2;
SetLength(Fkeys, max);
SetLength(FwideStringElements, max);
SetLength(Felements, max);
end;
function THashtable.containsKey(const key: WideString): Boolean;
begin
Result:= indexOf(Fkeys, key) <> -1;
end;
function THashtable.getLength: Integer;
begin
Result:= Flength;
end;
function THashtable.getWideStringElements: TWideStringDynarray;
begin
Result:= FwideStringElements;
end;
procedure THashtable.clear;
begin
Flength:= 0;
SetLength(Fkeys, 0);
SetLength(FwideStringElements, 0);
SetLength(Felements, 0);
end;
function THashtable.has(const key: WideString): Boolean;
begin
Result:= containsKey(key);
end;
end.
|
unit DelphiTwain_FMX;
{$I DelphiTwain.inc}
interface
uses
SysUtils, Classes, DelphiTwain, Twain, Messages, Windows, FMX.Types, UITypes,
FMX.Forms
{$IFDEF DELPHI_XE5_UP}, FMX.Graphics{$ENDIF}
;
type
TOnTwainAcquire = procedure(Sender: TObject; const Index: Integer;
Image: TBitmap; var Cancel: Boolean) of object;
TOnAcquireProgress = procedure(Sender: TObject; const Index: Integer;
const Current, Total: Integer) of object;
TDelphiTwain = class(TCustomDelphiTwain)
private
fMessagesTimer: TTimer;
procedure DoMessagesTimer(Sender: TObject);
procedure WndProc(var Message: TMessage);
private
fOnTwainAcquire: TOnTwainAcquire;
fOnAcquireProgress: TOnAcquireProgress;
protected
procedure DoCreate; override;
procedure DoDestroy; override;
procedure MessageTimer_Enable; override;
procedure MessageTimer_Disable; override;
function CustomSelectSource: Integer; override;
function CustomGetParentWindow: TW_HANDLE; override;
procedure DoTwainAcquire(Sender: TObject; const Index: Integer; Image:
HBitmap; var Cancel: Boolean); override;
procedure DoAcquireProgress(Sender: TObject; const Index: Integer;
const Image: HBitmap; const Current, Total: Integer); override;
public
constructor Create; override;
destructor Destroy; override;
public
{Image acquired}
property OnTwainAcquire: TOnTwainAcquire read fOnTwainAcquire
write fOnTwainAcquire;
{Acquire progress, for memory transfers}
property OnAcquireProgress: TOnAcquireProgress read fOnAcquireProgress
write fOnAcquireProgress;
end;
implementation
{ TDelphiTwain }
uses uFormSelectSource_FMX;
function ColorToAlpha(const aColor: Cardinal): TAlphaColor; inline;
begin
Result := $FF000000 or (($FF0000 and aColor) shr 16) or (($00FF00 and aColor)) or (($0000FF and aColor) shl 16);
end;
procedure HBitmapToTBitmap(aHBitmap: HBitmap; aFMXBitmap: TBitmap);
var
xWinBM: Windows.Bitmap;
xDC: HDC;
X, Y: Integer;
{$IFDEF DELPHI_XE3_UP}
xBMData: TBitmapData;
{$ENDIF}
begin
GetObject(aHBitmap, SizeOf(xWinBM), @xWinBM);
aFMXBitmap.Width := xWinBM.bmWidth;
aFMXBitmap.Height := xWinBM.bmHeight;
{$IFDEF DELPHI_XE3_UP}
aFMXBitmap.Map(TMapAccess.maWrite, xBMData);
{$ENDIF}
xDC := CreateCompatibleDC(0);
try
SelectObject(xDC, aHBitmap);
for X := 0 to aFMXBitmap.Width-1 do
for Y := 0 to aFMXBitmap.Height-1 do begin
{$IFDEF DELPHI_XE3_UP}
xBMData.SetPixel(X, Y, ColorToAlpha(GetPixel(xDC, X, Y)));
{$ELSE}
aFMXBitmap.StartLine[X + (Y * aFMXBitmap.Width)] := ColorToAlpha(GetPixel(xDC, X, Y));//slow, but sorry...
{$ENDIF}
end;
finally
ReleaseDC(0, xDC);
{$IFDEF DELPHI_XE3_UP}
aFMXBitmap.UnMap(xBMData);
{$ELSE}
aFMXBitmap.UpdateHandles;
aFMXBitmap.BitmapChanged;
{$ENDIF}
end;
end;
constructor TDelphiTwain.Create;
begin
inherited Create;
fMessagesTimer := TTimer.Create(nil);
fMessagesTimer.Enabled := False;
fMessagesTimer.Interval := 100;
fMessagesTimer.OnTimer := DoMessagesTimer;
end;
function TDelphiTwain.CustomGetParentWindow: TW_HANDLE;
begin
Result := 0;
end;
function TDelphiTwain.CustomSelectSource: Integer;
var
xForm: TFormSelectSource;
I: Integer;
begin
Result := -1;
if SourceCount = 0 then begin
Exit;
end;
xForm := TFormSelectSource.CreateNew(nil);
try
for I := 0 to SourceCount-1 do
xForm.LBSources.Items.Add(Source[I].ProductName);
xForm.LBSources.ItemIndex := 0;
if (SelectedSourceIndex >= 0) and (SelectedSourceIndex < xForm.LBSources.Items.Count) then
xForm.LBSources.ItemIndex := SelectedSourceIndex;
if xForm.ShowModal = mrOK then begin
Result := xForm.LBSources.ItemIndex;
end else begin
Result := -1;
end;
finally
xForm.Free;
end;
end;
destructor TDelphiTwain.Destroy;
begin
FreeAndNil(fMessagesTimer);
inherited;
end;
procedure TDelphiTwain.DoAcquireProgress(Sender: TObject; const Index: Integer;
const Image: HBitmap; const Current, Total: Integer);
begin
if Assigned(fOnAcquireProgress) then
fOnAcquireProgress(Self, Index, Current, Total);
end;
procedure TDelphiTwain.DoMessagesTimer(Sender: TObject);
begin
//MUST BE HERE SO THAT TWAIN RECEIVES MESSAGES
if VirtualWindow > 0 then begin
SendMessage(VirtualWindow, WM_USER, 0, 0);
end;
end;
procedure TDelphiTwain.DoTwainAcquire(Sender: TObject; const Index: Integer;
Image: HBitmap; var Cancel: Boolean);
var
xBmp: TBitmap;
begin
if Assigned(OnTwainAcquire) then
begin
xBmp := TBitmap.Create(0, 0);
try
HBitmapToTBitmap(Image, xBmp);
fOnTwainAcquire(Sender, Index, xBmp, Cancel);
finally
xBmp.Free;
end;
end;
end;
procedure TDelphiTwain.MessageTimer_Disable;
begin
if Assigned(fMessagesTimer) then
fMessagesTimer.Enabled := False;
end;
procedure TDelphiTwain.MessageTimer_Enable;
begin
if Assigned(fMessagesTimer) then
fMessagesTimer.Enabled := True;
end;
procedure TDelphiTwain.DoCreate;
begin
inherited;
fVirtualWindow := Classes.AllocateHWnd(WndProc);
end;
procedure TDelphiTwain.DoDestroy;
begin
DestroyWindow(VirtualWindow);
inherited;
end;
procedure TDelphiTwain.WndProc(var Message: TMessage);
var
i : Integer;
xMsg : TMsg;
begin
//WndProc := False;
with Message do begin
{Tests for the message}
{Try to obtain the current object pointer}
if Assigned(Self) then
{If there are sources loaded, we need to verify}
{this message}
if (Self.SourcesLoaded > 0) then
begin
{Convert parameters to a TMsg}
xMsg := MakeMsg(Handle, Msg, wParam, lParam);//MakeMsg(Handle, Msg, wParam, lParam);
{Tell about this message}
FOR i := 0 TO Self.SourceCount - 1 DO
if ((Self.Source[i].Loaded) and (Self.Source[i].Enabled)) then
if Self.Source[i].ProcessMessage(xMsg) then
begin
{Case this was a message from the source, there is}
{no need for the default procedure to process}
//Result := 0;
//WndProc := True;
Exit;
end;
end; {if (Twain.SourcesLoaded > 0)}
end;
end;
end.
|
{ *******************************************************************************
Copyright (c) 2004-2010 by Edyard Tolmachev
IMadering project
http://imadering.com
ICQ: 118648
E-mail: imadering@mail.ru
******************************************************************************* }
unit TrafficUnit;
interface
{$REGION 'Uses'}
uses
Windows,
Messages,
SysUtils,
Variants,
Classes,
Graphics,
Controls,
Forms,
Dialogs,
StdCtrls,
Buttons;
type
TTrafficForm = class(TForm)
TrafGroupBox: TGroupBox;
ResetCurTrafButton: TButton;
ResetAllTrafButton: TButton;
CurTrafEdit: TEdit;
AllTrafEdit: TEdit;
CurTrafLabel: TLabel;
AllTrafLabel: TLabel;
CloseBitBtn: TBitBtn;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure CloseBitBtnClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure ResetCurTrafButtonClick(Sender: TObject);
procedure ResetAllTrafButtonClick(Sender: TObject);
procedure FormDblClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
procedure TranslateForm;
end;
{$ENDREGION}
var
TrafficForm: TTrafficForm;
implementation
{$R *.dfm}
{$REGION 'MyUses'}
uses
MainUnit,
VarsUnit,
UtilsUnit;
{$ENDREGION}
{$REGION 'TranslateForm'}
procedure TTrafficForm.TranslateForm;
begin
// Создаём шаблон для перевода
// CreateLang(Self);
// Применяем язык
SetLang(Self);
// Другое
CloseBitBtn.Caption := Lang_Vars[8].L_S;
ResetAllTrafButton.Caption := ResetCurTrafButton.Caption;
end;
{$ENDREGION}
{$REGION 'Reset'}
procedure TTrafficForm.ResetCurTrafButtonClick(Sender: TObject);
begin
// Обнуляем текущий трафик
V_TrafSend := 0;
V_TrafRecev := 0;
V_SesDataTraf := Now;
// Показываем сколько трафика передано за эту сессию
CurTrafEdit.Text := FloatToStrF(V_TrafRecev / 1000, FfFixed, 18, 3) + ' KB | ' + FloatToStrF(V_TrafSend / 1000, FfFixed, 18, 3) + ' KB | ' + DateTimeToStr(V_SesDataTraf);
end;
procedure TTrafficForm.ResetAllTrafButtonClick(Sender: TObject);
begin
// Обнуляем общий трафик
V_AllTrafSend := 0;
V_AllTrafRecev := 0;
V_AllSesDataTraf := DateTimeToStr(Now);
// Показываем сколько трафика передано всего
AllTrafEdit.Text := FloatToStrF(V_AllTrafRecev / 1000000, FfFixed, 18, 3) + ' MB | ' + FloatToStrF(V_AllTrafSend / 1000000, FfFixed, 18, 3) + ' MB | ' + V_AllSesDataTraf;
end;
{$ENDREGION}
{$REGION 'Other'}
procedure TTrafficForm.CloseBitBtnClick(Sender: TObject);
begin
// Закрываем окно
Close;
end;
procedure TTrafficForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
// Указываем что форма должна уничтожиться после закрытия
Action := CaFree;
TrafficForm := nil;
end;
procedure TTrafficForm.FormDblClick(Sender: TObject);
begin
// Устанавливаем перевод
TranslateForm;
end;
{$ENDREGION}
{$REGION 'FormCreate'}
procedure TTrafficForm.FormCreate(Sender: TObject);
begin
// Переводим форму на язык
TranslateForm;
// Присваиваем иконку окну и кнопке
MainForm.AllImageList.GetIcon(226, Icon);
MainForm.AllImageList.GetBitmap(3, CloseBitBtn.Glyph);
// Помещаем кнопку формы в таскбар и делаем независимой
SetWindowLong(Handle, GWL_HWNDPARENT, 0);
SetWindowLong(Handle, GWL_EXSTYLE, GetWindowLong(Handle, GWL_EXSTYLE) or WS_EX_APPWINDOW);
end;
{$ENDREGION}
end.
|
unit D_CorrectExportFolder;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, RBtnDlg, StdCtrls, Buttons, ExtCtrls, vtCtrls, vtRadioButton,
vtLabel;
type
TTCorrectExportFolder = class(TRBtnDlg)
btnSelectDir: TSpeedButton;
vtLabel1: TvtLabel;
rbChangeFolder: TvtRadioButton;
rbCancel: TvtRadioButton;
edtFolder: TVEdit;
procedure btnSelectDirClick(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure rbCancelClick(Sender: TObject);
private
{ Private declarations }
procedure CheckPathWritable(const aPath: AnsiString);
public
{ Public declarations }
function Execute(var theFolder: AnsiString): Boolean;
end;
var
TCorrectExportFolder: TTCorrectExportFolder;
implementation
{$R *.dfm}
uses
D_SelectDir, l3FileUtils, l3IniFile;
{ TTCorrectExportFolder }
function TTCorrectExportFolder.Execute(var theFolder: AnsiString): Boolean;
var
l_History: TStringList;
l_Index: Integer;
begin
edtFolder.Text := theFolder;
Result := (ShowModal = mrOk) and rbChangeFolder.Checked;
if Result then
begin
theFolder := Trim(edtFolder.Text);
l_History := TStringList.Create;
try
UserConfig.Section := 'ExportPathHistory';
UserConfig.ReadParamList('PathHistory', l_History, 10);
l_Index := l_History.IndexOf(theFolder);
if l_Index = -1 then
l_History.Insert(0, theFolder)
else
l_History.Move(l_Index, 0);
UserConfig.Section := 'Export';
UserConfig.WriteParamStr ('ExpDir', theFolder);
UserConfig.Section := 'ExportPathHistory';
UserConfig.WriteParamList('PathHistory', l_History, 10);
finally
FreeAndNil(l_History);
end;
end;
end;
procedure TTCorrectExportFolder.btnSelectDirClick(Sender: TObject);
var
l_Dlg: TarDirSelectDlg;
begin
l_Dlg := TarDirSelectDlg.Create(Self);
try
l_Dlg.Path := Trim(edtFolder.Text);
if l_Dlg.ShowModal = mrOK then
edtFolder.Text := l_Dlg.Path;
finally
FreeAndNil(l_Dlg);
end;
end;
procedure TTCorrectExportFolder.FormCloseQuery(Sender: TObject;
var CanClose: Boolean);
begin
if ModalResult = mrOk then
try
CheckPathWritable(Trim(edtFolder.Text));
except
ModalResult := mrNone;
edtFolder.SetFocus;
CanClose := False;
raise;
end;
end;
procedure TTCorrectExportFolder.CheckPathWritable(const aPath: AnsiString);
begin
if not l3CheckPathWritable(aPath) then
raise Exception.Create('Невозможно запсать в указанную папку');
end;
procedure TTCorrectExportFolder.rbCancelClick(Sender: TObject);
begin
inherited;
edtFolder.Enabled := rbChangeFolder.Checked;
btnSelectDir.Enabled := edtFolder.Enabled;
end;
end.
|
{===============================================================================
CRC32 Calculation
©František Milt 2013-11-22
Version 1.3.1
===============================================================================}
unit CRC32;
interface
uses
Classes;
type
TCRC32 = LongWord;
PCRC32 = ^TCRC32;
const
InitialCRC32: TCRC32 = $00000000;
Function CRC32ToStr(const CRC32: TCRC32): String;
Function StrToCRC32(const Str: String): TCRC32;
Function BufferCRC32(const CRC32: TCRC32; const Buffer; Size: Integer): TCRC32; register;
Function StringCRC32(const Text: AnsiString): TCRC32; overload;
Function StringCRC32(const Text: WideString): TCRC32; overload;
Function FileCRC32(const FileName: String): TCRC32;
Function StreamCRC32(const InputStream: TStream): TCRC32;
implementation
{.$DEFINE LargeBuffers}
{.$DEFINE UseStringStream}
uses
SysUtils;
const
{$IFDEF LargeBuffers}
cBufferSize = $100000; // 1MiB buffer
{$ELSE}
cBufferSize = 4096; // 4KiB buffer
{$ENDIF}
CRCTable: Array[Byte] of TCRC32 = (
$00000000, $77073096, $EE0E612C, $990951BA, $076DC419, $706AF48F, $E963A535,
$9E6495A3, $0EDB8832, $79DCB8A4, $E0D5E91E, $97D2D988, $09B64C2B, $7EB17CBD,
$E7B82D07, $90BF1D91, $1DB71064, $6AB020F2, $F3B97148, $84BE41DE, $1ADAD47D,
$6DDDE4EB, $F4D4B551, $83D385C7, $136C9856, $646BA8C0, $FD62F97A, $8A65C9EC,
$14015C4F, $63066CD9, $FA0F3D63, $8D080DF5, $3B6E20C8, $4C69105E, $D56041E4,
$A2677172, $3C03E4D1, $4B04D447, $D20D85FD, $A50AB56B, $35B5A8FA, $42B2986C,
$DBBBC9D6, $ACBCF940, $32D86CE3, $45DF5C75, $DCD60DCF, $ABD13D59, $26D930AC,
$51DE003A, $C8D75180, $BFD06116, $21B4F4B5, $56B3C423, $CFBA9599, $B8BDA50F,
$2802B89E, $5F058808, $C60CD9B2, $B10BE924, $2F6F7C87, $58684C11, $C1611DAB,
$B6662D3D, $76DC4190, $01DB7106, $98D220BC, $EFD5102A, $71B18589, $06B6B51F,
$9FBFE4A5, $E8B8D433, $7807C9A2, $0F00F934, $9609A88E, $E10E9818, $7F6A0DBB,
$086D3D2D, $91646C97, $E6635C01, $6B6B51F4, $1C6C6162, $856530D8, $F262004E,
$6C0695ED, $1B01A57B, $8208F4C1, $F50FC457, $65B0D9C6, $12B7E950, $8BBEB8EA,
$FCB9887C, $62DD1DDF, $15DA2D49, $8CD37CF3, $FBD44C65, $4DB26158, $3AB551CE,
$A3BC0074, $D4BB30E2, $4ADFA541, $3DD895D7, $A4D1C46D, $D3D6F4FB, $4369E96A,
$346ED9FC, $AD678846, $DA60B8D0, $44042D73, $33031DE5, $AA0A4C5F, $DD0D7CC9,
$5005713C, $270241AA, $BE0B1010, $C90C2086, $5768B525, $206F85B3, $B966D409,
$CE61E49F, $5EDEF90E, $29D9C998, $B0D09822, $C7D7A8B4, $59B33D17, $2EB40D81,
$B7BD5C3B, $C0BA6CAD, $EDB88320, $9ABFB3B6, $03B6E20C, $74B1D29A, $EAD54739,
$9DD277AF, $04DB2615, $73DC1683, $E3630B12, $94643B84, $0D6D6A3E, $7A6A5AA8,
$E40ECF0B, $9309FF9D, $0A00AE27, $7D079EB1, $F00F9344, $8708A3D2, $1E01F268,
$6906C2FE, $F762575D, $806567CB, $196C3671, $6E6B06E7, $FED41B76, $89D32BE0,
$10DA7A5A, $67DD4ACC, $F9B9DF6F, $8EBEEFF9, $17B7BE43, $60B08ED5, $D6D6A3E8,
$A1D1937E, $38D8C2C4, $4FDFF252, $D1BB67F1, $A6BC5767, $3FB506DD, $48B2364B,
$D80D2BDA, $AF0A1B4C, $36034AF6, $41047A60, $DF60EFC3, $A867DF55, $316E8EEF,
$4669BE79, $CB61B38C, $BC66831A, $256FD2A0, $5268E236, $CC0C7795, $BB0B4703,
$220216B9, $5505262F, $C5BA3BBE, $B2BD0B28, $2BB45A92, $5CB36A04, $C2D7FFA7,
$B5D0CF31, $2CD99E8B, $5BDEAE1D, $9B64C2B0, $EC63F226, $756AA39C, $026D930A,
$9C0906A9, $EB0E363F, $72076785, $05005713, $95BF4A82, $E2B87A14, $7BB12BAE,
$0CB61B38, $92D28E9B, $E5D5BE0D, $7CDCEFB7, $0BDBDF21, $86D3D2D4, $F1D4E242,
$68DDB3F8, $1FDA836E, $81BE16CD, $F6B9265B, $6FB077E1, $18B74777, $88085AE6,
$FF0F6A70, $66063BCA, $11010B5C, $8F659EFF, $F862AE69, $616BFFD3, $166CCF45,
$A00AE278, $D70DD2EE, $4E048354, $3903B3C2, $A7672661, $D06016F7, $4969474D,
$3E6E77DB, $AED16A4A, $D9D65ADC, $40DF0B66, $37D83BF0, $A9BCAE53, $DEBB9EC5,
$47B2CF7F, $30B5FFE9, $BDBDF21C, $CABAC28A, $53B39330, $24B4A3A6, $BAD03605,
$CDD70693, $54DE5729, $23D967BF, $B3667A2E, $C4614AB8, $5D681B02, $2A6F2B94,
$B40BBE37, $C30C8EA1, $5A05DF1B, $2D02EF8D );
//==============================================================================
Function CRC32ToStr(const CRC32: TCRC32): String;
begin
Result := IntToHex(CRC32,8);
end;
//------------------------------------------------------------------------------
Function StrToCRC32(const Str: String): TCRC32;
begin
Result := TCRC32(StrToInt('$' + Str));
end;
//==============================================================================
Function BufferCRC32(const CRC32: TCRC32; const Buffer; Size: Integer): TCRC32; register;
{$IFDEF PUREPASCAL}
var
i: Integer;
Buff: PByteArray;
begin
Result := not CRC32;
If Size > 0 then
begin
Buff := @Buffer;
For i := 0 to Pred(Size) do
Result := CRCTable[Byte(Result xor LongWord(Buff^[i]))] xor (Result shr 8);
end;
Result := not Result;
end;
{$ELSE}
asm
{******************************************************************************}
{ Register Content }
{ EAX old CRC32 value, Result }
{ EDX pointer to Buffer }
{ ECX Size value }
{ }
{ Registers used in routine: }
{ EAX (contains result), EBX (value preserved), ECX, EDX }
{******************************************************************************}
CMP ECX, 0 // check whether size is larger than zero...
JNG @RoutineEnd // ...end calculation when isn't
PUSH EBX // EBX register value must be preserved
MOV EBX, EDX // EBX now contains pointer to Buffer
NOT EAX
{*** Main calculation loop, executed ECX times ********************************}
@MainLoop: MOV DL, [EBX]
XOR DL, AL
AND EDX, $000000FF
MOV EDX, [EDX * 4 + CRCTable]
SHR EAX, 8
XOR EAX, EDX
INC EBX
LOOP @MainLoop
NOT EAX
POP EBX // restore EBX register
@RoutineEnd: MOV Result, EAX
end;
{$ENDIF}
//==============================================================================
Function StringCRC32(const Text: AnsiString): TCRC32;
{$IFDEF UseStringStream}
var
StringStream: TStringStream;
begin
StringStream := TStringStream.Create(Text);
try
Result := StreamCRC32(StringStream);
finally
StringStream.Free;
end;
end;
{$ELSE}
begin
Result := BufferCRC32(0,PAnsiChar(Text)^,Length(Text) * SizeOf(AnsiChar));
end;
{$ENDIF}
//------------------------------------------------------------------------------
Function StringCRC32(const Text: WideString): TCRC32;
{$IFDEF UseStringStream}
var
StringStream: TStringStream;
begin
StringStream := TStringStream.Create(Text);
try
Result := StreamCRC32(StringStream);
finally
StringStream.Free;
end;
end;
{$ELSE}
begin
Result := BufferCRC32(0,PWideChar(Text)^,Length(Text) * SizeOf(WideChar));
end;
{$ENDIF}
//------------------------------------------------------------------------------
Function FileCRC32(const FileName: String): TCRC32;
var
FileStream: TFileStream;
begin
FileStream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
try
Result := StreamCRC32(FileStream);
finally
FileStream.Free;
end;
end;
//------------------------------------------------------------------------------
Function StreamCRC32(const InputStream: TStream): TCRC32;
var
Buffer: Pointer;
Readed: Integer;
begin
Result := 0;
If Assigned(InputStream) then
begin
InputStream.Position := 0;
GetMem(Buffer,cBufferSize);
try
Repeat
Readed := InputStream.Read(Buffer^,cBufferSize);
Result := BufferCRC32(Result,Buffer^,Readed);
Until Readed < cBufferSize;
finally
FreeMem(Buffer,cBufferSize);
end;
InputStream.Position := 0;
end;
end;
end.
|
{
Clever Internet Suite
Copyright (C) 2013 Clever Components
All Rights Reserved
www.CleverComponents.com
}
unit clUriUtils;
interface
{$I clVer.inc}
{$IFDEF DELPHI6}
{$WARN SYMBOL_PLATFORM OFF}
{$ENDIF}
uses
clWinInet, clWUtils;
type
TclUrlType = (utUnknown, utFTP, utGOPHER, utHTTP, utHTTPS, utFILE, utNEWS, utMAILTO);
TclOnUrlParsing = procedure (Sender: TObject; var URLComponents: TURLComponents) of object;
TclUrlParser = class
private
FUrlpath: string;
FUserName: string;
FExtra: string;
FHost: string;
FPassword: string;
FUrlType: TclUrlType;
FPort: Integer;
FAbsoluteUri: string;
FOnUrlParsing: TclOnUrlParsing;
FCharSet: string;
function InternalParse(const AFullUrl: string): string;
function GetAbsolutePath: string;
class function IsUnsafeChar(ACharCode: TclChar): Boolean;
protected
procedure DoUrlParsing(var UrlComponents: TURLComponents); virtual;
public
class function CombineUrl(const AUrl, ABaseUrl: string): string; overload;
class function CombineUrl(const AUrl, ABaseUrl, ACharSet: string): string; overload;
class function EncodeUrl(const AUrl, ACharSet: string): string;
function Parse(const AFullUrl: string): string; overload;
function Parse(const AFullUrl, ACharSet: string): string; overload;
procedure Assign(Source: TclUrlParser); virtual;
property CharSet: string read FCharSet write FCharSet;
property Host: string read FHost;
property UserName: string read FUserName;
property Password: string read FPassword;
property Urlpath: string read FUrlpath;
property Extra: string read FExtra;
property AbsolutePath: string read GetAbsolutePath;
property Port: Integer read FPort;
property UrlType: TclUrlType read FUrlType;
property AbsoluteUri: string read FAbsoluteUri;
property OnUrlParsing: TclOnUrlParsing read FOnUrlParsing write FOnUrlParsing;
end;
TclUrlCorrector = class(TclUrlParser)
private
FIsByLocalFile: Boolean;
FLocalFile: string;
protected
procedure DoUrlParsing(var UrlComponents: TURLComponents); override;
public
function GetURLByLocalFile(const AFullUrl, ALocalFile: string): string;
function GetLocalFileByURL(const AFullUrl, ALocalFolder: string): string;
end;
implementation
uses
{$IFNDEF DELPHIXE2}
SysUtils, Windows,
{$ELSE}
System.SysUtils, Winapi.Windows,
{$ENDIF}
clUtils, clIdnTranslator, clTranslator{$IFDEF DELPHIXE4}, System.AnsiStrings{$ENDIF};
var
UnsafeUriChars: PclChar = nil;
UnsafeUriCharsCount: Integer = 0;
{$IFDEF DELPHIXE4}
function StrLen(A: PclChar): Integer;
begin
Result := System.AnsiStrings.StrLen(A);
end;
{$ENDIF}
procedure InitStaticVars;
const
Chars = ' <>"#%{}|\^~[]`';
begin
UnsafeUriCharsCount := TclTranslator.GetByteCount(Chars, 'us-ascii');
if (UnsafeUriCharsCount > 0) then
begin
GetMem(UnsafeUriChars, UnsafeUriCharsCount + 1);
try
TclTranslator.GetBytes(Chars, UnsafeUriChars, UnsafeUriCharsCount + 1, 'us-ascii');
UnsafeUriChars[UnsafeUriCharsCount] := #0;
except
FreeMem(UnsafeUriChars);
UnsafeUriChars := nil;
UnsafeUriCharsCount := 0;
end;
end;
end;
{ TclUrlParser }
class function TclUrlParser.CombineUrl(const AUrl, ABaseUrl: string): string;
begin
Result := CombineUrl(AUrl, ABaseUrl, '');
end;
procedure TclUrlParser.DoUrlParsing(var UrlComponents: TURLComponents);
begin
if Assigned(FOnUrlParsing) then
begin
FOnUrlParsing(Self, UrlComponents);
end;
end;
class function TclUrlParser.EncodeUrl(const AUrl, ACharSet: string): string;
function IsHexDigit(c: TclChar): Boolean;
begin
Result := (c in ['0'..'9']) or (c in ['a'..'f']) or (c in ['A'..'F']);
end;
var
i, size: Integer;
encBytes: PclChar;
begin
Result := '';
size := TclTranslator.GetByteCount(AUrl, ACharSet);
if (size > 0) then
begin
GetMem(encBytes, size);
try
TclTranslator.GetBytes(AUrl, encBytes, size, ACharSet);
i := 0;
while (i < size) do
begin
if (encBytes[i] = '%') and (i + 2 < size)
and IsHexDigit(encBytes[i + 1]) and IsHexDigit(encBytes[i + 2]) then
begin
Result := Result + '%' + string(encBytes[i + 1]) + string(encBytes[i + 2]);
Inc(i, 2);
end else
if IsUnsafeChar(encBytes[i]) or (encBytes[i] >= #$7F) or (encBytes[i] < #$20) then
begin
Result := Result + '%' + IntToHex(Integer(encBytes[i]), 2);
end else
begin
Result := Result + string(encBytes[i]);
end;
Inc(i);
end;
finally
FreeMem(encBytes);
end;
end else
begin
Result := StringReplace(Trim(AUrl), #32, '%20', [rfReplaceAll]);
end;
end;
function TclUrlParser.Parse(const AFullUrl, ACharSet: string): string;
begin
FCharSet := ACharSet;
Result := InternalParse(AFullUrl);
if (Result = '') and (AFullUrl <> '')
and (GetLastError() = ERROR_INTERNET_UNRECOGNIZED_SCHEME) then
begin
Result := InternalParse('http://' + AFullUrl);
end;
FAbsoluteUri := Result;
end;
function TclUrlParser.InternalParse(const AFullUrl: string): string;
procedure CleanArray(var Arr: array of TclChar);
begin
ZeroMemory(Arr + 0, High(Arr) - Low(Arr) + 1);
end;
var
UrlComponents: TURLComponents;
scheme: array[0..INTERNET_MAX_SCHEME_LENGTH - 1] of TclChar;
host: array[0..INTERNET_MAX_HOST_NAME_LENGTH - 1] of TclChar;
user: array[0..INTERNET_MAX_USER_NAME_LENGTH - 1] of TclChar;
password: array[0..INTERNET_MAX_PASSWORD_LENGTH - 1] of TclChar;
urlpath: array[0..INTERNET_MAX_PATH_LENGTH - 1] of TclChar;
fullurl: array[0..INTERNET_MAX_URL_LENGTH - 1] of TclChar;
extra: array[0..4096 - 1] of TclChar;
dwLen: DWORD;
res: BOOL;
begin
FUrlType := utUnknown;
FHost := '';
FUserName := '';
FPassword := '';
FUrlpath := '';
FExtra := '';
FPort := INTERNET_INVALID_PORT_NUMBER;
Result := '';
CleanArray(scheme);
CleanArray(host);
CleanArray(user);
CleanArray(password);
CleanArray(urlpath);
CleanArray(fullurl);
CleanArray(extra);
ZeroMemory(@UrlComponents, SizeOf(TURLComponents));
UrlComponents.dwStructSize := SizeOf(TURLComponents);
UrlComponents.lpszScheme := scheme;
UrlComponents.dwSchemeLength := High(scheme) + 1;
UrlComponents.lpszHostName := host;
UrlComponents.dwHostNameLength := High(host) + 1;
UrlComponents.lpszUserName := user;
UrlComponents.dwUserNameLength := High(user) + 1;
UrlComponents.lpszPassword := password;
UrlComponents.dwPasswordLength := High(password) + 1;
UrlComponents.lpszUrlPath := urlpath;
UrlComponents.dwUrlPathLength := High(urlpath) + 1;
UrlComponents.lpszExtraInfo := extra;
UrlComponents.dwExtraInfoLength := High(extra) + 1;
res := InternetCrackUrl(PclChar(GetTclString(AFullUrl)), Length(AFullUrl), 0, UrlComponents);
if res then
begin
if (UrlComponents.nScheme in [Integer(Low(TclUrlType))..Integer(High(TclUrlType))]) then
begin
FUrlType := TclUrlType(UrlComponents.nScheme);
end;
DoUrlParsing(UrlComponents);
if (StrLen(user) = 0) then
begin
UrlComponents.lpszUserName := nil;
UrlComponents.dwUserNameLength := 0;
end;
if (StrLen(password) = 0) then
begin
UrlComponents.lpszPassword := nil;
UrlComponents.dwPasswordLength := 0;
end;
FHost := string(host);
FUserName := string(user);
FPassword := string(password);
FUrlpath := string(urlpath);
FExtra := string(extra);
FPort := UrlComponents.nPort;
FHost := TclIdnTranslator.GetAscii(FHost);
CleanArray(host);
Move(PclChar(TclString(FHost))^, host, Length(FHost));
UrlComponents.dwHostNameLength := StrLen(host);
dwLen := INTERNET_MAX_URL_LENGTH;
fullurl[0] := #0;
res := InternetCreateUrl(UrlComponents, 0, fullurl, dwLen);
if res then
begin
Result := system.Copy(string(fullurl), 1, dwLen);
Result := EncodeUrl(Result, FCharSet);
end;
end;
end;
class function TclUrlParser.IsUnsafeChar(ACharCode: TclChar): Boolean;
var
i: Integer;
begin
for i := 0 to UnsafeUriCharsCount - 1 do
begin
if (UnsafeUriChars[i] = ACharCode) then
begin
Result := True;
Exit;
end;
end;
Result := False;
end;
function TclUrlParser.Parse(const AFullUrl: string): string;
begin
Result := Parse(AFullUrl, '');
end;
procedure TclUrlParser.Assign(Source: TclUrlParser);
begin
FAbsoluteUri := Source.AbsoluteUri;
FHost := Source.Host;
FUserName := Source.UserName;
FPassword := Source.Password;
FUrlpath := Source.Urlpath;
FExtra := Source.Extra;
FPort := Source.Port;
FUrlType := Source.UrlType;
end;
function TclUrlParser.GetAbsolutePath: string;
begin
if (Host = '*') then
begin
Result := Host;
end else
begin
Result := Urlpath;
if (Extra <> '') then
begin
if (Extra[1] <> '?') and (Result <> '') and (Result[Length(Result)] <> '?') then
begin
Result := Result + '?';
end;
Result := Result + Extra;
end;
if (Result = '') then
begin
Result := '/';
end;
end;
Result := EncodeUrl(Result, FCharSet);
end;
class function TclUrlParser.CombineUrl(const AUrl, ABaseUrl, ACharSet: string): string;
var
buf: array[0..INTERNET_MAX_URL_LENGTH - 1] of TclChar;
len: DWORD;
urlParser: TclUrlParser;
begin
len := SizeOf(buf);
ZeroMemory(buf + 0, len);
InternetCombineUrl(PclChar(GetTclString(ABaseUrl)), PclChar(GetTclString(AUrl)), buf, len, ICU_BROWSER_MODE);
Result := string(buf);
urlParser := TclUrlParser.Create();
try
Result := urlParser.Parse(Result, ACharSet);
finally
urlParser.Free();
end;
end;
{ TclUrlCorrector }
function TclUrlCorrector.GetURLByLocalFile(const AFullUrl, ALocalFile: string): string;
begin
FIsByLocalFile := True;
try
FLocalFile := ALocalFile;
Result := Parse(AFullUrl, CharSet);
finally
FIsByLocalFile := False;
end;
end;
function TclUrlCorrector.GetLocalFileByURL(const AFullUrl, ALocalFolder: string): string;
var
ind: Integer;
begin
Result := ALocalFolder;
if (Parse(AFullUrl, CharSet) <> '') then
begin
Result := AddTrailingBackSlash(Result);
ind := LastDelimiter('/', Urlpath);
Result := Result + system.Copy(Urlpath, ind + 1, MaxInt);
end;
end;
procedure TclUrlCorrector.DoUrlParsing(var UrlComponents: TURLComponents);
var
ind: Integer;
s: string;
ansiStr: TclString;
begin
if FIsByLocalFile then
begin
s := string(URLComponents.lpszUrlPath);
ind := LastDelimiter('/', s);
s := system.Copy(s, 1, ind);
ind := Length(s);
if (ind > 0) and (s[ind] <> '/') then
begin
s := s + '/';
end;
ind := LastDelimiter('\', FLocalFile);
s := s + system.Copy(FLocalFile, ind + 1, MaxInt);
ansiStr := GetTclString(s);
ZeroMemory(URLComponents.lpszUrlPath + 0, INTERNET_MAX_PATH_LENGTH);
CopyMemory(URLComponents.lpszUrlPath + 0, PclChar(ansiStr), Length(ansiStr));
URLComponents.dwUrlPathLength := Length(ansiStr);
end;
inherited DoUrlParsing(UrlComponents);
end;
initialization
InitStaticVars();
finalization
FreeMem(UnsafeUriChars);
end.
|
{$MODE OBJFPC}
program COCI6;
const
InputFile = 'WEIGHT.INP';
OutputFile = 'WEIGHT.OUT';
maxN = Round(1E6);
type
TStack = record
items: array[1..maxN] of Integer;
top: Integer;
end;
TArr = array[1..maxN] of Integer;
var
a: array[1..maxN] of Integer;
lmax, rmax, lmin, rmin: TArr;
stack: TStack;
n: Integer;
res: Int64;
procedure Enter;
var
f: TextFile;
i: Integer;
begin
AssignFile(f, InputFile); Reset(f);
try
ReadLn(f, n);
for i := 1 to n do Read(f, a[i]);
finally
CloseFile(f);
end;
end;
procedure GetLR(var left, right: TArr);
var i: Integer;
begin
with stack do
begin
top := 0;
for i := 1 to n do
begin
while (top > 0) and (a[items[top]] < a[i]) do
Dec(top);
if top > 0 then left[i] := items[top]
else left[i] := 0;
Inc(top); items[top] := i;
end;
top := 0;
for i := n downto 1 do
begin
while (top > 0) and (a[items[top]] <= a[i]) do
Dec(top);
if top > 0 then right[i] := items[top]
else right[i] := n + 1;
Inc(top); items[top] := i;
end;
end;
end;
function nSegs(L, R, p: Integer): Int64;
begin
Result := Int64(p - L) * (R - p);
end;
procedure Solve;
var
i: Integer;
t: Int64;
begin
GetLR(lmax, rmax);
for i := 1 to n do a[i] := -a[i];
GetLR(lmin, rmin);
res := 0;
for i := 1 to n do
begin
t := nSegs(lmax[i], rmax[i], i);
res := res - a[i] * t;
t := nSegs(lmin[i], rmin[i], i);
res := res + a[i] * t;
end;
end;
procedure Print;
var
f: TextFile;
begin
AssignFile(f, OutputFile); Rewrite(f);
try
Write(f, res);
finally
CloseFile(f);
end;
end;
begin
Enter;
Solve;
Print;
end.
|
unit PatchExeUnit;
{
Freeware downloaded from delphipraxis.net
Author: sx2008
Date: 2010-01-05
}
interface
type
TExeData = record
MagicWord : array[0..11] of Ansichar;
Checksum : Cardinal;
BrandingDate : TDateTime;
Data : array[0..19] of Ansichar;
end;
PExeData = ^TExeData;
function GetConfigString:Ansistring;
function IsExeChecksumValid:boolean;
procedure PatchFile(const sourcefilename, destfilename:string; const newconfigstr:Ansistring);
procedure PatchOwnExefile(const filename, newconfigstr:ansistring);
implementation
uses SysUtils, Classes;
var
globalConfigData:Ansistring = '@magic#word@'+
#0#0#0#0+ // Checksum
#0#0#0#0#0#0#0+ // BrandingDate
#0#0#0#0#0#0+
#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0+
#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0;
(*
globalConfigData : TExeData = (MagicWord:'@magic#word@');
*)
function FileToString(const FileName: AnsiString): AnsiString;
var
FS: TFileStream;
Len: Integer;
begin
FS := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
try
Len := FS.Size;
SetLength(Result, Len);
if Len > 0 then
FS.ReadBuffer(Result[1], Len);
finally
FS.Free;
end;
end;
procedure StringToFile(const FileName: AnsiString; const Contents: AnsiString);
var
FS: TFileStream;
Len: Integer;
begin
FS := TFileStream.Create(FileName, fmCreate);
try
Len := Length(Contents);
if Len > 0 then
FS.WriteBuffer(Contents[1], Len);
finally
FS.Free;
end;
end;
function GetExeRecordPtr:PExeData;
begin
Result := PExeData(@globalConfigData[1]);
end;
function GetConfigString:Ansistring;
begin
result := GetExeRecordPtr.Data;
end;
function CalcXorSum(const s:Ansistring):Cardinal;
var
i : integer;
x : PCardinal;
begin
result := 0;
x := PCardinal(PChar(s));
for i := 0 to Length(s) div sizeof(Cardinal) do
begin
result := result xor x^;
Inc(x);
end;
end;
function IsExeChecksumValid:boolean;
var
exedata : AnsiString;
begin
exedata := FileToString(ParamStr(0)); // Exe-Datei als String laden
result := CalcXorSum(exedata) = 0;
end;
function GetMagicWord:AnsiString;
begin
Result := GetExeRecordPtr.MagicWord;
end;
procedure PatchFile(const sourcefilename, destfilename:string; const newconfigstr:Ansistring);
var
exedata, magicword : Ansistring;
p : integer;
x : PExeData;
begin
// verhindern, dass die neuen Konfigdaten zu lang werden
if Length(newconfigstr) > sizeof(x.Data) then
raise Exception.Create('Config String too long');
magicword := GetMagicWord;
exedata := FileToString(sourcefilename); // Exe-Datei als String laden
p := Pos(magicword, exedata); // Magisches Wort suchen
if p = 0 then
raise Exception.Create('Magic Word not found');
x := PExeData(@exedata[p]);
// Configdaten überschreiben
Move(newconfigstr[1], x.Data[0], length(newconfigstr));
x.BrandingDate := now;
x.Checksum := CalcXorSum(exedata);
// modifizierte EXE speichern
StringToFile(destfilename, exedata);
end;
procedure PatchOwnExeFile(const filename, newconfigstr:ansistring);
var
sourcefilename : string;
begin
sourcefilename := ParamStr(0);
Assert(sourcefilename <> filename);
PatchFile(sourcefilename, filename, newconfigstr);
end;
end.
|
unit formSOListExample;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, SOList,
FMX.Layouts, FMX.Controls.Presentation, FMX.StdCtrls, FireDAC.Stan.Intf,
FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS,
FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.StorageBin, Data.DB,
FireDAC.Comp.DataSet, FireDAC.Comp.Client, framePeople, FMX.TabControl,
frameProduct, Data.Bind.GenData, Fmx.Bind.GenData, Data.Bind.Components,
Data.Bind.ObjectScope, FMX.Edit, frameColor, frameForm, System.Rtti,
FMX.Grid.Style, Data.Bind.Controls, Data.Bind.EngExt, Fmx.Bind.DBEngExt,
Fmx.Bind.Grid, System.Bindings.Outputs, Fmx.Bind.Editors, Data.Bind.Grid,
Data.Bind.DBScope, Fmx.Bind.Navigator, FMX.ScrollBox, FMX.Grid, FMX.Objects;
type
TSOListExample = class(TForm)
mCliente: TFDMemTable;
mClienteid: TAutoIncField;
mClientenome: TStringField;
mClientesobrenome: TStringField;
TabControl1: TTabControl;
tbiProduct: TTabItem;
tbiDragDrop: TTabItem;
tbiFormList: TTabItem;
vsbProduct: TVertScrollBox;
Layout1: TLayout;
btnProductLoad: TButton;
btnProductAdd: TButton;
btnProductDelete: TButton;
btnProductClear: TButton;
gbProductAdd: TGroupBox;
edtProductAmount: TEdit;
edtProductDescription: TEdit;
edtProductName: TEdit;
GroupBox1: TGroupBox;
edtProductSearch: TEdit;
btnProductRemove: TButton;
btnProductChange: TButton;
btnProductShowItem: TButton;
btnProductHide: TButton;
vsbColor: TVertScrollBox;
Layout2: TLayout;
btnColorLoad: TButton;
btnColorClear: TButton;
btnColorStartDrag: TButton;
btnColorStopDrag: TButton;
vsbForm: TVertScrollBox;
Layout3: TLayout;
btnFormLoad: TButton;
btnFormClear: TButton;
btnFormShowHidden: TButton;
tbiDataset: TTabItem;
Layout4: TLayout;
btnDatasetLoad: TButton;
btnDatasetClear: TButton;
vsbDataset: TVertScrollBox;
mClientefoto: TBlobField;
BindingsList1: TBindingsList;
od: TOpenDialog;
GroupBox2: TGroupBox;
Grid1: TGrid;
BindNavigator1: TBindNavigator;
Image1: TImage;
BindSourceDB1: TBindSourceDB;
LinkGridToDataSourceBindSourceDB12: TLinkGridToDataSource;
LinkPropertyToFieldBitmap2: TLinkPropertyToField;
Button1: TButton;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure btnProductLoadClick(Sender: TObject);
procedure btnProductClearClick(Sender: TObject);
procedure btnProductAddClick(Sender: TObject);
procedure btnProductDeleteClick(Sender: TObject);
procedure btnProductRemoveClick(Sender: TObject);
procedure btnProductChangeClick(Sender: TObject);
procedure btnProductShowItemClick(Sender: TObject);
procedure btnProductHideClick(Sender: TObject);
procedure btnColorLoadClick(Sender: TObject);
procedure btnColorClearClick(Sender: TObject);
procedure btnColorStartDragClick(Sender: TObject);
procedure btnColorStopDragClick(Sender: TObject);
procedure btnFormLoadClick(Sender: TObject);
procedure btnFormShowHiddenClick(Sender: TObject);
procedure btnFormClearClick(Sender: TObject);
procedure btnDatasetLoadClick(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure btnDatasetClearClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
ProductList: TSOList<TVertScrollBox, TFraProduct>;
ColorList: TSOList<TVertScrollBox, TFraColor>;
FormList: TSOList<TVertScrollBox, TFraForm>;
DataList: TSOList<TVertScrollBox, TFraPeople>;
procedure btSaveDatasetClick(Sender: TObject);
procedure btDelDatasetClick(Sender: TObject);
end;
var
SOListExample: TSOListExample;
implementation
{$R *.fmx}
procedure TSOListExample.btSaveDatasetClick(Sender: TObject);
var
Item : TfraPeople;
begin
Item := TfraPeople(TFmxObject(Sender).parent);
with mCliente do begin
if Locate('id', Item.ID, []) then begin
Edit;
FieldByName('nome').AsString := Item.edtFirstName.Text;
FieldByName('sobrenome').AsString := Item.edtLastName.Text;
Post;
end;
end;
end;
procedure TSOListExample.btDelDatasetClick(Sender: TObject);
var
Item : TfraPeople;
begin
Item := TfraPeople(TFmxObject(Sender).parent);
with mCliente do begin
if Locate('id', Item.ID, []) then begin
Delete;
end;
end;
DataList. Remove(Item.Name);
end;
procedure TSOListExample.btnColorClearClick(Sender: TObject);
begin
ColorList.Clear;
end;
procedure TSOListExample.btnColorLoadClick(Sender: TObject);
var
Item: TfraColor;
I: Integer;
AnimeDelay: Single;
begin
AnimeDelay := 0;
for I := 1 to 50 do begin
Item := TFraColor.Create(ColorList);
Item.Name:='ColorItem'+I.ToString;
Item.Margins.Top := 10;
Item.Margins.Left := 10;
Item.Background.Fill.Color := TAlphaColor(Random(99999999999));
ColorList.Add(Item, 0.4, AnimeDelay);
AnimeDelay := AnimeDelay+0.2;
end;
end;
procedure TSOListExample.btnColorStartDragClick(Sender: TObject);
begin
ColorList.BeginDragDrop;
Showmessage('Drag and Drop is associate to TFrame, notice the HitTest=false to background TRectangle');
end;
procedure TSOListExample.btnColorStopDragClick(Sender: TObject);
begin
ColorList.EndDragDrop;
end;
procedure TSOListExample.btnDatasetClearClick(Sender: TObject);
begin
DataList.Clear;
end;
procedure TSOListExample.btnDatasetLoadClick(Sender: TObject);
begin
DataList.Load(mCliente,
procedure (Data: TDataset; Item: TfraPeople)
var
stream: TMemoryStream;
begin
Item.ID := Data.FieldByName('id').AsInteger;
Item.edtFirstName.Text := Data.FieldByName('nome').AsString;
Item.edtLastName.Text := Data.FieldByName('sobrenome').AsString;
// picture
Stream := TMemoryStream.Create;
TBlobField(Data.FieldByName('foto')).SaveToStream(Stream);
Item.Image1.Bitmap.LoadFromStream(stream);
Stream.Free;
Item.btnSave.OnClick := btSaveDatasetClick;
Item.btnDel.OnClick := btDelDatasetClick;
end,
procedure (Data: TDataset) begin
Showmessage('Record Count: '+Data.RecordCount.ToString);
end
);
end;
procedure TSOListExample.btnFormClearClick(Sender: TObject);
begin
FormList.Clear;
end;
procedure TSOListExample.btnFormLoadClick(Sender: TObject);
var
Item: TfraForm;
I: Integer;
AnimeDelay: Single;
begin
AnimeDelay := 0;
for I := 1 to 20 do begin
Item := TfraForm.Create(FormList);
Item.Name:='FormItem'+I.ToString;
Item.Margins.Top := 10;
Item.Margins.Left := 10;
Item.lblTitle.Text := 'Form '+I.ToString;
FormList.Add(Item, 0.5, AnimeDelay);
AnimeDelay := AnimeDelay+0.05;
end;
end;
procedure TSOListExample.btnFormShowHiddenClick(Sender: TObject);
begin
FormList.ShowHiddenItems;
end;
procedure TSOListExample.btnProductAddClick(Sender: TObject);
var
item: TFraProduct;
begin
Item := TfraProduct.Create(ProductList);
Item.Name := 'ProductItem_'+StringReplace(edtProductName.Text, ' ', '',[rfReplaceAll]);
Item.Margins.Top := 10;
Item.Margins.Left := 10;
Item.lblTitle.Text := edtProductName.Text;
Item.lblDescription.Text := edtProductDescription.Text;
Item.lblAmount.Text := edtProductAmount.Text;
ProductList.Add(Item);
edtProductSearch.Text := Item.Name;
vsbProduct.ScrollBy(0, -item.Position.Y);
end;
procedure TSOListExample.btnProductClearClick(Sender: TObject);
begin
ProductList.Clear;
end;
procedure TSOListExample.btnProductLoadClick(Sender: TObject);
var
Item: TfraProduct;
I: Integer;
AnimeDelay: Single;
begin
AnimeDelay := 0;
for I := 1 to 50 do begin
Item := TFraProduct.Create(ProductList);
Item.Name:='ProductItem'+I.ToString;
Item.Margins.Top := 10;
Item.Margins.Left := 10;
Item.lblTitle.Text := 'Product Name '+I.ToString;
Item.lblDescription.Text := 'Description of product '+I.ToString;
Item.lblAmount.Text := Random(100).ToString;
ProductList.Add(Item, 0.4, AnimeDelay);
AnimeDelay := AnimeDelay+0.2;
end;
end;
procedure TSOListExample.btnProductRemoveClick(Sender: TObject);
begin
ProductList.Remove(edtProductSearch.Text);
end;
procedure TSOListExample.btnProductShowItemClick(Sender: TObject);
var
Product: TfraProduct;
begin
Product := ProductList.Items(edtProductSearch.Text);
if Product = nil then showmessage('Product not found.');
ProductList.ShowItem(Product);
end;
procedure TSOListExample.Button1Click(Sender: TObject);
begin
if Od.execute then begin
mCliente.Edit;
mClientefoto.LoadFromFile(od.filename);
mCliente.Post;
end;
end;
procedure TSOListExample.btnProductDeleteClick(Sender: TObject);
begin
ProductList.Delete(1);
end;
procedure TSOListExample.btnProductHideClick(Sender: TObject);
var
Product: TfraProduct;
begin
// just hide, donīt free ;)
Product := ProductList.Items(edtProductSearch.Text);
if Product = nil then showmessage('Product not found.');
ProductList.HideItem(Product);
end;
procedure TSOListExample.btnProductChangeClick(Sender: TObject);
var
Product : TfraProduct;
begin
Product := ProductList.Items(edtProductSearch.Text);
if Product = nil then
showmessage('Product not found.');
Product.Content.Fill.Color := TAlphaColors.Blanchedalmond;
end;
procedure TSOListExample.FormCreate(Sender: TObject);
begin
ProductList := TSOList<TVertScrollBox, TfraProduct>.New(vsbProduct);
ColorList := TSOList<TVertScrollBox, TFraColor>.New(vsbColor);
FormList := TSOList<TVertScrollBox, TFraForm>.New(vsbForm);
DataList := TSOList<TVertScrollBox, TfraPeople>.New(vsbDataset);
if FileExists('../../Data/peossoas.dat') then
mCliente.LoadFromFile('../../Data/peossoas.dat')
else begin
ShowMessage('File PESSOAS.DAT not found, please find the file in DATA path.');
if od.Execute then
mCliente.LoadFromFile(od.FileName);
end;
mCliente.Open;
end;
procedure TSOListExample.FormDestroy(Sender: TObject);
begin
if Assigned(DataList) then
DataList.Free;
if Assigned(ProductList) then
ProductList.Free;
if Assigned(ColorList) then
ColorList.Free;
if Assigned(FormList) then
FormList.Free;
end;
end.
|
unit DirectoryServerProtocol;
interface
type
TAccountId = string;
const
DIR_NOERROR_StillTrial = -1;
DIR_NOERROR = 0;
DIR_ERROR_Unknown = 1;
DIR_ERROR_AccountAlreadyExists = 2;
DIR_ERROR_UnexistingAccount = 3;
DIR_ERROR_SerialMaxed = 4;
DIR_ERROR_InvalidSerial = 5;
DIR_ERROR_InvalidAlias = 6;
DIR_ERROR_InvalidPassword = 7;
DIR_ERROR_AccountBlocked = 8;
DIR_ERROR_TrialExpired = 9;
DIR_ERROR_SubscriberIdNotFound = 10;
// SEGA SNAP ERROR CODES
DIR_SEGA_NOERROR = 0;
DIR_SEGA_ERROR_UserNotFound = 1;
DIR_SEGA_ERROR_BadUserIDFormat = 2;
DIR_SEGA_ERROR_UnknownDomain = 3;
DIR_SEGA_ERROR_InternalError = 4;
DIR_SEGA_ERROR_UserNotAuthorized = 5;
DIR_SEGA_ERROR_SystemDown = 6;
DIR_SEGA_ERROR_NotInitialized = 7;
DIR_SEGA_ERROR_TimeOut = 8;
const
DIR_ACC_RegUser = 0;
DIR_ACC_TrialUser = 1;
DIR_ACC_BlockedUser = 2;
DIR_ACC_NoAuthUserA = 3;
DIR_ACC_NoAuthUserB = 33;
type
TSerialFamilyId = (famRegular, famTester, famGameMaster, famTutor);
var
SerialFamilies : array[TSerialFamilyId] of extended =
(0.1233, 0.1233, 0.1233, 0.1233);
// (0.1233, 0.1233, 0.1233, 0.1233);
// (0.3737, 0.1212, 0.5555, 0.9191);
function GetFamily( AccountId : TAccountId; out FamilyId : TSerialFamilyId ) : boolean;
function AuthenticAlias(Alias : string) : boolean;
function IsValidAlias( Alias : string ) : boolean;
function GetUserPath( Alias : string ) : string;
function GetUserMapPath(Alias : string) : string;
function GetAliasId( Alias : string ) : string;
implementation
uses
SysUtils, GenIdd;
function GetFamily( AccountId : TAccountId; out FamilyId : TSerialFamilyId ) : boolean;
var
EndOfArray : boolean;
begin
FamilyId := low(FamilyId);
repeat
result := HeavyIddCheck( AccountId, SerialFamilies[FamilyId] );
EndOfArray := FamilyId = high(FamilyId);
if not EndOfArray
then inc( FamilyId );
until result or EndOfArray;
end;
function AuthenticAlias(Alias : string) : boolean;
const
reserved : array[0..7] of string = ('oc_', 'gm_', 'sp_', 'oceanus', 'starpeace', 'support', 'gamemaster', 'sega');
var
i : integer;
begin
result := true;
Alias := LowerCase(Alias);
i := low(reserved);
while (i <= high(reserved)) and result do
begin
result := result and (pos(reserved[i], Alias) = 0);
inc(i);
end;
end;
function IsValidAlias( Alias : string ) : boolean;
const
Alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
//ValidChars = Alphabet + '0123456789 -_:?!(){}[]<>+=&@#$%^&|;,';
ValidChars = Alphabet + '0123456789 -_!()[]+=#;,';
var
i : integer;
begin
Alias := Trim( Alias );
if (Length( Alias ) > 0) and (Pos( UpCase( Alias[1] ), Alphabet ) > 0) and AuthenticAlias(Alias)
then
begin
i := 2;
while (i <= Length( Alias )) and (Pos( UpCase( Alias[i] ), ValidChars ) > 0) do
inc( i );
result := i > Length( Alias );
end
else result := false;
end;
function GetAliasId( Alias : string ) : string;
var
i : integer;
begin
result := Trim( Alias );
for i := 1 to Length( result ) do
if result[i] = ' '
then result[i] := '.'
else result[i] := UpCase( result[i] );
end;
function GetUserPath( Alias : string ) : string;
var
aID : string;
begin
aID := GetAliasID( Alias );
result := 'Root/Users/' + aID[1] + '/' + aID
end;
function GetUserMapPath(Alias : string) : string;
var
aID : string;
begin
aID := GetAliasID( Alias );
result := 'Root/SegaUsers/' + aID[1] + '/' + aID
end;
end.
|
unit sina_InfoApp;
interface
uses
cef_apiobj,
HostWnd_chromium,
define_dealitem,
BaseStockApp;
type
TSinaInfoApp = class(TBaseStockApp)
protected
fCefClientObject: cef_apiobj.TCefClientObject;
fStockIndex: integer;
fHostWindow: HostWnd_chromium.THostWndChromium;
procedure LoadUrl(AStockItem: PRT_DealItem); overload;
procedure LoadUrl; overload;
procedure CreateBrowser;
procedure CreateHostWindow;
public
function Initialize: Boolean; override;
procedure Run; override;
end;
var
GlobalApp: TSinaInfoApp = nil;
implementation
uses
Windows,
Sysutils,
chromium_dom_sina,
windef_msg,
win.wnd,
define_datasrc,
cef_type,
cef_app,
cef_api,
cef_utils,
cef_apilib;
const
Url_StockHome = 'https://Sina.com/S/'; // https://Sina.com/S/SZ300134
// 股本结构
Url_StockStruct = 'https://Sina.com/S/SZ300134/GBJG';
WM_LoadUrl = WM_CustomAppBase + 1;
// http://finance.sina.com.cn/stock/
// http://finance.sina.com.cn/realstock/company/sz300144/nc.shtml
// http://vip.stock.finance.sina.com.cn/corp/go.php/vCI_StockHolder/stockid/300144/displaytype/30.phtml 主要股东
// http://vip.stock.finance.sina.com.cn/corp/go.php/vCI_CirculateStockHolder/stockid/300144/displaytype/30.phtml 流通股东
// http://vip.stock.finance.sina.com.cn/corp/go.php/vCI_StockStructure/stockid/300144.phtml 股本结构
// http://vip.stock.finance.sina.com.cn/quotes_service/view/vMS_tradedetail.php?symbol=sz300144 成交明细
// http://vip.stock.finance.sina.com.cn/corp/go.php/vMS_FuQuanMarketHistory/stockid/300144.phtml 复权交易
// https://Sina.com/S/SH600000/
//https://Sina.com/S/SZ300134/ZYGD // 主要股东
//https://Sina.com/S/SZ300134/LTGD // 流通股东
//https://Sina.com/S/SZ300134/GDHS // 股东户数
//https://Sina.com/S/SZ300134/XSGDMD // 限售股东
//https://Sina.com/S/SZ300134/LHB // 龙虎榜数据
// 交易明细
// http://stockhtm.finance.qq.com/sstock/quotpage/q/300134.htm#detail
// 分价表
// http://stockhtm.finance.qq.com/sstock/quotpage/q/300134.htm#price
// 大单统计
// http://quotes.money.163.com/trade/ddtj_300134.html
// 基金持股
// http://stock.jrj.com.cn/share,300134,jjcg.shtml
procedure TSinaInfoApp.CreateBrowser;
begin
if CefApp.CefLibrary.LibHandle = 0 then
begin
cef_app.CefApp.CefLibrary.CefCoreSettings.multi_threaded_message_loop := False;
CefApp.CefLibrary.CefCoreSettings.multi_threaded_message_loop := True;
cef_apilib.InitCefLib(@CefApp.CefLibrary, @CefApp.CefAppObject);
if CefApp.CefLibrary.LibHandle <> 0 then
begin
fCefClientObject.HostWindow := fHostWindow.BaseWnd.UIWndHandle;
fCefClientObject.CefIsCreateWindow := true;
fCefClientObject.Rect.Left := 0;
fCefClientObject.Rect.Top := 0;
fCefClientObject.Width := fHostWindow.BaseWnd.ClientRect.Right; //Self.Width - pnlRight.Width - 4 * 2;
fCefClientObject.Height := fHostWindow.BaseWnd.ClientRect.Bottom; //Self.Height - pnlTop.Height - 4 * 2;
fCefClientObject.CefUrl := 'about:blank';
fCefClientObject.Rect.Right := fCefClientObject.Rect.Left + fCefClientObject.Width;
fCefClientObject.Rect.Bottom := fCefClientObject.Rect.Top + fCefClientObject.Height;
cef_utils.CreateBrowserCore(@fCefClientObject, @CefApp.CefLibrary, fHostWindow.BaseWnd.UIWndHandle);//Self.WindowHandle);
end;
end;
end;
procedure TSinaInfoApp.CreateHostWindow;
begin
fHostWindow.BaseWnd.WindowRect.Top := 30;
fHostWindow.BaseWnd.WindowRect.Left := 50;
fHostWindow.BaseWnd.ClientRect.Right := 800;
fHostWindow.BaseWnd.ClientRect.Bottom := 600;
fHostWindow.BaseWnd.Style := WS_POPUP or WS_OVERLAPPEDWINDOW;
fHostWindow.BaseWnd.ExStyle := WS_EX_APPWINDOW //WS_EX_TOOLWINDOW
//or WS_EX_TOPMOST
;
CreateHostWndChromium(@fHostWindow);
end;
function TSinaInfoApp.Initialize: Boolean;
begin
Result := inherited Initialize;
if Result then
begin
Self.InitializeDBStockItem();
if 1 > StockItemDB.RecordCount then
begin
Result := false;
fStockIndex := 0;
end;
end;
end;
(*//
每股收益:0.70
市盈率LYR/TTM:6.70/6.35
总股本:196.53亿
每股净资产:17.48
市净率TTM:0.99
流通股本:186.53亿
每股股息:0.757
市销率TTM:2.20
//*)
procedure DoLoadEnd(ACefClient: PCefClientObject; AUrl: string);
var
tmpDealItem: PRT_DealItem;
begin
if SameText(ACefClient.CefUrl, AUrl) then
begin
tmpDealItem := ACefClient.ExParam;
if nil <> tmpDealItem then
begin
chromium_dom_sina.TestTraverseChromiumDom(ACefClient, nil);
end;
end;
Sleep(1000);
//PostMessage(GlobalApp.AppWindow, WM_LoadUrl, 0, 0);
end;
procedure TSinaInfoApp.LoadUrl;
var
tmpDealItem: PRT_DealItem;
begin
if nil = StockItemDB then
exit;
if fStockIndex < 0 then
fStockIndex := 0;
if fStockIndex >= StockItemDB.RecordCount then
exit;
tmpDealItem := StockItemDB.Items[fStockIndex];
fStockIndex := fStockIndex + 1;
if 0 = tmpDealItem.EndDealDate then
begin
LoadUrl(tmpDealItem);
end else
begin
PostMessage(GlobalApp.AppWindow, WM_LoadUrl, 0, 0);
end;
end;
procedure TSinaInfoApp.LoadUrl(AStockItem: PRT_DealItem);
var
tmpMainFrame: PCefFrame;
tmpUrl: cef_type.TCefString;
begin
if nil <> fCefClientObject.CefBrowser then
begin
tmpMainFrame := fCefClientObject.CefBrowser.get_main_frame(fCefClientObject.CefBrowser);
if nil <> tmpMainFrame then
begin
fCefClientObject.ExParam := AStockItem;
fCefClientObject.CefOnLoadEnd := DoLoadEnd;
// sh600000 大小写敏感的
// http://finance.sina.com.cn/realstock/company/sz300144/nc.shtml
//fCefClientObject.CefUrl := 'https://Sina.com/S/' + GetStockCode_Sina(AStockItem);
fCefClientObject.CefUrl := 'http://finance.sina.com.cn/realstock/company/' + GetStockCode_Sina(AStockItem) + '/nc.shtml';
tmpUrl := CefString(fCefClientObject.CefUrl);
tmpMainFrame.load_url(tmpMainFrame, @tmpUrl);
end;
end;
end;
function AppCmdWndProcA(AWnd: HWND; AMsg: UINT; wParam: WPARAM; lParam: LPARAM): HRESULT; stdcall;
begin
case AMsg of
WM_AppStart: begin
if nil <> GlobalApp then
begin
PostMessage(AWnd, WM_LoadUrl, 0, 0);
end;
end;
WM_LoadUrl: begin
GlobalApp.LoadUrl();
end;
end;
Result := DefWindowProcA(AWnd, AMsg, wParam, lParam);
end;
function AppStartDelayRunProc(AParam: Pointer): HResult; stdcall;
begin
Result := 0;
Sleep(1 * 200);
if nil <> GlobalApp then
begin
PostMessage(GlobalApp.fBaseWinAppData.WinAppRecord.AppCmdWnd, windef_msg.WM_AppStart, 0, 0);
end;
Windows.ExitThread(Result);
end;
procedure TSinaInfoApp.Run;
var
tmpThreadHandle: THandle;
tmpThreadId: DWORD;
begin
inherited;
FillChar(fCefClientObject, SizeOf(fCefClientObject), 0);
FillChar(fHostWindow, SizeOf(fHostWindow), 0);
fBaseWinAppData.WinAppRecord.AppCmdWnd := CreateCommandWndA(@AppCmdWndProcA, 'F2488C22-131B-407F-840C-7F7EF6E8C8F4');
if IsWindow(fBaseWinAppData.WinAppRecord.AppCmdWnd) then
begin
CreateHostWindow;
if IsWindow(fHostWindow.BaseWnd.UIWndHandle) then
begin
ShowWindow(fHostWindow.BaseWnd.UIWndHandle, SW_SHOW);
CreateBrowser;
tmpThreadHandle := Windows.CreateThread(nil, //lpThreadAttributes: Pointer;
0, //dwStackSize: DWORD;
@AppStartDelayRunProc, //lpStartAddress: TFNThreadStartRoutine;
nil, //lpParameter: Pointer;
CREATE_SUSPENDED, // dwCreationFlags: DWORD;
tmpThreadId //var lpThreadId: DWORD);
);
ResumeThread(tmpThreadHandle);
RunAppMsgLoop;
end;
end;
end;
end.
|
{ GDAX/Coinbase-Pro client library
Copyright (c) 2018 mr-highball
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.
}
unit gdax.api.orders;
{$i gdax.inc}
interface
uses
Classes, gdax.api, gdax.api.consts, gdax.api.types;
type
{ TGDAXOrderImpl }
TGDAXOrderImpl = class(TGDAXRestApi,IGDAXOrder)
public
const
PROP_ID = 'id';
PROP_PRICE = 'price';
PROP_SIZE = 'size';
PROP_FUNDS = 'funds';
PROP_PROD = 'product_id';
PROP_SIDE = 'side';
PROP_TYPE = 'type';
PROP_POST = 'post_only';
PROP_CREATE = 'created_at';
PROP_FEE = 'fill_fees';
PROP_FILL = 'filled_size';
PROP_EXEC = 'executed_value';
PROP_STATUS = 'status';
PROP_SETTLED = 'settled';
PROP_REJECT = 'reject_reason';
PROP_STOP = 'stop';
PROP_STOP_PRICE = 'stop_price';
PROP_STOP_ENTRY = 'entry';
PROP_STOP_LOSS = 'loss';
private
FProduct: IGDAXProduct;
FPostOnly: Boolean;
FSize: Extended;
FType: TOrderType;
FID: String;
FFillFees: Extended;
FFilledSize: Extended;
FExecutedValue: Extended;
FStatus: TOrderStatus;
FSettled: Boolean;
FSide: TOrderSide;
FPrice: Extended;
FRejectReason: String;
FCreatedAt: TDateTime;
FStop: Boolean;
protected
function GetCreatedAt: TDateTime;
function GetProduct: IGDAXProduct;
function GetStopOrder: Boolean;
procedure SetCreatedAt(Const AValue: TDateTime);
procedure SetProduct(Const Value: IGDAXProduct);
function GetPostOnly: Boolean;
procedure SetPostOnly(Const Value: Boolean);
function GetSize: Extended;
procedure SetSize(Const Value: Extended);
function GetOrderType: TOrderType;
procedure SetOrderType(Const Value: TOrderType);
function GetID: String;
procedure SetID(Const Value: String);
function GetFillFees: Extended;
procedure SetFillFees(Const Value: Extended);
function GetFilledSized: Extended;
procedure SetFilledSized(Const Value: Extended);
function GetExecutedValue: Extended;
procedure SetExecutedValue(Const Value: Extended);
function GetOrderStatus: TOrderStatus;
procedure SetOrderStatus(Const Value: TOrderStatus);
function GetSettled: Boolean;
procedure SetSettled(Const Value: Boolean);
function GetSide: TOrderSide;
procedure SetSide(Const Value: TOrderSide);
function GetPrice: Extended;
procedure SetPrice(Const Value: Extended);
function GetRejectReason: String;
procedure SetRejectReason(Const Value: String);
procedure SetStopOrder(Const AValue: Boolean);
protected
function DoGetPostBody: string; override;
function DoGet(Const AEndpoint: string; Const AHeaders: TStrings;
out Content: string; out Error: string): Boolean; override;
function DoPost(Const AEndPoint: string; Const AHeaders: TStrings;
Const ABody: string; out Content: string; out Error: string): Boolean;override;
function GetEndpoint(Const AOperation: TRestOperation): string; override;
function DoLoadFromJSON(Const AJSON: string; out Error: string): Boolean;override;
function DoGetSupportedOperations: TRestOperations; override;
function DoDelete(Const AEndpoint: string; Const AHeaders: TStrings;
out Content: string; out Error: string): Boolean; override;
public
property ID: String read GetID write SetID;
property Product: IGDAXProduct read GetProduct write SetProduct;
property OrderType: TOrderType read GetOrderType write SetOrderType;
property OrderStatus: TOrderStatus read GetOrderStatus write SetOrderStatus;
property Side: TOrderSide read GetSide write SetSide;
property PostOnly: Boolean read GetPostOnly write SetPostOnly;
property StopOrder: Boolean read GetStopOrder write SetStopOrder;
property Settled: Boolean read GetSettled write SetSettled;
property Size: Extended read GetSize write SetSize;
property Price: Extended read GetPrice write SetPrice;
property FillFees: Extended read GetFillFees write SetFillFees;
property FilledSized: Extended read GetFilledSized write SetFilledSized;
property ExecutedValue: Extended read GetExecutedValue write SetExecutedValue;
property RejectReason: String read GetRejectReason write SetRejectReason;
property CreatedAt: TDateTime read GetCreatedAt write SetCreatedAt;
constructor Create; override;
destructor Destroy; override;
end;
{ TGDAXOrdersImpl }
TGDAXOrdersImpl = class(TGDAXPagedApi,IGDAXOrders)
private
FOrders: TGDAXOrderList;
FStatuses: TOrderStatuses;
FProduct: IGDAXProduct;
function GetOrders: TGDAXOrderList;
function GetPaged: IGDAXPaged;
function GetStatuses: TOrderStatuses;
procedure SetStatuses(Const Value: TOrderStatuses);
function BuildQueryStringForStatus:String;
function GetProduct: IGDAXProduct;
procedure SetProduct(Const Value: IGDAXProduct);
protected
function DoGetSupportedOperations: TRestOperations; override;
function DoLoadFromJSON(Const AJSON: string;
out Error: string): Boolean;override;
function GetEndpoint(Const AOperation: TRestOperation): string; override;
function DoMove(Const ADirection: TGDAXPageDirection; out Error: String;
Const ALastBeforeID, ALastAfterID: Integer;
Const ALimit: TPageLimit=0): Boolean; override;
public
property Orders: TGDAXOrderList read GetOrders;
property Statuses: TOrderStatuses read GetStatuses write SetStatuses;
property Product: IGDAXProduct read GetProduct write SetProduct;
property Paged: IGDAXPaged read GetPaged;
constructor Create; override;
destructor Destroy; override;
end;
implementation
uses
SysUtils,
fpjson,
jsonparser,
fpindexer,
gdax.api.products;
{ TGDAXOrderImpl }
constructor TGDAXOrderImpl.Create;
begin
inherited;
FStatus := stUnknown;
FProduct := TGDAXProductImpl.Create;
FPostOnly := True;
FType := otLimit;
FSize:=0;
FID:='';
FFillFees:=0;
FFilledSize:=0;
FExecutedValue:=0;
FSettled := False;
FSide := osUnknown;
FPrice:=0;
FRejectReason:='';
FCreatedAt := Now;
FStop := False;
end;
destructor TGDAXOrderImpl.Destroy;
begin
FProduct := nil;
inherited;
end;
function TGDAXOrderImpl.DoDelete(Const AEndpoint: string; Const AHeaders: TStrings; out
Content: string; out Error: string): Boolean;
begin
Result := False;
try
if Trim(FID)='' then
begin
Error := Format(E_INVALID,['id','a long ass string']);
Exit;
end;
Result := inherited;
if not Result then
Exit;
except on E: Exception do
Error := E.Message;
end;
end;
function TGDAXOrderImpl.DoGet(Const AEndpoint: string; Const AHeaders: TStrings; out
Content: string; out Error: string): Boolean;
begin
Result := False;
if Trim(FID)='' then
begin
Error := Format(E_INVALID,['id','a long ass string']);
Exit;
end;
Result := inherited;
end;
function TGDAXOrderImpl.DoGetPostBody: string;
var
LJSON : TJSONObject;
LFunds: Extended;
LFundsDigits: Integer;
begin
Result:='';
LJSON := TJSONObject(GetJSON('{}'));
try
LFundsDigits := 8;
LJSON.Add(PROP_SIZE, FloatToStrF(FSize, TFloatFormat.ffFixed,15,8));
//specify price only for limit orders, otherwise market will require fund
if (FType = otLimit) then
LJSON.Add(PROP_PRICE, FloatToStrF(FPrice,TFloatFormat.ffFixed,15,8))
else
begin
LFunds := Trunc(FSize * FPrice / Product.BaseMinSize) * Product.BaseMinSize;
//not very elegant, but should save caller from "too specific" errors on cb
if Pos('usd', LowerCase(Product.QuoteCurrency)) > 0 then
LFundsDigits := 2;
//case when funds were specified but lower than min, so user probably
//just wants the minimum order (since they called market order in the first place)
if (LFunds < Product.MinMarketFunds) and (LFunds > 0) then
LFunds := Product.MinMarketFunds;
LJSON.Add(PROP_FUNDS, FloatToStrF(LFunds, TFloatFormat.ffFixed, 15, LFundsDigits));
end;
LJSON.Add(PROP_SIDE, OrderSideToString(FSide));
LJSON.Add(PROP_PROD, FProduct.ID);
if (FType = otLimit) and FPostOnly then
LJSON.Add(PROP_POST,FPostOnly);
LJSON.Add(PROP_TYPE,OrderTypeToString(FType));
if FStop then
begin
case FSide of
osBuy: LJSON.Add(PROP_STOP,PROP_STOP_ENTRY);
osSell: LJSON.Add(PROP_STOP,PROP_STOP_LOSS);
end;
LJSON.Add(PROP_STOP_PRICE,FloatToStrF(FPrice,TFloatFormat.ffFixed,15,8))
end;
Result := LJSON.AsJSON;
finally
LJSON.Free;
end;
end;
function TGDAXOrderImpl.DoGetSupportedOperations: TRestOperations;
begin
Result:=[roGet,roPost,roDelete];
end;
function TGDAXOrderImpl.DoLoadFromJSON(Const AJSON: string; out Error: string): Boolean;
var
LJSON : TJSONObject;
begin
Result := False;
try
LJSON := TJSONObject(GetJSON(AJSON));
if not Assigned(LJSON) then
raise Exception.Create(E_BADJSON);
try
//id is required in all situations
if LJSON.Find(PROP_ID) = nil then
begin
Error := Format(E_BADJSON_PROP,[PROP_ID]);
Exit;
end
else
FID := LJSON.Get(PROP_ID);
//Price per bitcoin (not required)
if LJSON.Find(PROP_PRICE) = nil then
FPrice:=0
else
FPrice := StrToFloat(LJSON.Get(PROP_PRICE));
//Amount of BTC to buy or sell
if LJSON.Find(PROP_SIZE) = nil then
begin
Error := Format(E_BADJSON_PROP,[PROP_SIZE]);
Exit;
end
else
FSize := StrToFloat(LJSON.Get(PROP_SIZE));
//product id is the type of currency
if LJSON.Find(PROP_PROD) = nil then
begin
Error := Format(E_BADJSON_PROP,[PROP_PROD]);
Exit;
end
else
FProduct.ID := LJSON.Get(PROP_PROD);
//side is buying or selling
if LJSON.Find(PROP_SIDE) = nil then
begin
Error := Format(E_BADJSON_PROP,[PROP_SIDE]);
Exit;
end
else
FSide := StringToOrderSide(LJSON.Get(PROP_SIDE));
//type of the order (limit/market)
if LJSON.Find(PROP_TYPE) = nil then
begin
Error := Format(E_BADJSON_PROP,[PROP_TYPE]);
Exit;
end
else
FType := StringToOrderType(LJSON.Get(PROP_TYPE));
//status of the order
if LJSON.Find(PROP_STATUS) = nil then
begin
Error := Format(E_BADJSON_PROP,[PROP_STATUS]);
Exit;
end
else
FStatus := StringToOrderStatus(LJSON.Get(PROP_STATUS));
//post only is for limit orders, but should still come back in response
if LJSON.Find(PROP_POST) = nil then
begin
Error := Format(E_BADJSON_PROP,[PROP_POST]);
Exit;
end
else
FPostOnly := LJSON.Get(PROP_POST);
//settled
if LJSON.Find(PROP_SETTLED) = nil then
begin
Error := Format(E_BADJSON_PROP,[PROP_SETTLED]);
Exit;
end
else
FSettled := LJSON.Get(PROP_SETTLED);
//fill fees
if LJSON.Find(PROP_FEE) = nil then
begin
Error := Format(E_BADJSON_PROP,[PROP_FEE]);
Exit;
end
else
FFillFees := StrToFloat(LJSON.Get(PROP_FEE));
//filled size is how much of size is actually filled
if LJSON.Find(PROP_FILL) = nil then
begin
Error := Format(E_BADJSON_PROP,[PROP_FILL]);
Exit;
end
else
FFilledSize := StrToFloat(LJSON.Get(PROP_FILL));
//executed value
if LJSON.Find(PROP_EXEC) = nil then
begin
Error := Format(E_BADJSON_PROP,[PROP_EXEC]);
Exit;
end
else
FExecutedValue := StrToFloat(LJSON.Get(PROP_EXEC));
//rejected reason may or may not be here
if LJSON.Find(PROP_REJECT) = nil then
FRejectReason:=''
else
FRejectReason := LJSON.Get(PROP_REJECT);
//create time in utc of the order
if LJSON.Find(PROP_CREATE) = nil then
begin
Error := Format(E_BADJSON_PROP,[PROP_CREATE]);
Exit;
end
else
FCreatedAt := fpindexer.ISO8601ToDate(LJSON.Get(PROP_CREATE));
Result := True;
finally
LJSON.Free;
end;
except on E: Exception do
Error := E.Message;
end;
end;
function TGDAXOrderImpl.DoPost(Const AEndPoint: string; Const AHeaders: TStrings;
Const ABody: string; out Content: string; out Error: string): Boolean;
begin
Result := False;
if FType=otUnknown then
begin
Error := Format(E_UNKNOWN,['order type',Self.ClassName]);
Exit;
end;
if FSide=TOrderSide.osUnknown then
begin
Error := Format(E_UNKNOWN,['order side',Self.ClassName]);
Exit;
end;
if FSize<=0 then
begin
Error := Format(E_INVALID,['size '+FloatToStr(FSize),'0.01 and 10000.0']);
Exit;
end;
if FProduct.ID.IsEmpty then
begin
Error := Format(E_UNKNOWN,['product',Self.ClassName]);
Exit;
end;
Result := inherited;
end;
function TGDAXOrderImpl.GetEndpoint(Const AOperation: TRestOperation): string;
begin
Result:='';
if (AOperation=roGet) or (AOperation=roDelete) then
Result := Format(GDAX_END_API_ORDER,[FID])
else if AOperation=roPost then
Result := GDAX_END_API_ORDERS
else if AOperation=roDelete then
Result := Format(GDAX_END_API_ORDER,[FID]);
end;
function TGDAXOrderImpl.GetExecutedValue: Extended;
begin
Result := FExecutedValue;
end;
function TGDAXOrderImpl.GetFilledSized: Extended;
begin
Result := FFilledSize;
end;
function TGDAXOrderImpl.GetFillFees: Extended;
begin
Result := FFillFees;
end;
function TGDAXOrderImpl.GetID: String;
begin
Result := FID;
end;
function TGDAXOrderImpl.GetOrderStatus: TOrderStatus;
begin
Result := FStatus;
//when an order is "done" and the settled propery is true, return
//that this order is "settled". this is done here, because the orderstatus
//won't get mapped correctly by name from cbpro since it's a separate bool
//property
if (Result = stDone) and FSettled then
Result := stSettled;
end;
function TGDAXOrderImpl.GetOrderType: TOrderType;
begin
Result := FType;
end;
function TGDAXOrderImpl.GetPostOnly: Boolean;
begin
Result := FPostOnly;
end;
function TGDAXOrderImpl.GetPrice: Extended;
begin
Result := FPrice;
end;
function TGDAXOrderImpl.GetProduct: IGDAXProduct;
begin
Result := FProduct;
end;
function TGDAXOrderImpl.GetStopOrder: Boolean;
begin
Result := FStop;
end;
function TGDAXOrderImpl.GetCreatedAt: TDateTime;
begin
Result := FCreatedAt;
end;
procedure TGDAXOrderImpl.SetCreatedAt(Const AValue: TDateTime);
begin
FCreatedAt := AValue;
end;
function TGDAXOrderImpl.GetRejectReason: String;
begin
Result := FRejectReason;
end;
function TGDAXOrderImpl.GetSettled: Boolean;
begin
Result := FSettled;
end;
function TGDAXOrderImpl.GetSide: TOrderSide;
begin
Result := FSide;
end;
function TGDAXOrderImpl.GetSize: Extended;
begin
Result := FSize;
end;
procedure TGDAXOrderImpl.SetExecutedValue(Const Value: Extended);
begin
FExecutedValue := Value;
end;
procedure TGDAXOrderImpl.SetFilledSized(Const Value: Extended);
begin
FFilledSize := Value;
end;
procedure TGDAXOrderImpl.SetFillFees(Const Value: Extended);
begin
FFillFees := Value;
end;
procedure TGDAXOrderImpl.SetID(Const Value: String);
begin
FID := Value;
end;
procedure TGDAXOrderImpl.SetOrderStatus(Const Value: TOrderStatus);
begin
FStatus := Value;
end;
procedure TGDAXOrderImpl.SetOrderType(Const Value: TOrderType);
begin
FType := Value;
end;
procedure TGDAXOrderImpl.SetPostOnly(Const Value: Boolean);
begin
FPostOnly := Value;
end;
procedure TGDAXOrderImpl.SetPrice(Const Value: Extended);
begin
FPrice := Value;
end;
procedure TGDAXOrderImpl.SetProduct(Const Value: IGDAXProduct);
begin
//free reference first
FProduct := nil;
FProduct := Value;
end;
procedure TGDAXOrderImpl.SetRejectReason(Const Value: String);
begin
FRejectReason := Value;
end;
procedure TGDAXOrderImpl.SetStopOrder(Const AValue: Boolean);
begin
FStop := AValue;
end;
procedure TGDAXOrderImpl.SetSettled(Const Value: Boolean);
begin
FSettled := Value;
end;
procedure TGDAXOrderImpl.SetSide(Const Value: TOrderSide);
begin
FSide := Value;
end;
procedure TGDAXOrderImpl.SetSize(Const Value: Extended);
begin
FSize := Value;
end;
{ TGDAXOrdersImpl }
function TGDAXOrdersImpl.BuildQueryStringForStatus: String;
Const
QUERY = '?status=%s';
QUERY_ADD = '&status=%s';
begin
Result:='';
if FStatuses=[] then
begin
Result := Format(QUERY,['all']);
Exit;
end;
if stPending in FStatuses then
Result := Format(Query,[OrderStatusToString(stPending)]);
if stOpen in FStatuses then
begin
if Result='' then
Result := Result+Format(QUERY,[OrderStatusToString(stOpen)])
else
Result := Result+Format(QUERY_ADD,[OrderStatusToString(stOpen)]);
end;
if stActive in FStatuses then
begin
if Result='' then
Result := Result+Format(QUERY,[OrderStatusToString(stActive)])
else
Result := Result+Format(QUERY_ADD,[OrderStatusToString(stActive)]);
end;
if stDone in FStatuses then
begin
if Result='' then
Result := Result+Format(QUERY,[OrderStatusToString(stDone)])
else
Result := Result+Format(QUERY_ADD,[OrderStatusToString(stDone)]);
end;
if stRejected in FStatuses then
begin
if Result='' then
Result := Result+Format(QUERY,[OrderStatusToString(stRejected)])
else
Result := Result+Format(QUERY_ADD,[OrderStatusToString(stRejected)]);
end;
end;
constructor TGDAXOrdersImpl.Create;
begin
inherited;
FProduct := TGDAXProductImpl.Create;
FOrders := TGDAXOrderList.Create;
end;
destructor TGDAXOrdersImpl.Destroy;
begin
FProduct := nil;
FOrders.Free;
inherited;
end;
function TGDAXOrdersImpl.DoGetSupportedOperations: TRestOperations;
begin
Result:=[roGet];
end;
function TGDAXOrdersImpl.DoLoadFromJSON(Const AJSON: string;
out Error: string): Boolean;
var
LJSON : TJSONObject;
I: Integer;
LOrder: IGDAXOrder;
begin
Result := False;
try
FOrders.Clear;
LJSON := TJSONObject(GetJSON(AJSON));
if not Assigned(LJSON) then
raise Exception.Create(E_BADJSON);
try
for I := 0 to Pred(LJSON.Count) do
begin
LOrder := TGDAXOrderImpl.Create;
//try to deserialzie order
if not LOrder.LoadFromJSON(TJSONObject(LJSON.Items[I]).AsJSON, Error) then
Exit;
FOrders.Add(LOrder);
end;
Result := True;
finally
LJSON.Free;
end;
except on E: Exception do
Error := E.Message;
end;
end;
function TGDAXOrdersImpl.GetEndpoint(Const AOperation: TRestOperation): string;
var
LMoving:String;
begin
Result:='';
//filters for statuses
Result := GDAX_END_API_ORDERS+BuildQueryStringForStatus;
//specific product
if not FProduct.ID.IsEmpty then
Result := Result+'&product_id='+FProduct.ID;
//paging params
LMoving := GetMovingParameters;
if LMoving.Length>0 then
Result := Result+LMoving;
end;
function TGDAXOrdersImpl.DoMove(Const ADirection: TGDAXPageDirection; out Error: String;
Const ALastBeforeID, ALastAfterID: Integer;
Const ALimit: TPageLimit): Boolean;
var
I:Integer;
LList:TGDAXOrderList;
begin
LList := TGDAXOrderList.Create;
try
try
//keep old orders on page move
LList.Assign(FOrders);
Result := inherited DoMove(ADirection, Error, ALastBeforeID,
ALastAfterID,ALimit
);
//add all the previous orders
for I:=0 to Pred(LList.Count) do
FOrders.Add(LList[I]);
except on E:Exception do
Error := E.Message;
end;
finally
LList.Free;
end;
end;
function TGDAXOrdersImpl.GetOrders: TGDAXOrderList;
begin
Result := FOrders;
end;
function TGDAXOrdersImpl.GetProduct: IGDAXProduct;
begin
Result := FProduct;
end;
function TGDAXOrdersImpl.GetStatuses: TOrderStatuses;
begin
Result := FStatuses;
end;
procedure TGDAXOrdersImpl.SetProduct(Const Value: IGDAXProduct);
begin
FProduct := Value;
end;
procedure TGDAXOrdersImpl.SetStatuses(Const Value: TOrderStatuses);
begin
FStatuses := Value;
end;
function TGDAXOrdersImpl.GetPaged: IGDAXPaged;
begin
Result := Self as IGDAXPaged;
end;
end.
|
{
DBAExplorer - Oracle Admin Management Tool
Copyright (C) 2008 Alpaslan KILICKAYA
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
}
unit frmRollbackSegmentProperties;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxMemo, cxRichEdit, cxLabel, cxContainer, cxEdit, cxTextEdit,
dxBar, cxPC, cxControls, StdCtrls, ExtCtrls, cxCheckBox, cxGraphics,
cxDropDownEdit, cxImageComboBox, cxMaskEdit, cxGroupBox, cxButtonEdit,
cxSpinEdit, GenelDM, OraRollbackSegment, VirtualTable, frmBaseform;
type
TRollbackSegmentPropertiesFrm = class(TBaseform)
Panel1: TPanel;
imgToolBar: TImage;
lblDescription: TLabel;
pcSequenceProperties: TcxPageControl;
tsRollbackSegmentDetails: TcxTabSheet;
dxBarDockControl1: TdxBarDockControl;
edtName: TcxTextEdit;
cxLabel1: TcxLabel;
cxLabel8: TcxLabel;
edtTablespace: TcxTextEdit;
tsSequenceScripts: TcxTabSheet;
redtDDL: TcxRichEdit;
dxBarManager1: TdxBarManager;
bbtnCreateRollbackSegment: TdxBarButton;
bbtnAlterRollbackSegment: TdxBarButton;
bbtnDropRollbackSegment: TdxBarButton;
bbtnRefreshRollbackSegment: TdxBarButton;
chkOnline: TcxCheckBox;
chkPublic: TcxCheckBox;
gbStorageClause: TcxGroupBox;
Label11: TLabel;
Label12: TLabel;
Label13: TLabel;
Label14: TLabel;
edtInitialExtend: TcxButtonEdit;
edtNextExtend: TcxButtonEdit;
edtMinExtents: TcxSpinEdit;
edtMaxExtents: TcxSpinEdit;
bbtnTakeOffRollbackSegment: TdxBarButton;
bbtnTakeOnRollbackSegment: TdxBarButton;
procedure bbtnCreateRollbackSegmentClick(Sender: TObject);
procedure bbtnAlterRollbackSegmentClick(Sender: TObject);
procedure bbtnDropRollbackSegmentClick(Sender: TObject);
procedure bbtnTakeOnRollbackSegmentClick(Sender: TObject);
procedure bbtnTakeOffRollbackSegmentClick(Sender: TObject);
private
{ Private declarations }
FSegmentName : string;
RollbackSegment: TRollbackSegment;
procedure GetRollbackSegment;
procedure GetRollbackSegmentDetail;
public
{ Public declarations }
procedure Init(ObjName, OwnerName: string); override;
end;
var
RollbackSegmentPropertiesFrm: TRollbackSegmentPropertiesFrm;
implementation
{$R *.dfm}
uses frmSchemaBrowser, Util, OraStorage, frmSchemaPublicEvent,
frmRollbackSegmentDetail, VisualOptions;
procedure TRollbackSegmentPropertiesFrm.Init(ObjName, OwnerName: string);
begin
inherited Show;
DMGenel.ChangeLanguage(self);
ChangeVisualGUI(self);
top := 0;
left := 0;
FSegmentName := ObjName;
GetRollbackSegment;
end;
procedure TRollbackSegmentPropertiesFrm.GetRollbackSegment;
begin
if RollbackSegment <> nil then
FreeAndNil(RollbackSegment);
RollbackSegment := TRollbackSegment.Create;
RollbackSegment.OraSession := TSchemaBrowserFrm(Application.MainForm.ActiveMDIChild).OraSession;
RollbackSegment.SEGMENT_NAME := FSegmentName;
RollbackSegment.SetDDL;
lblDescription.Caption := FSegmentName;
GetRollbackSegmentDetail;
redtDDL.Text := RollbackSegment.GetDDL;
CodeColors(self, 'Default', redtDDL, false);
end;
procedure TRollbackSegmentPropertiesFrm.GetRollbackSegmentDetail;
begin
with RollbackSegment do
begin
edtName.Text := SEGMENT_NAME;
edtTablespace.Text := TABLESPACE_NAME;
chkOnline.Checked := STATUS = 'ONLINE';
chkPublic.Checked := PUBLIC;
edtInitialExtend.Text := FloatToStr(INITIAL_EXTENT);
edtNextExtend.Text := FloatToStr(NEXT_EXTENT);
edtMinExtents.Text := FloatToStr(MIN_EXTENTS);
edtMaxExtents.Text := FloatToStr(MAX_EXTENTS);
end;
end;
procedure TRollbackSegmentPropertiesFrm.bbtnCreateRollbackSegmentClick(
Sender: TObject);
var
FRollbackSegment : TRollbackSegment;
begin
FRollbackSegment := TRollbackSegment.Create;
FRollbackSegment.OraSession := RollbackSegment.OraSession;
FRollbackSegment.Mode := InsertMode;
if RollbackSegmentDetailFrm.Init(FRollbackSegment) then
TSchemaBrowserFrm(Application.MainForm.ActiveMDIChild).RefreshNode(dbRollbackSegments);
end;
procedure TRollbackSegmentPropertiesFrm.bbtnAlterRollbackSegmentClick(
Sender: TObject);
begin
if RollbackSegment = nil then exit;
RollbackSegment.Mode := UpdateMode;
if RollbackSegmentDetailFrm.Init(RollbackSegment) then
TSchemaBrowserFrm(Application.MainForm.ActiveMDIChild).RefreshNode(dbRollbackSegments);
end;
procedure TRollbackSegmentPropertiesFrm.bbtnDropRollbackSegmentClick(
Sender: TObject);
begin
if RollbackSegment = nil then exit;
if RollbackSegment.SEGMENT_NAME = '' then exit;
if SchemaPublicEventFrm.Init(RollbackSegment, oeDrop) then
TSchemaBrowserFrm(Application.MainForm.ActiveMDIChild).RefreshNode(dbRollbackSegments);
end;
procedure TRollbackSegmentPropertiesFrm.bbtnTakeOnRollbackSegmentClick(
Sender: TObject);
begin
if RollbackSegment = nil then exit;
if RollbackSegment.SEGMENT_NAME = '' then exit;
if SchemaPublicEventFrm.Init(RollbackSegment, oeOnLine) then
TSchemaBrowserFrm(Application.MainForm.ActiveMDIChild).RefreshNode(dbRollbackSegments);
end;
procedure TRollbackSegmentPropertiesFrm.bbtnTakeOffRollbackSegmentClick(
Sender: TObject);
begin
if RollbackSegment = nil then exit;
if RollbackSegment.SEGMENT_NAME = '' then exit;
if SchemaPublicEventFrm.Init(RollbackSegment, oeOffLine) then
TSchemaBrowserFrm(Application.MainForm.ActiveMDIChild).RefreshNode(dbRollbackSegments);
end;
end.
|
unit Thread.ImportarPedidosSIMExpress;
interface
uses
System.Classes, Control.Entregas, Control.PlanilhaEntradaSIMExpress, System.SysUtils, System.DateUtils, Control.VerbasExpressas,
Control.Bases, Control.EntregadoresExpressas, Generics.Collections, System.StrUtils;
type
TThread_ImportarPedidosSIMExpress = class(TThread)
private
{ Private declarations }
FPlanilha: TPlanilhaEntradaSimExpressControl;
FEntregas: TEntregasControl;
FVerbas: TVerbasExpressasControl;
FBases: TBasesControl;
FEntregadores: TEntregadoresExpressasControl;
protected
procedure Execute; override;
procedure UpdateLOG(sMensagem: string);
procedure UpdateProgress(dPosition: Double);
procedure BeginProcesso;
procedure TerminateProcess;
function RetornaVerba(aParam: array of variant): double;
public
FFile: String;
iCodigoCliente: Integer;
bCancel : Boolean;
bProcess: Boolean;
dPositionRegister: double;
sLog: String;
sAlerta: 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 TThread_ImportarPedidosSIMExpress.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.
}
uses Common.ENum, Global.Parametros;
{ TThread_ImportarPedidosSIMExpress }
procedure TThread_ImportarPedidosSIMExpress.BeginProcesso;
var
sMensagem: String;
begin
sLog := '';
bCancel := False;
Global.Parametros.pbProcess := True;
sMensagem := '';
sMensagem := '>> ' + FormatDateTime('dd/mm/yyyy hh:mm:ss', Now) + ' > iniciando importação do arquivo ' + FFile;
UpdateLog(sMensagem);
sMensagem := '>> ' + FormatDateTime('dd/mm/yyyy hh:mm:ss', Now) + ' > tratando os dados da planilha. Aguarde...';
UpdateLog(sMensagem);
end;
procedure TThread_ImportarPedidosSIMExpress.Execute;
var
FEntregadores : TEntregadoresExpressasControl;
aParam: Array of variant;
iPos, iPosition, iTotal, iTabela, iFaixa, iAgente, iEntregador,i: Integer;
sCEP, sMensagem: String;
dPos, dPerformance, dVerba, dVerbaTabela: double;
slParam: TStringList;
bProcess: Boolean;
begin
try
try
Synchronize(BeginProcesso);
FPlanilha := TPlanilhaEntradaSIMExpressControl.Create;
FEntregas := TEntregasControl.Create;
sMensagem := FormatDateTime('yyyy/mm/dd hh:mm:ss', Now) + ' importando os dados. Aguarde...';
UpdateLog(sMensagem);
if FPLanilha.GetPlanilha(FFile) then
begin
iPos := 0;
iPosition := 0;
dPos := 0;
iTotal := FPlanilha.Planilha.Planilha.Count;
for i := 0 to Pred(iTotal) do
begin
SetLength(aParam,3);
aParam := ['NNCLIENTE', FPlanilha.Planilha.Planilha[i].IDPedido, iCodigoCliente];
if not FEntregas.LocalizarExata(aParam) then
begin
FEntregas.Entregas.Acao := tacIncluir;
end
else
begin
FEntregas.Entregas.Acao := tacAlterar;
end;
FEntregadores := TEntregadoresExpressasControl.Create;
Finalize(aParam);
SetLength(aParam,3);
aParam := ['CHAVECLIENTE',FPlanilha.Planilha.Planilha[i].IdMotorista,iCodigoCliente];
if not FEntregadores.LocalizarExato(aParam) then
begin
sMensagem := FormatDateTime('yyyy/mm/dd hh:mm:ss', Now) + ' entregador não encontrado ' + FPlanilha.Planilha.Planilha[i].Motorista;
UpdateLog(sMensagem);
FEntregas.Entregas.Distribuidor := 1;
FEntregas.Entregas.Entregador := 781;
end
else
begin
FEntregas.Entregas.Distribuidor := FEntregadores.Entregadores.Agente;
FEntregas.Entregas.Entregador := Fentregadores.Entregadores.Entregador;
end;
Finalize(aParam);
FEntregadores.Free;
FEntregas.Entregas.Cliente := 0;
FEntregas.Entregas.NN := FPlanilha.Planilha.Planilha[i].IDPedido;
FEntregas.Entregas.NF := FPlanilha.Planilha.Planilha[I].NF;
FEntregas.Entregas.Consumidor := LeftStr(FPlanilha.Planilha.Planilha[I].Destinatario,70);
FEntregas.Entregas.Retorno := FormatFloat('00000000000', StrToIntDef(FPlanilha.Planilha.Planilha[i].NREntrega,0));
FEntregas.Entregas.Endereco := LeftStr(FPlanilha.Planilha.Planilha[I].Endereco,70);
FEntregas.Entregas.Complemento := '';
FEntregas.Entregas.Bairro := LeftStr(FPlanilha.Planilha.Planilha[I].Bairro, 70);
FEntregas.Entregas.Cidade := LeftStr(FPlanilha.Planilha.Planilha[I].Municipio,70);
FEntregas.Entregas.Cep := FPlanilha.Planilha.Planilha[I].CEP;
FEntregas.Entregas.Telefone := '';
if FPlanilha.Planilha.Planilha[I].Coleta <> '00/00/0000' then FEntregas.Entregas.Expedicao := StrToDate(FPlanilha.Planilha.Planilha[I].Coleta);
FEntregas.Entregas.Previsao := StrToDate(FPlanilha.Planilha.Planilha[I].Viagem);
FEntregas.Entregas.Status := 909;
if FPlanilha.Planilha.Planilha[i].Ocorrencia = 'REALIZADA' then
begin
FEntregas.Entregas.Baixa := StrToDate(FPlanilha.Planilha.Planilha[i].DataEntrega);
FEntregas.Entregas.Entrega := StrToDate(FPlanilha.Planilha.Planilha[i].DataEntrega);
FEntregas.Entregas.Baixado := 'S';
if FEntregas.Entregas.Previsao < FEntregas.Entregas.Entrega then
begin
FEntregas.Entregas.Atraso := DaysBetween(FEntregas.Entregas.Previsao,FEntregas.Entregas.Entrega);
end
else
begin
FEntregas.Entregas.Atraso := 0;
end;
SetLength(aParam,7);
aParam := [FEntregas.Entregas.Distribuidor, FEntregas.Entregas.Entregador, FEntregas.Entregas.CEP,
FEntregas.Entregas.PesoReal, FEntregas.Entregas.Baixa, 0, 0];
FEntregas.Entregas.VerbaEntregador := RetornaVerba(aParam);
Finalize(aParam);
if FEntregas.Entregas.VerbaEntregador = 0 then
begin
sMensagem := 'Verba do NN ' + FEntregas.Entregas.NN + ' do entregador ' +
FPlanilha.Planilha.Planilha[i].Motorista + ' não atribuida !';
UpdateLog(sMensagem);
end;
end
else
begin
FEntregas.Entregas.Baixado := 'N';
end;
FEntregas.Entregas.VerbaFranquia := 0;
FEntregas.Entregas.PesoReal := StrToFloatDef(FPlanilha.Planilha.Planilha[I].Peso,0);
FEntregas.Entregas.PesoCobrado := StrToFloatDef(FPlanilha.Planilha.Planilha[I].Peso,0);
FEntregas.Entregas.Volumes := StrToInt(FPlanilha.Planilha.Planilha[I].Volumes);
FEntregas.Entregas.VolumesExtra := 0;
FEntregas.Entregas.ValorVolumes := 0;
FEntregas.Entregas.Atraso := 0;
FEntregas.Entregas.Container := '0';
FEntregas.Entregas.ValorProduto := StrToFloatDef(FPlanilha.Planilha.Planilha[I].Valor,0);
FEntregas.Entregas.Atribuicao := StrToDate(FPlanilha.Planilha.Planilha[I].Viagem);
FEntregas.Entregas.Altura := 0;
FEntregas.Entregas.Largura := 0;
FEntregas.Entregas.Comprimento := 0;
FEntregas.Entregas.Rastreio := '> ' + FormatDateTime('yyyy/mm/dd hh:mm:ss', Now) + ' inserido por importação por ' +
Global.Parametros.pUser_Name;
FEntregas.Entregas.Pedido := FPlanilha.Planilha.Planilha[I].Pedido;
FEntregas.Entregas.CodCliente := iCodigoCliente;
if not FEntregas.Gravar() then
begin
sMensagem := 'Erro ao gravar o NN ' + FEntregas.Entregas.NN + ' !';
UpdateLog(sMensagem);
end;
inc(iPos, 1);
dPos := (iPos / iTotal) * 100;
if not(Self.Terminated) then
begin
UpdateProgress(dPos);
end
else
begin
Abort;
end;
end;
Synchronize(TerminateProcess);
end
else
begin
sMensagem := FPlanilha.Planilha.Mensagem;
bCancel := True;
end;
Except on E: Exception do
begin
sMensagem := '** ERROR **' + Chr(13) + 'Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message;
UpdateLog(sMensagem);
bCancel := True;
end;
end;
finally
FPlanilha.Free;
FEntregas.Free;
end;
end;
function TThread_ImportarPedidosSIMExpress.RetornaVerba(aParam: array of variant): double;
var
FBase: TBasesControl;
FEntregador: TEntregadoresExpressasControl;
FVerbas: TVerbasExpressasControl;
iTabela, iFaixa: Integer;
dVerba, dVerbaEntregador: Double;
FParam: array of variant;
FTipoVerba: array of string;
begin
try
Result := 0;
iTabela := 0;
iFaixa := 0;
dVerba := 0;
dVerbaEntregador := 0;
SetLength(FTipoVerba,8);
//cria um array com as formas de pesquisa da classe
FTipoVerba := ['NONE','FIXA','FIXACEP','FIXAPESO','SLA','CEPPESO','ROTEIROFIXA','ROTEIROPESO'];
// procura dos dados da base referentes à verba
FBase := TBasesControl.Create;
SetLength(FParam,2);
FParam := ['CODIGO',aParam[0]];
if FBase.LocalizarExato(FParam) then
begin
iTabela := FBase.Bases.Tabela;
iFaixa := FBase.Bases.Grupo;
dVerba := FBase.Bases.ValorVerba;
end;
Finalize(FParam);
FBase.Free;
// se a base não possui uma verba fixa, verifica se a base possui uma vinculação a uma
// tabela e faixa.
if dVerba = 0 then
begin
if iTabela <> 0 then
begin
if iFaixa <> 0 then
begin
FVerbas := TVerbasExpressasControl.Create;
FVerbas.Verbas.Tipo := iTabela;
FVerbas.Verbas.Cliente := iCodigoCliente;
FVerbas.Verbas.Grupo := iFaixa;
FVerbas.Verbas.Vigencia := aParam[4];
FVerbas.Verbas.CepInicial := aParam[2];
FVerbas.Verbas.PesoInicial := aParam[3];
FVerbas.Verbas.Roteiro := aParam[5];
FVerbas.Verbas.Performance := aParam[6];
dVerba := FVerbas.RetornaVerba();
FVerbas.Free;
end;
end;
end;
// pesquisa a tabela de entregadores e apanha os dados referente à verba
if dVerba = 0 then
begin
FEntregador := TEntregadoresExpressasControl.Create;
SetLength(FParam,2);
FParam := ['ENTREGADOR', aParam[1]];
if not Fentregador.Localizar(FParam).IsEmpty then
begin
iTabela := FEntregador.Entregadores.Tabela;
iFaixa := FEntregador.Entregadores.Grupo;
dVerbaEntregador := FEntregador.Entregadores.Verba;
end;
Finalize(FParam);
FEntregador.Free;
// verifica se o entregador possui uma verba fixa, se estiver zerada, verifica com as informações
// de tabela e faixa.
if dVerbaEntregador = 0 then
begin
if iTabela <> 0 then
begin
if iFaixa <> 0 then
begin
FVerbas := TVerbasExpressasControl.Create;
FVerbas.Verbas.Tipo := iTabela;
FVerbas.Verbas.Cliente := iCodigoCliente;
FVerbas.Verbas.Grupo := iFaixa;
FVerbas.Verbas.Vigencia := aParam[4];
FVerbas.Verbas.CepInicial := aParam[2];
FVerbas.Verbas.PesoInicial := aParam[3];
FVerbas.Verbas.Roteiro := aParam[5];
FVerbas.Verbas.Performance := aParam[6];
dVerbaEntregador := FVerbas.RetornaVerba();
FVerbas.Free;
end;
end;
end;
if dVerbaEntregador > 0 then
begin
dVerba := dVerbaEntregador;
end;
end;
Result := dVerba;
finally
Finalize(FTipoVerba);
end;
end;
procedure TThread_ImportarPedidosSIMExpress.TerminateProcess;
begin
Global.Parametros.pbProcess := False;
end;
procedure TThread_ImportarPedidosSIMExpress.UpdateLOG(sMensagem: string);
begin
if Global.Parametros.psLog <> '' then
begin
Global.Parametros.psLog := Global.Parametros.psLog + #13;
end;
Global.Parametros.psLog := Global.Parametros.psLog + sMensagem;
end;
procedure TThread_ImportarPedidosSIMExpress.UpdateProgress(dPosition: Double);
begin
Global.Parametros.pdPos := dPosition;
end;
end.
|
unit fmMain;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, uEventAgg, uEvents, uModel;
type
TfrmMain = class(TForm)
Edit5: TEdit;
Edit6: TEdit;
Edit7: TEdit;
Edit8: TEdit;
btnPrev: TButton;
btnNext: TButton;
btnBarChart: TButton;
btnGrid: TButton;
btnPieChart: TButton;
procedure FormCreate(Sender: TObject);
procedure btnPrevClick(Sender: TObject);
procedure btnNextClick(Sender: TObject);
procedure btnBarChartClick(Sender: TObject);
procedure btnGridClick(Sender: TObject);
procedure Edit5Exit(Sender: TObject);
procedure btnPieChartClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
FCurrent: TReportCard;
procedure UpdateForm(const aPublisher: TObject; const anEvent: TEventClass);
procedure UpdateModel;
end;
var
frmMain: TfrmMain;
implementation
uses dmController, fmBarChart, fmGrid, fmPieChart;
{$R *.dfm}
procedure TfrmMain.FormCreate(Sender: TObject);
begin
FCurrent := nil;
UpdateForm(dtmController.Current, TReportCardNav);
EA.Subscribe(UpdateForm, TReportCardEvent);
end;
procedure TfrmMain.FormDestroy(Sender: TObject);
begin
EA.Unsubscribe(UpdateForm);
end;
procedure TfrmMain.btnPrevClick(Sender: TObject);
begin
dtmController.Prev;
end;
procedure TfrmMain.btnNextClick(Sender: TObject);
begin
dtmController.Next;
end;
procedure TfrmMain.Edit5Exit(Sender: TObject);
begin
if TEdit(Sender).Modified then
UpdateModel;
end;
procedure TfrmMain.UpdateModel;
begin
dtmController.Current.BeginUpdate;
try
dtmController.Current.Name := Edit5.Text;
dtmController.Current.ScoreA := StrToInt(Edit6.Text);
dtmController.Current.ScoreB := StrToInt(Edit7.Text);
dtmController.Current.ScoreC := StrToInt(Edit8.Text);
finally
dtmController.Current.EndUpdate;
end;
end;
procedure TfrmMain.UpdateForm(const aPublisher: TObject; const anEvent: TEventClass);
begin
if anEvent.InheritsFrom(TReportCardNav) then
FCurrent := TReportCard(aPublisher);
if aPublisher = FCurrent then
begin
Edit5.Text := FCurrent.Name;
Edit6.Text := IntToStr(FCurrent.ScoreA);
Edit7.Text := IntToStr(FCurrent.ScoreB);
Edit8.Text := IntToStr(FCurrent.ScoreC);
end;
end;
procedure TfrmMain.btnPieChartClick(Sender: TObject);
var
NewChart: TfrmPieChart;
begin
NewChart := TfrmPieChart.Create(Self);
NewChart.Show;
end;
procedure TfrmMain.btnBarChartClick(Sender: TObject);
var
NewBarChart: TfrmBarChart;
begin
NewBarChart := TfrmBarChart.Create(Self);
NewBarChart.Show;
end;
procedure TfrmMain.btnGridClick(Sender: TObject);
var
NewGrid: TfrmGrid;
begin
NewGrid := TfrmGrid.Create(Self);
NewGrid.Show;
end;
end.
|
unit Main;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, uniGUIBaseClasses, uniGUIClasses,
uniButton, Vcl.StdCtrls, Vcl.ExtCtrls;
type
TMainForm = class(TForm)
Panel1: TPanel;
Button1: TButton;
ListBox1: TListBox;
Panel2: TPanel;
Button2: TButton;
ListBox2: TListBox;
Panel3: TPanel;
Button3: TButton;
ListBox3: TListBox;
Panel4: TPanel;
Button4: TButton;
ListBox4: TListBox;
procedure Button1Click(Sender: TObject);
procedure ListBox1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure Button4Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
MainForm: TMainForm;
implementation
{$R *.dfm}
procedure TMainForm.Button1Click(Sender: TObject);
var
valores: array[1..5] of Integer;
i, soma: Integer;
begin
// vamos preencher o array com os valores de 1 a 5
for i := 1 to 5 do
begin
valores[i] := i;
end;
// vamos percorrer o array novamente e obter a soma dos
// valores de seus elementos
soma := 0;
for i := 1 to 5 do
begin
soma := soma + valores[i];
end;
// vamos exibir o resultado
ListBox1.Items.Add('A soma dos valores é: ' + IntToStr(soma))
// ShowMessage('A soma dos valores é: ' + IntToStr(soma));
end;
procedure TMainForm.Button2Click(Sender: TObject);
var
valores: array[1..10] of Integer;
begin
valores[5] := 20;
ListBox2.Items.Add('O valo é: '+IntToStr(valores[5]) );
end;
procedure TMainForm.Button3Click(Sender: TObject);
const
valores: array[1..5] of Integer = (3, 2, 6, 12, 9);
var
i, soma: Integer;
begin
// vamos percorrer o array novamente e obter a soma dos
// valores de seus elementos
soma := 0;
for i := 1 to 5 do
begin
soma := soma + valores[i];
end;
// vamos exibir o resultado
ListBox3.Items.Add('A soma dos valores é:: '+IntToStr(soma) );
end;
procedure TMainForm.Button4Click(Sender: TObject);
const
letras: array[1..5] of Char = ('O', 's', 'm', 'a', 'r');
var
i: Integer;
resultado: String;
begin
resultado := '';
// vamos exibir a palavra na forma normal
for i := 1 to 5 do
resultado := resultado + letras[i];
// exibe o resultado
ListBox4.Items.Add((resultado));
// vamos exibir a palavra invertida
resultado := '';
for i := 5 downto 1 do
resultado := resultado + letras[i];
// exibe o resultado
ListBox4.Items.Add((resultado));
end;
procedure TMainForm.ListBox1Click(Sender: TObject);
begin
ListBox1.Items.Delete( ListBox1.ItemIndex );
end;
end.
|
{ ***************************************************************************
Copyright (c) 2015-2019 Kike Pérez
Unit : Quick.Config.YAML
Description : Save config to YAML file
Author : Kike Pérez
Version : 1.0
Created : 12/04/2019
Modified : 27/04/2019
This file is part of QuickLib: https://github.com/exilon/QuickLib
***************************************************************************
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*************************************************************************** }
unit Quick.Config.YAML;
{$i QuickLib.inc}
interface
uses
Classes,
SysUtils,
{$IFDEF DELPHIXE_UP}
IOUtils,
{$ELSE}
Quick.Files,
{$ENDIF}
Rtti,
Quick.YAML.Serializer,
Quick.FileMonitor,
Quick.Config.Base;
type
TFileModifiedEvent = procedure of object;
TLoadConfigEvent = procedure of object;
{$IFNDEF FPC}
TNotSerializableProperty = Quick.YAML.Serializer.TNotSerializableProperty;
TCommentProperty = Quick.YAML.Serializer.TCommentProperty;
TCustomNameProperty = Quick.YAML.Serializer.TCustomNameProperty;
{$ENDIF}
TAppConfigYMALProvider = class(TAppConfigProvider)
private
fFilename : string;
fFileMonitor : TFileMonitor;
fOnFileModified : TFileModifiedEvent;
fLoaded : Boolean;
fReloadIfFileChanged : Boolean;
fOnConfigLoaded : TLoadConfigEvent;
fOnConfigReloaded : TLoadConfigEvent;
fNotifyReload : TLoadConfigEvent;
procedure CreateFileMonitor;
procedure FileModifiedNotify(MonitorNotify : TMonitorNotify);
procedure SetFileName(const Value: string);
procedure SetReloadIfFileChanged(const Value: Boolean);
procedure SetReloadNotify(aNotifyReload : TLoadConfigEvent);
procedure DoNofifyReload;
protected
procedure Load(cConfig : TAppConfig); override;
procedure Save(cConfig : TAppConfig); override;
public
constructor Create(const aFilename : string; aReloadIfFileChanged : Boolean = False); overload;
destructor Destroy; override;
property Filename : string read fFilename write SetFileName;
property ReloadIfFileChanged : Boolean read fReloadIfFileChanged write SetReloadIfFileChanged;
property IsLoaded : Boolean read fLoaded;
property OnFileModified : TFileModifiedEvent read fOnFileModified write fOnFileModified;
property OnConfigLoaded : TLoadConfigEvent read fOnConfigLoaded write fOnConfigLoaded;
property OnConfigReloaded : TLoadConfigEvent read fOnConfigReloaded write fOnConfigReloaded;
end;
TAppConfigYAML = class(TAppConfig)
private
function GetProvider : TAppConfigYMALProvider;
procedure ReloadNotify;
public
constructor Create(const aFilename : string; aReloadIfFileChanged : Boolean = False);
destructor Destroy; override;
property Provider : TAppConfigYMALProvider read GetProvider;
function ToYAML : string;
procedure FromYAML(const yaml : string);
end;
{Usage: create a descend class from TAppConfigYAML and add published properties to be loaded/saved
TMyConfig = class(TAppConfigYAML)
private
fName : string;
fSurname : string;
fStatus : Integer;
published
property Name : string read fName write fName;
property SurName : string read fSurname write fSurname;
property Status : Integer read fStatus write fStatus;
end;
MyConfig := TMyConfig.Create;
MyConfig.Provider.FileName := '.\MyAppName.yml';
MyConfig.Name := 'John';
MyConfig.Save;
}
implementation
constructor TAppConfigYMALProvider.Create(const aFilename : string; aReloadIfFileChanged : Boolean = False);
begin
inherited Create;
if aFilename = '' then fFilename := TPath.ChangeExtension(ParamStr(0),'yml')
else fFilename := aFilename;
fLoaded := False;
fReloadIfFileChanged := aReloadIfFileChanged;
if aReloadIfFileChanged then CreateFileMonitor;
end;
procedure TAppConfigYMALProvider.CreateFileMonitor;
begin
fFileMonitor := TQuickFileMonitor.Create;
fFileMonitor.FileName := fFilename;
fFileMonitor.Interval := 2000;
fFileMonitor.Notifies := [TMonitorNotify.mnFileModified];
fFileMonitor.OnFileChange := FileModifiedNotify;
fFileMonitor.Enabled := True;
end;
destructor TAppConfigYMALProvider.Destroy;
begin
if Assigned(fFileMonitor) then fFileMonitor.Free;
inherited;
end;
procedure TAppConfigYMALProvider.DoNofifyReload;
begin
if Assigned(fNotifyReload) then fNotifyReload
else raise EAppConfig.Create('Not config assigned to reload!');
end;
procedure TAppConfigYMALProvider.FileModifiedNotify(MonitorNotify : TMonitorNotify);
begin
if MonitorNotify = TMonitorNotify.mnFileModified then
begin
if Assigned(fOnFileModified) then fOnFileModified;
if fReloadIfFileChanged then DoNofifyReload;
end;
end;
procedure TAppConfigYMALProvider.Load(cConfig : TAppConfig);
var
yaml : TStrings;
serializer : TYamlSerializer;
begin
if (not FileExists(fFilename)) and (CreateIfNotExists) then
begin
TAppConfig(cConfig).DefaultValues;
Self.Save(cConfig);
end;
try
yaml := TStringList.Create;
try
yaml.LoadFromFile(fFilename);
if yaml.Count > 0 then
begin
serializer := TYamlSerializer.Create(slPublishedProperty,UseEnumNames);
try
//Streamer.Options := Streamer.Options + [jsoDateTimeAsString ,jsoUseFormatString];
//Streamer.DateTimeFormat := 'yyyy-mm-dd"T"hh:mm:ss.zz';
serializer.YamlToObject(cConfig,yaml.Text);
finally
serializer.Free;
end;
end else
TAppConfig(cConfig).DefaultValues;
finally
yaml.Free;
end;
if not fLoaded then
begin
fLoaded := True;
if Assigned(fOnConfigLoaded) then fOnConfigLoaded;
end
else if Assigned(fOnConfigReloaded) then fOnConfigReloaded;
except
on e : Exception do raise EAppConfig.Create(e.Message);
end;
end;
procedure TAppConfigYMALProvider.Save(cConfig : TAppConfig);
var
yaml : TStrings;
Serializer : TYamlSerializer;
begin
if not Assigned(cConfig) then cConfig := TAppConfigYAML.Create(fFilename,fReloadIfFileChanged);
try
yaml := TStringList.Create;
try
serializer := TYamlSerializer.Create(TSerializeLevel.slPublishedProperty,UseEnumNames);
try
//Streamer.Options := Streamer.Options + [jsoDateTimeAsString ,jsoUseFormatString];
//Streamer.DateTimeFormat := 'yyyy-mm-dd"T"hh:mm:ss.zz';
yaml.Text := serializer.ObjectToYaml(cConfig);
finally
serializer.Free;
end;
yaml.SaveToFile(fFilename);
finally
yaml.Free;
end;
except
on e : Exception do raise EAppConfig.Create(e.Message);
end;
end;
procedure TAppConfigYMALProvider.SetFileName(const Value: string);
begin
fFilename := Value;
if Assigned(fFileMonitor) then fFileMonitor.Free;
if fReloadIfFileChanged then CreateFileMonitor;
end;
procedure TAppConfigYMALProvider.SetReloadIfFileChanged(const Value: Boolean);
begin
if Value = fReloadIfFileChanged then Exit;
fReloadIfFileChanged := Value;
if Assigned(fFileMonitor) then fFileMonitor.Free;
if fReloadIfFileChanged then CreateFileMonitor;
end;
procedure TAppConfigYMALProvider.SetReloadNotify(aNotifyReload: TLoadConfigEvent);
begin
fNotifyReload := aNotifyReload;
end;
{ TAppConfigYAML }
constructor TAppConfigYAML.Create(const aFilename : string; aReloadIfFileChanged : Boolean = False);
begin
inherited Create(TAppConfigYMALProvider.Create(aFileName,aReloadIfFileChanged));
TAppConfigYMALProvider(fProvider).SetReloadNotify(ReloadNotify);
end;
destructor TAppConfigYAML.Destroy;
begin
inherited;
end;
function TAppConfigYAML.GetProvider: TAppConfigYMALProvider;
begin
if not Assigned(fProvider) then raise EAppConfig.Create('No provider assigned!');
Result := TAppConfigYMALProvider(fProvider);
end;
procedure TAppConfigYAML.ReloadNotify;
begin
Self.Load;
end;
function TAppConfigYAML.ToYAML: string;
var
serializer : TYamlSerializer;
begin
serializer := TYamlSerializer.Create(slPublishedProperty,fProvider.UseEnumNames);
try
Result := serializer.ObjectToYaml(Self);
finally
serializer.Free;
end;
end;
procedure TAppConfigYAML.FromYAML(const yaml: string);
var
serializer : TYamlSerializer;
begin
serializer := TYamlSerializer.Create(slPublishedProperty,fProvider.UseEnumNames);
try
serializer.YamlToObject(Self,yaml);
finally
serializer.Free;
end;
end;
end.
|
unit LS.ServiceModule;
interface
uses
System.SysUtils, System.Classes, System.Android.Service, System.Sensors, System.Notification,
Androidapi.JNI.App, AndroidApi.JNI.GraphicsContentViewText, Androidapi.JNI.Os, Androidapi.JNIBridge,
AndroidApi.JNI.JavaTypes,
DW.FileWriter, DW.MultiReceiver.Android, DW.Location.Android,
LS.AndroidTimer, LS.Config;
type
TServiceModule = class;
/// <summary>
/// Acts as a receiver of broadcasts sent by Android
/// </summary>
TServiceReceiver = class(TMultiReceiver)
private
FService: TServiceModule;
protected
procedure ConfigureActions; override;
procedure Receive(context: JContext; intent: JIntent); override;
public
constructor Create(const AService: TServiceModule);
end;
/// <summary>
/// Acts as a receiver of broadcasts sent by the application
/// </summary>
TLocalReceiver = class(TMultiReceiver)
private
FService: TServiceModule;
protected
procedure ConfigureActions; override;
procedure Receive(context: JContext; intent: JIntent); override;
public
constructor Create(const AService: TServiceModule);
end;
TLocationChangeFrom = (Listener, Timer, Alarm);
TServiceModule = class(TAndroidService)
NotificationCenter: TNotificationCenter;
function AndroidServiceStartCommand(const Sender: TObject; const Intent: JIntent; Flags, StartId: Integer): Integer;
procedure AndroidServiceDestroy(Sender: TObject);
private
FConfig: TLocationConfig;
FDozeAlarmIntent: JPendingIntent;
FIsDozed: Boolean;
FIsForeground: Boolean;
FLastSend: TDateTime;
FLocalReceiver: TLocalReceiver;
FLocation: TLocation;
FNotificationChannel: JNotificationChannel;
FLogWriter: TFileWriter;
FSending: Boolean;
FServiceReceiver: TServiceReceiver;
FTimer: TAndroidTimer;
FWakeLock: JPowerManager_WakeLock;
function CreateDozeAlarm(const AAction: string; const AStartAt: Int64): Boolean;
procedure CreateNotificationChannel;
procedure CreateTimer;
procedure DoMessage(const AMsg: string);
procedure DoStatus;
procedure DozeModeChange(const ADozed: Boolean);
procedure EnableWakeLock(const AEnable: Boolean);
procedure LocalReceiverReceive(intent: JIntent);
procedure LocationChangeHandler(Sender: TObject; const ALocation: TLocationCoord2D);
procedure Pause;
procedure PostRequest(const ARequest: TStream);
procedure RestartService;
procedure Resume;
procedure SendNewLocation(const NewLocation: TLocationCoord2D; const AFrom: TLocationChangeFrom);
function Service: JService;
procedure ScreenLockChange(const ALocked: Boolean);
procedure ServiceReceiverReceive(intent: JIntent);
procedure SetIsPaused(const AValue: Boolean);
procedure StartDozeAlarm;
procedure StartForeground;
procedure StopDozeAlarm;
procedure StopForeground;
procedure TimerEventHandler(Sender: TObject);
procedure UpdateConfig;
procedure UpdateFromLastKnownLocation(const AFrom: TLocationChangeFrom);
procedure SendNotification(const NewLocation: TLocationCoord2D; const AFrom: TLocationChangeFrom);
protected
procedure LocationChanged(const ANewLocation: TLocationCoord2D; const AFrom: TLocationChangeFrom);
procedure WriteLog(const AMsg: string);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
end;
var
ServiceModule: TServiceModule;
implementation
{%CLASSGROUP 'FMX.Controls.TControl'}
{$R *.dfm}
uses
System.IOUtils, System.DateUtils, System.NetConsts, System.Net.URLClient, System.Net.HttpClient, REST.Types, REST.Json,
Androidapi.Helpers, Androidapi.JNI.Support, Androidapi.JNI.Provider,
DW.Androidapi.JNI.LocalBroadcastManager, DW.OSLog, DW.OSDevice, DW.Android.Helpers,
LS.Consts;
const
cServiceName = 'com.embarcadero.services.LocationService';
// Defining these constants here just saves having to import it from Java code
cReceiverName = 'com.delphiworlds.kastri.DWMultiBroadcastReceiver';
cActionServiceAlarm = cReceiverName + '.ACTION_SERVICE_ALARM';
cActionServiceRestart = cReceiverName + '.ACTION_SERVICE_RESTART';
cExtraServiceRestart = cReceiverName + '.EXTRA_SERVICE_RESTART';
cWakeLockTag = 'com.delphiworlds.locationservice.wakelock';
cNotificationChannelName = 'AndroidLocation';
cServiceForegroundId = 3987; // Just a random number
cServiceNotificationCaption = 'Location Service';
// https://developer.android.com/training/monitoring-device-state/doze-standby.html#assessing_your_app
cMinDozeAlarmIntervalSecs = 9 * 60; // Once per 9 minutes is the minimum when "dozed", apparently
// ***** Modify the following 2 lines to suit your requirements *****
cLocationUpdateURL = 'http://your.locationupdate.url';
cLocationRequestJSON = '{"deviceid":"%s", "latitude":"%2.6f","longitude":"%2.6f", "tag":"%S", "inactive":"%d"}';
cHTTPResultOK = 200;
cTimerIntervalMinimum = 240000; // = 4 minutes
cSendIntervalMinimum = 30; // seconds
cLocationMonitoringInterval = 15000;
cLocationMonitoringDistance = 10;
cLocationFromCaptions: array[TLocationChangeFrom] of string = ('Listener', 'Timer', 'Alarm');
function GetTimeFromNowInMillis(const ASeconds: Integer): Int64;
var
LCalendar: JCalendar;
begin
LCalendar := TJCalendar.JavaClass.getInstance;
LCalendar.add(TJCalendar.JavaClass.SECOND, ASeconds);
Result := LCalendar.getTimeInMillis;
end;
function GetLogTime: string;
begin
Result := FormatDateTime('mm-dd hh:nn:ss.zzz', Now);
end;
{ TServiceReceiver }
constructor TServiceReceiver.Create(const AService: TServiceModule);
begin
inherited Create;
FService := AService;
end;
procedure TServiceReceiver.ConfigureActions;
begin
// Filtering for various system events
IntentFilter.addAction(TJIntent.JavaClass.ACTION_SCREEN_ON);
IntentFilter.addAction(TJIntent.JavaClass.ACTION_SCREEN_OFF);
IntentFilter.addAction(TJIntent.JavaClass.ACTION_USER_PRESENT);
if TOSVersion.Check(6) then
IntentFilter.addAction(TJPowerManager.JavaClass.ACTION_DEVICE_IDLE_MODE_CHANGED);
end;
procedure TServiceReceiver.Receive(context: JContext; intent: JIntent);
begin
FService.ServiceReceiverReceive(intent);
end;
{ TLocalReceiver }
constructor TLocalReceiver.Create(const AService: TServiceModule);
begin
inherited Create(True);
FService := AService;
end;
procedure TLocalReceiver.ConfigureActions;
begin
IntentFilter.addAction(StringToJString(cServiceCommandAction));
end;
procedure TLocalReceiver.Receive(context: JContext; intent: JIntent);
begin
FService.LocalReceiverReceive(intent);
end;
{ TServiceModule }
constructor TServiceModule.Create(AOwner: TComponent);
begin
inherited;
FLocation := TLocation.Create;
FLocation.OnLocationChange := LocationChangeHandler;
FConfig := TLocationConfig.GetConfig;
// Creating a log file that can be read by both the service and the application
FLogWriter := TFileWriter.Create(TPath.Combine(TPath.GetDocumentsPath, 'Location.log'), True);
// AutoFlush means that writes are committed immediately
FLogWriter.AutoFlush := True;
FServiceReceiver := TServiceReceiver.Create(Self);
FLocalReceiver := TLocalReceiver.Create(Self);
CreateTimer;
if not FConfig.IsPaused then
Resume;
end;
destructor TServiceModule.Destroy;
begin
// Do not use an overridden Destroy for cleanup in a service - use the OnDestroy event
inherited;
end;
function TServiceModule.Service: JService;
begin
Result := TJService.Wrap(System.JavaContext);
end;
procedure TServiceModule.AndroidServiceDestroy(Sender: TObject);
begin
EnableWakeLock(False);
FWakeLock := nil;
FServiceReceiver.DisposeOf;
FLocalReceiver.DisposeOf;
FTimer.DisposeOf;
FLogWriter.DisposeOf;
FConfig.DisposeOf;
RestartService;
end;
function TServiceModule.AndroidServiceStartCommand(const Sender: TObject; const Intent: JIntent; Flags, StartId: Integer): Integer;
var
LRestart: Boolean;
begin
// The broadcast receiver will send a start command when the doze alarm goes off, so there is a check here to see if that is why it was "started"
if FIsDozed then
begin
if (Intent <> nil) and JStringToString(Intent.getAction).Equals(cActionServiceAlarm) then
begin
WriteLog('TServiceModule.AndroidServiceStartCommand from doze alarm');
UpdateFromLastKnownLocation(TLocationChangeFrom.Alarm);
// Starts the next alarm
StartDozeAlarm;
end
end;
LRestart := (Intent <> nil) and (Intent.getIntExtra(StringToJString(cExtraServiceRestart), 0) = 1);
// If the screen is locked when the service starts, it should start in "foreground" mode to ensure it can still access the network
if (LRestart and TAndroidHelperEx.CheckBuildAndTarget(26)) or TAndroidHelperEx.KeyguardManager.inKeyguardRestrictedInputMode then
StartForeground;
Result := TJService.JavaClass.START_STICKY;
end;
procedure TServiceModule.RestartService;
var
LIntent: JIntent;
begin
LIntent := TJIntent.JavaClass.init(StringToJString(cActionServiceRestart));
LIntent.setClassName(TAndroidHelper.Context.getPackageName, StringToJString(cReceiverName));
LIntent.putExtra(StringToJString('ServiceName'), StringToJString(cServiceName));
TAndroidHelper.Context.sendBroadcast(LIntent);
end;
procedure TServiceModule.CreateNotificationChannel;
begin
if FNotificationChannel <> nil then
Exit; // <======
FNotificationChannel := TJNotificationChannel.JavaClass.init(TAndroidHelper.Context.getPackageName, StrToJCharSequence(cNotificationChannelName),
TJNotificationManager.JavaClass.IMPORTANCE_HIGH);
FNotificationChannel.enableLights(True);
FNotificationChannel.enableVibration(True);
FNotificationChannel.setLightColor(TJColor.JavaClass.GREEN);
FNotificationChannel.setLockscreenVisibility(TJNotification.JavaClass.VISIBILITY_PRIVATE);
TAndroidHelperEx.NotificationManager.createNotificationChannel(FNotificationChannel);
end;
procedure TServiceModule.StartForeground;
var
LBuilder: JNotificationCompat_Builder;
begin
if FIsForeground or not TAndroidHelperEx.CheckBuildAndTarget(TAndroidHelperEx.OREO) then
Exit; // <======
TOSLog.d('TServiceModule.StartForeground');
EnableWakeLock(True);
CreateNotificationChannel;
LBuilder := TJNotificationCompat_Builder.JavaClass.init(TAndroidHelper.Context, StringToJString(cNotificationChannelName));
LBuilder.setAutoCancel(True);
LBuilder.setContentTitle(StrToJCharSequence(cServiceNotificationCaption));
LBuilder.setContentText(StrToJCharSequence('Monitoring location changes'));
LBuilder.setSmallIcon(TAndroidHelper.Context.getApplicationInfo.icon);
LBuilder.setTicker(StrToJCharSequence(cServiceNotificationCaption));
Service.startForeground(cServiceForegroundId, LBuilder.build);
FIsForeground := True;
end;
procedure TServiceModule.StopForeground;
begin
TOSLog.d('TServiceModule.StopForeground');
if FIsForeground then
begin
EnableWakeLock(False);
Service.stopForeground(True);
FIsForeground := False;
end;
end;
procedure TServiceModule.EnableWakeLock(const AEnable: Boolean);
begin
if AEnable then
begin
if FWakeLock = nil then
FWakeLock := TAndroidHelperEx.PowerManager.newWakeLock(TJPowerManager.JavaClass.PARTIAL_WAKE_LOCK, StringToJString(cWakeLockTag));
if not FWakeLock.isHeld then
FWakeLock.acquire;
end
else if (FWakeLock <> nil) and FWakeLock.isHeld then
FWakeLock.release;
end;
function TServiceModule.CreateDozeAlarm(const AAction: string; const AStartAt: Int64): Boolean;
var
LIntent: JIntent;
begin
Result := False;
// Make doubly sure that the old alarm is removed
StopDozeAlarm;
LIntent := TJIntent.JavaClass.init(StringToJString(AAction));
LIntent.setClassName(TAndroidHelper.Context.getPackageName, StringToJString(cReceiverName));
// The brodcast receiver that monitors for alarms needs to know whether it was requested by a service
LIntent.putExtra(StringToJString('ServiceName'), StringToJString(cServiceName));
FDozeAlarmIntent := TJPendingIntent.JavaClass.getBroadcast(TAndroidHelper.Context, 0, LIntent, TJPendingIntent.JavaClass.FLAG_CANCEL_CURRENT);
if FDozeAlarmIntent <> nil then
begin
TAndroidHelper.AlarmManager.setAndAllowWhileIdle(TJAlarmManager.JavaClass.RTC_WAKEUP, AStartAt, FDozeAlarmIntent);
Result := True;
end
else
WriteLog('Unable to create a pending intent for action: ' + AAction);
end;
procedure TServiceModule.CreateTimer;
begin
FTimer := TAndroidTimer.Create;
FTimer.Interval := cTimerIntervalMinimum;
FTimer.OnTimer := TimerEventHandler;
FTimer.Enabled := True;
end;
procedure TServiceModule.DoMessage(const AMsg: string);
var
LIntent: JIntent;
begin
// Sends a local broadcast containing a debug message
LIntent := TJIntent.JavaClass.init(StringToJString(cServiceMessageAction));
LIntent.putExtra(StringToJString(cServiceBroadcastParamMessage), StringToJString(GetLogTime + ': ' + AMsg));
TJLocalBroadcastManager.JavaClass.getInstance(TAndroidHelper.Context).sendBroadcast(LIntent);
end;
procedure TServiceModule.DoStatus;
var
LIntent: JIntent;
begin
// Sends a local broadcast that informs the app that the status has changed
LIntent := TJIntent.JavaClass.init(StringToJString(cServiceStatusAction));
TJLocalBroadcastManager.JavaClass.getInstance(TAndroidHelper.Context).sendBroadcast(LIntent);
end;
procedure TServiceModule.WriteLog(const AMsg: string);
begin
TOSLog.d(AMsg);
FLogWriter.WriteLine(GetLogTime + ': ' + AMsg);
end;
procedure TServiceModule.StartDozeAlarm;
begin
// setAndAllowWhileIdle is available only on Android 6 or greater
if FIsDozed and TOSVersion.Check(6) then
begin
if FLastSend = 0 then
FLastSend := Now;
// Set an alarm for the difference between the last update and the minimum doze alarm
CreateDozeAlarm(cActionServiceAlarm, GetTimeFromNowInMillis(cMinDozeAlarmIntervalSecs - SecondsBetween(FLastSend, Now)));
end;
end;
procedure TServiceModule.StopDozeAlarm;
begin
if FDozeAlarmIntent <> nil then
TAndroidHelper.AlarmManager.cancel(FDozeAlarmIntent);
FDozeAlarmIntent := nil;
end;
procedure TServiceModule.LocalReceiverReceive(intent: JIntent);
var
LCommand: Integer;
begin
if intent.getAction.equals(StringToJString(cServiceCommandAction)) then
begin
LCommand := intent.getIntExtra(StringToJString(cServiceBroadcastParamCommand), 0);
TOSLog.d('TServiceModule.LocalReceiverReceive received command: %d', [LCommand]);
// Commands from the app
case intent.getIntExtra(StringToJString(cServiceBroadcastParamCommand), 0) of
cServiceCommandPause:
Pause;
cServiceCommandResume:
Resume;
cServiceCommandAppBecameActive:
StopForeground;
cServiceCommandAppEnteredBackground:
StartForeground;
end;
end;
DoStatus;
end;
procedure TServiceModule.ServiceReceiverReceive(intent: JIntent);
begin
// Handles the intent that was sent to the broadcast receiver
// First, screenlock changes
if intent.getAction.equals(TJIntent.JavaClass.ACTION_USER_PRESENT) or intent.getAction.equals(TJIntent.JavaClass.ACTION_SCREEN_OFF)
or intent.getAction.equals(TJIntent.JavaClass.ACTION_SCREEN_ON) then
begin
ScreenLockChange(TAndroidHelperEx.KeyguardManager.inKeyguardRestrictedInputMode);
end
// Otherwise, check for "doze" mode changes
else if TOSVersion.Check(6) and intent.getAction.equals(TJPowerManager.JavaClass.ACTION_DEVICE_IDLE_MODE_CHANGED) then
DozeModeChange(TAndroidHelperEx.PowerManager.isDeviceIdleMode);
end;
procedure TServiceModule.SetIsPaused(const AValue: Boolean);
begin
//
end;
procedure TServiceModule.ScreenLockChange(const ALocked: Boolean);
begin
WriteLog('TServiceModule.ScreenLockChange: ' + BoolToStr(ALocked, True));
// If the screen is being locked, put the service into foreground mode so that it can still have network access
if ALocked then
StartForeground
else
StopForeground;
end;
procedure TServiceModule.DozeModeChange(const ADozed: Boolean);
begin
WriteLog('TServiceModule.DozeModeChange: ' + BoolToStr(ADozed, True));
// If the device is going into "doze" mode, set an alarm
FIsDozed := ADozed;
if FIsDozed then
StartDozeAlarm
else
StopDozeAlarm;
end;
procedure TServiceModule.TimerEventHandler(Sender: TObject);
begin
WriteLog('TServiceModule.TimerEventHandler');
UpdateFromLastKnownLocation(TLocationChangeFrom.Timer);
end;
procedure TServiceModule.UpdateFromLastKnownLocation(const AFrom: TLocationChangeFrom);
var
LLocation: TLocationCoord2D;
begin
LLocation := FLocation.GetLastKnownLocation;
if Abs(LLocation.Latitude) <= 90 then
begin
WriteLog('TServiceModule.UpdateFromLastKnownLocation from: ' + cLocationFromCaptions[AFrom]);
LocationChanged(LLocation, AFrom);
end;
end;
procedure TServiceModule.LocationChanged(const ANewLocation: TLocationCoord2D; const AFrom: TLocationChangeFrom);
begin
// Only send if a location change has been obtained within the specified interval
if not FSending and (SecondsBetween(Now, FLastSend) >= cSendIntervalMinimum) then
begin
WriteLog('Starting send task (Time difference >= cSendIntervalMinimum)');
// FSending flag is used to ensure that a request is not sent if it is already sending
FSending := True;
try
SendNewLocation(ANewLocation, AFrom); // <---- Comment out this line and uncomment the next line to test notifications
// SendNotification(ANewLocation, AFrom); // <---- This line was added to test notifications inside an Android service.
finally
FSending := False;
end;
end;
end;
procedure TServiceModule.LocationChangeHandler(Sender: TObject; const ALocation: TLocationCoord2D);
begin
LocationChanged(ALocation, TLocationChangeFrom.Listener);
end;
procedure TServiceModule.SendNewLocation(const NewLocation: TLocationCoord2D; const AFrom: TLocationChangeFrom);
const
cLocationUpdateTag = '%s: %s @ %s';
var
LStream: TStringStream;
LTag: string;
begin
// Format the request, and post it
// ****** Modify the following 2 lines to suit your location update request requirements *******
LTag := Format(cLocationUpdateTag, ['DW', cLocationFromCaptions[AFrom], FormatDateTime('mm-dd hh:nn:ss.zzz', Now)]);
LStream := TStringStream.Create(Format(cLocationRequestJSON, ['x', NewLocation.Latitude, NewLocation.Longitude, LTag, Ord(FIsDozed)]));
try
DoMessage(LStream.DataString);
//!!!!!!
{
TOSLog.d('Posting request: %s', [LStream.DataString]);
try
PostRequest(LStream);
// Accessing a reference outside of the task, however in theory this one should be safe
FLastSend := Now;
except
on E: Exception do
begin
WriteLog('Exception in PostRequest: ' + E.Message);
end;
end;
}
finally
LStream.Free;
end;
end;
procedure TServiceModule.PostRequest(const ARequest: TStream);
var
LHTTP: THTTPClient;
LResponse: IHTTPResponse;
begin
// Posts the JSON request to the server
WriteLog('Sending new location..');
LHTTP := THTTPClient.Create;
try
LHTTP.Accept := CONTENTTYPE_APPLICATION_JSON;
LHTTP.ContentType := CONTENTTYPE_APPLICATION_JSON;
LResponse := LHTTP.Post(cLocationUpdateURL, ARequest);
if LResponse.StatusCode = cHTTPResultOK then
begin
TOSLog.d('Successful - Response: %s', [LResponse.ContentAsString]);
DoMessage('Send of new location successful');
end
else
begin
TOSLog.d('Unsuccessful - Status: %s, Response: %s', [LResponse.StatusText, LResponse.ContentAsString]);
DoMessage('Send of new location unsuccessful - response: ' + LResponse.ContentAsString);
end;
finally
LHTTP.Free;
end;
WriteLog('Successfully sent new location');
end;
procedure TServiceModule.SendNotification(const NewLocation: TLocationCoord2D; const AFrom: TLocationChangeFrom);
var
LNotification: TNotification;
begin
LNotification := NotificationCenter.CreateNotification;
try
LNotification.EnableSound := False;
LNotification.AlertBody := Format('Received location update from %s @ %.4f, %.4f', [cLocationFromCaptions[AFrom],
NewLocation.Latitude, NewLocation.Longitude]);
NotificationCenter.PresentNotification(LNotification);
finally
LNotification.Free;
end;
end;
procedure TServiceModule.Pause;
begin
FLocation.Pause;
UpdateConfig;
end;
procedure TServiceModule.Resume;
begin
FLocation.Resume;
UpdateConfig;
end;
procedure TServiceModule.UpdateConfig;
begin
FConfig.IsPaused := FLocation.IsPaused;
FConfig.Save;
DoStatus;
end;
end.
|
(*
* iocp 线程锁、线程基类
*)
unit iocp_baseObjs;
interface
{$I in_iocp.inc} // 模式设置
uses
{$IFDEF DELPHI_XE7UP}
Winapi.Windows, System.Classes, System.SysUtils, Winapi.ActiveX, {$ELSE}
Windows, Classes, SysUtils, ActiveX, {$ENDIF}
iocp_base, iocp_log;
type
// ===================== 线程锁 类 =====================
TThreadLock = class(TObject)
protected
FSection: TRTLCriticalSection;
public
constructor Create;
destructor Destroy; override;
public
procedure Acquire; {$IFDEF USE_INLINE} inline; {$ENDIF}
procedure Release; {$IFDEF USE_INLINE} inline; {$ENDIF}
end;
// ===================== 线程基类 =====================
TBaseThread = class(TThread)
protected
procedure Execute; override;
procedure ExecuteWork; virtual; abstract; // 在子类继承
end;
// ===================== 循环执行任务的线程 =====================
TCycleThread = class(TBaseThread)
protected
FInnerHandle: Boolean; // 内含信号灯
FSemaphore: THandle; // 信号灯
procedure AfterWork; virtual; abstract;
procedure DoThreadMethod; virtual; abstract;
procedure ExecuteWork; override;
public
constructor Create(InnerHandle: Boolean = True);
destructor Destroy; override;
procedure Activate; {$IFDEF USE_INLINE} inline; {$ENDIF}
procedure Stop;
end;
// ===================== 系统全局锁 =====================
TSystemGlobalLock = class(TThreadLock)
{$IFNDEF DELPHI_7}
private
class var
FMessageId: TIOCPMsgId; // 消息编号
FInstance: TSystemGlobalLock; // 当前实例
FRefCount: Integer; // 引用次数
{$ENDIF}
public
class function CreateGlobalLock: TSystemGlobalLock;
class function GetMsgId: TIOCPMsgId;
class procedure FreeGlobalLock;
end;
implementation
{$IFDEF DELPHI_7}
var
FMessageId: TIOCPMsgId; // 消息编号
FInstance: TSystemGlobalLock; // 当前实例
FRefCount: Integer; // 引用次数
{$ENDIF}
{ TThreadLock }
procedure TThreadLock.Acquire;
begin
EnterCriticalSection(FSection);
end;
constructor TThreadLock.Create;
begin
inherited Create;
InitializeCriticalSection(FSection);
end;
destructor TThreadLock.Destroy;
begin
DeleteCriticalSection(FSection);
inherited;
end;
procedure TThreadLock.Release;
begin
LeaveCriticalSection(FSection);
end;
{ TBaseThread }
procedure TBaseThread.Execute;
begin
inherited;
CoInitializeEx(Nil, 0);
try
ExecuteWork;
finally
CoUninitialize;
end;
end;
{ TCycleThread }
procedure TCycleThread.Activate;
begin
// 信号量+,激活线程
ReleaseSemapHore(FSemaphore, 8, Nil); // 发几个信号量
end;
constructor TCycleThread.Create(InnerHandle: Boolean);
begin
inherited Create(True);
FreeOnTerminate := True;
FInnerHandle := InnerHandle;
if FInnerHandle then // 内置信号灯
FSemaphore := CreateSemapHore(Nil, 0, MaxInt, Nil); // 信号最大值 = MaxInt
end;
destructor TCycleThread.Destroy;
begin
if FInnerHandle then
CloseHandle(FSemaphore);
inherited;
end;
procedure TCycleThread.ExecuteWork;
begin
inherited;
try
while (Terminated = False) do
if (WaitForSingleObject(FSemaphore, INFINITE) = WAIT_OBJECT_0) then // 等待信号灯
if Terminated then
Break
else
try
DoThreadMethod; // 执行子类方法
except
on E: Exception do
iocp_log.WriteLog(Self.ClassName + '->循环线程异常: ' + E.Message);
end;
finally
AfterWork;
end;
end;
procedure TCycleThread.Stop;
begin
Terminate;
Activate;
end;
{ TSystemGlobalLock }
class function TSystemGlobalLock.CreateGlobalLock: TSystemGlobalLock;
begin
if not Assigned(FInstance) then
FInstance := TSystemGlobalLock.Create;
Result := FInstance;
Inc(FRefCount);
end;
class procedure TSystemGlobalLock.FreeGlobalLock;
begin
Dec(FRefCount);
if (FRefCount = 0) then
begin
FInstance.Free;
FInstance := nil;
end;
end;
class function TSystemGlobalLock.GetMsgId: TIOCPMsgId;
begin
if Assigned(FInstance) then
begin
{$IFDEF WIN64}
Result := System.AtomicIncrement(FMessageId);
{$ELSE}
FInstance.Acquire;
try
Inc(FMessageId);
Result := FMessageId;
finally
FInstance.Release;
end;
{$ENDIF}
end else
Result := 0;
end;
end.
|
{$mode delphi}
unit uSHA256; {taken from fundamentals. see license at bottom of file }
interface
type
T256BitDigest = record
case integer of
0 : (Longs : array[0..7] of LongWord);
1 : (Words : array[0..15] of Word);
2 : (Bytes : array[0..31] of Byte);
end;
{ }
{ SHA256 Hashing }
{ 256 bit SHA-2 hash }
{ }
procedure SHA256InitDigest(var Digest: T256BitDigest);
procedure SHA256Buf(var Digest: T256BitDigest; const Buf; const BufSize: Integer);
procedure SHA256FinalBuf(var Digest: T256BitDigest; const Buf; const BufSize: Integer; const TotalSize: Int64);
function CalcSHA256(const Buf; const BufSize: Integer): T256BitDigest; overload;
function CalcSHA256(const Buf: AnsiString): T256BitDigest; overload;
function SHA256DigestToStrA(const Digest: T256BitDigest): AnsiString;
function SHA256DigestToHexA(const Digest: T256BitDigest): AnsiString;
function SHA256DigestToHexW(const Digest: T256BitDigest): WideString;
implementation
type
T512BitBuf = array[0..63] of Byte;
{ }
{ ReverseMem }
{ Utility function to reverse order of data in buffer. }
{ }
procedure ReverseMem(var Buf; const BufSize: Integer);
var I : Integer;
P : PByte;
Q : PByte;
T : Byte;
begin
P := @Buf;
Q := P;
Inc(Q, BufSize - 1);
for I := 1 to BufSize div 2 do
begin
T := P^;
P^ := Q^;
Q^ := T;
Inc(P);
Dec(Q);
end;
end;
{ }
{ StdFinalBuf }
{ Utility function to prepare final buffer(s). }
{ Fills Buf1 and potentially Buf2 from Buf (FinalBufCount = 1 or 2). }
{ Used by MD5, SHA1, SHA256, SHA512. }
{ }
procedure StdFinalBuf512(
const Buf; const BufSize: Integer; const TotalSize: Int64;
var Buf1, Buf2: T512BitBuf;
var FinalBufs: Integer;
const SwapEndian: Boolean);
var P, Q : PByte;
I : Integer;
L : Int64;
begin
Assert(BufSize < 64, 'Final BufSize must be less than 64 bytes');
Assert(TotalSize >= BufSize, 'TotalSize >= BufSize');
P := @Buf;
Q := @Buf1[0];
if BufSize > 0 then
begin
Move(P^, Q^, BufSize);
Inc(Q, BufSize);
end;
Q^ := $80;
Inc(Q);
{$IFDEF DELPHI5}
// Delphi 5 sometimes reports fatal error (internal error C1093) when compiling:
// L := TotalSize * 8
L := TotalSize;
L := L * 8;
{$ELSE}
L := TotalSize * 8;
{$ENDIF}
if SwapEndian then
ReverseMem(L, 8);
if BufSize + 1 > 64 - Sizeof(Int64) then
begin
FillChar(Q^, 64 - BufSize - 1, #0);
Q := @Buf2[0];
FillChar(Q^, 64 - Sizeof(Int64), #0);
Inc(Q, 64 - Sizeof(Int64));
PInt64(Q)^ := L;
FinalBufs := 2;
end
else
begin
I := 64 - Sizeof(Int64) - BufSize - 1;
FillChar(Q^, I, #0);
Inc(Q, I);
PInt64(Q)^ := L;
FinalBufs := 1;
end;
end;
{ }
{ Digests }
{ }
const
s_HexDigitsLower : String[16] = '0123456789abcdef';
procedure DigestToHexBufA(const Digest; const Size: Integer; const Buf);
var I : Integer;
P : PAnsiChar;
Q : PByte;
begin
P := @Buf;;
Assert(Assigned(P));
Q := @Digest;
Assert(Assigned(Q));
for I := 0 to Size - 1 do
begin
P^ := s_HexDigitsLower[Q^ shr 4 + 1];
Inc(P);
P^ := s_HexDigitsLower[Q^ and 15 + 1];
Inc(P);
Inc(Q);
end;
end;
procedure DigestToHexBufW(const Digest; const Size: Integer; const Buf);
var I : Integer;
P : PWideChar;
Q : PByte;
begin
P := @Buf;;
Assert(Assigned(P));
Q := @Digest;
Assert(Assigned(Q));
for I := 0 to Size - 1 do
begin
P^ := WideChar(s_HexDigitsLower[Q^ shr 4 + 1]);
Inc(P);
P^ := WideChar(s_HexDigitsLower[Q^ and 15 + 1]);
Inc(P);
Inc(Q);
end;
end;
function DigestToHexA(const Digest; const Size: Integer): AnsiString;
begin
SetLength(Result, Size * 2);
DigestToHexBufA(Digest, Size, Pointer(Result)^);
end;
function DigestToHexW(const Digest; const Size: Integer): WideString;
begin
SetLength(Result, Size * 2);
DigestToHexBufW(Digest, Size, Pointer(Result)^);
end;
procedure SwapEndianBuf(var Buf; const Count: Integer);
var P : PLongWord;
I : Integer;
begin
P := @Buf;
for I := 1 to Count do
begin
P^ := SwapEndian(P^);
Inc(P);
end;
end;
{ }
{ Secure memory clear }
{ }
procedure SecureClear(var Buf; const BufSize: Integer);
begin
if BufSize <= 0 then
exit;
FillChar(Buf, BufSize, #$00);
end;
procedure SecureClear512(var Buf: T512BitBuf);
begin
SecureClear(Buf, SizeOf(Buf));
end;
{$IFDEF ASM386_DELPHI}
function RotateLeftBits(const Value: LongWord; const Bits: Byte): LongWord;
asm
MOV CL, DL
ROL EAX, CL
end;
{$ELSE}
function RotateLeftBits(const Value: LongWord; const Bits: Byte): LongWord;
var I : Integer;
R : LongWord;
begin
R := Value;
for I := 1 to Bits do
if R and $80000000 = 0 then
R := LongWord(R shl 1)
else
R := LongWord(R shl 1) or 1;
Result := R;
end;
{$ENDIF}
{$IFDEF ASM386_DELPHI}
function RotateRightBits(const Value: LongWord; const Bits: Byte): LongWord;
asm
MOV CL, DL
ROR EAX, CL
end;
{$ELSE}
function RotateRightBits(const Value: LongWord; const Bits: Byte): LongWord;
var I, B : Integer;
begin
Result := Value;
if Bits >= 32 then
B := Bits mod 32
else
B := Bits;
for I := 1 to B do
if Result and 1 = 0 then
Result := Result shr 1
else
Result := (Result shr 1) or $80000000;
end;
{$ENDIF}
{ }
{ SHA256 hashing }
{ }
procedure SHA256InitDigest(var Digest: T256BitDigest);
begin
Digest.Longs[0] := $6a09e667;
Digest.Longs[1] := $bb67ae85;
Digest.Longs[2] := $3c6ef372;
Digest.Longs[3] := $a54ff53a;
Digest.Longs[4] := $510e527f;
Digest.Longs[5] := $9b05688c;
Digest.Longs[6] := $1f83d9ab;
Digest.Longs[7] := $5be0cd19;
end;
function SHA256Transform1(const A: LongWord): LongWord;
begin
Result := RotateRightBits(A, 7) xor RotateRightBits(A, 18) xor (A shr 3);
end;
function SHA256Transform2(const A: LongWord): LongWord;
begin
Result := RotateRightBits(A, 17) xor RotateRightBits(A, 19) xor (A shr 10);
end;
function SHA256Transform3(const A: LongWord): LongWord;
begin
Result := RotateRightBits(A, 2) xor RotateRightBits(A, 13) xor RotateRightBits(A, 22);
end;
function SHA256Transform4(const A: LongWord): LongWord;
begin
Result := RotateRightBits(A, 6) xor RotateRightBits(A, 11) xor RotateRightBits(A, 25);
end;
const
// first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311
SHA256K: array[0..63] of LongWord = (
$428a2f98, $71374491, $b5c0fbcf, $e9b5dba5, $3956c25b, $59f111f1, $923f82a4, $ab1c5ed5,
$d807aa98, $12835b01, $243185be, $550c7dc3, $72be5d74, $80deb1fe, $9bdc06a7, $c19bf174,
$e49b69c1, $efbe4786, $0fc19dc6, $240ca1cc, $2de92c6f, $4a7484aa, $5cb0a9dc, $76f988da,
$983e5152, $a831c66d, $b00327c8, $bf597fc7, $c6e00bf3, $d5a79147, $06ca6351, $14292967,
$27b70a85, $2e1b2138, $4d2c6dfc, $53380d13, $650a7354, $766a0abb, $81c2c92e, $92722c85,
$a2bfe8a1, $a81a664b, $c24b8b70, $c76c51a3, $d192e819, $d6990624, $f40e3585, $106aa070,
$19a4c116, $1e376c08, $2748774c, $34b0bcb5, $391c0cb3, $4ed8aa4a, $5b9cca4f, $682e6ff3,
$748f82ee, $78a5636f, $84c87814, $8cc70208, $90befffa, $a4506ceb, $bef9a3f7, $c67178f2
);
{$IFOPT Q+}{$DEFINE QOn}{$Q-}{$ELSE}{$UNDEF QOn}{$ENDIF}
procedure TransformSHA256Buffer(var Digest: T256BitDigest; const Buf);
var
I : Integer;
W : array[0..63] of LongWord;
P : PLongWord;
S0, S1, Maj, T1, T2, Ch : LongWord;
H : array[0..7] of LongWord;
begin
P := @Buf;
for I := 0 to 15 do
begin
W[I] := SwapEndian(P^);
Inc(P);
end;
for I := 16 to 63 do
begin
S0 := SHA256Transform1(W[I - 15]);
S1 := SHA256Transform2(W[I - 2]);
W[I] := W[I - 16] + S0 + W[I - 7] + S1;
end;
for I := 0 to 7 do
H[I] := Digest.Longs[I];
for I := 0 to 63 do
begin
S0 := SHA256Transform3(H[0]);
Maj := (H[0] and H[1]) xor (H[0] and H[2]) xor (H[1] and H[2]);
T2 := S0 + Maj;
S1 := SHA256Transform4(H[4]);
Ch := (H[4] and H[5]) xor ((not H[4]) and H[6]);
T1 := H[7] + S1 + Ch + SHA256K[I] + W[I];
H[7] := H[6];
H[6] := H[5];
H[5] := H[4];
H[4] := H[3] + T1;
H[3] := H[2];
H[2] := H[1];
H[1] := H[0];
H[0] := T1 + T2;
end;
for I := 0 to 7 do
Inc(Digest.Longs[I], H[I]);
end;
{$IFDEF QOn}{$Q+}{$ENDIF}
procedure SHA256Buf(var Digest: T256BitDigest; const Buf; const BufSize: Integer);
var P : PByte;
I, J : Integer;
begin
I := BufSize;
if I <= 0 then
exit;
Assert(I mod 64 = 0, 'BufSize must be multiple of 64 bytes');
P := @Buf;
for J := 0 to I div 64 - 1 do
begin
TransformSHA256Buffer(Digest, P^);
Inc(P, 64);
end;
end;
procedure SHA256FinalBuf(var Digest: T256BitDigest; const Buf; const BufSize: Integer; const TotalSize: Int64);
var B1, B2 : T512BitBuf;
C : Integer;
begin
StdFinalBuf512(Buf, BufSize, TotalSize, B1, B2, C, True);
TransformSHA256Buffer(Digest, B1);
if C > 1 then
TransformSHA256Buffer(Digest, B2);
SwapEndianBuf(Digest, Sizeof(Digest) div Sizeof(LongWord));
SecureClear512(B1);
if C > 1 then
SecureClear512(B2);
end;
function CalcSHA256(const Buf; const BufSize: Integer): T256BitDigest;
var I, J : Integer;
P : PByte;
begin
SHA256InitDigest(Result);
P := @Buf;
if BufSize <= 0 then
I := 0 else
I := BufSize;
J := (I div 64) * 64;
if J > 0 then
begin
SHA256Buf(Result, P^, J);
Inc(P, J);
Dec(I, J);
end;
SHA256FinalBuf(Result, P^, I, BufSize);
end;
function CalcSHA256(const Buf: AnsiString): T256BitDigest;
begin
Result := CalcSHA256(Pointer(Buf)^, Length(Buf));
end;
function SHA256DigestToStrA(const Digest: T256BitDigest): AnsiString;
begin
SetLength(Result, Sizeof(Digest));
Move(Digest, Pointer(Result)^, Sizeof(Digest));
end;
function SHA256DigestToHexA(const Digest: T256BitDigest): AnsiString;
begin
Result := DigestToHexA(Digest, Sizeof(Digest));
end;
function SHA256DigestToHexW(const Digest: T256BitDigest): WideString;
begin
Result := DigestToHexW(Digest, Sizeof(Digest));
end;
end.
{******************************************************************************}
{ }
{ Library: Fundamentals 4.00 }
{ File name: cHash.pas }
{ File version: 4.18 }
{ Description: Hashing functions }
{ }
{ Copyright: Copyright (c) 1999-2013, David J Butler }
{ 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. }
{ 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 REGENTS 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. }
{ }
{ Home page: http://fundementals.sourceforge.net }
{ Forum: http://sourceforge.net/forum/forum.php?forum_id=2117 }
{ E-mail: fundamentals.library@gmail.com }
|
program gcd(input, output);
var
n, m : integer;
function gcd(n, m : integer) : integer;
var
rem : integer;
begin
while m <> 0 do
begin
rem := n mod m;
n := m;
m := rem;
end;
gcd := n
end;
begin
write('(n, m) : ');
read(n, m);
writeln('GCD(', n, ', ', m, ') = ', gcd(n, m))
end.
|
unit Charge;
interface
uses
Pkg.Json.DTO, System.Generics.Collections, REST.Json.Types;
{$M+}
type
TBilling = class
private
FBirthDate: string;
FDocument: string;
FEmail: string;
FName: string;
FNotify: Boolean;
FPhone: string;
FSecondaryEmail: string;
published
property BirthDate: string read FBirthDate write FBirthDate;
property Document: string read FDocument write FDocument;
property Email: string read FEmail write FEmail;
property Name: string read FName write FName;
property Notify: Boolean read FNotify write FNotify;
property Phone: string read FPhone write FPhone;
property SecondaryEmail: string read FSecondaryEmail write FSecondaryEmail;
end;
TSplit = class
private
FAmount: Integer;
FAmountRemainder: Boolean;
FChargeFee: Boolean;
FPercentage: Integer;
FRecipientToken: string;
published
property Amount: Integer read FAmount write FAmount;
property AmountRemainder: Boolean read FAmountRemainder write FAmountRemainder;
property ChargeFee: Boolean read FChargeFee write FChargeFee;
property Percentage: Integer read FPercentage write FPercentage;
property RecipientToken: string read FRecipientToken write FRecipientToken;
end;
TCharge = class
private
FAmount: Double;
FDescription: string;
FDiscountAmount: string;
FDiscountDays: Integer;
FDueDate: string;
FFeeSchemaToken: string;
FFine: Integer;
FInstallments: Integer;
FInterest: string;
FMaxOverdueDays: Integer;
FPaymentAdvance: Boolean;
FPaymentTypes: TArray<string>;
FReferences: TArray<string>;
[JSONName('split')]
FSplitArray: TArray<TSplit>;
[GenericListReflect]
FSplit: TObjectList<TSplit>;
FTotalAmount: Double;
function GetSplit: TObjectList<TSplit>;
published
property Amount: Double read FAmount write FAmount;
property Description: string read FDescription write FDescription;
property DiscountAmount: string read FDiscountAmount write FDiscountAmount;
property DiscountDays: Integer read FDiscountDays write FDiscountDays;
property DueDate: string read FDueDate write FDueDate;
property FeeSchemaToken: string read FFeeSchemaToken write FFeeSchemaToken;
property Fine: Integer read FFine write FFine;
property Installments: Integer read FInstallments write FInstallments;
property Interest: string read FInterest write FInterest;
property MaxOverdueDays: Integer read FMaxOverdueDays write FMaxOverdueDays;
property PaymentAdvance: Boolean read FPaymentAdvance write FPaymentAdvance;
property PaymentTypes: TArray<string> read FPaymentTypes write FPaymentTypes;
property References: TArray<string> read FReferences write FReferences;
property Split: TObjectList<TSplit> read GetSplit;
property TotalAmount: Double read FTotalAmount write FTotalAmount;
destructor Destroy; override;
end;
TRootCharge = class(TJsonDTO)
private
FBilling: TBilling;
FCharge: TCharge;
published
property Billing: TBilling read FBilling write FBilling;
property Charge: TCharge read FCharge write FCharge;
public
constructor Create; override;
destructor Destroy; override;
end;
implementation
{ TCharge }
destructor TCharge.Destroy;
begin
GetSplit.Free;
inherited;
end;
function TCharge.GetSplit: TObjectList<TSplit>;
begin
if not Assigned(FSplit) then
begin
FSplit := TObjectList<TSplit>.Create;
FSplit.AddRange(FSplitArray);
end;
Result := FSplit;
end;
{ TRootCharge }
constructor TRootCharge.Create;
begin
inherited;
FCharge := TCharge.Create;
FBilling := TBilling.Create;
end;
destructor TRootCharge.Destroy;
begin
FCharge.Free;
FBilling.Free;
inherited;
end;
end.
|
object fmCodeOptions: TfmCodeOptions
Left = 442
Top = 167
BorderIcons = [biSystemMenu, biMaximize]
Caption = 'Code Librarian Options'
ClientHeight = 241
ClientWidth = 321
Color = clBtnFace
Font.Charset = ANSI_CHARSET
Font.Color = clWindowText
Font.Height = -12
Font.Name = 'Tahoma'
Font.Style = []
OldCreateOrder = True
Position = poScreenCenter
Scaled = False
OnCreate = FormCreate
PixelsPerInch = 96
TextHeight = 14
object btnOK: TButton
Left = 160
Top = 208
Width = 73
Height = 26
Anchors = [akRight, akBottom]
Caption = 'OK'
Default = True
ModalResult = 1
TabOrder = 1
end
object btnCancel: TButton
Left = 240
Top = 208
Width = 73
Height = 26
Anchors = [akRight, akBottom]
Cancel = True
Caption = 'Cancel'
ModalResult = 2
TabOrder = 2
end
object pgeCodeOpt: TPageControl
Left = 8
Top = 8
Width = 305
Height = 185
ActivePage = tabPaths
Anchors = [akLeft, akTop, akRight, akBottom]
TabOrder = 0
object tabPaths: TTabSheet
Caption = 'Paths'
object lblStoragePath: TLabel
Left = 8
Top = 16
Width = 173
Height = 14
Caption = 'Code Librarian Storage Location'
end
object sbBrowse: TButton
Left = 268
Top = 32
Width = 21
Height = 21
Anchors = [akTop, akRight]
Caption = '...'
TabOrder = 1
OnClick = sbBrowseClick
end
object edPath: TEdit
Left = 8
Top = 32
Width = 259
Height = 22
Anchors = [akLeft, akTop, akRight]
TabOrder = 0
end
end
object tabLayout: TTabSheet
Caption = 'Layout'
object rbSide: TRadioButton
Left = 22
Top = 16
Width = 137
Height = 17
Caption = 'Side by side'
TabOrder = 0
end
object pnlSideSide: TPanel
Left = 22
Top = 40
Width = 105
Height = 89
BevelOuter = bvLowered
Color = clWindow
TabOrder = 2
object shpLeft: TShape
Left = 8
Top = 8
Width = 41
Height = 73
end
object shpRight: TShape
Left = 56
Top = 8
Width = 41
Height = 73
end
end
object rbTop: TRadioButton
Left = 160
Top = 16
Width = 113
Height = 17
Caption = 'Top to bottom'
TabOrder = 1
end
object pnlTopBottom: TPanel
Left = 160
Top = 40
Width = 105
Height = 89
BevelOuter = bvLowered
Color = clWindow
TabOrder = 3
object shpTop: TShape
Left = 8
Top = 8
Width = 89
Height = 33
end
object shpBottom: TShape
Left = 8
Top = 48
Width = 89
Height = 33
end
end
end
object tabFonts: TTabSheet
Caption = 'Fonts'
object lblTreeView: TLabel
Left = 8
Top = 16
Width = 51
Height = 14
Caption = 'Treeview'
end
object lblEditor: TLabel
Left = 8
Top = 64
Width = 32
Height = 14
Caption = 'Editor'
end
object lblSize: TLabel
Left = 232
Top = 13
Width = 41
Height = 17
Alignment = taCenter
AutoSize = False
Caption = 'Size'
end
object fcTreeview: TComboBox
Left = 8
Top = 32
Width = 205
Height = 22
Style = csDropDownList
DropDownCount = 18
ItemHeight = 0
TabOrder = 0
end
object fcEditor: TComboBox
Left = 8
Top = 80
Width = 205
Height = 22
Style = csDropDownList
DropDownCount = 18
ItemHeight = 0
TabOrder = 3
end
object udTreeview: TUpDown
Left = 273
Top = 32
Width = 15
Height = 21
Associate = eTreeview
Min = 4
Max = 24
Position = 8
TabOrder = 2
Wrap = False
end
object udEditor: TUpDown
Left = 273
Top = 80
Width = 15
Height = 21
Associate = eEditor
Min = 4
Max = 24
Position = 8
TabOrder = 5
Wrap = False
end
object eTreeview: TEdit
Left = 232
Top = 32
Width = 41
Height = 22
TabOrder = 1
Text = '8'
OnKeyPress = eNumericKeyPress
end
object eEditor: TEdit
Left = 232
Top = 80
Width = 41
Height = 22
TabOrder = 4
Text = '8'
end
end
end
end
|
{ Subroutine SST_W_C_DTYPE_VREC (FIELD_P)
*
* Write data type definition of a variant within a record. On entry,
* FIELD_P is pointing to the first field within each variant (overlay).
* On return, it will be pointing to the next field after the last field
* in this overlay, or NIL if no fields follow this overlay. The C record
* will have the structure below. Square brackets are used because curly
* brackets are meaningful in the Pascal source code here:
*
* typdef union recname_t [
* struct [ /* non-variant part, always called BASE */
* int a;
* int b;
* ] base;
* struct [ /* first overlay */
* char unused[8];
* float x;
* float y;
* ] i1;
* struct [ /* second overlay */
* char unused_1[8];
* float u;
* float v;
* ] i2;
* ] recname_t;
*
* This routine will be called the first time for the "A" field. The
* top UNION declartion line has already been written. Each invocation
* must handle all the fields within the same overlay. If the variant IDs
* are enumerated values, then "clever" naming will be used to elminate
* as much redundancy in the struct and field names as possible.
}
module sst_w_c_dtype_vrec;
define sst_w_c_dtype_vrec;
%include 'sst_w_c.ins.pas';
var {static variables preseved between calls}
enum_trunc_beg: sys_int_machine_t; {num chars to trunc from beg of enum name}
enum_trunc_end: sys_int_machine_t; {num chars to trunc from end of enum name}
name_nv: string_var16_t := {name of STRUCT for non-variant fields}
[str := 'base', len := 4, max := 16];
procedure sst_w_c_dtype_vrec ( {write data type definition of variant record}
in out field_p: sst_symbol_p_t; {pnt to first field in variant, updated}
in pack: boolean); {TRUE if variant part of packed record}
val_param;
var
str_h: syo_string_t; {string handle for error message}
pos_hash: string_hash_pos_t; {hash table position handle}
ovlid: sys_int_machine_t; {sequential ID of this overlay}
trunc_beg: sys_int_machine_t; {num char to trunc from field names}
f_p: sst_symbol_p_t; {scratch field pointer}
e_p, e2_p: sst_symbol_p_t; {scratch enum value symbol pointers}
i, j, k: sys_int_machine_t; {scratch integers and loop counters}
unused1_p, unused2_p: univ_ptr; {unused arguments returned from subroutine}
sname: string_var32_t; {STRUCT name}
str: string_var32_t; {scratch string}
name: string_var80_t; {scratch name string}
label
got_enum_truncs, done_first, got_sname, loop_field;
begin
sname.max := sizeof(sname.str); {init local var strings}
str.max := sizeof(str.str);
name.max := sizeof(name.str);
if field_p^.field_variant <> 1 {not first overlay in a new record ?}
then goto done_first;
{
*******************************************************************
*
* This section gets run only once per data type before any variants
* are written. Some information common to all the variants is saved
* in static storage so that it doesn't need to be recomputed for other
* variants within the same record.
*
* If the variant ID data type is enumerated, then find the prefix and
* suffix common to all the enumerated names. This allows using just
* the unique part later. The prefix and suffix are identified by setting
* ENUM_TRUNC_BEG and ENUM_TRUNC_END. These are static variables, since
* they will apply to all the variants in this record.
}
if {variant IDs are ENUMERATED ?}
field_p^.field_var_val.dtype = sst_dtype_enum_k
then begin
e_p := {get pointer to first enumerated name}
field_p^.field_var_val.enum_p^.enum_dtype_p^.enum_first_p;
e2_p := e_p^.enum_next_p; {get pointer to next enumerated name}
if e2_p = nil then begin {only one enumerated name in data type ?}
enum_trunc_beg := 0; {don't truncate name at all}
enum_trunc_end := 0;
goto got_enum_truncs; {done computing enum truncation lengths}
end;
enum_trunc_beg := e_p^.name_in_p^.len; {init truncation lengths to whole name}
enum_trunc_end := enum_trunc_beg;
while e2_p <> nil do begin {once for each enum name to compare}
j := e_p^.name_in_p^.len; {get length of first name}
k := e2_p^.name_in_p^.len; {get length of second name}
enum_trunc_beg := min(enum_trunc_beg, k); {clip to length of new name}
enum_trunc_end := min(enum_trunc_end, k);
for i := 1 to enum_trunc_beg do begin {check beginning truncation length}
if {name characters don't match here ?}
e2_p^.name_in_p^.str[i] <> e_p^.name_in_p^.str[i]
then begin
enum_trunc_beg := i - 1; {names only same up to previous character}
exit; {done checking beginning truncation length}
end;
end; {back to check out next character}
for i := 1 to enum_trunc_end do begin {check end truncation length}
if {name characters don't match here ?}
e2_p^.name_in_p^.str[k+1-i] <> e_p^.name_in_p^.str[j+1-i]
then begin
enum_trunc_end := i - 1; {names only same up to previous character}
exit; {done checking ending truncation length}
end;
end; {back to check out next character}
e_p := e2_p; {old second name becomes new first name}
e2_p := e_p^.enum_next_p; {make pointer to new second name}
end; {back to process this new name}
{
* ENUM_TRUNC_BEG and ENUM_TRUNC_END identify the prefix and suffix
* common to all the enumerated names. Now make sure the prefix and
* suffix we actually use end/start on underscores. This prevents
* accidentally cutting into what is intended to be the unique part, which
* may cause forward compatibility problems when new names are added that
* don't start with the same characters in the unique part.
}
k := 0; {set default beginning trunc value}
for i := enum_trunc_beg downto 1 do begin {scan backwards thru prefix}
if e_p^.name_in_p^.str[i] = '_' then begin {found last underscore in prefix ?}
k := i; {underscore is last character in prefix}
exit;
end;
end; {back for previous prefix character}
enum_trunc_beg := k; {set final beginnning truncation length}
k := 0; {set default ending trunc value}
j := e_p^.name_in_p^.len; {get length of name to check suffix with}
for i := enum_trunc_end downto 1 do begin {scan forwards thru suffix}
if e_p^.name_in_p^.str[j+1-i] = '_' then begin {first underscore in suffix ?}
k := i; {underscore is first character in suffix}
exit;
end;
end; {back for next suffix character}
enum_trunc_end := k; {set final ending truncation length}
end; {done with variant data type is ENUMERATED}
got_enum_truncs: {ENUM_TRUNC_BEG, ENUM_TRUNC_END all set}
done_first: {all done with first time for this data type}
{
* Done with code that gets run only once for each new data type, before
* any fields are written.
*
*******************************************************************
}
ovlid := field_p^.field_variant; {save sequential ID of this overlay}
trunc_beg := 0; {init to not truncate start of field names}
{
* Put the STRUCT name in SNAME.
}
if ovlid = 0 then begin {this STRUCT is for non-variant part ?}
string_copy (name_nv, sname); {set name explicitly}
goto got_sname; {SNAME all set}
end;
case field_p^.field_var_val.dtype of {what type is the variant ID ?}
sst_dtype_int_k: begin {variant ID type is INTEGER}
string_vstring (sname, 'i', 1); {set struct name prefix}
i := field_p^.field_var_val.int_val; {get raw user variant ID}
if i < 0 then begin {variant ID value is negative ?}
string_append1 (sname, 'm'); {use "m" instead of minus sign}
i := -i; {make absolute value}
end;
string_f_int (str, i); {make variant number str}
string_append (sname, str); {make composite STRUCT name}
end;
sst_dtype_enum_k: begin {variant ID type is ENUMERATED}
i := field_p^.field_var_val.enum_p^.name_in_p^.len; {get raw user var name len}
string_substr ( {extract unique portion from variant name}
field_p^.field_var_val.enum_p^.name_in_p^, {input string to extract from}
enum_trunc_beg + 1, {index of first char to extract}
i - enum_trunc_end, {index of last char to extract}
str); {extracted string}
sst_w.name^ ( {rename to avoid intrinsic symbols, etc}
str.str, str.len, {preferred name and length}
'', 0, {mandatory suffix name and length}
sst_rename_ncheck_k, {just avoid reserved symbols, etc.}
sname, {returned name}
pos_hash); {hash table handle for new name, unused}
{
* Set TRUNC_BEG to the number of characters to truncate from the beginning
* of field names. This is to avoid redundant naming with the STRUCT
* name. The raw STRUCT name used for comparison is in STR. STR will
* be trashed.
}
f_p := field_p; {init pointer to first field in list}
string_append1 (str, '_'); {may truncate STRUCT name plus underscore}
trunc_beg := str.len; {init to max possible trunc length}
while f_p <> nil do begin {once for each field in this variant}
if f_p^.field_variant <> ovlid {this new field not within our variant ?}
then exit;
trunc_beg := {clip to max allowed trunc for this field}
min(trunc_beg, f_p^.name_out_p^.len - 1);
for i := 1 to trunc_beg do begin {scan start of names}
if f_p^.name_out_p^.str[i] <> str.str[i] then begin {first mismatch char ?}
trunc_beg := i - 1; {set index of last common character found}
exit; {no point looking further}
end;
end; {check next character in this field name}
f_p := f_p^.field_next_p; {advance to next field in record}
end; {back to process this new field name}
k := 0; {init trunc length to last underscore}
for i := trunc_beg downto 1 do begin {scan backwards thru truncated string}
if str.str[i] = '_' then begin {found last underscore in truncated string}
k := i; {set truncation length to here}
exit;
end;
end; {back to check previous character for "_"}
trunc_beg := k; {set final field name truncation length}
{
* Punt the whole truncation attempt if any of the field names now don't
* start with a letter.
}
f_p := field_p; {init pointer to first field in list}
while f_p <> nil do begin {once for each field in this variant}
if f_p^.field_variant <> ovlid {this new field not within our variant ?}
then exit;
if {first non-truncated char not a letter ?}
(f_p^.name_out_p^.str[trunc_beg + 1] < 'a') or
(f_p^.name_out_p^.str[trunc_beg + 1] > 'z')
then begin
trunc_beg := 0; {disable all truncation}
exit;
end;
f_p := f_p^.field_next_p; {advance to next field in record}
end; {back to process this new field name}
end; {end of variant ID type is ENUMERATED}
sst_dtype_bool_k: begin {variant ID type is BOOLEAN}
if field_p^.field_var_val.bool_val
then begin {variant ID is TRUE}
string_vstring (sname, 't', 1);
end
else begin {variant ID is FALSE}
string_vstring (sname, 'f', 1);
end;
;
end;
sst_dtype_char_k: begin {variant ID type is CHARACTER}
string_vstring (sname, 'c', 1); {set struct name prefix}
string_f_int (str, ord(field_p^.field_var_val.char_val));
string_append (sname, str); {make composite STRUCT name}
end;
otherwise {unexpected variant ID type}
str_h.first_char := field_p^.char_h;
str_h.last_char := field_p^.char_h;
syo_error (str_h, 'sst_c_write', 'variant_id_dtype_unexpected', nil, 0);
end;
got_sname: {got STRUCT name in SNAME}
{
* The final STRUCT name for this variant is in SNAME. TRUNC_BEG
* is all set if the user variant data type is enumerated.
}
sst_w.tab_indent^; {write STRUCT header}
sst_w.appendn^ ('struct {', 8);
sst_w.line_close^;
sst_w.indent^; {add indentation level for STRUCT}
{
* Make sure the first field starts at the correct record offset.
* Padding is added as an array of CHAR to reach the correct offset,
* if not already there.
}
if field_p^.field_ofs_adr > 0 then begin {need to add padding ?}
sst_w.name^ ( {make unique name for this UNUSED array}
'unused', 6, {desired name}
'', 0, {name suffix}
sst_rename_all_k, {this name will definately be unique}
name, {resulting name for UNUSED array}
pos_hash); {hash table position handle for new name}
string_hash_ent_add ( {make sure this UNUSED name never used again}
pos_hash, {hash table handle where entry will go}
unused1_p, unused2_p); {unused arguments returned by subroutine}
sst_w.tab_indent^;
sst_w.appendn^ ('char', 4);
sst_w.delimit^;
sst_w.append^ (name);
sst_w.appendn^ ('[', 1);
string_f_int (str, field_p^.field_ofs_adr);
sst_w.append^ (str);
sst_w.appendn^ ('];', 2);
sst_w.line_close^;
end; {done adding padding at start of this variant}
{
* Loop thru all the fields of this variant (overlay). FIELD_P will
* be left pointing to the first field not part of this variant, or
* NIL, if there are no fields after this variant.
}
loop_field: {back here for each new field}
string_substr ( {make field name with lead chars truncated}
field_p^.name_out_p^, {string to extract substring from}
trunc_beg + 1, {first char index of substring}
field_p^.name_out_p^.len, {last char index of substring}
str); {resulting substring}
if string_equal (str, name_nv) then begin {same name as non-variant STRUCT ?}
string_appendn (str, '_2', 2); {at least some attempt to make unique name}
end;
sst_w.tab_indent^; {go to proper indentation level}
sst_w.indent^; {indent wrapped lines}
sst_w_c_dtype_simple ( {write data type declaration}
field_p^.field_dtype_p^, {descriptor for data type to write}
str, {name of field to declare}
pack); {TRUE if this is field in packed record}
sst_w.undent^; {undo indent for wrapped lines}
sst_w.appendn^ (';', 1);
sst_w.line_close^;
{
* Done writing the C code declaring this field. The field name actually
* declared is in STR. Now update the field output name so that it will
* be correctly referenced in later code.
}
string_copy (sname, name); {start with STRUCT name}
string_append1 (name, '.');
string_append (name, str); {add field name}
if field_p^.name_out_p^.max < name.len then begin {old string too small ?}
string_alloc ( {allocate memory for new string}
name.len, {min required length of new string}
sst_scope_p^.mem_p^, {handle to memory context}
false, {don't need to individually deallocate this}
field_p^.name_out_p); {returned pointer to new memory}
end; {NAME_OUT_P now all set for copy}
string_copy (name, field_p^.name_out_p^); {set new name for this field}
{
* Advance to next field.
}
field_p := field_p^.field_next_p; {point to next field in record}
if {back and process this new field ?}
(field_p <> nil) and then {new field exists ?}
(field_p^.field_variant = ovlid) {still within same variant ?}
then goto loop_field;
{
* Done declaring all the fields in this variant.
* Now close the STRUCT for this variant.
}
sst_w.tab_indent^; {go to proper indentation level}
sst_w.appendn^ ('} ', 2);
sst_w.append^ (sname);
sst_w.appendn^ (';', 1);
sst_w.line_close^;
sst_w.undent^; {undo indentation for STRUCT}
end;
|
{ behavior3delphi - a Behavior3 client library (Behavior Trees) for Delphi
by Dennis D. Spreen <dennis@spreendigital.de>
see Behavior3.pas header for full license information }
unit Behavior3.Core.Decorator;
interface
uses
System.JSON,
Behavior3, Behavior3.Core.BaseNode;
type
(**
* Decorator is the base class for all decorator nodes. Thus, if you want to
* create new custom decorator nodes, you need to inherit from this class.
*
* When creating decorator nodes, you will need to propagate the tick signal
* to the child node manually, just like the composite nodes. To do that,
* override the `tick` method and call the `_execute` method on the child
* node. For instance, take a look at how the Inverter node inherit this
* class and how it call its children:
*
* // Inherit from Decorator, using the util function Class.
* var Inverter = b3.Class(b3.Decorator, {
* name: 'Inverter',
*
* tick: function(tick) {
* if (!this.child) {
* return b3.ERROR;
* }
*
* // Propagate the tick
* var status = this.child._execute(tick);
*
* if (status == b3.SUCCESS) {
* status = b3.FAILURE;
* } else if (status == b3.FAILURE) {
* status = b3.SUCCESS;
* }
*
* return status;
* }
* });
*
* @module b3
* @class Decorator
* @extends BaseNode
**)
TB3Decorator = class(TB3BaseNode)
private
protected
Child: TB3BaseNode;
public
constructor Create; override;
constructor Create(ChildNode: TB3BaseNode); overload;
procedure Load(JsonNode: TJSONValue); override;
end;
implementation
{ TB3Decorator }
uses
Behavior3.Helper, Behavior3.Core.BehaviorTree;
constructor TB3Decorator.Create;
begin
inherited Create;
(**
* Node category. Default to b3.DECORATOR.
* @property {String} category
* @readonly
**)
Category := Behavior3.Decorator;
(**
* Initialization method.
* @method initialize
* @constructor
**)
end;
constructor TB3Decorator.Create(ChildNode: TB3BaseNode);
begin
Child := ChildNode;
Create;
{
// initialize: function(params) {
b3.BaseNode.prototype.initialize.call(this);
this.child = params.child || null;
}
end;
procedure TB3Decorator.Load(JsonNode: TJSONValue);
var
ChildNode: String;
begin
inherited;
ChildNode := JsonNode.GetValue('child', '');
if ChildNode = '' then
Child := NIL
else
Child := Tree.Nodes[ChildNode];
end;
end.
|
unit DAO.Acareacao;
interface
uses
FireDAC.Comp.Client, System.SysUtils, DAO.Conexao, Model.Acareacoes;
type
TAcareacaoDAO = class
private
FConexao : TConexao;
public
constructor Create;
function GetID(): Integer;
function Inserir(AAcareacoes: TAcareacoes): Boolean;
function Alterar(AAcareacoes: TAcareacoes): Boolean;
function Excluir(AAcareacoes: TAcareacoes): Boolean;
function Pesquisar(aParam: array of variant): TFDQuery;
function AcareacaoExiste(AAcareacoes: TAcareacoes): Boolean;
end;
const
TABLENAME = 'tbacareacoes';
implementation
{ TAcareacaoDAO }
uses Control.Sistema;
function TAcareacaoDAO.AcareacaoExiste(AAcareacoes: TAcareacoes): Boolean;
var
FDQuery: TFDQuery;
begin
try
Result := False;
FDQuery := FConexao.ReturnQuery();
FDQuery.SQL.Clear;
FDQuery.SQL.Add('select * from ' + TABLENAME + ' where ID_ACAREACAO = :ID_ACAREACAO and NUM_NOSSONUMERO = :NUM_NOSSONUMERO');
FDQuery.ParamByName('ID_ACAREACAO').AsString := AAcareacoes.Id;
FDQuery.ParamByName('NUM_NOSSONUMERO').AsString := AAcareacoes.Nossonumero;
FDQuery.Open();
if FDQuery.IsEmpty then Exit;
Result := True;
finally
FDQuery.Connection.Close;
FDquery.Free;
end;
end;
function TAcareacaoDAO.Alterar(AAcareacoes: TAcareacoes): Boolean;
var
FDQuery: TFDQuery;
begin
try
Result := False;
FDQuery := FConexao.ReturnQuery();
FDQuery.ExecSQL('UPDATE ' + TABLENAME + ' SET ' +
'ID_ACAREACAO = :ID_ACAREACAO, DAT_ACAREACAO = :DAT_ACAREACAO, ' +
'NUM_NOSSONUMERO = :NUM_NOSSONUMERO, COD_ENTREGADOR = :COD_ENTREGADOR, COD_BASE = :COD_BASE, ' +
'DAT_ENTREGA = :DAT_ENTREGA, DES_MOTIVO = :DES_MOTIVO, DES_TRATATIVA = :DES_TRATATIVA, ' +
'DES_APURACAO = :DES_APURACAO, DES_RESULTADO = :DES_RESULTADO, VAL_EXTRAVIO = :VAL_EXTRAVIO, ' +
'VAL_MULTA = :VAL_MULTA, DES_ENVIO_CORRESPONDENCIA = :DES_ENVIO_CORRESPONDENCIA, ' +
'DES_RETORNO_CORRESPONDENCIA = :DES_RETORNO_CORRESPONDENCIA, DES_OBSERVACOES = :DES_OBSERVACOES, ' +
'DOM_FINALIZAR = :DOM_FINALIZAR, DES_EXECUTOR = :DES_EXECUTOR, DAT_MANUTENCAO = :DAT_MANUTENCAO ' +
'WHERE SEQ_ACAREACAO = :SEQ_ACAREACAO;',
[AAcareacoes.Id, AAcareacoes.Data, AAcareacoes.Nossonumero, AAcareacoes.Entregador, AAcareacoes.Base,
AAcareacoes.DataEntrega, AAcareacoes.Motivo, AAcareacoes.Tratativa, AAcareacoes.Apuracao, AAcareacoes.Resultado,
AAcareacoes.Extravio, AAcareacoes.Multa, AAcareacoes.Envio, AAcareacoes.Retorno, AAcareacoes.Obs,
AAcareacoes.Finalizar, AAcareacoes.Executor, AAcareacoes.Manutencao, AAcareacoes.Sequencia]);
Result := True;
finally
FDQuery.Connection.Close;
FDQuery.Free;
end;
end;
constructor TAcareacaoDAO.Create;
begin
FConexao := TSistemaControl.GetInstance().Conexao;
end;
function TAcareacaoDAO.Excluir(AAcareacoes: TAcareacoes): Boolean;
var
FDQuery: TFDQuery;
begin
try
Result := False;
FDQuery := FConexao.ReturnQuery();
FDQuery.ExecSQL('delete from ' + TABLENAME + ' where SEQ_ACAREACAO = :SEQ_ACAREACAO', [AAcareacoes.Sequencia]);
Result := True;
finally
FDQuery.Connection.Close;
FDquery.Free;
end;
end;
function TAcareacaoDAO.GetID(): Integer;
var
FDQuery: TFDQuery;
begin
try
FDQuery := FConexao.ReturnQuery();
FDQuery.Open('select coalesce(max(SEQ_ACAREACAO),0) + 1 from ' + TABLENAME);
try
Result := FDQuery.Fields[0].AsInteger;
finally
FDQuery.Close;
end;
finally
FDQuery.Connection.Close;
FDQuery.Free;
end;
end;
function TAcareacaoDAO.Inserir(AAcareacoes: TAcareacoes): Boolean;
var
FDQuery: TFDQuery;
begin
try
Result := False;
FDQuery := FConexao.ReturnQuery();
AAcareacoes.Sequencia := GetID();
FDQuery.ExecSQL('INSERT INTO ' + TABLENAME + '(SEQ_ACAREACAO, ID_ACAREACAO, DAT_ACAREACAO, NUM_NOSSONUMERO, COD_ENTREGADOR, ' +
'COD_BASE, DAT_ENTREGA, DES_MOTIVO, DES_TRATATIVA, DES_APURACAO, DES_RESULTADO, VAL_EXTRAVIO, VAL_MULTA, ' +
'DES_ENVIO_CORRESPONDENCIA, DES_RETORNO_CORRESPONDENCIA, DES_OBSERVACOES, DOM_FINALIZAR, DES_EXECUTOR, ' +
'DAT_MANUTENCAO) ' +
'VALUES ' +
'(:SEQ_ACAREACAO, :ID_ACAREACAO, :DAT_ACAREACAO, :NUM_NOSSONUMERO, :COD_ENTREGADOR, :COD_BASE, :DAT_ENTREGA, ' +
':DES_MOTIVO, :DES_TRATATIVA, :DES_APURACAO, :DES_RESULTADO, :VAL_EXTRAVIO, :VAL_MULTA, ' +
':DES_ENVIO_CORRESPONDENCIA, :DES_RETORNO_CORRESPONDENCIA, :DES_OBSERVACOES, :DOM_FINALIZAR, :DES_EXECUTOR, ' +
':DAT_MANUTENCAO);',
[AAcareacoes.Sequencia, AAcareacoes.Id, AAcareacoes.Data, AAcareacoes.Nossonumero, AAcareacoes.Entregador,
AAcareacoes.Base, AAcareacoes.DataEntrega, AAcareacoes.Motivo, AAcareacoes.Tratativa, AAcareacoes.Apuracao,
AAcareacoes.Resultado, AAcareacoes.Extravio, AAcareacoes.Multa, AAcareacoes.Envio, AAcareacoes.Retorno,
AAcareacoes.Obs, AAcareacoes.Finalizar, AAcareacoes.Executor, AAcareacoes.Manutencao]);
Result := True;
finally
FDQuery.Connection.Close;
FDQuery.Free;
end;
end;
function TAcareacaoDAO.Pesquisar(aParam: array of variant): TFDQuery;
var
FDQuery: TFDQuery;
begin
FDQuery := FConexao.ReturnQuery();
if Length(aParam) < 2 then Exit;
FDQuery.SQL.Clear;
FDQuery.SQL.Add('select * from ' + TABLENAME);
if aParam[0] = 'SEQUENCIA' then
begin
FDQuery.SQL.Add('WHERE SEQ_ACAREACAO = :SEQ_ACAREACAO');
FDQuery.ParamByName('SEQ_ACAREACAO').AsInteger := aParam[1];
end;
if aParam[0] = 'ID' then
begin
FDQuery.SQL.Add('WHERE ID_ACAREACAO = :ID_ACAREACAO');
FDQuery.ParamByName('ID_ACAREACAO').AsString := aParam[1];
end;
if aParam[0] = 'DATA' then
begin
FDQuery.SQL.Add('WHERE DAT_ACAREACAO = :DAT_ACAREACAO');
FDQuery.ParamByName('WHERE DAT_ACAREACAO').AsDate := aParam[1];
end;
if aParam[0] = 'NN' then
begin
FDQuery.SQL.Add('WHERE NUM_NOSSONUMERO = :NUM_NOSSONUMERO');
FDQuery.ParamByName('NUM_NOSSONUMERO').AsString := aParam[1];
end;
if aParam[0] = 'FILTRO' then
begin
FDQuery.SQL.Add('WHERE ' + aParam[1]);
end;
FDQuery.Open;
Result := FDQuery;
end;
end.
|
unit Rule_TROUGH;
interface
uses
BaseRule,
BaseRuleData;
(*//
TROUGH -- PEAK
TROUGH(CLOSE,N,1)
收盘价N%之字转向的前1个波谷值
//*)
type
TRule_TROUGH = class(TBaseRule)
protected
fParamA: Word;
fInt64Ret: PArrayInt64;
fFloatRet: PArrayDouble;
function Get_TROUGH_ValueF(AIndex: integer): double;
function Get_TROUGH_ValueI(AIndex: integer): int64;
function GetParamA: Word;
procedure SetParamA(const Value: Word);
procedure ComputeInt64;
procedure ComputeFloat;
public
constructor Create(ADataType: TRuleDataType = dtNone); override;
destructor Destroy; override;
procedure Execute; override;
procedure Clear; override;
property ValueF[AIndex: integer]: double read Get_TROUGH_ValueF;
property ValueI[AIndex: integer]: int64 read Get_TROUGH_ValueI;
property ParamA: Word read GetParamA write SetParamA;
end;
// 分子 numerator 分母 denominator 比 ratio
TParamFactor = record { 系数 }
Numerator : int64; // 分子
Denominator : int64; // 分母
Ratio : double; // value
end;
PDMAParam = ^TDMAParam;
TDMAParam = record
ParamN : Word;
ParamFactor1: TParamFactor;
ParamFactor2: TParamFactor;
end;
procedure InitDMAParam(AParam: PDMAParam; AParamN: word);
implementation
{ TRule_TROUGH }
constructor TRule_TROUGH.Create(ADataType: TRuleDataType = dtNone);
begin
inherited;
fInt64Ret := nil;
fFloatRet := nil;
// SetLength(fFloatRet, 0);
// SetLength(fInt64Ret, 0);
end;
destructor TRule_TROUGH.Destroy;
begin
Clear;
inherited;
end;
procedure TRule_TROUGH.Execute;
begin
Clear;
if Assigned(OnGetDataLength) then
begin
fBaseRuleData.DataLength := OnGetDataLength;
case fBaseRuleData.DataType of
dtInt64: begin
ComputeInt64;
end;
dtDouble: begin
ComputeFloat;
end;
end;
end;
end;
procedure TRule_TROUGH.Clear;
begin
CheckInArrayDouble(fFloatRet);
CheckInArrayInt64(fInt64Ret);
fBaseRuleData.DataLength := 0;
end;
(*
当日指数平均值 = 平滑系数*(当日指数值-昨日指数平均值)+ 昨日指数平均值
平滑系数 = 2 /(周期单位+1)
EMA(X,N) = 2*X/(N+1)+(N-1)/(N+1)*昨天的指数收盘平均值
http://blog.csdn.net/wlr_tang/article/details/7243287
2、EMA(X,N)求X的
N日指数平滑移动平均
。算法是:
若Y=EMA(X,N),则Y=[2*X+(N-1)*Y’]/(N+1),其中Y’表示上一周期的Y值。
EMA引用函数在计算机上使用递归算法很容易实现,但不容易理解。例举分析说明EMA函数。
X是变量,每天的X值都不同,从远到近地标记,它们分别记为X1,X2,X3,….,Xn
如果N=1,则EMA(X,1)=[2*X1+(1-1)*Y’]/(1+1)=X1
如果N=2,则EMA(X,2)=[2*X2+(2-1)*Y’]/(2+1)=
(2/3)*X2+(1/3)Y’
如果N=3,则EMA(X,3)=[2*X3+(3-1)*Y’]/(3+1)=
[2*X3+2*Y’]/4=
[2*X3+2*((2/3)*X2+(1/3)*Y’)]/4=
(1/2)*X3+(1/3)*X2+(1/6)*Y’
如果N=4,则EMA(X,4)=[2*X4+(4-1)*Y’]/(4+1)=
2/5*X4 + 3/5*((1/2)*X3+(1/3)*X2+(1/6)*X1)=
2/5*X4 + 3/10*X3+3/15*X2+3/30*X1
如果N=5,则EMA(X,5)=
2/(5+1)*X5+(5-1)/(5+1)(2/5*X4+3/10*X3+3/15*X2+3/30*X1)=
(1/3)*X5+(4/15)*X4+(3/15)*X3+(2/15)*X2+(1/15)*X1
EMA(X,3)=[2*X3+(3-1)*Y’]/(3+1)
=[2*X3+(3-1)* (2*X2+(2-1) * X1)]/(3+1)
*)
procedure InitDMAParam(AParam: PDMAParam; AParamN: word);
begin
AParam.ParamN := AParamN;
AParam.ParamFactor1.Numerator := 2;
AParam.ParamFactor1.Denominator := AParamN + 1;
AParam.ParamFactor1.Ratio := AParam.ParamFactor1.Numerator / AParam.ParamFactor1.Denominator;
AParam.ParamFactor2.Numerator := AParamN - 1;
AParam.ParamFactor2.Denominator := AParamN + 1;
AParam.ParamFactor2.Ratio := AParam.ParamFactor2.Numerator / AParam.ParamFactor2.Denominator;
end;
procedure TRule_TROUGH.ComputeInt64;
var
tmpInt64_Meta: array of Int64;
i: integer;
tmpDMAParam: TDMAParam;
tmpInt64: Int64;
begin
if Assigned(OnGetDataI) then
begin
if fInt64Ret = nil then
fInt64Ret := CheckOutArrayInt64;
SetArrayInt64Length(fInt64Ret, fBaseRuleData.DataLength);
SetLength(tmpInt64_Meta, fBaseRuleData.DataLength);
FillChar(tmpDMAParam, SizeOf(tmpDMAParam), 0);
InitDMAParam(@tmpDMAParam, fParamA);
for i := 0 to fBaseRuleData.DataLength - 1 do
begin
tmpInt64_Meta[i] := OnGetDataI(i);
if i = 0 then
begin
SetArrayInt64Value(fInt64Ret, i, tmpInt64_Meta[i]);
fBaseRuleData.MaxI := tmpInt64_Meta[i];
fBaseRuleData.MinI := fBaseRuleData.MaxI;
fInt64Ret.MaxValue := fBaseRuleData.MaxI;
fInt64Ret.MinValue := fBaseRuleData.MaxI;
end else
begin
tmpInt64 := Round(tmpInt64_Meta[i] * tmpDMAParam.ParamFactor1.Ratio +
GetArrayInt64Value(fInt64Ret, i - 1) * tmpDMAParam.ParamFactor2.Ratio);
SetArrayInt64Value(fInt64Ret, i, tmpInt64);
if fBaseRuleData.MaxI < tmpInt64 then
begin
fBaseRuleData.MaxI := tmpInt64;
fInt64Ret.MaxValue := fBaseRuleData.MaxI;
end;
if fBaseRuleData.MinI > tmpInt64 then
begin
fBaseRuleData.MinI := tmpInt64;
fInt64Ret.MinValue := fBaseRuleData.MinI;
end;
end;
end;
end;
end;
procedure TRule_TROUGH.ComputeFloat;
var
tmpFloat_Meta: array of double;
i: integer;
tmpDMAParam: TDMAParam;
tmpDouble: double;
begin
if Assigned(OnGetDataF) then
begin
if fFloatRet = nil then
fFloatRet := CheckOutArrayDouble;
SetArrayDoubleLength(fFloatRet, fBaseRuleData.DataLength);
SetLength(tmpFloat_Meta, fBaseRuleData.DataLength);
FillChar(tmpDMAParam, SizeOf(tmpDMAParam), 0);
InitDMAParam(@tmpDMAParam, fParamA);
for i := 0 to fBaseRuleData.DataLength - 1 do
begin
tmpFloat_Meta[i] := OnGetDataF(i);
if i = 0 then
begin
SetArrayDoubleValue(fFloatRet, i, tmpFloat_Meta[i]);
fBaseRuleData.MaxF := tmpFloat_Meta[i];
fBaseRuleData.MinF := fBaseRuleData.MaxF;
fFloatRet.MaxValue := fBaseRuleData.MaxF;
fFloatRet.MinValue := fBaseRuleData.MaxF;
end else
begin
tmpDouble := tmpFloat_Meta[i] * tmpDMAParam.ParamFactor1.Ratio +
GetArrayDoubleValue(fFloatRet, i - 1) * tmpDMAParam.ParamFactor2.Ratio;
SetArrayDoubleValue(fFloatRet, i, tmpDouble);
if fBaseRuleData.MaxF < tmpDouble then
begin
fBaseRuleData.MaxF := tmpDouble;
fFloatRet.MaxValue := fBaseRuleData.MaxF;
end;
if fBaseRuleData.MinF > tmpDouble then
begin
fBaseRuleData.MinF := tmpDouble;
fFloatRet.MinValue := fBaseRuleData.MinF;
end;
end;
end;
end;
end;
function TRule_TROUGH.GetParamA: Word;
begin
Result := fParamA;
end;
procedure TRule_TROUGH.SetParamA(const Value: Word);
begin
if Value > 0 then
begin
fParamA := Value;
end;
end;
function TRule_TROUGH.Get_TROUGH_ValueF(AIndex: integer): double;
begin
Result := 0;
if fBaseRuleData.DataType = dtDouble then
begin
if fFloatRet <> nil then
begin
Result := GetArrayDoubleValue(fFloatRet, AIndex);
end;
end;
end;
function TRule_TROUGH.Get_TROUGH_ValueI(AIndex: integer): int64;
begin
Result := 0;
if fBaseRuleData.DataType = dtInt64 then
begin
if fInt64Ret <> nil then
begin
Result := GetArrayInt64Value(fInt64Ret, AIndex);
end;
end;
end;
end.
|
{ Subroutine SST_R_PAS_RAW_SMENT
*
* Create new opcodes from the RAW_STATEMENT syntax. All opcodes will be of
* "executable" type.
}
module sst_r_pas_RAW_SMENT;
define sst_r_pas_raw_sment;
%include 'sst_r_pas.ins.pas';
procedure sst_r_pas_raw_sment; {build opcodes from RAW_STATEMENT syntax}
const
max_msg_parms = 3; {max parameters we can pass to a message}
var
tag: sys_int_machine_t; {syntax tag ID}
str_h: syo_string_t; {handle to string associated with TAG}
tag2: sys_int_machine_t; {extra syntax tag to avoid corrupting TAG}
str2_h: syo_string_t; {handle to string associated with TAG2}
var_p: sst_var_p_t; {points to variable descriptor}
sym_p: sst_symbol_p_t; {pointer to scratch symbol descriptor}
sym_prev_p: sst_symbol_p_t; {points to previous symbol in linked list}
args_here: boolean; {TRUE if subroutine has call arguments}
s: string_var80_t; {scratch var string for error messages, etc}
msg_parm: {parameter references for messages}
array[1..max_msg_parms] of sys_parm_msg_t;
stat: sys_err_t; {completion status code}
label
tag_loop, loop_tag6, loop_tag8, do_call, leave;
{
*************************************************************************
*
* Local subroutine GET_LABEL_SYM_PNT (STR_H,SYM_P)
*
* STR_H is the SYN string handle for a label name. SYM_P will be returned
* pointing to the symbol descriptor for the label. Errors will be checked.
}
procedure get_label_sym_pnt (
in str_h: syo_string_t; {string handle to lable name}
out sym_p: sst_symbol_p_t); {returned pointing to symbol descriptor}
var
fnam: string_treename_t; {file name passed to a message}
lnum: sys_int_machine_t; {line number passed to a message}
begin
fnam.max := sizeof(fnam.str);
sst_symbol_lookup (str_h, sym_p, stat); {get pointer to label symbol}
syo_error_abort (stat, str_h, '', '', nil, 0);
if sym_p^.symtype <> sst_symtype_label_k then begin {symbol not a label ?}
sst_charh_info (sym_p^.char_h, fnam, lnum);
sys_msg_parm_vstr (msg_parm[1], sym_p^.name_in_p^);
sys_msg_parm_int (msg_parm[2], lnum);
sys_msg_parm_vstr (msg_parm[3], fnam);
syo_error (str_h, 'sst_pas_read', 'symbol_not_label', msg_parm, 3);
end;
end;
{
*************************************************************************
*
* Start of main routine.
}
begin
s.max := sizeof(s.str); {init local var string}
syo_level_down; {down into RAW_STATMENT syntax}
tag_loop: {back here each new top level synax tag}
syo_get_tag_msg (tag, str_h, 'sst_pas_read', 'statement_exec_bad', nil, 0);
case tag of
{
***************************
*
* No more tags in this RAW_STATEMENT syntax.
}
syo_tag_end_k: begin
goto leave; {go to normal exit code}
end;
{
***************************
*
* Tag indicates a null statement. This happens in empty BEGIN ... END blocks,
* and consecutive ";". This is harmless and ignored.
}
1: begin
end;
{
***************************
*
* Tag is label name of a GOTO statement.
}
2: begin
sst_opcode_new; {make new opcode descriptor}
sst_opc_p^.opcode := sst_opc_goto_k; {set opcode type}
sst_opc_p^.str_h := str_h; {save handle to source characters}
get_label_sym_pnt (str_h, sst_opc_p^.label_sym_p); {get pointer to label symbol}
end;
{
***************************
*
* Tag is the conditional logical expression of an IF statement.
}
3: begin
sst_opcode_new; {make new opcode descriptor}
sst_opc_p^.opcode := sst_opc_if_k; {set opcode type}
sst_opc_p^.str_h := str_h; {save handle to source characters}
sst_r_pas_exp (str_h, false, sst_opc_p^.if_exp_p); {process conditional expression}
sst_exp_useage_check ( {check expression attributes for this useage}
sst_opc_p^.if_exp_p^, {expression to check}
[sst_rwflag_read_k], {read/write access needed to expression value}
sst_dtype_bool_p^); {data type value must be compatible with}
syo_get_tag_msg (tag, str_h, 'sst_pas_read', 'statement_exec_bad', nil, 0);
sst_opcode_pos_push (sst_opc_p^.if_true_p); {new opcodes get chained here}
sst_r_pas_raw_sment; {build opcodes for TRUE case}
sst_opcode_pos_pop; {back to regular opcode chain}
syo_get_tag_msg (tag, str_h, 'sst_pas_read', 'statement_exec_bad', nil, 0);
if tag = syo_tag_end_k
then begin {no ELSE clause}
sst_opc_p^.if_false_p := nil; {indicate no opcodes for FALSE case}
end
else begin {ELSE clause exists}
sst_opcode_pos_push (sst_opc_p^.if_false_p); {new opcodes get chained here}
sst_r_pas_raw_sment; {build opcodes for FALSE case}
sst_opcode_pos_pop; {back to regular opcode chain}
end
;
end;
{
***************************
*
* Tag is for a CASE statement.
}
4: begin
sst_r_pas_sment_case (str_h); {process CASE statement}
end;
{
***************************
*
* Tag is for a FOR statement.
}
5: begin
sst_opcode_new; {make new opcode descriptor}
sst_opc_p^.opcode := sst_opc_loop_cnt_k; {opcode is for a counted loop}
sst_opc_p^.str_h := str_h; {save handle to source characters}
{
* Process counting variable.
}
syo_get_tag_msg (tag, str_h, 'sst_pas_read', 'statement_exec_bad', nil, 0);
if tag <> 1 then syo_error_tag_unexp (tag, str_h);
sst_r_pas_variable (sst_opc_p^.lpcn_var_p); {get descriptor for counting var}
sst_var_funcname (sst_opc_p^.lpcn_var_p^); {call func instead of stuff return val}
if sst_opc_p^.lpcn_var_p^.vtype <> sst_vtype_var_k then begin {not a variable ?}
syo_get_tag_string (str_h, s); {get "variable" reference string}
sys_msg_parm_vstr (msg_parm[1], s);
syo_error (str_h, 'sst_pas_read', 'not_a_variable', msg_parm, 1);
end;
if not (sst_rwflag_write_k in sst_opc_p^.lpcn_var_p^.rwflag) then begin
syo_error (str_h, 'sst', 'var_not_writeable', nil, 0);
end;
{
* Process starting value expression.
}
syo_get_tag_msg (tag, str_h, 'sst_pas_read', 'statement_exec_bad', nil, 0);
if tag <> 1 then syo_error_tag_unexp (tag, str_h);
sst_r_pas_exp (str_h, false, sst_opc_p^.lpcn_exp_start_p); {build exp descriptor}
sst_exp_useage_check ( {check expression attributes for this useage}
sst_opc_p^.lpcn_exp_start_p^, {expression to check}
[sst_rwflag_read_k], {read/write access needed to expression value}
sst_opc_p^.lpcn_var_p^.dtype_p^); {data type value must be compatible with}
{
* Process TO/DOWNTO keywords.
}
syo_get_tag_msg (tag, str_h, 'sst_pas_read', 'statement_exec_bad', nil, 0);
case tag of
1: begin {keyword is TO}
sst_opc_p^.lpcn_inc_dir := sst_incdir_up_k;
end;
2: begin {keyword is DOWNTO}
sst_opc_p^.lpcn_inc_dir := sst_incdir_down_k;
end;
otherwise
syo_error_tag_unexp (tag, str_h);
end; {end of TO/DOWNTO tag cases}
{
* Process ending value expression.
}
syo_get_tag_msg (tag, str_h, 'sst_pas_read', 'statement_exec_bad', nil, 0);
if tag <> 1 then syo_error_tag_unexp (tag, str_h);
sst_r_pas_exp (str_h, false, sst_opc_p^.lpcn_exp_end_p); {build exp descriptor}
sst_exp_useage_check ( {check expression attributes for this useage}
sst_opc_p^.lpcn_exp_end_p^, {expression to check}
[sst_rwflag_read_k], {read/write access needed to expression value}
sst_opc_p^.lpcn_var_p^.dtype_p^); {data type value must be compatible with}
{
* Set up the loop increment value expression. This is either -1 or +1,
* or an explicit value if the BY keyword is present.
}
syo_get_tag_msg (tag, str_h, 'sst_pas_read', 'statement_exec_bad', nil, 0);
case tag of
1: begin {implicit value is either -1 or +1}
sst_mem_alloc_namesp ( {allocate mem for increment value expression}
sizeof(sst_opc_p^.lpcn_exp_inc_p^), sst_opc_p^.lpcn_exp_inc_p);
with sst_opc_p^.lpcn_exp_inc_p^: exp do begin {EXP is increment expression desc}
exp.str_h := str_h; {source is TO/DOWNTO keyword}
exp.dtype_p := sst_config.int_machine_p;
exp.dtype_hard := false;
exp.val_eval := true;
exp.val_fnd := true;
exp.val.dtype := sst_dtype_int_k;
case sst_opc_p^.lpcn_inc_dir of
sst_incdir_up_k: exp.val.int_val := 1;
sst_incdir_down_k: exp.val.int_val := -1;
end;
exp.rwflag := [sst_rwflag_read_k];
exp.term1.next_p := nil;
exp.term1.op2 := sst_op2_none_k;
exp.term1.op1 := sst_op1_none_k;
exp.term1.ttype := sst_term_const_k;
exp.term1.str_h := exp.str_h;
exp.term1.dtype_p := exp.dtype_p;
exp.term1.dtype_hard := false;
exp.term1.val_eval := true;
exp.term1.val_fnd := true;
exp.term1.val := exp.val;
exp.term1.rwflag := exp.rwflag;
end; {done with EXP abbreviation}
end;
2: begin {loop increment value is given explicitly}
sst_r_pas_exp (str_h, false, sst_opc_p^.lpcn_exp_inc_p); {build exp descriptor}
sst_exp_useage_check ( {check expression attributes for this useage}
sst_opc_p^.lpcn_exp_inc_p^, {expression to check}
[sst_rwflag_read_k], {read/write access needed to expression value}
sst_opc_p^.lpcn_var_p^.dtype_p^); {data type value must be compatible with}
end;
otherwise
syo_error_tag_unexp (tag, str_h);
end;
{
* Process the loop statement.
}
syo_get_tag_msg (tag, str_h, 'sst_pas_read', 'statement_exec_bad', nil, 0);
if tag <> 1 then syo_error_tag_unexp (tag, str_h);
sst_opcode_pos_push (sst_opc_p^.lpcn_code_p); {new opcodes get chained here}
sst_r_pas_raw_sment; {build opcodes for body of loop}
sst_opcode_pos_pop; {back to regular opcode chain}
end; {end of FOR statement case}
{
***************************
*
* Tag is for a REPEAT ... UNTIL loop.
}
6: begin
sst_opcode_new; {make new opcode descriptor}
sst_opc_p^.opcode := sst_opc_loop_tbot_k; {set opcode type}
sst_opc_p^.str_h := str_h; {save handle to source characters}
sst_opcode_pos_push (sst_opc_p^.lpbt_code_p); {new opcodes get chained here}
loop_tag6: {back here each new syntax tag}
syo_get_tag_msg (tag, str_h, 'sst_pas_read', 'statement_exec_bad', nil, 0);
case tag of
1: begin {tag is for more statements in loop body}
sst_r_pas_raw_sment; {add more statements to body of loop}
goto loop_tag6; {back for next tag}
end;
2: begin {tag is for loop termination expression}
sst_opcode_pos_pop; {back to regular opcode chain}
sst_r_pas_exp (str_h, false, sst_opc_p^.lpbt_exp_p); {make ending expression}
sst_exp_useage_check ( {check expression attributes for this useage}
sst_opc_p^.lpbt_exp_p^, {expression to check}
[sst_rwflag_read_k], {read/write access needed to expression value}
sst_dtype_bool_p^); {data type value must be compatible with}
end;
otherwise
syo_error_tag_unexp (tag, str_h);
end;
end;
{
***************************
*
* Tag is for a WHILE statement.
}
7: begin
sst_opcode_new; {make new opcode descriptor}
sst_opc_p^.opcode := sst_opc_loop_ttop_k; {set opcode type}
sst_opc_p^.str_h := str_h; {save handle to source characters}
{
* Process loop conditional expression.
}
syo_get_tag_msg (tag, str_h, 'sst_pas_read', 'statement_exec_bad', nil, 0);
if tag <> 1 then syo_error_tag_unexp (tag, str_h);
sst_r_pas_exp (str_h, false, sst_opc_p^.lptp_exp_p); {make conditional expression}
sst_exp_useage_check ( {check expression attributes for this useage}
sst_opc_p^.lptp_exp_p^, {expression to check}
[sst_rwflag_read_k], {read/write access needed to expression value}
sst_dtype_bool_p^); {data type value must be compatible with}
{
* Process loop body code.
}
syo_get_tag_msg (tag, str_h, 'sst_pas_read', 'statement_exec_bad', nil, 0);
if tag <> 1 then syo_error_tag_unexp (tag, str_h);
sst_opcode_pos_push (sst_opc_p^.lptp_code_p); {new opcodes get chained here}
sst_r_pas_raw_sment; {build opcodes for loop body}
sst_opcode_pos_pop; {back to regular opcode chain}
end;
{
***************************
*
* Tag is for a WITH statement.
}
8: begin
sst_opcode_new; {make new opcode descriptor}
sst_opc_p^.opcode := sst_opc_abbrev_k; {set opcode type}
sst_opc_p^.str_h := str_h; {save handle to source characters}
sst_scope_new; {create new scope for abbreviations}
sst_scope_p^.flag_ref_used := true; {flag referenced symbols as used}
sst_opc_p^.abbrev_scope_p := sst_scope_p; {save scope of abbreviation symbols}
sst_opc_p^.abbrev_sym_first_p := nil; {init to no symbols in linked list}
sym_prev_p := nil; {init to no previous symbol created yet}
loop_tag8: {back here each new tag in WITH statement}
syo_get_tag_msg (tag, str_h, 'sst_pas_read', 'statement_exec_bad', nil, 0);
case tag of
1: begin {tag is for another WITH_ABBREV syntax}
syo_level_down; {down into WITH_ABBREV syntax}
syo_get_tag_msg ( {get tag for abbreviation expansion "variable"}
tag, str_h, 'sst_pas_read', 'statement_with_bad', nil, 0);
if tag <> 1 then syo_error_tag_unexp (tag, str_h);
sst_r_pas_variable (var_p); {create var descriptor for abbrev expansion}
sst_var_funcname (var_p^); {call func instead of stuff return value}
syo_get_tag_msg ( {get tag for abbreviation name}
tag2, str2_h, 'sst_pas_read', 'statement_with_bad', nil, 0);
if tag <> 1 then syo_error_tag_unexp (tag, str_h);
syo_level_up; {back up from WITH_ABBREV syntax}
sst_symbol_new {create initial symbol for abbrev name}
(str2_h, syo_charcase_down_k, sym_p, stat);
syo_error_abort (stat, str2_h, 'sst_pas_read', 'statement_with_bad', nil, 0);
sym_p^.symtype := sst_symtype_abbrev_k; {new symbol is an abbreviation}
sym_p^.abbrev_var_p := var_p; {point abbreviation to its expansion}
sym_p^.next_p := nil; {init this symbol to be end of chain}
if sym_prev_p = nil
then begin {this is the first symbol in the chain}
sst_opc_p^.abbrev_sym_first_p := sym_p; {save pointer to start of chain}
end
else begin
sym_prev_p^.next_p := sym_p; {create link from previous symbol to new sym}
end
;
sym_prev_p := sym_p; {update pointer to last symbol in chain}
goto loop_tag8; {back for next tag in WITH statement}
end;
2: begin {tag is for statements covered by abbrevs}
sst_opcode_pos_push (sst_opc_p^.abbrev_code_p); {new opcodes get chained here}
sst_r_pas_raw_sment; {build opcodes for code using abbrevs}
sst_opcode_pos_pop; {back to regular opcode chain}
sst_scope_old; {restore to previous scope}
end;
otherwise
syo_error_tag_unexp (tag, str_h);
end;
end;
{
***************************
*
* Tag is for EXIT statement.
}
9: begin
sst_opcode_new;
sst_opc_p^.opcode := sst_opc_loop_exit_k;
sst_opc_p^.str_h := str_h;
end;
{
***************************
*
* Tag is for NEXT statement.
}
10: begin
sst_opcode_new;
sst_opc_p^.opcode := sst_opc_loop_next_k;
sst_opc_p^.str_h := str_h;
end;
{
***************************
*
* Tag is for RETURN statement.
}
11: begin
sst_opcode_new;
sst_opc_p^.opcode := sst_opc_return_k;
sst_opc_p^.str_h := str_h;
end;
{
***************************
*
* Tag is for a variable or other symbol. This could be an assignment
* statement or a procecure call.
}
12: begin
sst_opcode_new; {make new opcode descriptor}
sst_opc_p^.str_h := str_h; {save handle to source characters}
sst_r_pas_variable (var_p); {read VARIABLE and build variable descriptor}
syo_get_tag_msg (tag, str_h, 'sst_pas_read', 'statement_exec_bad', nil, 0);
case tag of
{
* Statement is a procedure call with no arguments.
}
syo_tag_end_k: begin
args_here := false; {no subroutine arguments exist}
goto do_call; {to common code for to handle subroutine call}
end;
{
* Statement is a procedure call with arguments.
}
1: begin
sst_var_funcname (var_p^); {call function instead of stuff return value}
args_here := true; {subroutine arguments do exist}
do_call: {start common code to handle subroutine call}
if {is this a function instead of subroutine ?}
(var_p^.vtype = sst_vtype_rout_k) and then
(var_p^.rout_proc_p^.dtype_func_p <> nil)
then begin
syo_error (str_h, 'sst_pas_read', 'routine_is_function', nil, 0);
end;
sst_opc_p^.opcode := sst_opc_call_k; {opcode is for subroutine call}
sst_opc_p^.call_var_p := var_p; {point opcode to variable referencing subr}
sst_r_pas_routine ( {build and check subroutine call descriptor}
sst_opc_p^.str_h, var_p^, args_here, sst_opc_p^.call_proc_p);
sst_opc_p^.call_proct_p := var_p^.rout_proc_p; {save pointer to routine template}
end;
{
* Statement is an assignment statement. The tag is for the expression to the
* right of the ":=".
}
2: begin
sst_rwcheck ( {check that variable is writeable}
[sst_rwflag_write_k], {access actually used}
var_p^.rwflag, {allowed access to this variable}
stat);
syo_error_abort (stat, sst_opc_p^.str_h, '', '', nil, 0);
sst_opc_p^.opcode := sst_opc_assign_k; {opcode indicates assignment statement}
sst_opc_p^.assign_var_p := var_p; {set pointer to variable being assigned to}
sst_r_pas_exp (str_h, false, sst_opc_p^.assign_exp_p); {build expression descriptor}
sst_exp_useage_check ( {check expression attributes for this useage}
sst_opc_p^.assign_exp_p^, {expression to check}
[sst_rwflag_read_k], {read/write access needed to expression value}
var_p^.dtype_p^); {data type value must be compatible with}
syo_error_abort (stat, sst_opc_p^.assign_exp_p^.str_h, '', '', nil, 0);
end;
{
* Unexpected tag value.
}
otherwise
syo_error_tag_unexp (tag, str_h);
end; {end of TAG cases within call/assign sment}
end;
{
***************************
*
* Tag is block of statements within BEGIN ... END.
}
13: begin
sst_r_pas_statements; {process nested BEGIN ... END block}
end;
{
***************************
*
* Tag is label name for any upcoming statements.
}
14: begin
sst_opcode_new; {make new opcode descriptor}
sst_opc_p^.opcode := sst_opc_label_k; {set opcode type}
sst_opc_p^.str_h := str_h; {save handle to source characters}
sst_scope_p^.flag_ref_used := false; {putting label in code is not "use"}
get_label_sym_pnt (str_h, sst_opc_p^.label_sym_p); {get pointer to label symbol}
sst_scope_p^.flag_ref_used := true; {restore to symbol references are "uses"}
goto tag_loop;
end;
{
***************************
*
* Tag is for WRITE or WRITELN statement.
}
15: begin
sst_r_pas_write; {process WRITE/WRITELN statement}
end;
{
***************************
*
* Tag is for DISCARD intrinsic procedure.
}
16: begin
sst_opcode_new; {make new opcode descriptor}
sst_opc_p^.str_h := str_h; {save handle to source characters}
sst_opc_p^.opcode := sst_opc_discard_k; {indicate the type of this new opcode}
syo_get_tag_msg ( {get tag to function reference expression}
tag, str_h, 'sst_pas_read', 'statement_exec_bad', nil, 0);
if tag <> 1 then begin
syo_error_tag_unexp (tag, str_h);
end;
sst_r_pas_exp (str_h, false, sst_opc_p^.discard_exp_p); {get function reference exp}
with sst_opc_p^.discard_exp_p^: exp do begin {EXP is func ref expression descriptor}
if {invalid expression for DISCARD ?}
(exp.term1.next_p <> nil) or {more than one term in expression ?}
(exp.term1.op1 <> sst_op1_none_k) or {unadic operator in front of exp ?}
( (exp.term1.ttype <> sst_term_func_k) and {not some kind of function ?}
(exp.term1.ttype <> sst_term_ifunc_k))
then begin
syo_error (str_h, 'sst_pas_read', 'discard_arg_bad', nil, 0);
end;
end; {done with EXP abbreviation}
end;
{
***************************
*
* Unrecognized or unimplemented TAG value.
}
otherwise
syo_error_tag_unexp (tag, str_h);
end; {end of tag cases}
{
* Make sure there are no more tags left in this RAW_STATEMENT syntax.
}
syo_get_tag_msg (tag, str_h, 'sst_pas_read', 'statement_exec_bad', nil, 0);
if tag <> syo_tag_end_k then begin
syo_error_tag_unexp (tag, str_h); {complain if not hit end of syntax}
end;
leave: {common exit point}
syo_level_up; {up from RAW_STATEMENT syntax level}
end;
|
unit uCardapio;
interface
uses
System.Classes;
type TCardapio = class(TPersistent)
private
FPRO_VALORINTEIRA: Double;
FPRO_GRUPO: Integer;
FPRO_VALORMEIA: Double;
FPRO_DESCRICAO: String;
FPRO_CODIGO: Integer;
procedure SetPRO_CODIGO(const Value: Integer);
procedure SetPRO_DESCRICAO(const Value: String);
procedure SetPRO_GRUPO(const Value: Integer);
procedure SetPRO_VALORINTEIRA(const Value: Double);
procedure SetPRO_VALORMEIA(const Value: Double);
public
constructor Create;
destructor Destroy; override;
protected
published
property PRO_CODIGO : Integer read FPRO_CODIGO write SetPRO_CODIGO;
property PRO_GRUPO : Integer read FPRO_GRUPO write SetPRO_GRUPO;
property PRO_DESCRICAO : String read FPRO_DESCRICAO write SetPRO_DESCRICAO;
property PRO_VALORMEIA : Double read FPRO_VALORMEIA write SetPRO_VALORMEIA;
property PRO_VALORINTEIRA : Double read FPRO_VALORINTEIRA write SetPRO_VALORINTEIRA;
end;
implementation
{ TCardapio }
constructor TCardapio.Create;
begin
FPRO_VALORINTEIRA := 0;
FPRO_GRUPO := 0;
FPRO_VALORMEIA := 0;
FPRO_DESCRICAO := '';
FPRO_CODIGO := 0;
end;
destructor TCardapio.Destroy;
begin
inherited;
end;
procedure TCardapio.SetPRO_CODIGO(const Value: Integer);
begin
FPRO_CODIGO := Value;
end;
procedure TCardapio.SetPRO_DESCRICAO(const Value: String);
begin
FPRO_DESCRICAO := Value;
end;
procedure TCardapio.SetPRO_GRUPO(const Value: Integer);
begin
FPRO_GRUPO := Value;
end;
procedure TCardapio.SetPRO_VALORINTEIRA(const Value: Double);
begin
FPRO_VALORINTEIRA := Value;
end;
procedure TCardapio.SetPRO_VALORMEIA(const Value: Double);
begin
FPRO_VALORMEIA := Value;
end;
end.
|
unit mnSynUtils;
{$mode delphi}
{**
* Light PHP Edit project
*
* This file is part of the "Mini Library"
*
* @url http://www.sourceforge.net/projects/minilib
* @license modifiedLGPL (modified of http://www.gnu.org/licenses/lgpl.html)
* See the file COPYING.MLGPL, included in this distribution,
* @author Zaher Dirkey
*}
{**
Useful functions and classes to use it in Highlighters
*}
interface
uses
SysUtils, Classes, SynHighlighterHashEntries, SynEditTypes;
type
TProcTableProc = procedure of object;
PIdentifierTable = ^TIdentifierTable;
TIdentifierTable = array[AnsiChar] of ByteBool;
PHashCharTable = ^THashCharTable;
THashCharTable = array[AnsiChar] of Integer;
{ TSynPersistent }
TSynPersistent = class(TObject)
private
HashNumber: AnsiChar;
protected
function NewNumber: AnsiChar;
function KeyHash(ToHash: PChar; out L: Integer): Integer; virtual;
function KeyComp(const aKey: string; aWithKey: PChar; L: Integer): Boolean; virtual;
procedure DoAddKeyword(AKeyword: string; AKind: integer); virtual;
procedure MakeIdentifiers; virtual;
procedure MakeHashes; virtual;
function GetDefaultKind: Integer; virtual; abstract;
public
Keywords: TSynHashEntryList;
Identifiers: TIdentifierTable;
HashTable: THashCharTable;
function GetIdentChars: TSynIdentChars; virtual;
function GetSampleSource: string; virtual;
function GetIdentKind(MayBe: PChar; out L: Integer): Integer; overload; virtual;
constructor Create; virtual;
destructor Destroy; override;
end;
procedure EnumerateKeywords(AKind: integer; KeywordList: TStringList;
Identifiers: TSynIdentChars; AKeywordProc: TEnumerateKeywordEvent);
implementation
procedure EnumerateKeywords(AKind: integer; KeywordList: TStringList;
Identifiers: TSynIdentChars; AKeywordProc: TEnumerateKeywordEvent);
var
i: Integer;
begin
if Assigned(AKeywordProc) then
for i := 0 to KeywordList.Count -1 do
AKeywordProc(KeywordList[i], AKind);
end;
procedure TSynPersistent.MakeIdentifiers;
var
c: char;
begin
FillChar(Identifiers, SizeOf(Identifiers), 0);
for c := 'a' to 'z' do
Identifiers[c] := True;
for c := 'A' to 'Z' do
Identifiers[c] := True;
for c := '0' to '9' do
Identifiers[c] := True;
Identifiers['_'] := True;
end;
procedure TSynPersistent.MakeHashes;
var
c: AnsiChar;
begin
FillChar(HashTable, SizeOf(HashTable), 0);
HashTable['_'] := 1;
for c := 'a' to 'z' do
HashTable[c] := 2 + Ord(c) - Ord('a');
for c := 'A' to 'Z' do
HashTable[c] := 2 + Ord(c) - Ord('A');
end;
function TSynPersistent.GetIdentChars: TSynIdentChars;
begin
Result := TSynValidStringChars;
end;
function TSynPersistent.GetSampleSource: string;
begin
Result := '';
end;
procedure TSynPersistent.DoAddKeyword(AKeyword: string; AKind: integer);
var
HashValue, L: integer;
begin
HashValue := KeyHash(PChar(AKeyword), L);
Keywords[HashValue] := TSynHashEntry.Create(AKeyword, AKind);
end;
constructor TSynPersistent.Create;
begin
inherited Create;
Keywords := TSynHashEntryList.Create;
MakeIdentifiers;
MakeHashes;
end;
destructor TSynPersistent.Destroy;
begin
inherited;
FreeAndNil(Keywords);
end;
function TSynPersistent.NewNumber: AnsiChar;
begin
Inc(HashNumber);
Result := HashNumber;
end;
function TSynPersistent.KeyHash(ToHash: PChar; out L: Integer): Integer;
begin
Result := 0;
L := 0;
while ToHash^ in GetIdentChars do
begin
Inc(Result, HashTable[ToHash^]);
Inc(ToHash);
Inc(L);
end;
end;
function TSynPersistent.KeyComp(const aKey: string; aWithKey: PChar; L: Integer): Boolean;
var
i: integer;
pKey1, pKey2: PChar;
begin
pKey1 := aWithKey;
pKey2 := Pointer(aKey);
for i := 1 to L do
begin
if HashTable[pKey1^] <> HashTable[pKey2^] then
begin
Result := False;
exit;
end;
Inc(pKey1);
Inc(pKey2);
end;
Result := True;
end;
function TSynPersistent.GetIdentKind(MayBe: PChar; out L: Integer): Integer;
var
Entry: TSynHashEntry;
begin
Entry := Keywords[KeyHash(MayBe, L)];
while Assigned(Entry) do
begin
if Entry.KeywordLen > L then
break
else if Entry.KeywordLen = L then
if KeyComp(Entry.Keyword, MayBe, L) then
begin
Result := Entry.Kind;
exit;
end;
Entry := Entry.Next;
end;
Result := GetDefaultKind;
end;
end.
|
unit App;
{ Based on 013_striped_cubes.cpp example from oglplus (http://oglplus.org/) }
{$INCLUDE 'Sample.inc'}
interface
uses
System.Classes,
Neslib.Ooogles,
Neslib.FastMath,
Sample.Geometry,
Sample.App;
type
TStripedCubesApp = class(TApplication)
private
FProgram: TGLProgram;
FVerts: TGLBuffer;
FTexCoords: TGLBuffer;
FIndices: TGLBuffer;
FCube: TCubeGeometry;
FUniProjectionMatrix: TGLUniform;
FUniCameraMatrix: TGLUniform;
FUniModelMatrix: TGLUniform;
public
procedure Initialize; override;
procedure Render(const ADeltaTimeSec, ATotalTimeSec: Double); override;
procedure Shutdown; override;
procedure KeyDown(const AKey: Integer; const AShift: TShiftState); override;
procedure Resize(const AWidth, AHeight: Integer); override;
end;
implementation
uses
{$INCLUDE 'OpenGL.inc'}
System.UITypes,
Sample.Math;
{ TStripedCubesApp }
procedure TStripedCubesApp.Initialize;
var
VertexShader, FragmentShader: TGLShader;
VertAttr: TGLVertexAttrib;
begin
VertexShader.New(TGLShaderType.Vertex,
'uniform mat4 ProjectionMatrix, CameraMatrix, ModelMatrix;'#10+
'attribute vec3 Position;'#10+
'attribute vec2 TexCoord;'#10+
'varying vec2 vertTexCoord;'#10+
'void main(void)'#10+
'{'#10+
' vertTexCoord = TexCoord;'#10+
' gl_Position = '#10+
' ProjectionMatrix *'#10+
' CameraMatrix *'#10+
' ModelMatrix *'#10+
' vec4(Position, 1.0);'#10+
'}');
VertexShader.Compile;
FragmentShader.New(TGLShaderType.Fragment,
'precision mediump float;'#10+
'varying vec2 vertTexCoord;'#10+
'void main(void)'#10+
'{'#10+
' float i = floor(mod((vertTexCoord.x + vertTexCoord.y) * 8.0, 2.0));'#10+
' gl_FragColor = mix('#10+
' vec4(0, 0, 0, 1),'#10+
' vec4(1, 1, 0, 1),'#10+
' i'#10+
' );'#10+
'}');
FragmentShader.Compile;
FProgram.New(VertexShader, FragmentShader);
FProgram.Link;
VertexShader.Delete;
FragmentShader.Delete;
FProgram.Use;
FCube.Generate(0.5);
{ Positions }
FVerts.New(TGLBufferType.Vertex);
FVerts.Bind;
FVerts.Data<TVector3>(FCube.Positions);
VertAttr.Init(FProgram, 'Position');
VertAttr.SetConfig<TVector3>;
VertAttr.Enable;
{ Texture coordinates }
FTexCoords.New(TGLBufferType.Vertex);
FTexCoords.Bind;
FTexCoords.Data<TVector2>(FCube.TexCoords);
VertAttr.Init(FProgram, 'TexCoord');
VertAttr.SetConfig<TVector2>;
VertAttr.Enable;
{ Indices }
FIndices.New(TGLBufferType.Index);
FIndices.Bind;
FIndices.Data<UInt16>(FCube.Indices);
{ Don't need data anymore }
FCube.Clear;
{ Uniforms }
FUniProjectionMatrix.Init(FProgram, 'ProjectionMatrix');
FUniCameraMatrix.Init(FProgram, 'CameraMatrix');
FUniModelMatrix.Init(FProgram, 'ModelMatrix');
gl.ClearColor(0.8, 0.8, 0.7, 0);
gl.ClearDepth(1);
gl.Enable(TGLCapability.DepthTest);
end;
procedure TStripedCubesApp.KeyDown(const AKey: Integer; const AShift: TShiftState);
begin
{ Terminate app when Esc key is pressed }
if (AKey = vkEscape) then
Terminate;
end;
procedure TStripedCubesApp.Render(const ADeltaTimeSec, ATotalTimeSec: Double);
var
Translation, Rotation, CameraMatrix, ModelMatrix: TMatrix4;
begin
{ Clear the color and depth buffer }
gl.Clear([TGLClear.Color, TGLClear.Depth]);
{ Use the program }
FProgram.Use;
{ Orbit camera around cubes }
OrbitCameraMatrix(TVector3.Zero, 3.5, Radians(ATotalTimeSec * 15),
Radians(FastSin(ATotalTimeSec) * 45), CameraMatrix);
FUniCameraMatrix.SetValue(CameraMatrix);
{ Update and render first cube }
Translation.InitTranslation(-1, 0, 0);
Rotation.InitRotationZ(Radians(ATotalTimeSec * 180));
ModelMatrix := Translation * Rotation;
FUniModelMatrix.SetValue(ModelMatrix);
FCube.DrawWithBoundIndexBuffer;
{ Update and render second cube }
Translation.InitTranslation(1, 0, 0);
Rotation.InitRotationY(Radians(ATotalTimeSec * 90));
ModelMatrix := Translation * Rotation;
FUniModelMatrix.SetValue(ModelMatrix);
FCube.DrawWithBoundIndexBuffer;
end;
procedure TStripedCubesApp.Resize(const AWidth, AHeight: Integer);
var
ProjectionMatrix: TMatrix4;
begin
inherited;
ProjectionMatrix.InitPerspectiveFovRH(Radians(60), AWidth / AHeight, 1, 30);
FProgram.Use;
FUniProjectionMatrix.SetValue(ProjectionMatrix);
end;
procedure TStripedCubesApp.Shutdown;
begin
{ Release resources }
FIndices.Delete;
FTexCoords.Delete;
FVerts.Delete;
FProgram.Delete;
end;
end.
|
{***********************************************************************************************************************
*
* TERRA Game Engine
* ==========================================
*
* Copyright (C) 2003, 2014 by SÚrgio Flores (relfos@gmail.com)
*
***********************************************************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
**********************************************************************************************************************
* TERRA_DistanceFields
* Implements distance fields for font rendering
***********************************************************************************************************************
}
Unit TERRA_DistanceField;
{$I terra.inc}
Interface
Uses TERRA_Utils, TERRA_Image, TERRA_Color;
{ Computes a distance field transform of a high resolution binary source channel
and returns the result as a low resolution channel.
scale_down : The amount the source channel will be scaled down.
A value of 8 means the destination image will be 1/8th the size of the source
spread: The spread in pixels before the distance field clamps to (zero/one). The value
is specified in units of the destination image. The spread in the source image
will be spread*scale_down.
}
Function CreateDistanceField(Source:Image; Component, Scale:Cardinal; Spread:Single):Image;
Implementation
Uses TERRA_Log;
Function SignedDistance(Source:Image; Component, cx, cy:Integer; clamp:Single):Single;
Var
w, h, dx, dy:Integer;
x, y1, y2:Integer;
min_x, max_x:Integer;
d, d2:Single;
cd, distance:Single;
c:Single;
Begin
w := Source.Width;
h := Source.Height;
If (CX<0) Or (CY<0) Or (CX>=Source.Width) Or (CY>=Source.Height) Then
C := 0
Else
c := Source.GetComponent(cx, cy, component)/255.0;
cd := c - 0.5;
min_x := cx - Trunc(clamp) - 1;
if (min_x < 0) Then min_x := 0;
max_x := cx + Trunc(clamp) + 1;
if (max_x >= w) Then max_x := w-1;
distance := clamp;
For dy :=0 To Pred(Trunc(clamp) + 1) Do
Begin
If (dy > distance) Then
Continue;
If (cy - dy >=0) Then
Begin
y1 := cy-dy;
For x:=min_x To max_x Do
Begin
If (x - cx > distance) Then
Continue;
c := Source.GetComponent(x, y1, component)/255.0;
d := c - 0.5;
If (cd*d<0) Then
Begin
d2 := (y1 - cy)*(y1 - cy) + (x-cx)*(x-cx);
If (d2 < distance*distance) Then
distance := Sqrt(d2);
End;
End;
End;
If (dy <> 0) And (cy+dy < h) Then
Begin
y2 := cy + dy;
For x:=min_x To max_x Do
Begin
If (x - cx > distance) Then
Continue;
c := Source.GetComponent(x, y2, component)/255.0;
d := c - 0.5;
If (cd*d<0) Then
Begin
d2 := (y2 - cy)*(y2 - cy) + (x-cx)*(x-cx);
If (d2 < distance*distance) Then
distance := Sqrt(d2);
End;
End;
End;
End;
If (cd > 0) Then
Result := -Distance
Else
Result := distance;
End;
Function CreateDistanceField(Source:Image; Component, Scale:Cardinal; Spread:Single):Image;
Var
x,y:Integer;
Padding:Integer;
PX, PY:Integer;
sd:Single;
n:Single;
c:Byte;
Temp:Image;
Begin
Padding := Source.Width Div 10;
Log(logWarning, 'Application', 'Making distance field glyph...');
Temp := Image.Create(Source);
Temp.Resize(Source.Width - Padding * 2, Source.Height - Padding * 2);
Source := Image.Create(Source.Width, Source.Height);
Source.Blit(Padding, Padding, 0, 0, Temp.Width, Temp.Height, Temp);
Result := Image.Create(Source.Width, Source.Height);
For Y:=0 To Pred(Result.Height) Do
For X:=0 To Pred(Result.Width) Do
Begin
PX := X;
PY := Y;
sd := SignedDistance(Source, Component, PX, PY, Spread);
n := (sd + Spread) / (Spread*2);
C := Trunc(N*255);
Result.SetPixel(X, Y, ColorGrey(C, C));
End;
ReleaseObject(Temp);
ReleaseObject(Source);
(* While (Scale>1) Do
Begin
Temp := Result;
Result := Temp.MipMap();
ReleaseObject(Temp);
Scale := Scale Shr 1;
End;*)
End;
End. |
{$I ACBr.inc}
unit ASCIOTReg;
interface
uses
SysUtils, Classes, ASCIOT, pcnConversao,
{$IFDEF VisualCLX} QDialogs {$ELSE} Dialogs, FileCtrl {$ENDIF},
{$IFDEF FPC}
LResources, LazarusPackageIntf, PropEdits, componenteditors
{$ELSE}
{$IFNDEF COMPILER6_UP}
DsgnIntf
{$ELSE}
DesignIntf,
DesignEditors
{$ENDIF}
{$ENDIF} ;
type
{ Editor de Proriedades de Componente para mostrar o AboutACBr }
TASAboutDialogProperty = class(TPropertyEditor)
public
procedure Edit; override;
function GetAttributes: TPropertyAttributes; override;
function GetValue: string; override;
end;
THRWEBSERVICEUFProperty = class( TStringProperty )
public
function GetAttributes: TPropertyAttributes; override;
procedure GetValues( Proc : TGetStrProc) ; override;
end;
{ Editor de Proriedades de Componente para chamar OpenDialog }
TASCIOTDirProperty = class( TStringProperty )
public
procedure Edit; override;
function GetAttributes: TPropertyAttributes; override;
end;
const
NFeUF: array[0..26] of String =
('AC','AL','AP','AM','BA','CE','DF','ES','GO','MA','MT','MS','MG','PA',
'PB','PR','PE','PI','RJ','RN','RS','RO','RR','SC','SP','SE','TO');
procedure Register;
implementation
uses ASCIOTConfiguracoes;
//
//{$IFNDEF FPC}
// {$R ASCIOT.dcr}
//{$ENDIF}
procedure Register;
begin
RegisterComponents('AmericaSoft', [TAmsCIOT]);
RegisterPropertyEditor(TypeInfo(TAmsCIOTAboutInfo), nil, 'AboutAmsCIOT', TASAboutDialogProperty);
RegisterPropertyEditor(TypeInfo(TCertificadosConf), TConfiguracoes, 'Certificados', TClassProperty);
RegisterPropertyEditor(TypeInfo(TConfiguracoes), TAMSCIOT, 'Configuracoes', TClassProperty);
RegisterPropertyEditor(TypeInfo(TWebServicesConf), TConfiguracoes, 'WebServices', TClassProperty);
RegisterPropertyEditor(TypeInfo(String), TWebServicesConf, 'UF', THRWEBSERVICEUFProperty);
RegisterPropertyEditor(TypeInfo(TGeralConf), TConfiguracoes, 'Geral', TClassProperty);
RegisterPropertyEditor(TypeInfo(String), TGeralConf, 'PathSalvar', TASCIOTDirProperty);
RegisterPropertyEditor(TypeInfo(TArquivosConf), TConfiguracoes, 'Arquivos', TClassProperty);
end;
{ TASAboutDialogProperty }
procedure TASAboutDialogProperty.Edit;
begin
ACBrAboutDialog ;
end;
function TASAboutDialogProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paDialog, paReadOnly];
end;
function TASAboutDialogProperty.GetValue: string;
begin
Result := 'Versão: ' + AmsCIOT_VERSAO ;
end;
{ THRWEBSERVICEUFProperty }
function THRWEBSERVICEUFProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paValueList, paAutoUpdate];
end;
procedure THRWEBSERVICEUFProperty.GetValues(Proc: TGetStrProc);
var
i : integer;
begin
inherited;
for i:= 0 to High(NFeUF) do
Proc(NFeUF[i]);
end;
{ TACBrCIOTDirProperty }
procedure TASCIOTDirProperty.Edit;
Var
{$IFNDEF VisualCLX} Dir : String ; {$ELSE} Dir : WideString ; {$ENDIF}
begin
{$IFNDEF VisualCLX}
Dir := GetValue ;
if SelectDirectory(Dir,[],0) then
SetValue( Dir ) ;
{$ELSE}
Dir := '' ;
if SelectDirectory('Selecione o Diretório','',Dir) then
SetValue( Dir ) ;
{$ENDIF}
end;
function TASCIOTDirProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paDialog];
end;
initialization
{$IFDEF FPC}
{$i ACBrCIOT.lrs}
{$ENDIF}
end.
|
{*********************************************************}
{* VPEDPOP.PAS 1.03 *}
{*********************************************************}
{* ***** BEGIN LICENSE BLOCK ***** *}
{* Version: MPL 1.1 *}
{* *}
{* 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. *}
{* *}
{* The Original Code is TurboPower Visual PlanIt *}
{* *}
{* The Initial Developer of the Original Code is TurboPower Software *}
{* *}
{* Portions created by TurboPower Software Inc. are Copyright (C) 2002 *}
{* TurboPower Software Inc. All Rights Reserved. *}
{* *}
{* Contributor(s): *}
{* *}
{* ***** END LICENSE BLOCK ***** *}
{$I Vp.INC}
unit VpEdPop;
{-base popup edit field class}
interface
uses
{$IFDEF LCL}
LMessages,LCLProc,LCLType,LCLIntf,
{$ELSE}
Windows,
{$ENDIF}
Buttons, Classes, Controls, ExtCtrls, Forms, Graphics, Menus,
Messages, StdCtrls, SysUtils, VpBase, VpConst;
type
TVpEdButton = class(TBitBtn)
public
procedure Click;
override;
end;
TVpEdPopup = class(TCustomEdit)
protected {private}
{property variables}
FButton : TVpEdButton;
FPopupActive : Boolean;
FShowButton : Boolean;
function GetVersion : string;
procedure SetShowButton(Value : Boolean);
procedure SetVersion(const Value : string);
{internal methods}
function GetButtonWidth : Integer;
protected
procedure CreateParams(var Params : TCreateParams); override;
procedure CreateWnd; override;
function GetButtonEnabled : Boolean; dynamic;
procedure PopupClose(Sender : TObject); dynamic;
property ShowButton : Boolean
read FShowButton write SetShowButton default True;
property Version : string read GetVersion write SetVersion stored False;
public
constructor Create(AOwner : TComponent); override;
destructor Destroy; override;
procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer);
override;
procedure PopupOpen; dynamic;
property PopupActive : Boolean read FPopupActive;
end;
implementation
{*** TVpEditBtn ***}
procedure TVpEdButton.Click;
begin
TVpEdPopup(Parent).PopupOpen;
end;
{*** TVpEdPopup ***}
constructor TVpEdPopup.Create(AOwner : TComponent);
begin
inherited Create(AOwner);
ControlStyle := ControlStyle - [csSetCaption];
FShowButton := True;
FButton := TVpEdButton.Create(Self);
FButton.Visible := True;
FButton.Parent := Self;
FButton.Caption := '';
FButton.TabStop := False;
{$IFNDEF LCL}
FButton.Style := bsNew;
{$ENDIF}
end;
procedure TVpEdPopup.CreateParams(var Params : TCreateParams);
begin
inherited CreateParams(Params);
Params.Style := Params.Style or WS_CLIPCHILDREN;
end;
procedure TVpEdPopup.CreateWnd;
begin
inherited CreateWnd;
{force button placement}
SetBounds(Left, Top, Width, Height);
FButton.Enabled := GetButtonEnabled;
end;
destructor TVpEdPopup.Destroy;
begin
FButton.Free;
FButton := nil;
inherited Destroy;
end;
function TVpEdPopup.GetButtonEnabled : Boolean;
begin
Result := not ReadOnly;
end;
function TVpEdPopup.GetButtonWidth : Integer;
begin
if Assigned(FButton) and FShowButton then
Result := FButton.Width
else
Result := 0;
end;
function TVpEdPopup.GetVersion : string;
begin
Result := VpVersionStr;
end;
procedure TVpEdPopup.PopupClose;
begin
FPopupActive := False;
end;
procedure TVpEdPopup.PopupOpen;
begin
FPopupActive := True;
end;
procedure TVpEdPopup.SetBounds(ALeft, ATop, AWidth, AHeight : Integer);
var
H : Integer;
begin
inherited SetBounds(ALeft, ATop, AWidth, AHeight);
if not HandleAllocated then
Exit;
if not FShowButton then begin
FButton.Height := 0;
FButton.Width := 0;
Exit;
end;
H := ClientHeight;
if BorderStyle = bsNone then begin
FButton.Height := H;
FButton.Width := (FButton.Height div 4) * 3;
if Assigned(Fbutton.Glyph) then
if FButton.Width < FButton.Glyph.Width + 6 then
FButton.Width := FButton.Glyph.Width + 6;
FButton.Left := Width - FButton.Width;
FButton.Top := 0;
end else begin
FButton.Height := H - 2;
FButton.Width := (FButton.Height div 4) * 3;
if Assigned(Fbutton.Glyph) then
if FButton.Width < FButton.Glyph.Width + 6 then
FButton.Width := FButton.Glyph.Width + 6;
FButton.Left := Width - FButton.Width - 1;
FButton.Top := 1;
end;
end;
procedure TVpEdPopup.SetShowButton(Value : Boolean);
begin
if Value <> FShowButton then begin
FShowButton := Value;
{force resize and redisplay of button}
SetBounds(Left, Top, Width, Height);
end;
end;
procedure TVpEdPopup.SetVersion(const Value : string);
begin
// Leave empty
end;
{=====}
end.
|
{ ***************************************************************************
Copyright (c) 2015-2021 Kike Pérez
Unit : Quick.Options
Description : Configuration group settings
Author : Kike Pérez
Version : 1.0
Created : 18/10/2019
Modified : 15/12/2021
This file is part of QuickLib: https://github.com/exilon/QuickLib
***************************************************************************
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*************************************************************************** }
unit Quick.Options;
{$i QuickLib.inc}
interface
uses
Classes,
RTTI,
System.TypInfo,
System.SysUtils,
System.Generics.Collections,
Quick.RTTI.Utils,
Quick.Commons,
Quick.FileMonitor;
type
Required = class(TCustomAttribute);
TValidationCustomAttribute = class(TCustomAttribute)
protected
fErrorMsg : string;
public
property ErrorMsg : string read fErrorMsg write fErrorMsg;
end;
Range = class(TValidationCustomAttribute)
private
fRangeMin : Double;
fRangeMax : Double;
public
constructor Create(aMin, aMax : Integer; const aErrorMsg : string = ''); overload;
constructor Create(aMin, aMax : Double; const aErrorMsg : string = ''); overload;
property Min : Double read fRangeMin write fRangeMax;
property Max : Double read fRangeMax write fRangeMax;
end;
StringLength = class(TValidationCustomAttribute)
private
fMaxLength : Integer;
public
constructor Create(aMaxLength : Integer; const aErrorMsg : string = '');
property MaxLength : Integer read fMaxLength write fMaxLength;
end;
TOptionsBase = class(TInterfacedObject)
end;
{$IFDEF DELPHIRX102_UP}
{$M+}
TOptions = class;
{$M-}
TConfigureOptionsProc<T : TOptions> = reference to procedure(aOptions : T);
{$ELSE}
TConfigureOptionsProc<T> = reference to procedure(aOptions : T);
{$ENDIF}
IOptionsValidator = interface
['{C6A09F78-8E34-4689-B943-83620437B9EF}']
procedure ValidateOptions;
end;
{$M+}
TOptions = class(TInterfacedObject,IOptionsValidator)
private
fName : string;
fHideOptions : Boolean;
procedure DoValidateOptions; virtual;
public
constructor Create; virtual;
property Name : string read fName write fName;
property HideOptions : Boolean read fHideOptions write fHideOptions;
procedure DefaultValues; virtual;
{$IFDEF DELPHIRX102_UP}
function ConfigureOptions<T : TOptions>(aOptionsFunc : TConfigureOptionsProc<T>) : IOptionsValidator;
{$ELSE}
function ConfigureOptions<T>(aOptionsFunc : TConfigureOptionsProc<T>) : IOptionsValidator;
{$ENDIF}
procedure ValidateOptions;
end;
{$M-}
TOptionsValidator = class(TInterfacedObject,IOptionsValidator)
private
fOptions : TOptions;
public
constructor Create(aOptions : TOptions);
procedure ValidateRequired(const aInstance : TObject; aProperty: TRttiProperty);
procedure ValidateStringLength(const aInstance : TObject; aProperty: TRttiProperty; aValidation : StringLength);
procedure ValidateRange(const aInstance : TObject; aProperty: TRttiProperty; aValidation : Range);
procedure ValidateObject(aObj : TObject);
procedure ValidateArray(aValue : TValue);
procedure ValidateOptions;
end;
TOptions<T : TOptions> = record
private
fOptions : T;
public
constructor Create(aOptions : T);
function ConfigureOptions(aOptionsFunc : TConfigureOptionsProc<T>) : IOptionsValidator;
end;
IOptions<T : TOptions> = interface
['{2779F946-2692-4F74-88AD-F35F5137057A}']
function GetSectionValue : T;
property Value : T read GetSectionValue;
end;
TOptionsClass = class of TOptions;
IOptionsContainer = interface
['{A593C8BB-53CF-4AA4-9641-BF974E45CBD1}']
function AddSection(aOption : TOptionsClass; const aOptionsName : string = '') : TOptions;
function GetOptions(aOptionClass : TOptionsClass): TOptions;
function GetSection(aOptionsSection : TOptionsClass; var vOptions : TOptions) : Boolean; overload;
procedure AddOption(aOption : TOptions);
function ExistsSection(aOption : TOptionsClass; const aSectionName : string = '') : Boolean;
end;
TSectionList = TObjectList<TOptions>;
IOptionsSerializer = interface
['{7DECE203-4AAE-4C9D-86C8-B3D583DF7C8B}']
function Load(aSections : TSectionList; aFailOnSectionNotExists : Boolean) : Boolean;
function LoadSection(aSections : TSectionList; aOptions: TOptions) : Boolean;
procedure Save(aSections : TSectionList);
function GetFileSectionNames(out oSections : TArray<string>) : Boolean;
function ConfigExists : Boolean;
end;
IFileOptionsSerializer = interface(IOptionsSerializer)
['{3417B142-2879-4DA6-86CA-19F0F427A92C}']
function GetFileName : string;
procedure SetFileName(const aFilename : string);
property Filename : string read GetFilename write SetFilename;
end;
TOptionsSerializer = class(TInterfacedObject,IOptionsSerializer)
public
function Load(aSections : TSectionList; aFailOnSectionNotExists : Boolean) : Boolean; virtual; abstract;
function LoadSection(aSections : TSectionList; aOptions: TOptions) : Boolean; virtual; abstract;
procedure Save(aSections : TSectionList); virtual; abstract;
function GetFileSectionNames(out oSections : TArray<string>) : Boolean; virtual; abstract;
function ConfigExists : Boolean; virtual; abstract;
end;
TOptionsFileSerializer = class(TOptionsSerializer,IFileOptionsSerializer)
private
fFilename : string;
function GetFileName : string;
procedure SetFileName(const aFilename : string);
public
property Filename : string read GetFilename write SetFilename;
end;
TFileModifiedEvent = reference to procedure;
TLoadConfigEvent = reference to procedure;
TOptionValue<T : TOptions> = class(TInterfacedObject,IOptions<T>)
private
fValue : T;
function GetSectionValue : T;
public
constructor Create(aValue : T);
property Value : T read GetSectionValue;
end;
TOptionsContainer = class(TInterfacedObject,IOptionsContainer)
private
fSerializer : IOptionsSerializer;
fSections : TSectionList;
fLoaded : Boolean;
fOnConfigLoaded : TLoadConfigEvent;
fOnConfigReloaded : TLoadConfigEvent;
function GetOptions(aOptionClass : TOptionsClass): TOptions; overload;
function GetOptions(aIndex : Integer) : TOptions; overload;
function GetSection(aOptionsSection : TOptionsClass; var vOptions : TOptions) : Boolean; overload;
public
constructor Create(aOptionsSerializer : IOptionsSerializer);
destructor Destroy; override;
property IsLoaded : Boolean read fLoaded;
function ExistsSection(aOption : TOptionsClass; const aSectionName : string = '') : Boolean; overload;
function ExistsSection<T : TOptions>(const aSectionName : string = '') : Boolean; overload;
property Items[aOptionClass : TOptionsClass] : TOptions read GetOptions; default;
property Items[aIndex : Integer] : TOptions read GetOptions; default;
property OnConfigLoaded : TLoadConfigEvent read fOnConfigLoaded write fOnConfigLoaded;
property OnConfigReloaded : TLoadConfigEvent read fOnConfigReloaded write fOnConfigReloaded;
function AddSection(aOption : TOptionsClass; const aSectionName : string = '') : TOptions; overload;
function AddSection<T : TOptions>(const aSectionName : string = '') : TOptions<T>; overload;
procedure AddOption(aOption : TOptions);
function GetSectionInterface<T : TOptions> : IOptions<T>;
function GetSection<T : TOptions>(const aSectionName : string = '') : T; overload;
function GetFileSectionNames(out oSections : TArray<string>) : Boolean;
function Count : Integer;
procedure Load(aFailOnSectionNotExists : Boolean = False); virtual;
procedure LoadSection(aOptions : TOptions);
procedure Save; virtual;
end;
TFileOptionsContainer = class(TOptionsContainer)
private
fFilename : string;
fFileMonitor : TFileMonitor;
fOnFileModified : TFileModifiedEvent;
fReloadIfFileChanged : Boolean;
procedure CreateFileMonitor;
procedure FileModifiedNotify(MonitorNotify : TMonitorNotify);
procedure SetReloadIfFileChanged(const Value: Boolean);
public
constructor Create(aOptionsSerializer : IFileOptionsSerializer; aReloadIfFileChanged : Boolean = False);
destructor Destroy; override;
property FileName : string read fFilename;
property ReloadIfFileChanged : Boolean read fReloadIfFileChanged write SetReloadIfFileChanged;
property OnFileModified : TFileModifiedEvent read fOnFileModified write fOnFileModified;
procedure Save; override;
function GetFileSectionNames(out oSections: TArray<string>): Boolean;
end;
IOptionsBuilder<T : TOptions> = interface
['{1A1DC9A9-7F2D-4CC4-A772-6C7DBAB34424}']
function Options : T;
end;
TOptionsBuilder<T : TOptions> = class(TInterfacedObject,IOptionsBuilder<T>)
protected
fOptions : T;
public
constructor Create;
function Options : T;
end;
EOptionConfigureError = class(Exception);
EOptionLoadError = class(Exception);
EOptionSaveError = class(Exception);
EOptionValidationError = class(Exception);
implementation
{ TCustomOptionsContainer}
function TOptionsContainer.ExistsSection(aOption: TOptionsClass;const aSectionName: string): Boolean;
var
option : TOptions;
begin
Result := False;
for option in fSections do
begin
if CompareText(option.ClassName,aOption.ClassName) = 0 then
begin
if (not aSectionName.IsEmpty) and (CompareText(option.Name,aSectionName) = 0) then Exit(True);
end;
end;
end;
function TOptionsContainer.ExistsSection<T>(const aSectionName: string): Boolean;
begin
Result := GetSection<T>(aSectionName) <> nil;
end;
procedure TOptionsContainer.AddOption(aOption: TOptions);
begin
if aOption.Name.IsEmpty then aOption.Name := Copy(aOption.ClassName,2,aOption.ClassName.Length);
fSections.Add(aOption);
end;
function TOptionsContainer.AddSection(aOption : TOptionsClass; const aSectionName : string = '') : TOptions;
var
option : TOptions;
begin
//if section already exists, returns it
option := Self.GetOptions(aOption);
if option <> nil then Exit(option);
option := aOption.Create;
if aSectionName.IsEmpty then option.Name := Copy(aOption.ClassName,2,aOption.ClassName.Length)
else option.Name := aSectionName;
fSections.Add(option);
Result := option;
end;
function TOptionsContainer.AddSection<T>(const aSectionName: string): TOptions<T>;
var
option : TOptions;
begin
//if section already exists, returns it
option := Self.GetSection<T>(aSectionName);
if option <> nil then Exit(TOptions<T>(option));
//new section
option := TRTTI.CreateInstance<T>;
if aSectionName.IsEmpty then option.Name := Copy(T.ClassName,2,T.ClassName.Length)
else option.Name := aSectionName;
fSections.Add(option);
Result.Create(option);
end;
function TOptionsContainer.Count: Integer;
begin
Result := fSections.Count;
end;
constructor TOptionsContainer.Create(aOptionsSerializer: IOptionsSerializer);
begin
fSerializer := aOptionsSerializer;
fSections := TSectionList.Create(False);
fLoaded := False;
end;
destructor TOptionsContainer.Destroy;
var
option : TOptions;
begin
fSerializer := nil;
for option in fSections do
begin
if option.RefCount = 0 then option.Free;
end;
fSections.Free;
inherited;
end;
function TOptionsContainer.GetFileSectionNames(out oSections: TArray<string>): Boolean;
begin
Result := fSerializer.GetFileSectionNames(oSections);
end;
function TOptionsContainer.GetOptions(aIndex: Integer): TOptions;
begin
Result := fSections[aIndex];
end;
function TOptionsContainer.GetSection(aOptionsSection: TOptionsClass; var vOptions: TOptions): Boolean;
var
option : TOptions;
begin
Result := False;
for option in fSections do
begin
if option is TOptionsClass then
begin
vOptions := option as TOptionsClass;
Exit;
end;
end;
end;
function TOptionsContainer.GetOptions(aOptionClass : TOptionsClass) : TOptions;
var
option : TOptions;
begin
Result := nil;
for option in fSections do
begin
if option is aOptionClass then Result := option as TOptionsClass;
end;
end;
function TOptionsContainer.GetSection<T>(const aSectionName : string = '') : T;
var
option : TOptions;
begin
Result := nil;
for option in fSections do
begin
if option is T then
begin
if (aSectionName.IsEmpty) or (CompareText(option.Name,aSectionName) = 0) then
begin
Result := option as T;
Exit;
end;
end;
end;
end;
function TOptionsContainer.GetSectionInterface<T>: IOptions<T>;
begin
Result := TOptionValue<T>.Create(Self.GetSection<T>);
end;
procedure TOptionsContainer.Load(aFailOnSectionNotExists : Boolean = False);
var
option : TOptions;
begin
if fSerializer.ConfigExists then
begin
if not fSerializer.Load(fSections,aFailOnSectionNotExists) then Save;
if not fLoaded then
begin
fLoaded := True;
if Assigned(fOnConfigLoaded) then fOnConfigLoaded;
end
else if Assigned(fOnConfigReloaded) then fOnConfigReloaded;
end
else
begin
//if config not exists get default values
for option in fSections do option.DefaultValues;
//saves default
Save;
end;
end;
procedure TOptionsContainer.LoadSection(aOptions : TOptions);
begin
if fSerializer.ConfigExists then
begin
if not fSerializer.LoadSection(fSections,aOptions) then Save;
end;
end;
procedure TOptionsContainer.Save;
begin
fSerializer.Save(fSections);
end;
{ TOptionsContainer }
constructor TFileOptionsContainer.Create(aOptionsSerializer : IFileOptionsSerializer; aReloadIfFileChanged : Boolean = False);
begin
inherited Create(aOptionsSerializer);
fFilename := aOptionsSerializer.Filename;
if aReloadIfFileChanged then CreateFileMonitor;
end;
procedure TFileOptionsContainer.Save;
var
laststate : Boolean;
begin
//disable filemonitor to avoid detect manual save as a external file change
if fReloadIfFileChanged then
begin
laststate := fFileMonitor.Enabled;
fFileMonitor.Enabled := False;
try
//save config file
inherited;
finally
//set last state
Sleep(0);
fFileMonitor.Enabled := laststate;
end;
end
else inherited;
end;
procedure TFileOptionsContainer.SetReloadIfFileChanged(const Value: Boolean);
begin
if Value = fReloadIfFileChanged then Exit;
fReloadIfFileChanged := Value;
if Assigned(fFileMonitor) then fFileMonitor.Free;
if fReloadIfFileChanged then CreateFileMonitor;
end;
procedure TFileOptionsContainer.CreateFileMonitor;
begin
fFileMonitor := TQuickFileMonitor.Create;
fFileMonitor.FileName := fFilename;
fFileMonitor.Interval := 2000;
fFileMonitor.Notifies := [TMonitorNotify.mnFileModified];
fFileMonitor.OnFileChange := FileModifiedNotify;
fFileMonitor.Enabled := True;
end;
destructor TFileOptionsContainer.Destroy;
begin
if Assigned(fFileMonitor) then fFileMonitor.Free;
inherited;
end;
procedure TFileOptionsContainer.FileModifiedNotify(MonitorNotify: TMonitorNotify);
begin
if MonitorNotify = TMonitorNotify.mnFileModified then
begin
if Assigned(fOnFileModified) then fOnFileModified;
if fReloadIfFileChanged then
begin
Load(False);
end;
end;
end;
function TFileOptionsContainer.GetFileSectionNames(out oSections : TArray<string>) : Boolean;
begin
Result := fSerializer.GetFileSectionNames(oSections);
end;
{ TOptions }
function TOptions.ConfigureOptions<T>(aOptionsFunc: TConfigureOptionsProc<T>): IOptionsValidator;
var
value : TValue;
begin
Result := TOptionsValidator.Create(Self);
if Assigned(aOptionsFunc) then
begin
value := Self;
aOptionsFunc(value.AsType<T>);
end;
end;
constructor TOptions.Create;
begin
fName := '';
fHideOptions := False;
end;
procedure TOptions.DefaultValues;
begin
//nothing
end;
procedure TOptions.DoValidateOptions;
var
ivalidator : IOptionsValidator;
begin
ivalidator := TOptionsValidator.Create(Self);
ivalidator.ValidateOptions;
end;
procedure TOptions.ValidateOptions;
begin
try
DoValidateOptions;
except
on E : Exception do
begin
raise EOptionConfigureError.CreateFmt('Validation Options Error : %s',[e.Message]);
end;
end;
end;
{ TOptionsValidator }
procedure TOptionsValidator.ValidateObject(aObj : TObject);
var
ctx : TRttiContext;
rtype : TRttiType;
rprop : TRttiProperty;
attrib : TCustomAttribute;
rvalue : TValue;
begin
rtype := ctx.GetType(aObj.ClassInfo);
for rprop in rtype.GetProperties do
begin
//check only published properties
if rprop.Visibility = TMemberVisibility.mvPublished then
begin
//check validation option attributes
for attrib in rprop.GetAttributes do
begin
if attrib is Required then ValidateRequired(aObj,rprop)
else if attrib is StringLength then ValidateStringLength(aObj,rprop,StringLength(attrib))
else if attrib is Range then ValidateRange(aObj,rprop,Range(attrib));
end;
rvalue := rprop.GetValue(aObj);
if not rvalue.IsEmpty then
begin
case rvalue.Kind of
tkClass : ValidateObject(rvalue.AsObject);
tkDynArray : ValidateArray(rvalue);
end;
end;
end;
end;
end;
constructor TOptionsValidator.Create(aOptions: TOptions);
begin
fOptions := aOptions;
end;
procedure TOptionsValidator.ValidateOptions;
begin
ValidateObject(fOptions);
end;
procedure TOptionsValidator.ValidateArray(aValue : TValue);
type
PPByte = ^PByte;
var
ctx : TRttiContext;
rDynArray : TRttiDynamicArrayType;
itvalue : TValue;
i : Integer;
begin
rDynArray := ctx.GetType(aValue.TypeInfo) as TRTTIDynamicArrayType;
for i := 0 to aValue.GetArrayLength - 1 do
begin
TValue.Make(PPByte(aValue.GetReferenceToRawData)^ + rDynArray.ElementType.TypeSize * i, rDynArray.ElementType.Handle,itvalue);
if not itvalue.IsEmpty then
begin
case itvalue.Kind of
tkClass : ValidateObject(itvalue.AsObject);
tkDynArray : ValidateArray(itvalue);
end;
end;
end;
end;
procedure TOptionsValidator.ValidateRange(const aInstance : TObject; aProperty: TRttiProperty; aValidation : Range);
var
value : TValue;
msg : string;
begin
value := aProperty.GetValue(aInstance);
if not value.IsEmpty then
begin
if value.Kind = tkFloat then
begin
if (value.AsExtended < aValidation.Min) or (value.AsExtended > aValidation.Max) then
begin
if aValidation.ErrorMsg.IsEmpty then msg := Format('Option %s "%s.%s" exceeds predefined range (%2f - %2f)',[fOptions.Name,aInstance.ClassName,aProperty.Name,aValidation.Min,aValidation.Max])
else msg := aValidation.ErrorMsg;
raise EOptionValidationError.Create(msg);
end;
end
else if value.Kind in [tkInteger,tkInt64] then
begin
if (value.AsInt64 < aValidation.Min) or (value.AsInt64 > aValidation.Max) then
begin
if aValidation.ErrorMsg.IsEmpty then msg := Format('Option %s "%s.%s" exceeds predefined range (%d - %d)',[fOptions.Name,aInstance.ClassName,aProperty.Name,Round(aValidation.Min),Round(aValidation.Max)])
else msg := aValidation.ErrorMsg;
raise EOptionValidationError.Create(msg);
end;
end;
end;
end;
procedure TOptionsValidator.ValidateRequired(const aInstance : TObject; aProperty: TRttiProperty);
begin
if aProperty.GetValue(aInstance).IsEmpty then raise EOptionValidationError.CreateFmt('Option %s "%s.%s" is required',[fOptions.Name,aInstance.ClassName,aProperty.Name]);
end;
procedure TOptionsValidator.ValidateStringLength(const aInstance : TObject; aProperty: TRttiProperty; aValidation : StringLength);
var
value : TValue;
msg : string;
begin
value := aProperty.GetValue(aInstance);
if (not value.IsEmpty) and (value.AsString.Length > aValidation.MaxLength) then
begin
if aValidation.ErrorMsg.IsEmpty then msg := Format('Option %s "%s.%s" exceeds max length (%d)',[fOptions.Name,aInstance.ClassName,aProperty.Name,aValidation.MaxLength])
else msg := aValidation.ErrorMsg;
raise EOptionValidationError.Create(msg);
end;
end;
{ Range }
constructor Range.Create(aMin, aMax: Integer; const aErrorMsg : string = '');
begin
fRangeMin := aMin;
fRangeMax := aMax;
fErrorMsg := aErrorMsg;
end;
constructor Range.Create(aMin, aMax: Double; const aErrorMsg: string);
begin
fRangeMin := aMin;
fRangeMax := aMax;
fErrorMsg := aErrorMsg;
end;
{ StringLength }
constructor StringLength.Create(aMaxLength: Integer; const aErrorMsg : string = '');
begin
fMaxLength := aMaxLength;
fErrorMsg := aErrorMsg;
end;
{ TOptionValue<T> }
constructor TOptionValue<T>.Create(aValue: T);
begin
fValue := aValue;
end;
function TOptionValue<T>.GetSectionValue: T;
begin
Result := fValue;
end;
{ TOptions<T> }
function TOptions<T>.ConfigureOptions(aOptionsFunc: TConfigureOptionsProc<T>): IOptionsValidator;
begin
if Assigned(aOptionsFunc) then Result := fOptions.ConfigureOptions<T>(aOptionsFunc)
else Result := TOptionsValidator.Create(fOptions);
end;
constructor TOptions<T>.Create(aOptions: T);
begin
fOptions := aOptions;
end;
{ TOptionsBuilder<T> }
constructor TOptionsBuilder<T>.Create;
begin
fOptions := (PTypeInfo(TypeInfo(T)).TypeData.ClassType.Create) as T;
end;
function TOptionsBuilder<T>.Options: T;
begin
Result := fOptions;
end;
{ TOptionsFileSerializer }
function TOptionsFileSerializer.GetFileName: string;
begin
Result := fFilename;
end;
procedure TOptionsFileSerializer.SetFileName(const aFilename: string);
begin
fFilename := aFilename;
end;
end.
|
//---------------------------------------------------------------------------
// This software is Copyright (c) 2015 Embarcadero Technologies, Inc.
// You may only use this software if you are an authorized licensee
// of an Embarcadero developer tools product.
// This software is considered a Redistributable as defined under
// the software license agreement that comes with the Embarcadero Products
// and is subject to that software license agreement.
//---------------------------------------------------------------------------
unit ResourceModuleU;
// EMS Resource Module
interface
uses
System.SysUtils, System.Classes, System.JSON, EMS.Services, EMS.ResourceAPI,
EMS.ResourceTypes, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param,
FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf,
FireDAC.Stan.Async, FireDAC.DApt, FireDAC.UI.Intf, FireDAC.Stan.ExprFuncs,
FireDAC.Phys.SQLiteDef, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Phys,
FireDAC.Phys.SQLite, Data.DB, FireDAC.Comp.Client, FireDAC.Comp.UI,
FireDAC.Stan.StorageJSON, FireDAC.Comp.DataSet, FireDAC.ConsoleUI.Wait,
EMS.DataSetResource;
type
[ResourceName('test')] // Url segment. For example, use http://localhost:8080/test
TResourceModule = class(TDataModule)
dsOrders: TDataSource;
dsCustomers: TDataSource;
qOrders: TFDQuery;
qCustomers: TFDQuery;
FDSchemaAdapter1: TFDSchemaAdapter;
FDStanStorageJSONLink1: TFDStanStorageJSONLink;
FDGUIxWaitCursor1: TFDGUIxWaitCursor;
FDPhysSQLiteDriverLink1: TFDPhysSQLiteDriverLink;
FDConnection1: TFDConnection;
[EndPointRequestSummary('List', 'FireDACResource', 'List Of Records', 'Process GetRecords and return available records', 'application/vnd.embarcadero.firedac+json', '')]
[EndPointRequestSummary('Post', 'FireDACResource', 'Post Updates', 'Process PostUpdates and save changed records', '', 'application/vnd.embarcadero.firedac+json')]
[EndPointRequestSummary('Get', 'FireDACResource', 'Not Implemented', 'Endpoint is not enabled.', '', '')]
[EndPointRequestSummary('Put', 'FireDACResource', 'Not Implemented', 'Endpoint is not enabled.', '', '')]
[EndPointRequestSummary('Delete', 'FireDACResource', 'Not Implemented', 'Endpoint is not enabled.', '', '')]
[EndPointResponseDetails(200, 'Ok', TAPIDoc.TPrimitiveType.spObject, TAPIDoc.TPrimitiveFormat.None, '', '')]
[ResourceSuffix('/')]
[EndpointName('GetRecords', 'List')] // Name to show in analytics
[EndpointName('PostUpdates', 'Post')] // Name to show in analytics
EMSDataSetResource1: TEMSDataSetResource;
end;
procedure Register;
implementation
{%CLASSGROUP 'System.Classes.TPersistent'}
{$R *.dfm}
procedure Register;
begin
RegisterResource(TypeInfo(TResourceModule));
end;
end.
|
unit uImportarNFeXLS;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, DB, ZAbstractRODataset, ZDataset, JvDialogs, ImgList,
Menus, ZAbstractDataset, Buttons, ExtCtrls, Grids, DBGrids, JvExDBGrids,
JvDBGrid, JvExStdCtrls, JvGroupBox, JvCombobox, ZConnection, DBCtrls,
JvExControls, JvNavigationPane, JvComponentBase, JvFormPlacement, xmldom,
XMLIntf, msxmldom, XMLDoc, DBClient, LbCipher, LbUtils, IdBaseComponent,
IdComponent, IdTCPConnection, IdTCPClient, IdHTTP, ComCtrls, Mask,
JvExMask, JvToolEdit, JvDBControls, JvSpeedButton, JvBaseEdits, ACBrBase,
ACBrEnterTab, CheckDoc, JvDBCombobox, cxGraphics, cxControls,
cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, cxTextEdit,
cxMaskEdit, cxDropDownEdit, cxImageComboBox;
type
TTipoCadastro = (tcCobranca, tcEntrega);
TfrmImportarNFeXLS = class(TForm)
qrInsertXLs: TZReadOnlyQuery;
dsNotasXLS: TDataSource;
qrNotasXLS: TZQuery;
qrNotasXLSid: TLargeintField;
qrNotasXLSempresa_codigo: TLargeintField;
qrNotasXLScodigo: TLargeintField;
qrNotasXLSdata: TDateTimeField;
qrNotasXLSdata_importacao: TDateTimeField;
qrNotasXLScliente_codigo: TIntegerField;
qrNotasXLScliente_filial: TIntegerField;
qrNotasXLSnome: TStringField;
qrNotasXLScnpj: TStringField;
qrNotasXLStelefone: TStringField;
qrNotasXLSlogradouro: TStringField;
qrNotasXLSnumero: TStringField;
qrNotasXLScomplemento: TStringField;
qrNotasXLSbairro: TStringField;
qrNotasXLScidade: TStringField;
qrNotasXLScep: TStringField;
qrNotasXLSuf: TStringField;
qrNotasXLScob_logradouro: TStringField;
qrNotasXLScob_numero: TStringField;
qrNotasXLScob_complemento: TStringField;
qrNotasXLScob_bairro: TStringField;
qrNotasXLScob_cidade: TStringField;
qrNotasXLScob_cep: TStringField;
qrNotasXLScob_uf: TStringField;
qrNotasXLSmeio_pagamento: TStringField;
qrNotasXLSforma_pagamento: TStringField;
qrNotasXLSparcelas: TIntegerField;
qrNotasXLSvencimento: TDateField;
qrNotasXLSdata_fatura: TDateField;
qrNotasXLSgrupo: TStringField;
qrNotasXLSproduto: TStringField;
qrNotasXLSquantidade: TFloatField;
qrNotasXLSunitario: TFloatField;
qrNotasXLStotal: TFloatField;
qrNotasXLSmarca: TFloatField;
PopupMenu1: TPopupMenu;
MarcarTodos1: TMenuItem;
DesmarcarTodos1: TMenuItem;
InverterSeleo1: TMenuItem;
ImageList1: TImageList;
qrNotasItens: TZQuery;
JvOpenDialog1: TJvOpenDialog;
JvGroupBox1: TJvGroupBox;
Label1: TLabel;
edCNPJ: TEdit;
Label2: TLabel;
cbMeio: TJvComboBox;
Label3: TLabel;
cbTipo: TJvComboBox;
JvNavPanelHeader4: TJvNavPanelHeader;
DBText2: TDBText;
DBText1: TDBText;
DBText3: TDBText;
DBText4: TDBText;
DBText5: TDBText;
dsCabecalho: TDataSource;
qrCabecalho: TZReadOnlyQuery;
qrCabecalhocredito_vista: TStringField;
qrCabecalhoboleto_vista: TStringField;
qrCabecalhocredito_parcelado: TStringField;
qrCabecalhoboleto_2x: TStringField;
qrCabecalhototal: TStringField;
lbl1: TLabel;
edtNome: TEdit;
lbl2: TLabel;
Bevel1: TBevel;
qrUltimo: TZReadOnlyQuery;
Label5: TLabel;
Label6: TLabel;
qrNotasXLScliente: TIntegerField;
Label7: TLabel;
cbEnvio: TJvComboBox;
Label8: TLabel;
cbCliente: TJvComboBox;
JvFormStorage1: TJvFormStorage;
Label4: TLabel;
NotasFiltradas: TJvNavPanelHeader;
cdsLojaVirtual: TClientDataSet;
xmlLojaVirtual: TXMLDocument;
qrNotasXLSenvio: TLargeintField;
Label9: TLabel;
cbImportacao: TJvComboBox;
qrNotasXLStipo_importacao: TStringField;
PageControl1: TPageControl;
tbsGrid: TTabSheet;
JvDBGrid1: TJvDBGrid;
tbsFicha: TTabSheet;
dsFicha: TDataSource;
qrFicha: TZQuery;
qrFichaid: TLargeintField;
qrFichaempresa_codigo: TLargeintField;
qrFichacodigo: TLargeintField;
qrFichadata: TDateTimeField;
qrFichadata_importacao: TDateTimeField;
qrFichacliente_codigo: TIntegerField;
qrFichacliente_filial: TIntegerField;
qrFichanome: TStringField;
qrFichacnpj: TStringField;
qrFichaemail: TStringField;
qrFichatelefone: TStringField;
qrFichalogradouro: TStringField;
qrFichanumero: TStringField;
qrFichacomplemento: TStringField;
qrFichabairro: TStringField;
qrFichacidade: TStringField;
qrFichacep: TStringField;
qrFichauf: TStringField;
qrFichacob_logradouro: TStringField;
qrFichacob_numero: TStringField;
qrFichacob_complemento: TStringField;
qrFichacob_bairro: TStringField;
qrFichacob_cidade: TStringField;
qrFichacob_cep: TStringField;
qrFichacob_uf: TStringField;
qrFichameio_pagamento: TStringField;
qrFichaforma_pagamento: TStringField;
qrFichaparcelas: TIntegerField;
qrFichavencimento: TDateField;
qrFichadata_fatura: TDateField;
qrFichagrupo: TStringField;
qrFichaproduto: TStringField;
qrFichaquantidade: TFloatField;
qrFichaunitario: TFloatField;
qrFichatotal: TFloatField;
qrFichaenvio: TLargeintField;
qrFichacliente: TSmallintField;
qrFichatipo_importacao: TStringField;
DataSource1: TDataSource;
Label10: TLabel;
edCodigo: TDBEdit;
Label11: TLabel;
Label12: TLabel;
edCodCli: TDBEdit;
edCodFilial: TDBEdit;
Label14: TLabel;
Label15: TLabel;
Label16: TLabel;
edEmail: TDBEdit;
Label17: TLabel;
DBEdit8: TDBEdit;
Label18: TLabel;
edLogradouro: TDBEdit;
Label19: TLabel;
edNumero: TDBEdit;
Label20: TLabel;
edComplemento: TDBEdit;
Label21: TLabel;
edBairro: TDBEdit;
Label22: TLabel;
edCidade: TDBEdit;
Label23: TLabel;
edCepEntrega: TDBEdit;
Label24: TLabel;
edUF: TDBEdit;
Label25: TLabel;
edLogradouroCobranca: TDBEdit;
Label26: TLabel;
edNumeroCobranca: TDBEdit;
Label27: TLabel;
edComplementoCobranca: TDBEdit;
Label28: TLabel;
edBairroCobranca: TDBEdit;
Label29: TLabel;
edCidadeCobranca: TDBEdit;
Label30: TLabel;
edCepCobranca: TDBEdit;
Label31: TLabel;
edUFCobranca: TDBEdit;
Label32: TLabel;
Label33: TLabel;
Label34: TLabel;
Label35: TLabel;
Label36: TLabel;
Label37: TLabel;
Label38: TLabel;
Label39: TLabel;
Label40: TLabel;
Label41: TLabel;
Panel2: TPanel;
Bevel2: TBevel;
Label42: TLabel;
edData: TJvDBDateEdit;
btGravar: TJvSpeedButton;
btCancelar: TJvSpeedButton;
btExcluir: TJvSpeedButton;
btAlterar: TJvSpeedButton;
btIncluir: TJvSpeedButton;
btGridFicha: TJvSpeedButton;
Label43: TLabel;
Bevel3: TBevel;
edUnitario: TJvDBCalcEdit;
edQuantidade: TJvDBCalcEdit;
edTotal: TJvDBCalcEdit;
edVencimento: TJvDBDateEdit;
Bevel4: TBevel;
Label45: TLabel;
Label13: TLabel;
Bevel5: TBevel;
Label44: TLabel;
Bevel6: TBevel;
Label46: TLabel;
Label47: TLabel;
StatusBar1: TStatusBar;
Panel1: TPanel;
SpeedButton1: TSpeedButton;
SpeedButton2: TSpeedButton;
SpeedButton3: TSpeedButton;
SpeedButton4: TSpeedButton;
btnAtualizar: TSpeedButton;
SpeedButton5: TSpeedButton;
SpeedButton7: TSpeedButton;
SpeedButton6: TSpeedButton;
Bevel7: TBevel;
ACBrEnterTab1: TACBrEnterTab;
cbProdutoEdit: TJvDBComboBox;
cbMeioPagamento: TJvDBComboBox;
cbFormaPagamento: TJvDBComboBox;
DBCheckDocEdit1: TDBCheckDocEdit;
cbEnvioProduto: TJvDBComboBox;
JvSpeedButton1: TJvSpeedButton;
JvSpeedButton2: TJvSpeedButton;
cbTipoImportacao: TJvDBComboBox;
cbTipoCliente: TJvDBComboBox;
ckEndCob: TCheckBox;
edCliente: TJvDBComboEdit;
qrFichauser_inclusao: TStringField;
qrFichadata_inclusao: TDateTimeField;
qrFichauser_alteracao: TStringField;
qrFichadata_alteracao: TDateTimeField;
qrFichaitem: TLargeintField;
SpeedButton8: TSpeedButton;
cbProduto: TcxImageComboBox;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure JvDBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect;
DataCol: Integer; Column: TColumn; State: TGridDrawState);
procedure JvDBGrid1CellClick(Column: TColumn);
procedure MarcarTodos1Click(Sender: TObject);
procedure DesmarcarTodos1Click(Sender: TObject);
procedure InverterSeleo1Click(Sender: TObject);
procedure JvDBGrid1KeyPress(Sender: TObject; var Key: Char);
procedure qrNotasXLScnpjGetText(Sender: TField; var Text: string;
DisplayText: Boolean);
procedure SpeedButton1Click(Sender: TObject);
procedure SpeedButton2Click(Sender: TObject);
procedure SpeedButton3Click(Sender: TObject);
procedure SpeedButton4Click(Sender: TObject);
procedure SpeedButton5Click(Sender: TObject);
procedure cbMeioClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure qrNotasXLSenvioGetText(Sender: TField; var Text: string;
DisplayText: Boolean);
procedure qrNotasXLSclienteGetText(Sender: TField; var Text: string;
DisplayText: Boolean);
procedure btnAtualizarClick(Sender: TObject);
procedure SpeedButton7Click(Sender: TObject);
procedure SpeedButton9Click(Sender: TObject);
procedure qrNotasXLStipo_importacaoGetText(Sender: TField;
var Text: string; DisplayText: Boolean);
procedure btExcluirClick(Sender: TObject);
procedure btIncluirClick(Sender: TObject);
procedure btAlterarClick(Sender: TObject);
procedure btGridFichaClick(Sender: TObject);
procedure btCancelarClick(Sender: TObject);
procedure btGravarClick(Sender: TObject);
procedure JvSpeedButton1Click(Sender: TObject);
procedure JvSpeedButton2Click(Sender: TObject);
procedure edQuantidadeExit(Sender: TObject);
procedure ckEndCobClick(Sender: TObject);
procedure edClienteButtonClick(Sender: TObject);
procedure edCodFilialExit(Sender: TObject);
procedure SpeedButton6Click(Sender: TObject);
procedure dsFichaDataChange(Sender: TObject; Field: TField);
procedure SpeedButton8Click(Sender: TObject);
private
{ Private declarations }
FSerie, FNota, FModelo: Integer;
bEdit: Boolean;
ReturnToGridAfterEdit: Boolean;
funcao: string;
procedure ImportarNFe;
procedure ImportarNFeWB;
function VeCliente(const ACnpj: string; var Cliente, Filial: Integer): Boolean;
function VeCodigoIBGE(ACidade, AUF: string): string;
procedure CadastraCliente;
procedure Selecao_Grade(Tipo: Integer);
procedure ve_proxima_nota(AEmpresa: Integer; AOperacao: string; AGrava: Boolean = True);
procedure GerarNFe;
function VeCodigoImportado(ACodigo: string; AItem: Integer = 1; ATipo: Integer = 1): Boolean;
procedure VeNotas;
procedure UltimoCodigo;
procedure AtualizaContagem;
procedure AtualizaNotaImportada(ACodigo: Integer);
function VeContaNotas: Integer;
function GetLinkLoja(bConta: Boolean = False): string;
procedure AtualizaTotalProdutos(AID_Nota: Integer);
procedure EnableEdit(OldState: TDataSetState); dynamic;
procedure atualiza_cep(ACEP: string; AEntrega: TTipoCadastro = tcEntrega);
procedure HabilitaBotoes;
public
{ Public declarations }
end;
var
frmImportarNFeXLS: TfrmImportarNFeXLS;
implementation
uses
udmPrincipal, funcoes, ComObj, uClientes, uSeriesNotasFiscais,
uNotaFiscal_Eletronica, uTipoImportacaoNotas, uConsultarNFeXLS,
uConsulta_Padrao, uProdutosKits;
{$R *.dfm}
{ TForm1 }
procedure TfrmImportarNFeXLS.CadastraCliente;
var
qrTemp, qrCliente: TZReadOnlyQuery;
Cliente: Integer;
begin
qrTemp := TZReadOnlyQuery.Create(nil);
qrCliente := TZReadOnlyQuery.Create(nil);
try
qrCliente.Connection := dmPrincipal.Database;
qrTemp.Connection := dmPrincipal.Database;
qrTemp.Close;
qrTemp.SQL.Clear;
qrTemp.SQL.Add('select * from notas_fiscais_xls');
qrTemp.SQL.Add('where cliente_codigo=-1 and cliente_filial=-1 and isnull(data_importacao)');
qrTemp.SQL.Add('group by cnpj');
qrTemp.Open;
while not qrTemp.Eof do
begin
with qrCliente do
begin
Close;
SQL.Clear;
SQL.Add('insert into clientes_fornecedores(');
SQL.Add(' codigo,filial,tipo_cadastro,tipo_pessoa,nome,fantasia,cnpj,logradouro,numero,complemento,');
SQL.Add(' bairro,cep,codigo_cidade,cidade,uf,telefone1,user_inclusao,data_inclusao,regime_tributario,email,danfe_pdf)');
SQL.Add('select');
SQL.Add(' :codigo,:filial,"C",:pessoa,nome,nome,:cnpj,logradouro,numero,complemento,');
SQL.Add(' bairro,:cep,:ibge,cidade,uf,telefone,:usuario,current_date,1,email,"S"');
SQL.Add('from notas_fiscais_xls');
SQL.Add('where codigo=:pCodigo');
ParamByName('pCodigo').Value := qrTemp['codigo'];
Cliente := Sequenciador('clientes');
ParamByName('codigo').Value := Cliente;
ParamByName('filial').Value := 0;
if Length(qrTemp['cnpj']) > 11 then
begin
ParamByName('pessoa').Value := 'J';
ParamByName('cnpj').Value := FormataCnpj(qrTemp['cnpj']);
end
else
begin
ParamByName('pessoa').Value := 'F';
ParamByName('cnpj').Value := FormataCpf(qrTemp['cnpj']);
end;
ParamByName('cep').Value := FormataCep(qrTemp.fieldbyname('cep').AsString);
ParamByName('ibge').Value := VeCodigoIBGE(qrTemp['cidade'], qrTemp['uf']);
ParamByName('usuario').Value := dmPrincipal.usuario;
ExecSQL;
SQL.Text := 'update notas_fiscais_xls set cliente_codigo=:cliente,cliente_filial=0 where codigo=:codigo';
ParamByName('cliente').Value := Cliente;
ParamByName('codigo').Value := qrTemp['codigo'];
try
ExecSQL;
except
end;
end;
qrTemp.Next;
end;
finally
qrTemp.Free;
qrCliente.Free;
end;
end;
procedure TfrmImportarNFeXLS.ImportarNFe;
var
Cliente, Filial: Integer;
linha, linha_inicial, linha_final: integer;
planilha, sheet: OleVariant;
ValorSheet, ValorSheet1, Codigo: string;
Data: TDateTime;
T: TFormatSettings;
begin
JvOpenDialog1.Title := 'Selecione a Planilha Excel';
JvOpenDialog1.DefaultExt := '*.XLS';
JvOpenDialog1.Filter := 'Arquivos do Excel 2003 (*.xls)|*.xls|Arquivos do Excel 2010 (*.xlsx)|*.xlsx';
if not JvOpenDialog1.Execute then
Exit;
try
planilha := CreateOleObject('Excel.Application');
planilha.Workbooks.Open(JvOpenDialog1.FileName);
sheet := planilha.workbooks[1].worksheets[1];
ValorSheet := sheet.Range['B1'];
if ValorSheet <> 'CODIGO_PEDIDO' then
begin
MessageBox(handle, 'O layout da planilha está diferente do layout do sistema.' + #13 + 'Corrija a planilha e tente importar novamente.', 'Erro na Importação', mb_ok + mb_IconError);
Exit;
end;
linha_inicial := 2;
linha_final := sheet.Cells.SpecialCells(11).Row;
for linha := linha_inicial to linha_final do
begin
try
ValorSheet := sheet.cells[linha, 1];
if ValorSheet = EmptyStr then
Break;
with qrInsertXLs do
begin
ParamByName('empresa_codigo').Value := dmPrincipal.empresa_login;
ParamByName('item').AsInteger := 1;
ParamByName('tipo_importacao').AsInteger := 1;
ValorSheet := sheet.cells[linha, 2];
Codigo := ValorSheet;
ParamByName('codigo').Value := Codigo;
ValorSheet := sheet.cells[linha, 1];
T.ShortDateFormat := 'yyyy-mm-dd hh:nn';
T.DateSeparator := '-';
Data := StrToDateTime(ValorSheet, T);
ParamByName('data').AsDateTime := Data;
ValorSheet := sheet.cells[linha, 3];
ParamByName('nome').Value := AnsiUpperCase(ValorSheet);
ValorSheet := sheet.cells[linha, 4];
if not VeCliente(ValorSheet, Cliente, Filial) then
begin
Cliente := -1;
Filial := -1;
end;
ParamByName('cliente_codigo').Value := Cliente;
ParamByName('cliente_filial').Value := Filial;
ParamByName('cnpj').Value := ValorSheet;
ValorSheet := sheet.cells[linha, 5];
ValorSheet1 := sheet.cells[linha, 6];
ParamByName('telefone').Value := ValorSheet + ValorSheet1;
ValorSheet := sheet.cells[linha, 7];
ValorSheet1 := sheet.cells[linha, 8];
ParamByName('logradouro').Value := ValorSheet + ' ' + ValorSheet1;
ValorSheet := sheet.cells[linha, 9];
ParamByName('numero').Value := ValorSheet;
ValorSheet := sheet.cells[linha, 10];
ParamByName('complemento').Value := ValorSheet;
ValorSheet := sheet.cells[linha, 11];
ParamByName('bairro').Value := ValorSheet;
ValorSheet := sheet.cells[linha, 12];
ParamByName('cidade').Value := ValorSheet;
ValorSheet := sheet.cells[linha, 13];
ParamByName('cep').Value := SoNumeros(ValorSheet);
ValorSheet := sheet.cells[linha, 14];
ParamByName('uf').Value := ValorSheet;
ValorSheet := sheet.cells[linha, 15];
ValorSheet1 := sheet.cells[linha, 16];
ParamByName('cob_logradouro').Value := ValorSheet + ' ' + ValorSheet1;
ValorSheet := sheet.cells[linha, 17];
ParamByName('cob_numero').Value := ValorSheet;
ValorSheet := sheet.cells[linha, 18];
ParamByName('cob_complemento').Value := ValorSheet;
ValorSheet := sheet.cells[linha, 19];
ParamByName('cob_bairro').Value := ValorSheet;
ValorSheet := sheet.cells[linha, 20];
ParamByName('cob_cidade').Value := ValorSheet;
ValorSheet := sheet.cells[linha, 21];
ParamByName('cob_cep').Value := SoNumeros(ValorSheet);
ValorSheet := sheet.cells[linha, 22];
ParamByName('cob_uf').Value := ValorSheet;
ValorSheet := sheet.cells[linha, 23];
ParamByName('meio_pagamento').Value := ValorSheet;
ValorSheet := sheet.cells[linha, 24];
ParamByName('forma_pagamento').Value := ValorSheet;
ValorSheet1 := sheet.Range['Y' + IntToStr(linha)];
ValorSheet := EmptyStr;
ValorSheet := SoNumeros(ValorSheet1);
ParamByName('parcelas').Value := ValorSheet;
ValorSheet := sheet.cells[linha, 26];
if ValorSheet <> EmptyStr then
begin
T.ShortDateFormat := 'yyyy-mm-dd';
T.DateSeparator := '-';
Data := StrToDate(ValorSheet, T);
ParamByName('vencimento').AsDate := Data;
end
else
ParamByName('vencimento').AsDate := dmPrincipal.SoData;
ValorSheet := sheet.cells[linha, 27];
ParamByName('produto').Value := ValorSheet;
ValorSheet := sheet.cells[linha, 28];
ParamByName('quantidade').Value := StrToFloat(StringReplace(ValorSheet, '.', ',', []));
ValorSheet := sheet.cells[linha, 29];
ParamByName('unitario').Value := StrToFloat(StringReplace(ValorSheet, '.', ',', []));
ParamByName('total').Value := ParamByName('unitario').Value * ParamByName('quantidade').Value;
ValorSheet := sheet.Range['AD' + IntToStr(linha)];
ParamByName('email').Value := ValorSheet;
//Coluna para e-Sedex (1) ou PAC (2)
ValorSheet := sheet.Range['AE' + IntToStr(linha)];
ParamByName('envio').Value := ValorSheet;
//Coluna para Inadimplente (1) ou Sem Pendências (2)
ValorSheet := sheet.Range['AF' + IntToStr(linha)];
ParamByName('cliente').Value := ValorSheet;
try
if not VeCodigoImportado(Codigo) then
ExecSQL;
except
on E: Exception do
ShowMessage(E.Message);
end;
end;
except
planilha.workbooks[1].close(0);
planilha.quit;
planilha := Unassigned;
sheet := Unassigned;
ShowMessage('Erro ao importar os dados da planilha [' + JvOpenDialog1.FileName + ']');
end;
end;
CadastraCliente;
qrNotasXLS.Refresh;
ShowMessage('Arquivo importado com sucesso');
finally
planilha.workbooks[1].close(0);
planilha.quit;
planilha := Unassigned;
sheet := Unassigned;
end;
end;
function TfrmImportarNFeXLS.VeCliente(const ACnpj: string; var Cliente,
Filial: Integer): Boolean;
var
qrTemp: TZReadOnlyQuery;
begin
Result := False;
qrTemp := TZReadOnlyQuery.Create(nil);
try
qrTemp.Connection := dmPrincipal.Database;
qrTemp.Close;
qrTemp.SQL.Clear;
qrTemp.SQL.Add('select codigo,filial from clientes_fornecedores');
qrTemp.SQL.Add('where trim(replace(replace(replace(cnpj,".",""),"/",""),"-",""))=' + Trim(SoNumeros(ACNPJ)));
qrTemp.Open;
Result := not qrTemp.IsEmpty;
if Result then
begin
Cliente := qrTemp.Fields[0].AsInteger;
Filial := qrTemp.Fields[1].AsInteger;
end;
finally
qrTemp.Free;
end;
end;
function TfrmImportarNFeXLS.VeCodigoIBGE(ACidade, AUF: string): string;
var
qrIBGE: TZReadOnlyQuery;
begin
Result := EmptyStr;
qrIBGE := TZReadOnlyQuery.Create(nil);
try
qrIBGE.Connection := dmPrincipal.Database;
with qrIBGE do
begin
Close;
sql.clear;
sql.Add('select c.codigo_cidade from cidades c, estados e');
sql.Add('where e.codigo=c.codigo_uf');
sql.Add('and c.nome=:pCidade and e.sigla=:pUF');
ParamByName('pCidade').AsString := ACidade;
ParamByName('pUF').AsString := AUF;
Open;
if not IsEmpty then
Result := fieldbyname('codigo_cidade').AsString;
end;
finally
FreeAndNil(qrIBGE);
end;
end;
procedure TfrmImportarNFeXLS.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
qrNotasXLS.Close;
qrFicha.Close;
Action := caFree;
end;
procedure TfrmImportarNFeXLS.FormCreate(Sender: TObject);
begin
VeNotas;
qrCabecalho.Open;
qrFicha.Open;
CarregaCombo(cbProdutoEdit, 'select id, nome from produtos_kits where ativo="S" order by 2');
CarregaCombo(cbProduto, 'select id, nome from produtos_kits where ativo="S" order by 2');
end;
procedure TfrmImportarNFeXLS.JvDBGrid1DrawColumnCell(Sender: TObject;
const Rect: TRect; DataCol: Integer; Column: TColumn;
State: TGridDrawState);
begin
if (Column.Index = 0) and (not dsNotasXLS.DataSet.IsEmpty) then
begin
// Desenha um campo em branco
JvDBGrid1.Canvas.FillRect(Rect);
ImageList1.Draw(JvDBGrid1.Canvas, Rect.Left + 3, Rect.Top + 1, qrNotasXLSMarca.AsInteger);
end;
end;
procedure TfrmImportarNFeXLS.JvDBGrid1CellClick(Column: TColumn);
begin
qrNotasXLS.Edit;
if qrNotasXLSMarca.AsInteger = 0 then
qrNotasXLSMarca.AsInteger := 1
else
qrNotasXLSMarca.AsInteger := 0;
qrNotasXLS.Post;
end;
procedure TfrmImportarNFeXLS.Selecao_Grade(Tipo: Integer);
begin
qrNotasXLS.DisableControls;
qrNotasXLS.First;
while not qrNotasXLS.Eof do
begin
qrNotasXLS.Edit;
case Tipo of
1: qrNotasXLSmarca.AsInteger := 0; // Marcar todos
2: qrNotasXLSmarca.AsInteger := 1; // Desmarcar todas
3: if qrNotasXLSmarca.AsInteger = 0 then // Alternar seleção
qrNotasXLSmarca.AsInteger := 1
else
qrNotasXLSmarca.AsInteger := 0;
end;
qrNotasXLS.Next;
end;
qrNotasXLS.First;
qrNotasXLS.EnableControls;
end;
procedure TfrmImportarNFeXLS.MarcarTodos1Click(Sender: TObject);
begin
Selecao_Grade(1);
end;
procedure TfrmImportarNFeXLS.DesmarcarTodos1Click(Sender: TObject);
begin
Selecao_Grade(2);
end;
procedure TfrmImportarNFeXLS.InverterSeleo1Click(Sender: TObject);
begin
Selecao_Grade(3);
end;
procedure TfrmImportarNFeXLS.JvDBGrid1KeyPress(Sender: TObject;
var Key: Char);
begin
if Key = #32 then //barra de espaço
JvDBGrid1CellClick(nil);
end;
procedure TfrmImportarNFeXLS.GerarNFe;
var
qrTemp: TZReadOnlyQuery;
Observacoes: WideString;
ID_Nota: Integer;
bImportou: Boolean;
begin
qrTemp := TZReadOnlyQuery.Create(nil);
bImportou := False;
try
qrTemp.Connection := dmPrincipal.Database;
qrNotasXLS.First;
while not qrNotasXLS.Eof do
begin
if qrNotasXLSmarca.AsInteger = 0 then
with qrTemp do
begin
bImportou := True;
Close;
SQL.Clear;
SQL.Add('insert into notas_fiscais(');
SQL.Add('id,tipo_operacao,tipo_pt,empresa_codigo,serie,nota,modelo,');
SQL.Add('venda_codigo,cfop,cfop_dv,nat_operacao,emissao,saida,vencimento,tipo_frete,');
SQL.Add('fatura,valor_produtos,valor_nota,base_icms,');
SQL.Add('valor_icms,ipi,pis,cofins,cliente_codigo,cliente_filial,cliente_nome,cliente_cnpj,');
SQL.Add('cliente_ie,end_logradouro,end_numero,end_complemento,end_bairro,end_codigo_cidade,');
SQL.Add('end_cidade,end_uf,end_nome_pais,end_codigo_pais,end_cep,telefone,observacoes,');
SQL.Add('user_inclusao,data_inclusao,meio_pagamento,forma_pagamento,emitido)');
SQL.Add('select');
SQL.Add(':pID,"S","P",empresa_codigo,:pSerie,:pNota,:pModelo,');
SQL.Add('a.codigo,concat(if(a.uf="SP","5","6"),"102"),1,:pNatureza,current_date,current_date,a.vencimento,"E",');
SQL.Add('NULL,sum(total) total_produtos,');
SQL.Add('sum(total) valor_nota,0,');
SQL.Add('0,0,0,0,cliente_codigo,cliente_filial,a.nome,c.cnpj,');
SQL.Add('ie,a.logradouro,a.numero,a.complemento,a.bairro,codigo_cidade,');
SQL.Add('a.cidade,a.uf,nome_pais,codigo_pais,INSERT(a.cep,6,0,"-"),a.telefone,:pObservacao,');
SQL.Add(':pUsuario,current_date,:pMeio_pagamento,:pForma_pagamento,:pEmitido');
SQL.Add('from notas_fiscais_xls a left join clientes_fornecedores c on cliente_codigo=c.codigo and cliente_filial=filial');
SQL.Add('where empresa_codigo=:pEmpresa and a.codigo=:pVenda');
SQL.Add('group by a.codigo');
Observacoes := 'I. DOCUMENTO EMITIDO POR ME OU EPP OPTANTE PELO SIMPLES NACIONAL' + #13#10 + 'II. NÃO GERA DIREITO DE CREDITO FISCAL DE ISS E IPI';
ve_proxima_nota(qrNotasXLS['empresa_codigo'], 'S', False);
ID_Nota := Sequenciador('notas_fiscais', dmPrincipal.empresa_real);
ParamByName('pID').Value := ID_Nota;
ParamByName('pSerie').Value := FSerie;
ParamByName('pNota').Value := FNota;
ParamByName('pModelo').Value := FModelo;
ParamByName('pNatureza').AsString := 'VENDAS';
ParamByName('pObservacao').AsString := Observacoes;
ParamByName('pEmpresa').Value := qrNotasXLS['empresa_codigo'];
ParamByName('pVenda').Value := qrNotasXLS['codigo'];
ParamByName('pUsuario').Value := dmPrincipal.usuario;
ParamByName('pForma_pagamento').AsInteger := StrToIntDef(qrNotasXLS.FieldByName('meio_pagamento').AsString, 1);
if StrToIntDef(qrNotasXLS.FieldByName('meio_pagamento').AsString, 0) in [2, 4] then //Boleto
ParamByName('pMeio_pagamento').AsInteger := 1
else if StrToIntDef(qrNotasXLS.FieldByName('meio_pagamento').AsString, 0) in [1, 3] then //Crédito em conta
ParamByName('pMeio_pagamento').AsInteger := 5;
{ ***** Pedido Cleiton para Impressão automáttica dos Kits - 25/11/2013
//Nova opção para já marcar notas de Suplemento como Impressa
if StrToIntDef(qrNotasXLS.FieldByName('produto').AsString, 0) in [1, 2] then //Livro
ParamByName('pEmitido').AsInteger := 0
else if StrToIntDef(qrNotasXLS.FieldByName('produto').AsString, 0) in [5, 6] then //Suplemento
ParamByName('pEmitido').AsInteger := 1;
***** }
ParamByName('pEmitido').AsInteger := 0;
ExecSQL;
{ ***** Insere os Itens da Nota ***** }
qrNotasItens.Close;
qrNotasItens.ParamByName('pCodigo').Value := qrNotasXLS['codigo'];
qrNotasItens.Open;
qrNotasItens.First;
while not qrNotasItens.Eof do
begin
Close;
SQL.Clear;
SQL.Add('insert into notas_fiscais_itens(');
SQL.Add('id,id_nota,tipo_operacao,empresa_codigo,serie,nota,emissao,cliente_codigo,cliente_filial,cfop_item,cfop_dv_item,');
SQL.Add('num_item,produto_codigo,produto_ncm,produto_nome,cst,unidade,quantidade,valor_total,valor_unitario,soma_item_nf,');
SQL.Add('mod_icms,icms_item,base_icms_item,valor_icms_item,cst_ipi,ipi_item,base_ipi_item,valor_ipi_item,');
SQL.Add('valor_pis_item,valor_cofins_item,');
SQL.Add('user_inclusao,data_inclusao,base_ii_item,valor_ii_item,');
SQL.Add('pis_item,cofins_item,cst_pis,cst_cofins,base_pis_cofins_item,calcula_icms,calcula_ipi,calcula_icms_st,calcula_pis,calcula_cofins)');
SQL.Add('select');
SQL.Add(' :pID,:pID_Nota,"S",a.empresa_codigo,:pSerie,:pNota,current_date,cliente_codigo,cliente_filial,concat(if(uf="SP","5","6"),if(perc_custo=0,"910","102")),1,');
SQL.Add(' :pItemNota,produto_codigo,codigo_ncm,p.nome,"0400",unidade,k.quantidade,');
SQL.Add(' @total:=if(perc_custo=0,0/*p.preco*/,total*perc_custo/100) as valor_total,');
SQL.Add(' @total/k.quantidade as valor_unitario,');
SQL.Add(' if(perc_custo=0,"N","S") as soma_item,');
SQL.Add(' null,0,0,0,null,0,0,0,0,0,:pUsuariio,current_date,0,0,0,0,"99","99",0,"S","S","S","S","S"');
SQL.Add('from notas_fiscais_xls a');
SQL.Add(' left join produtos_kits_itens k on k.id_kit=a.produto');
SQL.Add(' left join produtos p on p.codigo=k.produto_codigo');
SQL.Add('where a.empresa_codigo=:pEmpresa and a.id=:pID_XLS');
SQL.Add(' and produto_codigo=:pProduto');
SQL.Add('order by a.codigo');
ParamByName('pID').Value := Sequenciador('notas_fiscais_itens', dmPrincipal.empresa_real);
ParamByName('pID_Nota').Value := ID_Nota;
ParamByName('pSerie').Value := FSerie;
ParamByName('pNota').Value := FNota;
ParamByName('pItemNota').Value := qrNotasItens.RecNo;
ParamByName('pEmpresa').Value := qrNotasItens['empresa_codigo'];
ParamByName('pID_XLS').Value := qrNotasItens['id'];
ParamByName('pProduto').Value := qrNotasItens['produto_codigo'];
ParamByName('pUsuariio').Value := dmPrincipal.usuario;
try
ExecSQL;
ve_proxima_nota(qrNotasXLS['empresa_codigo'], 'S');
except
end;
qrNotasItens.Next;
end;
{ ***** Fim ***** }
grava_notas_eletronica(ID_Nota, qrNotasXLS['empresa_codigo'], FSerie, FNota, dmPrincipal.SoData, 'A');
AtualizaTotalProdutos(ID_Nota);
AtualizaNotaImportada(qrNotasXLS.FieldByName('codigo').AsInteger);
end;
qrNotasXLS.Next;
end;
finally
qrTemp.Free;
qrNotasXLS.Refresh;
qrCabecalho.Refresh;
if bImportou then
ShowMessage('Notas geradas com sucesso.')
else
ShowMessage('Nenhuma nota selecionada para gerar.');
end;
end;
procedure TfrmImportarNFeXLS.ve_proxima_nota(AEmpresa: Integer;
AOperacao: string; AGrava: Boolean);
var
query: TZReadOnlyQuery;
begin
query := TZReadOnlyQuery.Create(nil);
try
try
with query do
begin
Connection := dmPrincipal.Database;
close;
sql.clear;
sql.add('lock tables series_nf write');
execsql;
close;
sql.clear;
sql.add('select serie,nota + 1 nota,modelo ');
sql.add('from series_nf');
sql.add('where tipo_operacao in("A",:pOperacao) and ativo="S" and empresa_codigo=' + IntToStr(AEmpresa));
ParamByName('pOperacao').Value := AOperacao;
open;
if not IsEmpty then
begin
if not AGrava then
begin
FSerie := fieldbyname('serie').AsInteger;
FNota := fieldbyname('nota').AsInteger;
FModelo := fieldbyname('modelo').AsInteger;
end;
end
else
MessageBox(Handle, 'Séries de notas não cadastrados!', 'Erro', MB_ICONERROR);
if AGrava then
begin
close;
sql.clear;
sql.add('update series_nf');
sql.add('set nota=:pNota where tipo_operacao in("A",:pOperacao) and ativo="S" and empresa_codigo=:pEmpresa');
ParamByName('pNota').Value := FNota;
ParamByName('pEmpresa').AsInteger := AEmpresa;
ParamByName('pOperacao').AsString := AOperacao;
execsql;
close;
sql.clear;
sql.add('unlock tables');
ExecSQL;
end
else
begin
close;
sql.clear;
sql.add('unlock tables');
ExecSQL;
end;
end;
except
with query do
begin
close;
sql.clear;
sql.add('unlock tables');
ExecSQL;
end;
end;
finally
FreeAndNil(query);
end;
end;
function TfrmImportarNFeXLS.VeCodigoImportado(ACodigo: string; AItem, ATipo: Integer): Boolean;
var
qrTemp: TZReadOnlyQuery;
begin
Result := False;
qrTemp := TZReadOnlyQuery.Create(nil);
try
qrTemp.Connection := dmPrincipal.Database;
qrTemp.Close;
qrTemp.SQL.Clear;
qrTemp.SQL.Add('select count(*) from notas_fiscais_xls where codigo=:pCodigo and item=:pItem and tipo_importacao=:pTipo');
qrTemp.ParamByName('pCodigo').Value := ACodigo;
qrTemp.ParamByName('pItem').AsInteger := AItem;
qrTemp.ParamByName('pTipo').AsInteger := ATipo;
qrTemp.Open;
Result := qrTemp.Fields[0].AsInteger > 0;
finally
qrTemp.Free;
end;
end;
procedure TfrmImportarNFeXLS.qrNotasXLScnpjGetText(Sender: TField;
var Text: string; DisplayText: Boolean);
begin
if Length(Sender.AsString) > 11 then
Text := FormataCnpj(Sender.AsString)
else
Text := FormataCpf(Sender.AsString);
end;
procedure TfrmImportarNFeXLS.SpeedButton1Click(Sender: TObject);
begin
Close;
end;
procedure TfrmImportarNFeXLS.SpeedButton2Click(Sender: TObject);
var
TipoImportacao: Byte; //(0) - XLS (1) - Loja Virtual
begin
frmTipoImportacaoNotas := TfrmTipoImportacaoNotas.Create(nil);
try
frmTipoImportacaoNotas.ShowModal;
TipoImportacao := frmTipoImportacaoNotas.Tag;
finally
frmTipoImportacaoNotas.Release;
frmTipoImportacaoNotas := nil;
end;
if TipoImportacao = -1 then
Exit;
case TipoImportacao of
0: ImportarNFe;
1: ImportarNFeWB;
end;
btnAtualizar.Click;
UltimoCodigo;
end;
procedure TfrmImportarNFeXLS.SpeedButton3Click(Sender: TObject);
begin
CadastraCliente;
GerarNFe;
AtualizaContagem;
end;
procedure TfrmImportarNFeXLS.VeNotas;
begin
try
with qrNotasXLS do
begin
Close;
SQL.Clear;
SQL.Add('select 1/1 marca,');
SQL.Add(' id,empresa_codigo,codigo,item,data,data_importacao,cliente_codigo,cliente_filial,nome,cnpj,');
SQL.Add(' email,telefone,logradouro,numero,complemento,bairro,cidade,cep,uf,cob_logradouro,cob_numero,');
SQL.Add(' cob_complemento,cob_bairro,cob_cidade,cob_cep,cob_uf,meio_pagamento,forma_pagamento,parcelas,');
SQL.Add(' vencimento,data_fatura,grupo,produto,sum(quantidade)quantidade, sum(total)/sum(quantidade)unitario,');
SQL.Add(' sum(total)total,envio,cliente, tipo_importacao');
SQL.Add('from notas_fiscais_xls');
SQL.Add('where isnull(data_importacao)');
if edCNPJ.Text <> EmptyStr then
begin
SQL.Add('and cnpj=:pCNPJ');
ParamByName('pCNPJ').AsString := SoNumeros(edCNPJ.Text);
end;
if edtNome.Text <> EmptyStr then
begin
SQL.Add('and nome like :pNome');
ParamByName('pNome').AsString := '%' + edtNome.Text + '%';
end;
if cbMeio.ItemIndex > 0 then
begin
if cbTipo.ItemIndex = 0 then
SQL.Add('and meio_pagamento=:pPagamento')
else
SQL.Add('and meio_pagamento<>:pPagamento');
ParamByName('pPagamento').AsInteger := cbMeio.ItemIndex;
end;
case cbEnvio.ItemIndex of
0: ; //Não faz nada
1: SQL.Add('and envio=1');
2: SQL.Add('and envio=2');
end;
case cbCliente.ItemIndex of
0: ; //Não faz nada
1: SQL.Add('and cliente=1');
2: SQL.Add('and cliente=2');
end;
if cbProduto.ItemIndex <> -1 then
begin
SQL.add('and produto=:pProduto');
ParamByName('pProduto').AsInteger := cbProduto.Properties.Items.Items[cbProduto.ItemIndex].Value;
end;
if cbImportacao.ItemIndex > 0 then
begin
SQL.Add('and tipo_importacao=:pTipo');
ParamByName('pTipo').AsInteger := cbImportacao.ItemIndex;
end;
SQL.Add('group by codigo');
Open;
end;
AtualizaContagem;
finally
//
end;
end;
procedure TfrmImportarNFeXLS.SpeedButton4Click(Sender: TObject);
begin
VeNotas;
end;
procedure TfrmImportarNFeXLS.SpeedButton5Click(Sender: TObject);
begin
if frmClientes <> nil then
Exit;
frmClientes := TfrmClientes.Create(nil);
try
frmClientes.ShowModal;
finally
frmClientes.Release;
frmClientes := nil;
end;
end;
procedure TfrmImportarNFeXLS.cbMeioClick(Sender: TObject);
begin
SpeedButton4.Click;
end;
procedure TfrmImportarNFeXLS.FormShow(Sender: TObject);
begin
if edtNome.CanFocus then
edtNome.SetFocus;
cbTipo.ItemIndex := 0;
cbMeio.ItemIndex := 0;
cbEnvio.ItemIndex := 0;
cbCliente.ItemIndex := 0;
UltimoCodigo;
EnableEdit(dsBrowse);
PageControl1.ActivePage := tbsGrid;
end;
procedure TfrmImportarNFeXLS.FormDestroy(Sender: TObject);
begin
qrCabecalho.Close;
qrUltimo.Close;
qrInsertXLs.Close;
qrNotasXLS.Close;
qrNotasItens.Close;
end;
procedure TfrmImportarNFeXLS.UltimoCodigo;
begin
qrUltimo.Close;
qrUltimo.SQL.Clear;
qrUltimo.SQL.Add('select max(codigo) as maior_codigo,');
qrUltimo.SQL.Add('(select codigo from notas_fiscais_xls order by id desc limit 1) as ultimo');
qrUltimo.SQL.Add(' from notas_fiscais_xls');
qrUltimo.Open;
Label6.Caption := 'Maior: ' + qrUltimo.FieldByName('maior_codigo').AsString;
Label5.Caption := 'Último: ' + qrUltimo.FieldByName('ultimo').AsString;
end;
procedure TfrmImportarNFeXLS.qrNotasXLSenvioGetText(Sender: TField;
var Text: string; DisplayText: Boolean);
begin
if Sender.AsInteger = 1 then
Text := 'e-Sedex'
else if Sender.AsInteger = 2 then
Text := 'PAC';
end;
procedure TfrmImportarNFeXLS.qrNotasXLSclienteGetText(Sender: TField;
var Text: string; DisplayText: Boolean);
begin
if Sender.AsInteger = 1 then
Text := 'Inadimplente'
else if Sender.AsInteger = 2 then
Text := 'Sem Restrição';
end;
procedure TfrmImportarNFeXLS.btnAtualizarClick(Sender: TObject);
begin
qrNotasXLS.Refresh;
qrCabecalho.Refresh;
VeNotas;
AtualizaContagem;
end;
procedure TfrmImportarNFeXLS.SpeedButton7Click(Sender: TObject);
begin
if frmNotaFiscal_Eletronica <> nil then
Exit;
frmNotaFiscal_Eletronica := TfrmNotaFiscal_Eletronica.Create(nil);
try
frmNotaFiscal_Eletronica.ShowModal
finally
frmNotaFiscal_Eletronica.Release;
frmNotaFiscal_Eletronica := nil;
end;
end;
procedure TfrmImportarNFeXLS.SpeedButton9Click(Sender: TObject);
begin
if frmConsultarNFeXLS <> nil then
Exit;
frmConsultarNFeXLS := TfrmConsultarNFeXLS.Create(nil);
try
frmConsultarNFeXLS.ShowModal
finally
frmConsultarNFeXLS.Release;
frmConsultarNFeXLS := nil;
end;
end;
procedure TfrmImportarNFeXLS.AtualizaContagem;
begin
if qrNotasXLS.RecordCount > 1 then
NotasFiltradas.Caption := inttostr(qrNotasXLS.RecordCount) + ' Registros Filtrados'
else
NotasFiltradas.Caption := inttostr(qrNotasXLS.RecordCount) + ' Registro Filtrado';
end;
procedure TfrmImportarNFeXLS.ImportarNFeWB;
var
XML: TStringStream;
procedure InsereNotas;
var
Cliente, Filial: Integer;
Codigo: string;
begin
with qrInsertXLs do
begin
ParamByName('empresa_codigo').AsInteger := dmPrincipal.empresa_login;
Codigo := cdsLojaVirtual.FieldByName('pedido').AsString;
ParamByName('codigo').AsString := Codigo;
ParamByName('item').AsInteger := cdsLojaVirtual.FieldByName('item').AsInteger;
ParamByName('tipo_importacao').AsInteger := 2;
ParamByName('data').AsDateTime := cdsLojaVirtual.FieldByName('data').AsDateTime;
ParamByName('nome').AsString := cdsLojaVirtual.FieldByName('cliente').AsString;
if not VeCliente(cdsLojaVirtual.FieldByName('cpf').AsString, Cliente, Filial) then
begin
Cliente := -1;
Filial := -1;
end;
ParamByName('cliente_codigo').AsInteger := Cliente;
ParamByName('cliente_filial').AsInteger := Filial;
ParamByName('cnpj').AsString := cdsLojaVirtual.FieldByName('cpf').AsString;
ParamByName('telefone').AsString := cdsLojaVirtual.FieldByName('telefone').AsString;
ParamByName('logradouro').AsString := cdsLojaVirtual.FieldByName('endereco').AsString;
ParamByName('numero').AsString := 'SN';
ParamByName('complemento').Clear;
ParamByName('bairro').AsString := cdsLojaVirtual.FieldByName('bairro').AsString;
ParamByName('cidade').AsString := cdsLojaVirtual.FieldByName('cidade').AsString;
ParamByName('cep').AsString := SoNumeros(cdsLojaVirtual.FieldByName('cep').AsString);
ParamByName('uf').AsString := cdsLojaVirtual.FieldByName('uf').AsString;
ParamByName('cob_logradouro').AsString := cdsLojaVirtual.FieldByName('endereco').AsString;
ParamByName('cob_numero').AsString := 'SN';
ParamByName('cob_complemento').Clear;
ParamByName('cob_bairro').AsString := cdsLojaVirtual.FieldByName('bairro').AsString;
ParamByName('cob_cidade').AsString := cdsLojaVirtual.FieldByName('cidade').AsString;
ParamByName('cob_cep').AsString := SoNumeros(cdsLojaVirtual.FieldByName('cep').AsString);
ParamByName('cob_uf').AsString := cdsLojaVirtual.FieldByName('uf').AsString;
ParamByName('meio_pagamento').AsInteger := 10; //Pegar do parametro loja virtual
ParamByName('forma_pagamento').AsString := cdsLojaVirtual.FieldByName('pagamento').AsString;
ParamByName('parcelas').AsInteger := 1;
ParamByName('vencimento').AsDate := dmPrincipal.SoData;
ParamByName('produto').AsString := cdsLojaVirtual.FieldByName('produto_sistema').AsString;
ParamByName('quantidade').AsFloat := cdsLojaVirtual.FieldByName('quantidade').AsFloat;
ParamByName('unitario').AsCurrency := cdsLojaVirtual.FieldByName('valor_unitario').AsCurrency;
ParamByName('total').AsCurrency := cdsLojaVirtual.FieldByName('valor_total').AsCurrency;
ParamByName('email').AsString := cdsLojaVirtual.FieldByName('email').AsString;
//Coluna para e-Sedex (1) ou PAC (2)
ParamByName('envio').AsInteger := StrToIntDef(cdsLojaVirtual.FieldByName('entrega_codigo').AsString, 0);
//Coluna para Inadimplente (1) ou Sem Pendências (2)
ParamByName('cliente').AsInteger := 2;
try
if ParamByName('empresa_codigo').AsInteger > 0 then
if not VeCodigoImportado(Codigo, cdsLojaVirtual.FieldByName('item').AsInteger, 2) then
ExecSQL;
except
on E: Exception do
ShowMessage(E.Message);
end;
end;
end;
begin
if VeContaNotas = 0 then
begin
MessageBox(handle, 'Não existem notas a serem geradas na loja virtual!', 'Aviso', mb_ok + mb_IconError);
Exit;
end;
try
wait('Aguardando resposta da loja virtual...', 1);
xmlLojaVirtual.FileName := GetLinkLoja;
xmlLojaVirtual.Active := True;
XML := TStringStream.Create(xmlLojaVirtual.XML.Text);
cdsLojaVirtual.LoadFromStream(XML);
cdsLojaVirtual.First;
while not cdsLojaVirtual.Eof do
begin
InsereNotas;
cdsLojaVirtual.Next;
end;
finally
FreeAndNil(XML);
xmlLojaVirtual.Active := False;
wait;
end;
end;
procedure TfrmImportarNFeXLS.AtualizaNotaImportada(ACodigo: Integer);
begin
with TZReadOnlyQuery.Create(nil) do
begin
Connection := dmPrincipal.Database;
try
SQL.Text := 'update notas_fiscais_xls set data_importacao = :pData where codigo= :pCodigo';
ParamByName('pData').AsDateTime := dmPrincipal.DataHora;
ParamByName('pCodigo').AsInteger := ACodigo;
ExecSQL;
finally
Close;
Free;
end;
end;
end;
function TfrmImportarNFeXLS.VeContaNotas: Integer;
var
IdHTTP1: TIdHTTP;
TotalNotas: string;
procedure doConfiguraHTTP;
begin
with IdHTTP1 do
begin
Request.Accept := 'text/html, */*';
Request.UserAgent := 'Mozilla/3.0 (compatible; IndyLibrary)';
Request.ContentType := 'application/x-www-form-urlencoded';
HandleRedirects := True;
end;
end;
begin
IdHTTP1 := TIdHTTP.Create(nil);
try
doConfiguraHTTP;
TotalNotas := IdHTTP1.Get(GetLinkLoja(True));
Result := StrToIntDef(TotalNotas, 0);
finally
FreeAndNil(IdHTTP1);
end;
end;
function TfrmImportarNFeXLS.GetLinkLoja(bConta: Boolean): string;
var
SHA1Digest: TSHA1Digest;
Senha, Formato: string;
begin
//Converte senha para SHA1
StringHashSHA1(SHA1Digest, FormatDateTime('YYYYMMDD', dmPrincipal.SoData));
Senha := AnsiLowerCase(BufferToHex(SHA1Digest, SizeOf(SHA1Digest)));
//Converte formato para SHA1
//StringHashSHA1(SHA1Digest, '09355599000150');
StringHashSHA1(SHA1Digest, SoNumeros(dmPrincipal.EmpresaCnpj));
Formato := AnsiLowerCase(BufferToHex(SHA1Digest, SizeOf(SHA1Digest)));
Result := 'http://www.rwa.com.br/sistema/soysano/webservice/?senha=' + Senha + '&formato=' + Formato;
//Result := 'http://www.soysano.br/webservice/?senha=' + Senha + '&formato=' + Formato;
if bConta then
Result := Result + '&tipo=1';
end;
procedure TfrmImportarNFeXLS.AtualizaTotalProdutos(AID_Nota: Integer);
begin
with TZReadOnlyQuery.Create(nil) do
begin
Connection := dmPrincipal.Database;
try
SQL.Clear;
SQL.Add('update notas_fiscais');
SQL.Add(' set valor_produtos = (select sum(valor_total) from notas_fiscais_itens where id_nota=notas_fiscais.id),');
SQL.Add(' valor_nota = (select sum(if(soma_item_nf="S",valor_total,0)) from notas_fiscais_itens where id_nota=notas_fiscais.id)');
SQL.Add('where id=:pID');
ParamByName('pID').AsInteger := AID_Nota;
ExecSQL;
finally
Close;
Free;
end;
end;
end;
procedure TfrmImportarNFeXLS.qrNotasXLStipo_importacaoGetText(
Sender: TField; var Text: string; DisplayText: Boolean);
begin
if Sender.AsString = 'XLS' then
Text := 'Planilha de Excel'
else if Sender.AsString = 'Loja' then
Text := 'Loja Virtual'
else if Sender.AsString = 'Manual' then
Text := 'Pelo Sistema';
end;
procedure TfrmImportarNFeXLS.btExcluirClick(Sender: TObject);
begin
if dsNotasXLS.DataSet.IsEmpty then
Exit;
if MessageBox(Handle, 'Confirma Exclusão ?', 'Cuidado !!!', MB_YESNO +
MB_ICONQUESTION + MB_DEFBUTTON2) = IDYES then
begin
dsNotasXLS.DataSet.Delete;
dsNotasXLS.DataSet.Refresh;
end;
AtualizaContagem;
end;
procedure TfrmImportarNFeXLS.EnableEdit(OldState: TDataSetState);
begin
// verificar o Status do registro atual
bEdit := dsFicha.State in [dsEdit, dsInsert];
//Desabilita campo de valores na Visualização
edQuantidade.Enabled := dsFicha.State in [dsInsert, dsEdit];
edUnitario.Enabled := dsFicha.State in [dsInsert, dsEdit];
edTotal.Enabled := dsFicha.State in [dsInsert, dsEdit];
{Trocar página do PageControl}
if bEdit then
begin
PageControl1.ActivePage := tbsFicha;
btGridFicha.Caption := 'Tabela' + #13#10 + 'F5';
Repaint;
end
else
begin
if (OldState in [dsEdit, dsInsert]) and ReturnToGridAfterEdit then
begin
PageControl1.ActivePage := tbsGrid;
btGridFicha.Caption := 'Ficha' + #13#10 + 'F5';
ActiveControl := JvDBGrid1;
end;
end;
{Desabilitar/habilitar as ações}
//btIncluir.Enabled := (not bEdit) and ((not dsNotasXLS.DataSet.Eof) or (not dsNotasXLS.DataSet.Bof));
//btAlterar.Enabled := (not bEdit) and ((not dsNotasXLS.DataSet.Eof) or (not dsNotasXLS.DataSet.Bof));
//btExcluir.Enabled := (not bEdit) and ((not dsNotasXLS.DataSet.Eof) or (not dsNotasXLS.DataSet.Bof));
//btGridFicha.Enabled := (not bEdit) and ((not dsNotasXLS.DataSet.Eof) or (not dsNotasXLS.DataSet.Bof));
btCancelar.Enabled := (bEdit) and ((not dsNotasXLS.DataSet.Eof) or (not dsNotasXLS.DataSet.Bof));
btGravar.Enabled := (bEdit) and ((not dsNotasXLS.DataSet.Eof) or (not dsNotasXLS.DataSet.Bof));
case dsFicha.State of
dsInsert:
begin
funcao := 'incluir';
StatusBar1.Panels[0].Text := 'Incluindo';
end;
dsEdit:
begin
funcao := 'alterar';
StatusBar1.Panels[0].Text := 'Alterando';
end;
else
begin
funcao := '';
StatusBar1.Panels[0].Text := 'Navegando';
end;
end;
end;
procedure TfrmImportarNFeXLS.btIncluirClick(Sender: TObject);
begin
dsFicha.DataSet.Append;
EnableEdit(dsBrowse);
//Padrões para Inserção
ckEndCob.Checked := False;
qrFichatipo_importacao.AsInteger := 3;
qrFichacliente_codigo.AsInteger := 2;
qrFichameio_pagamento.AsInteger := 1;
qrFichaforma_pagamento.AsString := 'CARTAO DE CREDITO';
qrFichaenvio.AsInteger := 1;
qrFichaproduto.AsInteger := 5;
qrFichacliente_codigo.AsInteger := -1;
qrFichacliente_filial.AsInteger := -1;
qrFichaempresa_codigo.AsInteger := dmPrincipal.empresa_login;
qrFichadata_importacao.Clear;
qrFichaparcelas.AsInteger := 1;
btAlterar.Enabled := False;
btExcluir.Enabled := False;
if edCodigo.CanFocus then
edCodigo.SetFocus;
end;
procedure TfrmImportarNFeXLS.btAlterarClick(Sender: TObject);
begin
if dsFicha.DataSet.IsEmpty then
Exit;
dsFicha.DataSet.Edit;
EnableEdit(dsBrowse);
end;
procedure TfrmImportarNFeXLS.btGridFichaClick(Sender: TObject);
begin
if PageControl1.ActivePage = tbsGrid then
begin
PageControl1.ActivePage := tbsFicha;
btGridFicha.Caption := 'Tabela' + #13#10 + 'F5';
end
else
begin
PageControl1.ActivePage := tbsGrid;
btGridFicha.Caption := 'Ficha' + #13#10 + 'F5'
end;
end;
procedure TfrmImportarNFeXLS.btCancelarClick(Sender: TObject);
var
OldState: TDatasetState;
ID: Variant;
begin
OldState := dsFicha.State;
if dsFicha.State in [dsinsert, dsedit] then
dsFicha.DataSet.Cancel;
EnableEdit(OldState);
btGridFicha.Click;
HabilitaBotoes;
end;
procedure TfrmImportarNFeXLS.btGravarClick(Sender: TObject);
var
OldState: TDatasetState;
ID: Variant;
begin
ActiveControl := nil;
qrFichacnpj.AsString := SoNumeros(qrFichacnpj.AsString);
qrFichacep.AsString := SoNumeros(qrFichacep.AsString);
qrFichacob_cep.AsString := SoNumeros(qrFichacob_cep.AsString);
qrFichatipo_importacao.AsInteger := 3;
//Testa se o código existe
if dsFicha.DataSet.State = dsInsert then
begin
with TZReadOnlyQuery.Create(nil) do
begin
Connection := dmPrincipal.Database;
try
Close;
SQL.Clear;
SQL.Add('select count(*) from notas_fiscais_xls where codigo=:pCodigo');
ParamByName('pCodigo').AsString := qrFichacodigo.AsString;
Open;
if Fields[0].AsInteger > 0 then
begin
MessageBox(handle, 'Código já utilizado em outra venda, utilize outro código!', 'Erro!', mb_ok + mb_IconError);
if edCodigo.CanFocus then
edCodigo.SetFocus;
Exit;
end;
finally
Close;
Free;
end;
end;
end;
//Testa se o código é nulo
if StringEmBranco(qrFichacodigo.AsString) then
begin
MessageBox(handle, 'Código da venda não pode ser nula!', 'Campo Obrigatório', mb_ok + mb_IconError);
if edCodigo.CanFocus then
edCodigo.SetFocus;
Exit;
end;
//Testa se o Nome é nulo
if StringEmBranco(qrFichanome.AsString) then
begin
MessageBox(handle, 'O Nome do Cliente não pode ser nulo!', 'Campo Obrigatório', mb_ok + mb_IconError);
if edCliente.CanFocus then
edCliente.SetFocus;
Exit;
end;
//Testa se o CEP é nulo
if StringEmBranco(qrFichacep.AsString) then
begin
MessageBox(handle, 'O CEP não pode ser nulo!', 'Campo Obrigatório', mb_ok + mb_IconError);
if edCepEntrega.CanFocus then
edCepEntrega.SetFocus;
Exit;
end;
//Testa se o logradouro é nulo
if StringEmBranco(qrFichalogradouro.AsString) then
begin
MessageBox(handle, 'O Endereço não pode ser nulo!', 'Campo Obrigatório', mb_ok + mb_IconError);
if edLogradouro.CanFocus then
edLogradouro.SetFocus;
Exit;
end;
//Testa se o número é nulo
if StringEmBranco(qrFichanumero.AsString) then
begin
MessageBox(handle, 'O número do endereço não pode ser nulo!', 'Campo Obrigatório', mb_ok + mb_IconError);
if edNumero.CanFocus then
edNumero.SetFocus;
Exit;
end;
//Testa se o bairro é nulo
if StringEmBranco(qrFichabairro.AsString) then
begin
MessageBox(handle, 'O bairro do endereço não pode ser nulo!', 'Campo Obrigatório', mb_ok + mb_IconError);
if edBairro.CanFocus then
edBairro.SetFocus;
Exit;
end;
//Testa se a cidade é nula
if StringEmBranco(qrFichacidade.AsString) then
begin
MessageBox(handle, 'A cidade do endereço não pode ser nulo!', 'Campo Obrigatório', mb_ok + mb_IconError);
if edCidade.CanFocus then
edCidade.SetFocus;
Exit;
end;
//Testa se o Estado é nulo
if StringEmBranco(qrFichauf.AsString) then
begin
MessageBox(handle, 'O estado do endereço não pode ser nulo!', 'Campo Obrigatório', mb_ok + mb_IconError);
if edUF.CanFocus then
edUF.SetFocus;
Exit;
end;
//Testa se a data é nula
if StringEmBranco(qrFichadata.AsString) then
begin
MessageBox(handle, 'A data não pode ser nula!', 'Campo Obrigatório', mb_ok + mb_IconError);
if edData.CanFocus then
edData.SetFocus;
Exit;
end;
//Testa se o vencimento é nulo
if StringEmBranco(qrFichavencimento.AsString) then
begin
MessageBox(handle, 'O vencimento não pode ser nulo!', 'Campo Obrigatório', mb_ok + mb_IconError);
if edVencimento.CanFocus then
edVencimento.SetFocus;
Exit;
end;
//Testa se o vencimento é menor que a emissão
if (Trunc(qrFichavencimento.AsDateTime) < Trunc(qrFichadata.AsDateTime)) then
begin
MessageBox(handle, 'A data de vencimento não pode ser menor que a data de emissão', 'Erro', mb_ok + mb_IconError);
if edVencimento.CanFocus then
edVencimento.SetFocus;
Exit;
end;
//Testa o valor total
if StringEmBranco(qrFichatotal.AsString) then
begin
MessageBox(handle, 'O valor precisa ser maior que 0!', 'Erro', mb_ok + mb_IconError);
if edTotal.CanFocus then
edTotal.SetFocus;
Exit;
end;
//Testa a quantidade
if StringEmBranco(qrFichaquantidade.AsString) then
begin
MessageBox(handle, 'A quantidade precisa ser maior que 0!', 'Erro', mb_ok + mb_IconError);
if edQuantidade.CanFocus then
edQuantidade.SetFocus;
Exit;
end;
//Testa o valor unitário
if StringEmBranco(qrFichaunitario.AsString) then
begin
MessageBox(handle, 'O valor unitário precisa ser maior que 0!', 'Erro', mb_ok + mb_IconError);
if edUnitario.CanFocus then
edUnitario.SetFocus;
Exit;
end;
if qrFicha.State = dsInsert then
begin
qrFicha['user_inclusao'] := dmPrincipal.usuario;
qrFicha['data_inclusao'] := dmPrincipal.DataHora;
end
else
begin
qrFicha['user_alteracao'] := dmPrincipal.usuario;
qrFicha['data_alteracao'] := dmPrincipal.DataHora;
end;
ID := qrFichacodigo.AsVariant;
qrNotasXLS.Locate('id', ID, []);
OldState := dsFicha.State;
if dsFicha.State in [dsinsert, dsedit] then
dsFicha.DataSet.Post;
EnableEdit(OldState);
btnAtualizar.Click;
btGridFicha.Click;
UltimoCodigo;
HabilitaBotoes;
end;
procedure TfrmImportarNFeXLS.JvSpeedButton1Click(Sender: TObject);
begin
aguarde('Consultando CEP na base dos Correios', 1);
atualiza_cep(edCepEntrega.Text, tcEntrega);
aguarde();
end;
procedure TfrmImportarNFeXLS.atualiza_cep(ACEP: string;
AEntrega: TTipoCadastro);
var
parametros: TStringList;
begin
if dsFicha.DataSet.State in [dsEdit, dsInsert] then
begin
try
parametros := TStringList.Create;
if ve_cep(ACEP, parametros) then
begin
case AEntrega of
tcEntrega:
begin
qrFicha['logradouro'] := AnsiUpperCase(CleanText(parametros.Values['logradouro']));
qrFicha['bairro'] := AnsiUpperCase(CleanText(parametros.Values['bairro']));
qrFicha['cidade'] := AnsiUpperCase(CleanText(parametros.Values['cidade']));
qrFicha['uf'] := AnsiUpperCase(CleanText(parametros.Values['uf']));
//qrFicha['codigo_cidade'] := parametros.Values['ibge'];
end;
tcCobranca:
begin
qrFicha['cob_logradouro'] := AnsiUpperCase(CleanText(parametros.Values['logradouro']));
qrFicha['cob_bairro'] := AnsiUpperCase(CleanText(parametros.Values['bairro']));
qrFicha['cob_cidade'] := AnsiUpperCase(CleanText(parametros.Values['cidade']));
qrFicha['cob_uf'] := AnsiUpperCase(CleanText(parametros.Values['uf']));
//qrFicha['cob_codigo_cidade'] := parametros.Values['ibge'];
end;
end;
end
else
MessageBox(Handle, 'CEP não encontrado!', 'Erro', MB_ICONERROR);
finally
FreeAndNil(parametros);
end;
end;
end;
procedure TfrmImportarNFeXLS.JvSpeedButton2Click(Sender: TObject);
begin
aguarde('Consultando CEP na base dos Correios', 1);
atualiza_cep(edCepEntrega.Text, tcCobranca);
aguarde();
end;
procedure TfrmImportarNFeXLS.edQuantidadeExit(Sender: TObject);
begin
if dsFicha.State in [dsInsert, dsEdit] then
if qrFichaquantidade.AsFloat > 0 then
if qrFichaunitario.AsFloat > 0 then
qrFichatotal.AsFloat := qrFichaquantidade.AsFloat * qrFichaunitario.AsFloat;
end;
procedure TfrmImportarNFeXLS.ckEndCobClick(Sender: TObject);
begin
if dsFicha.State in [dsInsert, dsEdit] then
if ckEndCob.Checked then
begin
qrFicha['cob_cep'] := qrFicha['cep'];
qrFicha['cob_logradouro'] := qrFicha['logradouro'];
qrFicha['cob_bairro'] := qrFicha['bairro'];
qrFicha['cob_cidade'] := qrFicha['cidade'];
qrFicha['cob_uf'] := qrFicha['uf'];
end;
end;
procedure TfrmImportarNFeXLS.edClienteButtonClick(Sender: TObject);
begin
if dsFicha.DataSet.State in [dsInsert, dsEdit] then
with TfrmConsulta_Padrao.Create(self) do
begin
with Query.SQL do
begin
Clear;
Add('select fantasia, nome, codigo, filial, email, telefone1,');
Add('cnpj, logradouro, numero, complemento, bairro, cep, cidade,');
Add('uf, meio_pagamento, forma_pagamento');
Add('from clientes_fornecedores');
Add('where fantasia like :pFantasia and ativo="S" and (tipo_cadastro="A" or tipo_cadastro="C")');
Add('order by 1');
end;
with DBGrid do
begin
Columns.Clear;
Columns.Add;
Columns[0].FieldName := 'fantasia';
Columns[0].Title.Caption := 'Nome Fantasia';
Columns[0].Width := 250;
Columns.Add;
Columns[1].FieldName := 'nome';
Columns[1].Title.Caption := 'Razão Social';
Columns[1].Width := 300;
end;
CampoLocate := 'fantasia';
Parametro := 'pFantasia';
ColunasGrid := -1;
ShowModal;
if Tag = 1 then
begin
qrFicha['nome'] := Query.Fields[1].Value;
qrFicha['cliente_codigo'] := Query.Fields[2].Value;
qrFicha['cliente_filial'] := Query.Fields[3].Value;
qrFicha['email'] := Query.Fields[4].Value;
qrFicha['telefone'] := Query.Fields[5].Value;
qrFicha['cnpj'] := Query.Fields[6].Value;
qrFicha['logradouro'] := Query.Fields[7].Value;
qrFicha['cob_logradouro'] := Query.Fields[7].Value;
qrFicha['numero'] := Query.Fields[8].Value;
qrFicha['cob_numero'] := Query.Fields[8].Value;
qrFicha['complemento'] := Query.Fields[9].Value;
qrFicha['cob_complemento'] := Query.Fields[9].Value;
qrFicha['bairro'] := Query.Fields[10].Value;
qrFicha['cob_bairro'] := Query.Fields[10].Value;
qrFicha['cep'] := Query.Fields[11].Value;
qrFicha['cob_cep'] := Query.Fields[11].Value;
qrFicha['cidade'] := Query.Fields[12].Value;
qrFicha['cob_cidade'] := Query.Fields[12].Value;
qrFicha['uf'] := Query.Fields[13].Value;
qrFicha['cob_uf'] := Query.Fields[13].Value;
//edCliente.Text := Query.Fields[0].Value;
end;
Free;
end;
qrCabecalho.Refresh;
if edEmail.CanFocus then
edEmail.SetFocus;
end;
procedure TfrmImportarNFeXLS.edCodFilialExit(Sender: TObject);
begin
if (edCodCli.DataSource.State in [dsEdit, dsInsert]) and (edCodCli.Text = '') then
edCliente.Button.Click;
end;
procedure TfrmImportarNFeXLS.SpeedButton6Click(Sender: TObject);
begin
if frmConsultarNFeXLS <> nil then
Exit;
frmConsultarNFeXLS := TfrmConsultarNFeXLS.Create(nil);
try
frmConsultarNFeXLS.ShowModal
finally
frmConsultarNFeXLS.Release;
frmConsultarNFeXLS := nil;
end;
end;
procedure TfrmImportarNFeXLS.dsFichaDataChange(Sender: TObject;
Field: TField);
begin
(***** Barra de Status *****)
if StringEmBranco(qrFichauser_inclusao.AsString) then
StatusBar1.Panels[1].Text := ''
else
StatusBar1.Panels[1].Text := 'Inclusão: ' + qrFichauser_inclusao.AsString + ' - ' + qrFichadata_inclusao.AsString;
if StringEmBranco(qrFichauser_alteracao.AsString) then
StatusBar1.Panels[2].Text := ''
else
StatusBar1.Panels[2].Text := 'Alteração: ' + qrFichauser_alteracao.AsString + ' - ' + qrFichadata_alteracao.AsString; ;
end;
procedure TfrmImportarNFeXLS.SpeedButton8Click(Sender: TObject);
begin
if frmProdutosKits <> nil then
Exit;
frmProdutosKits := TfrmProdutosKits.Create(nil);
try
frmProdutosKits.ShowModal;
finally
frmProdutosKits.Release;
frmProdutosKits := nil;
end
end;
procedure TfrmImportarNFeXLS.HabilitaBotoes;
begin
btAlterar.Enabled := True;
btExcluir.Enabled := True;
btIncluir.Enabled := True;
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/NPL/NPL-1_1Final.html
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
the specific language governing rights and limitations under the License.
The Original Code is: mwGenericLex.pas, released April, 2001.
The Initial Developer of the Original Code is Martin Waldenburg
(Martin.Waldenburg@T-Online.de).
Portions created by Martin Waldenburg are Copyright (C) 2001 Martin Waldenburg.
All Rights Reserved.
Contributor(s): _____________________________________.
Last Modified: mm/dd/yyyy
Current Version: 0.9
Notes: This program is a fast generic scriptable lexical analyser.
Modification history:
Known Issues:
-----------------------------------------------------------------------------}
{$A+,B-,C-,D-,E-,I+,J-,O+,Q-,R-,S-,V-}
unit mwGenericLex;
{$IFDEF FPC}
{$MODE DELPHI}
{$ENDIF}
interface
uses
Classes;
const
piAtEnd = High(Word);
piZero = High(Word) - 1;
piUnknown = High(Word) - 2;
piSymbol = 0;
piSpace = 1;
piLineEnd = 2;
piInnerLineEnd = 3;
piIdent = 4;
piKeyWord = 5;
piString = 6;
piComment = 7;
piNumber = 8;
piAssembler = 9;
piBadString = 10;
piDirective = 11;
piChar = 12;
piBadChar = 13;
type
TAny = class;
TmwGenLex = class;
TmwLexInitProc = procedure(Lex: TmwGenLex);
TmwLexInitMethod = procedure(Lex: TmwGenLex) of object;
TmwCharClass = set of Char;
PmwChars = ^TmwChars;
TmwChars = record
Chars: TmwCharClass;
end;
TAnyKind = (
pkAny,
pkChar,
pkCharClass,
pkInnerLineEnd,
pkKey,
pkLineEnd,
pkTillChars,
pkTillKey
);
TAnyStatus = (
psMultiLine,
psNegative,
psProcessingNeeded,
psRegress
);
TAnyStorage = packed record
Count: Byte;
Kind: TAnyKind;
Status: set of TAnyStatus;
Min: Byte;
Id: Word;
ExId: Word;
Max: Word;
end;
PmwOptionsList = ^TmwOptionsList;
TmwOptionsList = array[0..0] of TAny;
TAny = class(TPersistent)
private
fOptionsList: PmwOptionsList;
fToRegress: TAny;
FKey: string;
FFollow: TAny;
function GetNodes(Index: Byte): TAny;
function GetMultiLine: Boolean;
function GetNegative: Boolean;
function GetProcessingNeeded: Boolean;
procedure SetMultiLine(const Value: Boolean);
procedure SetNegative(const Value: Boolean);
procedure SetProcessingNeeded(const Value: Boolean);
procedure SetKey(const Value: string);
procedure SetCharClass(const Value: TmwCharClass);
function GetCharClass: TmwCharClass;
function GetRegress: Boolean;
procedure SetRegress(const Value: Boolean);
protected
Storage: TAnyStorage;
ToRestore: TAny;
public
constructor Create(AParent: TAny); virtual;
destructor Destroy; override;
function AddOption(const Value: TAny): Integer;
function IndexOf(const Any: TAny): Integer;
property CharClass: TmwCharClass read GetCharClass write SetCharClass;
property Count: Byte read Storage.Count;
property Options[Index: Byte]: TAny read GetNodes; default;
property ToRegress: TAny read fToRegress write FToRegress;
published
property ExId: Word read Storage.ExId write Storage.ExId;
property Follow: TAny read FFollow write FFollow;
property Id: Word read Storage.Id write Storage.Id;
property Max: Word read Storage.Max write Storage.Max;
property Min: Byte read Storage.Min write Storage.Min;
property Key: string read FKey write SetKey;
property Kind: TAnyKind read Storage.Kind write Storage.Kind;
property MultiLine: Boolean read GetMultiLine write SetMultiLine;
property Negative: Boolean read GetNegative write SetNegative;
property ProcessingNeeded: Boolean read GetProcessingNeeded write SetProcessingNeeded;
property Regress: Boolean read GetRegress write SetRegress;
end;
TLineEnd = class(TAny)
public
constructor Create(AParent: TAny); override;
end;
TAlpha = class(TAny)
public
constructor Create(AParent: TAny); override;
end;
TAlphaNumeric = class(TAny)
public
constructor Create(AParent: TAny); override;
end;
(*
TCharAlpha = class(TAny)
public
constructor Create(AParent: TAny); override;
end;
TCharAlphaNumeric = class(TAny)
public
constructor Create(AParent: TAny); override;
end;
TCharLower = class(TAny)
public
constructor Create(AParent: TAny); override;
end;
TCharUpper = class(TAny)
public
constructor Create(AParent: TAny); override;
end;
*)
TIdentifier = class(TAlpha)
public
constructor Create(AParent: TAny); override;
end;
TCRLF = class(TAny)
public
constructor Create(AParent: TAny); override;
end;
TLF = class(TAny)
public
constructor Create(AParent: TAny); override;
end;
TNotZero = class(TAny)
public
constructor Create(AParent: TAny); override;
end;
TNumeric = class(TAny)
public
constructor Create(AParent: TAny); override;
end;
TTill = class(TAny)
public
constructor Create(AParent: TAny); override;
end;
TTillChars = class(TAny)
public
constructor Create(AParent: TAny); override;
end;
TTillLineEnd = class(TAny)
public
constructor Create(AParent: TAny); override;
end;
TZero = class(TAny)
public
constructor Create(AParent: TAny); override;
end;
TmwGenLex = class(TPersistent)
private
FChain: TList;
FCurrent: TAny;
FSensitive: Boolean;
FInitMethod: TmwLexInitMethod;
FInitProc: TmwLexInitProc;
FRange: TAny;
FOrigin: PChar;
FProcessingNeeded: Boolean;
function ApplyAny: Boolean;
function ApplyChar: Boolean;
function ApplyCharClass: Boolean;
function ApplyInnerLineEnd: Boolean;
function ApplyKey: Boolean;
function ApplyLineEnd: Boolean;
function ApplyTillChars: Boolean;
function ApplyTillKey: Boolean;
function GetToken: string;
procedure SetInitMethod(const Value: TmwLexInitMethod);
procedure SetInitProc(const Value: TmwLexInitProc);
procedure SetInput(const Value: string);
procedure SetOrigin(const Value: PChar);
function GetRunPos: Integer;
procedure SetRunPos(const Value: Integer);
function GetEndPos: Integer;
procedure SetEndPos(const Value: Integer);
function SubNext: Boolean;
function GetLinePos: Integer;
protected
fLineCount : Longint;
FExId: Word;
FId: Word;
Run: PChar;
Start: PChar;
TheEnd: PChar;
InnerLineEnd: TAny;
MainSelector: array[#0..#255] of TAny;
Selector: array[Low(TAnyKind)..High(TAnyKind)] of function: Boolean of object;
procedure AddToMainSelector(Pattern: TAny);
procedure Clear;
function Execute: Boolean;
procedure InitMainSelector;
procedure InitSelector;
property Current: TAny read FCurrent write FCurrent;
property Chain: TList read FChain write FChain;
public
constructor Create;
destructor Destroy; override;
procedure Add(Pattern: TAny);
function AtEnd: Boolean;
procedure Next;
procedure SetStartData(Ptr: Pointer; aLen: Integer);
property EndPos: Integer read GetEndPos write SetEndPos;
property Id: Word read FId;
property ExId: Word read FExId;
property Input: string write SetInput;
property Origin: PChar read FOrigin write SetOrigin;
property ProcessingNeeded: Boolean read FProcessingNeeded;
property Range: TAny read FRange write FRange;
property RunPos: Integer read GetRunPos write SetRunPos;
property LinePos : Integer read GetLinePos;
property Sensitive: Boolean read FSensitive write FSensitive;
property Token: string read GetToken;
property InitProc: TmwLexInitProc read FInitProc write SetInitProc;
property InitMethod: TmwLexInitMethod read FInitMethod write SetInitMethod;
end;
implementation
uses
SysUtils;
var
CompTable: array[#0..#255] of Char;
procedure InitTables;
var
I: Char;
begin
for I := #0 to #255 do
CompTable[I] := AnsiUpperCase(I)[1];
end;
{ TAny }
function TAny.AddOption(const Value: TAny): Integer;
begin
Result := -1;
if Assigned(Value) then
begin
Result := Storage.Count;
inc(Storage.Count);
ReallocMem(fOptionsList, Storage.Count * SizeOf(TAny));
fOptionsList^[Result] := Value;
end;
end;
constructor TAny.Create(AParent: TAny);
begin
inherited Create;
if Assigned(AParent) then AParent.Follow := Self;
end;
destructor TAny.Destroy;
var
I: Integer;
begin
if Assigned(Follow) then Follow.Free;
for I := 0 to Storage.Count - 1 do
fOptionsList^[I].Free;
ReallocMem(fOptionsList, 0);
inherited Destroy;
end;
function GetIt(const C): TmwCharClass;
begin
Result := TmwCharClass(C);
end;
function TAny.GetCharClass: TmwCharClass;
begin
Result := PmwChars(FKey).Chars;
end;
function TAny.GetMultiLine: Boolean;
begin
Result := psMultiLine in Storage.Status;
end;
function TAny.GetNegative: Boolean;
begin
Result := psNegative in Storage.Status;
end;
function TAny.GetNodes(Index: Byte): TAny;
begin
Result := nil;
if Index < Storage.Count then Result := fOptionsList^[Index];
end;
function TAny.GetProcessingNeeded: Boolean;
begin
Result := psProcessingNeeded in Storage.Status;
end;
function TAny.GetRegress: Boolean;
begin
Result := psRegress in Storage.Status;
end;
function TAny.IndexOf(const Any: TAny): Integer;
var
I: Integer;
begin
Result := -1;
for I := 0 to Count - 1 do
if FOptionsList[I] = Any then
begin
Result := I;
break;
end;
end;
procedure TAny.SetCharClass(const Value: TmwCharClass);
begin
SetLength(FKey, 32);
PmwChars(FKey).Chars := Value;
Storage.Kind := pkCharClass;
end;
procedure TAny.SetKey(const Value: string);
begin
FKey := Value;
case Storage.Kind of
pkTillChars: ;
else
if Length(Value) > 1 then
Storage.Kind := pkKey
else
if Length(Value) = 1 then
Storage.Kind := pkChar
else
Storage.Kind := pkAny;
end;
end;
procedure TAny.SetMultiLine(const Value: Boolean);
begin
case Value of
True: Include(Storage.Status, psMultiLine);
False: Exclude(Storage.Status, psMultiLine);
end;
end;
procedure TAny.SetNegative(const Value: Boolean);
begin
case Value of
True: Include(Storage.Status, psNegative);
False: Exclude(Storage.Status, psNegative);
end;
end;
procedure TAny.SetProcessingNeeded(const Value: Boolean);
begin
case Value of
True: Include(Storage.Status, psProcessingNeeded);
False: Exclude(Storage.Status, psProcessingNeeded);
end;
end;
procedure TAny.SetRegress(const Value: Boolean);
begin
case Value of
True: Include(Storage.Status, psRegress);
False: Exclude(Storage.Status, psRegress);
end;
end;
{ TLineEnd }
constructor TLineEnd.Create(AParent: TAny);
var
Pattern, Option: TAny;
begin
inherited Create(AParent);
Key := #13;
Max := 1;
Option := TAny.Create(nil);
Option.Key := #10;
Option.Min := 1;
AddOption(Option);
Pattern := TAny.Create(Self);
Pattern.Key := #10;
Pattern.Max := 1;
end;
{ TCRLF }
constructor TCRLF.Create(AParent: TAny);
begin
inherited Create(AParent);
Key := #13#10;
Min := 1;
Max := 1;
end;
{ TLF }
constructor TLF.Create(AParent: TAny);
begin
inherited Create(AParent);
Key := #10;
Min := 1;
Max := 1;
end;
{ TNotZero }
constructor TNotZero.Create(AParent: TAny);
begin
inherited Create(AParent);
Storage.Kind := pkCharClass;
CharClass := [#0];
Negative := True;
end;
{ TTill }
constructor TTill.Create(AParent: TAny);
begin
inherited Create(AParent);
Storage.Kind := pkTillKey;
end;
{ TTillChars }
constructor TTillChars.Create(AParent: TAny);
begin
inherited Create(AParent);
Storage.Kind := pkTillChars;
end;
{ TTillLineEnd }
constructor TTillLineEnd.Create(AParent: TAny);
begin
inherited Create(AParent);
Storage.Kind := pkTillChars;
CharClass := [#10, #13];
Negative := True;
end;
{ TZero }
constructor TZero.Create(AParent: TAny);
begin
inherited Create(AParent);
Key := #0;
Id := piZero;
end;
{ TAlpha }
constructor TAlpha.Create(AParent: TAny);
begin
inherited Create(AParent);
Min := 1;
Id := piIdent;
Storage.Kind := pkCharClass;
CharClass := ['_', 'A'..'Z', 'a'..'z'];
end;
{ TAlphaNumeric }
constructor TAlphaNumeric.Create(AParent: TAny);
begin
inherited Create(AParent);
Min := 1;
Id := piIdent;
Storage.Kind := pkCharClass;
CharClass := ['_', '0'..'9', 'A'..'Z', 'a'..'z'];
end;
{ TNumeric }
constructor TNumeric.Create(AParent: TAny);
begin
inherited Create(AParent);
Min := 1;
Storage.Kind := pkCharClass;
CharClass := ['0'..'9'];
end;
{ TIdentifier }
constructor TIdentifier.Create(AParent: TAny);
begin
inherited Create(AParent);
TAlphaNumeric.Create(Self);
end;
(*
{ TCharAlpha }
constructor TCharAlpha.Create(AParent: TAny);
var
I: Char;
begin
inherited Create(AParent);
Storage.Kind := pkCharClass;
SetLength(FKey, 32);
for I := #0 to #255 do
if IsCharAlpha(I) then Include(PmwChars(FKey).Chars, I);
end;
{ TCharAlphaNumeric }
constructor TCharAlphaNumeric.Create(AParent: TAny);
var
I: Char;
begin
inherited Create(AParent);
Storage.Kind := pkCharClass;
SetLength(FKey, 32);
for I := #0 to #255 do
if IsCharAlphaNumeric(I) then Include(PmwChars(FKey).Chars, I);
end;
{ TCharLower }
constructor TCharLower.Create(AParent: TAny);
var
I: Char;
begin
inherited Create(AParent);
Storage.Kind := pkCharClass;
SetLength(FKey, 32);
for I := #0 to #255 do
if IsCharLower(I) then Include(PmwChars(FKey).Chars, I);
end;
{ TCharUpper }
constructor TCharUpper.Create(AParent: TAny);
var
I: Char;
begin
inherited Create(AParent);
Storage.Kind := pkCharClass;
SetLength(FKey, 32);
for I := #0 to #255 do
if IsCharUpper(I) then Include(PmwChars(FKey).Chars, I);
end;
*)
{ TmwGenLex }
procedure TmwGenLex.Add(Pattern: TAny);
var
I: Integer;
begin
FChain.Add(Pattern);
AddToMainSelector(Pattern);
for I := 0 to Pattern.Count - 1 do
AddToMainSelector(Pattern[Byte(I)]);
end;
procedure TmwGenLex.AddToMainSelector(Pattern: TAny);
var
I: Char;
begin
case Pattern.Kind of
pkAny, pkTillChars, pkTillKey:
raise exception.Create('pkAny, pkTillChars, pkTillKey not allowed here');
pkCharClass:
for I := #0 to #255 do
case Pattern.Negative of
True:
if not (I in Pattern.CharClass) then
MainSelector[Char(I)] := Pattern;
False:
if I in Pattern.CharClass then
MainSelector[I] := Pattern;
end;
pkLineEnd:
begin
MainSelector[#10] := Pattern;
MainSelector[#13] := Pattern;
end;
else
if Length(Pattern.Key) > 0 then
MainSelector[Pattern.Key[1]] := Pattern;
end;
end;
function TmwGenLex.ApplyAny: Boolean;
begin
Range := nil;
Result := True;
if Run >= TheEnd then
begin
Result := False;
exit;
end;
inc(Run);
end;
function TmwGenLex.ApplyChar: Boolean;
var
Temp: PChar;
begin
Range := nil;
Temp := Run;
case psNegative in Current.Storage.Status of
True:
case Sensitive of
True: if Current.Key <> Run^ then
begin
if Run >= TheEnd then
begin
Result := False;
exit;
end;
inc(Run)
end;
False: if CompTable[Current.Key[1]] <> CompTable[Run^] then
begin
if Run >= TheEnd then
begin
Result := False;
exit;
end;
inc(Run)
end;
end;
False:
case Sensitive of
True: if Current.Key = Run^ then
begin
if Run >= TheEnd then
begin
Result := False;
exit;
end;
inc(Run)
end;
False: if CompTable[Current.Key[1]] = CompTable[Run^] then
begin
if Run >= TheEnd then
begin
Result := False;
exit;
end;
inc(Run)
end;
end;
end;
Result := Run - Temp = 1;
end;
function TmwGenLex.ApplyCharClass: Boolean;
var
Temp: PChar;
begin
Range := nil;
Temp := Run;
case psNegative in Current.Storage.Status of
True:
if Current.Max > 0 then
begin
if not (Run^ in PmwChars(Current.FKey).Chars) then
if not AtEnd then inc(Run)
end else
while not (Run^ in PmwChars(Current.FKey).Chars) do
begin
if Run >= TheEnd then break;
inc(Run);
end;
False:
if Current.Max > 0 then
begin
if Run^ in PmwChars(Current.FKey).Chars then
if not AtEnd then inc(Run)
end else
while Run^ in PmwChars(Current.FKey).Chars do
begin
if Run >= TheEnd then break;
inc(Run);
end;
end;
Result := Run > Temp;
end;
function TmwGenLex.ApplyInnerLineEnd: Boolean;
begin
Result := True;
case Run^ of
#13:
begin
inc(Run);
if Run < TheEnd then if Run^ = #10 then inc(Run);
end;
#10: inc(Run);
end;
if Result then
Inc(fLineCount);
Range := Current.ToRestore;
end;
function TmwGenLex.ApplyKey: Boolean;
var
I: Integer;
Temp: PChar;
begin
Range := nil;
Temp := Run;
for I := 1 to Length(Current.Key) do
begin
if Run >= TheEnd then break;
case Sensitive of
True: if Current.Key[I] = Run^ then inc(Run) else break;
False: if CompTable[Current.Key[I]] = CompTable[Run^] then inc(Run) else break;
end;
end;
Result := (Run - Temp) = Length(Current.Key);
if not Result then Run := Temp;
end;
function TmwGenLex.ApplyLineEnd: Boolean;
begin
Range := nil;
Result := True;
case Run^ of
#13:
begin
inc(Run);
if Run < TheEnd then if Run^ = #10 then inc(Run);
end;
#10: inc(Run);
else Result := False;
end;
if Result then
Inc(fLineCount);
end;
function TmwGenLex.ApplyTillChars: Boolean;
var
Temp: PChar;
begin
Temp := Run;
Result := False;
while Result = False do
begin
if Run >= TheEnd then break;
case Run^ of
#10, #13:
case Current.Multiline of
True:
begin
Range := InnerLineEnd;
InnerLineEnd.ToRestore := Current;
Exit;
end;
False:
begin
Result := False;
break;
end;
end;
else
Temp := Run;
Result := ApplyCharClass;
if Result = False then inc(Run);
end;
end;
if Result then
begin
Range := nil;
if psNegative in Current.Storage.Status then Run := Temp;
end else
case Current.Multiline of
True: Range := Current;
False:
begin
Range := nil;
Run := Temp;
end;
end;
end;
function TmwGenLex.ApplyTillKey: Boolean;
var
Temp: PChar;
begin
Temp := Run;
Result := False;
while Result = False do
begin
if Run >= TheEnd then break;
case Run^ of
#10, #13:
case Current.Multiline of
True:
begin
Range := InnerLineEnd;
InnerLineEnd.ToRestore := Current;
Exit;
end;
False:
begin
Result := False;
break;
end;
end;
else
if Run^ = Current.Key[1] then
begin
Result := ApplyKey;
if Result = False then inc(Run);
end else inc(Run)
end;
end;
if Result then
begin
Range := nil;
if psNegative in Current.Storage.Status then Run := Run - Length(Current.Key);
end else
case Current.Multiline of
True: Range := Current;
False:
begin
Range := nil;
Run := Temp;
end;
end;
end;
function TmwGenLex.AtEnd: Boolean;
begin
Result := Run >= TheEnd;
end;
procedure TmwGenLex.Clear;
var
I: Integer;
begin
for I := 0 to fChain.Count - 1 do
if Assigned(fChain[I]) then TObject(fChain[I]).Free;
fChain.Clear;
end;
constructor TmwGenLex.Create;
begin
inherited Create;
fLineCount := 0;
InnerLineEnd := TAny.Create(nil);
InnerLineEnd.Kind := pkInnerLineEnd;
InnerLineEnd.Id := piInnerLineEnd;
InitSelector;
FChain := TList.Create;
InitMainSelector;
FId := piUnknown;
FExId := piUnknown;
end;
destructor TmwGenLex.Destroy;
begin
InnerLineEnd.Free;
Clear;
FChain.Free;
inherited Destroy;
end;
function TmwGenLex.Execute: Boolean;
var
I: Integer;
Temp: PChar;
begin
Temp := Run;
Result := True;
if (Current.Max = 0) and (Current.Min = 0) then Selector[Current.Kind] else
begin
for I := 0 to Current.Min - 1 do Result := Selector[Current.Kind];
if not Result then Run := Temp;
for I := Current.Min to Current.Max - 1 do Selector[Current.Kind];
end;
end;
function TmwGenLex.GetEndPos: Integer;
begin
Result := TheEnd - FOrigin;
end;
function TmwGenLex.GetLinePos: Integer;
begin
Result := fLineCount;
end;
function TmwGenLex.GetRunPos: Integer;
begin
Result := Run - FOrigin;
end;
function TmwGenLex.GetToken: string;
begin
SetLength(Result, Run - Start);
Move(Start^, Result[1], Run - Start);
end;
procedure TmwGenLex.InitMainSelector;
var
I: Char;
Default: TAny;
begin
Default := TAny.Create(nil);
Default.Key := #0;
Default.Id := piZero;
FChain.Add(Default);
MainSelector[#0] := Default;
Default := TAny.Create(nil);
FChain.Add(Default);
for I := #1 to #255 do
MainSelector[I] := Default;
end;
procedure TmwGenLex.InitSelector;
begin
Selector[pkAny] := ApplyAny;
Selector[pkChar] := ApplyChar;
Selector[pkCharClass] := ApplyCharClass;
Selector[pkInnerLineEnd] := ApplyInnerLineEnd;
Selector[pkKey] := ApplyKey;
Selector[pkLineEnd] := ApplyLineEnd;
Selector[pkTillChars] := ApplyTillChars;
Selector[pkTillKey] := ApplyTillKey;
end;
procedure TmwGenLex.Next;
var
Succeed: Boolean;
TempRun: PChar;
begin
Start := Run;
if Range <> nil then Current := Range else
Current := MainSelector[Run^];
while Current <> nil do
begin
case Current.Regress of
True:
begin
TempRun := Run;
Succeed := SubNext;
if Succeed then
begin
Current := Current.ToRegress;
Succeed := SubNext
end;
if Succeed then
begin
FId := Current.Id;
FExId := Current.ExId;
Current := Current.Follow;
end else
begin
Run := TempRun;
Current:= nil;
end;
end;
False:
begin
Succeed := SubNext;
if Succeed then
begin
FId := Current.Id;
FExId := Current.ExId;
Current := Current.Follow;
end;
end;
end;
end;
end;
procedure TmwGenLex.SetEndPos(const Value: Integer);
begin
TheEnd := FOrigin + Value;
end;
procedure TmwGenLex.SetInitMethod(const Value: TmwLexInitMethod);
begin
if Assigned(Value) then
begin
Clear;
FInitMethod := Value;
InitMainSelector;
Value(Self);
end;
end;
procedure TmwGenLex.SetInitProc(const Value: TmwLexInitProc);
begin
if Assigned(Value) then
begin
Clear;
FInitProc := Value;
InitMainSelector;
Value(Self);
end;
end;
procedure TmwGenLex.SetInput(const Value: string);
begin
FOrigin := PChar(Value);
Run := FOrigin;
TheEnd := FOrigin + Length(Value);
end;
procedure TmwGenLex.SetOrigin(const Value: PChar);
begin
FOrigin := Value;
Run := FOrigin;
Start := Value;
TheEnd := FOrigin;
fLineCount := 0;
FId := piUnknown;
FExId := piUnknown;
end;
procedure TmwGenLex.SetRunPos(const Value: Integer);
begin
Run := FOrigin + Value;
Start := Run;
end;
procedure TmwGenLex.SetStartData(Ptr: Pointer; aLen: Integer);
begin
Origin := Ptr;
TheEnd := PChar(Ptr) + aLen;
end;
function TmwGenLex.SubNext: Boolean;
var
I: Integer;
Temp: TAny;
begin
Result := Execute;
if not Result then
if Current.Count = 0 then Current := nil else
for I := 0 to Current.Count - 1 do
begin
Temp := Current;
Current := Current[Byte(I)];
Result := Execute;
if Result then break else
begin
Current := Temp;
if I = Current.Count - 1 then
begin
Current := nil;
break;
end;
end;
end;
end;
initialization
InitTables;
end.
|
{$REGION 'Copyright (C) CMC Development Team'}
{ **************************************************************************
Copyright (C) 2015 CMC Development Team
CMC is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
CMC 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 CMC. If not, see <http://www.gnu.org/licenses/>.
************************************************************************** }
{ **************************************************************************
Additional Copyright (C) for this modul:
Chromaprint: Audio fingerprinting toolkit
Copyright (C) 2010-2012 Lukas Lalinsky <lalinsky@gmail.com>
Lomont FFT: Fast Fourier Transformation
Original code by Chris Lomont, 2010-2012, http://www.lomont.org/Software/
************************************************************************** }
{$ENDREGION}
{$REGION 'Notes'}
{ **************************************************************************
See CP.Chromaprint.pas for more information
************************************************************************** }
unit CP.Resampler;
{$IFDEF FPC}
{$MODE delphi}
{$ENDIF}
interface
uses
Windows, Classes, SysUtils, CP.Def;
const
FILTER_SHIFT = 15;
WINDOW_TYPE = 9;
type
TFELEM = smallint;
TFELEML = double;
PFELEM = ^TFELEML;
PAVClass = pointer;
{ TAVResampleContext }
TAVResampleContext = record
rAVClass: PAVClass;
rFilterBank: array of smallint;
rFilterLength: integer;
rIdealDstIncr: integer;
rDstIncr: integer;
rIndex: int32;
rFrac: integer;
rSrcIncr: integer;
rCompensationDistance: integer;
rPhaseShift: integer;
rPhaseMask: integer;
rLinear: integer;
procedure Clear;
procedure Init(out_rate, in_rate, filter_size, APhaseShift: integer; ALinear: integer; cutoff: double);
function Resample(dst: TSmallintArray; src: TSmallintArray; var consumed: integer; src_size: integer; dst_size: integer; update_ctx: integer): integer;
end;
PAVResampleContext = ^TAVResampleContext;
implementation
uses
{$IFDEF FPC}
DaMath;
{$ELSE}
Math;
{$ENDIF}
function FFABS(a: integer): integer; overload;
begin
if (a >= 0) then
Result := a
else
Result := -a;
end;
function FFSIGN(a: integer): integer; overload;
begin
if (a > 0) then
Result := 1
else if (a < 0) then
Result := -1
else
Result := 0;
end;
function FFMAX(a, b: integer): integer; overload;
begin
if (a > b) then
Result := a
else
Result := b;
end;
function FFMIN(a, b: integer): integer; overload;
begin
if (a > b) then
Result := b
else
Result := a;
end;
function FFABS(a: double): double; overload;
begin
if (a >= 0) then
Result := a
else
Result := -a;
end;
function FFSIGN(a: double): integer; overload;
begin
if (a > 0) then
Result := 1
else if (a < 0) then
Result := -1
else
Result := 0;
end;
function FFMAX(a, b: double): double; overload;
begin
if (a > b) then
Result := a
else
Result := b;
end;
function FFMIN(a, b: double): double; overload;
begin
if (a > b) then
Result := b
else
Result := a;
end;
{ 0th order modified bessel function of the first kind. }
function bessel(x: double): double;
var
v, lastv, t, lx: double;
i: integer;
begin
v := 1;
lastv := 0;
t := 1;
lx := x * x / 4;
i := 1;
while v <> lastv do
begin
lastv := v;
t := t * lx / (i * i);
v := v + t;
Inc(i);
end;
Result := v;
end;
function Clip(a: integer; amin, amax: smallint): smallint;
begin
if (a < amin) then
Result := amin
else if (a > amax) then
Result := amax
else
Result := smallint(a);
end;
function BuildFilter(var filter: array of smallint; factor: double; tap_count: integer; phase_count, scale, _type: integer): boolean;
var
ph, i, center: integer;
x, y, w: double;
tab: array of double;
norm: double;
d: double;
ex: integer;
begin
SetLength(tab, tap_count);
center := (tap_count - 1) div 2;
// if upsampling, only need to interpolate, no filter
if (factor > 1.0) then
factor := 1.0;
for ph := 0 to phase_count - 1 do
begin
norm := 0;
for i := 0 to tap_count - 1 do
begin
x := Math_Pi * ((i - center) - ph / phase_count) * factor;
if (x = 0) then
y := 1.0
else
y := Sin(x) / x;
case (_type) of
0:
begin
d := -0.5; // first order derivative = -0.5
x := Abs(((i - center) - ph / phase_count) * factor);
if (x < 1.0) then
y := 1 - 3 * x * x + 2 * x * x * x + d * (-x * x + x * x * x)
else
y := d * (-4 + 8 * x - 5 * x * x + x * x * x);
end;
1:
begin
w := 2.0 * x / (factor * tap_count) + Math_Pi;
y := y * (0.3635819 - 0.4891775 * Cos(w) + 0.1365995 * Cos(2 * w) - 0.0106411 * Cos(3 * w));
end;
else
begin
w := 2.0 * x / (factor * tap_count * Math_Pi);
{$IFDEF FPC}
y := y * (bessel(_type * Sqrt(MaxD(1 - w * w, 0))));
{$ELSE}
y := y * (bessel(_type * Sqrt(Max(1 - w * w, 0))));
{$ENDIF}
end;
end;
tab[i] := y;
norm := norm + y;
end;
// normalize so that an uniform color remains the same
for i := 0 to tap_count - 1 do
begin
ex := floor(tab[i] * scale / norm + 0.50000);
filter[ph * tap_count + i] := Clip(ex, -32768, 32767);
end;
end;
Result := True;
end;
{ TAVResampleContext }
procedure TAVResampleContext.Clear;
begin
rAVClass := nil;
SetLength(rFilterBank, 0);
rFilterLength := 0;
rIdealDstIncr := 0;
rDstIncr := 0;
rIndex := 0;
rFrac := 0;
rSrcIncr := 0;
rCompensationDistance := 0;
rPhaseShift := 0;
rPhaseMask := 0;
rLinear := 0;
end;
procedure TAVResampleContext.Init(out_rate, in_rate, filter_size, APhaseShift: integer; ALinear: integer; cutoff: double);
var
factor: double;
phase_count: integer;
r: boolean;
i: integer;
begin
{$IFDEF FPC}
factor := MinD(out_rate * cutoff / in_rate, 1.0);
{$ELSE}
factor := min(out_rate * cutoff / in_rate, 1.0);
{$ENDIF}
phase_count := 1 shl APhaseShift;
rPhaseShift := APhaseShift;
rPhaseMask := phase_count - 1;
rLinear := ALinear;
rFilterLength := Max(ceil(filter_size / factor), 1);
SetLength(rFilterBank, rFilterLength * (phase_count + 1));
begin
r := BuildFilter(rFilterBank, factor, rFilterLength, phase_count, (1 shl FILTER_SHIFT), WINDOW_TYPE);
if (r) then
begin
Move(rFilterBank[0], rFilterBank[rFilterLength * phase_count + 1], (rFilterLength - 1) * sizeof(TFELEM));
rFilterBank[rFilterLength * phase_count] := rFilterBank[rFilterLength - 1];
rSrcIncr := out_rate;
rDstIncr := in_rate * phase_count;
rIdealDstIncr := rDstIncr;
rIndex := -phase_count * ((rFilterLength - 1) div 2);
end;
end;
end;
function TAVResampleContext.Resample(dst: TSmallintArray; src: TSmallintArray; var consumed: integer; src_size: integer; dst_size: integer;
update_ctx: integer): integer;
var
dst_index, i: integer;
lIndex, lFrac, ldst_incr_frac, lDst_incr, lCompensationDistance: int32;
lIndex2, lIncr: int64;
lFilterOffset: integer;
lSampleIndex, lVal, lV2: int32;
lr: longint;
lTempSrcIdx: integer;
begin
// c++ is pain
lIndex := self.rIndex;
lFrac := self.rFrac;
ldst_incr_frac := self.rDstIncr mod self.rSrcIncr;
lDst_incr := self.rDstIncr div self.rSrcIncr;
lCompensationDistance := self.rCompensationDistance;
if (lCompensationDistance = 0) and (self.rFilterLength = 1) and (self.rPhaseShift = 0) then
begin
lIndex2 := longint(lIndex) shl 32;
lIncr := (1 shl 32) * self.rDstIncr div self.rSrcIncr;
dst_size := min(dst_size, (src_size - 1 - lIndex) * self.rSrcIncr div self.rDstIncr);
for dst_index := 0 to dst_size - 1 do
begin
dst[dst_index] := src[lIndex2 shr 32];
lIndex2 := lIndex2 + lIncr;
end;
lFrac := lFrac + dst_index * ldst_incr_frac;
lIndex := lIndex + dst_index * lDst_incr;
lIndex := lIndex + lFrac div self.rSrcIncr;
lFrac := lFrac mod self.rSrcIncr;
end
else
begin
for dst_index := 0 to dst_size - 1 do
begin
lFilterOffset := self.rFilterLength * (lIndex and self.rPhaseMask);
lr := longint(int64(lIndex) shr self.rPhaseShift);
lSampleIndex := lr;
lVal := 0;
if (lSampleIndex < 0) then
begin
for i := 0 to self.rFilterLength - 1 do
begin
lTempSrcIdx := Abs(lSampleIndex + i) mod src_size;
lVal := lVal + (src[lTempSrcIdx] * self.rFilterBank[lFilterOffset + i]);
end;
end
else if (lSampleIndex + self.rFilterLength > src_size) then
begin
break;
end
else if (self.rLinear = 1) then
begin
lV2 := 0;
for i := 0 to self.rFilterLength - 1 do
begin
lVal := lVal + src[lSampleIndex + i] * self.rFilterBank[lFilterOffset + i];
lV2 := lV2 + src[lSampleIndex + i] * self.rFilterBank[lFilterOffset + i + self.rFilterLength];
end;
lVal := lVal + ((lV2 - lVal) * (lFrac div self.rSrcIncr));
end
else
begin
for i := 0 to self.rFilterLength - 1 do
begin
lVal := lVal + (src[lSampleIndex + i] * self.rFilterBank[lFilterOffset + i]);
if (dst_index = 1148) and (i = 29) then
outputDebugstring(pchar(intToStr(lVal)));
end;
end;
lVal := (lVal + (1 shl (FILTER_SHIFT - 1))) shr FILTER_SHIFT;
dst[dst_index] := lVal; // Pascal is cool, C++ is pain
lFrac := lFrac + ldst_incr_frac;
lIndex := lIndex + lDst_incr;
if (lFrac >= self.rSrcIncr) then
begin
lFrac := lFrac - self.rSrcIncr;
Inc(lIndex);
end;
if (dst_index + 1 = lCompensationDistance) then
begin
lCompensationDistance := 0;
ldst_incr_frac := self.rIdealDstIncr mod self.rSrcIncr;
lDst_incr := self.rIdealDstIncr div self.rSrcIncr;
end;
end;
end;
consumed := Max(lIndex, 0) shr self.rPhaseShift;
if (lIndex >= 0) then
lIndex := lIndex and self.rPhaseMask;
if (lCompensationDistance <> 0) then
begin
lCompensationDistance := lCompensationDistance - dst_index;
end;
if (update_ctx = 1) then
begin
self.rFrac := lFrac;
self.rIndex := lIndex;
self.rDstIncr := ldst_incr_frac + self.rSrcIncr * lDst_incr;
self.rCompensationDistance := lCompensationDistance;
end;
Result := dst_index;
end;
end.
|
unit SctBtn;
{ ----------------------------------------------------------------
Ace Reporter
Copyright 1995-2004 SCT Associates, Inc.
Written by Kevin Maher, Steve Tyrakowski
---------------------------------------------------------------- }
interface
{$I ace.inc}
uses windows, SysUtils, Messages, Classes, Graphics, Controls,
Forms, Dialogs, StdCtrls, Buttons, sctrep, psetup;
type
TSctBtnDest = (bdPrinter, bdScreen, bdDefault);
TSctBtnPrompt = (bpPrompt, bpNoPrompt, bpDefault);
TSctBtnDataRange = (brAllRecords, brSingleRecord, brDefault);
{ TSctOnBeforeRunEvent }
TSctOnBeforeRunEvent = procedure (PageSetup: TObject) of object;
{$IFDEF VCL230PLUS}
[ComponentPlatformsAttribute(pidWin32 or pidWin64)]
{$ENDIF}
TSctReportButton = class(TBitBtn)
private
{ Private declarations }
FReport: TSctReport;
FDestination: TSctBtnDest;
FPrompt: TSctBtnPrompt;
FOnBeforeRun: TSctOnBeforeRunEvent;
FDataRange: TSctBtnDataRange;
protected
{ Protected declarations }
procedure SetParent(AParent: TWinControl); override;
procedure Notification(AComponent: TComponent;
Operation: TOperation); override;
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
procedure Click; override;
published
{ Published declarations }
property Report: TSctReport read FReport write FReport;
property Destination: TSctBtnDest read FDestination write FDestination;
property Prompt: TSctBtnPrompt read FPrompt write FPrompt;
property OnBeforeRun: TSctOnBeforeRunEvent read FOnBeforeRun write FOnBeforeRun;
property DataRange: TSctBtnDataRange read FDataRange write FDataRange;
end;
implementation
constructor TSctReportButton.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FDestination := bdDefault;
FPrompt := bpDefault;
FDataRange := brDefault;
end;
procedure TSctReportButton.Notification(AComponent: TComponent;
Operation: TOperation);
begin
Inherited Notification(AComponent, Operation);
if (AComponent is TSctReport) Then
begin
if (Operation = opRemove) And (TSctReport(AComponent) = Report) Then
Report := nil;
end;
end;
procedure TSctReportButton.Click;
var
nogo: Boolean;
PageSetup: TSctPageSetup;
begin
if FReport <> nil then
begin
nogo := false;
PageSetup := Report.Page.PageSetup;
if Destination <> bdDefault then
begin
if Destination = bdPrinter then PageSetup.Destination := destPrinter
else if Destination = bdScreen then PageSetup.Destination := destScreen;
end;
if Prompt <> bpDefault then
begin
if Prompt = bpPrompt then Report.Prompt := True
else Report.Prompt := False;
end;
if DataRange <> brDefault then
begin
if DataRange = brAllRecords Then TSctGroupPage(Report.Page).DataRange := drAllRecords
else TSctGroupPage(Report.Page).DataRange := drSingleRecord;
end;
if Assigned(FOnBeforeRun) then
begin
try
FOnBeforeRun( PageSetup );
except
nogo := True;
end;
end;
if Not nogo then FReport.Run;
end;
inherited Click;
end;
procedure TSctReportButton.SetParent(AParent: TWinControl);
begin
{ do this check so don't put my component on where is does not belong }
if (AParent = nil) Or (Not (AParent is TSctPage)
And Not (AParent is TSctBand) And Not (AParent is TSctReport) ) Then
begin
inherited SetParent(AParent);
end else Abort;
end;
end.
|
unit Backup;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ComCtrls, StdCtrls, Buttons, ErrorListDialog, VCLZip, VCLUnZip, kpZipObj,
FFSColorLabel, FFSReportProgress, ExtCtrls, sBitBtn;
type
TBackupProgress = procedure(percent:integer) of object;
TBackup = class(TComponent)
private
zip : TVclZip;
ErrorList : TStringList; // passed the pointer - not created
FOnProgress : TBackupProgress;
FZipFileName: TFileName;
procedure ZipSkippingFile(Sender: TObject; Reason: TSkipReason; FName: String; FileIndex: Integer; var Retry: Boolean);
procedure ZipOnPercentDone(Sender: TObject; Percent: Integer);
procedure SetOnProgress(const Value: TBackupProgress);
procedure SetZipFileName(const Value: TFileName);
public
constructor create(AOwner:TComponent; AErrorList:TStringList);reintroduce;
destructor destroy;override;
procedure Backup;
procedure Restore;
property OnProgress : TBackupProgress read FOnProgress write SetOnProgress;
property ZipFileName : TFileName read FZipFileName write SetZipFileName;
end;
TfrmBackup = class(TForm)
SaveDialog1: TSaveDialog;
OpenDialog1: TOpenDialog;
Label1: TLabel;
Elist: TErrorListDialog;
StatusBar1: TStatusBar;
Label2: TLabel;
Label3: TLabel;
ZipLender: TVCLZip;
Label4: TLabel;
UnzipLender: TVCLUnZip;
btnBackup: TsBitBtn;
btnClose: TsBitBtn;
btnRestore: TsBitBtn;
btnLenderBackup: TsBitBtn;
btnLenderRestore: TsBitBtn;
procedure btnBackupClick(Sender: TObject);
procedure btnRestoreClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure StatusBar1DrawPanel(StatusBar: TStatusBar; Panel: TStatusPanel; const Rect: TRect);
procedure btnLenderBackupClick(Sender: TObject);
procedure btnLenderRestoreClick(Sender: TObject);
procedure ZipLenderStartZip(Sender: TObject; FName: String;
var ZipHeader: TZipHeaderInfo; var Skip: Boolean);
procedure ZipLenderEndZip(Sender: TObject; FName: String;
UncompressedSize, CompressedSize, CurrentZipSize: Integer);
procedure ZipLenderFilePercentDone(Sender: TObject; Percent: Integer);
procedure UnzipLenderFilePercentDone(Sender: TObject;
Percent: Integer);
procedure UnzipLenderStartUnZip(Sender: TObject; FileIndex: Integer;
var FName: String; var Skip: Boolean);
procedure UnzipLenderEndUnZip(Sender: TObject; FileIndex: Integer;
FName: String);
private
{ Private declarations }
ErrorList : TStringList;
procedure DoOnProgress(percent:integer);
public
{ Public declarations }
SiteID : string;
Flag:string;
end;
var
frmBackup: TfrmBackup;
implementation
uses FFSUtils, ProgramSettings, TicklerTypes, TicklerGlobals, datamod ;
{$R *.DFM}
{ TBackup }
constructor TBackup.Create(AOwner: TComponent; AErrorList: TStringList);
begin
inherited create(AOwner);
ErrorList := AErrorList;
zip := TVclZip.Create(self);
zip.OnSkippingFile := ZipSkippingFile;
zip.OnTotalPercentDone := ZipOnPercentDone;
end;
procedure TBackup.ZipOnPercentDone(Sender:TObject;Percent:LongInt);
begin
if Assigned(OnProgress) then OnProgress(Percent);
end;
destructor TBackup.destroy;
begin
inherited;
end;
procedure TBackup.Backup;
//var
// fn : string;
begin
try
try
zip.RootDir := Dir(drData);
zip.ZipName := ZipFileName;
zip.FilesList.Add('*.DAT');
zip.FilesList.Add('*.IDX');
zip.FilesList.Add('*.BLB');
zip.Password := 'ZIPRX';
zip.Zip;
except
on e:Exception do ErrorList.Add(e.Message);
end;
finally
end;
end;
procedure TBackup.Restore;
//var
// fn : string;
begin
try
try
zip.DestDir := Dir(drData);
zip.ZipName := ZipFileName;
zip.Password := 'ZIPRX';
zip.OverwriteMode := Always;
zip.FilesList.Add('*');
// this causes an "incolmplete zip file" error, so I did the above
//zip.DoAll := TRUE;
zip.UnZip;
except
on e:Exception do ErrorList.Add(e.Message);
end;
finally
end;
end;
procedure TBackup.SetOnProgress(const Value: TBackupProgress);
begin
FOnProgress := Value;
end;
procedure TBackup.ZipSkippingFile(Sender: TObject; Reason: TSkipReason; FName: String; FileIndex: Integer; var Retry: Boolean);
begin
ErrorList.Add(FName + ' not processed.');
end;
procedure TBackup.SetZipFileName(const Value: TFileName);
begin
FZipFileName := Value;
end;
{ TfrmBackup }
procedure TfrmBackup.DoOnProgress(percent:integer);
begin
StatusBar1.Panels[1].Text := IntToStr(percent);
end;
procedure TfrmBackup.btnBackupClick(Sender: TObject);
var
bkup : TBackup;
begin
SaveDialog1.InitialDir := Dir(drExport);
SaveDialog1.FileName := 'TTS' + SiteID + AnyDateToyyyymmdd(SystemDateString) + '.ZIP';
if SaveDialog1.Execute then begin
EList.Items.Clear;
btnBackup.Enabled := false;
btnClose.Enabled := false;
btnRestore.Enabled := false;
StatusBar1.Panels[0].Text := 'Backing Up Data...';
StatusBar1.Panels[1].Text := '0';
update;
try
DeleteFile(SaveDialog1.FileName); // if we got this far, overwrite if it exists
// zip up the database
bkup := TBackup.Create(self,ErrorList);
bkup.ZipFileName := SaveDialog1.FileName;
bkup.OnProgress := DoOnProgress;
bkup.Backup;
bkup.Free;
finally
StatusBar1.Panels[0].Text := 'Idle';
StatusBar1.Panels[1].Text := '0';
btnRestore.Enabled := true;
btnBackup.Enabled := true;
btnClose.Enabled := true;
if ErrorList.Count > 0 then begin
EList.Items.AddStrings(ErrorList);
EList.Execute;
end;
end;
end;
end;
procedure TfrmBackup.btnRestoreClick(Sender: TObject);
var
bkup : TBackup;
begin
OpenDialog1.InitialDir := Dir(drExport);
if OpenDialog1.Execute then begin
if MessageDlg('WARNING: You are about to overwrite your current data '+
'files with a backup. Are you sure you wish to continue?',
mtConfirmation,mbYesNoCancel,0)<>mrYes then exit;
EList.Items.Clear;
btnBackup.Enabled := false;
btnClose.Enabled := false;
btnRestore.Enabled := false;
StatusBar1.Panels[0].Text := 'Restoring Data...';
StatusBar1.Panels[1].Text := '0';
update;
try
// zip up the database
bkup := TBackup.Create(self,ErrorList);
bkup.ZipFileName := OpenDialog1.FileName;
bkup.OnProgress := DoOnProgress;
bkup.Restore;
bkup.Free;
finally
StatusBar1.Panels[0].Text := 'Idle';
StatusBar1.Panels[1].Text := '0';
btnRestore.Enabled := true;
btnBackup.Enabled := true;
btnClose.Enabled := true;
if ErrorList.Count > 0 then begin
EList.Items.AddStrings(ErrorList);
EList.Execute;
end;
end;
end;
end;
procedure TfrmBackup.FormCreate(Sender: TObject);
begin
ErrorList := TStringList.create;
StatusBar1.Panels[0].Text := 'Idle';
StatusBar1.Panels[1].Text := '0';
end;
procedure TfrmBackup.FormDestroy(Sender: TObject);
begin
ErrorList.free;
end;
procedure TfrmBackup.StatusBar1DrawPanel(StatusBar: TStatusBar; Panel: TStatusPanel; const Rect: TRect);
var
X,Y,pct : integer;
newrect : TRect;
s : string;
size : TSize;
begin
try
pct := StrToInt(Panel.Text);
StatusBar.Canvas.Brush.Color := StatusBar.Color;
StatusBar.Canvas.FillRect(Rect);
// if pct=0 then Exit;
StatusBar.Canvas.Brush.Color := clNavy;
newrect := Rect;
newrect.Right := Rect.Left+Trunc((pct/100)*Panel.Width);
StatusBar.Canvas.FillRect(newrect);
s := Format('%d%%',[pct]);
size := StatusBar.Canvas.TextExtent(s);
X := Rect.Left+((Panel.Width-size.cx) div 2);
Y := Rect.Top+(((rect.bottom-rect.top)-size.cy) div 2);
SetBkMode(StatusBar.Canvas.Handle,TRANSPARENT);
StatusBar.Canvas.Font.Color := clGreen;
StatusBar.Canvas.TextOut(X,Y,s);
except
end;
end;
procedure TfrmBackup.btnLenderBackupClick(Sender: TObject);
//var
// zip :TVclZip;
// TIdx: Integer;
begin
{$IFDEF SERVER}
Flag := 'LB';
btnClose.Click;
Exit;
{$ENDIF}
{$ifdef THINVER}
exit;
{$endif}
//zip := TVclZip.Create(self);
//zip.OnSkippingFile := ZipSkippingFile;
//zip.OnTotalPercentDone := ZipOnPercentDone;
if CurrentLend.Number = '' then begin
ShowMessage('Current Lender is empty. Please select lender from Main screen and retry');
btnClose.Click;
Exit;
end;
// CIF
StatusBar1.Panels[0].Text := 'Backing Up CIF...';
StatusBar1.Panels[1].Text := '0';
Application.ProcessMessages;
daapi.LenderBackUp(CurrentLend.Number,'CIF',StatusBar1);
// CITM
StatusBar1.Panels[0].Text := 'Backing Up CITM...';
StatusBar1.Panels[1].Text := '0';
Application.ProcessMessages;
daapi.LenderBackUp(CurrentLend.Number,'CITM',StatusBar1);
// CODE
StatusBar1.Panels[0].Text := 'Backing Up CODE...';
StatusBar1.Panels[1].Text := '0';
Application.ProcessMessages;
daapi.LenderBackUp(CurrentLend.Number,'CODE',StatusBar1);
// COLL
StatusBar1.Panels[0].Text := 'Backing Up COLL...';
StatusBar1.Panels[1].Text := '0';
Application.ProcessMessages;
daapi.LenderBackUp(CurrentLend.Number,'COLL',StatusBar1);
// DCRUN
StatusBar1.Panels[0].Text := 'Backing Up DCRUN...';
StatusBar1.Panels[1].Text := '0';
Application.ProcessMessages;
daapi.LenderBackUp(CurrentLend.Number,'DCRUN',StatusBar1);
// GUAR
StatusBar1.Panels[0].Text := 'Backing Up GUAR...';
StatusBar1.Panels[1].Text := '0';
Application.ProcessMessages;
daapi.LenderBackUp(CurrentLend.Number,'GUAR',StatusBar1);
// HITM
StatusBar1.Panels[0].Text := 'Backing Up HITM...';
StatusBar1.Panels[1].Text := '0';
Application.ProcessMessages;
daapi.LenderBackUp(CurrentLend.Number,'HITM',StatusBar1);
// LDOC
StatusBar1.Panels[0].Text := 'Backing Up LDOC...';
StatusBar1.Panels[1].Text := '0';
Application.ProcessMessages;
daapi.LenderBackUp(CurrentLend.Number,'LDOC',StatusBar1);
// LEND
StatusBar1.Panels[0].Text := 'Backing Up LEND...';
StatusBar1.Panels[1].Text := '0';
Application.ProcessMessages;
daapi.LenderBackUp(CurrentLend.Number,'LEND',StatusBar1);
// LOAN
StatusBar1.Panels[0].Text := 'Backing Up LOAN...';
StatusBar1.Panels[1].Text := '0';
Application.ProcessMessages;
daapi.LenderBackUp(CurrentLend.Number,'LOAN',StatusBar1);
// NCOL
StatusBar1.Panels[0].Text := 'Backing Up NCOL...';
StatusBar1.Panels[1].Text := '0';
Application.ProcessMessages;
daapi.LenderBackUp(CurrentLend.Number,'NCOL',StatusBar1);
// NOTE
StatusBar1.Panels[0].Text := 'Backing Up NOTE...';
StatusBar1.Panels[1].Text := '0';
Application.ProcessMessages;
daapi.LenderBackUp(CurrentLend.Number,'NOTE',StatusBar1);
// PLDG
StatusBar1.Panels[0].Text := 'Backing Up PLDG...';
StatusBar1.Panels[1].Text := '0';
Application.ProcessMessages;
daapi.LenderBackUp(CurrentLend.Number,'PLDG',StatusBar1);
// PROCESS
StatusBar1.Panels[0].Text := 'Backing Up PROCESS...';
StatusBar1.Panels[1].Text := '0';
Application.ProcessMessages;
daapi.LenderBackUp(CurrentLend.Number,'PROCESS',StatusBar1);
// RPTSAVE
StatusBar1.Panels[0].Text := 'Backing Up RPTSAVE...';
StatusBar1.Panels[1].Text := '0';
Application.ProcessMessages;
daapi.LenderBackUp(CurrentLend.Number,'RPTSAVE',StatusBar1);
// TDOC
StatusBar1.Panels[0].Text := 'Backing Up TDOC...';
StatusBar1.Panels[1].Text := '0';
Application.ProcessMessages;
daapi.LenderBackUp(CurrentLend.Number,'TDOC',StatusBar1);
// TITM
StatusBar1.Panels[0].Text := 'Backing Up TITM...';
StatusBar1.Panels[1].Text := '0';
Application.ProcessMessages;
daapi.LenderBackUp(CurrentLend.Number,'TITM',StatusBar1);
// TRAK
StatusBar1.Panels[0].Text := 'Backing Up TRAK...';
StatusBar1.Panels[1].Text := '0';
Application.ProcessMessages;
daapi.LenderBackUp(CurrentLend.Number,'TRAK',StatusBar1);
// UTL
StatusBar1.Panels[0].Text := 'Backing Up UTL...';
StatusBar1.Panels[1].Text := '0';
Application.ProcessMessages;
daapi.LenderBackUp(CurrentLend.Number,'UTL',StatusBar1);
// UTLNOMAT
StatusBar1.Panels[0].Text := 'Backing Up UTLNOMAT...';
StatusBar1.Panels[1].Text := '0';
Application.ProcessMessages;
daapi.LenderBackUp(CurrentLend.Number,'UTLNOMAT',StatusBar1);
StatusBar1.Panels[0].Text := 'Idle';
StatusBar1.Panels[1].Text := '0';
Application.ProcessMessages;
ZipLender.RootDir := Dir(drUpdate);
ZipLender.ZipName := Dir(drExport) + 'BKUP'+CurrentLend.Number+'.zip';
ZipLender.Password := 'ZIPRX';
ZipLender.FilesList.Clear;
ZipLender.FilesList.Add('*.csv');
ZipLender.Zip;
//TIdx := ZipLender.Zip;
end;
procedure TfrmBackup.btnLenderRestoreClick(Sender: TObject);
var
TmpFile: String;
SearchRec : TSearchRec;
filemask : string;
err : integer;
FileList : TStringList;
TIdx : Integer;
TLen : Integer;
TableName : String;
begin
{$IFDEF SERVER}
Flag := 'LR';
btnClose.Click;
Exit;
{$ENDIF}
{$ifdef THINVER}
exit;
{$endif}
TmpFile := dir(drExport)+'BKUP'+CurrentLend.Number+'.zip';
if not fileexists(TmpFile) then
begin
ShowMessage('There is no archive for Lender: '+ CurrentLend.Number);
exit;
end;
StatusBar1.Panels[0].Text := 'Unzipping...';
UnzipLender.ZipName := TmpFile;
UnzipLender.RootDir := dir(drExport);
UnzipLender.DestDir := dir(drUpdate);
UnzipLender.PassWord := 'ZIPRX';
UnzipLender.OverwriteMode := Always;
UnzipLender.FilesList.Add('*');
UnzipLender.UnZip;
FileList := TStringList.Create;
filemask := Dir(drUpdate) + '*.csv';
err := FindFirst(filemask,faAnyFile,SearchRec);
while (err = 0) do
begin
FileList.Add(SearchRec.Name);
err := FindNext(SearchRec);
end;
FindClose(SearchRec);
for TIdx := 0 to FileList.Count-1 do
begin
TLen := length(FileList.Strings[TIdx]);
TableName := copy(FileList.Strings[TIdx],1,TLen-8);
StatusBar1.Panels[0].Text := 'Restoring '+TableName+'...';
StatusBar1.Panels[1].Text := '0';
Application.ProcessMessages;
daapi.LenderRestore(CurrentLend.Number,TableName, StatusBar1);
DeleteFile(Dir(drUpdate)+FileList.Strings[TIdx]);
end;
StatusBar1.Panels[0].Text := 'Idle';
StatusBar1.Panels[1].Text := '0';
Application.ProcessMessages;
FileList.Free;
end;
procedure TfrmBackup.ZipLenderStartZip(Sender: TObject; FName: String;
var ZipHeader: TZipHeaderInfo; var Skip: Boolean);
begin
StatusBar1.Panels[0].Text := 'Zipping...';
StatusBar1.Panels[1].Text := '0';
Application.ProcessMessages;
end;
procedure TfrmBackup.ZipLenderEndZip(Sender: TObject; FName: String;
UncompressedSize, CompressedSize, CurrentZipSize: Integer);
begin
StatusBar1.Panels[0].Text := 'Idle';
StatusBar1.Panels[1].Text := '0';
Application.ProcessMessages;
end;
procedure TfrmBackup.ZipLenderFilePercentDone(Sender: TObject;
Percent: Integer);
begin
StatusBar1.Panels[1].Text := IntToStr(percent);
end;
procedure TfrmBackup.UnzipLenderFilePercentDone(Sender: TObject;
Percent: Integer);
begin
StatusBar1.Panels[1].Text := IntToStr(percent);
end;
procedure TfrmBackup.UnzipLenderStartUnZip(Sender: TObject;
FileIndex: Integer; var FName: String; var Skip: Boolean);
begin
StatusBar1.Panels[0].Text := 'UnZipping...';
StatusBar1.Panels[1].Text := '0';
Application.ProcessMessages;
end;
procedure TfrmBackup.UnzipLenderEndUnZip(Sender: TObject;
FileIndex: Integer; FName: String);
begin
StatusBar1.Panels[0].Text := 'Idle';
StatusBar1.Panels[1].Text := '0';
Application.ProcessMessages;
end;
end.
|
// ***************************************************************************
//
// Delphi MVC Framework
//
// Copyright (c) 2010-2020 Daniele Teti and the DMVCFramework Team
//
// https://github.com/danieleteti/delphimvcframework
//
// ***************************************************************************
//
// 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 MVCFramework.Middleware.ActiveRecord;
{$I dmvcframework.inc}
interface
uses
System.SysUtils,
System.StrUtils,
System.Generics.Collections,
MVCFramework,
MVCFramework.Commons,
MVCFramework.Serializer.Commons;
type
TMVCActiveRecordMiddleware = class(TInterfacedObject, IMVCMiddleware)
private
fConnectionDefName: string;
fConnectionDefFileName: string;
fConnectionLoaded: Boolean;
protected
procedure EnsureConnection;
procedure OnBeforeRouting(
AContext: TWebContext;
var AHandled: Boolean);
procedure OnBeforeControllerAction(
AContext: TWebContext;
const AControllerQualifiedClassName: string;
const AActionName: string;
var AHandled: Boolean
);
procedure OnAfterControllerAction(
AContext: TWebContext;
const AActionName: string;
const AHandled: Boolean
);
procedure OnAfterRouting(
AContext: TWebContext;
const AHandled: Boolean);
public
constructor Create(
const ConnectionDefName: string;
const ConnectionDefFileName: string = 'FDConnectionDefs.ini'); virtual;
end;
implementation
uses
MVCFramework.ActiveRecord,
FireDAC.Comp.Client;
{ TMVCActiveRecordMiddleware }
constructor TMVCActiveRecordMiddleware.Create(const ConnectionDefName: string;
const ConnectionDefFileName: string);
begin
inherited Create;
fConnectionLoaded := False;
fConnectionDefName := ConnectionDefName;
fConnectionDefFileName := ConnectionDefFileName;
end;
procedure TMVCActiveRecordMiddleware.EnsureConnection;
begin
if fConnectionLoaded then
begin
Exit;
end;
// if not FDManager.ConnectionDefFileLoaded then
// begin
FDManager.ConnectionDefFileName := fConnectionDefFileName;
FDManager.ConnectionDefFileAutoLoad := False;
FDManager.LoadConnectionDefFile;
// end;
if not FDManager.IsConnectionDef(fConnectionDefName) then
begin
raise EMVCConfigException.CreateFmt('ConnectionDefName "%s" not found in config file "%s"',
[fConnectionDefName, FDManager.ActualConnectionDefFileName]);
end
else
begin
fConnectionLoaded := True;
end;
end;
procedure TMVCActiveRecordMiddleware.OnAfterControllerAction(
AContext: TWebContext;
const AActionName: string;
const AHandled: Boolean);
begin
// Implement as needed
end;
procedure TMVCActiveRecordMiddleware.OnAfterRouting(AContext: TWebContext; const AHandled: Boolean);
begin
ActiveRecordConnectionsRegistry.RemoveDefaultConnection;
end;
procedure TMVCActiveRecordMiddleware.OnBeforeControllerAction(
AContext: TWebContext;
const AControllerQualifiedClassName, AActionName: string;
var AHandled: Boolean);
begin
// do nothing
end;
procedure TMVCActiveRecordMiddleware.OnBeforeRouting(AContext: TWebContext; var AHandled: Boolean);
var
lConn: TFDConnection;
begin
EnsureConnection;
lConn := TFDConnection.Create(nil);
lConn.ConnectionDefName := fConnectionDefName;
ActiveRecordConnectionsRegistry.AddDefaultConnection(lConn, True);
AHandled := False;
end;
end.
|
unit BatchForwardGeocodeAddressUnit;
interface
uses SysUtils, BaseExampleUnit;
type
TBatchForwardGeocodeAddress = class(TBaseExample)
public
procedure Execute(Address: String);
end;
implementation
uses GeocodingUnit;
procedure TBatchForwardGeocodeAddress.Execute(Address: String);
var
ErrorString: String;
Geocoding: TGeocoding;
begin
Geocoding := Route4MeManager.Geocoding.ForwardGeocodeAddress(Address, ErrorString);
try
WriteLn('');
if (Geocoding <> nil) and
(Geocoding.Latitude.IsNotNull) and (Geocoding.Longitude.IsNotNull) then
begin
WriteLn('BatchForwardGeocodeAddress executed successfully');
WriteLn(Format('Latitude: %f, Longitude: %f',
[Geocoding.Latitude.Value, Geocoding.Longitude.Value]));
end
else
WriteLn(Format('BatchForwardGeocodeAddress error: "%s"', [ErrorString]));
finally
FreeAndNil(Geocoding);
end;
end;
end.
|
{uMyExcel - модуль для выполнения основных операций с MS Excel
Разработчик Vlad
Сайт http://webdelphi.ru
E-mail: vlad383@mail.ru
Описание модуля:
Вся работа ведется через переменную MyExcel
[+] CheckExcelInstall - проверяет установлен ли Excel на компьютре
[+] CheckExcelRun - проверяет есть ил запущенный экземпляр Excel и, если таковой
обнаруживается - получает ссылку на него для дальнейшей работы
[+] RunExcel() - запускает Excel
DisableAlerts - включает/отключает сообщения Excel (рекомендуется
использовать значение по-умолчанию);
Visible - определяет будет ли показано окно Excel после открытия
[+] StopExcel - останавливает Excel без каких-либо сохранений документа
[+] AddWorkBook - добавляет рабочую книгу в запущенном Excel, если параметр
AutoRun=true, то сначала запускает Excel (если он не запущен)
и затем добавляет пустую книгу
[+] GetAllWorkBooks - перечисляет все рабочие книги, которые открыты в данный
момент в Excel в список заносятся полные названия книг
[+] SaveWorkBook - сохраняет рабочую книгу с индексом WBIndex в файл с названием
FileName (индекс первой открытой рабочей книги всегда 1)
[+] OpenWorkBook - открывает файл рабочей книги FileName; Visible - определяет
будет ли окно Excel показано пользователю
}
unit uMyExcel;
interface
uses ComObj, ActiveX, Variants, Windows, Messages, SysUtils, Classes, Db;
const ExcelApp = 'Excel.Application';
type
TDataSetFilterFunction = function (ADataSet: TDataSet; Context: IInterface): Boolean;
function CheckExcelInstall:boolean;
function CheckExcelRun: boolean;
function RunExcel(DisableAlerts:boolean=true; Visible: boolean=false): boolean;
function StopExcel:boolean;
function AddWorkBook(AutoRun:boolean=true):boolean;
function GetAllWorkBooks:TStringList;
function SaveWorkBook(FileName:TFileName; WBIndex:integer):boolean;
function OpenWorkBook(FileName:TFileName; Visible:boolean=true):boolean;
function ExportToExcel(ATemplateFileName: string; ADataSet: TDataSet;
FilterFunction: TDataSetFilterFunction = nil): Boolean;
function ImportFromExcel(AFileName: string; ADataSet: TDataSet;
FilterFunction: TDataSetFilterFunction = nil): Boolean;
var MyExcel: OleVariant;
implementation
uses
Dialogs, ExcelXP, StrUtils, uProgressForm;
function OpenWorkBook(FileName:TFileName; Visible:boolean=true):boolean;
begin
try
MyExcel.WorkBooks.Open(FileName);
MyExcel.Visible:=Visible;
Result:=true;
except
result:=false;
end;
end;
function GetAllWorkBooks:TStringList;
var i:integer;
begin
try
Result:=TStringList.Create;
for i:=1 to MyExcel.WorkBooks.Count do
Result.Add(MyExcel.WorkBooks.Item[i].FullName)
except
MessageBox(0,'Ошибка перечисления открытых книг','Ошибка',MB_OK+MB_ICONERROR);
end;
end;
function SaveWorkBook(FileName:TFileName; WBIndex:integer):boolean;
begin
try
MyExcel.WorkBooks.Item[WBIndex].SaveAs(FileName);
if MyExcel.WorkBooks.Item[WBIndex].Saved then
Result:=true
else
Result:=false;
except
Result:=false;
end;
end;
function AddWorkBook(AutoRun:boolean=true):boolean;
begin
if CheckExcelRun then
begin
MyExcel.WorkBooks.Add;
Result:=true;
end
else
if AutoRun then
begin
RunExcel;
MyExcel.WorkBooks.Add;
Result:=true;
end
else
Result:=false;
end;
function CheckExcelInstall:boolean;
var
ClassID: TCLSID;
Rez : HRESULT;
begin
// Ищем CLSID OLE-объекта
Rez := CLSIDFromProgID(PWideChar(WideString(ExcelApp)), ClassID);
if Rez = S_OK then // Объект найден
Result := true
else
Result := false;
end;
function CheckExcelRun: boolean;
begin
try
MyExcel:=GetActiveOleObject(ExcelApp);
Result:=True;
except
Result:=false;
end;
end;
function RunExcel(DisableAlerts:boolean=true; Visible: boolean=false): boolean;
begin
try
{проверяем установлен ли Excel}
if CheckExcelInstall then
begin
MyExcel:=CreateOleObject(ExcelApp);
//показывать/не показывать системные сообщения Excel (лучше не показывать)
MyExcel.Application.EnableEvents:=DisableAlerts;
MyExcel.Visible:=Visible;
Result:=true;
end
else
begin
MessageBox(0,'Приложение MS Excel не установлено на этом компьютере', 'Ошибка', MB_OK+MB_ICONERROR);
Result:=false;
end;
except
Result:=false;
end;
end;
function StopExcel:boolean;
begin
try
if MyExcel.Visible then MyExcel.Visible:=false;
MyExcel.Quit;
MyExcel:=Unassigned;
Result:=True;
except
Result:=false;
end;
end;
function FillColumnsFields(ColumnsFields: TList;
const ws: Variant; ADataSet: TDataSet): Integer;
var
Cols: Integer;
ColumnTitle: string;
Field: TField;
I: Integer;
ColIndex: Integer;
Rows: Integer;
begin
ColumnsFields.Clear;
Rows := ws.UsedRange.Rows.Count;
Cols := ws.UsedRange.Columns.Count;
Result := Rows;
for I := 1 to Rows do
begin
if VarToStr(ws.UsedRange.Cells[I, Cols].Value) <> EmptyStr then
begin
Result := I;
Break;
end;
end;
for ColIndex := 1 to Cols do
begin
ColumnsFields.Add(nil);
ColumnTitle := VarToStr(ws.UsedRange.Cells[Result, ColIndex].Value);
if ColumnTitle <> EmptyStr then
begin
for I := 0 to ADataSet.FieldCount-1 do
begin
Field := ADataSet.Fields[I];
if AnsiStartsText(Field.DisplayLabel, ColumnTitle)
or AnsiSameText(Field.FieldName, ColumnTitle) then
begin
ColumnsFields[ColumnsFields.Count-1] := Field;
end;
end;
end;
end;
end;
function ExportToExcel(ATemplateFileName: string; ADataSet: TDataSet;
FilterFunction: TDataSetFilterFunction = nil): Boolean;
var
Cols: Integer;
ColumnsFields: TList;
ColumnTitle: string;
I, J: integer;
FData: Variant;
Field: TField;
Range: Variant;
ws: Variant;
wb: Variant;
HeaderRowIndex: Integer;
begin
ColumnsFields := TList.Create();
Result := False;
if ADataSet.Active then
begin
if FileExists(ATemplateFileName) then
begin
RunExcel();
wb := MyExcel.Workbooks.Add(ATemplateFileName);
ws := wb.Worksheets[1];
Cols := ws.UsedRange.Columns.Count;
FData := VarArrayCreate([1, ADataSet.RecordCount, 1, Cols], varVariant);
HeaderRowIndex := FillColumnsFields(ColumnsFields, ws, ADataSet);
ADataSet.DisableControls;
ADataSet.First;
I := 1;
while not ADataSet.Eof do
begin
if not Assigned(FilterFunction) or FilterFunction(ADataSet, nil) then
begin
for J := 1 to Cols do
begin
Field := TField(ColumnsFields[J-1]);
if (Field <> nil) then
FData[I, J] := Field.Value;
end;
Inc(I);
end;
ADataSet.Next;
end;
ADataSet.First;
ADataSet.EnableControls;
ws.Activate;
Range := ws.Range[ws.Cells[HeaderRowIndex + 1, 1],
ws.Cells[HeaderRowIndex + I - 1, VarArrayHighBound(FData, 2)]];
Range.Value:=FData;
MyExcel.Visible:=True;
Result := True;
end
else
MessageDlg(Format('Файл шаблона "%s" не найден', [ATemplateFileName]),
mtError, [mbOk], 0);
end
else
MessageDlg('Набор данных закрыт', mtError, [mbOk], 0);
ColumnsFields.Free;
end;
function ImportFromExcel(AFileName: string; ADataSet: TDataSet;
FilterFunction: TDataSetFilterFunction = nil): Boolean;
var
Cols: Integer;
ColumnsFields: TList;
ColumnTitle: string;
I, J: integer;
FData: Variant;
Field: TField;
Range: Variant;
ws: Variant;
wb: Variant;
HeaderRowIndex: Integer;
N: Integer;
RowIndex: Integer;
Rows: Integer;
begin
ColumnsFields := TList.Create();
Result := False;
if ADataSet.Active then
begin
if FileExists(AFileName) then
begin
RunExcel();
wb := MyExcel.Workbooks.Open(AFileName);
ws := wb.Worksheets[1];
ShowProgress('Загрузка данных. Ждите ...', 0, 100, False);
Cols := ws.UsedRange.Columns.Count;
Rows := ws.UsedRange.Rows.Count;
FData := ws.UsedRange.Value;
HeaderRowIndex := FillColumnsFields(ColumnsFields, ws, ADataSet);
ADataSet.DisableControls;
N := Rows - HeaderRowIndex ;
for I := 0 to N-1 do
begin
RowIndex := I + HeaderRowIndex + 1;
if I mod (N div 10) = 0 then
begin
if not ShowProgress(Format('Импорт данных из Excel. ' +
'Загружено %d из %d записей', [I, N]), I, N) then
Break;
end;
ADataSet.Append;
for J := 0 to ColumnsFields.Count-1 do
begin
Field := TField(ColumnsFields[J]);
if (Field <> nil) and (Field.CanModify) then
begin
Field.Value := FData[RowIndex, J+1];
end;
end;
if not Assigned(FilterFunction) or FilterFunction(ADataSet, nil) then
ADataSet.Post
else
ADataSet.Cancel;
end;
ADataSet.First;
ADataSet.EnableControls;
wb.Close();
StopExcel;
Result := True;
end
else
MessageDlg(Format('Файл "%s" не найден', [AFileName]),
mtError, [mbOk], 0);
end
else
MessageDlg('Набор данных закрыт', mtError, [mbOk], 0);
HideProgress;
ColumnsFields.Free;
end;
end.
|
unit K607751255;
{* [RequestLink:607751255] }
// Модуль: "w:\common\components\rtl\Garant\Daily\K607751255.pas"
// Стереотип: "TestCase"
// Элемент модели: "K607751255" MUID: (56124E780397)
// Имя типа: "TK607751255"
{$Include w:\common\components\rtl\Garant\Daily\TestDefine.inc.pas}
interface
{$If Defined(nsTest) AND NOT Defined(NoScripts)}
uses
l3IntfUses
, EVDtoBothNSRCWriterTest
;
type
TK607751255 = class(TEVDtoBothNSRCWriterTest)
{* [RequestLink:607751255] }
protected
function GetFolder: AnsiString; override;
{* Папка в которую входит тест }
function GetModelElementGUID: AnsiString; override;
{* Идентификатор элемента модели, который описывает тест }
end;//TK607751255
{$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts)
implementation
{$If Defined(nsTest) AND NOT Defined(NoScripts)}
uses
l3ImplUses
, TestFrameWork
//#UC START# *56124E780397impl_uses*
//#UC END# *56124E780397impl_uses*
;
function TK607751255.GetFolder: AnsiString;
{* Папка в которую входит тест }
begin
Result := '7.12';
end;//TK607751255.GetFolder
function TK607751255.GetModelElementGUID: AnsiString;
{* Идентификатор элемента модели, который описывает тест }
begin
Result := '56124E780397';
end;//TK607751255.GetModelElementGUID
initialization
TestFramework.RegisterTest(TK607751255.Suite);
{$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts)
end.
|
unit uCadastraUsuario;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Objects,
FMX.Controls.Presentation, FMX.StdCtrls, FMX.Layouts, FMX.Edit, FMX.ListBox,
FMX.MediaLibrary.Actions, System.Actions, FMX.ActnList, FMX.StdActns,
System.ImageList, FMX.ImgList, FMX.Ani, System.IOUtils;
type
TFCadastraUsuario = class(TForm)
LayoutCliente: TLayout;
ToolBar1: TToolBar;
Rectangle1: TRectangle;
SpeedButton1: TSpeedButton;
Rectangle2: TRectangle;
GridPanelLayout1: TGridPanelLayout;
Rectangle3: TRectangle;
Image1: TImage;
Rectangle4: TRectangle;
Label1: TLabel;
Rectangle5: TRectangle;
Label2: TLabel;
Rectangle6: TRectangle;
Label3: TLabel;
Rectangle7: TRectangle;
SpeedButton2: TSpeedButton;
Rectangle8: TRectangle;
edtUsuario: TEdit;
edtSenha: TEdit;
edtEmail: TEdit;
lstPopup: TListBox;
ActionList1: TActionList;
actSelFotoDaBiblioteca: TTakePhotoFromLibraryAction;
actSelFotoDaCamera: TTakePhotoFromCameraAction;
lsItemCamera: TListBoxItem;
lstitemBiblioteca: TListBoxItem;
ListBoxItem3: TListBoxItem;
lstitemCancelar: TListBoxItem;
ImageList1: TImageList;
procedure SpeedButton1Click(Sender: TObject);
procedure actSelFotoDaBibliotecaDidFinishTaking(Image: TBitmap);
procedure actSelFotoDaCameraDidFinishTaking(Image: TBitmap);
procedure lsItemCameraClick(Sender: TObject);
procedure lstitemBibliotecaClick(Sender: TObject);
procedure Image1Click(Sender: TObject);
procedure lstitemCancelarClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormVirtualKeyboardShown(Sender: TObject;
KeyboardVisible: Boolean; const Bounds: TRect);
procedure FormVirtualKeyboardHidden(Sender: TObject;
KeyboardVisible: Boolean; const Bounds: TRect);
procedure SpeedButton2Click(Sender: TObject);
private
{ Private declarations }
FTecladoShow : Boolean;
procedure HidePopup;
procedure ShowPopup;
public
{ Public declarations }
end;
var
FCadastraUsuario: TFCadastraUsuario;
implementation
{$R *.fmx}
{$R *.NmXhdpiPh.fmx ANDROID}
uses uLogin, uCRUDUsuario, uDMPrincipal;
procedure TFCadastraUsuario.actSelFotoDaBibliotecaDidFinishTaking(
Image: TBitmap);
begin
Image1.Bitmap.Assign(Image);
end;
procedure TFCadastraUsuario.actSelFotoDaCameraDidFinishTaking(Image: TBitmap);
begin
Image1.Bitmap.Assign(Image);
end;
procedure TFCadastraUsuario.FormCreate(Sender: TObject);
begin
lstPopUp.Visible := False;
end;
procedure TFCadastraUsuario.FormVirtualKeyboardHidden(Sender: TObject;
KeyboardVisible: Boolean; const Bounds: TRect);
begin
FTecladoShow := false;
if not KeyboardVisible then
AnimateFloat('Padding.Top', 0, 0.1);
end;
procedure TFCadastraUsuario.FormVirtualKeyboardShown(Sender: TObject;
KeyboardVisible: Boolean; const Bounds: TRect);
var
O: TFMXObject;
begin
FTecladoShow := true;
if Assigned(Focused) and (Focused.GetObject is TControl) then
if TControl(Focused).AbsoluteRect.Bottom - Padding.Top >= (Bounds.Top - ToolBar1.Height) then
begin
//If switching between controls, the KeyboardHidden animation will run first
//and we'll see the form scroll up and then down.
//Calling StopPropertyAnimation jumps the first animation to it's final value - same problem
//Instead we need to search for the other animation and call StopAtCurrent.
for O in Children do
if (O is TFloatAnimation) and (TFloatAnimation(O).PropertyName = 'Padding.Top') then
TFloatAnimation(O).StopAtCurrent;
//AnimateFloat
AnimateFloat('Padding.Top',Bounds.Top - ToolBar1.Height - TControl(Focused).AbsoluteRect.Bottom + Padding.Top, 0.1)
end
else
else
AnimateFloat('Padding.Top', 0, 0.1);
end;
procedure TFCadastraUsuario.lsItemCameraClick(Sender: TObject);
begin
HidePopup;
actSelFotoDaCamera.ExecuteTarget(Sender);
end;
procedure TFCadastraUsuario.lstitemBibliotecaClick(Sender: TObject);
begin
HidePopup;
actSelFotoDaBiblioteca.ExecuteTarget(Sender);
end;
procedure TFCadastraUsuario.lstitemCancelarClick(Sender: TObject);
begin
HidePopup;
end;
procedure TFCadastraUsuario.SpeedButton1Click(Sender: TObject);
begin
FLogin.AbrirForm(TFLogin);
end;
procedure TFCadastraUsuario.SpeedButton2Click(Sender: TObject);
var
vloCRUDUsuaio : TCRUDUsuario;
begin
vloCRUDUsuaio := TCRUDUsuario.Create;
try
vloCRUDUsuaio.Usua_Nome := edtUsuario.Text;
vloCRUDUsuaio.Usua_Email := edtEmail.Text;
vloCRUDUsuaio.Usua_Imagem := '';
vloCRUDUsuaio.Usua_Senha := edtSenha.Text;
if not vloCRUDUsuaio.GravarDados then
ShowMessage('Houve um erro para Grava o Usuário.')
else
begin
edtUsuario.Text := '';
edtEmail.Text := '';
edtSenha.Text := '';
ShowMessage('Usuário Salvo com sucesso!');
FLogin.AbrirForm(TFLogin);
end;
finally
FreeAndNil(vloCRUDUsuaio);
end;
end;
procedure TFCadastraUsuario.HidePopup;
begin
lstPopUp.AnimateFloat('position.y', lstPopUp.Height * -1);
lstPopUp.Visible := False;
end;
procedure TFCadastraUsuario.Image1Click(Sender: TObject);
begin
ShowPopup;
end;
procedure TFCadastraUsuario.ShowPopup;
begin
lstPopUp.Visible := True;
lstPopUp.AnimateFloat('position.y', lstPopup.Width - 70);
lstPopUp.BringToFront;
end;
end.
|
unit SFXAutoRun;
interface
uses
SysUtils, Windows, IniFiles, ShellAPI;
type
TExecuteSFXAutoRunResult = record
AutoRunSectionAvailable: boolean;
ExecutionSucceed: boolean;
HInstance: Integer;
OpenUnzippedContent: boolean;
end;
function ExecuteSFXAutoRun(ADirectory: string): TExecuteSFXAutoRunResult;
implementation
function StrToShowCmd(s: String): Integer;
begin
s := UpperCase(s);
if s = 'SW_HIDE' then
result := SW_HIDE
else if s = 'SW_MAXIMIZE' then
result := SW_MAXIMIZE
else if s = 'SW_MINIMIZE' then
result := SW_MINIMIZE
else if s = 'SW_RESTORE' then
result := SW_RESTORE
else if s = 'SW_SHOW' then
result := SW_SHOW
else if s = 'SW_SHOWDEFAULT' then
result := SW_SHOWDEFAULT
else if s = 'SW_SHOWMAXIMIZED' then
result := SW_SHOWMAXIMIZED
else if s = 'SW_SHOWMINIMIZED' then
result := SW_SHOWMINIMIZED
else if s = 'SW_SHOWMINNOACTIVE' then
result := SW_SHOWMINNOACTIVE
else if s = 'SW_SHOWNA' then
result := SW_SHOWNA
else if s = 'SW_SHOWNOACTIVATE' then
result := SW_SHOWNOACTIVATE
else if s = 'SW_SHOWNORMAL' then
result := SW_SHOWNORMAL
else
result := -1;
end;
function ExecuteSFXAutoRun(ADirectory: string): TExecuteSFXAutoRunResult;
var
x: TIniFile;
Operation, FileName, Parameters, Directory, ShowCmd: string;
XShowCmd: Integer;
XOperation, XFileName, XParameters, XDirectory: PChar;
const
AR = 'AutoRun.inf';
Section = 'AutoSFX';
begin
result.AutoRunSectionAvailable := false;
result.ExecutionSucceed := false;
result.HInstance := -1;
result.OpenUnzippedContent := true;
if not DirectoryExists(ADirectory) then Exit;
ADirectory := IncludeTrailingPathDelimiter(ADirectory);
if not FileExists(ADirectory + AR) then Exit;
x := TIniFile.Create(ADirectory + AR);
try
if not x.SectionExists(Section) then Exit;
result.AutoRunSectionAvailable := true;
Operation := x.ReadString(Section, 'Operation', 'open');
FileName := x.ReadString(Section, 'FileName', '');
if FileName = '' then Exit;
Parameters := x.ReadString(Section, 'Parameters', '');
Directory := x.ReadString(Section, 'Directory', '');
ShowCmd := x.ReadString(Section, 'ShowCmd', 'SW_NORMAL');
if UpperCase(Operation) = 'NULL' then
begin
XOperation := nil
end
else
begin
XOperation := PChar(Operation);
end;
XFileName := PChar(FileName);
XParameters := PChar(Parameters);
XDirectory := PChar(Directory);
XShowCmd := StrToShowCmd(ShowCmd);
// Since our application will now terminate, I let the handle be 0.
result.HInstance := ShellExecute(0, XOperation, XFileName, XParameters, XDirectory, XShowCmd);
result.ExecutionSucceed := result.HInstance > 32;
result.OpenUnzippedContent := x.ReadBool(Section, 'OpenUnzippedContent', true)
finally
x.Free;
end;
end;
end.
|
unit nsExternalObjectData;
(*-----------------------------------------------------------------------------
Название: nsExternalObjectData
Автор: Лукьянец Р. В.
Назначение: Реализация интерфайса InsLinkedObjectData для IExternalObject
Версия:
$Id: nsExternalObjectData.pas,v 1.10 2014/01/15 12:57:42 kostitsin Exp $
История:
$Log: nsExternalObjectData.pas,v $
Revision 1.10 2014/01/15 12:57:42 kostitsin
{requestlink: 451251129}
Revision 1.9 2009/08/04 11:25:42 lulin
[$159351827].
Revision 1.8 2009/07/31 17:29:55 lulin
- убираем мусор.
Revision 1.7 2009/07/31 10:25:12 oman
- new: {RequestLink:158795599}
Revision 1.6 2009/07/31 09:43:23 oman
- new: {RequestLink:158795599}
Revision 1.5 2009/02/10 18:11:59 lulin
- <K>: 133891247. Выделяем интерфейсы работы с документом.
Revision 1.4 2008/12/12 19:19:09 lulin
- <K>: 129762414.
Revision 1.3 2008/01/10 07:23:30 oman
Переход на новый адаптер
Revision 1.2.4.1 2007/11/22 10:50:08 oman
Перепиливаем на новый адаптер
Revision 1.2 2007/09/28 07:03:07 mmorozov
- небольшой рефакторинг _StdRes и _nsSaveDialog;
- разделяем получение имени файла для диалогов сохранения и временных файлов + сопутствующий рефакторинг (в рамках работы над CQ: OIT5-26809);
Revision 1.1 2007/07/11 10:05:35 oman
- new: Показ информации о графическом объекте - передаем всю
нужную информацию (cq24711)
-----------------------------------------------------------------------------*)
interface
uses
l3Interfaces,
l3Types,
l3IID,
nevNavigation,
vcmBase,
DocumentDomainInterfaces,
ExternalObjectUnit
;
type
TnsExternalObjectData = class(TvcmBase, InsLinkedObjectData)
protected
// InsLinkedObjectData
function pm_GetObjectTitle: Il3CString;
{-}
function pm_GetFileName: Il3CString;
{-}
function pm_GetWindowCaption: Il3CString;
{-}
function pm_GetData: IStream;
{-}
function pm_GetDescription: InsLinkedObjectDescription;
{-}
function Get_IsPicture: Boolean;
{-}
private
f_Description: InsLinkedObjectDescription;
f_Object: IExternalObject;
f_Stream: IStream;
protected
procedure Cleanup;
override;
{-}
public
constructor Create(const aHyperLink: IevHyperLink;
const aObject: IExternalObject);
reintroduce;
{-}
class function Make(const aHyperLink: IevHyperLink;
const aObject: IExternalObject): InsLinkedObjectData;
reintroduce;
{-}
function COMQueryInterface(const IID: Tl3GUID; out Obj): Tl3HResult;
override;
{-}
end;
implementation
uses
Classes,
l3Stream,
l3Memory,
l3Base,
k2Interfaces,
k2Tags,
StdRes,
nsTypes,
nsLinkedObjectDescription,
nsExternalObject,
nsExternalObjectPrim
;
{ TnsExternalObjectData }
procedure TnsExternalObjectData.Cleanup;
begin
f_Stream := nil;
f_Description := nil;
f_Object := nil;
inherited Cleanup;
end;
function TnsExternalObjectData.COMQueryInterface(const IID: Tl3GUID;
out Obj): Tl3HResult;
begin
Result := inherited COMQueryInterface(IID, Obj);
if Result.Fail then
if IID.EQ(IExternalObject) then
begin
IExternalObject(Obj) := f_Object;
Result.SetOK;
end;//if IID.EQ(IExternalObject) then
end;
constructor TnsExternalObjectData.Create(const aHyperLink: IevHyperLink;
const aObject: IExternalObject);
var
l_Stream : TnsExternalObjectStream;
begin
inherited Create;
f_Object := aObject;
with aHyperLink do
f_Description := TnsLinkedObjectDescription.Make(nsCStr(Hint),
nsCStr(Name),
TargetDocumentID);
l_Stream := TnsExternalObjectStream.Create(f_Object);
try
f_Stream := l3Stream2IStream(l_Stream);
finally
vcmFree(l_Stream);
end;
end;
function TnsExternalObjectData.Get_IsPicture: Boolean;
begin
Result := f_Object.GetDataType = EOT_PIC;
end;
class function TnsExternalObjectData.Make(const aHyperLink: IevHyperLink;
const aObject: IExternalObject): InsLinkedObjectData;
var
l_Instance: TnsExternalObjectData;
begin
l_Instance := Create(aHyperLink, aObject);
try
Result := l_Instance;
finally
vcmFree(l_Instance);
end;
end;
function TnsExternalObjectData.pm_GetData: IStream;
begin
Result := f_Stream;
end;
function TnsExternalObjectData.pm_GetDescription: InsLinkedObjectDescription;
begin
Result := f_Description;
end;
function TnsExternalObjectData.pm_GetFileName: Il3CString;
begin
Result := nsPrepareFileName(pm_GetObjectTitle);
end;
function TnsExternalObjectData.pm_GetObjectTitle: Il3CString;
begin
Result := nsGetExternalObjectName(f_Object);
end;
function TnsExternalObjectData.pm_GetWindowCaption: Il3CString;
begin
Result := vcmFmt(str_pncSimplePicture, [pm_GetObjectTitle])
end;
end.
|
{ Subroutine SST_W_C_IMPLICIT_CONST (DTYPE,VAL,SYM_P)
*
* Create or reuse an implicit variable with a constant value. If an
* implicit variable exists with the same data type and value, then it
* is reused. Otherwise, a new variable is created.
}
module sst_w_c_IMPLICIT_CONST;
define sst_w_c_implicit_const;
%include 'sst_w_c.ins.pas';
procedure sst_w_c_implicit_const ( {create/reuse implicit constant variable}
in dtype: sst_dtype_t; {data type descriptor for variable}
in val: sst_var_value_t; {descriptor for variable's value}
out sym_p: sst_symbol_p_t); {returned pointing to reused/new variable}
const
max_msg_parms = 1; {max parameters we can pass to a message}
var
dt_p: sst_dtype_p_t; {points to base data type}
exp_p: sst_exp_p_t; {points to value expression for new variable}
msg_parm: {parameter references for messages}
array[1..max_msg_parms] of sys_parm_msg_t;
label
next_sym;
begin
dt_p := addr(dtype); {resolve base data type of variable}
while dt_p^.dtype = sst_dtype_copy_k do dt_p := dt_p^.copy_dtype_p;
sym_p := frame_scope_p^.const_p; {init curr symbol to first const implicit var}
while sym_p <> nil do begin {look thru all the existing const impl vars}
if sym_p^.var_dtype_p <> dt_p {data types don't match ?}
then goto next_sym;
if sym_p^.var_val_p = nil {doesn't have init val ? (shouldn't happen)}
then goto next_sym;
if not sym_p^.var_val_p^.val_fnd {init val not const ? (shouldn't happen)}
then goto next_sym;
with sym_p^.var_val_p^.val: symval do begin {SYMVAL is symbol's value descriptor}
if symval.dtype <> val.dtype {const value data types don't match ?}
then goto next_sym;
case val.dtype of
sst_dtype_int_k: begin
if symval.int_val <> val.int_val then goto next_sym;
end;
sst_dtype_enum_k: begin
if symval.enum_p <> val.enum_p then goto next_sym;
end;
sst_dtype_float_k: begin
if symval.float_val <> val.float_val then goto next_sym;
end;
sst_dtype_bool_k: begin
if symval.bool_val <> val.bool_val then goto next_sym;
end;
sst_dtype_char_k: begin
if symval.char_val <> val.char_val then goto next_sym;
end;
sst_dtype_array_k: begin
if not string_equal(symval.ar_str_p^, val.ar_str_p^) then goto next_sym;
end;
sst_dtype_set_k: begin
goto next_sym; {set values not implemented yet}
end;
sst_dtype_pnt_k: begin
if symval.pnt_dtype_p <> val.pnt_dtype_p then goto next_sym;
if symval.pnt_exp_p <> val.pnt_exp_p then goto next_sym;
end;
otherwise
sys_msg_parm_int (msg_parm[1], ord(val.dtype));
sys_message_bomb ('sst', 'dtype_unexpected', msg_parm, 1);
end;
end; {done with SYMVAL abbreviation}
return; {SYM_P is pointing to reused variable}
next_sym: {jump here if curr symbol not reusable}
sym_p := sym_p^.next_p; {advance to next symbol in chain}
end; {back and test this new symbol in chain}
{
* None of the existing symbols matched the requirements for the new symbol.
* Now create a new implicit variable.
}
sst_sym_var_new_out ( {create variable and install in symbol table}
dt_p^, {data type of new variable}
sym_p); {returned pointing to new var descriptor}
sst_mem_alloc_scope (sizeof(exp_p^), exp_p); {allocate mem for exp descriptor}
exp_p^.str_h.first_char.crange_p := nil; {fill in const val expression descriptor}
exp_p^.str_h.first_char.ofs := 0;
exp_p^.str_h.last_char.crange_p := nil;
exp_p^.str_h.last_char.ofs := 0;
exp_p^.dtype_p := dt_p;
exp_p^.dtype_hard := true;
exp_p^.val_eval := true;
exp_p^.val_fnd := true;
exp_p^.val := val;
exp_p^.rwflag := [sst_rwflag_read_k];
exp_p^.term1.next_p := nil;
exp_p^.term1.op2 := sst_op2_none_k;
exp_p^.term1.op1 := sst_op1_none_k;
exp_p^.term1.ttype := sst_term_const_k;
exp_p^.term1.str_h := exp_p^.str_h;
exp_p^.term1.dtype_p := dt_p;
exp_p^.term1.dtype_hard := true;
exp_p^.term1.val_eval := true;
exp_p^.term1.val_fnd := true;
exp_p^.term1.val := val;
exp_p^.term1.rwflag := [sst_rwflag_read_k];
sym_p^.var_val_p := exp_p; {set expression as variable's initial value}
sym_p^.flags := sym_p^.flags + [sst_symflag_static_k]; {flag variable as static}
sst_w_c_symbol (sym_p^); {declare variable and set initial value}
sym_p^.next_p := frame_scope_p^.const_p; {link new var onto const impl var chain}
frame_scope_p^.const_p := sym_p;
end;
|
unit DW.UIHelper.iOS;
{*******************************************************}
{ }
{ Kastri Free }
{ }
{ DelphiWorlds Cross-Platform Library }
{ }
{*******************************************************}
{$I DW.GlobalDefines.inc}
interface
uses
// RTL
System.Types,
// FMX
FMX.Types;
type
/// <summary>
/// Helper functions specific to UI
/// </summary>
TPlatformUIHelper = record
public
/// <summary>
/// Special function for handling of "notch" based devices
/// </summary>
class function GetOffsetRect: TRectF; overload; static;
class function GetOffsetRect(const AHandle: TWindowHandle): TRectF; overload; static;
end;
implementation
uses
// RTL
System.SysUtils,
// Mac
Macapi.ObjectiveC, Macapi.Helpers,
// iOS
iOSapi.UIKit, iOSapi.Foundation,
// FMX
FMX.Forms, FMX.Platform.iOS;
type
UIView = interface(iOSapi.UIKit.UIView)
['{9E246E80-7773-400C-8027-9FF0FA6FFA3E}']
function safeAreaInsets: UIEdgeInsets; cdecl;
end;
TUIView = class(TOCGenericImport<UIViewClass, UIView>) end;
class function TPlatformUIHelper.GetOffsetRect: TRectF;
begin
Result := TRectF.Empty;
if Application.MainForm <> nil then
Result := GetOffsetRect(Application.MainForm.Handle);
end;
class function TPlatformUIHelper.GetOffsetRect(const AHandle: TWindowHandle): TRectF;
var
LInsets: UIEdgeInsets;
begin
Result := TRectF.Empty;
if TOSVersion.Check(11) and (AHandle <> nil) then
begin
LInsets := TUIView.Wrap(NSObjectToID(WindowHandleToPlatform(AHandle).View)).safeAreaInsets;
Result := RectF(LInsets.left, LInsets.top, LInsets.right, LInsets.bottom);
end;
end;
end.
|
{ Subroutine SST_R_PAS_SMENT_DEFINE
*
* Process DEFINE_STATEMENT syntax. The tag for this syntax has just been read.
* This statement indicates that the named symbol will be globally know to the
* binder, and will be defined here.
}
module sst_r_pas_SMENT_DEFINE;
define sst_r_pas_sment_define;
%include 'sst_r_pas.ins.pas';
procedure sst_r_pas_sment_define; {process DEFINE_STATEMENT syntax}
const
max_msg_parms = 2; {max parameters we can pass to a message}
var
tag: sys_int_machine_t; {syntax tag ID}
str_h: syo_string_t; {handle to string associated with TAG}
sym_p: sst_symbol_p_t; {points to descriptor for this symbol}
lnum: sys_int_machine_t; {input file line number}
fnam: string_treename_t; {input file name}
msg_parm: {parameter references for messages}
array[1..max_msg_parms] of sys_parm_msg_t;
stat: sys_err_t; {completion status code}
label
leave;
begin
fnam.max := sizeof(fnam.str); {init local var string}
syo_level_down; {down into DEFINE_STATEMENT syntax}
syo_get_tag_msg ( {get tag for symbol name}
tag, str_h, 'sst_pas_read', 'define_statement_bad', nil, 0);
sst_symbol_new ( {make new symbol or find old sym descriptor}
str_h, syo_charcase_asis_k, sym_p, stat);
sym_p^.flags := sym_p^.flags + {flag symbol as globally known}
[sst_symflag_global_k, sst_symflag_used_k];
sym_p^.flags := sym_p^.flags - {symbol lives right here}
[sst_symflag_extern_k];
syo_get_tag_msg ( {get tag for optional initial value}
tag, str_h, 'sst_pas_read', 'define_statement_bad', nil, 0);
if tag = syo_tag_end_k then goto leave; {no optional initial value present ?}
{
* An initial value was supplied for this symbol. It had better be a
* variable with no previous initial value. TAG is for the
* VAR_INITIALIZER syntax.
}
if
(sym_p^.symtype <> sst_symtype_var_k) or else {symbol not a variable ?}
(sym_p^.var_proc_p <> nil) {dummy argument or function return value ?}
then begin
syo_error (str_h, 'sst_pas_read', 'initial_value_not_var', nil, 0);
end;
if sym_p^.var_val_p <> nil then begin {already has an initial value ?}
sst_charh_info ( {find where initial value was declared}
sym_p^.var_val_p^.str_h.first_char, {handle to first char of previous init val}
fnam, {file name of previous initial value}
lnum); {line number of previous initial value}
sys_msg_parm_int (msg_parm[1], lnum);
sys_msg_parm_vstr (msg_parm[2], fnam);
syo_error (str_h, 'sst_pas_read', 'initial_value_already', msg_parm, 2);
end;
if sym_p^.var_dtype_p = nil then begin {this variable has no data type yet ?}
syo_error (str_h, 'sst_pas_read', 'initial_value_no_dtype', nil, 0);
end;
{
* Done error checking. Everything looks OK for giving this variable an
* initial value.
}
sst_r_pas_var_init ( {process VAR_INITIALIZER syntax}
sym_p^.var_dtype_p^, {data type initial value must conform to}
sym_p^.var_val_p); {returned pointer to initial value expression}
leave: {common exit point}
syo_level_up; {back up to caller's syntax level}
end;
|
unit kwMainFormFormClose;
{* Эмулирует выполнение FormClose главной формы, возращая после выполнения все в исходное состояние.
Формат:
[code]
MainForm:FormClose
[code] }
// Модуль: "w:\archi\source\projects\Archi\Archi_Insider_Test_Support\kwMainFormFormClose.pas"
// Стереотип: "ScriptKeyword"
// Элемент модели: "MainForm_FormClose" MUID: (53EB19070285)
// Имя типа: "TkwMainFormFormClose"
{$Include w:\archi\source\projects\Archi\arDefine.inc}
interface
{$If Defined(nsTest) AND Defined(InsiderTest) AND Defined(AppClientSide) AND NOT Defined(NoScripts)}
uses
l3IntfUses
, tfwRegisterableWord
, tfwScriptingInterfaces
;
type
TkwMainFormFormClose = {final} class(TtfwRegisterableWord)
{* Эмулирует выполнение FormClose главной формы, возращая после выполнения все в исходное состояние.
Формат:
[code]
MainForm:FormClose
[code] }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
end;//TkwMainFormFormClose
{$IfEnd} // Defined(nsTest) AND Defined(InsiderTest) AND Defined(AppClientSide) AND NOT Defined(NoScripts)
implementation
{$If Defined(nsTest) AND Defined(InsiderTest) AND Defined(AppClientSide) AND NOT Defined(NoScripts)}
uses
l3ImplUses
, arArchiTestAdapter2
//#UC START# *53EB19070285impl_uses*
//#UC END# *53EB19070285impl_uses*
;
class function TkwMainFormFormClose.GetWordNameForRegister: AnsiString;
begin
Result := 'MainForm:FormClose';
end;//TkwMainFormFormClose.GetWordNameForRegister
procedure TkwMainFormFormClose.DoDoIt(const aCtx: TtfwContext);
//#UC START# *4DAEEDE10285_53EB19070285_var*
//#UC END# *4DAEEDE10285_53EB19070285_var*
begin
//#UC START# *4DAEEDE10285_53EB19070285_impl*
AcMainFormFormClose;
//#UC END# *4DAEEDE10285_53EB19070285_impl*
end;//TkwMainFormFormClose.DoDoIt
initialization
TkwMainFormFormClose.RegisterInEngine;
{* Регистрация MainForm_FormClose }
{$IfEnd} // Defined(nsTest) AND Defined(InsiderTest) AND Defined(AppClientSide) AND NOT Defined(NoScripts)
end.
|
unit NotificationToastExport_TLB;
// ************************************************************************ //
// WARNING
// -------
// The types declared in this file were generated from data read from a
// Type Library. If this type library is explicitly or indirectly (via
// another type library referring to this type library) re-imported, or the
// 'Refresh' command of the Type Library Editor activated while editing the
// Type Library, the contents of this file will be regenerated and all
// manual modifications will be lost.
// ************************************************************************ //
// $Rev: 52393 $
// File generated on 18.09.2019 15:35:03 from Type Library described below.
// ************************************************************************ //
// Type Lib: Z:\NotificationToast\source\d10\dll\NotificationToastExport (1)
// LIBID: {A9D3FDA7-06F6-4BB5-928F-9499145D453D}
// LCID: 0
// Helpfile:
// HelpString:
// DepndLst:
// (1) v2.0 stdole, (C:\Windows\SysWOW64\stdole2.tlb)
// SYS_KIND: SYS_WIN32
// ************************************************************************ //
{$TYPEDADDRESS OFF} // Unit must be compiled without type-checked pointers.
{$WARN SYMBOL_PLATFORM OFF}
{$WRITEABLECONST ON}
{$VARPROPSETTER ON}
{$ALIGN 4}
interface
// автосгенерированные библиотеки,
//uses Winapi.Windows, System.Classes, System.Variants, System.Win.StdVCL, Vcl.Graphics, Vcl.OleServer, Winapi.ActiveX;
uses Winapi.ActiveX;
// *********************************************************************//
// GUIDS declared in the TypeLibrary. Following prefixes are used:
// Type Libraries : LIBID_xxxx
// CoClasses : CLASS_xxxx
// DISPInterfaces : DIID_xxxx
// Non-DISP interfaces: IID_xxxx
// *********************************************************************//
const
// TypeLibrary Major and minor versions
NotificationToastExportMajorVersion = 1;
NotificationToastExportMinorVersion = 0;
LIBID_NotificationToastExport: TGUID = '{A9D3FDA7-06F6-4BB5-928F-9499145D453D}';
IID_INotificationToast: TGUID = '{3ADF7763-9F0E-45B6-AC12-702C6C04B4E9}';
CLASS_NotificationToast: TGUID = '{4219D790-B1CF-4BA3-A3C9-7A8C0784BFAD}';
type
// *********************************************************************//
// Forward declaration of types defined in TypeLibrary
// *********************************************************************//
INotificationToast = interface;
// *********************************************************************//
// Declaration of CoClasses defined in Type Library
// (NOTE: Here we map each CoClass to its Default Interface)
// *********************************************************************//
NotificationToast = INotificationToast;
// *********************************************************************//
// Interface: INotificationToast
// Flags: (256) OleAutomation
// GUID: {3ADF7763-9F0E-45B6-AC12-702C6C04B4E9}
// *********************************************************************//
INotificationToast = interface(IUnknown)
['{3ADF7763-9F0E-45B6-AC12-702C6C04B4E9}']
function Show(const msg: WideString): HResult; stdcall;
end;
// *********************************************************************//
// The Class CoNotificationToast provides a Create and CreateRemote method to
// create instances of the default interface INotificationToast exposed by
// the CoClass NotificationToast. The functions are intended to be used by
// clients wishing to automate the CoClass objects exposed by the
// server of this typelibrary.
// *********************************************************************//
CoNotificationToast = class
class function Create: INotificationToast;
class function CreateRemote(const MachineName: string): INotificationToast;
end;
implementation
uses System.Win.ComObj;
class function CoNotificationToast.Create: INotificationToast;
begin
Result := CreateComObject(CLASS_NotificationToast) as INotificationToast;
end;
class function CoNotificationToast.CreateRemote(const MachineName: string): INotificationToast;
begin
Result := CreateRemoteComObject(MachineName, CLASS_NotificationToast) as INotificationToast;
end;
end.
|
PROGRAM concordance (input, output);
CONST
tablesize = 1000;
maxwordlen = 20;
TYPE
charindex = 1..maxwordlen;
counttype = 1..1000;
tableindex = 1..tablesize;
wordtype = ARRAY [charindex] OF char;
entrytype = RECORD
word : wordtype;
count : counttype;
END;
tabletype = ARRAY [tableindex] OF entrytype;
VAR
table : tabletype;
entry, nextentry : tableindex;
tablefull : boolean;
FUNCTION isletter (ch : char) : boolean;
VAR b : boolean;
BEGIN
b := ((ch >= 'a') AND (ch <= 'z'))
OR ((ch >= 'A') AND (ch <= 'Z'));
isLetter := b;
END;
PROCEDURE readword (VAR buffer : wordtype);
CONST
blank = ' ';
VAR
charcount : integer;
ch : char;
BEGIN
IF NOT eof THEN BEGIN
REPEAT
read(ch);
UNTIL eof OR isletter(ch);
END;
IF NOT eof THEN BEGIN
charcount := 0;
WHILE isletter(ch) DO BEGIN
IF charcount < maxwordlen THEN BEGIN
charcount := charcount + 1;
buffer[charcount] := ch;
END;
IF eof THEN ch := blank
ELSE read(ch);
END;
FOR charcount := charcount + 1 TO maxwordlen DO BEGIN
buffer[charcount] := blank;
END;
END;
END;
PROCEDURE printword (buffer : wordtype);
CONST
blank = ' ';
VAR
charpos : integer;
BEGIN
FOR charpos := 1 TO maxwordlen DO write(buffer[charpos]);
END;
BEGIN
tablefull := false;
nextentry := 1;
WHILE NOT (eof OR tablefull) DO BEGIN
readword(table[nextentry].word);
IF NOT eof THEN BEGIN
entry := 1;
WHILE table[entry].word <> table[nextentry].word DO BEGIN
entry := entry + 1;
END;
IF entry < nextentry THEN BEGIN
table[entry].count := table[entry].count + 1;
END
ELSE IF nextentry < tablesize THEN BEGIN
nextentry := nextentry + 1;
table[entry].count := 1;
END
ELSE tablefull := true;
END;
END;
IF tablefull THEN BEGIN
writeln('The table is not large enough.');
END
ELSE BEGIN
writeln;
writeln('Concordance table with ', nextentry - 1, ' words.');
writeln;
FOR entry := 1 TO nextentry - 1 DO BEGIN
printword(table[entry].word);
writeln(table[entry].count);
END;
END;
END. |
unit f2Decorators;
interface
uses
Classes,
d2dTypes,
d2dInterfaces,
d2dClasses,
d2dUtils,
d2dSprite,
d2dStaticText,
d2dGUIButtons,
d2dGUITypes,
furqTypes,
furqContext,
f2Types,
f2DecorScript,
f2FontPool,
JclStringLists;
type
Tf2DecoratorList = class;
Tf2SingleTargetProcessor = class;
If2ActionDecorator = interface
['{7A023A01-BE35-4FF8-BDBC-2D3A8A85AA8F}']
procedure ProcessEvent(var theEvent: Td2dInputEvent);
function GetActionsData(const anID: string): IFURQActionData;
function pm_GetAllowed: Boolean;
function pm_GetEnabled: Boolean;
function pm_GetMenuAlign: Td2dAlign;
procedure pm_SetAllowed(const Value: Boolean);
procedure pm_SetEnabled(const Value: Boolean);
procedure pm_SetMenuAlign(const Value: Td2dAlign);
property Allowed: Boolean read pm_GetAllowed write pm_SetAllowed;
property Enabled: Boolean read pm_GetEnabled write pm_SetEnabled;
property MenuAlign: Td2dAlign read pm_GetMenuAlign write pm_SetMenuAlign;
end;
If2TargetProvider = interface
['{78E5369F-2D34-4C9E-B4D3-14F74940DA61}']
function GetTargetProcessor: Tf2SingleTargetProcessor;
end;
Tf2SingleTargetProcessor = class(Td2dProtoObject)
private
f_ActionData: IFURQActionData;
f_ActionID: string;
f_Context: TFURQContext;
f_OnAction: Tf2OnActionProc;
f_Target: string;
public
constructor Create(const aContext: TFURQContext);
constructor Load(aFiler: Td2dFiler; aContext: TFURQContext);
function GetActionsData(anID: string): IFURQActionData;
procedure ExecuteAction(const aRect: Td2dRect; const aMenuAlign: Td2dAlign);
procedure pm_SetTarget(const aTarget: string);
procedure Save(aFiler: Td2dFiler);
property Target: string read f_Target write pm_SetTarget;
property OnAction: Tf2OnActionProc read f_OnAction write f_OnAction;
end;
Tf2BaseDecorator = class(Td2dProtoObject)
private
f_PositionBlender: Td2dPositionBlender;
f_PosX: Single;
f_PosY: Single;
f_PosZ: Single;
f_Script: IInterfaceList;
f_ScriptDelay: Single;
f_ScriptPos: Integer;
f_ToDie: Boolean;
f_Visible: Boolean;
procedure ExecuteNextScriptOp;
procedure pm_SetPosX(const Value: Single);
procedure pm_SetPosY(const Value: Single);
procedure pm_SetPosZ(const Value: Single);
procedure pm_SetScript(const Value: IInterfaceList);
procedure ProcessScript(const aDelta: Single);
procedure UpdatePositionBlending(const aDelta: Single);
protected
f_List: Tf2DecoratorList;
procedure Cleanup; override;
procedure ClearPositionBlender;
procedure DoExecuteScriptOperator(const aOp: If2DSOperator); virtual;
procedure DoRender; virtual; abstract;
procedure DoSetPosX(const Value: Single); virtual;
procedure DoSetPosY(const Value: Single); virtual;
function pm_GetDecoratorType: Tf2DecorType; virtual;
function pm_GetHeight: Single; virtual; abstract;
function pm_GetWidth: Single; virtual; abstract;
property ScriptDelay: Single read f_ScriptDelay write f_ScriptDelay;
public
procedure BlendPosition(const aTargetX, aTargetY: Single; const aTime: Single);
constructor Create(const aPosX, aPosY, aPosZ: Single);
constructor Load(aFiler: Td2dFiler);
procedure Render;
procedure Save(aFiler: Td2dFiler); virtual;
procedure Update(const aDelta: Single); virtual;
function AsActionDecorator: If2ActionDecorator; virtual;
property DecoratorType: Tf2DecorType read pm_GetDecoratorType;
property Height: Single read pm_GetHeight;
property PosX: Single read f_PosX write pm_SetPosX;
property PosY: Single read f_PosY write pm_SetPosY;
property PosZ: Single read f_PosZ write pm_SetPosZ;
property Script: IInterfaceList read f_Script write pm_SetScript;
property ToDie: Boolean read f_ToDie;
property Visible: Boolean read f_Visible write f_Visible;
property Width: Single read pm_GetWidth;
end;
Tf2DecoratorList = class(TStringList)
private
procedure ClearObjects;
function pm_GetDecorators(Index: Integer): Tf2BaseDecorator;
public
constructor Create;
destructor Destroy; override;
procedure AddDecorator(const aName: string; const aDecorator: Tf2BaseDecorator);
procedure Clear; override;
procedure Delete(Index: Integer); override;
procedure Load(aFiler: Td2dFiler; aContext: TFURQContext);
procedure Save(aFiler: Td2dFiler);
procedure Sort; override;
procedure Update(aDelta: Single);
property Decorators[Index: Integer]: Tf2BaseDecorator read pm_GetDecorators;
end;
Tf2ColoredDecorator = class(Tf2BaseDecorator)
private
f_Color: Td2dColor;
f_ColorBlender: Td2dColorBlender;
procedure pm_SetColor(const Value: Td2dColor);
procedure UpdateColorBlending(const aDelta: Single);
protected
procedure Cleanup; override;
procedure ClearColorBlender;
procedure DoExecuteScriptOperator(const aOp: If2DSOperator); override;
procedure DoSetColor(aColor: Td2dColor); virtual;
public
constructor Create(const aPosX, aPosY, aPosZ: Single; const aColor: Td2dColor);
constructor Load(aFiler: Td2dFiler);
procedure BlendColor(const aTargetColor: Td2dColor; const aTime: Single);
procedure Save(aFiler: Td2dFiler); override;
procedure Update(const aDelta: Single); override;
property Color: Td2dColor read f_Color write pm_SetColor;
end;
Tf2TextDecorator = class(Tf2ColoredDecorator, If2ActionDecorator)
private
f_Actions: IJclStringList;
f_Allowed: Boolean;
f_Context: TFURQContext;
f_FontName: string;
f_LinkColorBlender: Td2dColorBlender;
f_LinkHColorBlender: Td2dColorBlender;
f_LinksEnabled: Boolean;
f_MenuAlign: Td2dAlign;
f_OnAction: Tf2OnActionProc;
f_StaticText: Td2dStaticText;
f_Text: string;
function pm_GetAlign: Td2dTextAlignType;
function pm_GetFont: Id2dFont;
function pm_GetLineSpacing: Single;
function pm_GetLinkColor: Td2dColor;
function pm_GetLinkHColor: Td2dColor;
function pm_GetParaSpacing: Single;
function pm_GetText: string;
procedure pm_SetAlign(const Value: Td2dTextAlignType);
procedure pm_SetFont(const Value: Id2dFont);
procedure pm_SetLineSpacing(const Value: Single);
procedure pm_SetLinkColor(const Value: Td2dColor);
procedure pm_SetLinkHColor(const Value: Td2dColor);
procedure pm_SetParaSpacing(const Value: Single);
procedure pm_SetText(const Value: string);
procedure pm_SetWidth(const Value: Single);
private // If2ActionDecorator
procedure ProcessEvent(var theEvent: Td2dInputEvent);
function GetActionsData(const anID: string): IFURQActionData;
function pm_GetAllowed: Boolean;
function pm_GetLinksEnabled: Boolean;
function pm_GetMenuAlign: Td2dAlign;
procedure pm_SetAllowed(const Value: Boolean);
procedure pm_SetLinksEnabled(const Value: Boolean);
procedure pm_SetMenuAlign(const Value: Td2dAlign);
procedure UpdateLinksState;
function If2ActionDecorator.pm_GetEnabled = pm_GetLinksEnabled;
procedure If2ActionDecorator.pm_SetEnabled = pm_SetLinksEnabled;
protected
procedure Cleanup; override;
procedure DoExecuteScriptOperator(const aOp: If2DSOperator); override;
procedure DoRender; override;
procedure DoSetColor(aColor: Td2dColor); override;
function pm_GetHeight: Single; override;
function pm_GetWidth: Single; override;
procedure DoSetPosX(const Value: Single); override;
procedure DoSetPosY(const Value: Single); override;
function pm_GetDecoratorType: Tf2DecorType; override;
public
constructor Create(const aContext: TFURQContext;
const aPosX, aPosY, aPosZ: Single;
const aColor: Td2dColor;
const aLinkColor, aLinkHColor: Td2dColor;
const aText: string;
const aFontName: string;
aFontPool: Tf2FontPool);
constructor Load(aFiler: Td2dFiler; aContext: TFURQContext);
function AsActionDecorator: If2ActionDecorator; override;
procedure BlendLinkColors(const aTargetLinkColor, aTargetLinkHColor: Td2dColor; const aTime: Single);
procedure Save(aFiler: Td2dFiler); override;
procedure Update(const aDelta: Single); override;
procedure _ClickHandler(const aSender: TObject; const aRect: Td2dRect; const aTarget: string);
property Align: Td2dTextAlignType read pm_GetAlign write pm_SetAlign;
property Allowed: Boolean read pm_GetAllowed write pm_SetAllowed;
property Context: TFURQContext read f_Context write f_Context;
property Font: Id2dFont read pm_GetFont write pm_SetFont;
property LineSpacing: Single read pm_GetLineSpacing write pm_SetLineSpacing;
property LinkColor: Td2dColor read pm_GetLinkColor write pm_SetLinkColor;
property LinkHColor: Td2dColor read pm_GetLinkHColor write pm_SetLinkHColor;
property LinksEnabled: Boolean read pm_GetLinksEnabled write pm_SetLinksEnabled;
property MenuAlign: Td2dAlign read pm_GetMenuAlign write pm_SetMenuAlign;
property ParaSpacing: Single read pm_GetParaSpacing write pm_SetParaSpacing;
property Text: string read pm_GetText write pm_SetText;
property Width: Single read pm_GetWidth write pm_SetWidth;
property OnAction: Tf2OnActionProc read f_OnAction write f_OnAction;
end;
Tf2GraphicDecorator = class(Tf2ColoredDecorator)
private
f_Angle: Single;
f_HotX: Integer;
f_HotY: Integer;
f_RotationBlender: Td2dSimpleBlender;
f_ScaleBlender : Td2dSimpleBlender;
f_RotSpeed: Single;
f_Scale: Single;
procedure pm_SetAngle(const Value: Single);
procedure pm_SetRotSpeed(const Value: Single);
procedure pm_SetScale(const Value: Single);
protected
f_AngleRad: Single;
procedure Cleanup; override;
procedure ClearRotationBlender;
procedure ClearScaleBlender;
procedure pm_SetHotX(const aHotX: Integer); virtual;
procedure pm_SetHotY(const aHotY: Integer); virtual;
procedure SetAnglePrim(aAngle: Single);
procedure DoExecuteScriptOperator(const aOp: If2DSOperator); override;
public
constructor Create(const aPosX, aPosY, aPosZ: Single; const aColor: Td2dColor);
constructor Load(aFiler: Td2dFiler);
procedure BlendAngle(const aDelta: Single; aTime: Single);
procedure BlendScale(const aTargetScale: Single; aTime: Single);
procedure Save(aFiler: Td2dFiler); override;
procedure Update(const aDelta: Single); override;
property Angle: Single read f_Angle write pm_SetAngle;
property HotX: Integer read f_HotX write pm_SetHotX;
property HotY: Integer read f_HotY write pm_SetHotY;
property RotSpeed: Single read f_RotSpeed write pm_SetRotSpeed;
property Scale: Single read f_Scale write pm_SetScale;
end;
Tf2BasicSpriteDecorator = class(Tf2GraphicDecorator)
private
f_FlipX: Boolean;
f_FlipY: Boolean;
procedure pm_SetFlipX(const Value: Boolean);
procedure pm_SetFlipY(const Value: Boolean);
protected
f_Sprite: Td2dSprite;
procedure ApplyFlips;
procedure Cleanup; override;
procedure DoRender; override;
procedure DoSetColor(aColor: Td2dColor); override;
function pm_GetHeight: Single; override;
function pm_GetWidth: Single; override;
procedure pm_SetHotX(const aHotX: Integer); override;
procedure pm_SetHotY(const aHotY: Integer); override;
public
constructor Load(aFiler: Td2dFiler);
procedure Save(aFiler: Td2dFiler); override;
property FlipX: Boolean read f_FlipX write pm_SetFlipX;
property FlipY: Boolean read f_FlipY write pm_SetFlipY;
end;
Tf2RectangleDecorator = class(Tf2BasicSpriteDecorator)
protected
function pm_GetDecoratorType: Tf2DecorType; override;
public
constructor Create(const aPosX, aPosY, aPosZ: Single; aWidth, aHeight: Integer; const aColor: Td2dColor);
constructor Load(aFiler: Td2dFiler);
procedure Save(aFiler: Td2dFiler); override;
end;
Tf2SpriteInitDataRec = record
rTX : Integer;
rTY : Integer;
rWidth : Integer;
rHeight : Integer;
end;
Tf2SpriteDecorator = class(Tf2BasicSpriteDecorator)
private
f_TexName: string;
f_InitRec: Tf2SpriteInitDataRec;
protected
function pm_GetDecoratorType: Tf2DecorType; override;
public
constructor Create(const aPosX, aPosY, aPosZ: Single; aTexName: string;
aTX, aTY, aWidth, aHeight: Integer);
constructor Load(aFiler: Td2dFiler);
procedure Save(aFiler: Td2dFiler); override;
end;
Tf2AnimationDecorator = class(Tf2BasicSpriteDecorator)
private
f_AniType: Integer;
f_InitRec: Tf2SpriteInitDataRec;
f_TexName: string;
function pm_GetAniType: Integer;
function pm_GetCurFrame: Integer;
function pm_GetSpeed: Single;
procedure pm_SetAniType(Value: Integer);
procedure pm_SetCurFrame(const Value: Integer);
procedure pm_SetSpeed(const Value: Single);
protected
function pm_GetDecoratorType: Tf2DecorType; override;
public
constructor Create(const aPosX, aPosY, aPosZ: Single; aTexName: string; const aTX, aTY, aWidth, aHeight, aFrames:
Integer);
constructor Load(aFiler: Td2dFiler);
procedure Save(aFiler: Td2dFiler); override;
procedure Update(const aDelta: Single); override;
property AniType: Integer read pm_GetAniType write pm_SetAniType;
property CurFrame: Integer read pm_GetCurFrame write pm_SetCurFrame;
property Speed: Single read pm_GetSpeed write pm_SetSpeed;
end;
Tf2GIFDecorator = class(Tf2BasicSpriteDecorator)
private
f_GIFName: string;
function pm_GetAniSpeed: Integer;
function pm_GetFrame: Integer;
procedure pm_SetAniSpeed(const Value: Integer);
procedure pm_SetFrame(const Value: Integer);
protected
function pm_GetDecoratorType: Tf2DecorType; override;
public
constructor Create(const aPosX, aPosY, aPosZ: Single; aGIFName: string);
constructor Load(aFiler: Td2dFiler);
procedure Save(aFiler: Td2dFiler); override;
procedure Update(const aDelta: Single); override;
property AniSpeed: Integer read pm_GetAniSpeed write pm_SetAniSpeed;
property Frame: Integer read pm_GetFrame write pm_SetFrame;
end;
Tf2ClickAreaDecorator = class(Tf2BaseDecorator, If2ActionDecorator, If2TargetProvider)
private
f_Allowed: Boolean;
f_Enabled: Boolean;
f_Width: Single;
f_Height: Single;
f_MenuAlign: Td2dAlign;
f_Rect: Td2dRect;
f_TargetProcessor: Tf2SingleTargetProcessor;
function pm_GetAllowed: Boolean;
function pm_GetEnabled: Boolean;
function pm_GetMenuAlign: Td2dAlign;
procedure pm_SetAllowed(const Value: Boolean);
procedure pm_SetEnabled(const Value: Boolean);
procedure pm_SetWidth(const Value: Single);
procedure pm_SetHeight(const Value: Single);
procedure pm_SetMenuAlign(const Value: Td2dAlign);
procedure RecalcRect;
protected
procedure DoRender; override;
procedure DoSetPosX(const Value: Single); override;
procedure DoSetPosY(const Value: Single); override;
function pm_GetDecoratorType: Tf2DecorType; override;
function pm_GetWidth: Single; override;
function pm_GetHeight: Single; override;
procedure Cleanup; override;
// If2ActionDecorator
procedure ProcessEvent(var theEvent: Td2dInputEvent);
function GetActionsData(const anID: string): IFURQActionData;
// If2TargetProvider
function GetTargetProcessor: Tf2SingleTargetProcessor;
public
constructor Create(const aPosX, aPosY, aPosZ: Single; const aContext: TFURQContext; const aWidth, aHeight: Single);
constructor Load(aFiler: Td2dFiler; aContext: TFURQContext);
function AsActionDecorator: If2ActionDecorator; override;
procedure Save(aFiler: Td2dFiler); override;
property Allowed: Boolean read pm_GetAllowed write pm_SetAllowed;
property Enabled: Boolean read pm_GetEnabled write pm_SetEnabled;
property Width: Single read pm_GetWidth write pm_SetWidth;
property Height: Single read pm_GetHeight write pm_SetHeight;
property MenuAlign: Td2dAlign read pm_GetMenuAlign write pm_SetMenuAlign;
property TargetProcessor: Tf2SingleTargetProcessor read f_TargetProcessor;
end;
Tf2CustomButtonDecorator = class(Tf2BaseDecorator, If2ActionDecorator, If2TargetProvider)
private
f_Allowed: Boolean;
f_Enabled: Boolean;
f_MenuAlign: Td2dAlign;
f_TargetProcessor: Tf2SingleTargetProcessor;
function pm_GetAllowed: Boolean;
function pm_GetEnabled: Boolean;
function pm_GetMenuAlign: Td2dAlign;
procedure pm_SetAllowed(const Value: Boolean);
procedure pm_SetEnabled(const Value: Boolean);
procedure pm_SetMenuAlign(const Value: Td2dAlign);
procedure UpdateButtonState;
protected
f_Button: Td2dCustomButton;
procedure Cleanup; override;
procedure ClickHandler(aSender: TObject);
procedure DoRender; override;
procedure DoSetPosX(const Value: Single); override;
procedure DoSetPosY(const Value: Single); override;
procedure LoadButton(const aFiler: Td2dFiler; const aContext: TFURQContext); virtual; abstract;
procedure SaveButton(const aFiler: Td2dFiler); virtual; abstract;
function pm_GetHeight: Single; override;
function pm_GetWidth: Single; override;
// If2ActionDecorator
procedure ProcessEvent(var theEvent: Td2dInputEvent);
function GetActionsData(const anID: string): IFURQActionData;
// If2TargetProvider
function GetTargetProcessor: Tf2SingleTargetProcessor;
public
constructor Create(const aPosX, aPosY, aPosZ: Single; const aContext: TFURQContext);
constructor Load(const aFiler: Td2dFiler; aContext: TFURQContext);
function AsActionDecorator: If2ActionDecorator; override;
procedure Save(aFiler: Td2dFiler); override;
procedure Update(const aDelta: Single); override;
property Allowed: Boolean read pm_GetAllowed write pm_SetAllowed;
property Enabled: Boolean read pm_GetEnabled write pm_SetEnabled;
property MenuAlign: Td2dAlign read pm_GetMenuAlign write pm_SetMenuAlign;
property TargetProcessor: Tf2SingleTargetProcessor read f_TargetProcessor;
end;
Tf2ImageButtonDecorator = class(Tf2CustomButtonDecorator)
private
f_TextureName: string;
f_TexX: Integer;
f_TexY: Integer;
protected
procedure LoadButton(const aFiler: Td2dFiler; const aContext: TFURQContext); override;
function pm_GetDecoratorType: Tf2DecorType; override;
procedure SaveButton(const aFiler: Td2dFiler); override;
public
constructor Create(const aPosX, aPosY, aPosZ: Single; const aContext: TFURQContext; const aTexName: string; aTx, aTy,
aWidth, aHeight: Integer);
end;
Tf2TextButtonDecorator = class(Tf2CustomButtonDecorator)
private
f_TextFrame: string;
function pm_GetText: string;
function pm_GetTextAlign: Td2dTextAlignType;
procedure pm_SetText(const Value: string);
procedure pm_SetTextAlign(const Value: Td2dTextAlignType);
procedure pm_SetWidth(const Value: Single);
protected
procedure LoadButton(const aFiler: Td2dFiler; const aContext: TFURQContext); override;
function pm_GetDecoratorType: Tf2DecorType; override;
function pm_GetWidth: Single; override;
procedure SaveButton(const aFiler: Td2dFiler); override;
public
constructor Create(const aPosX, aPosY, aPosZ: Single; const aContext: TFURQContext; const aTextFrame, aText: string);
property Text: string read pm_GetText write pm_SetText;
property TextAlign: Td2dTextAlignType read pm_GetTextAlign write pm_SetTextAlign;
property Width: Single read pm_GetWidth write pm_SetWidth;
end;
implementation
uses
SysUtils,
d2dCore,
d2dGIF,
furqBase,
f2Context,
f2LinkParser, d2dGUI;
const
cPi180 = Pi / 180;
procedure Tf2BaseDecorator.BlendPosition(const aTargetX, aTargetY: Single; const aTime: Single);
begin
if f_PositionBlender <> nil then
FreeAndNil(f_PositionBlender);
f_PositionBlender := Td2dPositionBlender.Create(aTime, D2DPoint(f_PosX, f_PosY), D2DPoint(aTargetX, aTargetY));
f_PositionBlender.Run;
end;
constructor Tf2BaseDecorator.Create(const aPosX, aPosY, aPosZ: Single);
begin
inherited Create;
f_PosX := aPosX;
f_PosY := aPosY;
f_PosZ := aPosZ;
f_Visible := True;
end;
constructor Tf2BaseDecorator.Load(aFiler: Td2dFiler);
begin
inherited Create;
with aFiler do
begin
f_PosX := ReadSingle;
f_PosY := ReadSingle;
f_PosZ := ReadSingle;
f_Visible := ReadBoolean;
if ReadBoolean then
f_PositionBlender := Td2dPositionBlender.Load(aFiler);
if ReadBoolean then
begin
f_ScriptDelay := ReadSingle;
f_ScriptPos := ReadInteger;
f_Script := LoadDSOperators(aFiler);
end;
end;
end;
procedure Tf2BaseDecorator.Cleanup;
begin
ClearPositionBlender;
inherited;
end;
function Tf2BaseDecorator.AsActionDecorator: If2ActionDecorator;
begin
Result := nil;
end;
procedure Tf2BaseDecorator.UpdatePositionBlending(const aDelta: Single);
begin
if f_PositionBlender <> nil then
begin
f_PositionBlender.Update(aDelta);
DoSetPosX(Int(f_PositionBlender.Current.X));
DoSetPosY(Int(f_PositionBlender.Current.Y));
if not f_PositionBlender.IsRunning then
FreeAndNil(f_PositionBlender);
end;
end;
procedure Tf2BaseDecorator.ClearPositionBlender;
begin
if f_PositionBlender <> nil then
FreeAndNil(f_PositionBlender);
end;
procedure Tf2BaseDecorator.DoExecuteScriptOperator(const aOp: If2DSOperator);
var
l_X, l_Y: Single;
l_Time : Single;
begin
case aOp.OpType of
otMove:
begin
l_X := aOp.Params[0].GetValue;
l_Y := aOp.Params[1].GetValue;
if aOp.IsRelative then
begin
l_X := l_X + PosX;
l_Y := l_Y + PosY;
end;
if aOp.ParamCount = 3 then
begin
l_Time := aOp.Params[2].GetValue/1000;
BlendPosition(l_X, l_Y, l_Time);
if not aOp.IsAsync then
ScriptDelay := l_Time;
end
else
begin
PosX := l_X;
PosY := l_Y;
end;
end;
otPause:
ScriptDelay := aOp.Params[0].GetValue/1000;
otRestart:
f_ScriptPos := -1; // потому что потом будет Inc, а нам нужен 0
otDelete:
f_ToDie := True;
end;
end;
procedure Tf2BaseDecorator.DoSetPosX(const Value: Single);
begin
f_PosX := Value;
end;
procedure Tf2BaseDecorator.DoSetPosY(const Value: Single);
begin
f_PosY := Value;
end;
procedure Tf2BaseDecorator.ExecuteNextScriptOp;
var
l_Op: If2DSOperator;
begin
while True do
begin
l_Op := f_Script[f_ScriptPos] as If2DSOperator;
DoExecuteScriptOperator(l_Op);
Inc(f_ScriptPos);
if f_ScriptPos >= f_Script.Count then
begin
f_Script := nil;
Exit;
end;
if (not l_Op.IsAsync) or f_ToDie then
Break;
end;
end;
function Tf2BaseDecorator.pm_GetDecoratorType: Tf2DecorType;
begin
Result := dtInvalid;
end;
procedure Tf2BaseDecorator.pm_SetPosX(const Value: Single);
begin
ClearPositionBlender;
DoSetPosX(Value);
end;
procedure Tf2BaseDecorator.pm_SetPosY(const Value: Single);
begin
ClearPositionBlender;
DoSetPosY(Value);
end;
procedure Tf2BaseDecorator.pm_SetPosZ(const Value: Single);
begin
f_PosZ := Value;
if f_List <> nil then
f_List.Sort;
end;
procedure Tf2BaseDecorator.pm_SetScript(const Value: IInterfaceList);
begin
f_Script := Value;
f_ScriptDelay := 0;
f_ScriptPos := 0;
if f_Script <> nil then
ExecuteNextScriptOp;
end;
procedure Tf2BaseDecorator.ProcessScript(const aDelta: Single);
begin
if f_Script <> nil then
begin
f_ScriptDelay := f_ScriptDelay - aDelta;
if f_ScriptDelay <= 0 then
begin
f_ScriptDelay := 0;
ExecuteNextScriptOp;
end;
end;
end;
procedure Tf2BaseDecorator.Render;
begin
if f_Visible then
DoRender;
end;
procedure Tf2BaseDecorator.Save(aFiler: Td2dFiler);
var
l_NotNil: Boolean;
begin
with aFiler do
begin
WriteSingle(f_PosX);
WriteSingle(f_PosY);
WriteSingle(f_PosZ);
WriteBoolean(f_Visible);
l_NotNil := f_PositionBlender <> nil;
WriteBoolean(l_NotNil);
if l_NotNil then
f_PositionBlender.Save(aFiler);
l_NotNil := f_Script <> nil;
WriteBoolean(l_NotNil);
if l_NotNil then
begin
WriteSingle(f_ScriptDelay);
WriteInteger(f_ScriptPos);
SaveDSOperators(f_Script, aFiler);
end;
end;
end;
procedure Tf2BaseDecorator.Update(const aDelta: Single);
begin
UpdatePositionBlending(aDelta);
ProcessScript(aDelta);
end;
constructor Tf2DecoratorList.Create;
begin
inherited;
CaseSensitive := False;
end;
destructor Tf2DecoratorList.Destroy;
begin
ClearObjects;
inherited Destroy;
end;
procedure Tf2DecoratorList.AddDecorator(const aName: string; const aDecorator: Tf2BaseDecorator);
var
l_Idx: Integer;
begin
l_Idx := IndexOf(aName);
if l_Idx <> -1 then
begin
Objects[l_Idx].Free;
Objects[l_Idx] := aDecorator;
end
else
AddObject(aName, aDecorator);
aDecorator.f_List := Self;
Sort;
end;
procedure Tf2DecoratorList.Clear;
begin
ClearObjects;
inherited Clear;
end;
procedure Tf2DecoratorList.ClearObjects;
var
I: Integer;
begin
for I := 0 to Pred(Count) do
if Objects[I] <> nil then
Objects[I].Free;
end;
procedure Tf2DecoratorList.Delete(Index: Integer);
begin
if Objects[Index] <> nil then
Objects[Index].Free;
inherited Delete(Index);
end;
function Tf2DecoratorList.pm_GetDecorators(Index: Integer): Tf2BaseDecorator;
begin
Result := Tf2BaseDecorator(Objects[Index]);
end;
function CompareDecorators(List: TStringList; Index1, Index2: Integer): Integer;
var
l_D1, l_D2: Tf2BaseDecorator;
begin
l_D1 := Tf2DecoratorList(List).Decorators[Index1];
l_D2 := Tf2DecoratorList(List).Decorators[Index2];
if l_D1.PosZ > l_D2.PosZ then
Result := -1
else
if l_D1.PosZ < l_D2.PosZ then
Result := 1
else
Result := 0;
end;
procedure Tf2DecoratorList.Load(aFiler: Td2dFiler; aContext: TFURQContext);
var
I, l_N: Integer;
l_Name: string;
l_Type: Tf2DecorType;
l_Decor: Tf2BaseDecorator;
begin
Clear;
l_N := aFiler.ReadInteger;
for I := 1 to l_N do
begin
l_Name := aFiler.ReadString;
l_Type := Tf2DecorType(aFiler.ReadInteger);
case l_Type of
dtText : l_Decor := Tf2TextDecorator.Load(aFiler, aContext);
dtRectangle : l_Decor := Tf2RectangleDecorator.Load(aFiler);
dtPicture : l_Decor := Tf2SpriteDecorator.Load(aFiler);
dtAnimation : l_Decor := Tf2AnimationDecorator.Load(aFiler);
dtGIF : l_Decor := Tf2GIFDecorator.Load(aFiler);
dtClickArea : l_Decor := Tf2ClickAreaDecorator.Load(aFiler, aContext);
dtImgButton : l_Decor := Tf2ImageButtonDecorator.Load(aFiler, aContext);
dtTextButton : l_Decor := Tf2TextButtonDecorator.Load(aFiler, aContext);
else
l_Decor := nil;
end;
if l_Decor <> nil then
AddDecorator(l_Name, l_Decor);
end;
end;
procedure Tf2DecoratorList.Save(aFiler: Td2dFiler);
var
I: Integer;
l_Type: Tf2DecorType;
begin
aFiler.WriteInteger(Count);
for I := 0 to Pred(Count) do
begin
aFiler.WriteString(Strings[I]);
l_Type := Decorators[I].DecoratorType;
Assert(l_Type <> dtInvalid, 'Запись неизвестного типа декоратора!');
aFiler.WriteInteger(Integer(l_Type));
Decorators[I].Save(aFiler);
end;
end;
procedure Tf2DecoratorList.Sort;
begin
CustomSort(CompareDecorators);
end;
procedure Tf2DecoratorList.Update(aDelta: Single);
var
I: Integer;
begin
I := 0;
while I < Count do
begin
Decorators[I].Update(aDelta);
if Decorators[I].ToDie then
Delete(I)
else
Inc(I);
end;
end;
constructor Tf2TextDecorator.Create(const aContext: TFURQContext;
const aPosX, aPosY, aPosZ: Single;
const aColor: Td2dColor;
const aLinkColor, aLinkHColor: Td2dColor;
const aText: string;
const aFontName: string;
aFontPool: Tf2FontPool);
var
l_Font: Id2dFont;
begin
inherited Create(aPosX, aPosY, aPosZ, aColor);
f_Context := aContext;
f_FontName := aFontName;
l_Font := aFontPool.GetFont(f_FontName);
if l_Font = nil then
l_Font := aFontPool.SysTextFont;
f_StaticText := Td2dStaticText.Create(l_Font, f_Color);
f_StaticText.LinkColor := aLinkColor;
f_StaticText.LinkHColor := aLinkHColor;
f_StaticText.X := PosX;
f_StaticText.Y := PosY;
f_StaticText.OnLinkClick := _ClickHandler;
f_Actions := JclStringList;
f_Allowed := True;
f_LinksEnabled := True;
f_MenuAlign := alBottomLeft;
Text := aText;
end;
constructor Tf2TextDecorator.Load(aFiler: Td2dFiler; aContext: TFURQContext);
var
l_Font: Id2dFont;
l_Text: string;
begin
inherited Load(aFiler);
f_Context := aContext;
f_Actions := JclStringList;
f_FontName := aFiler.ReadString;
l_Font := Tf2Context(f_Context).FontPool.GetFont(f_FontName);
if l_Font = nil then
l_Font := Tf2Context(f_Context).FontPool.SysTextFont;
l_Text := aFiler.ReadString;
f_StaticText := Td2dStaticText.Create(l_Font, f_Color);
f_StaticText.X := PosX;
f_StaticText.Y := PosY;
f_StaticText.Align := Td2dTextAlignType(aFiler.ReadInteger);
f_StaticText.AutoWidth := aFiler.ReadBoolean;
if not f_StaticText.AutoWidth then
f_StaticText.Width := aFiler.ReadSingle;
f_StaticText.LinkColor := aFiler.ReadColor;
f_StaticText.LinkHColor := aFiler.ReadColor;
f_LinksEnabled := aFiler.ReadBoolean;
f_MenuAlign := Td2dAlign(aFiler.ReadByte);
f_StaticText.OnLinkClick := _ClickHandler;
UpdateLinksState;
if aFiler.ReadBoolean then
f_LinkColorBlender := Td2dColorBlender.Load(aFiler);
if aFiler.ReadBoolean then
f_LinkHColorBlender := Td2dColorBlender.Load(aFiler);
Text := l_Text;
OnAction := Tf2Context(aContext).OnDecoratorAction;
end;
procedure Tf2TextDecorator.Cleanup;
begin
FreeAndNil(f_StaticText);
FreeAndNil(f_LinkColorBlender);
FreeAndNil(f_LinkHColorBlender);
inherited;
end;
function Tf2TextDecorator.AsActionDecorator: If2ActionDecorator;
begin
Result := Self;
end;
procedure Tf2TextDecorator.BlendLinkColors(const aTargetLinkColor, aTargetLinkHColor: Td2dColor; const aTime: Single);
begin
if f_LinkColorBlender <> nil then
FreeAndNil(f_LinkColorBlender);
f_LinkColorBlender := Td2dColorBlender.Create(aTime, LinkColor, aTargetLinkColor);
if f_LinkHColorBlender <> nil then
FreeAndNil(f_LinkHColorBlender);
f_LinkHColorBlender := Td2dColorBlender.Create(aTime, LinkHColor, aTargetLinkHColor);
f_LinkColorBlender.Run;
f_LinkHColorBlender.Run;
end;
procedure Tf2TextDecorator.DoExecuteScriptOperator(const aOp: If2DSOperator);
var
l_Time: Single;
begin
if (aOp.OpType = otColor) then
begin
if (aOp.ParamCount = 1) or ((aOp.ParamCount = 2) and (aOp.Params[1].GetValue <= 0)) then
Color := CorrectColor(Trunc(aOp.Params[0].GetValue))
else
if (aOp.ParamCount = 2) then
begin
l_Time := aOp.Params[1].GetValue/1000;
BlendColor(CorrectColor(Trunc(aOp.Params[0].GetValue)), l_Time);
if not aOp.IsAsync then
ScriptDelay := l_Time;
end
else
if (aOp.ParamCount = 3) or ((aOp.ParamCount = 4) and (aOp.Params[3].GetValue <= 0)) then
begin
Color := CorrectColor(Trunc(aOp.Params[0].GetValue));
LinkColor := CorrectColor(Trunc(aOp.Params[1].GetValue));
LinkHColor := CorrectColor(Trunc(aOp.Params[2].GetValue));
end
else
begin
l_Time := aOp.Params[3].GetValue/1000;
BlendColor(CorrectColor(Trunc(aOp.Params[0].GetValue)), l_Time);
BlendLinkColors(CorrectColor(Trunc(aOp.Params[1].GetValue)), CorrectColor(Trunc(aOp.Params[2].GetValue)), l_Time);
if not aOp.IsAsync then
ScriptDelay := l_Time;
end;
end
else
inherited DoExecuteScriptOperator(aOp);
end;
procedure Tf2TextDecorator.DoRender;
begin
f_StaticText.Render;
end;
procedure Tf2TextDecorator.DoSetColor(aColor: Td2dColor);
begin
inherited DoSetColor(aColor);
if f_StaticText.TextColor <> aColor then
begin
f_StaticText.TextColor := aColor;
if (f_StaticText.LinkColor and $FF000000) <> (aColor and $FF000000) then
f_StaticText.LinkColor := (aColor and $FF000000) or (f_StaticText.LinkColor and $00FFFFFF);
if (f_StaticText.LinkHColor and $FF000000) <> (aColor and $FF000000) then
f_StaticText.LinkHColor := (aColor and $FF000000) or (f_StaticText.LinkHColor and $00FFFFFF);
end;
end;
function Tf2TextDecorator.GetActionsData(const anID: string): IFURQActionData;
var
l_Idx: Integer;
begin
Result := nil;
l_Idx := f_Actions.IndexOf(anID);
if l_Idx >= 0 then
Result := f_Actions.Interfaces[l_Idx] as IFURQActionData;
end;
function Tf2TextDecorator.pm_GetAlign: Td2dTextAlignType;
begin
Result := f_StaticText.Align;
end;
function Tf2TextDecorator.pm_GetFont: Id2dFont;
begin
Result := f_StaticText.Font;
end;
function Tf2TextDecorator.pm_GetHeight: Single;
begin
Result := f_StaticText.Height;
end;
function Tf2TextDecorator.pm_GetLineSpacing: Single;
begin
Result := f_StaticText.LineSpacing;
end;
function Tf2TextDecorator.pm_GetLinkColor: Td2dColor;
begin
Result := f_StaticText.LinkColor;
end;
function Tf2TextDecorator.pm_GetLinkHColor: Td2dColor;
begin
Result := f_StaticText.LinkHColor;
end;
function Tf2TextDecorator.pm_GetParaSpacing: Single;
begin
Result := f_StaticText.ParaSpacing;
end;
function Tf2TextDecorator.pm_GetText: string;
begin
Result := f_Text;
end;
function Tf2TextDecorator.pm_GetWidth: Single;
begin
Result := f_StaticText.Width;
end;
procedure Tf2TextDecorator.pm_SetAlign(const Value: Td2dTextAlignType);
begin
f_StaticText.Align := Value;
end;
procedure Tf2TextDecorator.pm_SetFont(const Value: Id2dFont);
begin
f_StaticText.Font := Value;
end;
procedure Tf2TextDecorator.pm_SetLineSpacing(const Value: Single);
begin
f_StaticText.LineSpacing := Value;
end;
procedure Tf2TextDecorator.pm_SetLinkColor(const Value: Td2dColor);
begin
f_StaticText.LinkColor := (Value and $FFFFFF) or (f_Color and $FF000000);
end;
procedure Tf2TextDecorator.pm_SetLinkHColor(const Value: Td2dColor);
begin
f_StaticText.LinkHColor := (Value and $FFFFFF) or (f_Color and $FF000000);;
end;
procedure Tf2TextDecorator.pm_SetParaSpacing(const Value: Single);
begin
f_StaticText.ParaSpacing := Value;
end;
procedure Tf2TextDecorator.DoSetPosX(const Value: Single);
begin
inherited DoSetPosX(Value);
f_StaticText.X := PosX;
end;
procedure Tf2TextDecorator.DoSetPosY(const Value: Single);
begin
inherited DoSetPosY(Value);
f_StaticText.Y := PosY;
end;
function Tf2TextDecorator.pm_GetAllowed: Boolean;
begin
Result := f_Allowed;
end;
function Tf2TextDecorator.pm_GetDecoratorType: Tf2DecorType;
begin
Result := dtText;
end;
function Tf2TextDecorator.pm_GetLinksEnabled: Boolean;
begin
Result := f_LinksEnabled;
end;
function Tf2TextDecorator.pm_GetMenuAlign: Td2dAlign;
begin
Result := f_MenuAlign;
end;
procedure Tf2TextDecorator.pm_SetAllowed(const Value: Boolean);
begin
f_Allowed := Value;
UpdateLinksState;
end;
procedure Tf2TextDecorator.pm_SetLinksEnabled(const Value: Boolean);
begin
f_LinksEnabled := Value;
UpdateLinksState;
end;
procedure Tf2TextDecorator.pm_SetMenuAlign(const Value: Td2dAlign);
begin
f_MenuAlign := Value;
end;
procedure Tf2TextDecorator.pm_SetText(const Value: string);
begin
f_Actions.Clear;
f_StaticText.StartText;
try
OutTextWithLinks(Value, f_StaticText, f_Context, f_Actions);
finally
f_StaticText.EndText;
end;
f_Text := Value;
end;
procedure Tf2TextDecorator.pm_SetWidth(const Value: Single);
begin
if Value = 0 then
f_StaticText.AutoWidth := True
else
begin
f_StaticText.AutoWidth := False;
f_StaticText.Width := Value;
end;
end;
procedure Tf2TextDecorator.ProcessEvent(var theEvent: Td2dInputEvent);
begin
f_StaticText.ProcessEvent(theEvent);
end;
procedure Tf2TextDecorator.Save(aFiler: Td2dFiler);
var
l_NotNil: Boolean;
begin
inherited Save(aFiler);
aFiler.WriteString(f_FontName);
aFiler.WriteString(Text);
aFiler.WriteInteger(Ord(Align));
aFiler.WriteBoolean(f_StaticText.AutoWidth);
if not f_StaticText.AutoWidth then
aFiler.WriteSingle(Width);
aFiler.WriteColor(LinkColor);
aFiler.WriteColor(LinkHColor);
aFiler.WriteBoolean(f_LinksEnabled);
aFiler.WriteByte(Ord(f_MenuAlign));
l_NotNil := f_LinkColorBlender <> nil;
aFiler.WriteBoolean(l_NotNil);
if l_NotNil then
f_LinkColorBlender.Save(aFiler);
l_NotNil := f_LinkHColorBlender <> nil;
aFiler.WriteBoolean(l_NotNil);
if l_NotNil then
f_LinkHColorBlender.Save(aFiler);
end;
procedure Tf2TextDecorator.Update(const aDelta: Single);
begin
if f_LinkColorBlender <> nil then
begin
f_LinkColorBlender.Update(aDelta);
LinkColor := f_LinkColorBlender.Current;
if not f_LinkColorBlender.IsRunning then
FreeAndNil(f_LinkColorBlender);
end;
if f_LinkHColorBlender <> nil then
begin
f_LinkHColorBlender.Update(aDelta);
LinkHColor := f_LinkHColorBlender.Current;
if not f_LinkHColorBlender.IsRunning then
FreeAndNil(f_LinkHColorBlender);
end;
inherited;
end;
procedure Tf2TextDecorator.UpdateLinksState;
begin
f_StaticText.LinksEnabled := f_Allowed and f_LinksEnabled;
end;
procedure Tf2TextDecorator._ClickHandler(const aSender: TObject; const aRect: Td2dRect; const aTarget: string);
begin
if Assigned(f_OnAction) then
f_OnAction(aTarget, aRect, f_MenuAlign);
end;
constructor Tf2GraphicDecorator.Create(const aPosX, aPosY, aPosZ: Single; const aColor: Td2dColor);
begin
inherited;
f_Scale := 1.0;
end;
constructor Tf2GraphicDecorator.Load(aFiler: Td2dFiler);
begin
inherited Load(aFiler);
with aFiler do
begin
f_Angle := ReadSingle;
f_AngleRad := ReadSingle;
f_HotX := ReadInteger;
f_HotY := ReadInteger;
f_Scale := ReadSingle;
if ReadBoolean then
f_RotationBlender := Td2dSimpleBlender.Load(aFiler)
else
f_RotSpeed := ReadSingle;
if ReadBoolean then
f_ScaleBlender := Td2dSimpleBlender.Load(aFiler)
end;
end;
procedure Tf2GraphicDecorator.Cleanup;
begin
ClearRotationBlender;
inherited;
end;
procedure Tf2GraphicDecorator.BlendAngle(const aDelta: Single; aTime: Single);
begin
ClearRotationBlender;
f_RotSpeed := 0;
f_RotationBlender := Td2dSimpleBlender.Create(aTime, Angle, Angle + aDelta);
f_RotationBlender.Run;
end;
procedure Tf2GraphicDecorator.BlendScale(const aTargetScale: Single; aTime: Single);
begin
ClearScaleBlender;
f_ScaleBlender := Td2dSimpleBlender.Create(aTime, Scale, aTargetScale);
f_ScaleBlender.Run;
end;
procedure Tf2GraphicDecorator.ClearRotationBlender;
begin
if f_RotationBlender <> nil then
FreeAndNil(f_RotationBlender);
end;
procedure Tf2GraphicDecorator.ClearScaleBlender;
begin
if f_ScaleBlender <> nil then
FreeAndNil(f_ScaleBlender);
end;
procedure Tf2GraphicDecorator.DoExecuteScriptOperator(const aOp: If2DSOperator);
var
l_Time: Single;
l_Value: Single;
begin
case aOp.OpType of
otRotate:
begin
l_Value := aOp.Params[0].GetValue;
if not aOp.IsRelative then
Angle := l_Value
else
begin
if aOp.ParamCount = 2 then
begin
l_Time := aOp.Params[1].GetValue/1000;
BlendAngle(l_Value, l_Time);
if not aOp.IsAsync then
ScriptDelay := l_Time;
end
else
Angle := Angle + l_Value;
end;
end;
otScale:
begin
l_Value := aOp.Params[0].GetValue;
if aOp.ParamCount = 2 then
begin
l_Time := aOp.Params[1].GetValue/1000;
BlendScale(l_Value, l_Time);
if not aOp.IsAsync then
ScriptDelay := l_Time;
end
else
Scale := l_Value;
end;
otRotateSpeed: RotSpeed := aOp.Params[0].GetValue;
else
inherited DoExecuteScriptOperator(aOp);
end;
end;
procedure Tf2GraphicDecorator.pm_SetAngle(const Value: Single);
begin
f_RotSpeed := 0;
ClearRotationBlender;
SetAnglePrim(Value);
end;
procedure Tf2GraphicDecorator.pm_SetHotX(const aHotX: Integer);
begin
f_HotX := aHotX;
end;
procedure Tf2GraphicDecorator.pm_SetHotY(const aHotY: Integer);
begin
f_HotY := aHotY;
end;
procedure Tf2GraphicDecorator.pm_SetRotSpeed(const Value: Single);
begin
ClearRotationBlender;
f_RotSpeed := Value;
end;
procedure Tf2GraphicDecorator.pm_SetScale(const Value: Single);
begin
ClearScaleBlender;
f_Scale := Value;
end;
procedure Tf2GraphicDecorator.Save(aFiler: Td2dFiler);
var
l_NotNil: Boolean;
begin
inherited Save(aFiler);
with aFiler do
begin
WriteSingle(f_Angle);
WriteSingle(f_AngleRad);
WriteInteger(f_HotX);
WriteInteger(f_HotY);
WriteSingle(f_Scale);
l_NotNil := f_RotationBlender <> nil;
WriteBoolean(l_NotNil);
if l_NotNil then
f_RotationBlender.Save(aFiler)
else
WriteSingle(f_RotSpeed);
l_NotNil := f_ScaleBlender <> nil;
WriteBoolean(l_NotNil);
if l_NotNil then
f_ScaleBlender.Save(aFiler);
end;
end;
procedure Tf2GraphicDecorator.SetAnglePrim(aAngle: Single);
begin
f_Angle := aAngle;
if (f_Angle >= 360) or (f_Angle <= -360) then
f_Angle := f_Angle - Int(f_Angle/360) * 360;
if f_Angle < 0 then
f_Angle := 360 + f_Angle;
f_AngleRad := f_Angle * cPi180;
end;
procedure Tf2GraphicDecorator.Update(const aDelta: Single);
begin
if f_RotSpeed <> 0 then
SetAnglePrim(Angle + f_RotSpeed * aDelta);
if f_RotationBlender <> nil then
begin
f_RotationBlender.Update(aDelta);
SetAnglePrim(f_RotationBlender.Current);
if not f_RotationBlender.IsRunning then
ClearRotationBlender;
end;
if f_ScaleBlender <> nil then
begin
f_ScaleBlender.Update(aDelta);
f_Scale := f_ScaleBlender.Current;
if not f_ScaleBlender.IsRunning then
ClearScaleBlender;
end;
inherited Update(aDelta);
end;
constructor Tf2BasicSpriteDecorator.Load(aFiler: Td2dFiler);
begin
inherited Load(aFiler);
f_FlipX := aFiler.ReadBoolean;
f_FlipY := aFiler.ReadBoolean;
end;
procedure Tf2BasicSpriteDecorator.ApplyFlips;
begin
// это нужно для Load в наследниках, потому что данные о флипах
// загружаются раньше, чем создаётся сам спрайт
f_Sprite.FlipX := f_FlipX;
f_Sprite.FlipY := f_FlipY;
end;
procedure Tf2BasicSpriteDecorator.Cleanup;
begin
f_Sprite.Free;
end;
procedure Tf2BasicSpriteDecorator.DoRender;
begin
f_Sprite.RenderEx(f_PosX, f_PosY, f_AngleRad, f_Scale);
end;
procedure Tf2BasicSpriteDecorator.DoSetColor(aColor: Td2dColor);
begin
inherited;
f_Sprite.SetColor(aColor);
end;
function Tf2BasicSpriteDecorator.pm_GetHeight: Single;
begin
Result := f_Sprite.Height;
end;
function Tf2BasicSpriteDecorator.pm_GetWidth: Single;
begin
Result := f_Sprite.Width;
end;
procedure Tf2BasicSpriteDecorator.pm_SetFlipX(const Value: Boolean);
begin
f_FlipX := Value;
f_Sprite.FlipX := Value;
end;
procedure Tf2BasicSpriteDecorator.pm_SetFlipY(const Value: Boolean);
begin
f_FlipY := Value;
f_Sprite.FlipY := Value;
end;
procedure Tf2BasicSpriteDecorator.pm_SetHotX(const aHotX: Integer);
begin
inherited pm_SetHotX(aHotX);
f_Sprite.HotX := f_HotX;
end;
procedure Tf2BasicSpriteDecorator.pm_SetHotY(const aHotY: Integer);
begin
inherited pm_SetHotY(aHotY);
f_Sprite.HotY := f_HotY;
end;
procedure Tf2BasicSpriteDecorator.Save(aFiler: Td2dFiler);
begin
inherited Save(aFiler);
aFiler.WriteBoolean(FlipX);
aFiler.WriteBoolean(FlipY);
end;
constructor Tf2RectangleDecorator.Create(const aPosX, aPosY, aPosZ: Single;
aWidth, aHeight: Integer; const aColor: Td2dColor);
begin
inherited Create(aPosX, aPosY, aPosZ, aColor);
f_Sprite := Td2dRectangle.Create(aWidth, aHeight, aColor);
end;
constructor Tf2RectangleDecorator.Load(aFiler: Td2dFiler);
var
l_W, l_H: Integer;
begin
inherited Load(aFiler);
l_W := aFiler.ReadInteger;
l_H := aFiler.ReadInteger;
f_Sprite := Td2dRectangle.Create(l_W, l_H, f_Color);
f_Sprite.HotX := f_HotX;
f_Sprite.HotY := f_HotY;
f_Sprite.SetColor(f_Color);
end;
function Tf2RectangleDecorator.pm_GetDecoratorType: Tf2DecorType;
begin
Result := dtRectangle;
end;
procedure Tf2RectangleDecorator.Save(aFiler: Td2dFiler);
begin
inherited Save(aFiler);
aFiler.WriteInteger(Trunc(f_Sprite.Width));
aFiler.WriteInteger(Trunc(f_Sprite.Height));
end;
constructor Tf2SpriteDecorator.Create(const aPosX, aPosY, aPosZ: Single; aTexName: string;
aTX, aTY, aWidth, aHeight: Integer);
var
l_Tex: Id2dTexture;
begin
inherited Create(aPosX, aPosY, aPosZ, $FFFFFFFF);
f_TexName := aTexName;
l_Tex := gD2DE.Texture_Load(aTexName);
if l_Tex <> nil then
begin
if (aWidth = 0) then
aWidth := gD2DE.Texture_GetWidth(l_Tex) - aTX;
if (aHeight = 0) then
aHeight := gD2DE.Texture_GetHeight(l_Tex) - aTY;
if (aWidth < 1) or (aHeight < 1) then
begin
aWidth := 0;
aHeight := 0;
end;
end;
with f_InitRec do
begin
rTX := aTX;
rTY := aTY;
rWidth := aWidth;
rHeight:= aHeight;
end;
f_Sprite := Td2dSprite.Create(l_Tex, aTX, aTY, aWidth, aHeight);
end;
constructor Tf2SpriteDecorator.Load(aFiler: Td2dFiler);
var
l_Tex: Id2dTexture;
begin
inherited Load(aFiler);
f_TexName := aFiler.ReadString;
aFiler.Stream.ReadBuffer(f_InitRec, SizeOf(Tf2SpriteInitDataRec));
l_Tex := gD2DE.Texture_Load(f_TexName);
with f_InitRec do
f_Sprite := Td2dSprite.Create(l_Tex, rTX, rTY, rWidth, rHeight);
f_Sprite.HotX := f_HotX;
f_Sprite.HotY := f_HotY;
f_Sprite.SetColor(f_Color);
ApplyFlips;
end;
function Tf2SpriteDecorator.pm_GetDecoratorType: Tf2DecorType;
begin
Result := dtPicture;
end;
procedure Tf2SpriteDecorator.Save(aFiler: Td2dFiler);
begin
inherited Save(aFiler);
aFiler.WriteString(f_TexName);
aFiler.Stream.WriteBuffer(f_InitRec, SizeOf(Tf2SpriteInitDataRec));
end;
constructor Tf2AnimationDecorator.Create(const aPosX, aPosY, aPosZ: Single; aTexName: string;
const aTX, aTY, aWidth, aHeight, aFrames: Integer);
var
l_Tex: Id2dTexture;
begin
inherited Create(aPosX, aPosY, aPosZ, $FFFFFFFF);
f_TexName := aTexName;
l_Tex := gD2DE.Texture_Load(aTexName);
f_Sprite := Td2dTimedAnimation.Create(l_Tex, aFrames, aTX, aTY, aWidth, aHeight);
with f_InitRec do
begin
rTX := aTX;
rTY := aTY;
rWidth := aWidth;
rHeight:= aHeight;
end;
AniType := 1;
Speed := 250;
end;
constructor Tf2AnimationDecorator.Load(aFiler: Td2dFiler);
var
l_Tex: Id2dTexture;
l_Frames: Integer;
begin
inherited Load(aFiler);
f_TexName := aFiler.ReadString;
aFiler.Stream.ReadBuffer(f_InitRec, SizeOf(Tf2SpriteInitDataRec));
l_Tex := gD2DE.Texture_Load(f_TexName);
l_Frames := aFiler.ReadInteger;
with f_InitRec do
f_Sprite := Td2dTimedAnimation.Create(l_Tex, l_Frames, rTX, rTY, rWidth, rHeight);
AniType := aFiler.ReadInteger;
Td2dTimedAnimation(f_Sprite).CurFrame := aFiler.ReadInteger;
Speed := aFiler.ReadSingle;
f_Sprite.SetColor(f_Color);
Td2dTimedAnimation(f_Sprite).TimeSinceLastFrame := aFiler.ReadDouble;
f_Sprite.HotX := f_HotX;
f_Sprite.HotY := f_HotY;
f_Sprite.SetColor(f_Color);
ApplyFlips;
end;
function Tf2AnimationDecorator.pm_GetAniType: Integer;
begin
Result := f_AniType;
end;
function Tf2AnimationDecorator.pm_GetCurFrame: Integer;
begin
Result := Td2dTimedAnimation(f_Sprite).CurFrame;
end;
function Tf2AnimationDecorator.pm_GetDecoratorType: Tf2DecorType;
begin
Result := dtAnimation;
end;
function Tf2AnimationDecorator.pm_GetSpeed: Single;
begin
if Td2dTimedAnimation(f_Sprite).Playing then
begin
Result := Int(Td2dTimedAnimation(f_Sprite).Speed * 1000);
if Td2dTimedAnimation(f_Sprite).Reverse then
Result := -Result;
end
else
Result := 0;
end;
procedure Tf2AnimationDecorator.pm_SetAniType(Value: Integer);
begin
if Value < 0 then Value := 0;
if Value > 2 then Value := 2;
case Value of
0:
begin
Td2dTimedAnimation(f_Sprite).Looped := False;
end;
1:
begin
Td2dTimedAnimation(f_Sprite).Looped := True;
Td2dTimedAnimation(f_Sprite).LoopType := lt_OverAgain;
end;
2:
begin
Td2dTimedAnimation(f_Sprite).Looped := True;
Td2dTimedAnimation(f_Sprite).LoopType := lt_PingPong;
end;
end;
f_AniType := Value;
end;
procedure Tf2AnimationDecorator.pm_SetCurFrame(const Value: Integer);
begin
Td2dTimedAnimation(f_Sprite).Stop;
Td2dTimedAnimation(f_Sprite).CurFrame := Value;
end;
procedure Tf2AnimationDecorator.pm_SetSpeed(const Value: Single);
begin
if Value = 0.0 then
Td2dTimedAnimation(f_Sprite).Stop
else
begin
Td2dTimedAnimation(f_Sprite).Speed := Abs(Value)/1000;
Td2dTimedAnimation(f_Sprite).Reverse := (Value < 0);
Td2dTimedAnimation(f_Sprite).Resume;
end;
end;
procedure Tf2AnimationDecorator.Save(aFiler: Td2dFiler);
begin
inherited Save(aFiler);
aFiler.WriteString(f_TexName);
aFiler.Stream.WriteBuffer(f_InitRec, SizeOf(Tf2SpriteInitDataRec));
aFiler.WriteInteger(Td2dTimedAnimation(f_Sprite).FramesCount);
aFiler.WriteInteger(f_AniType);
aFiler.WriteInteger(CurFrame);
aFiler.WriteSingle(Speed);
aFiler.WriteDouble(Td2dTimedAnimation(f_Sprite).TimeSinceLastFrame);
end;
procedure Tf2AnimationDecorator.Update(const aDelta: Single);
begin
Td2dTimedAnimation(f_Sprite).Update(aDelta);
inherited Update(aDelta);
end;
constructor Tf2GIFDecorator.Create(const aPosX, aPosY, aPosZ: Single; aGIFName: string);
begin
inherited Create(aPosX, aPosY, aPosZ, $FFFFFFFF);
f_GIFName := aGIFName;
f_Sprite := Td2dGIFSprite.Create(aGIFName);
end;
constructor Tf2GIFDecorator.Load(aFiler: Td2dFiler);
var
l_Frame: Integer;
begin
inherited Load(aFiler);
f_GIFName := aFiler.ReadString;
f_Sprite := Td2dGIFSprite.Create(f_GIFName);
Td2dGIFSprite(f_Sprite).Stop; // для более точного восстановления кадра и скорости анимации
try
AniSpeed := aFiler.ReadInteger;
l_Frame := aFiler.ReadInteger;
Td2dGIFSprite(f_Sprite).Frame := l_Frame;
finally
Td2dGIFSprite(f_Sprite).Start;
end;
f_Sprite.HotX := f_HotX;
f_Sprite.HotY := f_HotY;
f_Sprite.SetColor(f_Color);
ApplyFlips;
end;
function Tf2GIFDecorator.pm_GetAniSpeed: Integer;
begin
Result := Td2dGIFSprite(f_Sprite).AniSpeed;
end;
function Tf2GIFDecorator.pm_GetDecoratorType: Tf2DecorType;
begin
Result := dtGIF;
end;
function Tf2GIFDecorator.pm_GetFrame: Integer;
begin
Result := Td2dGIFSprite(f_Sprite).Frame;
end;
procedure Tf2GIFDecorator.pm_SetAniSpeed(const Value: Integer);
begin
Td2dGIFSprite(f_Sprite).AniSpeed := Value;
end;
procedure Tf2GIFDecorator.pm_SetFrame(const Value: Integer);
begin
Td2dGIFSprite(f_Sprite).Frame := Value;
Td2dGIFSprite(f_Sprite).AniSpeed := 0;
end;
procedure Tf2GIFDecorator.Save(aFiler: Td2dFiler);
begin
inherited Save(aFiler);
aFiler.WriteString(f_GIFName);
aFiler.WriteInteger(AniSpeed);
aFiler.WriteInteger(Frame);
end;
procedure Tf2GIFDecorator.Update(const aDelta: Single);
begin
Td2dGIFSprite(f_Sprite).Update(aDelta);
inherited Update(aDelta);
end;
constructor Tf2ColoredDecorator.Create(const aPosX, aPosY, aPosZ: Single; const aColor: Td2dColor);
begin
inherited Create(aPosX, aPosY, aPosZ);
f_Color := aColor;
end;
constructor Tf2ColoredDecorator.Load(aFiler: Td2dFiler);
begin
inherited Load(aFiler);
with aFiler do
begin
f_Color := ReadColor;
if ReadBoolean then
f_ColorBlender := Td2dColorBlender.Load(aFiler);
end;
end;
procedure Tf2ColoredDecorator.BlendColor(const aTargetColor: Td2dColor; const aTime: Single);
begin
if f_ColorBlender <> nil then
FreeAndNil(f_ColorBlender);
f_ColorBlender := Td2dColorBlender.Create(aTime, f_Color, aTargetColor);
f_ColorBlender.Run;
end;
procedure Tf2ColoredDecorator.Cleanup;
begin
ClearColorBlender;
inherited;
end;
procedure Tf2ColoredDecorator.ClearColorBlender;
begin
if f_ColorBlender <> nil then
FreeAndNil(f_ColorBlender);
end;
procedure Tf2ColoredDecorator.DoExecuteScriptOperator(const aOp: If2DSOperator);
var
l_Color: Td2dColor;
l_A, l_R, l_G, l_B: Integer;
l_Time : Single;
function CorrectColorPart(const aReal: Double): Integer;
begin
Result := Trunc(aReal) mod 256;
if Result < 0 then
Result := 0;
end;
begin
case aOp.OpType of
otColor:
begin
l_Time := 0;
if aOp.ParamCount <= 2 then
begin
l_Color := CorrectColor(Trunc(aOp.Params[0].GetValue));
if aOp.ParamCount = 2 then
l_Time := aOp.Params[1].GetValue/1000;
end
else
begin
l_A := CorrectColorPart(aOp.Params[0].GetValue);
l_R := CorrectColorPart(aOp.Params[1].GetValue);
l_G := CorrectColorPart(aOp.Params[2].GetValue);
l_B := CorrectColorPart(aOp.Params[3].GetValue);
l_Color := ARGB(l_A, l_R, l_G, l_B);
if aOp.ParamCount = 5 then
l_Time := aOp.Params[4].GetValue/1000;
end;
if l_Time = 0 then
Color := l_Color
else
begin
BlendColor(l_Color, l_Time);
if not aOp.IsAsync then
ScriptDelay := l_Time;
end;
end;
else // case
inherited DoExecuteScriptOperator(aOp);
end;
end;
procedure Tf2ColoredDecorator.DoSetColor(aColor: Td2dColor);
begin
f_Color := aColor;
end;
procedure Tf2ColoredDecorator.pm_SetColor(const Value: Td2dColor);
begin
ClearColorBlender;
DoSetColor(Value);
end;
procedure Tf2ColoredDecorator.Save(aFiler: Td2dFiler);
var
l_NotNil: Boolean;
begin
inherited Save(aFiler);
with aFiler do
begin
WriteColor(f_Color);
l_NotNil := f_ColorBlender <> nil;
WriteBoolean(l_NotNil);
if l_NotNil then
f_ColorBlender.Save(aFiler);
end;
end;
procedure Tf2ColoredDecorator.Update(const aDelta: Single);
begin
UpdateColorBlending(aDelta);
inherited;
end;
procedure Tf2ColoredDecorator.UpdateColorBlending(const aDelta: Single);
begin
if f_ColorBlender <> nil then
begin
f_ColorBlender.Update(aDelta);
DoSetColor(f_ColorBlender.Current);
if not f_ColorBlender.IsRunning then
FreeAndNil(f_ColorBlender);
end;
end;
constructor Tf2ClickAreaDecorator.Create(const aPosX, aPosY, aPosZ: Single; const aContext: TFURQContext; const aWidth, aHeight: Single);
begin
inherited Create(aPosX, aPosY, aPosZ);
f_TargetProcessor := Tf2SingleTargetProcessor.Create(aContext);
Width := aWidth;
Height := aHeight;
f_Enabled := True;
f_Allowed := True;
f_MenuAlign := alTopLeft;
end;
constructor Tf2ClickAreaDecorator.Load(aFiler: Td2dFiler; aContext: TFURQContext);
begin
inherited Load(aFiler);
f_TargetProcessor := Tf2SingleTargetProcessor.Load(aFiler, aContext);
f_Width := aFiler.ReadSingle;
f_Height := aFiler.ReadSingle;
f_Enabled := aFiler.ReadBoolean;
f_MenuAlign := Td2dAlign(aFiler.ReadByte);
f_Allowed := True;
RecalcRect;
end;
function Tf2ClickAreaDecorator.AsActionDecorator: If2ActionDecorator;
begin
Result := Self;
end;
procedure Tf2ClickAreaDecorator.Cleanup;
begin
FreeAndNil(f_TargetProcessor);
inherited;
end;
procedure Tf2ClickAreaDecorator.DoRender;
begin
// пусто
//D2DRenderRect(f_Rect, $FFFF0000);
end;
procedure Tf2ClickAreaDecorator.DoSetPosX(const Value: Single);
begin
inherited;
RecalcRect;
gD2DE.Input_TouchMousePos;
end;
procedure Tf2ClickAreaDecorator.DoSetPosY(const Value: Single);
begin
inherited;
RecalcRect;
gD2DE.Input_TouchMousePos;
end;
function Tf2ClickAreaDecorator.GetActionsData(const anID: string): IFURQActionData;
begin
Result := f_TargetProcessor.GetActionsData(anID);
end;
function Tf2ClickAreaDecorator.GetTargetProcessor: Tf2SingleTargetProcessor;
begin
Result := f_TargetProcessor;
end;
function Tf2ClickAreaDecorator.pm_GetAllowed: Boolean;
begin
Result := f_Allowed;
end;
function Tf2ClickAreaDecorator.pm_GetDecoratorType: Tf2DecorType;
begin
Result := dtClickArea;
end;
function Tf2ClickAreaDecorator.pm_GetEnabled: Boolean;
begin
Result := f_Enabled;
end;
function Tf2ClickAreaDecorator.pm_GetWidth: Single;
begin
Result := f_Width;
end;
function Tf2ClickAreaDecorator.pm_GetHeight: Single;
begin
Result := f_Height;
end;
function Tf2ClickAreaDecorator.pm_GetMenuAlign: Td2dAlign;
begin
Result := f_MenuAlign;
end;
procedure Tf2ClickAreaDecorator.pm_SetAllowed(const Value: Boolean);
begin
f_Allowed := Value;
end;
procedure Tf2ClickAreaDecorator.pm_SetEnabled(const Value: Boolean);
begin
f_Enabled := Value;
end;
procedure Tf2ClickAreaDecorator.pm_SetWidth(const Value: Single);
begin
f_Width := Value;
RecalcRect;
end;
procedure Tf2ClickAreaDecorator.pm_SetHeight(const Value: Single);
begin
f_Height := Value;
RecalcRect;
end;
procedure Tf2ClickAreaDecorator.pm_SetMenuAlign(const Value: Td2dAlign);
begin
f_MenuAlign := Value;
end;
procedure Tf2ClickAreaDecorator.ProcessEvent(var theEvent: Td2dInputEvent);
begin
if f_Allowed and f_Enabled then
begin
if D2DIsPointInRect(gD2DE.MouseX, gD2DE.MouseY, f_Rect) then
begin
if (theEvent.EventType = INPUT_MBUTTONDOWN) and (theEvent.KeyCode = D2DK_LBUTTON) then
begin
f_TargetProcessor.ExecuteAction(f_Rect, f_MenuAlign);
Processed(theEvent);
end
else
if (theEvent.EventType = INPUT_MOUSEMOVE) and not IsMouseMoveMasked(theEvent) then
MaskMouseMove(theEvent);
end;
end;
end;
procedure Tf2ClickAreaDecorator.RecalcRect;
begin
f_Rect := D2DRect(PosX, PosY, PosX + Width, PosY + Height);
end;
procedure Tf2ClickAreaDecorator.Save(aFiler: Td2dFiler);
begin
inherited Save(aFiler);
f_TargetProcessor.Save(aFiler);
aFiler.WriteSingle(f_Width);
aFiler.WriteSingle(f_Height);
aFiler.WriteBoolean(f_Enabled);
aFiler.WriteByte(Ord(f_MenuAlign));
end;
constructor Tf2SingleTargetProcessor.Create(const aContext: TFURQContext);
begin
inherited Create;
f_Context := aContext;
end;
constructor Tf2SingleTargetProcessor.Load(aFiler: Td2dFiler; aContext: TFURQContext);
begin
inherited Create;
f_Context := aContext;
OnAction := Tf2Context(f_Context).OnDecoratorAction;
Target := aFiler.ReadString;
end;
procedure Tf2SingleTargetProcessor.ExecuteAction(const aRect: Td2dRect; const aMenuAlign: Td2dAlign);
begin
if Assigned(f_OnAction) and (f_ActionID <> '') then
f_OnAction(f_ActionID, aRect, aMenuAlign);
end;
function Tf2SingleTargetProcessor.GetActionsData(anID: string): IFURQActionData;
begin
if anID = f_ActionID then
Result := f_ActionData
else
Result := nil;
end;
procedure Tf2SingleTargetProcessor.pm_SetTarget(const aTarget: string);
var
l_AM: TFURQActionModifier;
l_LIdx: Integer;
l_Loc: string;
l_Params: IJclStringList;
begin
f_Target := aTarget;
l_Params := JclStringList;
ParseLocAndParams(aTarget, l_Loc, l_Params, l_AM);
l_LIdx := f_Context.Code.Labels.IndexOf(l_Loc);
if l_LIdx <> -1 then
begin
f_ActionData := TFURQActionData.Create(l_LIdx, l_Params, l_AM);
f_ActionID := ActionDataHash(f_ActionData);
end
else
begin
f_ActionID := '';
f_ActionData := nil;
end;
end;
procedure Tf2SingleTargetProcessor.Save(aFiler: Td2dFiler);
begin
aFiler.WriteString(Target);
end;
constructor Tf2CustomButtonDecorator.Create(const aPosX, aPosY, aPosZ: Single; const aContext: TFURQContext);
begin
inherited Create(aPosX, aPosY, aPosZ);
f_TargetProcessor := Tf2SingleTargetProcessor.Create(aContext);
f_Allowed := True;
f_Enabled := True;
f_MenuAlign := alTopLeft;
end;
constructor Tf2CustomButtonDecorator.Load(const aFiler: Td2dFiler; aContext: TFURQContext);
begin
inherited Load(aFiler);
f_TargetProcessor := Tf2SingleTargetProcessor.Load(aFiler, aContext);
f_Enabled := aFiler.ReadBoolean;
f_MenuAlign := Td2dAlign(aFiler.ReadByte);
LoadButton(aFiler, aContext);
f_Button.OnClick := ClickHandler;
f_Allowed := True;
UpdateButtonState;
end;
function Tf2CustomButtonDecorator.AsActionDecorator: If2ActionDecorator;
begin
Result := Self;
end;
procedure Tf2CustomButtonDecorator.Cleanup;
begin
FreeAndNil(f_Button);
FreeAndNil(f_TargetProcessor);
inherited;
end;
procedure Tf2CustomButtonDecorator.ClickHandler(aSender: TObject);
var
l_Rect: Td2dRect;
begin
l_Rect := D2DRect(f_Button.X, f_Button.Y, f_Button.X + f_Button.Width, f_Button.Y + f_Button.Height);
f_TargetProcessor.ExecuteAction(l_Rect, f_MenuAlign);
end;
procedure Tf2CustomButtonDecorator.DoRender;
begin
f_Button.Render;
end;
procedure Tf2CustomButtonDecorator.DoSetPosX(const Value: Single);
begin
inherited DoSetPosX(Value);
f_Button.X := Value;
gD2DE.Input_TouchMousePos;
end;
procedure Tf2CustomButtonDecorator.DoSetPosY(const Value: Single);
begin
inherited DoSetPosY(Value);
f_Button.Y := Value;
gD2DE.Input_TouchMousePos;
end;
function Tf2CustomButtonDecorator.GetActionsData(const anID: string): IFURQActionData;
begin
Result := f_TargetProcessor.GetActionsData(anID);
end;
function Tf2CustomButtonDecorator.GetTargetProcessor: Tf2SingleTargetProcessor;
begin
Result := f_TargetProcessor;
end;
function Tf2CustomButtonDecorator.pm_GetAllowed: Boolean;
begin
Result := f_Allowed;
end;
function Tf2CustomButtonDecorator.pm_GetEnabled: Boolean;
begin
Result := (f_Button <> nil) and (f_Button.Enabled);
end;
function Tf2CustomButtonDecorator.pm_GetHeight: Single;
begin
Result := f_Button.Height;
end;
function Tf2CustomButtonDecorator.pm_GetMenuAlign: Td2dAlign;
begin
Result := f_MenuAlign;
end;
function Tf2CustomButtonDecorator.pm_GetWidth: Single;
begin
Result := f_Button.Width;
end;
procedure Tf2CustomButtonDecorator.pm_SetAllowed(const Value: Boolean);
begin
f_Allowed := Value;
UpdateButtonState;
end;
procedure Tf2CustomButtonDecorator.pm_SetEnabled(const Value: Boolean);
begin
f_Enabled := Value;
UpdateButtonState;
end;
procedure Tf2CustomButtonDecorator.pm_SetMenuAlign(const Value: Td2dAlign);
begin
f_MenuAlign := Value;
end;
procedure Tf2CustomButtonDecorator.ProcessEvent(var theEvent: Td2dInputEvent);
begin
f_Button.ProcessEvent(theEvent);
end;
procedure Tf2CustomButtonDecorator.Save(aFiler: Td2dFiler);
begin
inherited Save(aFiler);
f_TargetProcessor.Save(aFiler);
aFiler.WriteBoolean(f_Enabled);
aFiler.WriteByte(Ord(f_MenuAlign));
SaveButton(aFiler);
end;
procedure Tf2CustomButtonDecorator.Update(const aDelta: Single);
begin
inherited Update(aDelta);
f_Button.FrameFunc(aDelta);
end;
procedure Tf2CustomButtonDecorator.UpdateButtonState;
begin
if f_Button <> nil then
f_Button.Enabled := f_Enabled and f_Allowed;
end;
constructor Tf2ImageButtonDecorator.Create(const aPosX, aPosY, aPosZ: Single; const aContext: TFURQContext; const
aTexName: string; aTx, aTy, aWidth, aHeight: Integer);
var
l_Tex: Id2dTexture;
begin
inherited Create(aPosX, aPosY, aPosZ, aContext);
l_Tex := gD2DE.Texture_Load(aTexName);
if l_Tex = nil then
raise EFURQRunTimeError.CreateFmt('Ошибка открытия файла %s', [aTexName]);
f_TextureName := aTexName;
f_TexX := aTx;
f_TexY := aTy;
f_Button := Td2dBitButton.Create(aPosX, aPosY, l_Tex, aTx, aTy, aWidth, aHeight);
f_Button.OnClick := ClickHandler;
end;
procedure Tf2ImageButtonDecorator.LoadButton(const aFiler: Td2dFiler; const aContext: TFURQContext);
var
l_Width, l_Height: Integer;
l_Tex: Id2dTexture;
begin
f_TextureName := aFiler.ReadString;
f_TexX := aFiler.ReadInteger;
f_TexY := aFiler.ReadInteger;
l_Width := aFiler.ReadInteger;
l_Height := aFiler.ReadInteger;
l_Tex := gD2DE.Texture_Load(f_TextureName);
if l_Tex = nil then
raise EFURQRunTimeError.CreateFmt('Ошибка открытия файла %s (при загрузке декоратора)', [f_TextureName]);
f_Button := Td2dBitButton.Create(PosX, PosY, l_Tex, f_TexX, f_TexY, l_Width, l_Height);
end;
function Tf2ImageButtonDecorator.pm_GetDecoratorType: Tf2DecorType;
begin
Result := dtImgButton;
end;
procedure Tf2ImageButtonDecorator.SaveButton(const aFiler: Td2dFiler);
begin
aFiler.WriteString(f_TextureName);
aFiler.WriteInteger(f_TexX);
aFiler.WriteInteger(f_TexY);
aFiler.WriteInteger(Trunc(f_Button.Width));
aFiler.WriteInteger(Trunc(f_Button.Height));
end;
constructor Tf2TextButtonDecorator.Create(const aPosX, aPosY, aPosZ: Single; const aContext: TFURQContext;
const aTextFrame, aText: string);
var
l_Frame: Id2dFramedButtonView;
begin
inherited Create(aPosX, aPosY, aPosZ, aContext);
f_TextFrame := aTextFrame;
l_Frame := Tf2Context(aContext).GetButtonFrame(aTextFrame);
if l_Frame = nil then
raise EFURQRunTimeError.Create('Невозможно создать текстовую кнопку-декоратор');
f_Button := Td2dFramedTextButton.Create(aPosX, aPosY, l_Frame, aText);
f_Button.OnClick := ClickHandler;
end;
procedure Tf2TextButtonDecorator.LoadButton(const aFiler: Td2dFiler; const aContext: TFURQContext);
var
l_Text: string;
l_Frame: Id2dFramedButtonView;
begin
f_TextFrame := aFiler.ReadString;
l_Text := aFiler.ReadString;
l_Frame := Tf2Context(aContext).GetButtonFrame(f_TextFrame);
f_Button := Td2dFramedTextButton.Create(PosX, PosY, l_Frame, l_Text);
end;
function Tf2TextButtonDecorator.pm_GetDecoratorType: Tf2DecorType;
begin
Result := dtTextButton;
end;
function Tf2TextButtonDecorator.pm_GetText: string;
begin
Result := Td2dFramedTextButton(f_Button).Caption;
end;
function Tf2TextButtonDecorator.pm_GetTextAlign: Td2dTextAlignType;
begin
Result := Td2dFramedTextButton(f_Button).TextAlign;
end;
function Tf2TextButtonDecorator.pm_GetWidth: Single;
begin
// TODO -cMM: Tf2TextButtonDecorator.pm_GetWidth default body inserted
Result := inherited pm_GetWidth;
end;
procedure Tf2TextButtonDecorator.pm_SetText(const Value: string);
begin
Td2dFramedTextButton(f_Button).Caption := Value;
end;
procedure Tf2TextButtonDecorator.pm_SetTextAlign(const Value: Td2dTextAlignType);
begin
Td2dFramedTextButton(f_Button).TextAlign := Value;
end;
procedure Tf2TextButtonDecorator.pm_SetWidth(const Value: Single);
begin
if Value = 0 then
Td2dFramedTextButton(f_Button).AutoSize := True
else
f_Button.Width := Value;
end;
procedure Tf2TextButtonDecorator.SaveButton(const aFiler: Td2dFiler);
begin
aFiler.WriteString(f_TextFrame);
aFiler.WriteString(Text);
end;
end.
|
unit fmuCustomerLetters;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, AtrPages, ToolCtrlsEh, ComCtrls, ToolWin,
GridsEh, DBGridEh, DB, FIBDataSet, pFIBDataSet, ActnList,
DBGridEhToolCtrls, Buttons, ExtCtrls, DBAxisGridsEh,
System.Actions, PrjConst, EhLibVCL, System.UITypes, DBGridEhGrouping,
DynVarsEh;
type
TapgCustomerLetters = class(TA4onPage)
dsLetters: TpFIBDataSet;
srcLetters: TDataSource;
dbgLetters: TDBGridEh;
ActListCustomers: TActionList;
actLetterDel: TAction;
pnlButtons: TPanel;
btnDel: TSpeedButton;
procedure actLetterDelExecute(Sender: TObject);
procedure srcLettersDataChange(Sender: TObject; Field: TField);
private
{ Private declarations }
procedure EnableControls;
public
procedure InitForm; override;
procedure OpenData; override;
procedure CloseData; override;
class function GetPageName: string; override;
end;
implementation
uses DM, MAIN;
{$R *.dfm}
class function TapgCustomerLetters.GetPageName: string;
begin
Result := rsLettersAndMessages;
end;
procedure TapgCustomerLetters.InitForm;
var
FullAccess : Boolean;
begin
FullAccess := (dmMain.AllowedAction(rght_Customer_full)); // Полный доступ
actLetterDel.Visible := FullAccess;
pnlButtons.Visible := FullAccess;
dsLetters.DataSource := FDataSource;
end;
procedure TapgCustomerLetters.OpenData;
begin
if dsLetters.Active then
dsLetters.Close;
dsLetters.OrderClause := GetOrderClause(dbgLetters);
dsLetters.Open;
EnableControls;
end;
procedure TapgCustomerLetters.actLetterDelExecute(Sender: TObject);
begin
if (MessageDlg(rsDeleteLetter, mtConfirmation, [mbYes, mbNo], 0) = mrNo)
then Exit;
if (dsLetters.FieldByName('ITS_LETTER').IsNull or (dsLetters['ITS_LETTER'] = 1))
then
dsLetters.SQLs.DeleteSQL.Text := 'delete from Custletter where Custletterid = :OLD_Mes_Id'
else
dsLetters.SQLs.DeleteSQL.Text := 'delete from MESSAGES where MES_ID = :OLD_Mes_Id and MES_RESULT <= 0';
dsLetters.Delete;
EnableControls;
end;
procedure TapgCustomerLetters.CloseData;
begin
dsLetters.Close;
end;
procedure TapgCustomerLetters.EnableControls;
begin
actLetterDel.Enabled := actLetterDel.Visible and ( dsLetters.RecordCount>0 );
end;
procedure TapgCustomerLetters.srcLettersDataChange(Sender: TObject;
Field: TField);
begin
actLetterDel.Enabled := (actLetterDel.Visible) // and (not dsLetters.FieldByName('ITS_LETTER').IsNull) and (dsLetters.FieldByName('ITS_LETTER').AsInteger = 1)
end;
end.
|
unit nsFolderFilterInfo;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Библиотека "Search"
// Модуль: "w:/garant6x/implementation/Garant/GbaNemesis/Search/nsFolderFilterInfo.pas"
// Родные Delphi интерфейсы (.pas)
// Generated from UML model, root element: <<SimpleClass::Class>> F1 Common For Shell And Monitoring::Search::Search::Search::TnsFolderFilterInfo
//
//
// Все права принадлежат ООО НПП "Гарант-Сервис".
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ! Полностью генерируется с модели. Править руками - нельзя. !
{$Include w:\garant6x\implementation\Garant\nsDefine.inc}
interface
{$If not defined(Admin) AND not defined(Monitorings)}
uses
l3SimpleObject,
FoldersDomainInterfaces,
l3Interfaces,
l3NotifyPtrList
;
{$IfEnd} //not Admin AND not Monitorings
{$If not defined(Admin) AND not defined(Monitorings)}
type
_l3Notifier_Parent_ = Tl3SimpleObject;
{$Include w:\common\components\rtl\Garant\L3\l3Notifier.imp.pas}
TnsFolderFilterInfo = class(_l3Notifier_, InsFolderFilterInfo)
private
// private fields
f_FilterType : TnsFolderFilter;
f_FilterFor : TnsFolderFilterFor;
f_ShowFolders : TnsShowFolders;
private
// private methods
procedure NotifyAboutChanged;
protected
// realized methods
function IsSame(const aValue: InsFolderFilterInfo): Boolean;
function pm_GetFilterFor: TnsFolderFilterFor;
function pm_GetFilterType: TnsFolderFilter;
procedure pm_SetFilterType(aValue: TnsFolderFilter);
function pm_GetShowFolders: TnsShowFolders;
procedure pm_SetShowFolders(aValue: TnsShowFolders);
public
// public methods
constructor Create(aFilterType: TnsFolderFilter;
aFilterFor: TnsFolderFilterFor;
aShowFolders: TnsShowFolders = sfAll); reintroduce;
class function Make(aFilterType: TnsFolderFilter;
aFilterFor: TnsFolderFilterFor;
aShowFolders: TnsShowFolders = sfAll): InsFolderFilterInfo; reintroduce;
{* Сигнатура фабрики TnsFolderFilterInfo.Make }
protected
// Методы преобразования к реализуемым интерфейсам
function As_Il3ChangeNotifier: Il3ChangeNotifier;
end;//TnsFolderFilterInfo
{$IfEnd} //not Admin AND not Monitorings
implementation
{$If not defined(Admin) AND not defined(Monitorings)}
uses
l3Base,
SysUtils
;
{$IfEnd} //not Admin AND not Monitorings
{$If not defined(Admin) AND not defined(Monitorings)}
{$Include w:\common\components\rtl\Garant\L3\l3Notifier.imp.pas}
// start class TnsFolderFilterInfo
procedure TnsFolderFilterInfo.NotifyAboutChanged;
//#UC START# *4BA3AA6D0181_4BA232B402FF_var*
var
l_Index : Integer;
l_Intf : InsFolderFilterInfoListener;
l_Item : IUnknown;
//#UC END# *4BA3AA6D0181_4BA232B402FF_var*
begin
//#UC START# *4BA3AA6D0181_4BA232B402FF_impl*
if (NotifiedObjList <> nil) then
for l_Index := NotifiedObjList.Hi downto 0 do
begin
l_Item := IUnknown(f_NotifiedObjList[l_Index]);
if Supports(l_Item, InsFolderFilterInfoListener, l_Intf) AND
(l_Item = l_Intf) then
try
l_Intf.Changed;
finally
l_Intf := nil;
end;//try..finaly
end;//for l_Index := NotifiedObjList.Hi downto 0 do
//#UC END# *4BA3AA6D0181_4BA232B402FF_impl*
end;//TnsFolderFilterInfo.NotifyAboutChanged
constructor TnsFolderFilterInfo.Create(aFilterType: TnsFolderFilter;
aFilterFor: TnsFolderFilterFor;
aShowFolders: TnsShowFolders = sfAll);
//#UC START# *4BA3A8330320_4BA232B402FF_var*
//#UC END# *4BA3A8330320_4BA232B402FF_var*
begin
//#UC START# *4BA3A8330320_4BA232B402FF_impl*
inherited Create;
f_FilterType := aFilterType;
f_FilterFor := aFilterFor;
f_ShowFolders := aShowFolders;
//#UC END# *4BA3A8330320_4BA232B402FF_impl*
end;//TnsFolderFilterInfo.Create
class function TnsFolderFilterInfo.Make(aFilterType: TnsFolderFilter;
aFilterFor: TnsFolderFilterFor;
aShowFolders: TnsShowFolders = sfAll): InsFolderFilterInfo;
var
l_Inst : TnsFolderFilterInfo;
begin
l_Inst := Create(aFilterType, aFilterFor, aShowFolders);
try
Result := l_Inst;
finally
l_Inst.Free;
end;//try..finally
end;
function TnsFolderFilterInfo.IsSame(const aValue: InsFolderFilterInfo): Boolean;
//#UC START# *49900FC80246_4BA232B402FF_var*
//#UC END# *49900FC80246_4BA232B402FF_var*
begin
//#UC START# *49900FC80246_4BA232B402FF_impl*
Result := (aValue = nil) or
((f_FilterType = aValue.FilterType) and (f_FilterFor = aValue.FilterFor));
//#UC END# *49900FC80246_4BA232B402FF_impl*
end;//TnsFolderFilterInfo.IsSame
function TnsFolderFilterInfo.pm_GetFilterFor: TnsFolderFilterFor;
//#UC START# *4990101E01A4_4BA232B402FFget_var*
//#UC END# *4990101E01A4_4BA232B402FFget_var*
begin
//#UC START# *4990101E01A4_4BA232B402FFget_impl*
Result := f_FilterFor;
//#UC END# *4990101E01A4_4BA232B402FFget_impl*
end;//TnsFolderFilterInfo.pm_GetFilterFor
function TnsFolderFilterInfo.pm_GetFilterType: TnsFolderFilter;
//#UC START# *499010600294_4BA232B402FFget_var*
//#UC END# *499010600294_4BA232B402FFget_var*
begin
//#UC START# *499010600294_4BA232B402FFget_impl*
Result := f_FilterType;
//#UC END# *499010600294_4BA232B402FFget_impl*
end;//TnsFolderFilterInfo.pm_GetFilterType
procedure TnsFolderFilterInfo.pm_SetFilterType(aValue: TnsFolderFilter);
//#UC START# *499010600294_4BA232B402FFset_var*
//#UC END# *499010600294_4BA232B402FFset_var*
begin
//#UC START# *499010600294_4BA232B402FFset_impl*
if f_FilterType <> aValue then
begin
f_FilterType := aValue;
NotifyAboutChanged;
end;//if f_FilterType <> aValue then
//#UC END# *499010600294_4BA232B402FFset_impl*
end;//TnsFolderFilterInfo.pm_SetFilterType
function TnsFolderFilterInfo.pm_GetShowFolders: TnsShowFolders;
//#UC START# *49901491011E_4BA232B402FFget_var*
//#UC END# *49901491011E_4BA232B402FFget_var*
begin
//#UC START# *49901491011E_4BA232B402FFget_impl*
Result := f_ShowFolders;
//#UC END# *49901491011E_4BA232B402FFget_impl*
end;//TnsFolderFilterInfo.pm_GetShowFolders
procedure TnsFolderFilterInfo.pm_SetShowFolders(aValue: TnsShowFolders);
//#UC START# *49901491011E_4BA232B402FFset_var*
//#UC END# *49901491011E_4BA232B402FFset_var*
begin
//#UC START# *49901491011E_4BA232B402FFset_impl*
if f_ShowFolders <> aValue then
begin
f_ShowFolders := aValue;
NotifyAboutChanged;
end;//if f_ShowFolders <> aValue then
//#UC END# *49901491011E_4BA232B402FFset_impl*
end;//TnsFolderFilterInfo.pm_SetShowFolders
// Методы преобразования к реализуемым интерфейсам
function TnsFolderFilterInfo.As_Il3ChangeNotifier: Il3ChangeNotifier;
begin
Result := Self;
end;
{$IfEnd} //not Admin AND not Monitorings
end. |
unit DriveCombo;
// Copyright (c) 1998 Jorge Romero Gomez, Merchise
interface
uses
Windows, Messages, SysUtils, Classes, Controls, StdCtrls,
Graphics;
// TDriveComboBox
type
TFilterDrive = procedure( Drive : char; var SkipDrive : boolean ) of object;
type
TDriveType = ( dtUnknown, dtNoDrive, dtFloppy, dtFixed, dtNetwork, dtCDROM, dtRAM );
type
TTextCase = ( tcLowerCase, tcUpperCase );
type
TDrivesCombo =
class( TCustomComboBox )
private
fDrive : char;
fTextCase : TTextCase;
fOnFilterDrive : TFilterDrive;
procedure CMFontChanged( var Message : TMessage ); message CM_FONTCHANGED;
procedure SetDrive( NewDrive : char );
procedure SetTextCase( NewTextCase : TTextCase );
procedure ReadBitmaps;
procedure ResetItemHeight;
protected
FloppyBMP, FixedBmp, NetworkBmp, CdromBmp, RamBmp : TBitmap;
procedure CreateWnd; override;
procedure DrawItem( Index : integer; Rect : TRect; State : TOwnerDrawState ); override;
procedure Click; override;
procedure BuildList; virtual;
public
constructor Create( AOwner : TComponent ); override;
destructor Destroy; override;
public
property Drive : char read fDrive write SetDrive;
published
property TextCase : TTextCase read fTextCase write SetTextCase default tcLowerCase;
property OnFilterDrive : TFilterDrive read fOnFilterDrive write fOnFilterDrive;
public
property Text;
published
property Color;
property Ctl3D;
property DragMode;
property DragCursor;
property Enabled;
property Font;
property ImeMode;
property ImeName;
property ParentColor;
property ParentCtl3D;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property TabOrder;
property TabStop;
property Visible;
property OnChange;
property OnClick;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnDropDown;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnStartDrag;
end;
// Component registration
procedure Register;
implementation
uses
GDI, FilenameUtils, NetUtils, NumUtils;
{$R *.res}
{$R *.dcr}
// TDrivesCombo
constructor TDrivesCombo.Create( AOwner : TComponent );
var
Temp : string;
begin
inherited;
Style := csOwnerDrawFixed;
ReadBitmaps;
GetDir( 0, Temp );
fDrive := Temp[1]; // Make default drive selected
if fDrive = '\'
then fDrive := #0;
ResetItemHeight;
end;
destructor TDrivesCombo.Destroy;
begin
FloppyBmp.Free;
FixedBmp.Free;
NetworkBmp.Free;
CdromBmp.Free;
RamBmp.Free;
inherited;
end;
procedure TDrivesCombo.BuildList;
var
DriveNum : integer;
DriveChar : char;
DriveType : TDriveType;
DriveBits : set of 0..25;
SkipDrive : boolean;
procedure AddDrive( const VolName : string; Obj : TObject );
begin
Items.AddObject( Format( '%s: %s', [DriveChar, VolName] ), Obj );
end;
begin
// Fill list
Clear;
integer( DriveBits ) := GetLogicalDrives;
for DriveNum := 0 to 25 do
begin
DriveChar := char( DriveNum + Ord( 'a' ) );
SkipDrive := false;
if Assigned( OnFilterDrive )
then OnFilterDrive( DriveChar, SkipDrive )
else SkipDrive := not ( DriveNum in DriveBits );
if not SkipDrive
then
begin
DriveType := TDriveType( GetDriveType( pchar( DriveChar + ':\' ) ) );
if TextCase = tcUpperCase
then DriveChar := Upcase( DriveChar );
case DriveType of
dtFloppy :
Items.AddObject( DriveChar + ':', FloppyBmp );
dtFixed :
AddDrive( VolumeID( DriveChar ), FixedBmp );
dtNetwork :
AddDrive( NetworkPath( DriveChar ), NetworkBmp );
dtCDROM :
AddDrive( VolumeID( DriveChar ), CdromBmp );
dtRAM :
AddDrive( VolumeID( DriveChar ), RamBmp );
else
Items.AddObject( DriveChar + ':', FixedBmp );
end;
end;
end;
end;
procedure TDrivesCombo.SetDrive( NewDrive : char );
var
Item : integer;
drv : string;
begin
if ( ItemIndex < 0 ) or ( UpCase( NewDrive ) <> UpCase( fDrive ) )
then
begin
if NewDrive = #0
then
begin
fDrive := NewDrive;
ItemIndex := -1;
end
else
begin
if TextCase = tcUpperCase
then fDrive := UpCase( NewDrive )
else fDrive := Chr( ord( UpCase( NewDrive ) ) + 32 );
// Change selected item
for Item := 0 to Items.Count - 1 do
begin
drv := Items[Item];
if ( UpCase( drv[1] ) = UpCase( fDrive ) ) and ( drv[2] = ':' )
then
begin
ItemIndex := Item;
break;
end;
end;
end;
Change;
end;
end;
procedure TDrivesCombo.SetTextCase( NewTextCase : TTextCase );
var
OldDrive : char;
begin
fTextCase := NewTextCase;
OldDrive := fDrive;
BuildList;
SetDrive( OldDrive );
end;
procedure TDrivesCombo.CreateWnd;
var
i : integer;
begin
inherited;
BuildList;
i := 0;
while ( i < Items.Count ) and ( UpperCase( Items[i][1] ) <> UpperCase( fDrive ) ) do
inc( i );
if i < Items.Count
then SetDrive( fDrive )
else SetDrive( Items[0][1] );
end;
procedure TDrivesCombo.DrawItem( Index : integer; Rect : TRect; State : TOwnerDrawState );
var
Str : pchar;
Bitmap : TBitmap;
BufRect : TRect;
BufBmp : TBitmap;
begin
BufRect := Rect;
OffsetRect( BufRect, -Rect.Left, -Rect.Top );
BufBmp := TBitmap.Create;
try
BufBmp.Width := BufRect.Right;
BufBmp.Height := BufRect.Bottom;
with BufBmp.Canvas do
begin
Font.Assign( Canvas.Font );
Pen.Assign( Canvas.Pen );
Brush.Assign( Canvas.Brush );
FillRect( BufRect );
Bitmap := TBitmap( Items.Objects[Index] );
if Assigned( Bitmap )
then
with Bitmap do
begin
BrushCopy( Bounds( 2, ( BufRect.Bottom - Height ) div 2, Width, Height ),
Bitmap, Bounds( 0, 0, Width, Height ), Canvas.Pixels[0, Height - 1] );
end;
// Uses DrawText instead of TextOut in order to get clipping against
// the combo box button
Str := pchar( Items[Index] );
BufRect.Left := 22;
DrawText( Handle, Str, 2, BufRect, DT_SINGLELINE or DT_VCENTER or DT_NOPREFIX );
if Str[3] <> #0
then
begin
BufRect.Left := BufRect.Left + 35;
DrawText( Handle, Str + 2, -1, BufRect, DT_SINGLELINE or DT_VCENTER or DT_NOPREFIX );
end;
end;
Canvas.Draw( Rect.Left, Rect.Top, BufBmp );
finally
BufBmp.Free;
end;
end;
procedure TDrivesCombo.Click;
begin
inherited;
if ItemIndex >= 0
then Drive := Items[ItemIndex][1];
end;
procedure TDrivesCombo.CMFontChanged( var Message : TMessage );
begin
inherited;
ResetItemHeight;
RecreateWnd;
end;
procedure TDrivesCombo.ResetItemHeight;
var
nuHeight : integer;
begin
nuHeight := GetTextHeight( Font.Handle );
if nuHeight < ( FloppyBmp.Height )
then nuHeight := FloppyBmp.Height;
ItemHeight := nuHeight + 2;
end;
procedure TDrivesCombo.ReadBitmaps;
begin
// Assign bitmap glyphs
FloppyBmp := TBitmap.Create;
FloppyBmp.Handle := LoadBitmap( hInstance, 'ICO_FLOPPYDRIVE' );
FixedBmp := TBitmap.Create;
FixedBmp.Handle := LoadBitmap( hInstance, 'ICO_HARDDRIVE' );
NetworkBmp := TBitmap.Create;
NetworkBmp.Handle := LoadBitmap( hInstance, 'ICO_NETWORKDRIVE' );
CdromBmp := TBitmap.Create;
CdromBmp.Handle := LoadBitmap( hInstance, 'ICO_CDROMDRIVE' );
RamBmp := TBitmap.Create;
RamBmp.Handle := LoadBitmap( hInstance, 'ICO_RAMDRIVE' );
end;
// Component registration
procedure Register;
begin
RegisterComponents( 'Merchise', [TDrivesCombo] );
end;
end.
|
unit tcDifference;
interface
uses
tcInterfaces
;
procedure tcBuildDifference(const aSource, aNew: ItcToolBarsList; OldMode: Boolean;
out anAddedToolbars: ItcAddedToolBarsList; out aChangedToolBars: ItcChangedToolBarsList);
implementation
uses
SysUtils,
l3Base,
l3Types,
l3String,
tcAddedToolBarsList,
tcChangedToolBarsList
;
type
TtcChange = procedure(const anItem, aParent: ItcItem) of Object;
TtcComparer = class(Tl3Base)
private
f_SourceDesc: ItcToolBarsList;
f_NewDesc: ItcToolBarsList;
f_Added: ItcAddedToolBarsList;
f_Changed: ItcChangedToolBarsList;
f_ComparingToolBar: ItcChangedToolBar;
f_OldMode: Boolean;
private
procedure ToolBarAdded(const anItem, aParent: ItcItem);
procedure ToolbarEqual(const anItem, aParent: ItcItem);
procedure ChildToolBarDeleted(const anItem, aParent: ItcItem);
procedure ChildToolBarAdded(const anItem, aParent: ItcItem);
procedure OperationDeleted(const anItem, aParent: ItcItem);
procedure OperationAdded(const anItem, aParent: ItcItem);
function ComparingToolBar(const anItem: ItcItem): ItcChangedToolBar;
private
property AddedToolBars: ItcAddedToolBarsList
read f_Added;
property ChangedToolBars: ItcChangedToolBarsList
read f_Changed;
protected
procedure Cleanup; override;
public
constructor Create(const aSource, aNew: ItcToolBarsList; OldMode: Boolean); reintroduce;
end;
procedure tcBuildDifference(const aSource, aNew: ItcToolBarsList; OldMode: Boolean;
out anAddedToolbars: ItcAddedToolBarsList; out aChangedToolBars: ItcChangedToolBarsList);
var
l_Comparer: TtcComparer;
begin
l_Comparer := TtcComparer.Create(aSource, aNew, OldMode);
try
anAddedToolbars := l_Comparer.AddedToolBars;
aChangedToolBars := l_Comparer.ChangedToolBars;
finally
FreeAndNil(l_Comparer);
end;
end;
procedure DoCompare(const aSource, aTarget: ItcItemList; onDelete, onEqual, onAdd: TtcChange;
aParent: ItcItem);
var
l_SourceIDX: Integer;
l_TargetIDX: Integer;
l_IDX: Integer;
l_Comp: Long;
begin
l_SourceIDX := 0;
l_TargetIDX := 0;
repeat
if l_SourceIDX >= aSource.Count then
begin
if Assigned(onAdd) then
for l_IDX := l_TargetIDX to aTarget.Count - 1 do
onAdd(aTarget.Item[l_IDX], aParent);
exit;
end;
if l_TargetIDX >= aTarget.Count then
begin
if Assigned(onDelete) then
for l_IDX := l_SourceIDX to aSource.Count - 1 do
onDelete(aSource.Item[l_IDX], aParent);
exit;
end;
l_Comp := l3Compare(aSource.Item[l_SourceIDX].ID.AsWStr, aTarget.Item[l_TargetIDX].ID.AsWStr);
if l_Comp = 0 then
begin
if Assigned(onEqual) then
onEqual(aTarget.Item[l_TargetIDX], aParent);
Inc(l_SourceIDX);
Inc(l_TargetIDX);
end
else
if l_Comp < 0 then
begin
if Assigned(onDelete) then
onDelete(aSource.Item[l_SourceIDX], aParent);
inc(l_SourceIDX);
end
else
begin
if Assigned(onAdd) then
onAdd(aTarget.Item[l_TargetIDX], aParent);
inc(l_TargetIDX);
end;
until False;
end;
{ TtcComparer }
procedure TtcComparer.ChildToolBarAdded(const anItem, aParent: ItcItem);
begin
ComparingToolBar(aParent).AddedChildren.AddExisting(f_NewDesc.Add(anItem.ID));
end;
procedure TtcComparer.ChildToolBarDeleted(const anItem, aParent: ItcItem);
begin
ComparingToolBar(aParent).DeletedChildren.AddExisting(f_SourceDesc.Add(anItem.ID));
end;
procedure TtcComparer.Cleanup;
begin
f_SourceDesc := nil;
f_NewDesc := nil;
f_Added := nil;
f_Changed := nil;
f_ComparingToolBar := nil;
inherited Cleanup;
end;
function TtcComparer.ComparingToolBar(const anItem: ItcItem): ItcChangedToolBar;
begin
if f_ComparingToolBar = nil then
begin
f_ComparingToolBar := f_Changed.Add(l3Cat([anItem.Caption, anItem.ID]));
f_ComparingToolBar.ToolBar := f_NewDesc.Add(anItem.ID);
end;
Result := f_ComparingToolBar;
end;
constructor TtcComparer.Create(const aSource, aNew: ItcToolBarsList; OldMode: Boolean);
begin
inherited Create;
f_SourceDesc := aSource;
f_NewDesc := aNew;
f_Added := TtcAddedToolBarsList.Make;
f_Changed := TtcChangedToolBarsList.Make;
f_OldMode := OldMode;
DoCompare(f_SourceDesc as ItcItemList, f_NewDesc as ItcItemList, nil, ToolbarEqual, ToolBarAdded, nil);
end;
procedure TtcComparer.OperationAdded(const anItem, aParent: ItcItem);
begin
ComparingToolBar(aParent).AddedOperations.AddExisting(f_NewDesc.Add(aParent.ID).Operations.Add(anItem.ID));
end;
procedure TtcComparer.OperationDeleted(const anItem, aParent: ItcItem);
begin
ComparingToolBar(aParent).DeletedOperations.AddExisting(f_SourceDesc.Add(aParent.ID).Operations.Add(anItem.ID));
end;
procedure TtcComparer.ToolBarAdded(const anItem, aParent: ItcItem);
begin
with f_Added.Add(l3Cat([anItem.Caption, anItem.ID])) do
ToolBar := f_NewDesc.Add(anItem.ID);
end;
procedure TtcComparer.ToolbarEqual(const anItem, aParent: ItcItem);
const
c_Map: array [Boolean] of TtcEditableChange = (ecRevokeEditable, ecBecomeEditable);
begin
f_ComparingToolBar := nil;
if not f_OldMode then
if f_SourceDesc.Add(anItem.ID).Editable xor f_NewDesc.Add(anItem.ID).Editable then
ComparingToolBar(anItem).EditableChange := c_Map[f_NewDesc.Add(anItem.ID).Editable];
if l3Compare(f_SourceDesc.Add(anItem.ID).Caption.AsWStr, f_NewDesc.Add(anItem.ID).Caption.AsWStr) <> 0 then
ComparingToolBar(anItem).OldCaption := f_SourceDesc.Add(anItem.ID).Caption;
if not f_OldMode then
DoCompare(f_SourceDesc.Add(anItem.ID).ChildToolBars as ItcItemList, f_NewDesc.Add(anItem.ID).ChildToolBars as ItcItemList,
ChildToolBarDeleted, nil, ChildToolBarAdded, anItem);
DoCompare(f_SourceDesc.Add(anItem.ID).Operations as ItcItemList, f_NewDesc.Add(anItem.ID).Operations as ItcItemList,
OperationDeleted, nil, OperationAdded, anItem);
end;
end.
|
{ Pubby - a flexible pub/sub implementation
Copyright (c) 2018 mr-highball
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.
}
unit pubby;
{$mode delphi}{$H+}
interface
uses
Classes, SysUtils;
type
TIntfList =
{$IFDEF FPC}
TInterfaceList
{$ELSE}
//todo - look at embarcadero wiki to find proper class,
//may be the same definition as fgl
TInterfaceList
{$ENDIF};
//forward
IPublisher<T> = interface;
ISubscriber<T> = interface;
(*
event triggered by a subscriber if calling Notify results in failure
*)
TSubNotifyErrorEvent<TSubscriber, T> = procedure(Const ASubscriber : TSubscriber;
Const AMessage:T;Const AError:String) of object;
(*
event occurring directly before Notify logic is called. If AbortNotfiy
is set to True, then Notify logic will not run and report success
*)
TSubBeforeNotifyEvent<TSubscriber, T> = procedure(Const ASubscriber : TSubscriber;
Const AMessage:T;Out AbortNotify:Boolean) of object;
(*
event occurring after notify success
*)
TSubAfterNotifyEvent<TSubscriber, T> = procedure(Const ASubscriber : TSubscriber;
Const AMessage:T) of object;
(*
event triggered by a publisher if calling Notify of a subscriber results
in failure
*)
TPubNotifyErrorEvent<TPublisher, TSubscriber, T> = procedure(Const APublisher : TPublisher;
Const ASubscriber : TSubscriber;Const AMessage:T;Const AError:String) of object;
{ ISubscriber }
(*
subscriber to a publisher
*)
ISubscriber<T> = interface
['{295F4B43-35DB-4A36-9651-61984D61A7FE}']
//property methods
function GetErrorEvent: TSubNotifyErrorEvent<ISubscriber<T>,T>;
procedure SetErrorEvent(AValue: TSubNotifyErrorEvent<ISubscriber<T>,T>);
procedure SetAfterEvent(AValue: TSubAfterNotifyEvent<ISubscriber<T>,T>);
procedure SetBeforeEvent(AValue: TSubBeforeNotifyEvent<ISubscriber<T>,T>);
function GetAfterEvent: TSubAfterNotifyEvent<ISubscriber<T>,T>;
function GetBeforeEvent: TSubBeforeNotifyEvent<ISubscriber<T>,T>;
//properties
property OnError : TSubNotifyErrorEvent<ISubscriber<T>,T> read GetErrorEvent
write SetErrorEvent;
property OnBeforeNotify : TSubBeforeNotifyEvent<ISubscriber<T>,T> read GetBeforeEvent
write SetBeforeEvent;
property OnAfterNotify : TSubAfterNotifyEvent<ISubscriber<T>,T> read GetAfterEvent
write SetAfterEvent;
//methods
function Notify(Const AMessage:T;Const APublisher : IPublisher<T>;
Out Error:String):Boolean;
end;
{ IPublisher }
(*
publisher of some type of message
*)
IPublisher<T> = interface
['{E2F65A97-6293-4FAD-B264-BDA6C98F1D4B}']
//property methods
function GetErrorEvent: TPubNotifyErrorEvent;
procedure SetErrorEvent(AValue: TPubNotifyErrorEvent);
//properties
property OnError : TPubNotifyErrorEvent read GetErrorEvent
write SetErrorEvent;
//methods
procedure Subscribe(Const ASubscriber:ISubscriber);
procedure Unsubscribe(Const ASubscriber:ISubscriber);
procedure Notify(Const AMessage:T);
end;
{ TSubscriberImpl }
(*
base class implementing the ISubscriber interface
*)
TSubscriberImpl<T> = class(TInterfacedObject,ISubscriber<T>)
protected
type
ITypedSubscriber = ISubscriber<T>;
//ITypedPublisher = IPublisher<T>; I
strict private
FErrorEvent : TSubNotifyErrorEvent<T>;
FBeforeEvent : TSubBeforeNotifyEvent<T>;
FAfterEvent : TSubAfterNotifyEvent<T>;
function GetAfterEvent: TSubAfterNotifyEvent;
function GetBeforeEvent: TSubBeforeNotifyEvent;
function GetErrorEvent: TSubNotifyErrorEvent;
procedure SetAfterEvent(AValue: TSubAfterNotifyEvent);
procedure SetBeforeEvent(AValue: TSubBeforeNotifyEvent);
procedure SetErrorEvent(AValue: TSubNotifyErrorEvent);
strict protected
procedure DoOnError(Const ASender:ITypedSubscriber;
Const AMessage:T;Const AError:String);
procedure DoOnBeforeNotify(Const ASender:ITypedSubscriber;
Const AMessage:T;Out AbortNotify:Boolean);
procedure DoOnAfterNotify(Const ASender:ITypedSubscriber;Const AMessage:T);
//children classes need to override this to perform notify logic
function DoNotify(Const AMessage:T;Const APublisher:IPublisher<T>;
Out Error:String):Boolean;virtual;abstract;
public
property OnError : TSubNotifyErrorEvent read GetErrorEvent
write SetErrorEvent;
property OnBeforeNotify : TSubBeforeNotifyEvent read GetBeforeEvent
write SetBeforeEvent;
property OnAfterNotify : TSubAfterNotifyEvent read GetAfterEvent
write SetAfterEvent;
function Notify(Const AMessage:T;Const APublisher:ITypedPublisher;
Out Error:String):Boolean;
end;
{ TPublisherImpl }
(*
base class implementing the IPublisher interface
*)
TPublisherImpl<T> = class(TInterfacedObject,IPublisher<T>)
strict private
FErrorEvent : TPubNotifyErrorEvent<T>;
FList : TIntfList;
function GetErrorEvent: TPubNotifyErrorEvent;
procedure SetErrorEvent(AValue: TPubNotifyErrorEvent);
strict protected
procedure DoOnError(Const ASender:IPublisher<T>;
Const ASubscriber:ISubscriber<T>;Const AMessage:T;Const AError:String);
public
property OnError : TPubNotifyErrorEvent read GetErrorEvent
write SetErrorEvent;
procedure Subscribe(Const ASubscriber:ISubscriber);
procedure Unsubscribe(Const ASubscriber:ISubscriber);
procedure Notify(Const AMessage:T);
constructor Create;virtual;
destructor Destroy; override;
end;
implementation
{ TSubscriberImpl }
function TSubscriberImpl<T>.GetAfterEvent: TSubAfterNotifyEvent<T>;
begin
Result:=@FAfterEvent;
end;
function TSubscriberImpl<T>.GetBeforeEvent: TSubBeforeNotifyEvent<T>;
begin
Result:=@FBeforeEvent;
end;
function TSubscriberImpl<T>.GetErrorEvent: TSubNotifyErrorEvent<T>;
begin
Result:=@FErrorEvent;
end;
procedure TSubscriberImpl<T>.SetAfterEvent(AValue: TSubAfterNotifyEvent);
begin
FAfterEvent:=AValue;
end;
procedure TSubscriberImpl<T>.SetBeforeEvent(AValue: TSubBeforeNotifyEvent);
begin
FBeforeEvent:=AValue;
end;
procedure TSubscriberImpl<T>.SetErrorEvent(AValue: TSubNotifyErrorEvent);
begin
FErrorEvent:=AValue;
end;
procedure TSubscriberImpl<T>.DoOnError(const ASender: ISubscriber<T>;
const AMessage: T; const AError: String);
begin
if Assigned(FErrorEvent) then
FErrorEvent(ASender,AMessage,AError);
end;
procedure TSubscriberImpl<T>.DoOnBeforeNotify(const ASender: ISubscriber<T>;
const AMessage: T; out AbortNotify: Boolean);
begin
AbortNotify:=False;
if Assigned(FBeforeEvent) then
FBeforeEvent(ASender,AMessage,AbortNotify);
end;
procedure TSubscriberImpl<T>.DoOnAfterNotify(const ASender: ISubscriber<T>;
const AMessage: T);
begin
if Assigned(FAfterEvent) then
FAfterEvent(ASender,AMessage);
end;
function TSubscriberImpl<T>.Notify(const AMessage: T;
const APublisher: IPublisher<T>; out Error: String): Boolean;
var
LSubscriber:ISubscriber<T>;
LAbort:Boolean;
begin
Result:=False;
try
LSubscriber:=Self;
DoOnBeforeNotify(LSubscriber,AMessage,LAbort);
//see if we need to skip notify logic
if LAbort then
begin
Result:=True;
//even though we are skipping, still trigger after event since
//we are reporting success
DoOnAfterNotify(LSubscriber,AMessage);
Exit;
end;
if not DoNotify(AMessage,APublisher,Error) then
Exit;
Result:=True;
DoOnAfterNotify(LSubscriber,AMessage);
except on E:Exception do
Error:=E.Message;
end;
end;
{ TPublisherImpl }
function TPublisherImpl<T>.GetErrorEvent: TPubNotifyErrorEvent;
begin
Result:=@FErrorEvent;
end;
procedure TPublisherImpl<T>.SetErrorEvent(AValue: TPubNotifyErrorEvent);
begin
FErrorEvent:=AValue;
end;
procedure TPublisherImpl<T>.Subscribe(const ASubscriber: ISubscriber);
var
I:Integer;
begin
I:=FList.IndexOf(ASubscriber);
if I<0 then
Flist.Add(ASubscriber);
end;
procedure TPublisherImpl<T>.Unsubscribe(const ASubscriber: ISubscriber);
var
I:Integer;
begin
I:=FList.IndexOf(ASubscriber);
if I<0 then
Exit;
FList.Delete(I);
end;
procedure TPublisherImpl<T>.Notify(const AMessage: T);
var
I:Integer;
LSubscriber:ISubscriber<T>;
LPublisher:IPublisher<T>;
LError:String;
begin
try
LPublisher:=Self;
for I:=0 to Pred(FList.Count) do
begin
LSubscriber:=FList[I] as ISubscriber<T>;
if not Assigned(LSubscriber) then
Continue;
if not LSubscriber.Notify(AMessage,LPublisher,LError) then
DoOnError(LPublisher,LSubscriber,AMessage,LError);
end;
except on E:Exception do
DoOnError(LPublisher,LSubscriber,AMessage,LError);
end;
end;
procedure TPublisherImpl<T>.DoOnError(Const ASender:IPublisher;
Const ASubscriber:ISubscriber;Const AMessage:T;Const AError:String);
begin
if Assigned(FErrorEvent) then
FErrorEvent(ASender,ASubscriber,AMessage,AError);
end;
constructor TPublisherImpl<T>.Create;
begin
FList:=TIntfList.Create;
end;
destructor TPublisherImpl<T>.Destroy;
begin
FList.Free;
inherited Destroy;
end;
end.
|
unit K599800930;
{* [Requestlink:599800930] }
// Модуль: "w:\common\components\rtl\Garant\Daily\K599800930.pas"
// Стереотип: "TestCase"
// Элемент модели: "K599800930" MUID: (5559ED00003A)
// Имя типа: "TK599800930"
{$Include w:\common\components\rtl\Garant\Daily\TestDefine.inc.pas}
interface
{$If Defined(nsTest) AND NOT Defined(NoScripts)}
uses
l3IntfUses
, RTFtoEVDWriterTest
;
type
TK599800930 = class(TRTFtoEVDWriterTest)
{* [Requestlink:599800930] }
protected
function GetFolder: AnsiString; override;
{* Папка в которую входит тест }
function GetModelElementGUID: AnsiString; override;
{* Идентификатор элемента модели, который описывает тест }
end;//TK599800930
{$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts)
implementation
{$If Defined(nsTest) AND NOT Defined(NoScripts)}
uses
l3ImplUses
, TestFrameWork
//#UC START# *5559ED00003Aimpl_uses*
//#UC END# *5559ED00003Aimpl_uses*
;
function TK599800930.GetFolder: AnsiString;
{* Папка в которую входит тест }
begin
Result := '7.11';
end;//TK599800930.GetFolder
function TK599800930.GetModelElementGUID: AnsiString;
{* Идентификатор элемента модели, который описывает тест }
begin
Result := '5559ED00003A';
end;//TK599800930.GetModelElementGUID
initialization
TestFramework.RegisterTest(TK599800930.Suite);
{$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts)
end.
|
unit RealAvoidanceZoneProviderUnit;
interface
uses
SysUtils,
AvoidanceZoneUnit, IAvoidanceZoneProviderUnit;
type
TRealAvoidanceZoneProvider = class(TInterfacedObject, IAvoidanceZoneProvider)
protected
public
function AvoidanceZones: TAvoidanceZoneList;
end;
implementation
uses
DateUtils,
EnumsUnit, UtilsUnit, JSONDictionaryIntermediateObjectUnit,
RouteParametersUnit, LinksUnit, AddressUnit, TerritoryContourUnit,
PositionUnit;
function TRealAvoidanceZoneProvider.AvoidanceZones: TAvoidanceZoneList;
var
AvoidanceZone: TAvoidanceZone;
begin
Result := TAvoidanceZoneList.Create;
AvoidanceZone := TAvoidanceZone.Create;
AvoidanceZone.TerritoryId := '1C4EC91F7C83E6D44A39C5EF0ED15422';
AvoidanceZone.TerritoryName := 'Johny4037200794235010051';
AvoidanceZone.TerritoryColor := 'ff0000';
AvoidanceZone.MemberId := '1';
AvoidanceZone.Territory := TTerritoryContour.MakePolygonContour([
TPosition.Create(56.127184156131065,56.93115234375),
TPosition.Create(58.41322259056806, 59.501953125),
TPosition.Create(61.53840616716746, 59.315185546875),
TPosition.Create(61.047650586031104,51.998291015625),
TPosition.Create(59.254649544483726,53.63525390625),
TPosition.Create(56.47462805805596, 54.42626953125)
]);
Result.Add(AvoidanceZone);
AvoidanceZone := TAvoidanceZone.Create;
AvoidanceZone.TerritoryId := '1E8516BDBBA2A27753B768B0F628A27B';
AvoidanceZone.TerritoryName := 'John5577006791947779410';
AvoidanceZone.TerritoryColor := 'beeeee';
AvoidanceZone.MemberId := '1';
AvoidanceZone.Territory := TTerritoryContour.MakeCircleContour(
37.569752822786455,-77.47833251953125, 5000);
Result.Add(AvoidanceZone);
AvoidanceZone := TAvoidanceZone.Create;
AvoidanceZone.TerritoryId := '2E10E418F0913D4C52C9D6386F41C303';
AvoidanceZone.TerritoryName := 'Rect Territory';
AvoidanceZone.TerritoryColor := 'ff0000';
AvoidanceZone.MemberId := '1';
AvoidanceZone.Territory := TTerritoryContour.MakeRectangularContour(
43.51668853502909, -109.3798828125, 46.98025235521883, -101.865234375);
Result.Add(AvoidanceZone);
end;
end.
|
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Math,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls,
Vcl.ComCtrls, Vcl.ExtDlgs;
type
TForm1 = class(TForm)
Image2: TImage;
Button2: TButton;
Edit1: TEdit;
Label2: TLabel;
Button1: TButton;
OpenPictureDialog1: TOpenPictureDialog;
procedure Button2Click(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
const
LibraryName = 'tflite.dll';
type
TfLiteStatus = (kTfLiteOk, kTfLiteError, kTfLiteDelegateError);
TfLiteType = (kTfLiteNoType = 0, kTfLiteFloat32 = 1, kTfLiteInt32 = 2,
kTfLiteUInt8 = 3, kTfLiteInt64 = 4, kTfLiteString = 5, kTfLiteBool = 6,
kTfLiteInt16 = 7, kTfLiteComplex64 = 8, kTfLiteInt8 = 9,
kTfLiteFloat16 = 10, kTfLiteFloat64 = 11);
function TfLiteModelCreateFromFile(const model_path: PAnsiChar): Pointer;
stdcall; external LibraryName;
function TfLiteInterpreterCreate(model: Pointer; optional_options: Pointer)
: Pointer; stdcall; external LibraryName;
function TfLiteInterpreterOptionsCreate(): Pointer; stdcall;
external LibraryName;
function TfLiteInterpreterAllocateTensors(interpreter: Pointer): TfLiteStatus;
stdcall; external LibraryName;
function TfLiteInterpreterGetInputTensor(interpreter: Pointer;
input_index: Int32): Pointer; stdcall; external LibraryName;
function TfLiteInterpreterGetOutputTensor(interpreter: Pointer;
output_index: Int32): Pointer; stdcall; external LibraryName;
function TfLiteTensorNumDims(tensor: Pointer): Int32; stdcall;
external LibraryName;
function TfLiteTensorName(tensor: Pointer): PAnsiChar; stdcall;
external LibraryName;
function TfLiteTensorType(tensor: Pointer): TfLiteType; stdcall;
external LibraryName;
function TfLiteTensorByteSize(tensor: Pointer): SIZE_T; stdcall;
external LibraryName;
function TfLiteInterpreterResizeInputTensor(interpreter: Pointer;
input_index: Int32; input_dims: PInteger; input_dims_size: Int32)
: TfLiteStatus; stdcall; external LibraryName;
function TfLiteInterpreterGetInputTensorCount(interpreter: Pointer): Int32;
stdcall; external LibraryName;
function TfLiteInterpreterGetOutputTensorCount(interpreter: Pointer): Int32;
stdcall; external LibraryName;
function TfLiteTensorCopyFromBuffer(tensor: Pointer; input_data: Pointer;
input_data_size: SIZE_T): TfLiteStatus; stdcall; external LibraryName;
function TfLiteTensorCopyToBuffer(output_tensor: Pointer; output_data: Pointer;
output_data_size: SIZE_T): TfLiteStatus; stdcall; external LibraryName;
procedure TfLiteInterpreterOptionsSetNumThreads(options: Pointer;
num_threads: Int32); stdcall; external LibraryName;
procedure TfLiteInterpreterOptionsDelete(options: Pointer); stdcall;
external LibraryName;
procedure TfLiteModelDelete(model: Pointer); stdcall; external LibraryName;
function TfLiteInterpreterInvoke(interpreter: Pointer): TfLiteStatus; stdcall;
external LibraryName;
procedure TForm1.Button1Click(Sender: TObject);
var
fBitmap: TBitmap;
begin
if OpenPictureDialog1.Execute then
begin
fBitmap := TBitmap.Create;
try
fBitmap.LoadFromFile(OpenPictureDialog1.FileName);
Image2.Picture.Bitmap.Canvas.StretchDraw
(Image2.Picture.Bitmap.Canvas.ClipRect, fBitmap);
// Image2.Picture.Bitmap.
finally
fBitmap.Free;
end;
end;
end;
procedure TForm1.Button2Click(Sender: TObject);
const
PixelCount = 300 * 300;
type
PRGBArray = ^TRGBArray;
TRGBArray = array [0 .. PixelCount - 1] of TRGBTriple;
type
PInputArray = ^TInputArray;
TInputArray = array [0 .. 300 * 300 - 1] of array [0 .. 3 - 1] of UInt8;
var
i, X, Y: DWORD;
fLibrary: HMODULE;
fModel: Pointer;
fInterpreterOptions: Pointer;
fInterpreter: Pointer;
fStatus: TfLiteStatus;
fInputTensorCount, fOutputTensorCount, fNumDims: Int32;
fInputTensor, fOutputTensor: Pointer;
fTensorName: PAnsiChar;
fTensorType: TfLiteType;
fTensorByteSize: SIZE_T;
fInputArray: PInputArray;
fOutputLocations: array [0 .. 10 - 1] of array [0 .. 4 - 1] of Float32;
fOutputClasses: array [0 .. 10 - 1] of Float32;
fOutputScores: array [0 .. 10 - 1] of Float32;
fNumDetections: array [0 .. 1 - 1] of Float32;
fColors: PRGBArray;
fLabelMap: TStringList;
fValue: Extended;
begin
fLibrary := LoadLibrary(LibraryName);
if fLibrary = 0 then
begin
ShowMessage('Error: Load tensorflow lite library ' + LibraryName + ' - ' +
SysErrorMessage(GetLastError));
Exit;
end;
try
fModel := TfLiteModelCreateFromFile(PAnsiChar(AnsiString(Edit1.Text)));
if fModel = nil then
begin
ShowMessage('Error: Create model from file - ' +
SysErrorMessage(GetLastError));
Exit;
end;
fInterpreterOptions := TfLiteInterpreterOptionsCreate;
if fInterpreterOptions <> nil then
begin
TfLiteInterpreterOptionsSetNumThreads(fInterpreterOptions, 2);
fInterpreter := TfLiteInterpreterCreate(fModel, fInterpreterOptions);
// параметры / модель могут быть удалены сразу же после создани¤ интерпретатора
TfLiteInterpreterOptionsDelete(fInterpreterOptions);
TfLiteModelDelete(fModel);
if fInterpreter <> nil then
begin
fStatus := TfLiteInterpreterAllocateTensors(fInterpreter);
fInputTensorCount := TfLiteInterpreterGetInputTensorCount(fInterpreter);
fOutputTensorCount := TfLiteInterpreterGetOutputTensorCount
(fInterpreter);
fInputTensor := TfLiteInterpreterGetInputTensor(fInterpreter, 0);
fOutputTensor := TfLiteInterpreterGetOutputTensor(fInterpreter, 0);
if fInputTensor <> nil then
begin
// инфа о тензоре
fNumDims := TfLiteTensorNumDims(fInputTensor);
fTensorName := TfLiteTensorName(fInputTensor);
fTensorType := TfLiteTensorType(fInputTensor);
fTensorByteSize := TfLiteTensorByteSize(fInputTensor);
// Размер картинки на входе только 300x300
// Object Detection
// https://www.tensorflow.org/lite/models/object_detection/overview#get_started
GetMem(fInputArray, fTensorByteSize);
try
// То ли модель такая говнотренированная, то ли фильтр надо сделать средний, то ли я тупой
for Y := 0 to Image2.Picture.Bitmap.Height - 1 do
begin
fColors := PRGBArray(Image2.Picture.Bitmap.ScanLine[Y]);
for X := 0 to Image2.Picture.Bitmap.Width - 1 do
begin
fInputArray[X + (Y * Image2.Picture.Bitmap.Width)][0] :=
fColors[X].rgbtRed;
fInputArray[X + (Y * Image2.Picture.Bitmap.Width)][1] :=
fColors[X].rgbtGreen;
fInputArray[X + (Y * Image2.Picture.Bitmap.Width)][2] :=
fColors[X].rgbtBlue;
end;
end;
fStatus := TfLiteTensorCopyFromBuffer(fInputTensor, fInputArray,
fTensorByteSize);
finally
FreeMem(fInputArray, fTensorByteSize);
end;
if fStatus = kTfLiteOk then
begin
fStatus := TfLiteInterpreterInvoke(fInterpreter);
if fStatus = kTfLiteOk then
begin
// Locations
fOutputTensor := TfLiteInterpreterGetOutputTensor
(fInterpreter, 0);
fTensorByteSize := TfLiteTensorByteSize(fOutputTensor);
if fOutputTensor <> nil then
begin
fStatus := TfLiteTensorCopyToBuffer(fOutputTensor,
@fOutputLocations, fTensorByteSize);
end;
// Classes
fLabelMap := TStringList.Create;
try
fLabelMap.LoadFromFile('labelmap.txt');
fOutputTensor := TfLiteInterpreterGetOutputTensor
(fInterpreter, 1);
fTensorByteSize := TfLiteTensorByteSize(fOutputTensor);
if fOutputTensor <> nil then
begin
fStatus := TfLiteTensorCopyToBuffer(fOutputTensor,
@fOutputClasses, fTensorByteSize);
end;
// Scores
fOutputTensor := TfLiteInterpreterGetOutputTensor
(fInterpreter, 2);
fTensorByteSize := TfLiteTensorByteSize(fOutputTensor);
if fOutputTensor <> nil then
begin
fStatus := TfLiteTensorCopyToBuffer(fOutputTensor,
@fOutputScores, fTensorByteSize);
end;
// Всегда 10 обьектов даёт, не нужды делать fnumDetections
// fStatus := TfLiteTensorCopyToBuffer(fOutputTensor,
// @fnumDetections, fTensorByteSize);
// There will always be 10 objects detected
{ 0 Locations Multidimensional array of [10][4] floating point values between 0 and 1, the inner arrays representing bounding boxes in the form [top, left, bottom, right]
1 Classes Array of 10 integers (output as floating point values) each indicating the index of a class label from the labels file
2 Scores Array of 10 floating point values between 0 and 1 representing probability that a class was detected
3 Number and detections }
if fStatus = kTfLiteOk then
begin
for i := 0 to Length(fOutputLocations[0]) - 1 do
begin
Image2.Canvas.Brush.Style := bsClear;
Image2.Canvas.FillRect(Image2.Canvas.ClipRect);
Image2.Canvas.Pen.Color := clRed;
// И опять гениальнейшее мое решение
fValue := StrToFloat
(Copy(FloatToStr(fOutputScores[i]), 1, 4));
if fValue >= 0.6 then
begin
Image2.Canvas.Rectangle
(Round(fOutputLocations[i][1] * 300),
Round(fOutputLocations[i][0] * 300),
Round(fOutputLocations[i][3] * 300),
Round(fOutputLocations[i][2] * 300));
Image2.Canvas.Brush.Style := bsSolid;
Image2.Canvas.Brush.Color := clRed;
Image2.Canvas.Font.Color := clWhite;
// SSD Mobilenet V1 Model assumes class 0 is background class
// in label file and class labels start from 1 to number_of_classes+1,
// while outputClasses correspond to class index from 0 to number_of_classes
// i начанаеться с 0 поэтому + 1
Image2.Canvas.TextOut(Round(fOutputLocations[i][1] * 300)
+ 2, Round(fOutputLocations[i][0] * 300) + 1,
fLabelMap.Strings[Round(fOutputClasses[i]) + 1] + ' - '
+ FloatToStr(fValue));
end;
end;
Beep;
end;
finally
fLabelMap.Free;
end;
end;
end;
end;
end;
end;
finally
FreeLibrary(fLibrary);
end;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
OpenPictureDialog1.InitialDir := GetCurrentDir;
end;
end.
|
Unit RdSwitch;
{ This file contains routines to process some of cjpeg's more complicated
command-line switches. Switches processed here are:
-qtables file Read quantization tables from text file
-scans file Read scan script from text file
-qslots N[,N,...] Set component quantization table selectors
-sample HxV[,HxV,...] Set component sampling factors }
{ Original: rdswitch.c ; Copyright (C) 1991-1996, Thomas G. Lane. }
interface
{$I jconfig.inc}
uses
cdjpeg, { Common decls for cjpeg/djpeg applications }
{ctype,} { to declare isdigit(), isspace() }
jinclude,
jmorecfg,
jcparam,
jpeglib;
{GLOBAL}
function set_quant_slots (cinfo : j_compress_ptr; argtxt : string) : boolean;
{ Process a quantization-table-selectors parameter string, of the form
N[,N,...]
If there are more components than parameters, the last value is re0licated.
}
{GLOBAL}
function set_sample_factors (cinfo : j_compress_ptr;
argtxt : string) : boolean;
{ Process a sample-factors parameter string, of the form
HxV[,HxV,...]
If there are more components than parameters, "1x1" is assumed for the rest.
}
{GLOBAL}
function read_quant_tables (cinfo : j_compress_ptr;
const filename : string;
scale_factor : int;
force_baseline : boolean) : boolean;
{ Read a set of quantization tables from the specified file.
The file is plain ASCII text: decimal numbers with whitespace between.
Comments preceded by '#' may be included in the file.
There may be one to NUM_QUANT_TBLS tables in the file, each of 64 values.
The tables are implicitly numbered 0,1,etc.
NOTE: does not affect the qslots mapping, which will default to selecting
table 0 for luminance (or primary) components, 1 for chrominance components.
You must use -qslots if you want a different component->table mapping. }
{GLOBAL}
function read_scan_script (cinfo : j_compress_ptr;
const filename : string) : boolean;
{ Read a scan script from the specified text file.
Each entry in the file defines one scan to be emitted.
Entries are separated by semicolons ';'.
An entry contains one to four component indexes,
optionally followed by a colon ':' and four progressive-JPEG parameters.
The component indexes denote which component(s) are to be transmitted
in the current scan. The first component has index 0.
Sequential JPEG is used if the progressive-JPEG parameters are omitted.
The file is free format text: any whitespace may appear between numbers
and the ':' and ';' punctuation marks. Also, other punctuation (such
as commas or dashes) can be placed between numbers if desired.
Comments preceded by '#' may be included in the file.
Note: we do very little validity checking here;
jcmaster.c will validate the script parameters. }
implementation
uses
fcache;
const
BLANK = ' ';
TAB = ^I; { #9 }
CR = #13; { ^M }
LF = #10; { }
{LOCAL}
function text_getc (var fc : Cache) : char;
{ Read next char, skipping over any comments (# to end of line) }
{ A comment/newline sequence is returned as a newline }
var
ch : char; {register }
begin
ch := char(fc_GetC(fc));
if (ch = '#') then
repeat
ch := char(fc_GetC(fc));
Until (ch = #13) or (ch = EOF);
text_getc := ch;
end;
{LOCAL}
function read_text_integer (var f : Cache;
var outval : long;
var termchar : char) : boolean;
{ Read an unsigned decimal integer from a file, store it in outval }
{ Reads one trailing character after the integer; returns it in termchar }
var
{register} ch : char;
{register} val : long;
begin
{ Skip any leading whitespace, detect EOF }
repeat
ch := text_getc(f);
if (ch = EOF) then
begin
termchar := EOF;
read_text_integer := FALSE;
exit;
end;
Until (ch <> BLANK) and (ch <> TAB) and (ch <> CR) and (ch <> LF);
if not (ch in ['0'..'9']) then
begin
termchar := ch;
read_text_integer := FALSE;
exit;
end;
val := ord(ch) - ord('0');
repeat
ch := text_getc(f);
if (ch <> EOF) then
begin
if not (ch in ['0'..'9']) then
break;
val := val * 10;
Inc(val, ord(ch) - ord('0'));
end;
until ch = EOF;
outval := val;
termchar := ch;
read_text_integer := TRUE;
end;
{GLOBAL}
function read_quant_tables (cinfo : j_compress_ptr;
const filename : string;
scale_factor : int;
force_baseline : boolean) : boolean;
{ Read a set of quantization tables from the specified file.
The file is plain ASCII text: decimal numbers with whitespace between.
Comments preceded by '#' may be included in the file.
There may be one to NUM_QUANT_TBLS tables in the file, each of 64 values.
The tables are implicitly numbered 0,1,etc.
NOTE: does not affect the qslots mapping, which will default to selecting
table 0 for luminance (or primary) components, 1 for chrominance components.
You must use -qslots if you want a different component->table mapping. }
var
f : file;
fp : Cache;
tblno, i : int;
termchar : char;
val : long;
table : array[0..DCTSIZE2-1] of uInt;
begin
Assign(f, filename);
{$I-}
Reset(f, 1);
{$IFDEF IoCheck} {$I+} {$ENDIF}
if (IOresult <> 0) then
begin
WriteLn(output, 'Can''t open table file ', filename);
read_quant_tables := FALSE;
exit;
end;
fc_Init(fp, f, 0);
tblno := 0;
while (read_text_integer(fp, val, termchar)) do
begin { read 1st element of table }
if (tblno >= NUM_QUANT_TBLS) then
begin
WriteLn(output, 'Too many tables in file ', filename);
fc_close(fp);
read_quant_tables := FALSE;
exit;
end;
table[0] := uInt (val);
for i := 1 to pred(DCTSIZE2) do
begin
if (not read_text_integer(fp, val, termchar)) then
begin
WriteLn(output, 'Invalid table data in file ', filename);
fc_close(fp);
read_quant_tables := FALSE;
exit;
end;
table[i] := uInt (val);
end;
jpeg_add_quant_table(cinfo, tblno, table, scale_factor, force_baseline);
Inc(tblno);
end;
if (termchar <> EOF) then
begin
WriteLn(output, 'Non-numeric data in file ', filename);
fc_close(fp);
read_quant_tables := FALSE;
exit;
end;
fc_close(fp);
read_quant_tables := TRUE;
end;
{$ifdef C_MULTISCAN_FILES_SUPPORTED}
{LOCAL}
function read_scan_integer (var f : cache;
var outval : long;
var termchar : char) : boolean;
{ Variant of read_text_integer that always looks for a non-space termchar;
this simplifies parsing of punctuation in scan scripts. }
var
ch : char; { register }
begin
if not read_text_integer(f, outval, termchar) then
begin
read_scan_integer := FALSE;
exit;
end;
ch := termchar;
while (ch <> EOF) and (ch in [BLANK, TAB]) do
ch := text_getc(f);
if (ch in ['0'..'9']) then
begin { oops, put it back }
if fc_ungetc(f, ch) = Byte(EOF) then
begin
read_scan_integer := FALSE;
exit;
end;
ch := BLANK;
end
else
begin
{ Any separators other than ';' and ':' are ignored;
this allows user to insert commas, etc, if desired. }
if (ch <> EOF) and (ch <> ';') and (ch <> ':') then
ch := BLANK;
end;
termchar := ch;
read_scan_integer := TRUE;
end;
{GLOBAL}
function read_scan_script (cinfo : j_compress_ptr;
const filename : string) : boolean;
{ Read a scan script from the specified text file.
Each entry in the file defines one scan to be emitted.
Entries are separated by semicolons ';'.
An entry contains one to four component indexes,
optionally followed by a colon ':' and four progressive-JPEG parameters.
The component indexes denote which component(s) are to be transmitted
in the current scan. The first component has index 0.
Sequential JPEG is used if the progressive-JPEG parameters are omitted.
The file is free format text: any whitespace may appear between numbers
and the ':' and ';' punctuation marks. Also, other punctuation (such
as commas or dashes) can be placed between numbers if desired.
Comments preceded by '#' may be included in the file.
Note: we do very little validity checking here;
jcmaster.c will validate the script parameters. }
label
bogus;
var
f : file;
fp : Cache;
scanno, ncomps : int;
termchar : char;
val : long;
scanptr : jpeg_scan_info_ptr;
const
MAX_SCANS = 100; { quite arbitrary limit }
var
scans : array[0..MAX_SCANS-1] of jpeg_scan_info;
begin
Assign(f,filename);
{$I-}
Reset(f, 1);
{$IFDEF IoCheck} {$I+} {$ENDIF}
if (IOresult <> 0) then
begin
WriteLn('Can''t open scan definition file ', filename);
read_scan_script := FALSE;
exit;
end;
fc_Init(fp, f, 0);
scanptr := @scans[0];
scanno := 0;
while (read_scan_integer(fp, val, termchar)) do
begin
if (scanno >= MAX_SCANS) then
begin
WriteLn(output, 'Too many scans defined in file ', filename);
fc_Close(fp);
read_scan_script := FALSE;
exit;
end;
scanptr^.component_index[0] := int(val);
ncomps := 1;
while (termchar = BLANK) do
begin
if (ncomps >= MAX_COMPS_IN_SCAN) then
begin
WriteLn(output, 'Too many components in one scan in file ',
filename);
fc_close(fp);
read_scan_script := FALSE;
exit;
end;
if (not read_scan_integer(fp, val, termchar)) then
goto bogus;
scanptr^.component_index[ncomps] := int (val);
Inc(ncomps);
end;
scanptr^.comps_in_scan := ncomps;
if (termchar = ':') then
begin
if (not read_scan_integer(fp, val, termchar)) or (termchar <> BLANK) then
goto bogus;
scanptr^.Ss := int (val);
if (not read_scan_integer(fp, val, termchar)) or (termchar <> BLANK) then
goto bogus;
scanptr^.Se := int (val);
if (not read_scan_integer(fp, val, termchar)) or (termchar <> BLANK) then
goto bogus;
scanptr^.Ah := int (val);
if (not read_scan_integer(fp, val, termchar)) then
goto bogus;
scanptr^.Al := int (val);
end
else
begin
{ set non-progressive parameters }
scanptr^.Ss := 0;
scanptr^.Se := DCTSIZE2-1;
scanptr^.Ah := 0;
scanptr^.Al := 0;
end;
if (termchar <> ';') and (termchar <> EOF) then
begin
bogus:
WriteLn(output, 'Invalid scan entry format in file ', filename);
fc_close(fp);
read_scan_script := FALSE;
exit;
end;
Inc(scanptr);
Inc(scanno);
end;
if (termchar <> EOF) then
begin
WriteLn(output, 'Non-numeric data in file ', filename);
fc_close(fp);
read_scan_script := FALSE;
exit;
end;
if (scanno > 0) then
begin
{ Stash completed scan list in cinfo structure.
NOTE: for cjpeg's use, JPOOL_IMAGE is the right lifetime for this data,
but if you want to compress multiple images you'd want JPOOL_PERMANENT. }
scanptr := jpeg_scan_info_ptr (
cinfo^.mem^.alloc_small ( j_common_ptr(cinfo), JPOOL_IMAGE,
scanno * SIZEOF(jpeg_scan_info)) );
MEMCOPY(scanptr, @scans, scanno * SIZEOF(jpeg_scan_info));
cinfo^.scan_info := scanptr;
cinfo^.num_scans := scanno;
end;
fc_close(fp);
read_scan_script := TRUE;
end;
{$endif} { C_MULTISCAN_FILES_SUPPORTED }
function sscanf(var lineptr : PChar;
var val : int;
var ch : char) : boolean;
var
digits : int;
begin
digits := 0;
while (lineptr^=BLANK) do { advance to next segment of the string }
Inc(lineptr);
val := 0;
while lineptr^ in ['0'..'9'] do
begin
val := val * 10 + (ord(lineptr^) - ord('0'));
Inc(lineptr);
Inc(digits);
end;
if lineptr^<>#0 then
begin
ch := lineptr^;
Inc(lineptr);
end;
sscanf := (digits > 0);
end;
{GLOBAL}
function set_quant_slots (cinfo : j_compress_ptr;
argtxt : string) : boolean;
{ Process a quantization-table-selectors parameter string, of the form
N[,N,...]
If there are more components than parameters, the last value is replicated.
}
var
val : int; { default table # }
ci : int;
ch : char;
var
arg_copy : string;
arg : PChar;
begin
arg_copy := argtxt + #0;
if arg_copy[Length(arg_copy)] <> #0 then
arg_copy[Length(arg_copy)] := #0;
arg := @arg_copy[1];
val := 0;
for ci := 0 to pred(MAX_COMPONENTS) do
begin
if (arg^ <> #0) then
begin
ch := ','; { if not set by sscanf, will be ',' }
if not sscanf(arg, val, ch) then
begin
set_quant_slots := FALSE;
exit;
end;
if (ch <> ',') then { syntax check }
begin
set_quant_slots := FALSE;
exit;
end;
if (val < 0) or (val >= NUM_QUANT_TBLS) then
begin
WriteLn(output, 'JPEG quantization tables are numbered 0..',
NUM_QUANT_TBLS-1);
set_quant_slots := FALSE;
exit;
end;
cinfo^.comp_info^[ci].quant_tbl_no := val;
end
else
begin
{ reached end of parameter, set remaining components to last table }
cinfo^.comp_info^[ci].quant_tbl_no := val;
end;
end;
set_quant_slots := TRUE;
end;
{GLOBAL}
function set_sample_factors (cinfo : j_compress_ptr;
argtxt : string) : boolean;
{ Process a sample-factors parameter string, of the form
HxV[,HxV,...]
If there are more components than parameters, "1x1" is assumed for the rest.
}
var
ci, val1, val2 : int;
ch1, ch2 : char;
var
arg_copy : string;
arg : PChar;
begin
arg_copy := argtxt + #0;
if arg_copy[Length(arg_copy)] <> #0 then
arg_copy[Length(arg_copy)] := #0;
arg := @arg_copy[1];
for ci := 0 to pred(MAX_COMPONENTS) do
begin
if (arg^ <> #0) then
begin
ch2 := ','; { if not set by sscanf, will be ',' }
if not (sscanf(arg, val1, ch1) and
sscanf(arg, val2, ch2)) then
begin
set_sample_factors := FALSE;
exit;
end;
if ((ch1 <> 'x') and (ch1 <> 'X')) or (ch2 <> ',') then { syntax check }
begin
set_sample_factors := FALSE;
exit;
end;
if (val1 <= 0) or (val1 > 4) or (val2 <= 0) or (val2 > 4) then
begin
WriteLn(output, 'JPEG sampling factors must be 1..4');
set_sample_factors := FALSE;
exit;
end;
cinfo^.comp_info^[ci].h_samp_factor := val1;
cinfo^.comp_info^[ci].v_samp_factor := val2;
end
else
begin
{ reached end of parameter, set remaining components to 1x1 sampling }
cinfo^.comp_info^[ci].h_samp_factor := 1;
cinfo^.comp_info^[ci].v_samp_factor := 1;
end;
end;
set_sample_factors := TRUE;
end;
end.
|
unit vcmPrimCollectionItem;
{ Библиотека "vcm" }
{ Автор: Люлин А.В. © }
{ Модуль: vcmPrimCollectionItem - }
{ Начат: 03.04.2003 12:16 }
{ $Id: vcmPrimCollectionItem.pas,v 1.25 2011/07/29 15:08:37 lulin Exp $ }
// $Log: vcmPrimCollectionItem.pas,v $
// Revision 1.25 2011/07/29 15:08:37 lulin
// {RequestLink:209585097}.
//
// Revision 1.24 2008/02/14 19:32:31 lulin
// - изменены имена файлов с примесями.
//
// Revision 1.23 2008/02/14 14:12:14 lulin
// - <K>: 83920106.
//
// Revision 1.22 2008/02/07 08:37:44 lulin
// - каждому базовому объекту по собственному модулю.
//
// Revision 1.21 2008/01/30 20:31:40 lulin
// - подготавливаемся к штатному использованию классов-примесей на модели.
//
// Revision 1.20 2008/01/25 12:06:50 lulin
// - синхронизируем имена с моделью.
//
// Revision 1.19 2008/01/25 11:32:05 lulin
// - синхронизируем имена с моделью.
//
// Revision 1.18 2007/08/13 17:23:30 lulin
// - cleanup.
//
// Revision 1.17 2007/01/18 10:49:32 lulin
// - заменяем объект менеджера памяти на интерфейс.
//
// Revision 1.16 2006/04/14 13:40:21 lulin
// - запрещаем перекрывать деструктор.
//
// Revision 1.15 2006/04/14 12:11:16 lulin
// - файлу с шаблоном дано более правильное название.
//
// Revision 1.14 2006/04/14 11:53:05 lulin
// - объединил интерфейс и реализацию _Unknown_ в один файл.
//
// Revision 1.13 2004/09/15 10:16:48 lulin
// - Tl3InterfacedComponent переведен на "шаблон" l3Unknown.
//
// Revision 1.12 2004/09/15 09:51:43 lulin
// - перевел реализацию IUnknown на "шаблонную" реализацию.
//
// Revision 1.11 2004/09/13 09:25:33 lulin
// - bug fix.
//
// Revision 1.10 2004/09/13 09:08:33 lulin
// - bug fix: не компилировался VCM.
//
// Revision 1.9 2004/09/13 08:56:10 lulin
// - new behavior: TvcmPrimCollectionItem теперь может кешироваться и распределяться в пуле объектов.
//
// Revision 1.8 2004/09/13 07:33:02 lulin
// - new behavior: Tl3InterfacedComponent теперь может распределять свою память в пуле объектов.
//
// Revision 1.7 2004/09/11 11:55:47 lulin
// - cleanup: избавляемся от прямого использования деструкторов.
//
// Revision 1.6 2004/09/08 11:22:43 lulin
// - new define: _l3NoTrace.
// - new define: l3TraceObjects.
//
// Revision 1.5 2004/04/09 14:25:12 law
// - new behavior: сделан контроль за объектами TvcmPrimCollectionItem.
//
// Revision 1.4 2003/11/30 11:39:41 law
// - new behavior: автогенерируем типы пользовательских объектов.
//
// Revision 1.3 2003/11/18 19:35:54 law
// - new: начал делать общий репозиторий модулей, сущностей и операций в MenuManager'е. Чтобы все можно было править из одного места.
//
// Revision 1.2 2003/04/03 15:43:54 law
// - change: из TvcmMainForm выделил класс TvcmDispatcher.
//
// Revision 1.1 2003/04/03 09:26:18 law
// - new behavior: сделал возможность подписки на события.
//
{$Include vcmDefine.inc }
interface
uses
Windows,
Classes,
vcmInterfaces
;
type
_l3Unknown_Parent_ = TCollectionItem;
{$Define _UnknownNeedsQI}
{$IfNDef vcmNeedL3}
{$Define _UnknownNotNeedL3}
{$EndIf vcmNeedL3}
{$Include l3Unknown.imp.pas}
TvcmPrimCollectionItem = class(_l3Unknown_)
protected
// property methods
function pm_GetDispatcher: IvcmDispatcher;
{-}
protected
// internal methods
class function IsCacheable: Boolean;
override;
{-}
public
// public properties
property Dispatcher: IvcmDispatcher
read pm_GetDispatcher;
{-}
end;//TvcmPrimCollectionItem
implementation
uses
SysUtils,
Forms,
{$IfDef vcmNeedL3}
l3Interfaces,
l3Base,
{$EndIf vcmNeedL3}
vcmBase
;
{$Include l3Unknown.imp.pas}
// start class TvcmPrimCollectionItem
class function TvcmPrimCollectionItem.IsCacheable: Boolean;
//override;
{-}
begin
Result := true;
end;
function TvcmPrimCollectionItem.pm_GetDispatcher: IvcmDispatcher;
{-}
begin
{$If Declared(vcmDispatcher)}
Result := vcmDispatcher;
{$Else}
Result := nil;
{$IfEnd}
end;
end.
|
unit RouteParametersQueryUnit;
interface
uses
REST.Json.Types, HttpQueryMemberAttributeUnit, JSONNullableAttributeUnit,
GenericParametersUnit, NullableBasicTypesUnit, RouteParametersUnit, EnumsUnit;
type
/// <summary>
/// Route parameters accepted by endpoints
/// </summary>
TRouteParametersQuery = class(TGenericParameters)
private
[JSONMarshalled(False)]
[Nullable]
[HttpQueryMember('route_id')]
FRouteId: NullableString;
[JSONMarshalled(False)]
[Nullable]
[HttpQueryMember('directions')]
FDirections: NullableBoolean;
[JSONMarshalled(False)]
[Nullable]
[HttpQueryMember('route_path_output')]
FRoutePathOutput: NullableString;
[JSONMarshalled(False)]
[Nullable]
[HttpQueryMember('device_tracking_history')]
FDeviceTrackingHistory: NullableBoolean;
[JSONMarshalled(False)]
[Nullable]
[HttpQueryMember('limit')]
FLimit: NullableInteger;
[JSONMarshalled(False)]
[Nullable]
[HttpQueryMember('offset')]
FOffset: NullableInteger;
[JSONMarshalled(False)]
[Nullable]
[HttpQueryMember('original')]
FOriginal: NullableBoolean;
[JSONMarshalled(False)]
[Nullable]
[HttpQueryMember('notes')]
FNotes: NullableBoolean;
[JSONMarshalled(False)]
[Nullable]
[HttpQueryMember('query')]
FQuery: NullableString;
[JSONMarshalled(False)]
[Nullable]
[HttpQueryMember('reoptimize')]
FReOptimize: NullableBoolean;
[JSONMarshalled(False)]
[Nullable]
[HttpQueryMember('recompute_directions')]
FRecomputeDirections: NullableBoolean;
[JSONName('parameters')]
[NullableObject(TRouteParameters)]
FParameters: NullableObject;
function GetRoutePathOutput: TRoutePathOutput;
procedure SetRoutePathOutput(const Value: TRoutePathOutput);
public
/// <remarks>
/// Constructor with 0-arguments must be and be public.
/// For JSON-deserialization.
/// </remarks>
constructor Create; overload; override;
destructor Destroy; override;
/// <summary>
/// Route Identifier
/// </summary>
property RouteId: NullableString read FRouteId write FRouteId;
/// <summary>
/// Pass True to return directions and the route path
/// </summary>
property Directions: NullableBoolean read FDirections write FDirections;
/// <summary>
/// "None" - no path output. "Points" - points path output
/// </summary>
property RoutePathOutput: TRoutePathOutput read GetRoutePathOutput write SetRoutePathOutput;
/// <summary>
/// Output route tracking data in response
/// </summary>
property DeviceTrackingHistory: NullableBoolean read FDeviceTrackingHistory write FDeviceTrackingHistory;
/// <summary>
/// The number of existing routes that should be returned per response when looking at a list of all the routes.
/// </summary>
property Limit: NullableInteger read FLimit write FLimit;
/// <summary>
/// The page number for route listing pagination.
/// Increment the offset by the limit number to move to the next page.
/// </summary>
property Offset: NullableInteger read FOffset write FOffset;
/// <summary>
/// Output addresses and directions in the original optimization request sequence.
/// This is to allow us to compare routes before & after optimization.
/// </summary>
property Original: NullableBoolean read FOriginal write FOriginal;
/// <summary>
/// Output route and stop-specific notes.
/// The notes will have timestamps, note types, and geospatial information if available
/// </summary>
property Notes: NullableBoolean read FNotes write FNotes;
/// <summary>
/// Search query
/// </summary>
property Query: NullableString read FQuery write FQuery;
/// <summary>
/// Updating a route supports the reoptimize=1 parameter, which reoptimizes only that route.
/// Also supports the parameters from GET.
/// </summary>
property ReOptimize: NullableBoolean read FReOptimize write FReOptimize;
/// <summary>
/// By sending recompute_directions=1 we request that the route directions be recomputed
/// (note that this does happen automatically if certain properties of the route are updated,
/// such as stop sequence_no changes or round-tripness)
/// </summary>
property RecomputeDirections: NullableBoolean read FRecomputeDirections write FRecomputeDirections;
/// <summary>
/// Route Parameters to update.
/// (After a PUT there is no guarantee that the route_destination_id values are preserved!
/// It may create copies resulting in new destination IDs, especially when dealing with multiple depots.)
/// </summary>
property Parameters: NullableObject read FParameters write FParameters;
end;
implementation
{ TRouteParametersQuery }
constructor TRouteParametersQuery.Create;
begin
Inherited Create;
FRouteId := NullableString.Null;
FDirections := NullableBoolean.Null;
FRoutePathOutput := NullableString.Null;
FDeviceTrackingHistory := NullableBoolean.Null;
FLimit := NullableInteger.Null;
FOffset := NullableInteger.Null;
FOriginal := NullableBoolean.Null;
FNotes := NullableBoolean.Null;
FQuery := NullableString.Null;
FReOptimize := NullableBoolean.Null;
FRecomputeDirections := NullableBoolean.Null;
FParameters := NullableObject.Null;
end;
destructor TRouteParametersQuery.Destroy;
begin
FParameters.Free;
inherited;
end;
function TRouteParametersQuery.GetRoutePathOutput: TRoutePathOutput;
var
RoutePathOutput: TRoutePathOutput;
begin
Result := TRoutePathOutput.rpoUndefined;
if FRoutePathOutput.IsNotNull then
for RoutePathOutput := Low(TRoutePathOutput) to High(TRoutePathOutput) do
if (FRoutePathOutput = TRoutePathOutputDescription[RoutePathOutput]) then
Exit(RoutePathOutput);
end;
procedure TRouteParametersQuery.SetRoutePathOutput(
const Value: TRoutePathOutput);
begin
FRoutePathOutput := TRoutePathOutputDescription[Value];
end;
end.
|
{
"name": "RockyRockNugget",
"players": [
2,
10
],
"creator": "(Metapod)",
"version": "1",
"date": "2016/07/02",
"description":"A barren rock with balanced spawns and evenly dispersed metal",
"planets": [
{
"name": "Chronosfear",
"mass": 5000,
"position_x": 32400,
"position_y": 14600,
"velocity_x": -48.731075286865234,
"velocity_y": 108.14292907714844,
"required_thrust_to_move": 3,
"starting_planet": true,
"respawn": false,
"start_destroyed": false,
"min_spawn_delay": 0,
"max_spawn_delay": 0,
"planet": {
"seed": 271234400,
"radius": 750,
"heightRange": 0,
"waterHeight": 0,
"waterDepth": 100,
"temperature": 0,
"metalDensity": 99,
"metalClusters": 14,
"metalSpotLimit": -1,
"biomeScale": 50,
"biome": "asteroid",
"symmetryType": "none",
"symmetricalMetal": false,
"symmetricalStarts": false,
"numArmies": 2,
"landingZonesPerArmy": 3,
"landingZoneSize": 0
},
"source": {
"brushes": [],
"metal_spots": [],
"landing_zones": {
"list": [],
"rules": []
}
},
"planetCSG": [],
"metal_spots": [],
"landing_zones": {
"list": [],
"rules": []
}
}
]
} |
unit kwPopEditorSetStyle2Block;
{* [code]
aStyle anEditor pop:editor:SetStyle2Block
[code]
aStyle - номер стиля из таблицы стилей.
anEditor - редактор, в котором производятся изменения. }
// Модуль: "w:\archi\source\projects\Archi\Archi_Insider_Test_Support\kwPopEditorSetStyle2Block.pas"
// Стереотип: "ScriptKeyword"
// Элемент модели: "pop_editor_SetStyle2Block" MUID: (4FF2EF7E03C7)
// Имя типа: "TkwPopEditorSetStyle2Block"
{$Include w:\archi\source\projects\Archi\arDefine.inc}
interface
{$If Defined(nsTest) AND Defined(InsiderTest) AND NOT Defined(NoScripts)}
uses
l3IntfUses
, kwEditorFromStackWord
, tfwScriptingInterfaces
, evCustomEditorWindow
;
type
TkwPopEditorSetStyle2Block = {final} class(TkwEditorFromStackWord)
{* [code]
aStyle anEditor pop:editor:SetStyle2Block
[code]
aStyle - номер стиля из таблицы стилей.
anEditor - редактор, в котором производятся изменения. }
protected
procedure DoWithEditor(const aCtx: TtfwContext;
anEditor: TevCustomEditorWindow); override;
class function GetWordNameForRegister: AnsiString; override;
end;//TkwPopEditorSetStyle2Block
{$IfEnd} // Defined(nsTest) AND Defined(InsiderTest) AND NOT Defined(NoScripts)
implementation
{$If Defined(nsTest) AND Defined(InsiderTest) AND NOT Defined(NoScripts)}
uses
l3ImplUses
{$If Defined(k2ForEditor)}
, evParaTools
{$IfEnd} // Defined(k2ForEditor)
, evOp
, Windows
{$If NOT Defined(NoVCL)}
, Controls
{$IfEnd} // NOT Defined(NoVCL)
{$If NOT Defined(NoVCL)}
, Forms
{$IfEnd} // NOT Defined(NoVCL)
//#UC START# *4FF2EF7E03C7impl_uses*
//#UC END# *4FF2EF7E03C7impl_uses*
;
procedure TkwPopEditorSetStyle2Block.DoWithEditor(const aCtx: TtfwContext;
anEditor: TevCustomEditorWindow);
//#UC START# *4F4CB81200CA_4FF2EF7E03C7_var*
var
l_StyleID: Integer;
//#UC END# *4F4CB81200CA_4FF2EF7E03C7_var*
begin
//#UC START# *4F4CB81200CA_4FF2EF7E03C7_impl*
if aCtx.rEngine.IsTopInt then
l_StyleID := aCtx.rEngine.PopInt
else
Assert(False, 'Не задан стиль для установки!');
evSetStyle2Block(anEditor.Selection.Cursor.MostInner.ParentPoint.Obj^.AsObject, anEditor.StartOp(ev_ocUser + 100), l_StyleID);
//#UC END# *4F4CB81200CA_4FF2EF7E03C7_impl*
end;//TkwPopEditorSetStyle2Block.DoWithEditor
class function TkwPopEditorSetStyle2Block.GetWordNameForRegister: AnsiString;
begin
Result := 'pop:editor:SetStyle2Block';
end;//TkwPopEditorSetStyle2Block.GetWordNameForRegister
initialization
TkwPopEditorSetStyle2Block.RegisterInEngine;
{* Регистрация pop_editor_SetStyle2Block }
{$IfEnd} // Defined(nsTest) AND Defined(InsiderTest) AND NOT Defined(NoScripts)
end.
|
unit CustomWebBrowser;
interface
uses
Windows, ActiveX, SHDocVw_TLB, Mshtmhst, Messages, Graphics, controls;
const
navOpenInNewWindow = $1; //.rag
navNoHistory = $2;
navNoReadFromCache = $4;
navNoWriteToCache = $8;
navAllowAutosearch = $10;
navBrowserBar = $20; //To here
type
{$IFDEF WebBrowserTest}
TOnWebBrowserTest = procedure (const log: string) of object;
{$EndIf}
TCustomWebBrowser =
class(TWebBrowser, IServiceProvider, IDocHostUIHandler)
private // IServiceProvider
function QueryService(const rsid, iid: TGuid; out Obj): HResult; stdcall;
private // IDocHostUIHandler
function ShowContextMenu(dwID : DWORD; ppt : PPoint; pcmdtReserved : IUnknown; pdispReserved : IDispatch) : HRESULT; stdcall;
function GetHostInfo(var pInfo : DOCHOSTUIINFO) : HRESULT; stdcall;
function ShowUI(dwID : DWORD; pActiveObject : IOleInPlaceActiveObject; pCommandTarget : IOleCommandTarget; pFrame : IOleInPlaceFrame; pDoc : IOleInPlaceUIWindow) : HRESULT; stdcall;
function HideUI : HRESULT; stdcall;
function UpdateUI : HRESULT; stdcall;
function EnableModeless(fEnable : BOOL) : HRESULT; stdcall;
function OnDocWindowActivate(fActivate : BOOL) : HRESULT; stdcall;
function OnFrameWindowActivate(fActivate : BOOL) : HRESULT; stdcall;
function ResizeBorder(prcBorder : PRect; pUIWindow : IOleInPlaceUIWindow; fRameWindow : BOOL) : HRESULT; stdcall;
function TranslateAccelerator(lpMsg : PMsg; const pguidCmdGroup : PGUID; nCmdID : DWORD) : HRESULT; stdcall;
function GetOptionKeyPath(out pchKey : PWideChar; dw : DWORD ) : HRESULT; stdcall;
function GetDropTarget(pDropTarget : IDropTarget; out ppDropTarget : IDropTarget) : HRESULT; stdcall;
function GetExternal(out ppDispatch : IDispatch) : HRESULT; stdcall;
function TranslateUrl(dwTranslate : DWORD; pchURLIn : PWideChar; out ppchURLOut : PWideChar) : HRESULT; stdcall;
function FilterDataObject(pDO : IDataObject; out ppDORet : IDataObject) : HRESULT; stdcall;
procedure WMEraseBkgnd(var Message: TWMEraseBkgnd); message WM_ERASEBKGND;
// procedure WMPaint(var Message: TWMPaint); message WM_PAINT;
{ procedure SetParent(which : TWinControl); override;}
private
procedure OnWebBrowserTitleChange(Sender: TObject; const Text: WideString);
//procedure OnWebBrowserDocumentComplete(Sender: TObject; const pDisp: IDispatch; var URL: OleVariant);
private
fHideScrollbars : boolean;
fFlatScrollbars : boolean;
fHideBorders : boolean;
fAllowTextSelection : boolean;
fColor : TColor;
fDefaultPage : string;
fEntryCount : integer;
{$IFDEF WebBrowserTest}
fOnWebBrowserTest : TOnWebBrowserTest;
{$EndIf}
//fLocalPaint : boolean;
public
procedure NavigateMemory(const str: string);
procedure SetDefaultPage(const str: string);
public
property HideScrollbars : boolean read fHideScrollbars write fHideScrollbars;
property FlatScrollbars : boolean read fFlatScrollbars write fFlatScrollbars;
property HideBorders : boolean read fHideBorders write fHideBorders;
property AllowTextSelection : boolean read fAllowTextSelection write fAllowTextSelection;
property Color : TColor read fColor write fColor;
{$IFDEF WebBrowserTest}
property OnWebBrowserTest : TOnWebBrowserTest write fOnWebBrowserTest read fOnWebBrowserTest;
{$EndIf}
end;
implementation
uses
URLMon2, InternetSecurityManager, Sysutils
{$IFDEF Logs}, LogFile{$ENDIF}
{$IFDEF WebBrowserTest}, ComObj{$ENDIF};
// TCustomWebBrowser
function TCustomWebBrowser.QueryService(const rsid, iid : TGuid; out Obj) : HResult;
begin
if IsEqualGUID(rsid, SID_IInternetSecurityManager)
then
begin
{$IFDEF Logs}
LogThis('InternetSecurityManager requested');
{$ENDIF}
IInternetSecurityManager(Obj) := TInternetSecurityManager.Create as IInternetSecurityManager;
Result := S_OK;
end
else
begin
IUnknown(Obj) := nil;
Result := E_NOINTERFACE;
end;
{$IFDEF WebBrowserTest}
if assigned(fOnWebBrowserTest)
then fOnWebBrowserTest('IServiceProvider QueryService '+GUIDToString(rsid));
{$EndIf}
end;
function TCustomWebBrowser.ShowContextMenu(dwID : DWORD; ppt : PPoint; pcmdtReserved : IUnknown; pdispReserved : IDispatch) : HRESULT;
begin
{$IFDEF Logs}
LogThis('ShowContextMenu called');
{$ENDIF}
{$IFDEF WebBrowserTest}
if assigned(fOnWebBrowserTest)
then fOnWebBrowserTest('IDocHostHandler ShowContextMenu');
{$EndIf}
Result := S_OK;
end;
function TCustomWebBrowser.GetHostInfo(var pInfo : DOCHOSTUIINFO) : HRESULT;
begin
{$IFDEF Logs}
LogThis('GetHostInfo called');
{$ENDIF}
{$IFDEF WebBrowserTest}
if assigned(fOnWebBrowserTest)
then fOnWebBrowserTest('IDocHostHandler GetHostInfo');
{$EndIf}
pInfo.cbSize := sizeof(DOCHOSTUIINFO);
pInfo.dwFlags := 0; // could disable help menus and text selection also, there are flags available for that
if fHideScrollbars
then pInfo.dwFlags := pInfo.dwFlags or DOCHOSTUIFLAG_SCROLL_NO;
if fFlatScrollbars
then pInfo.dwFlags := pInfo.dwFlags or DOCHOSTUIFLAG_FLAT_SCROLLBAR;
if fHideBorders
then pInfo.dwFlags := pInfo.dwFlags or DOCHOSTUIFLAG_NO3DBORDER;
if not fAllowTextSelection
then pInfo.dwFlags := pInfo.dwFlags or DOCHOSTUIFLAG_DIALOG;
pInfo.dwDoubleClick := DOCHOSTUIDBLCLK_DEFAULT;
{
pInfo.pchHostCss := nil;
pInfo.pchHostNS := nil;
}
Result := S_OK;
end;
function TCustomWebBrowser.ShowUI(dwID : DWORD; pActiveObject : IOleInPlaceActiveObject; pCommandTarget : IOleCommandTarget; pFrame : IOleInPlaceFrame; pDoc : IOleInPlaceUIWindow) : HRESULT;
begin
Result := S_OK;
{$IFDEF WebBrowserTest}
if assigned(fOnWebBrowserTest)
then fOnWebBrowserTest('IDocHostHandler ShowUI');
{$EndIf}
end;
function TCustomWebBrowser.HideUI : HRESULT;
begin
{$IFDEF WebBrowserTest}
if assigned(fOnWebBrowserTest)
then fOnWebBrowserTest('IDocHostHandler HideUI');
{$EndIf}
Result := S_OK;
end;
function TCustomWebBrowser.UpdateUI : HRESULT;
begin
{$IFDEF WebBrowserTest}
if assigned(fOnWebBrowserTest)
then fOnWebBrowserTest('IDocHostHandler UpdateUI');
{$EndIf}
Result := S_OK;
end;
function TCustomWebBrowser.EnableModeless(fEnable : BOOL) : HRESULT;
begin
{$IFDEF WebBrowserTest}
if assigned(fOnWebBrowserTest)
then fOnWebBrowserTest('IDocHostHandler EnableModeless');
{$EndIf}
Result := S_OK;
end;
function TCustomWebBrowser.OnDocWindowActivate(fActivate : BOOL) : HRESULT;
begin
{$IFDEF WebBrowserTest}
if assigned(fOnWebBrowserTest)
then fOnWebBrowserTest('IDocHostHandler OnDocWindowActivate');
{$EndIf}
Result := S_OK;
end;
function TCustomWebBrowser.OnFrameWindowActivate(fActivate : BOOL) : HRESULT;
begin
{$IFDEF WebBrowserTest}
if assigned(fOnWebBrowserTest)
then fOnWebBrowserTest('IDocHostHandler OnFrameWindowActivate');
{$EndIf}
Result := S_OK;
end;
function TCustomWebBrowser.ResizeBorder(prcBorder : PRect; pUIWindow : IOleInPlaceUIWindow; fRameWindow : BOOL) : HRESULT;
begin
{$IFDEF WebBrowserTest}
if assigned(fOnWebBrowserTest)
then fOnWebBrowserTest('IDocHostHandler ResizeBorder');
{$EndIf}
Result := S_OK;
end;
function TCustomWebBrowser.TranslateAccelerator(lpMsg : PMsg; const pguidCmdGroup : PGUID; nCmdID : DWORD) : HRESULT;
begin
{$IFDEF WebBrowserTest}
if assigned(fOnWebBrowserTest)
then fOnWebBrowserTest('IDocHostHandler TranslateAccelerator');
{$EndIf}
Result := S_FALSE;
end; // S_FALSE or S_OK, test this
function TCustomWebBrowser.GetOptionKeyPath(out pchKey : PWideChar; dw : DWORD) : HRESULT;
begin
{$IFDEF WebBrowserTest}
if assigned(fOnWebBrowserTest)
then fOnWebBrowserTest('IDocHostHandler GetOptionKeyPath' + pchKey);
{$EndIf}
pchKey := nil;
Result := S_FALSE;
end; // it's not really clear if S_FALSE should be returned
function TCustomWebBrowser.GetDropTarget(pDropTarget : IDropTarget; out ppDropTarget : IDropTarget) : HRESULT;
begin
{$IFDEF WebBrowserTest}
if assigned(fOnWebBrowserTest)
then fOnWebBrowserTest('IDocHostHandler GetDropTarget');
{$EndIf}
Result := S_FALSE;
end; // might need to set ppDropTarget to nil
function TCustomWebBrowser.GetExternal(out ppDispatch : IDispatch) : HRESULT;
begin
{$IFDEF WebBrowserTest}
if assigned(fOnWebBrowserTest)
then fOnWebBrowserTest('IDocHostHandler GetExternal');
{$EndIf}
ppDispatch := nil;
Result := S_OK; // check if S_OK or S_FALSE
end;
function TCustomWebBrowser.TranslateUrl(dwTranslate : DWORD; pchURLIn : PWideChar; out ppchURLOut : PWideChar) : HRESULT;
begin
{$IFDEF WebBrowserTest}
if assigned(fOnWebBrowserTest)
then fOnWebBrowserTest('IDocHostHandler TranslateUrl '+ pchURLIn);
{$EndIf}
ppchURLOut := nil; // this was added
Result := S_FALSE;
end;
function TCustomWebBrowser.FilterDataObject(pDO : IDataObject; out ppDORet : IDataObject) : HRESULT;
begin
{$IFDEF WebBrowserTest}
if assigned(fOnWebBrowserTest)
then fOnWebBrowserTest('IDocHostHandler FilterDataObject');
{$EndIf}
ppDORet := nil;
Result := S_FALSE;
end;
procedure TCustomWebBrowser.NavigateMemory(const str: string);
begin
end;
procedure TCustomWebBrowser.WMEraseBkgnd(var Message: TWMEraseBkgnd);
begin {
if fColor = clBtnFace
then inherited
else }
Begin
Brush.Color := fColor;
Windows.FillRect(Message.dc, Clientrect, Brush.handle);
Message.result := 1;
end;
end;
{
procedure TCustomWebBrowser.WMPaint(var Message: TWMPaint);
begin
if fLocalPaint
then inherited
else
Begin
Brush.Color := fColor;
Windows.FillRect(Handle, Clientrect, Brush.handle);
Message.result := 1;
end;
end;
}
procedure TCustomWebBrowser.OnWebBrowserTitleChange(Sender: TObject; const Text: WideString);
begin
if (fEntryCount>2) and ((pos('cannot be found', Text)>0) or
(pos('No page to display', Text)>0) or
(pos('Web page unavailable while offline', Text)>0) or
(pos('About Working Offline', Text)>0) or
(pos('Not Found', Text)>0))
then
begin
Stop;
if fileexists(fDefaultPage)
then Navigate(fDefaultPage);
fEntryCount := 0;
end
else inc(fEntryCount);
end;
{
procedure TCustomWebBrowser.OnWebBrowserDocumentComplete(Sender: TObject; const pDisp: IDispatch; var URL: OleVariant);
begin
fLocalPaint := true;
// invalidate;
end;}
procedure TCustomWebBrowser.SetDefaultPage(const str: string);
begin
fDefaultPage := str;
OnTitleChange := OnWebBrowserTitleChange;
//OnDocumentComplete := OnWebBrowserDocumentComplete;
fEntryCount := 0;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.