text stringlengths 14 6.51M |
|---|
unit parser_types;
interface
type
THTMLParserTagType = (
pttNone,
pttStartTag,
pttEndTag,
pttEmptyTag,
pttContent,
pttComment,
pttCDATA
);
PHTMLParser_Attribute = ^THTMLParser_Attribute;
THTMLParser_Attribute = record
Name: AnsiString;
Value: AnsiString;
end;
implementation
end.
|
unit Unit1;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, Graphics, Dialogs, ExtCtrls,
LCLProc, LCLType, LCLIntf, Math;
type
{ TForm1 }
TForm1 = class(TForm)
Panel1: TPanel;
Timer1: TTimer;
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure FormShow(Sender: TObject);
procedure Panel1Paint(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
private
FOn: boolean;
FX: integer;
FY: integer;
FCaretRect: TRect;
procedure UpdateR;
public
end;
var
Form1: TForm1;
implementation
uses ATCanvasPrimitives;
{$R *.lfm}
const
CharSizeX = 10;
CharSizeY = 18;
{ TForm1 }
procedure TForm1.UpdateR;
begin
FCaretRect:= Rect(
FX*CharSizeX,
FY*CharSizeY,
(FX+1)*CharSizeX,
(FY+1)*CharSizeY);
end;
procedure TForm1.Timer1Timer(Sender: TObject);
begin
FOn:= not FOn;
InvalidateRect(Panel1.Handle, @FCaretRect, false);
end;
procedure TForm1.Panel1Paint(Sender: TObject);
var
C: TCanvas;
begin
C:= Panel1.Canvas;
if FOn then
CanvasInvertRect(C, FCaretRect, clPurple)
else
begin
C.Brush.Color:= clYellow;
C.FillRect(FCaretRect);
end;
end;
procedure TForm1.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
if key=VK_UP then
begin
FY:= Max(0, FY-1);
UpdateR;
Panel1.Invalidate;
key:= 0;
end;
if key=VK_DOWN then
begin
FY:= Min(15, FY+1);
UpdateR;
Panel1.Invalidate;
key:= 0;
end;
if key=VK_LEFT then
begin
FX:= Max(0, FX-1);
UpdateR;
Panel1.Invalidate;
key:= 0;
end;
if key=VK_RIGHT then
begin
FX:= Min(15, FX+1);
UpdateR;
Panel1.Invalidate;
key:= 0;
end;
end;
procedure TForm1.FormShow(Sender: TObject);
begin
UpdateR;
end;
end.
|
unit TestuProtoBufRawIO;
{
Delphi DUnit Test Case
----------------------
This unit contains a skeleton test case class generated by the Test Case Wizard.
Modify the generated code to correctly setup and call the methods from the unit
being tested.
}
interface
uses
{$IFDEF FPC}
fpcunit, testregistry,
{$ELSE}
TestFramework,
{$ENDIF}
Classes,
SysUtils;
type
// Test methods for raw Input/Output methods
// in pbInput and pbOutput
TestProtoBufRawIO = class(TTestCase)
strict private
procedure InputErrorVarInt32EOF;
procedure InputErrorVarInt32Unterminated;
procedure InputErrorVarInt32ToLong;
procedure InputErrorStringNegativeSize;
procedure InputErrorStringEOF;
procedure InputErrorBytesNegativeSize;
procedure InputErrorBytesEOF;
private
procedure DoReadRawVarIntForError(ABytes: Pointer; ASize: Integer);
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestVarint;
procedure TestVarintErrors;
procedure TestReadLittleEndian32;
procedure TestReadLittleEndian64;
procedure TestDecodeZigZag;
procedure TestEncodeDecodeZigZag;
procedure TestManuallyGeneratedMessageBuffer;
procedure TestReadTag;
procedure TestReadString;
procedure TestReadStringError;
procedure TestReadBytes;
procedure TestReadBytesErrors;
procedure TestReusingInputBufStream;
procedure TestReusingInputBufBuffer;
end;
implementation
uses
pbPublic,
pbInput,
pbOutput;
type
{$IFNDEF PB_USE_ASSERTS}
ExpectedPBException = EPBInputException;
{$ELSE}
ExpectedPBException = EAssertionFailed;
{$ENDIF}
procedure TestProtoBufRawIO.SetUp;
begin
end;
procedure TestProtoBufRawIO.TearDown;
begin
end;
procedure TestProtoBufRawIO.TestDecodeZigZag;
begin
(* 32 *)
CheckEquals(0, decodeZigZag32(0));
CheckEquals(-1, decodeZigZag32(1));
CheckEquals(1, decodeZigZag32(2));
CheckEquals(-2, decodeZigZag32(3));
CheckEquals(integer($3FFFFFFF), decodeZigZag32($7FFFFFFE));
CheckEquals(integer($C0000000), decodeZigZag32($7FFFFFFF));
CheckEquals(integer($7FFFFFFF), decodeZigZag32(integer($FFFFFFFE)));
CheckEquals(integer($80000000), decodeZigZag32(integer($FFFFFFFF)));
(* 64 *)
CheckEquals(0, decodeZigZag64(0));
CheckEquals(-1, decodeZigZag64(1));
CheckEquals(1, decodeZigZag64(2));
CheckEquals(-2, decodeZigZag64(3));
CheckEquals(Int64($000000003FFFFFFF), decodeZigZag64($000000007FFFFFFE));
CheckEquals(Int64($FFFFFFFFC0000000), decodeZigZag64($000000007FFFFFFF));
CheckEquals(Int64($000000007FFFFFFF), decodeZigZag64($00000000FFFFFFFE));
CheckEquals(Int64($FFFFFFFF80000000), decodeZigZag64($00000000FFFFFFFF));
CheckEquals(Int64($7FFFFFFFFFFFFFFF), decodeZigZag64($FFFFFFFFFFFFFFFE));
CheckEquals(Int64($8000000000000000), decodeZigZag64($FFFFFFFFFFFFFFFF));
end;
procedure TestProtoBufRawIO.TestEncodeDecodeZigZag;
var
i: integer;
j: integer;
i64: Int64;
j64: Int64;
begin
for i := -50000 to 50000 do
begin
j := EncodeZigZag32(i);
CheckEquals(i, decodeZigZag32(j), 'ZigZag32 symmetry error');
end;
i := -MaxInt;
j := EncodeZigZag32(i);
CheckEquals(i, decodeZigZag32(j), 'ZigZag32 symmetry error');
i := MaxInt;
j := EncodeZigZag32(i);
CheckEquals(i, decodeZigZag32(j), 'ZigZag32 symmetry error');
for i := -50000 to 50000 do
begin
i64:= i;
j64 := EncodeZigZag64(i64);
CheckEquals(i64, decodeZigZag64(j64), 'ZigZag64 symmetry error');
end;
i64 := $7FFFFFFFFFFFFFFF;
j64 := EncodeZigZag64(i64);
CheckEquals(i64, decodeZigZag64(j64), 'ZigZag64 symmetry error');
end;
procedure TestProtoBufRawIO.TestReadBytes;
var
Bytes, BytesRead: TBytes;
out_pb: TProtoBufOutput;
outputString: AnsiString;
in_pb: TProtoBufInput;
begin
Bytes:= TBytes.Create($04, $20, $00, $FF, $C0);
out_pb:= TProtoBufOutput.Create;
try
out_pb.writeBytes(1, Bytes);
outputString:= out_pb.GetText;
finally
out_pb.Free;
end;
in_pb:= TProtoBufInput.Create(@outputString[1], Length(outputString), True);
try
in_pb.readTag;
BytesRead:= in_pb.readBytes;
CheckEquals(Length(Bytes), Length(BytesRead), 'Bytes length mismatch');
Check(CompareMem(@Bytes[0], @BytesRead[0], Length(BytesRead)));
finally
in_pb.Free;
end;
end;
procedure TestProtoBufRawIO.TestReadBytesErrors;
begin
CheckException(InputErrorBytesNegativeSize, ExpectedPBException, 'negative size must cause Exception in .readBytes');
CheckException(InputErrorBytesEOF, ExpectedPBException, 'negative size must cause Exception in .readBytes');
end;
procedure TestProtoBufRawIO.TestReadLittleEndian32;
type
TLittleEndianCase = record
bytes: array [1 .. 4] of byte; // Encoded bytes.
value: integer; // Parsed value.
end;
const
LittleEndianCases: array [0 .. 5] of TLittleEndianCase = ((bytes: ($78, $56, $34, $12); value: $12345678),
(bytes: ($F0, $DE, $BC, $9A); value: integer($9ABCDEF0)), (bytes: ($FF, $00, $00, $00); value: 255),
(bytes: ($FF, $FF, $00, $00); value: 65535), (bytes: ($4E, $61, $BC, $00); value: 12345678),
(bytes: ($B2, $9E, $43, $FF); value: - 12345678));
var
i, j: integer;
t: TLittleEndianCase;
pb: TProtoBufInput;
buf: AnsiString;
int: integer;
begin
for i := 0 to 5 do
begin
t := LittleEndianCases[i];
SetLength(buf, 4);
for j := 1 to 4 do
buf[j] := AnsiChar(t.bytes[j]);
pb := TProtoBufInput.Create(@buf[1], 4);
try
int := pb.readRawLittleEndian32;
CheckEquals(t.value, int, 'Test readRawLittleEndian32 fails');
finally
pb.Free;
end;
end;
end;
procedure TestProtoBufRawIO.TestReadLittleEndian64;
type
TLittleEndianCase = record
bytes: array [1 .. 8] of byte; // Encoded bytes.
value: Int64; // Parsed value.
end;
const
LittleEndianCases: array [0 .. 3] of TLittleEndianCase = ((bytes: ($67, $45, $23, $01, $78, $56, $34, $12);
value: $1234567801234567), (bytes: ($F0, $DE, $BC, $9A, $78, $56, $34, $12); value: $123456789ABCDEF0),
(bytes: ($79, $DF, $0D, $86, $48, $70, $00, $00); value: 123456789012345),
(bytes: ($87, $20, $F2, $79, $B7, $8F, $FF, $FF); value: - 123456789012345));
var
i, j: integer;
t: TLittleEndianCase;
pb: TProtoBufInput;
buf: AnsiString;
int: Int64;
begin
for i := 0 to 3 do
begin
t := LittleEndianCases[i];
SetLength(buf, 8);
for j := 1 to 8 do
buf[j] := AnsiChar(t.bytes[j]);
pb := TProtoBufInput.Create(@buf[1], 8);
try
int := pb.readRawLittleEndian64;
CheckEquals(t.value, int, 'Test readRawLittleEndian64 fails');
finally
pb.Free;
end;
end;
end;
procedure TestProtoBufRawIO.TestReadString;
const
TestStrings: array[1..5] of string = (
'Тестовая строка',
'Überläuferspaß',
'测试消息',
'ItMightNotGetLoudButRatherLongerThanExpectedUsingCamelCase',
'MultilineString'#13#10'Even with unix style line ending '#10'We''ll see: ©µ@'
);
var
out_pb: TProtoBufOutput;
outputString: AnsiString;
in_pb: TProtoBufInput;
i: Integer;
begin
out_pb:= TProtoBufOutput.Create;
try
for i:= Low(TestStrings) to High(TestStrings) do
out_pb.writeString(i, TestStrings[i]);
outputString:= out_pb.GetText;
finally
out_pb.Free;
end;
in_pb:= TProtoBufInput.Create(@outputString[1], Length(outputString), True);
try
for i:= Low(TestStrings) to High(TestStrings) do
begin
CheckEquals(makeTag(i, WIRETYPE_LENGTH_DELIMITED), in_pb.readTag, 'Unexpected tag');
CheckEquals(TestStrings[i], in_pb.readString);
end;
finally
in_pb.Free;
end;
end;
procedure TestProtoBufRawIO.TestReadStringError;
begin
CheckException(InputErrorStringNegativeSize, ExpectedPBException, 'String with negative size -255 must cause an exception');
CheckException(InputErrorStringEOF, ExpectedPBException, 'negative size must cause Exception in .readString');
end;
procedure TestProtoBufRawIO.TestManuallyGeneratedMessageBuffer;
const
TEST_string = 'Тестовая строка';
TEST_integer = 12345678;
TEST_single = 12345.123;
TEST_double = 1234567890.123;
var
out_pb: TProtoBufOutput;
in_pb: TProtoBufInput;
tag, t: integer;
text: string;
int: integer;
dbl: double;
flt: single;
memStream: TMemoryStream;
begin
out_pb := TProtoBufOutput.Create;
in_pb := TProtoBufInput.Create();
memStream := TMemoryStream.Create();
try
out_pb.writeString(1, TEST_string);
out_pb.writeFixed32(2, TEST_integer);
out_pb.writeFloat(3, TEST_single);
out_pb.writeDouble(4, TEST_double);
out_pb.SaveToStream(memStream);
memStream.Position:= 0;
in_pb.LoadFromStream(memStream);
// TEST_string
tag := makeTag(1, WIRETYPE_LENGTH_DELIMITED);
t := in_pb.readTag;
CheckEquals(tag, t);
text := in_pb.readString;
CheckEquals(TEST_string, text);
// TEST_integer
tag := makeTag(2, WIRETYPE_FIXED32);
t := in_pb.readTag;
CheckEquals(tag, t);
int := in_pb.readFixed32;
CheckEquals(TEST_integer, int);
// TEST_single
tag := makeTag(3, WIRETYPE_FIXED32);
t := in_pb.readTag;
CheckEquals(tag, t);
flt := in_pb.readFloat;
CheckEquals(TEST_single, flt, 0.001);
// TEST_double
tag := makeTag(4, WIRETYPE_FIXED64);
t := in_pb.readTag;
CheckEquals(tag, t);
dbl := in_pb.readDouble;
CheckEquals(TEST_double, dbl, 0.000001);
finally
memStream.Free;
in_pb.Free;
out_pb.Free;
end;
end;
procedure TestProtoBufRawIO.TestReadTag;
var
out_pb: TProtoBufOutput;
in_pb: TProtoBufInput;
tag, t: integer;
tmp: TMemoryStream;
data_size: integer;
garbage: Cardinal;
begin
tmp := TMemoryStream.Create;
try
out_pb := TProtoBufOutput.Create;
try
out_pb.writeSInt32(1, 150);
out_pb.SaveToStream(tmp);
finally
out_pb.Free;
end;
data_size := tmp.Size;
garbage := $BADBAD;
tmp.WriteBuffer(garbage, SizeOf(garbage));
in_pb := TProtoBufInput.Create(tmp.Memory, data_size);
try
tag := makeTag(1, WIRETYPE_VARINT);
t := in_pb.readTag;
CheckEquals(tag, t);
CheckEquals(150, in_pb.readSInt32);
CheckEquals(0, in_pb.readTag);
finally
in_pb.Free;
end;
finally
tmp.Free;
end;
end;
procedure TestProtoBufRawIO.TestReusingInputBufBuffer;
var
out_pb: TProtoBufOutput;
in_pb: TProtoBufInput;
outputString: AnsiString;
i: Integer;
begin
out_pb:= TProtoBufOutput.Create;
try
out_pb.writeString(1, 'TestString');
outputString:= out_pb.GetText;
finally
out_pb.Free;
end;
in_pb:= TProtoBufInput.Create;
try
for i:= 1 to 2 do
begin
in_pb.LoadFromBuf(@outputString[1], Length(outputString));
in_pb.readTag; //value of no interest here
CheckEquals('TestString', in_pb.readString, Format('string mismatch, trial %d', [i]));
end;
finally
in_pb.Free;
end;
end;
procedure TestProtoBufRawIO.TestReusingInputBufStream;
var
out_pb: TProtoBufOutput;
in_pb: TProtoBufInput;
ms: TMemoryStream;
i: Integer;
begin
ms:= TMemoryStream.Create;
try
out_pb:= TProtoBufOutput.Create;
try
out_pb.writeString(1, 'TestString');
out_pb.SaveToStream(ms);
finally
out_pb.Free;
end;
in_pb:= TProtoBufInput.Create;
try
for i:= 1 to 2 do
begin
in_pb.LoadFromStream(ms);
in_pb.readTag; //value of no interest here
CheckEquals('TestString', in_pb.readString, Format('string mismatch, trial %d', [i]));
end;
finally
in_pb.Free;
end;
finally
ms.Free;
end;
end;
procedure TestProtoBufRawIO.TestVarint;
type
TVarintCaseOptions = set of (vcoIs64, vcoSkipOutputCheck);
TVarintCase = record
bytes: array [1 .. 10] of byte; // Encoded bytes.
Size: integer; // Encoded size, in bytes.
value: Int64; // Parsed value.
Options: TVarintCaseOptions;
end;
const
VarintCases: array [1 .. 17] of TVarintCase = (
// 32-bit values
(bytes: ($00, $00, $00, $00, $00, $00, $00, $00, $00, $00); Size: 1; value: 0; Options: []),
(bytes: ($01, $00, $00, $00, $00, $00, $00, $00, $00, $00); Size: 1; value: 1; Options: []),
(bytes: ($7F, $00, $00, $00, $00, $00, $00, $00, $00, $00); Size: 1; value: 127; Options: []),
(bytes: ($A2, $74, $00, $00, $00, $00, $00, $00, $00, $00); Size: 2; value: 14882; Options: []),
(bytes: ($FF, $FF, $FF, $FF, $07, $00, $00, $00, $00, $00); Size: 5; value: 2147483647; Options: []),
(bytes: ($FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $01); Size: 10; value: -1; Options: []),
(bytes: ($D5, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $01); Size: 10; value: -43; Options: []),
(bytes: ($81, $FE, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $01); Size: 10; value: -255; Options: []),
(bytes: ($B7, $81, $FC, $FF, $FF, $FF, $FF, $FF, $FF, $01); Size: 10; value: -65353; Options: []),
(bytes: ($80, $80, $80, $80, $F8, $FF, $FF, $FF, $FF, $01); Size: 10; value: -2147483648; Options: []),
// 32-bit values that are not padded to 64bit, make sure we can read them,
// but don't compare our output, as it will have lenth 10, since we pad correctly
(bytes: ($FF, $FF, $FF, $FF, $0F, $00, $00, $00, $00, $00); Size: 5; value: -1; Options: [vcoSkipOutputCheck]),
(bytes: ($81, $FE, $FF, $FF, $0F, $00, $00, $00, $00, $00); Size: 5; value: -255; Options: [vcoSkipOutputCheck]),
(bytes: ($B7, $81, $FC, $FF, $0F, $00, $00, $00, $00, $00); Size: 5; value: -65353; Options: [vcoSkipOutputCheck]),
(bytes: ($80, $80, $80, $80, $08, $00, $00, $00, $00, $00); Size: 5; value: -2147483648; Options: [vcoSkipOutputCheck]),
// 64-bit
(bytes: ($BE, $F7, $92, $84, $0B, $00, $00, $00, $00, $00); Size: 5; value: 2961488830; Options: [vcoIs64]),
(bytes: ($BE, $F7, $92, $84, $1B, $00, $00, $00, $00, $00); Size: 5; value: 7256456126; Options: [vcoIs64]),
(bytes: ($80, $E6, $EB, $9C, $C3, $C9, $A4, $49, $00, $00); Size: 8; value: 41256202580718336; Options: [vcoIs64]));
var
i, j, k: integer;
t: TVarintCase;
pbi: TProtoBufInput;
pbo: TProtoBufOutput;
buf, output: AnsiString;
i64: Int64;
int: integer;
begin
pbo:= TProtoBufOutput.Create;
try
for i := Low(VarIntCases) to High(VarIntCases) do
begin
t:= VarintCases[i];
pbo.Clear;
// create test buffer
SetLength(buf, t.Size);
for j := 1 to t.Size do
buf[j] := AnsiChar(t.bytes[j]);
pbi := TProtoBufInput.Create(@buf[1], t.Size);
try
if vcoIs64 in t.Options then
begin
i64 := pbi.readRawVarint64;
CheckEquals(t.value, i64, Format('Test Varint64 %d fails', [i]));
pbo.writeRawVarint64(i64);
end else
begin
int := pbi.readRawVarint32;
CheckEquals(t.value, int, Format('Test Varint32 %d fails', [i]));
pbo.writeRawVarint32(t.value);
end;
if vcoSkipOutputCheck in t.Options then
Continue;
output:= pbo.GetText;
CheckEquals(t.Size, Length(output), Format('Output for Test %d is not as long/short as expected', [i]));
for k:= 1 to t.Size do
CheckEquals(t.bytes[k], Byte(output[k]), Format('Output for Test %d differs from input at index %d', [i, k]));
finally
pbi.Free;
end;
end;
finally
pbo.Free;
end;
end;
procedure TestProtoBufRawIO.DoReadRawVarIntForError(ABytes: Pointer; ASize: Integer);
var
pb: TProtoBufInput;
begin
pb:= TProtoBufInput.Create(ABytes, ASize);
try
//we only call readRawVarint64 as this is what readRawVarint32 does anyway
pb.readRawVarint64;
finally
pb.Free;
end;
end;
procedure TestProtoBufRawIO.InputErrorBytesEOF;
const
bytes: array[1..2] of Byte = ($02, $20);
var
pb: TProtoBufInput;
begin
pb:= TProtoBufInput.Create(@bytes[1], SizeOf(bytes));
try
pb.readBytes;
finally
pb.Free;
end;
end;
procedure TestProtoBufRawIO.InputErrorBytesNegativeSize;
const
//negative size -255, bytes taken from TestVarInt
bytes: array[1..10] of Byte = ($81, $FE, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $01);
var
pb: TProtoBufInput;
begin
pb:= TProtoBufInput.Create(@bytes[1], SizeOf(bytes));
try
pb.readBytes;
finally
pb.Free;
end;
end;
procedure TestProtoBufRawIO.InputErrorStringEOF;
const
bytes: array[1..2] of Byte = ($02, $20);
var
pb: TProtoBufInput;
begin
pb:= TProtoBufInput.Create(@bytes[1], SizeOf(bytes));
try
pb.readString;
finally
pb.Free;
end;
end;
procedure TestProtoBufRawIO.InputErrorStringNegativeSize;
const
//negative size -255, bytes taken from TestVarInt
bytes: array[1..10] of Byte = ($81, $FE, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $01);
var
pb: TProtoBufInput;
begin
pb:= TProtoBufInput.Create(@bytes[1], SizeOf(bytes));
try
pb.readString;
finally
pb.Free;
end;
end;
procedure TestProtoBufRawIO.InputErrorVarInt32EOF;
const
bytes: array[1..2] of Byte = ($FF, $FF);
begin
DoReadRawVarIntForError(@bytes, SizeOf(bytes));
end;
procedure TestProtoBufRawIO.InputErrorVarInt32Unterminated;
const
bytes: array[1..10] of Byte = ($FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF);
begin
DoReadRawVarIntForError(@bytes, SizeOf(bytes) - 1);
end;
procedure TestProtoBufRawIO.InputErrorVarInt32ToLong;
const
bytes: array[1..11] of Byte = ($FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF);
begin
DoReadRawVarIntForError(@bytes, SizeOf(bytes));
end;
procedure TestProtoBufRawIO.TestVarintErrors;
begin
CheckException(InputErrorVarInt32EOF, ExpectedPBException, 'VarInt32 unexpected EOF after 2 bytes');
CheckException(InputErrorVarInt32Unterminated, ExpectedPBException, 'VarInt32 with 10 bytes and last msb set');
CheckException(InputErrorVarInt32ToLong, ExpectedPBException, 'VarInt32 which has more than 5 bytes must cause an exception');
end;
initialization
RegisterTest('ProtoBufRawIO', TestProtoBufRawIO.Suite);
end.
|
{
$Project$
$Workfile$
$Revision$
$DateUTC$
$Id$
This file is part of the Indy (Internet Direct) project, and is offered
under the dual-licensing agreement described on the Indy website.
(http://www.indyproject.org/)
Copyright:
(c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved.
$Log$
//TODO: Elim read/write methods - they are duped
//TODO: See second uses comment
Rev 1.68 3/7/2005 5:48:18 PM JPMugaas
Made a backdoor so we can adjust command output in specific ways.
Rev 1.67 1/15/2005 6:02:02 PM JPMugaas
These should compile again.
Rev 1.66 1/15/05 2:16:04 PM RLebeau
Misc. tweaks
Rev 1.65 12/21/04 3:20:54 AM RLebeau
Removed compiler warning
Rev 1.64 12/12/04 2:24:28 PM RLebeau
Updated WriteRFCStrings() to call new method in the IOHandler.
Rev 1.63 10/26/2004 8:43:02 PM JPMugaas
Should be more portable with new references to TIdStrings and TIdStringList.
Rev 1.62 6/11/2004 8:48:36 AM DSiders
Added "Do not Localize" comments.
Rev 1.61 2004.06.07 1:34:20 PM czhower
OnWork fix now sends running total as it should.
Rev 1.60 2004.06.06 5:18:04 PM czhower
OnWork bug fix
Rev 1.59 2004.06.05 9:46:30 AM czhower
IOHandler OnWork fix
Rev 1.58 11/05/2004 17:13:32 HHariri
Fix brought from IW for overflow of DoWork
Rev 1.57 4/19/2004 9:50:08 AM BGooijen
Fixed AV in .Disconnect
Rev 1.56 2004.04.18 12:52:04 AM czhower
Big bug fix with server disconnect and several other bug fixed that I found
along the way.
Rev 1.55 2004.03.06 10:40:30 PM czhower
Changed IOHandler management to fix bug in server shutdowns.
Rev 1.54 2004.03.06 1:32:58 PM czhower
-Change to disconnect
-Addition of DisconnectNotifyPeer
-WriteHeader now write bufers
Rev 1.53 3/1/04 7:12:00 PM RLebeau
Bug fix for SetIOHandler() not updating the FSocket member correctly.
Rev 1.52 2004.02.03 4:16:56 PM czhower
For unit name changes.
Rev 1.51 1/29/04 9:37:18 PM RLebeau
Added setter method for Greeting property
Rev 1.50 2004.01.28 9:42:32 PM czhower
Now checks for connection.
Rev 1.49 2004.01.20 10:03:36 PM czhower
InitComponent
Rev 1.48 2003.12.31 3:47:44 PM czhower
Changed to use TextIsSame
Rev 1.47 12/28/2003 4:47:40 PM BGooijen
Removed ChangeReplyClass
Rev 1.46 14/12/2003 18:14:54 CCostelloe
Added ChangeReplyClass procedure.
Rev 1.45 11/4/2003 10:28:34 PM DSiders
Removed exceptions moved to IdException.pas.
Rev 1.44 2003.10.18 9:33:28 PM czhower
Boatload of bug fixes to command handlers.
Rev 1.43 10/15/2003 7:32:48 PM DSiders
Added a resource string for the exception raised in
TIdTCPConnection.CreateIOHandler.
Rev 1.42 2003.10.14 1:27:02 PM czhower
Uupdates + Intercept support
Rev 1.41 10/10/2003 11:00:36 PM BGooijen
Added GetReplyClass
Rev 1.40 2003.10.02 8:29:40 PM czhower
Added IdReply back
Rev 1.39 2003.10.02 8:08:52 PM czhower
Removed unneeded unit in uses.
Rev 1.38 2003.10.01 9:11:28 PM czhower
.Net
Rev 1.37 2003.10.01 5:05:18 PM czhower
.Net
Rev 1.36 2003.10.01 2:30:42 PM czhower
.Net
Rev 1.35 2003.10.01 11:16:38 AM czhower
.Net
Rev 1.34 2003.09.30 1:23:06 PM czhower
Stack split for DotNet
Rev 1.33 2003.09.18 7:12:42 PM czhower
AV Fix in SetIOHandler
Rev 1.32 2003.09.18 5:18:00 PM czhower
Implemented OnWork
Rev 1.31 2003.06.30 6:17:48 PM czhower
Moved socket property to public. Dont know how/why it got protected.
Rev 1.30 2003.06.30 5:41:56 PM czhower
-Fixed AV that occurred sometimes when sockets were closed with chains
-Consolidated code that was marked by a todo for merging as it no longer
needed to be separate
-Removed some older code that was no longer necessary
Passes bubble tests.
Rev 1.29 2003.06.05 10:08:52 AM czhower
Extended reply mechanisms to the exception handling. Only base and RFC
completed, handing off to J Peter.
Rev 1.28 6/4/2003 03:54:42 PM JPMugaas
Now should compile.
Rev 1.27 2003.06.04 8:10:00 PM czhower
Modified CheckResponse string version to allow ''
Rev 1.26 2003.06.04 12:02:30 PM czhower
Additions for text code and command handling.
Rev 1.25 2003.06.03 3:44:26 PM czhower
Removed unused variable.
Rev 1.24 2003.05.30 10:25:58 PM czhower
Implemented IsEndMarker
Rev 1.23 5/26/2003 04:29:52 PM JPMugaas
Removed GenerateReply and ParseReply. Those are now obsolete duplicate
functions in the new design.
Rev 1.22 5/26/2003 12:19:56 PM JPMugaas
Rev 1.21 2003.05.26 11:38:20 AM czhower
Rev 1.20 5/25/2003 03:34:54 AM JPMugaas
Rev 1.19 5/25/2003 03:16:22 AM JPMugaas
Rev 1.18 5/20/2003 02:40:10 PM JPMugaas
Rev 1.17 5/20/2003 12:43:50 AM BGooijen
changeable reply types
Rev 1.16 4/4/2003 8:10:14 PM BGooijen
procedure CreateIOHandler is now public
Rev 1.15 3/27/2003 3:17:32 PM BGooijen
Removed MaxLineLength, MaxLineAction, SendBufferSize, RecvBufferSize,
ReadLnSplit, ReadLnTimedOut
Rev 1.14 3/19/2003 1:04:16 PM BGooijen
changed procedure CreateIOHandler a little (default parameter, and other
behavour when parameter = nil (constructs default now))
Rev 1.13 3/5/2003 11:07:18 PM BGooijen
removed intercept from this file
Rev 1.12 2003.02.25 7:28:02 PM czhower
Fixed WriteRFCReply
Rev 1.11 2003.02.25 1:36:20 AM czhower
Rev 1.10 2/13/2003 02:14:44 PM JPMugaas
Now calls ReadLn in GetInternelResponse so a space is not dropped. Dropping
a space throws off some things in FTP such as the FEAT reply.
Rev 1.9 2003.01.18 12:29:52 PM czhower
Rev 1.8 1-17-2003 22:22:08 BGooijen
new design
Rev 1.7 12-16-2002 20:44:38 BGooijen
Added procedure CreateIOHandler(....)
Rev 1.6 12-15-2002 23:32:32 BGooijen
Added RecvBufferSize
Rev 1.5 12-14-2002 22:16:32 BGooijen
improved method to detect timeouts in ReadLn.
Rev 1.4 12/6/2002 02:11:46 PM JPMugaas
Protected Port and Host properties added to TCPClient because those are
needed by protocol implementations. Socket property added to TCPConnection.
Rev 1.3 6/12/2002 11:00:16 AM SGrobety
Rev 1.0 21/11/2002 12:36:48 PM SGrobety Version: Indy 10
Rev 1.2 11/15/2002 01:26:42 PM JPMugaas
Restored Trim to ReadLnWait and changed GetInternelResponse to use ReadLn
instead of ReadLn wait.
Rev 1.1 11/14/2002 06:44:54 PM JPMugaas
Removed Trim from ReadLnWait. It was breaking the new RFC Reply parsing code
by removing the space at the beggining of a line.
Rev 1.0 11/13/2002 09:00:30 AM JPMugaas
}
unit IdTCPConnection;
interface
{$i IdCompilerDefines.inc}
{
2003-12-14 - Ciaran Costelloe
- Added procedure ChangeReplyClass, because in .NET, you cannot set FReplyClass
before calling the constructor, so call this procedure after the constructor
to set FReplyClass to (say) TIdReplyIMAP4.
2002-06 -Andrew P.Rybin
-WriteStream optimization and new "friendly" interface, InputLn fix (CrLf only if AEcho)
2002-04-12 - Andrew P.Rybin
- ReadLn bugfix and optimization
2002-01-20 - Chad Z. Hower a.k.a Kudzu
-WriteBuffer change was not correct. Removed. Need info on original problem to fix properly.
-Modified ReadLnWait
2002-01-19 - Grahame Grieve
- Fix to WriteBuffer to accept -1 from the stack.
Also fixed to clean up FWriteBuffer if connection lost.
2002-01-19 - Chad Z. Hower a.k.a Kudzu
-Fix to ReadLn
2002-01-16 - Andrew P.Rybin
-ReadStream optimization, TIdManagedBuffer new
2002-01-03 - Chad Z. Hower a.k.a Kudzu
-Added MaxLineAction
-Added ReadLnSplit
2001-12-27 - Chad Z. Hower a.k.a Kudzu
-Changes and bug fixes to InputLn
-Modifed how buffering works
-Added property InputBuffer
-Moved some things to TIdBuffer
-Modified ReadLn
-Added LineCount to Capture
2001-12-25 - Andrew P.Rybin
-MaxLineLength,ReadLn,InputLn and Merry Christmas!
Original Author and Maintainer:
-Chad Z. Hower a.k.a Kudzu
}
uses
Classes,
IdComponent,
IdException,
IdExceptionCore,
IdGlobal,
IdIntercept,
IdIOHandler,
IdIOHandlerSocket,
IdIOHandlerStack,
IdReply,
IdSocketHandle,
IdBaseComponent;
type
TIdTCPConnection = class(TIdComponent)
protected
FGreeting: TIdReply;
FIntercept: TIdConnectionIntercept;
FIOHandler: TIdIOHandler;
FLastCmdResult: TIdReply;
FManagedIOHandler: Boolean;
FOnDisconnected: TNotifyEvent;
FSocket: TIdIOHandlerSocket;
FReplyClass: TIdReplyClass;
//
procedure CheckConnected;
procedure DoOnDisconnected; virtual;
procedure InitComponent; override;
function GetIntercept: TIdConnectionIntercept; virtual;
function GetReplyClass: TIdReplyClass; virtual;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure SetIntercept(AValue: TIdConnectionIntercept); virtual;
procedure SetIOHandler(AValue: TIdIOHandler); virtual;
procedure SetGreeting(AValue: TIdReply);
procedure WorkBeginEvent(ASender: TObject; AWorkMode: TWorkMode; AWorkCountMax: Int64);
procedure WorkEndEvent(ASender: TObject; AWorkMode: TWorkMode);
procedure WorkEvent(ASender: TObject; AWorkMode: TWorkMode; AWorkCount: Int64);
procedure PrepareCmd(var aCmd: string); virtual;
public
procedure CreateIOHandler(ABaseType: TIdIOHandlerClass = nil);
procedure CheckForGracefulDisconnect(ARaiseExceptionIfDisconnected: Boolean = True); virtual;
//
function CheckResponse(const AResponse: SmallInt;
const AAllowedResponses: array of SmallInt): SmallInt; overload; virtual;
function CheckResponse(const AResponse, AAllowedResponse: string): string; overload; virtual;
//
function Connected: Boolean; virtual;
destructor Destroy; override;
// Dont allow override of this one, its for overload only
procedure Disconnect; overload; // .Net overload
procedure Disconnect(ANotifyPeer: Boolean); overload; virtual;
// This is called when a protocol sends a command to tell the other side (typically client to
// server) that it is about to disconnect. The implementation should go here.
procedure DisconnectNotifyPeer; virtual;
// GetInternalResponse is not in IOHandler as some protocols may need to
// override it. It could be still moved and proxied from here, but at this
// point it is here.
procedure GetInternalResponse(AEncoding: TIdTextEncoding = nil); virtual;
// Reads response using GetInternalResponse which each reply type can define
// the behaviour. Then checks against expected Code.
//
// Seperate one for singles as one of the older Delphi compilers cannot
// match a single number into an array. IIRC newer ones do.
function GetResponse(const AAllowedResponse: SmallInt = -1;
AEncoding: TIdTextEncoding = nil): SmallInt; overload;
function GetResponse(const AAllowedResponses: array of SmallInt;
AEncoding: TIdTextEncoding = nil): SmallInt; overload; virtual;
// No array type for strings as ones that use strings are usually bastard
// protocols like POP3/IMAP which dont include proper substatus anyways.
//
// If a case can be made for some other condition this may be expanded
// in the future
function GetResponse(const AAllowedResponse: string;
AEncoding: TIdTextEncoding = nil): string; overload; virtual;
//
property Greeting: TIdReply read FGreeting write SetGreeting;
// RaiseExceptionForCmdResult - Overload necesary as a exception as a default param doesnt work
procedure RaiseExceptionForLastCmdResult; overload; virtual;
procedure RaiseExceptionForLastCmdResult(AException: TClassIdException);
overload; virtual;
// These are extended GetResponses, so see the comments for GetResponse
function SendCmd(AOut: string; const AResponse: SmallInt = -1;
AEncoding: TIdTextEncoding = nil): SmallInt; overload;
function SendCmd(AOut: string; const AResponse: array of SmallInt;
AEncoding: TIdTextEncoding = nil): SmallInt; overload; virtual;
function SendCmd(AOut: string; const AResponse: string;
AEncoding: TIdTextEncoding = nil): string; overload;
//
procedure WriteHeader(AHeader: TStrings);
procedure WriteRFCStrings(AStrings: TStrings);
//
property LastCmdResult: TIdReply read FLastCmdResult;
property ManagedIOHandler: Boolean read FManagedIOHandler write FManagedIOHandler;
property Socket: TIdIOHandlerSocket read FSocket;
published
property Intercept: TIdConnectionIntercept read GetIntercept write SetIntercept;
property IOHandler: TIdIOHandler read FIOHandler write SetIOHandler;
// Events
property OnDisconnected: TNotifyEvent read FOnDisconnected write FOnDisconnected;
property OnWork;
property OnWorkBegin;
property OnWorkEnd;
end;
implementation
uses
IdAntiFreezeBase, IdResourceStringsCore, IdStackConsts, IdReplyRFC,
SysUtils;
function TIdTCPConnection.GetIntercept: TIdConnectionIntercept;
begin
if (IOHandler <> nil) then begin
Result := IOHandler.Intercept;
end else begin
Result := FIntercept;
end;
end;
function TIdTCPConnection.GetReplyClass:TIdReplyClass;
begin
Result := TIdReplyRFC;
end;
procedure TIdTCPConnection.CreateIOHandler(ABaseType:TIdIOHandlerClass=nil);
begin
if Connected then begin
EIdException.Toss(RSIOHandlerCannotChange);
end;
if Assigned(ABaseType) then begin
IOHandler := TIdIOHandler.MakeIOHandler(ABaseType);
end else begin
IOHandler := TIdIOHandler.MakeDefaultIOHandler;
end;
ManagedIOHandler := True;
end;
function TIdTCPConnection.Connected: Boolean;
begin
// Its been changed now that IOHandler is not usually nil, but can be before the initial connect
// and also this keeps it here so the user does not have to access the IOHandler for this and
// also to allow future control from the connection.
Result := IOHandler <> nil;
if Result then begin
Result := IOHandler.Connected;
end;
end;
destructor TIdTCPConnection.Destroy;
begin
// Just close IOHandler directly. Dont call Disconnect - Disconnect may be override and
// try to read/write to the socket.
if Assigned(IOHandler) then begin
IOHandler.Close;
// This will free any managed IOHandlers
IOHandler := nil;
end;
FreeAndNil(FLastCmdResult);
FreeAndNil(FGreeting);
inherited Destroy;
end;
procedure TIdTCPConnection.Disconnect(ANotifyPeer: Boolean);
begin
try
// Separately to avoid calling .Connected unless needed
if ANotifyPeer then begin
if Connected then begin
DisconnectNotifyPeer;
end;
end;
finally
{
there are a few possible situations here:
1) we are still connected, then everything works as before,
status disconnecting, then disconnect, status disconnected
2) we are not connected, and this is just some "rogue" call to
disconnect(), then nothing happens
3) we are not connected, because ClosedGracefully, then
LConnected will be false, but the implicit call to
CheckForDisconnect (inside Connected) will call the events
}
// We dont check connected here - we realy dont care about actual socket state
// Here we just want to close the actual IOHandler. It is very possible for a
// socket to be disconnected but the IOHandler still open. In this case we only
// care of the IOHandler is still open.
//
// This is especially important if the socket has been disconnected with error, at this
// point we just want to ignore it and checking .Connected would trigger this. We
// just want to close. For some reason NS 7.1 (And only 7.1, not 7.0 or Mozilla) cause
// CONNABORTED. So its extra important we just disconnect without checking socket state.
if Assigned(IOHandler) then begin
if IOHandler.Opened then begin
DoStatus(hsDisconnecting);
IOHandler.Close;
DoOnDisconnected;
DoStatus(hsDisconnected);
//FIOHandler.InputBuffer.Clear;
end;
end;
end;
end;
procedure TIdTCPConnection.DoOnDisconnected;
begin
if Assigned(OnDisconnected) then begin
OnDisconnected(Self);
end;
end;
function TIdTCPConnection.GetResponse(const AAllowedResponses: array of SmallInt;
AEncoding: TIdTextEncoding = nil): SmallInt;
begin
GetInternalResponse(AEncoding);
Result := CheckResponse(LastCmdResult.NumericCode, AAllowedResponses);
end;
procedure TIdTCPConnection.RaiseExceptionForLastCmdResult(
AException: TClassIdException);
begin
raise AException.Create(LastCmdResult.Text.Text);
end;
procedure TIdTCPConnection.RaiseExceptionForLastCmdResult;
begin
LastCmdResult.RaiseReplyError;
end;
function TIdTCPConnection.SendCmd(AOut: string; const AResponse: Array of SmallInt;
AEncoding: TIdTextEncoding = nil): SmallInt;
begin
CheckConnected;
PrepareCmd(AOut);
IOHandler.WriteLn(AOut, AEncoding);
Result := GetResponse(AResponse, AEncoding);
end;
procedure TIdTCPConnection.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if (Operation = opRemove) then begin
if (AComponent = FIntercept) then begin
FIntercept := nil;
end;
if (AComponent = FIOHandler) then begin
FIOHandler := nil;
FSocket := nil;
end;
end;
end;
procedure TIdTCPConnection.SetIntercept(AValue: TIdConnectionIntercept);
begin
if AValue <> FIntercept then
begin
// RLebeau 8/25/09 - normally, short-circuit logic should skip all subsequent
// evaluations in a multi-condition statement once one of the conditions
// evaluates to False. However, a user just ran into a situation where that
// was not the case! It caused an AV in SetIOHandler() further below when
// AValue was nil (from Destroy() further above) because Assigned(AValue.Intercept)
// was still being evaluated even though Assigned(AValue) was returning False.
// SetIntercept() is using the same kind of short-circuit logic here as well.
// Let's not rely on short-circuiting anymore, just to be on the safe side.
//
// old code: if Assigned(IOHandler) and Assigned(IOHandler.Intercept) and Assigned(AValue) and (AValue <> IOHandler.Intercept) then begin
//
if Assigned(IOHandler) and Assigned(AValue) then begin
if Assigned(IOHandler.Intercept) and (IOHandler.Intercept <> AValue) then begin
EIdException.Toss(RSInterceptIsDifferent);
end;
end;
// remove self from the Intercept's free notification list
if Assigned(FIntercept) then begin
FIntercept.RemoveFreeNotification(Self);
end;
FIntercept := AValue;
// add self to the Intercept's free notification list
if Assigned(FIntercept) then begin
FIntercept.FreeNotification(Self);
end;
if Assigned(IOHandler) then begin
IOHandler.Intercept := AValue;
end;
end;
end;
procedure TIdTCPConnection.SetIOHandler(AValue: TIdIOHandler);
begin
if AValue <> FIOHandler then begin
// RLebeau 8/25/09 - normally, short-circuit logic should skip all subsequent
// evaluations in a multi-condition statement once one of the conditions
// evaluates to False. However, a user just ran into a situation where that
// was not the case! It caused an AV when AValue was nil (from Destroy()
// further above) because Assigned(AValue.Intercept) was still being evaluated
// even though Assigned(AValue) was returning False. Let's not rely on
// short-circuiting anymore, just to be on the safe side.
//
// old code: if Assigned(AValue) and Assigned(AValue.Intercept) and Assigned(FIntercept) and (AValue.Intercept <> FIntercept) then begin
//
if Assigned(AValue) and Assigned(FIntercept) then begin
if Assigned(AValue.Intercept) and (AValue.Intercept <> FIntercept) then begin
EIdException.Toss(RSInterceptIsDifferent);
end;
end;
if ManagedIOHandler and Assigned(FIOHandler) then begin
FreeAndNil(FIOHandler);
end;
// Reset this if nil (to match nil, but not needed) or when a new IOHandler is specified
// If true, code must set it after the IOHandler is set
// Must do after call to FreeManagedIOHandler
FSocket := nil;
ManagedIOHandler := False;
// Clear out old values whether setting AValue to nil, or setting a new value
if Assigned(FIOHandler) then begin
FIOHandler.WorkTarget := nil;
FIOHandler.RemoveFreeNotification(Self);
end;
if Assigned(AValue) then begin
// add self to the IOHandler's free notification list
AValue.FreeNotification(Self);
// Must set to handlers and not events directly as user may change
// the events of TCPConnection after we have initialized these and then
// these would point to old values
AValue.WorkTarget := Self;
if Assigned(FIntercept) then begin
AValue.Intercept := FIntercept;
end;
if AValue is TIdIOHandlerSocket then begin
FSocket := TIdIOHandlerSocket(AValue);
end;
end;
// Last as some code uses FIOHandler to finalize items
FIOHandler := AValue;
end;
end;
procedure TIdTCPConnection.WriteHeader(AHeader: TStrings);
var
i: Integer;
LBufferingStarted: Boolean;
begin
CheckConnected;
with IOHandler do
begin
LBufferingStarted := not WriteBufferingActive;
if LBufferingStarted then begin
WriteBufferOpen;
end;
try
for i := 0 to AHeader.Count -1 do begin
// No ReplaceAll flag - we only want to replace the first one
WriteLn(ReplaceOnlyFirst(AHeader[i], '=', ': '));
end;
WriteLn;
if LBufferingStarted then begin
WriteBufferClose;
end;
except
if LBufferingStarted then begin
WriteBufferCancel;
end;
raise;
end;
end;
end;
function TIdTCPConnection.SendCmd(AOut: string; const AResponse: SmallInt = -1;
AEncoding: TIdTextEncoding = nil): SmallInt;
begin
if AResponse < 0 then begin
Result := SendCmd(AOut, [], AEncoding);
end else begin
Result := SendCmd(AOut, [AResponse], AEncoding);
end;
end;
procedure TIdTCPConnection.CheckForGracefulDisconnect(ARaiseExceptionIfDisconnected: Boolean);
begin
if Assigned(IOHandler) then begin
IOHandler.CheckForDisconnect(ARaiseExceptionIfDisconnected);
end else if ARaiseExceptionIfDisconnected then begin
raise EIdException.Create(RSNotConnected);
end;
end;
function TIdTCPConnection.CheckResponse(const AResponse: SmallInt;
const AAllowedResponses: array of SmallInt): SmallInt;
var
i: Integer;
LResponseFound: Boolean;
begin
if High(AAllowedResponses) > -1 then begin
LResponseFound := False;
for i := Low(AAllowedResponses) to High(AAllowedResponses) do begin
if AResponse = AAllowedResponses[i] then begin
LResponseFound := True;
Break;
end;
end;
if not LResponseFound then begin
RaiseExceptionForLastCmdResult;
end;
end;
Result := AResponse;
end;
procedure TIdTCPConnection.GetInternalResponse(AEncoding: TIdTextEncoding = nil);
var
LLine: string;
LResponse: TStringList;
begin
CheckConnected;
LResponse := TStringList.Create; try
// Some servers with bugs send blank lines before reply. Dont remember which
// ones, but I do remember we changed this for a reason
// RLebeau 9/14/06: this can happen in between lines of the reply as well
repeat
LLine := IOHandler.ReadLnWait(MaxInt, AEncoding);
LResponse.Add(LLine);
until FLastCmdResult.IsEndMarker(LLine);
//Note that FormattedReply uses an assign in it's property set method.
FLastCmdResult.FormattedReply := LResponse;
finally FreeAndNil(LResponse); end;
end;
procedure TIdTCPConnection.WriteRFCStrings(AStrings: TStrings);
begin
CheckConnected;
IOHandler.WriteRFCStrings(AStrings, True);
end;
function TIdTCPConnection.GetResponse(const AAllowedResponse: SmallInt = -1;
AEncoding: TIdTextEncoding = nil): SmallInt;
begin
if AAllowedResponse < 0 then begin
Result := GetResponse([], AEncoding);
end else begin
Result := GetResponse([AAllowedResponse], AEncoding);
end;
end;
function TIdTCPConnection.GetResponse(const AAllowedResponse: string;
AEncoding: TIdTextEncoding = nil): string;
begin
GetInternalResponse(AEncoding);
Result := CheckResponse(LastCmdResult.Code, AAllowedResponse);
end;
function TIdTCPConnection.SendCmd(AOut: string; const AResponse: string;
AEncoding: TIdTextEncoding = nil): string;
begin
CheckConnected;
PrepareCmd(AOut);
IOHandler.WriteLn(AOut, AEncoding);
Result := GetResponse(AResponse, AEncoding);
end;
function TIdTCPConnection.CheckResponse(const AResponse, AAllowedResponse: string): string;
begin
if (AAllowedResponse <> '')
and (not TextIsSame(AResponse, AAllowedResponse)) then begin
RaiseExceptionForLastCmdResult;
end;
Result := AResponse;
end;
procedure TIdTCPConnection.WorkBeginEvent(ASender: TObject; AWorkMode: TWorkMode;
AWorkCountMax: Int64);
begin
BeginWork(AWorkMode, AWorkCountMax)
end;
procedure TIdTCPConnection.WorkEndEvent(ASender: TObject; AWorkMode: TWorkMode);
begin
EndWork(AWorkMode)
end;
procedure TIdTCPConnection.WorkEvent(ASender: TObject; AWorkMode: TWorkMode;
AWorkCount: Int64);
begin
DoWork(AWorkMode, AWorkCount)
end;
procedure TIdTCPConnection.InitComponent;
begin
inherited InitComponent;
FReplyClass := GetReplyClass;
FGreeting := FReplyClass.CreateWithReplyTexts(nil, nil);
FLastCmdResult := FReplyClass.CreateWithReplyTexts(nil, nil);
end;
procedure TIdTCPConnection.CheckConnected;
begin
if not Assigned(IOHandler) then begin
EIdNotConnected.Toss(RSNotConnected);
end;
end;
procedure TIdTCPConnection.SetGreeting(AValue: TIdReply);
begin
FGreeting.Assign(AValue);
end;
procedure TIdTCPConnection.Disconnect;
begin
// The default should be to tell the other side we are disconnecting
Disconnect(True);
end;
procedure TIdTCPConnection.DisconnectNotifyPeer;
begin
end;
procedure TIdTCPConnection.PrepareCmd(var aCmd: string);
begin
//Leave this empty here. It's for cases where we may need to
// override what is sent to a server in a transparent manner.
end;
end.
|
unit Model.FinanceiroEmpresa;
interface
uses Common.ENum, FireDAC.Comp.Client;
type
TFinanceiroEmpresa = class
private
FID: Integer;
FSequencia: Integer;
FTipoConta: String;
FBanco: String;
FAgencia: String;
FConta: String;
FOperacao: String;
FAcao: TAcao;
public
property ID: Integer read FID write FID;
property Sequencia: Integer read FSequencia write FSequencia;
property TipoConta: String read FTipoConta write FTipoConta;
property Banco: String read FBanco write FBanco;
property Agencia: String read FAgencia write FAgencia;
property Conta: String read FConta write FConta;
property Operacao: String read FOperacao write FOperacao;
property Acao: TAcao read FAcao write FAcao;
function GetID(iID: Integer): Integer;
function Localizar(aParam: array of variant): TFDQuery;
function Gravar(): Boolean;
end;
implementation
{ TFinanceiroEmpresa }
uses DAO.FinanceiroEmpresa;
function TFinanceiroEmpresa.GetID(iID: Integer): Integer;
var
financeiroDAO: TFinanceiroEmpresaDAO;
begin
try
financeiroDAO := TFinanceiroEmpresaDAO.Create;
Result := financeiroDAO.GetID(iID);
finally
financeiroDAO.Free;
end;
end;
function TFinanceiroEmpresa.Gravar: Boolean;
var
financeiroDAO : TFinanceiroEmpresaDAO;
begin
try
financeiroDAO := TFinanceiroEmpresaDAO.Create;
case FAcao of
tacIncluir: Result := financeiroDAO.Insert(Self);
tacAlterar: Result := financeiroDAO.Update(Self);
tacExcluir: Result := financeiroDAO.Delete(Self);
end;
finally
financeiroDAO.Free;
end;
end;
function TFinanceiroEmpresa.Localizar(aParam: array of variant): TFDQuery;
var
financeiroDAO: TFinanceiroEmpresaDAO;
begin
try
financeiroDAO := TFinanceiroEmpresaDAO.Create;
Result := financeiroDAO.Localizar(aParam);
finally
financeiroDAO.Free;
end;
end;
end.
|
{*******************************************************}
{ Проект: Repository }
{ Модуль: uBaseOptionsService.pas }
{ Описание: Базовая реализация IOptionsService }
{ Copyright (C) 2015 Боборыкин В.В. (bpost@yandex.ru) }
{ }
{ Распространяется по лицензии GPLv3 }
{*******************************************************}
unit uBaseOptionsService;
interface
uses
uServices;
type
TBaseOptionsService = class(TInterfacedObject, IOptionsService)
protected
function GetScopeSectionName(AScope: TOptionScope): string; virtual;
public
function ReadOption(AOptionName: String; ADefaultValue: Variant; AScope:
TOptionScope = opsDomainUser): Variant; virtual; stdcall; abstract;
procedure WriteOption(AOptionName: String; AValue: Variant; AScope:
TOptionScope = opsDomainUser); virtual; stdcall; abstract;
end;
implementation
uses
SysUtils, JclSysInfo, JclFileUtils;
{
***************************** TBaseOptionsService ******************************
}
function TBaseOptionsService.GetScopeSectionName(AScope: TOptionScope): string;
var
SecurityService: ISecurityService;
begin
Result := PathExtractFileNameNoExt(ParamStr(0));
case AScope of
opsAppUser:
begin
if Services.TryGetService(ISecurityService, SecurityService)
and SecurityService.IsLoggedIn then
Result := Result + ':' + SecurityService.CurrentAppUser.LoginName
else
Result := Result + ':NotLoggedIn';
end;
opsDomainUser:
begin
Result := Result + ':' + GetLocalComputerName + ':' + GetLocalUserName;
end;
opsComputer:
begin
Result := Result + ':' +GetLocalComputerName;
end;
opsGlobal:
Result := 'Global';
end;
end;
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.Image;
{$IFDEF FPC}
{$MODE delphi}
{$ENDIF}
interface
uses
Classes, SysUtils,
CP.Def;
type
{ TImage }
TImage = class
private
FColumns: integer;
FRows: integer;
FData: array of array of double; // a very big array of doubles :)
public
property NumRows: integer read FRows;
property NumColumns: integer read FColumns;
public
constructor Create(columns: integer; rows: integer = 0);
destructor Destroy; override;
procedure AddRow(Row: TDoubleArray);
function GetData(Row, Column: integer): double;
procedure SetData(Row, Column: integer; Value: double);
end;
implementation
{ TImage }
constructor TImage.Create(columns: integer; rows: integer = 0);
var
i: integer;
begin
FColumns := columns; // 12 columns 0...x rows (variabel);
FRows := rows;
// dim the array correctly
SetLength(FData, FRows);
if FRows > 0 then
begin
for i := 0 to FRows - 1 do
begin
SetLength(FData[i], FColumns);
end;
end;
end;
destructor TImage.Destroy;
var
i: integer;
begin
for i := 0 to FRows - 1 do
begin
SetLength(FData[i], 0);
end;
SetLength(FData, 0);
inherited;
end;
procedure TImage.AddRow(Row: TDoubleArray);
var
i: integer;
begin
// add a row and copy the values
Inc(FRows);
SetLength(FData, FRows);
SetLength(FData[FRows - 1], FColumns);
for i := 0 to FColumns - 1 do
begin
FData[FRows - 1, i] := Row[i];
end;
end;
function TImage.GetData(Row, Column: integer): double;
begin
Result := FData[Row][Column];
end;
procedure TImage.SetData(Row, Column: integer; Value: double);
begin
FData[Row][Column] := Value;
end;
end.
|
unit ssSocketConnection;
interface
uses
SysUtils, Classes, DB, DBClient, MConnect, SConnect, ExtCtrls, Messages, dialogs;
type
TssErrConnEvent = procedure(Sender: TObject; ACode: Integer) of object;
TssSocketConnection = class(TSocketConnection)
private
FDBID: integer;
FDBConnected: boolean;
FDBConnectAtOnce: boolean;
FErrCode: Integer;
FLastTrError: String;
FOnAfterDBConnect: TNotifyEvent;
FOnConnErr: TssErrConnEvent;
FOnLossConnect: TNotifyEvent;
FServerAddr: Integer;
FSelfName: string;
FSelfIP: string;
FTimer: TTimer;
FTransactionsCount: Integer;
function GetHost: string;
procedure SetDBID(const Value: integer);
procedure SetDBConnected(const Value: boolean);
procedure SetDBConnectAtOnce(const Value: boolean);
procedure Check(Sender: TObject);
procedure SetHost(Value: string); // it is a good idea on host change to disconnect old connection automatically
protected
procedure DoConnect; override;
procedure DoDBConnect; virtual;
procedure DoDBDisconnect; virtual;
procedure DoDisconnect; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function inTransaction: Boolean;
function Login(AUser, APass: WideString; DBID, SMode: Integer): Integer; //mimick app server checklogin func.
function TrCommit: Boolean;
procedure TrStart;
procedure TrRollBack;
property ServerAddr: Integer read FServerAddr;
property ErrCode: Integer read FErrCode write FErrCode;
property LastTrError: String read FLastTrError;
published
property DBID: integer read FDBID write SetDBID;
property DBConnected: boolean read FDBConnected write SetDBConnected;
property DBConnectAtOnce: boolean read FDBConnectAtOnce write SetDBConnectAtOnce;
property Host: string read GetHost write SetHost;
property SelfIP: string read FSelfIP;
property SelfName: string read FSelfName;
property OnConnectionError: TssErrConnEvent read FOnConnErr write FOnConnErr;
property OnLossConnect: TNotifyEvent read FOnLossConnect write FOnLossConnect;
property OnAfterDBConnect: TNotifyEvent read FOnAfterDBConnect write FOnAfterDBConnect;
end;
//==============================================================================================
//==============================================================================================
//==============================================================================================
implementation
uses
Winsock;
const
CheckInterval = 5000; //ms
//==============================================================================================
procedure TssSocketConnection.Check(Sender: TObject);
begin
if Connected then
try
AppServer.Clnt_Check;
except
FTimer.Enabled := False;
Connected := False;
if Assigned(FOnLossConnect) then FOnLossConnect(Self)
end;
end;
//==============================================================================================
constructor TssSocketConnection.Create(AOwner: TComponent);
var
WSAData: TWSAData;
p: PHostEnt;
Name: array[0..$ff] of AnsiChar;
begin
inherited;
FDBID := -1;
FDBConnected := False;
inherited Host := 'localhost';
FTransactionsCount := 0;
FDBConnectAtOnce := True;
FTimer := TTimer.Create(Self);
FTimer.Interval := CheckInterval;
FTimer.OnTimer := Check;
FTimer.Enabled := False;
if WSAStartup($0101, WSAData) = 0 then begin
GetHostName(PAnsiChar(@Name), $FF);
p := GetHostByName(PAnsiChar(@Name));
FSelfName := p.h_name;
FSelfIP := inet_ntoa(PInAddr(p.h_addr_list^)^);
WSACleanup;
end;
end;
//==============================================================================================
destructor TssSocketConnection.Destroy;
begin
FTimer.Free;
inherited;
end;
//==============================================================================================
procedure TssSocketConnection.DoConnect;
{var
FIntf: IDispatch;
FAppServer: IssSrvDisp;
}
begin
if Connected then Exit;
inherited;
FTimer.Enabled := True;
//FAppServer:=Self.GetServer as IssSrvDisp;
//FServerAddr:=FAppServer.SetClientInfo(ip, h, FIntf);
if FDBConnectAtOnce then DBConnected := True;
end;
//==============================================================================================
procedure TssSocketConnection.DoDisconnect;
begin
DBConnected := False;
ErrCode := 0;
FTimer.Enabled := False;
inherited;
end;
//==============================================================================================
procedure TssSocketConnection.DoDBConnect;
var
oldCAO: boolean;
errMsg: String;
begin
if FDBConnected then Exit;
try
errMsg := '';
oldCAO := FDBConnectAtOnce;
FDBConnectAtOnce := False;
DoConnect;
FDBConnectAtOnce := oldCAO;
FErrCode := AppServer.Connect(FDBID);
except
on e: Exception do begin
FErrCode := -99;
errMsg := e.Message;
end;
end;
FDBConnected := (FErrCode = 0);
if not FDBConnected then begin
if Assigned(FOnConnErr)
then FOnConnErr(Self, FErrCode)
else begin
if FErrCode = -10
then raise Exception.Create('Too many users connected!')
else raise Exception.Create('Database connection error: ' + errMsg + '. code ' + IntToStr(FErrCode));
end;
end
else if Assigned(FOnAfterDBConnect) then FOnAfterDBConnect(Self);
end;
//==============================================================================================
procedure TssSocketConnection.DoDBDisconnect;
begin
try
if FDBConnected then AppServer.Disconnect;
except
end;
FDBConnected := False;
end;
//==============================================================================================
procedure TssSocketConnection.SetDBConnected(const Value: boolean);
begin
if FDBConnected = Value then Exit;
if Value
then DoDBConnect
else DoDBDisconnect;
end;
//==============================================================================================
procedure TssSocketConnection.SetDBConnectAtOnce(const Value: boolean);
begin
FDBConnectAtOnce := Value;
end;
//==============================================================================================
procedure TssSocketConnection.SetDBID(const Value: integer);
begin
if FDBID = Value then Exit;
if FDBConnected then DoDBDisconnect;
FDBID := Value;
end;
//==============================================================================================
procedure TssSocketConnection.SetHost(Value: string);
begin
if 0 = AnsiCompareText(inherited Host, Value) then Exit;
DoDisconnect;
sleep(1000);
inherited Host := Value;
end;
//==============================================================================================
function TssSocketConnection.GetHost: string;
begin
Result := inherited Host;
end;
//==============================================================================================
function TssSocketConnection.Login(AUser, APass: WideString; DBID, SMode: Integer): Integer; //mimick app server checklogin func.
begin
try
if not Connected then Exception.Create('not connected on TssSocketConnection.login');
Result := Self.AppServer.CheckLogin(AUser, APass, DBID, SMode);
if Result = 0 then begin
FDBconnected := True;
FDBID := DBID;
end;
except
Result := -89;
FErrCode := -89;
setDBID(0);
end;
end;
//==============================================================================================
// Transactions helpers.
// for now we compress multiple transactions into one
function TssSocketConnection.inTransaction: Boolean;
begin
Result := (FTransactionsCount > 0);
end;
//==============================================================================================
procedure TssSocketConnection.TrStart;
begin
inc(FTransactionsCount);
if FTransactionsCount > 1 then Exit;
Self.AppServer.Start;
FLastTrError := '';
end;
//==============================================================================================
procedure TssSocketConnection.TrRollBack;
begin
if FTransactionsCount = 0 then Exit;
FTransactionsCount := 0;
Self.AppServer.Rollback;
end;
//==============================================================================================
function TssSocketConnection.TrCommit: Boolean;
begin
if FTransactionsCount = 0 then begin
FLastTrError := Self.Name + ': TrCommit W/O transaction';
Result := False;
Exit;
end;
dec(FTransactionsCount);
if FTransactionsCount > 1 then begin
Result := True;
Exit;
end;
Self.AppServer.Commit;
FLastTrError := Self.AppServer.stat_lastTrErrors;
Result := (FLastTrError = '');
end;
end.
|
{$include lem_directives.inc}
unit GameConfigScreen;
interface
uses
Windows, Classes, SysUtils, Controls,
StrUtils, Dialogs,
UMisc,
Gr32, Gr32_Image, Gr32_Layers,
LemCore,
LemTypes,
LemStrings,
LemLevelSystem,
LemGame,
GameControl,
{$ifdef flexi}LemDosStructures,{$endif}
LemDosStyle,
GameBaseScreen;
// LemCore, LemGame, LemDosFiles, LemDosStyles, LemControls,
//LemDosScreen;
const
MAX_GIM_SETTING = 23;
{-------------------------------------------------------------------------------
The dos postview screen, which shows you how you've done it.
-------------------------------------------------------------------------------}
type
TGameConfigScreen = class(TGameBaseScreen)
private
fLookForLVLOption: Boolean;
fExtraModeOption: Boolean;
fCustOptions: Boolean;
fTestModeOptions: Boolean;
fScreenNumber: Integer;
fGimmickSetting: Integer;
fSkillsetSetting: Integer;
fDoneFirstBuild: Boolean;
function GetScreenText: string;
procedure Form_KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure Form_KeyPress(Sender: TObject; var Key: Char);
{procedure SetScreenNumber(aValue: Integer);}
protected
procedure PrepareGameParams(Params: TDosGameParams); override;
procedure BuildScreen; override;
procedure CloseScreen(aNextScreen: TGameScreenType); override;
public
constructor Create(aOwner: TComponent); override;
destructor Destroy; override;
property ScreenNumber: Integer read fScreenNumber write fScreenNumber; //SetScreenNumber;
published
end;
implementation
uses Forms, LemStyle;
{ TDosGameConfig }
{procedure TGameConfigScreen.SetScreenNumber(aValue: Integer);
begin
if aValue <> 1 then aValue := 0;
if not (fCustOptions or fExtraModeOption) then aValue := 0;
fScreenNumber := aValue;
end;}
procedure TGameConfigScreen.CloseScreen(aNextScreen: TGameScreenType);
begin
inherited CloseScreen(aNextScreen);
end;
procedure TGameConfigScreen.PrepareGameParams(Params: TDosGameParams);
begin
inherited;
// First, set the options to the standard values
fLookForLVLOption := {$ifdef nolookforlvls}false{$else}true{$endif};
fExtraModeOption := {$ifdef noextramodes}false{$else}true{$endif};
fCustOptions := {$ifdef cust}true{$else}false{$endif};
fTestModeOptions := {$ifdef testmode}true{$else}false{$endif};
//Next, adjust for Flexi option on LookForLVLs and ExtraModes
{$ifdef flexi}
if GameParams.SysDat.Options and 1 = 0 then fLookForLVLOption := false;
if GameParams.SysDat.Options and 32 = 0 then fExtraModeOption := false;
{$endif}
end;
procedure TGameConfigScreen.BuildScreen;
var
Temp: TBitmap32;
// DstRect: TRect;
begin
//fSection := aSection;
//fLevelNumber := aLevelNumber;
//fGameResult := aResult;
ScreenImg.BeginUpdate;
Temp := TBitmap32.Create;
try
InitializeImageSizeAndPosition(640, 350);
if not fDoneFirstBuild then
begin
ExtractBackGround;
ExtractPurpleFont;
fDoneFirstBuild := true;
end;
Temp.SetSize(640, 350);
Temp.Clear(0);
TileBackgroundBitmap(0, 0, Temp);
DrawPurpleTextCentered(Temp, GetScreenText, 16);
ScreenImg.Bitmap.Assign(Temp);
finally
ScreenImg.EndUpdate;
Temp.Free;
end;
end;
constructor TGameConfigScreen.Create(aOwner: TComponent);
begin
inherited Create(aOwner);
Stretched := True;
OnKeyDown := Form_KeyDown;
OnKeyPress := Form_KeyPress;
end;
destructor TGameConfigScreen.Destroy;
begin
inherited Destroy;
end;
function TGameConfigScreen.GetScreenText: string;
var
i: Integer;
STarget: string;
SDone: string;
SScore: string;
H: string;
lfcount : integer;
fEnabled : Boolean;
fExtVal : LongWord;
procedure Add(const S: string);
begin
Result := Result + S + #13;
Inc(lfcount);
end;
procedure LF(aCount: Integer);
begin
Result := Result + StringOfChar(#13, aCount);
Inc(lfcount, aCount);
end;
function OnOffText(aVal: Boolean): String;
begin
if aVal then
Result := ' ON'
else
Result := 'OFF';
end;
procedure LPAdd(S: string; State: Boolean);
begin
while length(S) < 28 do
S := S + ' ';
S := S + ': ';
Add(S + OnOffText(State));
end;
function PercentOptionText(aVal: Integer): String;
begin
case aVal of
0: Result := 'OFF';
1: Result := ' ON';
2: Result := 'ADJ';
end;
end;
function OnOffAltText(Op1, Op2: Boolean): String;
begin
if Op1 = false then
Result := 'OFF'
else begin
if Op2 = false then
Result := ' ON'
else
Result := 'ALT';
end;
end;
function TestModeText(aVal: Integer): String;
begin
case aVal of
0: Result := ' Pre/Postview';
1: Result := ' No Preview';
2: Result := 'Gameplay Only';
3: Result := 'Game+AutoSave';
end;
end;
function SteelModeText(aVal: Integer): String;
begin
case aVal of
0: Result := ' No Override';
1: Result := ' Autosteel';
2: Result := 'Simple A.Steel';
end;
end;
function MechText(aVal: Integer): String;
begin
case aVal of
0: Result := 'Cust';
1: Result := 'Orig';
2: Result := 'OhNo';
end;
end;
function GimmickName(aVal: Integer): String;
begin
case aVal of
0: Result := 'Superlemming';
1: Result := 'Frenzy';
2: Result := 'Reverse Skill Count';
3: Result := 'Karoshi';
4: Result := 'Unalterable Terrain';
5: Result := 'Skill Count Overflow';
6: Result := 'No Gravity';
7: Result := 'Hardworkers';
8: Result := 'Backwards Walkers';
9: Result := 'Lazy Lemmings';
10: Result := 'Exhaustion';
11: Result := 'Non-Fatal Bombers';
12: Result := 'Invincibility';
13: Result := 'One Skill Per Lemming';
14: Result := 'Steel Inversion';
15: Result := 'Solid Level Bottom';
16: Result := 'Single-Use Permanents';
17: Result := 'Disobedience';
18: Result := 'Nuclear Bombers';
19: Result := 'Turnaround On Assign';
20: Result := 'Countdown Other Skills';
21: Result := 'Assign To All';
22: Result := 'Horizontal Wrap';
23: Result := 'Vertical Wrap';
// 1234567890123456789012345
end;
end;
function SkillsetName(aVal: Integer): String;
begin
case aVal of
0: Result := 'Walker';
1: Result := 'Climber';
2: Result := 'Swimmer';
3: Result := 'Floater';
4: Result := 'Glider';
5: Result := 'Mechanic';
6: Result := 'Bomber';
7: Result := 'Stoner';
8: Result := 'Blocker';
9: Result := 'Platformer';
10: Result := 'Builder';
11: Result := 'Stacker';
12: Result := 'Basher';
13: Result := 'Miner';
14: Result := 'Digger';
15: Result := 'Cloner';
end;
end;
function SoundOptionText(aMusic, aSound: Boolean): String;
begin
if aMusic then Result := ' ON'
else if aSound then Result := ' FX'
else Result := 'OFF';
end;
var
ts : String;
begin
Add('Lemmix Configuration');
LF(2);
Add('1) Show Particles: ' + OnOffText(GameParams.ShowParticles));
Add('2) Lemmix Trap Bug: ' + OnOffText(GameParams.LemmixTrapBug));
Add('3) State Control: ' + OnOffText(GameParams.StateControlEnabled));
Add('4) Assign While Paused: ' + OnOffText(GameParams.PauseAssignEnabled));
if fLookForLVLOption then
Add('5) Look For LVL Files: ' + OnOffText(GameParams.LookForLVLFiles));
if fCustOptions then
begin
{$ifdef cust}{$ifndef flexi}
Add('6) Mechanics: ' + MechText(GameParams.Mechanics));
ts := GameParams.LevelPack;
while (Length(ts) < 18) do
ts := ' ' + ts;
if (Length(ts) > 18) then
ts := LeftStr(ts, 15) + '...';
Add('Q) Level Pack: ' + ts);
ts := GameParams.fExternalPrefix;
if ts = '' then ts := '(none)';
while (Length(ts) < 18) do
ts := ' ' + ts;
if (Length(ts) > 18) then
ts := LeftStr(ts, 15) + '...';
Add('W) Prefix: ' + ts);
{$endif} {$endif}
end;
{$ifdef testmode}
if fTestModeOptions then
Add('E) Test Mode Style: ' + TestModeText(GameParams.QuickTestMode));
{$endif}
LF(19-lfcount);
Add('Press Esc to return to main menu');
end;
procedure TGameConfigScreen.Form_KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
case Key of
VK_ESCAPE: CloseScreen(gstMenu);
VK_RETURN: CloseScreen(gstMenu);
end;
end;
procedure TGameConfigScreen.Form_KeyPress(Sender: TObject; var Key: Char);
var
lChar : Char;
procedure SwitchOption(aOpt: Integer);
var
tNum : LongWord;
i: Integer;
fDialog: TOpenDialog;
ts, ts2: String;
begin
with GameParams do
case aOpt of
1: ShowParticles := not ShowParticles;
2: begin
LookForLVLFiles := not LookForLVLFiles;
TBaseDosLevelSystem(Style.LevelSystem).LookForLVL := LookForLVLFiles;
end;
{$ifdef testmode}
3: begin
QuickTestMode := QuickTestMode + 1;
if QuickTestMode > 3 then QuickTestMode := 0;
end;
{$endif}
{$ifdef cust}{$ifndef flexi}
4: begin
fDialog := tOpenDialog.Create(self);
fDialog.Title := 'Select level pack';
fDialog.Filter := 'DAT files|*.dat';
fDialog.Options := [ofFileMustExist];
if fDialog.Execute then
begin
ts := fDialog.FileName;
ts := ExtractFileName(ts);
GameParams.LevelPack := ts;
TDosCustLevelSystem(GameParams.Style.LevelSystem).LevelPack := ts;
end;
end;
5: begin
if fExternalPrefix = '' then
MessageDlg('Choose any GROUNDxO.DAT, VGAGRx.DAT, VGASPECx.DAT' + #13 +
'or MAIN.DAT file with the desired prefix.', mtcustom, [mbok], 0)
else begin
i := MessageDlg('Do you want to choose a new prefix? If you choose' + #13 +
'No, the prefix will be cleared.', mtcustom, [mbYes, mbNo], 0);
if i = mrNo then
begin
fExternalPrefix := '';
BuildScreen;
Exit;
end;
end;
fDialog := tOpenDialog.Create(self);
fDialog.Title := 'Select a prefixed file';
fDialog.Filter := 'DAT files|*.dat';
fDialog.Options := [ofFileMustExist];
if fDialog.Execute then
begin
ts := fDialog.FileName;
ts := ExtractFileName(ts);
ts2 := '';
for i := 1 to Length(ts) do
begin
if ts[i] = '_' then break;
ts2 := ts2 + ts[i];
end;
if i >= Length(ts) then
begin
MessageDlg('This does not appear to be a prefixed file.', mtCustom, [mbok], 0);
Exit;
end;
GameParams.fExternalPrefix := ts2;
end;
end;
6: begin
Mechanics := Mechanics + 1;
if Mechanics > 2 then Mechanics := 0;
end;
{$endif}{$endif}
7: begin
LemmixTrapBug := not LemmixTrapBug;
end;
8: begin
StateControlEnabled := not StateControlEnabled;
end;
9: begin
PauseAssignEnabled := not PauseAssignEnabled;
end;
end;
BuildScreen;
end;
begin
lChar := UpperCase(Key)[1];
case lChar of
'1' : SwitchOption(1);
'2' : SwitchOption(7);
'3' : SwitchOption(8);
'4' : SwitchOption(9);
'5' : if fLookForLVLOption then SwitchOption(2);
'6' : if fCustOptions then SwitchOption(6);
'Q' : if fCustOptions then SwitchOption(4);
'W' : if fCustOptions then SwitchOption(5);
'E' : if fTestModeOptions then SwitchOption(3);
end;
end;
end.
|
unit TextModifierFunctions;
{$MODE objfpc}{$J-}{$H+}
interface
function StrUp(text: string): string;
function Wiggle(text: string): string;
implementation
function StrUp(text: string): string;
begin
result := Upcase(text);
end;
function Wiggle(text: string): string;
var
state: boolean = true; (* true = upcase *)
c: char;
output: string = '';
begin
for c in text do
begin
if state then
begin
output := output + upcase(c);
end
else
begin
output := output + lowercase(c);
end;
state := not state;
end;
result := output;
end;
begin
end.
|
{******************************************************************************}
{ }
{ Library: Fundamentals TLS }
{ File name: flcTLSSessionID.pas }
{ File version: 5.02 }
{ Description: TLS Session ID }
{ }
{ Copyright: Copyright (c) 2008-2020, 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. }
{ }
{ Github: https://github.com/fundamentalslib }
{ E-mail: fundamentals.library at gmail.com }
{ }
{ Revision history: }
{ }
{ 2008/01/18 0.01 Initial development. }
{ 2020/05/09 5.02 Create flcTLSSessionID unit from flcTLSUtils unit. }
{ }
{******************************************************************************}
{$INCLUDE flcTLS.inc}
unit flcTLSSessionID;
interface
uses
flcStdTypes;
{ }
{ SessionID }
{ }
const
TLSSessionIDMaxLen = 32;
type
TTLSSessionID = record
Len : Byte;
Data : array[0..TLSSessionIDMaxLen - 1] of Byte;
end;
procedure InitTLSSessionID(var SessionID: TTLSSessionID; const A: RawByteString);
function EncodeTLSSessionID(var Buffer; const Size: Integer; const SessionID: TTLSSessionID): Integer;
function DecodeTLSSessionID(const Buffer; const Size: Integer; var SessionID: TTLSSessionID): Integer;
implementation
uses
{ TLS }
flcTLSErrors;
{ }
{ SessionID }
{ length : Byte; }
{ SessionID : <0..32>; }
{ }
procedure InitTLSSessionID(var SessionID: TTLSSessionID; const A: RawByteString);
var
L : Integer;
begin
L := Length(A);
if L > TLSSessionIDMaxLen then
raise ETLSError.Create(TLSError_InvalidParameter, 'Invalid SessionID length');
SessionID.Len := Byte(L);
FillChar(SessionID.Data[0], TLSSessionIDMaxLen, 0);
if L > 0 then
Move(A[1], SessionID.Data[0], L);
end;
function EncodeTLSSessionID(var Buffer; const Size: Integer; const SessionID: TTLSSessionID): Integer;
var L : Byte;
N : Integer;
P : PByte;
begin
L := SessionID.Len;
N := L + 1;
if Size < N then
raise ETLSError.CreateAlertBufferEncode;
P := @Buffer;
P^ := L;
Inc(P);
if L > 0 then
Move(SessionID.Data[0], P^, L);
Result := N;
end;
function DecodeTLSSessionID(const Buffer; const Size: Integer; var SessionID: TTLSSessionID): Integer;
var L : Byte;
P : PByte;
begin
if Size < 1 then
raise ETLSError.CreateAlertBufferDecode;
P := @Buffer;
L := P^;
if L = 0 then
begin
SessionID.Len := 0;
Result := 1;
end
else
begin
if Size < 1 + L then
raise ETLSError.CreateAlertBufferDecode;
if L > TLSSessionIDMaxLen then
raise ETLSError.CreateAlertBufferDecode; // invalid length
SessionID.Len := L;
Inc(P);
Move(P^, SessionID.Data[0], L);
Result := 1 + L;
end;
end;
end.
|
{
$Project$
$Workfile$
$Revision$
$DateUTC$
$Id$
This file is part of the Indy (Internet Direct) project, and is offered
under the dual-licensing agreement described on the Indy website.
(http://www.indyproject.org/)
Copyright:
(c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved.
}
{
$Log$
}
{
Rev 1.7 14/06/2004 21:38:42 CCostelloe
Converted StringToTIn4Addr call
Rev 1.6 09/06/2004 10:00:50 CCostelloe
Kylix 3 patch
Rev 1.5 2004.02.03 5:43:52 PM czhower
Name changes
Rev 1.4 1/21/2004 3:11:10 PM JPMugaas
InitComponent
Rev 1.3 10/26/2003 09:11:54 AM JPMugaas
Should now work in NET.
Rev 1.2 2003.10.24 10:38:28 AM czhower
UDP Server todos
Rev 1.1 2003.10.12 4:03:58 PM czhower
compile todos
Rev 1.0 11/13/2002 07:55:26 AM JPMugaas
2001-10-16 DSiders
Modified TIdIPMCastServer.MulticastBuffer to
validate the AHost argument to the method instead
of the MulticastGroup property.
}
unit IdIPMCastServer;
{
Dr. Harley J. Mackenzie, Initial revision.
}
interface
{$I IdCompilerDefines.inc}
//Put FPC into Delphi mode
uses
IdComponent,
IdGlobal,
IdIPMCastBase,
IdSocketHandle;
const
DEF_IMP_LOOPBACK = True;
DEF_IMP_TTL = 1;
type
TIdIPMCastServer = class(TIdIPMCastBase)
protected
FBinding: TIdSocketHandle;
FBoundIP: String;
FBoundPort: TIdPort;
FLoopback: Boolean;
FTimeToLive: Byte;
//
procedure ApplyLoopback;
procedure ApplyTimeToLive;
procedure CloseBinding; override;
function GetActive: Boolean; override;
function GetBinding: TIdSocketHandle; override;
procedure Loaded; override;
procedure MulticastBuffer(const AHost: string; const APort: Integer; const ABuffer : TIdBytes);
procedure SetLoopback(const AValue: Boolean); virtual;
procedure SetTTL(const AValue: Byte); virtual;
procedure InitComponent; override;
public
procedure Send(const AData: string; AByteEncoding: TIdTextEncoding = nil
{$IFDEF STRING_IS_ANSI}; ASrcEncoding: TIdTextEncoding = nil{$ENDIF}
); overload;
procedure Send(const ABuffer : TIdBytes); overload;
destructor Destroy; override;
//
property Binding: TIdSocketHandle read GetBinding;
published
property Active;
property BoundIP: String read FBoundIP write FBoundIP;
property BoundPort: TIdPort read FBoundPort write FBoundPort;
property Loopback: Boolean read FLoopback write SetLoopback default DEF_IMP_LOOPBACK;
property MulticastGroup;
property IPVersion;
property Port;
property ReuseSocket;
property TimeToLive: Byte read FTimeToLive write SetTTL default DEF_IMP_TTL;
end;
implementation
{ TIdIPMCastServer }
uses
IdResourceStringsCore,
IdStack,
IdStackConsts,
SysUtils;
procedure TIdIPMCastServer.InitComponent;
begin
inherited InitComponent;
FLoopback := DEF_IMP_LOOPBACK;
FTimeToLive := DEF_IMP_TTL;
end;
procedure TIdIPMCastServer.Loaded;
var
b: Boolean;
begin
inherited Loaded;
b := FDsgnActive;
FDsgnActive := False;
Active := b;
end;
destructor TIdIPMCastServer.Destroy;
begin
Active := False;
inherited Destroy;
end;
procedure TIdIPMCastServer.CloseBinding;
begin
FreeAndNil(FBinding);
end;
function TIdIPMCastServer.GetActive: Boolean;
begin
Result := (inherited GetActive) or (Assigned(FBinding) and FBinding.HandleAllocated);
end;
function TIdIPMCastServer.GetBinding: TIdSocketHandle;
begin
if not Assigned(FBinding) then begin
FBinding := TIdSocketHandle.Create(nil);
end;
if not FBinding.HandleAllocated then begin
FBinding.IPVersion := FIPVersion;
{$IFDEF LINUX}
FBinding.AllocateSocket(LongInt(Id_SOCK_DGRAM));
{$ELSE}
FBinding.AllocateSocket(Id_SOCK_DGRAM);
{$ENDIF}
FBinding.IP := FBoundIP;
FBinding.Port := FBoundPort;
FBinding.ReuseSocket := FReuseSocket;
FBinding.Bind;
ApplyTimeToLive;
ApplyLoopback;
end;
Result := FBinding;
end;
procedure TIdIPMCastServer.MulticastBuffer(const AHost: string; const APort: Integer; const ABuffer : TIdBytes);
begin
// DS - if not IsValidMulticastGroup(FMulticastGroup) then
if not IsValidMulticastGroup(AHost) then begin
EIdMCastNotValidAddress.Toss(RSIPMCastInvalidMulticastAddress);
end;
Binding.SendTo(AHost, APort, ABuffer, Binding.IPVersion);
end;
procedure TIdIPMCastServer.Send(const AData: string; AByteEncoding: TIdTextEncoding = nil
{$IFDEF STRING_IS_ANSI}; ASrcEncoding: TIdTextEncoding = nil{$ENDIF}
);
begin
MulticastBuffer(FMulticastGroup, FPort, ToBytes(AData, AByteEncoding{$IFDEF STRING_IS_ANSI}, ASrcEncoding{$ENDIF}));
end;
procedure TIdIPMCastServer.Send(const ABuffer : TIdBytes);
begin
MulticastBuffer(FMulticastGroup, FPort, ABuffer);
end;
procedure TIdIPMCastServer.SetLoopback(const AValue: Boolean);
begin
if FLoopback <> AValue then begin
FLoopback := AValue;
ApplyLoopback;
end;
end;
procedure TIdIPMCastServer.SetTTL(const AValue: Byte);
begin
if FTimeToLive <> AValue then begin
FTimeToLive := AValue;
ApplyTimeToLive;
end;
end;
procedure TIdIPMCastServer.ApplyLoopback;
begin
if Assigned(FBinding) and FBinding.HandleAllocated then begin
FBinding.SetLoopBack(FLoopback);
end;
end;
procedure TIdIPMCastServer.ApplyTimeToLive;
begin
if Assigned(FBinding) and FBinding.HandleAllocated then begin
FBinding.SetMulticastTTL(FTimeToLive);
end;
end;
end.
|
{******************************************************************************}
{ }
{ Library: Fundamentals TLS }
{ File name: flcTLSKeyExchangeParams.pas }
{ File version: 5.04 }
{ Description: TLS Key Exchange Parameters }
{ }
{ Copyright: Copyright (c) 2008-2020, 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. }
{ }
{ Github: https://github.com/fundamentalslib }
{ E-mail: fundamentals.library at gmail.com }
{ }
{ References: }
{ }
{ RFC 4492 - Elliptic Curve Cryptography (ECC) Cipher Suites for }
{ Transport Layer Security (TLS) }
{ https://tools.ietf.org/html/rfc4492 }
{ }
{ RFC 8422 - Elliptic Curve Cryptography (ECC) Cipher Suites for }
{ Transport Layer Security (TLS) Versions 1.2 and Earlier }
{ https://tools.ietf.org/html/rfc8422 }
{ }
{ https://ldapwiki.com/wiki/Key-Exchange }
{ https://crypto.stackexchange.com/questions/26354/whats-the-structure-of-server-key-exchange-message-during-tls-handshake }
{ https://security.stackexchange.com/questions/8343/what-key-exchange-mechanism-should-be-used-in-tls }
{ }
{ Revision history: }
{ }
{ 2008/01/18 0.01 Initial development. }
{ 2020/05/09 5.02 Create flcTLSKeyExchangeParams unit from }
{ flcTLSUtils unit. }
{ 2020/05/11 5.03 TLSDigitallySigned, SignTLSServerKeyExchangeDH_RSA. }
{ 2020/05/19 5.04 Sign/Verify RSA authentication signature for DHE_RSA. }
{ }
{******************************************************************************}
{$INCLUDE flcTLS.inc}
unit flcTLSKeyExchangeParams;
interface
uses
{ System }
SysUtils,
{ Utils }
flcStdTypes,
{ Cipher }
flcCipherRSA,
{ TLS }
flcTLSAlgorithmTypes;
{ }
{ ServerDHParams }
{ Ephemeral DH parameters }
{ }
type
TTLSServerDHParams = record
dh_p : RawByteString;
dh_g : RawByteString;
dh_Ys : RawByteString;
end;
procedure AssignTLSServerDHParams(var ServerDHParams: TTLSServerDHParams;
const p, g, Ys: RawByteString);
function EncodeTLSServerDHParams(
var Buffer; const Size: Integer;
const ServerDHParams: TTLSServerDHParams): Integer;
function DecodeTLSServerDHParams(
const Buffer; const Size: Integer;
var ServerDHParams: TTLSServerDHParams): Integer;
{ }
{ ServerRSAParams }
{ }
type
TTLSServerRSAParams = record
rsa_modulus : RawByteString;
rsa_exponent : RawByteString;
end;
procedure AssignTLSServerRSAParams(var ServerRSAParams: TTLSServerRSAParams;
const modulus, exponent: RawByteString);
function EncodeTLSServerRSAParams(
var Buffer; const Size: Integer;
const ServerRSAParams: TTLSServerRSAParams): Integer;
function DecodeTLSServerRSAParams(
const Buffer; const Size: Integer;
var ServerRSAParams: TTLSServerRSAParams): Integer;
{ }
{ ServerECDHParams }
{ }
{ }
{ ServerParamsHashBuf }
{ }
type
TTLSClientServerRandom = array[0..31] of Byte;
PTLSClientServerRandom = ^TTLSClientServerRandom;
function EncodeTLSServerDHParamsHashBuf(
var Buffer; const Size: Integer;
const client_random: TTLSClientServerRandom;
const server_random: TTLSClientServerRandom;
const Params: TTLSServerDHParams): Integer;
{ }
{ SignedStruct }
{ }
type
TTLSRSASignedStruct = packed record
md5_hash : array[0..15] of Byte;
sha_hash : array[0..19] of Byte;
end;
TTLSDSASignedStruct = packed record
sha_hash : array[0..19] of Byte;
end;
{ }
{ DigitallySigned }
{ }
{ SignatureAndHashAlgorithm algorithm; }
{ opaque signature<0..2^16-1>; }
{ }
type
TTLSDigitallySigned = record
Algorithm : TTLSSignatureAndHashAlgorithm;
Signature : RawByteString;
end;
function EncodeTLSDigitallySigned(
var Buffer; const Size: Integer;
const Signed: TTLSDigitallySigned): Integer;
function DecodeTLSDigitallySigned(
const Buffer; const Size: Integer;
var Signed: TTLSDigitallySigned): Integer;
{ }
{ ServerKeyExchange }
{ }
type
TTLSServerKeyExchange = record
DHParams : TTLSServerDHParams;
RSAParams : TTLSServerRSAParams;
SignedParams : TTLSDigitallySigned;
end;
procedure InitTLSServerKeyExchange(var ServerKeyExchange: TTLSServerKeyExchange);
procedure AssignTLSServerKeyExchangeDHParams(
var ServerKeyExchange: TTLSServerKeyExchange;
const p, g, Ys: RawByteString);
function EncodeTLSServerKeyExchange(
var Buffer; const Size: Integer;
const KeyExchangeAlgorithm: TTLSKeyExchangeAlgorithm;
const ServerKeyExchange: TTLSServerKeyExchange): Integer;
function DecodeTLSServerKeyExchange(
const Buffer; const Size: Integer;
const KeyExchangeAlgorithm: TTLSKeyExchangeAlgorithm;
var ServerKeyExchange: TTLSServerKeyExchange): Integer;
procedure SignTLSServerKeyExchangeDH_RSA(
var ServerKeyExchange: TTLSServerKeyExchange;
const client_random : TTLSClientServerRandom;
const server_random : TTLSClientServerRandom;
const RSAPrivateKey: TRSAPrivateKey);
function VerifyTLSServerKeyExchangeDH_RSA(
const ServerKeyExchange: TTLSServerKeyExchange;
const client_random : TTLSClientServerRandom;
const server_random : TTLSClientServerRandom;
const RSAPublicKey: TRSAPublicKey): Boolean;
{ }
{ ClientDiffieHellmanPublic }
{ }
type
TTLSClientDiffieHellmanPublic = record
PublicValueEncodingExplicit : Boolean;
dh_Yc : RawByteString;
end;
function EncodeTLSClientDiffieHellmanPublic(
var Buffer; const Size: Integer;
const ClientDiffieHellmanPublic: TTLSClientDiffieHellmanPublic): Integer;
function DecodeTLSClientDiffieHellmanPublic(
const Buffer; const Size: Integer;
const PublicValueEncodingExplicit: Boolean;
var ClientDiffieHellmanPublic: TTLSClientDiffieHellmanPublic): Integer;
{ }
{ ClientKeyExchange }
{ }
type
TTLSClientKeyExchange = record
EncryptedPreMasterSecret : RawByteString;
ClientDiffieHellmanPublic : TTLSClientDiffieHellmanPublic;
end;
function EncodeTLSClientKeyExchange(
var Buffer; const Size: Integer;
const KeyExchangeAlgorithm: TTLSKeyExchangeAlgorithm;
const ClientKeyExchange: TTLSClientKeyExchange): Integer;
function DecodeTLSClientKeyExchange(
const Buffer; const Size: Integer;
const KeyExchangeAlgorithm: TTLSKeyExchangeAlgorithm;
const PublicValueEncodingExplicit: Boolean;
var ClientKeyExchange: TTLSClientKeyExchange): Integer;
implementation
uses
{ Utils }
flcHugeInt,
{ Crypto }
flcCryptoHash,
{ TLS }
flcTLSAlert,
flcTLSErrors,
flcTLSOpaqueEncoding;
{ }
{ ServerDHParams }
{ Ephemeral DH parameters }
{ }
{ struct }
{ dh_p : opaque <1..2^16-1>; }
{ dh_g : opaque <1..2^16-1>; }
{ dh_Ys : opaque <1..2^16-1>; }
{ }
procedure AssignTLSServerDHParams(var ServerDHParams: TTLSServerDHParams;
const p, g, Ys: RawByteString);
begin
ServerDHParams.dh_p := p;
ServerDHParams.dh_g := g;
ServerDHParams.dh_Ys := Ys;
end;
function EncodeTLSServerDHParams(
var Buffer; const Size: Integer;
const ServerDHParams: TTLSServerDHParams): Integer;
var P : PByte;
N, L : Integer;
begin
Assert(Size >= 0);
if (ServerDHParams.dh_p = '') or
(ServerDHParams.dh_g = '') or
(ServerDHParams.dh_Ys = '') then
raise ETLSError.Create(TLSError_InvalidParameter);
N := Size;
P := @Buffer;
// dh_p
L := EncodeTLSOpaque16(P^, N, ServerDHParams.dh_p);
Dec(N, L);
Inc(P, L);
// dh_g
L := EncodeTLSOpaque16(P^, N, ServerDHParams.dh_g);
Dec(N, L);
Inc(P, L);
// dh_Ys
L := EncodeTLSOpaque16(P^, N, ServerDHParams.dh_Ys);
Dec(N, L);
Result := Size - N;
end;
function DecodeTLSServerDHParams(
const Buffer; const Size: Integer;
var ServerDHParams: TTLSServerDHParams): Integer;
var P : PByte;
N, L : Integer;
begin
Assert(Size >= 0);
N := Size;
P := @Buffer;
// dh_p
L := DecodeTLSOpaque16(P^, N, ServerDHParams.dh_p);
Dec(N, L);
Inc(P, L);
// dh_g
L := DecodeTLSOpaque16(P^, N, ServerDHParams.dh_g);
Dec(N, L);
Inc(P, L);
// dh_Ys
L := DecodeTLSOpaque16(P^, N, ServerDHParams.dh_Ys);
Dec(N, L);
Result := Size - N;
end;
{ }
{ ServerRSAParams }
{ }
{ struct }
{ rsa_modulus : opaque <1..2^16-1>; }
{ rsa_exponent : opaque <1..2^16-1>; }
{ }
procedure AssignTLSServerRSAParams(var ServerRSAParams: TTLSServerRSAParams;
const modulus, exponent: RawByteString);
begin
ServerRSAParams.rsa_modulus := modulus;
ServerRSAParams.rsa_exponent := exponent;
end;
function EncodeTLSServerRSAParams(
var Buffer; const Size: Integer;
const ServerRSAParams: TTLSServerRSAParams): Integer;
var P : PByte;
N, L : Integer;
begin
Assert(Size >= 0);
if (ServerRSAParams.rsa_modulus = '') or
(ServerRSAParams.rsa_exponent = '') then
raise ETLSError.Create(TLSError_InvalidParameter);
N := Size;
P := @Buffer;
// rsa_modulus
L := EncodeTLSOpaque16(P^, N, ServerRSAParams.rsa_modulus);
Dec(N, L);
Inc(P, L);
// rsa_exponent
L := EncodeTLSOpaque16(P^, N, ServerRSAParams.rsa_exponent);
Dec(N, L);
Result := Size - N;
end;
function DecodeTLSServerRSAParams(
const Buffer; const Size: Integer;
var ServerRSAParams: TTLSServerRSAParams): Integer;
var P : PByte;
N, L : Integer;
begin
Assert(Size >= 0);
N := Size;
P := @Buffer;
// rsa_modulus
L := DecodeTLSOpaque16(P^, N, ServerRSAParams.rsa_modulus);
Dec(N, L);
Inc(P, L);
// rsa_exponent
L := DecodeTLSOpaque16(P^, N, ServerRSAParams.rsa_exponent);
Dec(N, L);
Result := Size - N;
end;
{ }
{ ECParameters }
{ }
type
TTLSECParameters = record
CurveType : TTLSECCurveType;
NamedCurve : TTLSNamedCurve;
end;
(*
ECCurveType curve_type;
select (curve_type) {
case explicit_prime:
opaque prime_p <1..2^8-1>;
ECCurve curve;
ECPoint base;
opaque order <1..2^8-1>;
opaque cofactor <1..2^8-1>;
case explicit_char2:
uint16 m;
ECBasisType basis;
select (basis) {
case ec_trinomial:
opaque k <1..2^8-1>;
case ec_pentanomial:
opaque k1 <1..2^8-1>;
opaque k2 <1..2^8-1>;
opaque k3 <1..2^8-1>;
};
ECCurve curve;
ECPoint base;
opaque order <1..2^8-1>;
opaque cofactor <1..2^8-1>;
case named_curve:
NamedCurve namedcurve;
};
}
*)
{ }
{ ECPoint }
{ }
{ opaque point <1..2^8-1>; }
{ }
type
TTLSECPoint = array of Byte;
{ }
{ ServerECDHParams }
{ }
{ ECParameters curve_params; }
{ ECPoint public; }
{ }
type
TTLSServerECDHParams = record
CurveParams : TTLSECParameters;
PublicKey : TTLSECPoint;
end;
{ }
{ ServerParamsHashBuf }
{ }
function EncodeTLSServerDHParamsHashBuf(
var Buffer; const Size: Integer;
const client_random: TTLSClientServerRandom;
const server_random: TTLSClientServerRandom;
const Params: TTLSServerDHParams): Integer;
var P : PByte;
N, L : Integer;
begin
N := Size;
P := @Buffer;
Dec(N, 64);
if N < 0 then
raise ETLSError.Create(TLSError_InvalidBuffer);
Move(client_random, P^, 32);
Inc(P, 32);
Move(server_random, P^, 32);
Inc(P, 32);
L := EncodeTLSServerDHParams(P^, N, Params);
Dec(N, L);
Result := Size - N;
end;
{ }
{ DigitallySigned }
{ }
(* struct { *)
(* SignatureAndHashAlgorithm algorithm; *)
(* opaque signature<0..2^16-1>; *)
(* } DigitallySigned; *)
{ }
function EncodeTLSDigitallySigned(
var Buffer; const Size: Integer;
const Signed: TTLSDigitallySigned): Integer;
var P : PByte;
N, L : Integer;
begin
Assert(Signed.Algorithm.Hash <> tlshaNone);
Assert(Signed.Algorithm.Signature <> tlssaAnonymous);
Assert(Length(Signed.Signature) > 0);
N := Size;
P := @Buffer;
Dec(N, 2);
if N < 0 then
raise ETLSError.CreateAlertBufferEncode;
P^ := Ord(Signed.Algorithm.Hash);
Inc(P);
P^ := Ord(Signed.Algorithm.Signature);
Inc(P);
L := EncodeTLSOpaque16(P^, N, Signed.Signature);
Dec(N, L);
Result := Size - N;
end;
function DecodeTLSDigitallySigned(
const Buffer; const Size: Integer;
var Signed: TTLSDigitallySigned): Integer;
var P : PByte;
N, L : Integer;
begin
N := Size;
P := @Buffer;
Dec(N, 2);
if N < 0 then
raise ETLSError.CreateAlertBufferDecode;
Signed.Algorithm.Hash := TTLSHashAlgorithm(P^);
Inc(P);
Signed.Algorithm.Signature := TTLSSignatureAlgorithm(P^);
Inc(P);
L := DecodeTLSOpaque16(P^, N, Signed.Signature);
Dec(N, L);
Result := Size - N;
end;
{ }
{ Server Key Exchange }
{ }
{ select (KeyExchangeAlgorithm) }
{ case dh_anon: params : ServerDHParams; }
{ case dhe_dss: }
{ case dhe_rsa: params : ServerDHParams; }
{ signed_params : digitally-signed struct ( }
{ client_random : opaque [32]; }
{ server_random : opaque [32]; }
{ params : ServerDHParams ; }
{ ); }
{ case rsa: }
{ case dh_dss: }
{ case dh_rsa: struct (); }
{ case ec_diffie_hellman: }
{ ServerECDHParams params; }
{ Signature signed_params; }
{ }
procedure InitTLSServerKeyExchange(var ServerKeyExchange: TTLSServerKeyExchange);
begin
FillChar(ServerKeyExchange, SizeOf(ServerKeyExchange), 0);
end;
procedure AssignTLSServerKeyExchangeDHParams(
var ServerKeyExchange: TTLSServerKeyExchange;
const p, g, Ys: RawByteString);
begin
AssignTLSServerDHParams(ServerKeyExchange.DHParams, p, g, Ys);
end;
function EncodeTLSServerKeyExchange(
var Buffer; const Size: Integer;
const KeyExchangeAlgorithm: TTLSKeyExchangeAlgorithm;
const ServerKeyExchange: TTLSServerKeyExchange): Integer;
var P : PByte;
N, L : Integer;
begin
Assert(KeyExchangeAlgorithm <> tlskeaNone);
N := Size;
P := @Buffer;
case KeyExchangeAlgorithm of
tlskeaDH_Anon :
begin
L := EncodeTLSServerDHParams(P^, N, ServerKeyExchange.DHParams);
Dec(N, L);
end;
tlskeaDHE_DSS,
tlskeaDHE_RSA :
begin
L := EncodeTLSServerDHParams(P^, N, ServerKeyExchange.DHParams);
Dec(N, L);
Inc(P, L);
L := EncodeTLSDigitallySigned(P^, N, ServerKeyExchange.SignedParams);
Dec(N, L);
end;
tlskeaECDHE_ECDSA,
tlskeaECDHE_RSA : ;
tlskeaRSA,
tlskeaDH_DSS,
tlskeaDH_RSA : ;
end;
Result := Size - N;
end;
function DecodeTLSServerKeyExchange(
const Buffer; const Size: Integer;
const KeyExchangeAlgorithm: TTLSKeyExchangeAlgorithm;
var ServerKeyExchange: TTLSServerKeyExchange): Integer;
var P : PByte;
N, L : Integer;
begin
N := Size;
P := @Buffer;
case KeyExchangeAlgorithm of
tlskeaDH_Anon :
begin
L := DecodeTLSServerDHParams(P^, N, ServerKeyExchange.DHParams);
Dec(N, L);
end;
tlskeaDHE_DSS,
tlskeaDHE_RSA :
begin
L := DecodeTLSServerDHParams(P^, N, ServerKeyExchange.DHParams);
Dec(N, L);
Inc(P, L);
L := DecodeTLSDigitallySigned(P^, N, ServerKeyExchange.SignedParams);
Dec(N, L);
end;
tlskeaRSA,
tlskeaDH_DSS,
tlskeaDH_RSA : ;
end;
Result := Size - N;
end;
procedure SignTLSServerKeyExchangeDH_RSA(
var ServerKeyExchange: TTLSServerKeyExchange;
const client_random : TTLSClientServerRandom;
const server_random : TTLSClientServerRandom;
const RSAPrivateKey: TRSAPrivateKey);
const
MaxHashBufSize = 32768;
var
HashBuf : array[0..MaxHashBufSize - 1] of Byte;
L : Integer;
//HashMd5 : T128BitDigest;
//HashSha : T160BitDigest;
//SignedStruct : TTLSRSASignedStruct;
//SignHash : T256BitDigest;
SignatureBuf : RawByteString;
begin
Writeln('Sign:');
Assert(Length(ServerKeyExchange.DHParams.dh_p) > 0);
Assert(Length(ServerKeyExchange.DHParams.dh_g) > 0);
Assert(Length(ServerKeyExchange.DHParams.dh_Ys) > 0);
Assert(RSAPrivateKey.KeyBits > 0);
L := EncodeTLSServerDHParamsHashBuf(
HashBuf, SizeOf(HashBuf),
client_random,
server_random,
ServerKeyExchange.DHParams);
{
HashMd5 := CalcMD5(HashBuf, L);
HashSha := CalcSHA1(HashBuf, L);
Move(HashMd5, SignedStruct.md5_hash, SizeOf(SignedStruct.md5_hash));
Move(HashSha, SignedStruct.sha_hash, SizeOf(SignedStruct.sha_hash));
SignHash := CalcSHA256(SignedStruct, SizeOf(SignedStruct));
Writeln('SignHash:', DigestToHexU(SignHash, Sizeof(SignHash)));
Writeln('PrivateKey:', HugeWordToHex(RSAPrivateKey.Exponent), ' ', HugeWordToHex(RSAPrivateKey.Modulus));
}
SetLength(SignatureBuf, RSAPrivateKey.KeyBits div 8);
RSASignMessage(rsastEMSA_PKCS1, rsahfSHA256, RSAPrivateKey,
HashBuf, L,
Pointer(SignatureBuf)^, Length(SignatureBuf));
ServerKeyExchange.SignedParams.Algorithm.Hash := tlshaSHA256;
ServerKeyExchange.SignedParams.Algorithm.Signature := tlssaRSA;
ServerKeyExchange.SignedParams.Signature := SignatureBuf;
end;
function VerifyTLSServerKeyExchangeDH_RSA(
const ServerKeyExchange: TTLSServerKeyExchange;
const client_random : TTLSClientServerRandom;
const server_random : TTLSClientServerRandom;
const RSAPublicKey: TRSAPublicKey): Boolean;
const
MaxHashBufSize = 32768;
var
HashBuf : array[0..MaxHashBufSize - 1] of Byte;
L : Integer;
// HashMd5 : T128BitDigest;
// HashSha : T160BitDigest;
// SignedStruct : TTLSRSASignedStruct;
// SignHash : T256BitDigest;
SignatureBuf : RawByteString;
begin
Assert(Length(ServerKeyExchange.DHParams.dh_p) > 0);
Assert(Length(ServerKeyExchange.DHParams.dh_g) > 0);
Assert(Length(ServerKeyExchange.DHParams.dh_Ys) > 0);
Assert(RSAPublicKey.KeyBits > 0);
//// After validated, encode hash buf using received Params buf, it might
//// have params in a different order.
L := EncodeTLSServerDHParamsHashBuf(HashBuf, SizeOf(HashBuf),
client_random,
server_random,
ServerKeyExchange.DHParams);
SignatureBuf := ServerKeyExchange.SignedParams.Signature;
(*
HashMd5 := CalcMD5(HashBuf, L);
HashSha := CalcSHA1(HashBuf, L);
Move(HashMd5, SignedStruct.md5_hash, SizeOf(SignedStruct.md5_hash));
Move(HashSha, SignedStruct.sha_hash, SizeOf(SignedStruct.sha_hash));
SignHash := CalcSHA256(SignedStruct, SizeOf(SignedStruct));
Writeln('SignHash:', DigestToHexU(SignHash, Sizeof(SignHash)));
Writeln('Signature:', DigestToHexU(Pointer(SignatureBuf)^, Length(SignatureBuf)));
Writeln('PublicKey:', HugeWordToHex(RSAPublicKey.Exponent), ' ', HugeWordToHex(RSAPublicKey.Modulus));
*)
Result :=
RSACheckSignature(rsastEMSA_PKCS1, RSAPublicKey,
HashBuf, L,
Pointer(SignatureBuf)^, Length(SignatureBuf));
end;
{ }
{ ClientDiffieHellmanPublic }
{ select (PublicValueEncoding) }
{ case implicit: struct (); }
{ case explicit: opaque dh_Yc<1..2^16-1>; }
{ }
function EncodeTLSClientDiffieHellmanPublic(
var Buffer; const Size: Integer;
const ClientDiffieHellmanPublic: TTLSClientDiffieHellmanPublic): Integer;
var P : PByte;
N, L : Integer;
begin
N := Size;
P := @Buffer;
if ClientDiffieHellmanPublic.PublicValueEncodingExplicit then
begin
if ClientDiffieHellmanPublic.dh_Yc = '' then
raise ETLSError.Create(TLSError_InvalidParameter);
L := EncodeTLSOpaque16(P^, N, ClientDiffieHellmanPublic.dh_Yc);
Dec(N, L);
end;
Result := Size - N;
end;
function DecodeTLSClientDiffieHellmanPublic(
const Buffer; const Size: Integer;
const PublicValueEncodingExplicit: Boolean;
var ClientDiffieHellmanPublic: TTLSClientDiffieHellmanPublic): Integer;
var P : PByte;
N, L : Integer;
begin
N := Size;
P := @Buffer;
if PublicValueEncodingExplicit then
begin
L := DecodeTLSOpaque16(P^, N, ClientDiffieHellmanPublic.dh_Yc);
Dec(N, L);
end;
Result := Size - N;
end;
(*
struct {
ECPoint ecdh_Yc;
} ClientECDiffieHellmanPublic;
*)
{ }
{ ClientKeyExchange }
{ }
{ select (KeyExchangeAlgorithm) }
{ case rsa : EncryptedPreMasterSecret; }
{ case dhe_dss : }
{ case dhe_rsa : }
{ case dh_dss : }
{ case dh_rsa : }
{ case dh_anon : ClientDiffieHellmanPublic; }
{ }
function EncodeTLSClientKeyExchange(
var Buffer; const Size: Integer;
const KeyExchangeAlgorithm: TTLSKeyExchangeAlgorithm;
const ClientKeyExchange: TTLSClientKeyExchange): Integer;
var P : PByte;
N, L : Integer;
begin
N := Size;
P := @Buffer;
case KeyExchangeAlgorithm of
tlskeaRSA :
begin
L := Length(ClientKeyExchange.EncryptedPreMasterSecret);
if L = 0 then
raise ETLSError.Create(TLSError_InvalidParameter);
Move(ClientKeyExchange.EncryptedPreMasterSecret[1], P^, L);
Dec(N, L);
end;
tlskeaDHE_DSS,
tlskeaDHE_RSA,
tlskeaDH_DSS,
tlskeaDH_RSA,
tlskeaDH_Anon :
begin
L := EncodeTLSClientDiffieHellmanPublic(P^, N, ClientKeyExchange.ClientDiffieHellmanPublic);
Dec(N, L);
end;
end;
Result := Size - N;
end;
function DecodeTLSClientKeyExchange(
const Buffer; const Size: Integer;
const KeyExchangeAlgorithm: TTLSKeyExchangeAlgorithm;
const PublicValueEncodingExplicit: Boolean;
var ClientKeyExchange: TTLSClientKeyExchange): Integer;
var P : PByte;
N, L, C : Integer;
begin
N := Size;
P := @Buffer;
case KeyExchangeAlgorithm of
tlskeaRSA :
begin
L := DecodeTLSLen16(P^, N, C);
Dec(N, L);
Inc(P, L);
Assert(N = C);
SetLength(ClientKeyExchange.EncryptedPreMasterSecret, C);
Move(P^, ClientKeyExchange.EncryptedPreMasterSecret[1], C);
Dec(N, C);
end;
tlskeaDHE_DSS,
tlskeaDHE_RSA,
tlskeaDH_DSS,
tlskeaDH_RSA,
tlskeaDH_Anon :
begin
L := DecodeTLSClientDiffieHellmanPublic(P^, N, PublicValueEncodingExplicit, ClientKeyExchange.ClientDiffieHellmanPublic);
Dec(N, L);
end;
end;
Result := Size - N;
end;
end.
|
{ Date Created: 5/22/00 11:17:33 AM }
unit InfoLIENTable;
interface
uses
Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf;
type
TInfoLIENRecord = record
PLienID: Integer;
PModCount: String[1];
PName: String[30];
PAddr: String[30];
PCityStZip: String[30];
PPhone: String[30];
PContact: String[30];
End;
TInfoLIENBuffer = class(TDataBuf)
protected
function PtrIndex(Index:integer):Pointer;override;
public
Data: TInfoLIENRecord
end;
TEIInfoLIEN = (InfoLIENPrimaryKey, InfoLIENLienId, InfoLIENName);
TInfoLIENTable = class( TDBISAMTableAU )
private
FDFLienID: TAutoIncField;
FDFModCount: TStringField;
FDFName: TStringField;
FDFAddr: TStringField;
FDFCityStZip: TStringField;
FDFPhone: TStringField;
FDFContact: TStringField;
procedure SetPModCount(const Value: String);
function GetPModCount:String;
procedure SetPName(const Value: String);
function GetPName:String;
procedure SetPAddr(const Value: String);
function GetPAddr:String;
procedure SetPCityStZip(const Value: String);
function GetPCityStZip:String;
procedure SetPPhone(const Value: String);
function GetPPhone:String;
procedure SetPContact(const Value: String);
function GetPContact:String;
function GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string;
procedure SetEnumIndex(Value: TEIInfoLIEN);
function GetEnumIndex: TEIInfoLIEN;
protected
function CreateField( const FieldName : string ): TField;
procedure CreateFields; virtual;
procedure SetActive(Value: Boolean); override;
procedure LoadFieldDefs(AStringList:TStringList);override;
procedure LoadIndexDefs(AStringList:TStringList);override;
public
function GetDataBuffer:TInfoLIENRecord;
procedure StoreDataBuffer(ABuffer:TInfoLIENRecord);
property DFLienID: TAutoIncField read FDFLienID;
property DFModCount: TStringField read FDFModCount;
property DFName: TStringField read FDFName;
property DFAddr: TStringField read FDFAddr;
property DFCityStZip: TStringField read FDFCityStZip;
property DFPhone: TStringField read FDFPhone;
property DFContact: TStringField read FDFContact;
property PModCount: String read GetPModCount write SetPModCount;
property PName: String read GetPName write SetPName;
property PAddr: String read GetPAddr write SetPAddr;
property PCityStZip: String read GetPCityStZip write SetPCityStZip;
property PPhone: String read GetPPhone write SetPPhone;
property PContact: String read GetPContact write SetPContact;
procedure Validate; virtual;
published
property Active write SetActive;
property EnumIndex: TEIInfoLIEN read GetEnumIndex write SetEnumIndex;
end; { TInfoLIENTable }
procedure Register;
implementation
function TInfoLIENTable.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 { TInfoLIENTable.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; { TInfoLIENTable.GenerateNewFieldName }
function TInfoLIENTable.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; { TInfoLIENTable.CreateField }
procedure TInfoLIENTable.CreateFields;
begin
FDFLienID := CreateField( 'LienID' ) as TAutoIncField;
FDFModCount := CreateField( 'ModCount' ) as TStringField;
FDFName := CreateField( 'Name' ) as TStringField;
FDFAddr := CreateField( 'Addr' ) as TStringField;
FDFCityStZip := CreateField( 'CityStZip' ) as TStringField;
FDFPhone := CreateField( 'Phone' ) as TStringField;
FDFContact := CreateField( 'Contact' ) as TStringField;
end; { TInfoLIENTable.CreateFields }
procedure TInfoLIENTable.SetActive(Value: Boolean);
begin
inherited SetActive(Value);
if Active then
CreateFields;
end; { TInfoLIENTable.SetActive }
procedure TInfoLIENTable.Validate;
begin
{ Enter Validation Code Here }
end; { TInfoLIENTable.Validate }
procedure TInfoLIENTable.SetPModCount(const Value: String);
begin
DFModCount.Value := Value;
end;
function TInfoLIENTable.GetPModCount:String;
begin
result := DFModCount.Value;
end;
procedure TInfoLIENTable.SetPName(const Value: String);
begin
DFName.Value := Value;
end;
function TInfoLIENTable.GetPName:String;
begin
result := DFName.Value;
end;
procedure TInfoLIENTable.SetPAddr(const Value: String);
begin
DFAddr.Value := Value;
end;
function TInfoLIENTable.GetPAddr:String;
begin
result := DFAddr.Value;
end;
procedure TInfoLIENTable.SetPCityStZip(const Value: String);
begin
DFCityStZip.Value := Value;
end;
function TInfoLIENTable.GetPCityStZip:String;
begin
result := DFCityStZip.Value;
end;
procedure TInfoLIENTable.SetPPhone(const Value: String);
begin
DFPhone.Value := Value;
end;
function TInfoLIENTable.GetPPhone:String;
begin
result := DFPhone.Value;
end;
procedure TInfoLIENTable.SetPContact(const Value: String);
begin
DFContact.Value := Value;
end;
function TInfoLIENTable.GetPContact:String;
begin
result := DFContact.Value;
end;
procedure TInfoLIENTable.LoadFieldDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('LienID, AutoInc, 0, N');
Add('ModCount, String, 1, N');
Add('Name, String, 30, N');
Add('Addr, String, 30, N');
Add('CityStZip, String, 30, N');
Add('Phone, String, 30, N');
Add('Contact, String, 30, N');
end;
end;
procedure TInfoLIENTable.LoadIndexDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('PrimaryKey, LienID, Y, Y, N, N');
Add('LienId, LienID, N, Y, N, N');
Add('Name, Name, N, N, N, N');
end;
end;
procedure TInfoLIENTable.SetEnumIndex(Value: TEIInfoLIEN);
begin
case Value of
InfoLIENPrimaryKey : IndexName := '';
InfoLIENLienId : IndexName := 'LienId';
InfoLIENName : IndexName := 'Name';
end;
end;
function TInfoLIENTable.GetDataBuffer:TInfoLIENRecord;
var buf: TInfoLIENRecord;
begin
fillchar(buf, sizeof(buf), 0);
buf.PLienID := DFLienID.Value;
buf.PModCount := DFModCount.Value;
buf.PName := DFName.Value;
buf.PAddr := DFAddr.Value;
buf.PCityStZip := DFCityStZip.Value;
buf.PPhone := DFPhone.Value;
buf.PContact := DFContact.Value;
result := buf;
end;
procedure TInfoLIENTable.StoreDataBuffer(ABuffer:TInfoLIENRecord);
begin
DFModCount.Value := ABuffer.PModCount;
DFName.Value := ABuffer.PName;
DFAddr.Value := ABuffer.PAddr;
DFCityStZip.Value := ABuffer.PCityStZip;
DFPhone.Value := ABuffer.PPhone;
DFContact.Value := ABuffer.PContact;
end;
function TInfoLIENTable.GetEnumIndex: TEIInfoLIEN;
var iname : string;
begin
iname := uppercase(indexname);
if iname = '' then result := InfoLIENPrimaryKey;
if iname = 'LIENID' then result := InfoLIENLienId;
if iname = 'NAME' then result := InfoLIENName;
end;
(********************************************)
(************ Register Component ************)
(********************************************)
procedure Register;
begin
RegisterComponents( 'Info Tables', [ TInfoLIENTable, TInfoLIENBuffer ] );
end; { Register }
function TInfoLIENBuffer.PtrIndex(index:integer):Pointer;
begin
result := nil;
case index of
1 : result := @Data.PLienID;
2 : result := @Data.PModCount;
3 : result := @Data.PName;
4 : result := @Data.PAddr;
5 : result := @Data.PCityStZip;
6 : result := @Data.PPhone;
7 : result := @Data.PContact;
end;
end;
end. { InfoLIENTable }
|
unit GX_About;
{$I GX_CondDefine.inc}
interface
uses
Windows, Classes, Controls, Forms, StdCtrls, ExtCtrls, GX_BaseForm;
type
TfmAbout = class(TfmBaseForm)
lblGExperts: TLabel;
btnClose: TButton;
lblVersion: TLabel;
pnlLogo: TPanel;
imgLogo: TImage;
btnEmail: TButton;
lblWebPage: TLabel;
lblProjectLeader: TLabel;
lblContributors: TLabel;
lblErik: TLabel;
lblWebSite: TLabel;
lblPreRelease1: TLabel;
lblPreRelease2: TLabel;
mmoBuildDetails: TMemo;
mmoContributors: TMemo;
tim_Scroll: TTimer;
procedure btnEmailClick(Sender: TObject);
procedure lblWebPageClick(Sender: TObject);
procedure tim_ScrollTimer(Sender: TObject);
private
procedure InitVersionInfoControls;
protected
class function GetVersionStr: string;
class function DoAddToAboutDialog: Integer; virtual;
class function GetAboutIcon: HBITMAP; virtual;
class function GetSplashIcon: HBITMAP; virtual;
public
constructor Create(AOwner: TComponent); override;
// If you release an experimental GExperts, either
// set gblAboutFormClass to your own descentant of this form or
// call SetCustomBuildDetails and SetCustomBuildEmails to
// describe your build and provide feedback email adresses.
class procedure SetCustomBuildDetails(const Details: string);
class procedure SetCustomBuildEmails(const ABugEmail, ASuggestionEmail: string);
class procedure AddToSplashScreen;
class procedure AddToAboutDialog;
class procedure RemoveFromAboutDialog;
end;
type
TAboutFormClass = class of TfmAbout;
var
gblAboutFormClass: TAboutFormClass;
implementation
{$R *.dfm}
{$R GX_About.res}
uses
{$IFOPT D+} GX_DbugIntf, {$ENDIF}
SysUtils, Graphics, ToolsApi, Messages,
GX_GenericUtils, GX_FeedbackWizard;
const
DefaultBugEmail = 'bugs@gexperts.org'; // Do not localize.
DefaultSuggestionEmail = 'suggestions@gexperts.org'; // Do not localize.
var
BuildDetails: string = '';
BugEmail: string = DefaultBugEmail;
SuggestionEmail: string = DefaultSuggestionEmail;
procedure TfmAbout.btnEmailClick(Sender: TObject);
begin
TfmFeedbackWizard.Execute(Application, BugEmail, SuggestionEmail);
Close;
end;
procedure TfmAbout.lblWebPageClick(Sender: TObject);
var
Lbl: TLabel;
URL: string;
begin
Lbl := Sender as TLabel;
URL := Lbl.Hint;
if URL = '' then
URL := Lbl.Caption;
GXShellExecute(URL, '', True);
end;
constructor TfmAbout.Create(AOwner: TComponent);
begin
inherited;
SetFontBold(lblContributors);
SetFontBold(lblProjectLeader);
SetFontBold(lblWebSite);
SetFontBold(lblVersion);
SetFontBold(lblGExperts);
SetFontColor(lblPreRelease1, clRed);
SetFontColor(lblPreRelease2, clRed);
SetFontSize(lblGExperts, +4);
SetFontSize(lblVersion, +4);
SetFontUnderline(lblErik);
SetFontUnderline(lblWebPage);
SetFontColor(lblErik, clBlue);
SetFontColor(lblWebPage, clBlue);
SetFontColor(mmoBuildDetails, clRed);
imgLogo.Picture.Bitmap.LoadFromResourceName(HInstance, 'ABOUT_WIZ');
InitVersionInfoControls;
if NotEmpty(BuildDetails) then
begin
if (BugEmail = DefaultBugEmail) or (SuggestionEmail = DefaultSuggestionEmail) then
btnEmail.Visible := False;
mmoBuildDetails.Visible := True;
mmoBuildDetails.Lines.Text := BuildDetails;
end
else
begin
if gblAboutFormClass = TfmAbout then
btnEmail.Visible := True;
mmoBuildDetails.Visible := False;
end;
end;
procedure TfmAbout.InitVersionInfoControls;
begin
lblVersion.Caption := GetVersionStr;
end;
class procedure TfmAbout.SetCustomBuildDetails(const Details: string);
begin
BuildDetails := Details;
end;
class procedure TfmAbout.SetCustomBuildEmails(const ABugEmail, ASuggestionEmail: string);
begin
BugEmail := ABugEmail;
SuggestionEmail := ASuggestionEmail;
end;
procedure TfmAbout.tim_ScrollTimer(Sender: TObject);
var
Res: Integer;
begin
inherited;
if mmoContributors.Focused then
Exit;
Res := SendMessage(mmoContributors.Handle, WM_VSCROLL, SB_LINEDOWN, 0);
if Res = 0 then begin
// we have reached the end
SendMessage(mmoContributors.Handle, WM_VSCROLL, SB_TOP, 0);
end;
end;
class function TfmAbout.GetAboutIcon: HBITMAP;
const
GX_ABOUT_ICON32 = 'GX32';
begin
Result := LoadBitmap(HInstance, GX_ABOUT_ICON32);
end;
class function TfmAbout.GetSplashIcon: HBITMAP;
const
GX_ABOUT_ICON24 = 'GX24';
begin
Result := LoadBitmap(HInstance, GX_ABOUT_ICON24);
end;
class function TfmAbout.GetVersionStr: string;
resourcestring
SVersion = 'Version';
SUnknown = '<unknown>';
begin
try
Result := Format('%s %s', [SVersion, GetFileVersionString(ThisDllName, True, False)]);
except
Result := Format('%s %s', [SVersion, SUnknown]);
end;
end;
{$IFOPT D+}
procedure SendDebugComponent(_cmp: TComponent; _Recursive: Boolean = False; _Prefix: string = '');
var
i: integer;
begin
SendDebug(_Prefix + _cmp.Name + ': ' + _cmp.ClassName);
if _Recursive and (_cmp.ComponentCount > 0) then begin
SendIndent;
for i := 0 to _cmp.ComponentCount - 1 do begin
SendDebugComponent(_cmp.Components[i], _Recursive, '(' + IntToStr(i) + ') ');
end;
SendUnIndent;
end;
end;
{$ENDIF}
procedure AddPluginToSplashScreen(_Icon: HBITMAP; const _Title: string; const _Version: string);
{$IFDEF GX_VER170_up}
// Only Delphi 2005 and up support the splash screen services
begin
if Assigned(SplashScreenServices) then
SplashScreenServices.AddPluginBitmap(_Title,
_Icon, False, _Version);
end;
{$ELSE GX_VER170_up}
const
XPOS = 140;
YPOS = 150;
PluginLogoStr = 'PluginLogo';
var
imgLogo: TImage;
lblTitle: TLabel;
lblVersion: TLabel;
i: integer;
PluginIdx: integer;
frm: TCustomForm;
begin
{$IFOPT D+} SendDebug('Screen.Forms[]:'); {$ENDIF}
{$IFOPT D+} SendIndent; {$ENDIF}
for i := 0 to Screen.FormCount - 1 do begin
frm := Screen.Forms[i];
if (frm.Name = 'SplashScreen') and frm.ClassNameIs('TForm') then begin
{$IFOPT D+} SendDebugComponent(frm, True, '(' + IntToStr(i) + ') '); {$ENDIF}
PluginIdx := 0;
while frm.FindComponent(PluginLogoStr + IntToStr(PluginIdx)) <> nil do
Inc(PluginIdx);
imgLogo := TImage.Create(frm);
imgLogo.Name := PluginLogoStr + IntToStr(PluginIdx);
imgLogo.Parent := frm;
imgLogo.AutoSize := True;
imgLogo.Picture.Bitmap.Handle := _Icon;
imgLogo.Left := XPOS;
imgLogo.Top := YPOS + 32 * PluginIdx;
lblTitle := TLabel.Create(frm);
lblTitle.Name := 'PluginTitle' + IntToStr(PluginIdx);
lblTitle.Parent := frm;
lblTitle.Caption := _Title;
lblTitle.Top := imgLogo.Top;
lblTitle.Left := imgLogo.Left + 32 + 8;
lblTitle.Transparent := True;
lblTitle.Font.Color := clWhite;
lblTitle.Font.Style := [fsbold];
lblVersion := TLabel.Create(frm);
lblVersion.Name := 'PluginVersion' + IntToStr(PluginIdx);
lblVersion.Parent := frm;
lblVersion.Caption := _Version;
lblVersion.Top := imgLogo.Top + lblTitle.Height;
lblVersion.Left := imgLogo.Left + 32 + 20;
lblVersion.Transparent := True;
lblVersion.Font.Color := clWhite;
end else begin
{$IFOPT D+} SendDebugComponent(frm, False, '(' + IntToStr(i) + ') '); {$ENDIF}
end;
end;
{$IFOPT D+} SendUnIndent; {$ENDIF}
end;
{$ENDIF GX_VER170_up}
class procedure TfmAbout.AddToSplashScreen;
begin
AddPluginToSplashScreen(GetSplashIcon, 'GExperts', GetVersionStr);
end;
class function TfmAbout.DoAddToAboutDialog: Integer;
{$IFDEF GX_VER170_up}
// Only Delphi 2005 and up support the about box services
var
AboutBoxServices: IOTAAboutBoxServices;
begin
Result := -1;
if Supports(BorlandIDEServices, IOTAAboutBoxServices, AboutBoxServices) then
begin
Result := AboutBoxServices.AddPluginInfo(
'GExperts',
'GExperts is a free set of tools built to increase the productivity of Delphi and C++Builder'
+ ' programmers by adding several features to the IDE.'
+ ' GExperts is developed as Open Source software and we encourage user contributions to the project.'#13#10
+ '(c) Erik Berry and the GExperts Team'#13#10
+ 'http://www.gexperts.org',
GetAboutIcon,
False,
'', // leave this empty!
GetVersionStr);
end;
end;
{$ELSE not GX_VER170_up}
begin
Result := -1;
end;
{$ENDIF not GX_VER170_up}
var
FAboutPluginIndex: Integer;
class procedure TfmAbout.AddToAboutDialog;
begin
FAboutPluginIndex := DoAddToAboutDialog;
end;
class procedure TfmAbout.RemoveFromAboutDialog;
{$IFDEF GX_VER170_up}
// Only Delphi 2005 and up support the about box services
var
AboutBoxServices: IOTAAboutBoxServices;
begin
if FAboutPluginIndex <> -1 then
begin
if Supports(BorlandIDEServices, IOTAAboutBoxServices, AboutBoxServices) then
AboutBoxServices.RemovePluginInfo(FAboutPluginIndex);
FAboutPluginIndex := -1;
end;
end;
{$ELSE not GX_VER170_up}
begin //fi:W519
end;
{$ENDIF not GX_VER170_up}
initialization
TfmAbout.AddToSplashScreen;
gblAboutFormClass := TfmAbout;
finalization
end.
|
unit TTSNOTRECAPTable;
interface
uses
Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf;
type
TTTSNOTRECAPRecord = record
PCategory: String[8];
PDescription: String[30];
PItemCount: Integer;
PStage1: Integer;
PStage2: Integer;
PStage3: Integer;
PStage4: Integer;
PStage5: Integer;
PTotal: Integer;
End;
TTTSNOTRECAPBuffer = class(TDataBuf)
protected
function PtrIndex(Index:integer):Pointer;override;
public
Data: TTTSNOTRECAPRecord;
function FieldNameToIndex(s:string):integer;override;
function FieldType(index:integer):TFieldType;override;
end;
TEITTSNOTRECAP = (TTSNOTRECAPPrimaryKey);
TTTSNOTRECAPTable = class( TDBISAMTableAU )
private
FDFCategory: TStringField;
FDFDescription: TStringField;
FDFItemCount: TIntegerField;
FDFStage1: TIntegerField;
FDFStage2: TIntegerField;
FDFStage3: TIntegerField;
FDFStage4: TIntegerField;
FDFStage5: TIntegerField;
FDFTotal: TIntegerField;
procedure SetPCategory(const Value: String);
function GetPCategory:String;
procedure SetPDescription(const Value: String);
function GetPDescription:String;
procedure SetPItemCount(const Value: Integer);
function GetPItemCount:Integer;
procedure SetPStage1(const Value: Integer);
function GetPStage1:Integer;
procedure SetPStage2(const Value: Integer);
function GetPStage2:Integer;
procedure SetPStage3(const Value: Integer);
function GetPStage3:Integer;
procedure SetPStage4(const Value: Integer);
function GetPStage4:Integer;
procedure SetPStage5(const Value: Integer);
function GetPStage5:Integer;
procedure SetPTotal(const Value: Integer);
function GetPTotal:Integer;
procedure SetEnumIndex(Value: TEITTSNOTRECAP);
function GetEnumIndex: TEITTSNOTRECAP;
protected
procedure CreateFields; override;
procedure SetActive(Value: Boolean); override;
procedure LoadFieldDefs(AStringList:TStringList);override;
procedure LoadIndexDefs(AStringList:TStringList);override;
public
function GetDataBuffer:TTTSNOTRECAPRecord;
procedure StoreDataBuffer(ABuffer:TTTSNOTRECAPRecord);
property DFCategory: TStringField read FDFCategory;
property DFDescription: TStringField read FDFDescription;
property DFItemCount: TIntegerField read FDFItemCount;
property DFStage1: TIntegerField read FDFStage1;
property DFStage2: TIntegerField read FDFStage2;
property DFStage3: TIntegerField read FDFStage3;
property DFStage4: TIntegerField read FDFStage4;
property DFStage5: TIntegerField read FDFStage5;
property DFTotal: TIntegerField read FDFTotal;
property PCategory: String read GetPCategory write SetPCategory;
property PDescription: String read GetPDescription write SetPDescription;
property PItemCount: Integer read GetPItemCount write SetPItemCount;
property PStage1: Integer read GetPStage1 write SetPStage1;
property PStage2: Integer read GetPStage2 write SetPStage2;
property PStage3: Integer read GetPStage3 write SetPStage3;
property PStage4: Integer read GetPStage4 write SetPStage4;
property PStage5: Integer read GetPStage5 write SetPStage5;
property PTotal: Integer read GetPTotal write SetPTotal;
published
property Active write SetActive;
property EnumIndex: TEITTSNOTRECAP read GetEnumIndex write SetEnumIndex;
end; { TTTSNOTRECAPTable }
procedure Register;
implementation
procedure TTTSNOTRECAPTable.CreateFields;
begin
FDFCategory := CreateField( 'Category' ) as TStringField;
FDFDescription := CreateField( 'Description' ) as TStringField;
FDFItemCount := CreateField( 'ItemCount' ) as TIntegerField;
FDFStage1 := CreateField( 'Stage1' ) as TIntegerField;
FDFStage2 := CreateField( 'Stage2' ) as TIntegerField;
FDFStage3 := CreateField( 'Stage3' ) as TIntegerField;
FDFStage4 := CreateField( 'Stage4' ) as TIntegerField;
FDFStage5 := CreateField( 'Stage5' ) as TIntegerField;
FDFTotal := CreateField( 'Total' ) as TIntegerField;
end; { TTTSNOTRECAPTable.CreateFields }
procedure TTTSNOTRECAPTable.SetActive(Value: Boolean);
begin
inherited SetActive(Value);
if Active then
CreateFields;
end; { TTTSNOTRECAPTable.SetActive }
procedure TTTSNOTRECAPTable.SetPCategory(const Value: String);
begin
DFCategory.Value := Value;
end;
function TTTSNOTRECAPTable.GetPCategory:String;
begin
result := DFCategory.Value;
end;
procedure TTTSNOTRECAPTable.SetPDescription(const Value: String);
begin
DFDescription.Value := Value;
end;
function TTTSNOTRECAPTable.GetPDescription:String;
begin
result := DFDescription.Value;
end;
procedure TTTSNOTRECAPTable.SetPItemCount(const Value: Integer);
begin
DFItemCount.Value := Value;
end;
function TTTSNOTRECAPTable.GetPItemCount:Integer;
begin
result := DFItemCount.Value;
end;
procedure TTTSNOTRECAPTable.SetPStage1(const Value: Integer);
begin
DFStage1.Value := Value;
end;
function TTTSNOTRECAPTable.GetPStage1:Integer;
begin
result := DFStage1.Value;
end;
procedure TTTSNOTRECAPTable.SetPStage2(const Value: Integer);
begin
DFStage2.Value := Value;
end;
function TTTSNOTRECAPTable.GetPStage2:Integer;
begin
result := DFStage2.Value;
end;
procedure TTTSNOTRECAPTable.SetPStage3(const Value: Integer);
begin
DFStage3.Value := Value;
end;
function TTTSNOTRECAPTable.GetPStage3:Integer;
begin
result := DFStage3.Value;
end;
procedure TTTSNOTRECAPTable.SetPStage4(const Value: Integer);
begin
DFStage4.Value := Value;
end;
function TTTSNOTRECAPTable.GetPStage4:Integer;
begin
result := DFStage4.Value;
end;
procedure TTTSNOTRECAPTable.SetPStage5(const Value: Integer);
begin
DFStage5.Value := Value;
end;
function TTTSNOTRECAPTable.GetPStage5:Integer;
begin
result := DFStage5.Value;
end;
procedure TTTSNOTRECAPTable.SetPTotal(const Value: Integer);
begin
DFTotal.Value := Value;
end;
function TTTSNOTRECAPTable.GetPTotal:Integer;
begin
result := DFTotal.Value;
end;
procedure TTTSNOTRECAPTable.LoadFieldDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('Category, String, 8, N');
Add('Description, String, 30, N');
Add('ItemCount, Integer, 0, N');
Add('Stage1, Integer, 0, N');
Add('Stage2, Integer, 0, N');
Add('Stage3, Integer, 0, N');
Add('Stage4, Integer, 0, N');
Add('Stage5, Integer, 0, N');
Add('Total, Integer, 0, N');
end;
end;
procedure TTTSNOTRECAPTable.LoadIndexDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('PrimaryKey, Category, Y, Y, Y, N');
end;
end;
procedure TTTSNOTRECAPTable.SetEnumIndex(Value: TEITTSNOTRECAP);
begin
case Value of
TTSNOTRECAPPrimaryKey : IndexName := '';
end;
end;
function TTTSNOTRECAPTable.GetDataBuffer:TTTSNOTRECAPRecord;
var buf: TTTSNOTRECAPRecord;
begin
fillchar(buf, sizeof(buf), 0);
buf.PCategory := DFCategory.Value;
buf.PDescription := DFDescription.Value;
buf.PItemCount := DFItemCount.Value;
buf.PStage1 := DFStage1.Value;
buf.PStage2 := DFStage2.Value;
buf.PStage3 := DFStage3.Value;
buf.PStage4 := DFStage4.Value;
buf.PStage5 := DFStage5.Value;
buf.PTotal := DFTotal.Value;
result := buf;
end;
procedure TTTSNOTRECAPTable.StoreDataBuffer(ABuffer:TTTSNOTRECAPRecord);
begin
DFCategory.Value := ABuffer.PCategory;
DFDescription.Value := ABuffer.PDescription;
DFItemCount.Value := ABuffer.PItemCount;
DFStage1.Value := ABuffer.PStage1;
DFStage2.Value := ABuffer.PStage2;
DFStage3.Value := ABuffer.PStage3;
DFStage4.Value := ABuffer.PStage4;
DFStage5.Value := ABuffer.PStage5;
DFTotal.Value := ABuffer.PTotal;
end;
function TTTSNOTRECAPTable.GetEnumIndex: TEITTSNOTRECAP;
begin
// VG 220318: Hardcoded result because there are not other key types
result := TTSNOTRECAPPrimaryKey;
end;
(********************************************)
(************ Register Component ************)
(********************************************)
procedure Register;
begin
RegisterComponents( 'TTS Tables', [ TTTSNOTRECAPTable, TTTSNOTRECAPBuffer ] );
end; { Register }
function TTTSNOTRECAPBuffer.FieldNameToIndex(s:string):integer;
const flist:array[1..9] of string = ('CATEGORY','DESCRIPTION','ITEMCOUNT','STAGE1','STAGE2','STAGE3'
,'STAGE4','STAGE5','TOTAL' );
var x : integer;
begin
s := uppercase(s);
x := 1;
while (x <= 9) and (flist[x] <> s) do inc(x);
if x <= 9 then result := x else result := 0;
end;
function TTTSNOTRECAPBuffer.FieldType(index:integer):TFieldType;
begin
result := ftUnknown;
case index of
1 : result := ftString;
2 : result := ftString;
3 : result := ftInteger;
4 : result := ftInteger;
5 : result := ftInteger;
6 : result := ftInteger;
7 : result := ftInteger;
8 : result := ftInteger;
9 : result := ftInteger;
end;
end;
function TTTSNOTRECAPBuffer.PtrIndex(index:integer):Pointer;
begin
result := nil;
case index of
1 : result := @Data.PCategory;
2 : result := @Data.PDescription;
3 : result := @Data.PItemCount;
4 : result := @Data.PStage1;
5 : result := @Data.PStage2;
6 : result := @Data.PStage3;
7 : result := @Data.PStage4;
8 : result := @Data.PStage5;
9 : result := @Data.PTotal;
end;
end;
end.
|
unit DAO.Base;
interface
uses FireDAC.Comp.Client, System.SysUtils, DAO.Conexao, Model.Base;
type
TBaseDAO = class
private
FConexao : TConexao;
public
constructor Create;
function Inserir(ABases: TBase): Boolean;
function Alterar(ABases: TBase): Boolean;
function Excluir(ABases: TBase): Boolean;
function Pesquisar(aParam: array of variant): TFDQuery;
end;
const
TABLENAME = 'tbagentes';
implementation
{ TBaseDAO }
function TBaseDAO.Alterar(ABases: TBase): Boolean;
var
FDQuery : TFDQuery;
begin
try
Result := False;
FDQuery := FConexao.ReturnQuery;
FDQuery.ExecSQL('UPDATE ' + TABLENAME + ' SET ' +
'DES_RAZAO_SOCIAL = :DES_RAZAO_SOCIAL, NOM_FANTASIA = :NOM_FANTASIA, ' +
'DES_TIPO_DOC = :DES_TIPO_DOC: CNPJ, NUM_CNPJ = :NUM_CNPJ, NUM_IE = :NUM_IE, NUM_IEST = :NUM_IEST, ' +
'NUM_IM = :NUM_IM, COD_CNAE = :COD_CNAE, COD_CRT = :COD_CRT, NUM_CNH = :NUM_CNH, ' +
'DES_CATEGORIA_CNH = :DES_CATEGORIA_CNH, DAT_VALIDADE_CNH = :DAT_VALIDADE_CNH, DES_PAGINA = :DES_PAGINA, ' +
'COD_STATUS = :COD_STATUS, DES_OBSERVACAO = :DES_OBSERVACAO, DAT_CADASTRO = :DAT_CADASTRO, ' +
'DAT_ALTERACAO = :DAT_ALTERACAO, VAL_VERBA = :VAL_VERBA, DES_TIPO_CONTA = :DES_TIPO_CONTA, ' +
'COD_BANCO = :COD_BANCO, COD_AGENCIA = :COD_AGENCIA, NUM_CONTA = :NUM_CONTA, ' +
'NOM_FAVORECIDO = :NOM_FAVORECIDO, NUM_CPF_CNPJ_FAVORECIDO = :NUM_CPF_CNPJ_FAVORECIDO, ' +
'DES_FORMA_PAGAMENTO = :DES_FORMA_PAGAMENTO, COD_CENTRO_CUSTO = :COD_CENTRO_CUSTO, ' +
'COD_GRUPO = :COD_GRUPO ' +
'WHERE ' +
'COD_AGENTE = :COD_AGENTE;',
[ABases.Nome, ABases.Alias, ABases.TipoDoc, ABases.CPFCNPJ, ABases.RGIE, ABases.IE_ST, ABases.IM, ABases.CNAE,
ABases.CRT, ABases.NumCNH, ABases.CatergoriaCNH, ABases.ValidadeCNH, ABases.Pagina, ABases.Status, ABases.Obs,
ABases.DataCadastro, ABases.DataAlteracao, ABases.Verba, ABases.TipoConta, ABases.CodigoBanco,
ABases.NumeroAgencia, ABases.NumeroConta, ABases.NomeFavorecido, ABases.CPFCNPJFavorecido,
ABases.FormaPagamento, ABases.CentroCusto, ABases.GrupoVerba, ABases.Codigo]);
Result := True;
finally
FDQuery.Free;
end;
end;
constructor TBaseDAO.Create;
begin
FConexao := TConexao.Create;
end;
function TBaseDAO.Excluir(ABases: TBase): Boolean;
var
FDQuery : TFDQuery;
begin
try
FDQuery := FConexao.ReturnQuery;
Result := False;
FDQuery.ExecSQL('DELETE FROM ' + TABLENAME + 'WHERE COD_AGENTE = :PCOD_AGENTE', [ABases.Codigo]);
Result := True;
finally
FDQuery.Free;
end;
end;
function TBaseDAO.Inserir(ABases: TBase): Boolean;
var
FDQuery : TFDQuery;
begin
try
Result := False;
FDQuery := FConexao.ReturnQuery;
FDQuery.ExecSQL('INSERT INTO ' + TABLENAME + '(COD_AGENTE, DES_RAZAO_SOCIAL, NOM_FANTASIA, DES_TIPO_DOC, NUM_CNPJ, NUM_IE, ' +
'NUM_IEST, NUM_IM, COD_CNAE, COD_CRT, NUM_CNH, DES_CATEGORIA_CNH, DAT_VALIDADE_CNH, DES_PAGINA, COD_STATUS, ' +
'DES_OBSERVACAO, DAT_CADASTRO, DAT_ALTERACAO, VAL_VERBA, DES_TIPO_CONTA, COD_BANCO, COD_AGENCIA, NUM_CONTA, ' +
'NOM_FAVORECIDO, NUM_CPF_CNPJ_FAVORECIDO, DES_FORMA_PAGAMENTO, COD_CENTRO_CUSTO, COD_GRUPO) ' +
'VALUES ' +
'(:COD_AGENTE, :DES_RAZAO_SOCIAL, :NOM_FANTASIA, :DES_TIPO_DOC: CNPJ, :NUM_CNPJ, :NUM_IE, :NUM_IEST, ' +
':NUM_IM, :COD_CNAE, :COD_CRT, :NUM_CNH, :DES_CATEGORIA_CNH, :DAT_VALIDADE_CNH, :DES_PAGINA, :COD_STATUS, ' +
':DES_OBSERVACAO, :DAT_CADASTRO, :DAT_ALTERACAO, :VAL_VERBA, :DES_TIPO_CONTA, :COD_BANCO, :COD_AGENCIA, ' +
':NUM_CONTA, :NOM_FAVORECIDO, :NUM_CPF_CNPJ_FAVORECIDO, :DES_FORMA_PAGAMENTO, :COD_CENTRO_CUSTO, :COD_GRUPO);',
[ABases.Codigo, ABases.Nome, ABases.Alias, ABases.TipoDoc, ABases.CPFCNPJ, ABases.RGIE, ABases.IE_ST, ABases.IM,
ABases.CNAE, ABases.CRT, ABases.NumCNH, ABases.CatergoriaCNH, ABases.ValidadeCNH, ABases.Pagina, ABases.Status,
ABases.Obs, ABases.DataCadastro, ABases.DataAlteracao, ABases.Verba, ABases.TipoConta, ABases.CodigoBanco,
ABases.NumeroAgencia, ABases.NumeroConta, ABases.NomeFavorecido, ABases.CPFCNPJFavorecido,
ABases.FormaPagamento, ABases.CentroCusto, ABases.GrupoVerba]);
Result := True;
finally
FDQuery.Free;
end;
end;
function TBaseDAO.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] = 'CODIGO' then
begin
FDQuery.SQL.Add('WHERE COD_AGENTE = :COD_AGENTE');
FDQuery.ParamByName('PCOD_AGENTE').AsInteger := aParam[1];
end;
if aParam[0] = 'NOME' then
begin
FDQuery.SQL.Add('WHERE DES_RAZAO_SOCIAL LIKE :DES_RAZAO_SOCIAL');
FDQuery.ParamByName('DES_RAZAO_SOCIAL').AsString := aParam[1];
end;
if aParam[0] = 'ALIAS' then
begin
FDQuery.SQL.Add('WHERE NOM_FANTASIA LIKE :NOM_FANTASIA');
FDQuery.ParamByName('NOM_FANTASIA').AsString := aParam[1];
end;
if aParam[0] = 'CNPJ' then
begin
FDQuery.SQL.Add('WHERE NUM_CNPJ = :NUM_CNPJ');
FDQuery.ParamByName('NUM_CNPJ').AsString := aParam[1];
end;
if aParam[0] = 'FILTRO' then
begin
FDQuery.SQL.Add('WHERE ' + aParam[1]);
end;
if aParam[0] = 'APOIO' then
begin
FDQuery.SQL.Clear;
FDQuery.SQL.Add('SELECT ' + aParam[1] + ' FROM ' + TABLENAME + ' ' + aParam[2]);
end;
FDQuery.Open();
Result := FDQuery;
end;
end.
|
unit jc.Utils;
interface
uses
Windows, Messages, SysUtils, Classes;
function getPathApplication(ACustomDir: String = '';
ACustomFile: String = ''): String;
Function getStringNameEXE(const ACustomFile: String = ''): String;
Function ExtractName(const Filename: String): String;
function getPcName: string;
function GePcUserName: string;
function getOSPlatform: String;
function ReadString(SymbolSeparator: String; Value: String): String;
function RemoveString(SymbolSeparator: String; Value: String): String;
function getNumberSymbolSeparator(Asep, AValue: string): Integer;
function getDomain(AEmail: String): String;
function getHostName(AEmail: String): String;
function LineCount(AFile: String; AFlag: String = ''): Integer;
function SymbolCount(const subtext: string; Text: string): Integer;
Function NoMask(Value: string): string; overload;
function UpperFirstLetter(sNome: String): string;
implementation
uses
System.RegularExpressions;
function getPathApplication(ACustomDir: String = ''; ACustomFile: String = ''): String;
{$IFDEF MSWINDOWS}
var
Path: array[0..MAX_PATH - 1] of Char;
PathStr: string;
{$ENDIF MSWINDOWS}
begin
{$IFDEF MSWINDOWS}
SetString(PathStr, Path, GetModuleFileName(HInstance, Path, SizeOf(Path)));
result := ExtractFilePath(PathStr);
{$ENDIF MSWINDOWS}
{$IFDEF POSIX}
result := IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0)));
{$ENDIF POSIX}
if trim(ACustomDir) <> '' then
begin
if not DirectoryExists(result + ACustomDir) then
CreateDir(result + ACustomDir);
result := result + ACustomDir + PathDelim;
end;
if trim(ACustomFile) <> '' then
begin
result := result + ACustomFile;
end;
end;
Function getStringNameEXE(const ACustomFile: String = ''): String;
var
aExt : String;
aPos : Integer;
aExeName : String;
begin
if trim(ACustomFile) = '' then
aExeName := ParamStr(0)
else
aExeName := ACustomFile;
aExt := ExtractFileExt(aExeName);
Result := ExtractFileName(aExeName);
if aExt <> '' then
begin
aPos := Pos(aExt, Result);
if aPos > 0 then
begin
Delete(Result,aPos, Length(aExt));
end;
end;
end;
Function ExtractName(const Filename: String): String;
var
aExt : String;
aPos : Integer;
begin
aExt := ExtractFileExt(Filename);
Result := ExtractFileName(Filename);
if aExt <> '' then
begin
aPos := Pos(aExt,Result);
if aPos > 0 then
begin
Delete(Result,aPos, Length(aExt));
end;
end;
end;
function LineCount(AFile: String; AFlag: String): Integer;
var
f: TextFile;
sLinha: String;
sFlag: String;
CountLine: Integer;
begin
CountLine := 0;
AssignFile(f, AFile);
try
Reset(f);
While not Eof(f) do
begin
Readln(f, sLinha);
if not AFlag.IsEmpty then
begin
sflag := copy(sLinha, 1, AFlag.Length);
if sFlag = AFlag then
Inc(CountLine);
end
else
Inc(CountLine);
end;
finally
CloseFile(f);
end;
result := CountLine;
End;
function SymbolCount(const subtext: string; Text: string): Integer;
begin
if (Length(subtext) = 0) or (Length(Text) = 0) or (Pos(subtext, Text) = 0)
then
Result := 0
else
Result := (Length(Text) - Length(StringReplace(Text, subtext, '',
[rfReplaceAll]))) div Length(subtext);
end;
function NoMask(Value: String): string;
var
i: Integer;
xStr : String;
begin
xStr := '';
for i := 1 to Length(Value) do
begin
if (Pos(Copy(Value, i, 1), '/-.)(,"{}[]') = 0) then
xStr := xStr + Value[i];
end;
Result:= xStr;
end;
function ReadString(SymbolSeparator: String; Value: String): String;
begin
Result := Copy(Value, 1, pos(SymbolSeparator, Value)-1);
end;
function RemoveString(SymbolSeparator: String; Value: String): String;
begin
Delete(Value, 1, pos(SymbolSeparator, Value));
result := Value;
end;
function getNumberSymbolSeparator(Asep, AValue: string): Integer;
begin
result := TRegEx.Matches(AValue, Asep).Count;
end;
function getDomain(AEmail: String): String;
begin
result := Copy (AEmail, Pos ('@', AEmail) + 1, Length(AEmail));
end;
function getHostName(AEmail: String): String;
var
lHost: string;
begin
lHost := Copy (AEmail, Pos ('@', AEmail) + 1, Length(AEmail));
result := trim( LowerCase( Copy(lHost, 1, pos('.', lHost)-1) ) );
end;
function UpperFirstLetter(sNome: String): string;
const
excecao: array[0..5] of string = ('da', 'de', 'do', 'das', 'dos', 'e');
var
tamanho, j: integer;
i: byte;
begin
Result := AnsiLowerCase(sNome);
tamanho := Length(Result);
for j := 1 to tamanho do
if (j = 1) or ((j>1) and (Result[j-1]=Chr(32))) then
Result[j] := AnsiUpperCase(Result[j])[1];
for i := 0 to Length(excecao)-1 do
result:= StringReplace(result,excecao[i],excecao[i],[rfReplaceAll, rfIgnoreCase]);
end;
function getPcName: string;
var
buffer:array[0..MAX_COMPUTERNAME_LENGTH+1] of Char;
length:Cardinal;
begin
length := MAX_COMPUTERNAME_LENGTH+1;
GetComputerName(@buffer, length);
getPcName := buffer;
end;
function GePcUserName: string;
var
Size: DWord;
begin
Size := 1024;
SetLength(result, Size);
GetUserName(PChar(result), Size);
SetLength(result, Size - 1);
end;
function getOSPlatform: String;
const
PROCESSOR_ARCHITECTURE_INTEL = $0000;
PROCESSOR_ARCHITECTURE_IA64 = $0006;
PROCESSOR_ARCHITECTURE_AMD64 = $0009;
PROCESSOR_ARCHITECTURE_UNKNOWN = $FFFF;
var
xSysInfo: TSystemInfo;
begin
GetNativeSystemInfo(xSysInfo);
case xSysInfo.wProcessorArchitecture of
PROCESSOR_ARCHITECTURE_AMD64, PROCESSOR_ARCHITECTURE_IA64:
Result := 'x64';
else
Result := 'x86';
end;
end;
end.
|
unit Newspapers;
interface
uses
ModelServerCache, CacheAgent, Kernel;
const
tidCachePath_Newspapers = 'Newspapers\';
type
TNewspaper =
class
private
fName : string;
fTown : TTown;
public
property Name : string read fName write fName;
property Town : TTown read fTown write fTown;
end;
type
TNewspaperCacheAgent =
class( TCacheAgent )
public
class function GetPath ( Obj : TObject; kind, info : integer ) : string; override;
class function GetCache( Obj : TObject; kind, info : integer; update : boolean ) : TObjectCache; override;
end;
procedure RegisterCachers;
implementation
// TNewspaperCacheAgent
class function TNewspaperCacheAgent.GetPath( Obj : TObject; kind, info : integer ) : string;
begin
result := tidCachePath_Newspapers + TNewspaper(Obj).Name + '.five';
end;
class function TNewspaperCacheAgent.GetCache( Obj : TObject; kind, info : integer; update : boolean ) : TObjectCache;
begin
result := inherited GetCache( Obj, kind, info, update );
result.WriteString( 'Name', TNewspaper(Obj).Name );
if TNewspaper(Obj).Town <> nil
then result.WriteString( 'TownName', TNewspaper(Obj).Town.Name );
end;
// RegisterCachers
procedure RegisterCachers;
begin
RegisterCacher( TNewspaper.ClassName, TNewspaperCacheAgent );
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_UITransition
* Implements UI transitions (fades, etc)
***********************************************************************************************************************
}
Unit TERRA_UITransition;
{$I terra.inc}
Interface
Uses {$IFDEF USEDEBUGUNIT}TERRA_Debug,{$ENDIF}
TERRA_String, TERRA_Utils, TERRA_Math, TERRA_Vector2D, TERRA_Vector3D, TERRA_Texture, TERRA_Resource,
{$IFDEF POSTPROCESSING}TERRA_ScreenFX, {$ENDIF}
TERRA_Image, TERRA_Color, TERRA_Matrix4x4, TERRA_Matrix3x3, TERRA_VertexFormat;
Const
FadeVertexFormat = [vertexFormatPosition, vertexFormatUV0];
Type
FadeCallback = Procedure(Arg:Pointer); CDecl;
{ FadeVertex = Packed Record
Position:Vector2D;
UV:Vector2D;
End;}
UITransition = Class(TERRAObject)
Protected
_ID:Cardinal;
_Time:Cardinal;
_Duration:Integer;
_Delay:Integer;
_Active:Boolean;
_Running:Boolean;
_CallOnStart:Boolean;
_Callback:FadeCallback;
_Arg:Pointer;
_EaseType:Integer;
_FinishValue:Single;
_Transform:Matrix3x3;
_FadeVertices:VertexData;
Procedure Render(Alpha:Single); Virtual; Abstract;
Procedure InitVertices(OfsX, OfsY:Single);
Public
Function Update:Boolean;
Procedure SetCallback(Callback:FadeCallback; UserData:Pointer = Nil; OnStart:Boolean=False);
Procedure Release; Override;
Property FinishValue:Single Read _FinishValue Write _FinishValue;
Property Duration:Integer Read _Duration;
Property ID:Cardinal Read _ID;
Property EaseType:Integer Read _EaseType Write _EaseType;
Property Transform:Matrix3x3 Read _Transform Write _Transform;
End;
UIFade = Class(UITransition)
Protected
_FadeTexture:Texture;
_FadeOut:Boolean;
Procedure Render(Alpha:Single); Override;
Public
Color:TERRA_Color.Color;
Constructor Create(FadeTexture:Texture; Duration, Delay:Cardinal; Invert:Boolean);
End;
UISlide = Class(UITransition)
Protected
_Direction:Vector2D;
_Texture:Texture;
Procedure Render(Alpha:Single); Override;
Public
Constructor Create(Direction:Vector2D; Duration, Delay:Cardinal);
Procedure Release; Override;
End;
Implementation
Uses TERRA_OS, TERRA_ResourceManager, TERRA_GraphicsManager, TERRA_Renderer, TERRA_Tween, TERRA_UI;
Var
_FadeShader:ShaderInterface;
_SlideShader:ShaderInterface;
Function GetShader_UIFade:TERRAString;
Var
S:TERRAString;
Procedure Line(S2:TERRAString); Begin S := S + S2 + crLf; End;
Begin
S := '';
Line('vertex {');
Line(' attribute vec4 terra_position;');
Line(' attribute vec4 terra_UV0;');
Line(' uniform mat4 projectionMatrix;');
Line(' varying mediump vec4 texCoord;');
Line('void main() {');
Line(' texCoord = terra_UV0;');
Line(' gl_Position = projectionMatrix * terra_position;}');
Line('}');
Line('fragment {');
Line(' uniform sampler2D texture;');
Line(' uniform highp float alpha;');
Line(' uniform lowp vec4 fadeColor;');
Line(' varying mediump vec4 texCoord;');
Line(' void main() {');
Line(' highp float t = texture2D(texture, texCoord.xy).a;');
Line(' highp float p; if (t<alpha) p = 0.0; else p = 1.0;');
Line(' gl_FragColor = vec4(fadeColor.rgb, p);}');
Line('}');
Result := S;
End;
Function GetShader_UISlide:TERRAString;
Var
S:TERRAString;
Procedure Line(S2:TERRAString); Begin S := S + S2 + crLf; End;
Begin
S := '';
Line('vertex {');
Line(' attribute vec4 terra_position;');
Line(' attribute vec4 terra_UV0;');
Line(' uniform mat4 projectionMatrix;');
Line(' varying mediump vec4 texCoord;');
Line('void main() {');
Line(' texCoord = terra_UV0;');
Line(' gl_Position = projectionMatrix * terra_position;}');
Line('}');
Line('fragment {');
Line(' uniform sampler2D texture;');
Line(' varying mediump vec4 texCoord;');
Line(' void main() {');
Line(' highp vec4 p = texture2D(texture, texCoord.xy);');
Line(' gl_FragColor = p;}');
Line('}');
Result := S;
End;
{ UITransition }
Procedure UITransition.InitVertices(OfsX, OfsY:Single);
Var
W,H:Single;
P:Vector2D;
I:Integer;
Begin
W := UIManager.Instance.Width;
H := UIManager.Instance.Height;
If (_FadeVertices = Nil) Then
_FadeVertices := VertexData.Create(FadeVertexFormat, 6);
_FadeVertices.SetVector2D(0, vertexUV0, VectorCreate2D(0.0, 0.0));
_FadeVertices.SetVector2D(1, vertexUV0, VectorCreate2D(0.0, 1.0));
_FadeVertices.SetVector2D(2, vertexUV0, VectorCreate2D(1.0, 1.0));
_FadeVertices.SetVector2D(4, vertexUV0, VectorCreate2D(1.0, 0.0));
_FadeVertices.SetVector3D(0, vertexPosition, VectorCreate(OfsX, OfsY, 0.0));
_FadeVertices.SetVector3D(1, vertexPosition, VectorCreate(OfsX, OfsY + H, 0.0));
_FadeVertices.SetVector3D(2, vertexPosition, VectorCreate(OfsX + W, OfsY + H, 0.0));
_FadeVertices.SetVector3D(4, vertexPosition, VectorCreate(OfsX + W, OfsY, 0.0));
_FadeVertices.CopyVertex(2, 3);
_FadeVertices.CopyVertex(0, 5);
For I:=0 To 5 Do
Begin
_FadeVertices.GetVector2D(I, vertexPosition, P);
P := _Transform.Transform(P);
_FadeVertices.SetVector3D(I, vertexPosition, VectorCreate(P.X, P.Y, 0.0));
End;
End;
Procedure UITransition.SetCallback(Callback:FadeCallback; UserData:Pointer = Nil; OnStart:Boolean=False);
Begin
_Callback := Callback;
_Arg := UserData;
_CallOnStart := OnStart;
End;
Procedure UITransition.Release;
Begin
ReleaseObject(_FadeVertices);
End;
Function UITransition.Update:Boolean;
Var
Alpha:Single;
Begin
{$IFDEF DISABLETRANSITIONS}
_Callback(_Arg);
Result := False;
Exit;
{$ENDIF}
If Not _Running Then
Begin
_Running := True;
_Time := Application.GetTime + _Delay;
If (_CallOnStart) And (Assigned(_Callback)) Then
_Callback(_Arg);
End;
Alpha := Application.GetTime;
If (Alpha>=_Time) Then
Begin
Alpha := Alpha - _Time;
Alpha := Alpha / _Duration;
If (Alpha>1.0) Then
Alpha := 1.0;
End Else
Alpha := 0.0;
If (Alpha>=0.0) And (Alpha<_FinishValue) Then
Begin
_Active := True;
Result := True;
Render(Alpha);
End Else
Begin
Render(Alpha);
If (_Active) Then
Begin
_Active := False;
If (Not _CallOnStart) And (Assigned(_Callback)) Then
_Callback(_Arg);
Result := False;
End Else
Result := True;
End;
End;
{ UIFade }
Constructor UIFade.Create(FadeTexture:Texture; Duration, Delay:Cardinal; Invert:Boolean);
Begin
If Not Assigned(FadeTexture) Then
Exit;
FadeTexture.PreserveQuality := True;
_ID := Random(36242);
_FinishValue := 1.0;
_FadeTexture := FadeTexture;
_Duration := Duration;
_Delay := Delay;
_FadeOut := Invert;
_Active := False;
Color := ColorBlack;
If (Not Assigned(_FadeShader)) Then
Begin
_FadeShader := GraphicsManager.Instance.Renderer.CreateShader();
_FadeShader.Generate('ui_fade', GetShader_UIFade());
End;
End;
Procedure UIFade.Render(Alpha:Single);
Var
I:Integer;
X,Y:Single;
M:Matrix4x4;
StencilID:Byte;
Delta:Single;
_Shader:ShaderInterface;
Graphics:GraphicsManager;
Begin
If (_FadeOut) Then
Alpha := 1.0 - Alpha;
Delta := GetEase(Alpha, _EaseType);
Graphics := GraphicsManager.Instance;
If Not _FadeTexture.IsReady() Then
Exit;
_FadeTexture.Bind(0);
If (Not Graphics.Renderer.Features.Shaders.Avaliable) Then
Graphics.Renderer.SetBlendMode(blendZero)
Else
Graphics.Renderer.SetBlendMode(blendBlend);
_Shader := _FadeShader;
Graphics.Renderer.BindShader(_Shader);
//ShaderManager.Instance.Bind(_Shader);
M := Graphics.ProjectionMatrix;
Graphics.Renderer.SetModelMatrix(Matrix4x4Identity);
Graphics.Renderer.SetProjectionMatrix(M);
_Shader.SetIntegerUniform('texture', 0);
_Shader.SetFloatUniform('alpha', Delta);
_Shader.SetColorUniform('fadeColor', Color);
Self.InitVertices(0, 0);
Graphics.Renderer.SetDepthTest(False);
(*If (Not GraphicsManager.Instance.Renderer.Features.Shaders.Avaliable) Then
Begin
glMatrixMode(GL_PROJECTION);
glLoadMatrixf(@M);
glMatrixMode(GL_MODELVIEW);
M := Matrix4x4Identity;
glLoadMatrixf(@M);
glMatrixMode(GL_TEXTURE);
glLoadMatrixf(@M);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glVertexPointer(2, GL_FLOAT, SizeOf(FadeVertex), @FadeVertices[0].Position);
glTexCoordPointer(2, GL_FLOAT, SizeOf(FadeVertex), @FadeVertices[0].UV);
glEnable(GL_ALPHA_TEST);
glAlphaFunc(GL_GREATER, Delta);
StencilID := GraphicsManager.Instance.GenerateStencilID();
glEnable(GL_STENCIL_TEST);
glStencilFunc(GL_ALWAYS, StencilID, $FFFFFFFF);
glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE);
glColorMask(False, False, False, False);
End Else
{$ENDIF}
Begin
StencilID := 0;
glVertexAttribPointer(PositionHandle, 2, GL_FLOAT, False, 16, @(FadeVertices[0].Position));
glVertexAttribPointer(UVHandle, 2, GL_FLOAT, False, 16, @(FadeVertices[0].UV));
End;
glVertexAttribPointer(PositionHandle, 2, GL_FLOAT, False, 16, @(FadeVertices[0].Position));
glVertexAttribPointer(UVHandle, 2, GL_FLOAT, False, 16, @(FadeVertices[0].UV));
*);
{ Graphics.Renderer.SetSourceVertexSize(16);
Graphics.Renderer.SetAttributeSource('terra_position', vertexPosition, typeVector2D, @(FadeVertices[0].Position));
Graphics.Renderer.SetAttributeSource('terra_UV0', vertexUV0, typeVector2D, @(FadeVertices[0].UV));}
Graphics.Renderer.SetVertexSource(_FadeVertices);
Graphics.Renderer.DrawSource(renderTriangles, 6);
(*
If (Not GraphicsManager.Instance.Renderer.Features.Shaders.Avaliable) Then
Begin
TextureManager.Instance.WhiteTexture.Bind(0);
glColorMask(True, True, True, True);
glStencilFunc(GL_EQUAL, StencilID, $FFFFFFFF);
glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
glColor4f(Color.R/255, Color.G/255, Color.B/255, 1.0);
glDisable(GL_ALPHA_TEST);
GraphicsManager.Instance.Renderer.SetBlendMode(blendOne);
glDrawArrays(GL_TRIANGLES, 0, 6);
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glDisable(GL_STENCIL_TEST);
End;
*)
Graphics.Renderer.SetDepthTest(True);
End;
{ UISlide }
Constructor UISlide.Create(Direction: Vector2D; Duration,Delay: Cardinal);
Var
Src:Image;
Begin
_Direction := Direction;
_Duration := Duration;
_Delay := Delay;
_Active := False;
_FinishValue := 1.0;
_ID := Random(36242);
{$IFDEF POSTPROCESSING}
Src := GraphicsManager.Instance.ActiveViewport.GetRenderTarget(captureTargetColor).GetImage();
_Texture := Texture.Create(rtDynamic, 'ui_slide');
_Texture.InitFromSize(Src.Width, Src.Height, ColorWhite);
_Texture.UpdateRect(Src);
ReleaseObject(Src);
{$ELSE}
_Texture := Nil;
{$ENDIF}
If Not Assigned(_SlideShader) Then
Begin
_SlideShader := GraphicsManager.Instance.Renderer.CreateShader();
_SlideShader.Generate('ui_slide', GetShader_UISlide());
End;
End;
Procedure UISlide.Release;
Begin
ReleaseObject(_Texture);
Inherited;
End;
Procedure UISlide.Render(Alpha: Single);
Var
X,Y, W, H:Single;
_Shader:ShaderInterface;
StencilID:Integer;
Delta:Single;
Graphics:GraphicsManager;
I:Integer;
P:Vector2D;
Begin
Delta := GetEase(Alpha, _EaseType);
Graphics := GraphicsManager.Instance;
_Texture.Bind(0);
_Shader := _SlideShader;
Graphics.Renderer.BindShader(_Shader);
//ShaderManager.Instance.Bind(_Shader);
Graphics.Renderer.SetModelMatrix(Matrix4x4Identity);
Graphics.Renderer.SetProjectionMatrix(Graphics.ProjectionMatrix);
_Shader.SetIntegerUniform('texture', 0);
Graphics.Renderer.SetBlendMode(blendNone);
W := UIManager.Instance.Width;
H := UIManager.Instance.Height;
X := _Direction.X * Delta * W;
Y := _Direction.Y * Delta * H;
Self.InitVertices(X, Y);
Graphics.Renderer.SetDepthTest(False);
{ Graphics.Renderer.SetSourceVertexSize(16);
Graphics.Renderer.SetAttributeSource('terra_position', vertexPosition, typeVector2D, @(FadeVertices[0].Position));
Graphics.Renderer.SetAttributeSource('terra_UV0', vertexUV0, typeVector2D, @(FadeVertices[0].UV));}
Graphics.Renderer.SetVertexSource(_FadeVertices);
Graphics.Renderer.DrawSource(renderTriangles, 6);
Graphics.Renderer.SetDepthTest(True);
End;
End. |
{
classes that implement the player functions for FMOD library
written by Sebastian Kraft
sebastian_kraft@gmx.de
This software is free under the GNU Public License
(c)2005-2008
}
unit fmodplayer;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils,
{$ifdef win32} fmoddyn, {$endif}
{$ifdef unix} fmoddyn, {$endif}
fmodtypes, mediacol, playlist, playerclass, debug;
type
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
{ TFModPlayerClass }
TFModPlayerClass = class(TPlayerClass)
Private
Soundhandle: PFSoundStream;
Public
destructor destroy;
constructor create; override;
function play(index:integer):byte;override;
function play(url: string):byte;override;
procedure pause;override;
procedure stop;override;
function next_track:byte;override;
function prev_track:byte;override;
function Get_Stream_Status:TStreamStatus;override;
function Get_TrackLength:longint;override;
function Get_Time:longint;override;
function Get_TimeStr:string;override;
function Get_TimeRemainingStr: string; override;
function Get_FilePosition:longint;override;
function get_FileLength:longint;override;
procedure Set_Time(ms: longint);override;
procedure Set_FilePosition(fpos:longint);override;
procedure Set_Volume(vol:byte);override;
procedure Mute;override;
function Muted:boolean;override;
property CurrentTrack: Integer read GetCurrentTrack;
property playing: boolean read FPlaying;
property paused: boolean read FPaused;
property volume:byte read FVolume write Set_Volume;
property PlaybackMode: TPlaybackMode read FPlaybackMode;
end;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
implementation
uses functions;
var tmpp: PChar;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
destructor TFModPlayerClass.destroy;
var i:integer;
begin
fplaying:=false;
Playlist.Free;
end;
constructor TFModPlayerClass.create;
begin
inherited create;
end;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function TFModPlayerClass.play(index:integer):byte;
{startplay=0 -> succesful
startplay=1 -> file not found
startplay=2 -> soundcard init failed
startplay=3 -> index out of bounds
startplay=4 -> Last song in List}
var z: integer;
pPlaylistItem: pPlaylistItemClass;
begin
if (index<Playlist.ItemCount) and (index>=0) then begin
if (fplaying=true) then begin
if FSOUND_Stream_Stop(Soundhandle)=false then writeln('ERROR stop stream');
if FSOUND_Stream_Close(Soundhandle)=false then writeln('ERROR on closing stream');
fplaying:=false;
end;
if (fplaying=false) then begin
//FSOUND_Close;
{$ifdef linux}
if OutputMode = OSSOUT then begin
if FSOUND_SetOutput(FSOUND_OUTPUT_OSS) then writeln('Oss output openend') else writeln('failed opening oss output')
end
else begin
if FSOUND_SetOutput(FSOUND_OUTPUT_ALSA) then writeln('alsa output openend') else writeln('failed opening alsa output')
end;
{$endif}
if FSOUND_Init(44100, 32, 0)=true then begin
FPlaybackMode:=FILE_MODE;
DebugOutLn('playing -> '+playlist.items[index].path,0);
if (FileExists(playlist.items[index].path)) then
begin
tmpp:=StrAlloc(length(playlist.items[index].path)+1);
StrPCopy(tmpp,playlist.items[index].path);
// Open the stream
write(' openingstream... ');
Soundhandle:=FSOUND_Stream_Open(tmpp, FSOUND_MPEGACCURATE or FSOUND_NONBLOCKING {FSOUND_NORMAL}, 0, 0); //Fixes Bug when starting VBR files first, FSOUND_NORMAL is faster!!
z:=0;
repeat begin //Wait until it is loaded and ready
z:=FSOUND_Stream_GetOpenState(soundhandle);
end;
until (z=0) or (z=-3);
write(' ready... ');
if z = 0 then begin //If loading was succesful
write(' start playing... ');
FSOUND_Stream_Play (FSOUND_FREE,Soundhandle); // Start playing
DebugOutLn(' ready... ',0);
FSOUND_SetVolume(0, FVolume);
playlist.items[index].played:=true;
fplaying:=true;
result:=0;
FCurrentTrack:=index;
end
else
DebugOutLn(Format('error: can''t play file %d',[z]), 0);
end
else result:=1;
end
else result:=2;
end;
end
else begin
writeln('INTERNAL error: playlistindex out of bound');
Result:=3;
end;
end;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function TFModPlayerClass.play(url: string): byte;
{startplay=0 -> succesful
startplay=1 -> invalid stream URL
startplay=2 -> soundcard init failed}
var z: integer;
begin
if (fplaying=true) then begin
if FSOUND_Stream_Stop(Soundhandle)=false then writeln('ERROR stop stream');
if FSOUND_Stream_Close(Soundhandle)=false then writeln('ERROR on closing stream');
fplaying:=false;
end;
if (fplaying=false) then begin
//FSOUND_Close;
{$ifdef linux}
if OutputMode = OSSOUT then begin
if FSOUND_SetOutput(FSOUND_OUTPUT_OSS) then DebugOutLn('Oss output openend',0) else writeln('failed opening oss output')
end
else begin
if FSOUND_SetOutput(FSOUND_OUTPUT_ALSA) then DebugOutLn('alsa output openend',0) else writeln('failed opening alsa output')
end;
{$endif}
if FSOUND_Init(44100, 32, 0)=true then begin
FPlaybackMode:=STREAMING_MODE;
DebugOutLn('playing -> '+url,0);
tmpp:=StrAlloc(length(url)+1);
StrPCopy(tmpp,url);
// Open the stream
write(' openingstream... ');
Soundhandle:=FSOUND_Stream_Open(tmpp, FSOUND_NONBLOCKING, 0, 0);
end else result:=1;
end else result:=2;
end;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
procedure TFModPlayerClass.pause;
begin
if FSOUND_Getpaused(0)=false then
FSOUND_Setpaused(0, true)
else FSOUND_Setpaused(0, false);
fpaused:=FSOUND_Getpaused(0);
end;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
procedure TFModPlayerClass.stop;
begin
if fplaying=true then begin
FSOUND_Stream_Stop(Soundhandle);
FSOUND_Stream_Close(Soundhandle);
fplaying:=false;
FSOUND_Close;
// reset_random;
FCurrentTrack:=-1;
end;
end;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function TFModPlayerClass.prev_track: byte;
var r:byte;
begin
r:=127;
if fplaying then begin
if (FCurrentTrack<Playlist.ItemCount) and (FCurrentTrack>0) then begin
r:=play(FCurrentTrack-1);
end else
if (FCurrentTrack<Playlist.ItemCount) and (FCurrentTrack=0) then begin
r:=play(FCurrentTrack);
end;
end;
result:=r;
end;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function TFModPlayerClass.Get_Stream_Status: TStreamStatus;
var StreamStatus:TFSoundStreamNetStatus;
BufferUsed, Bitrate: integer;
Flags: Cardinal;
begin
if FSOUND_Stream_GetOpenState(Soundhandle)=0 then begin
FSOUND_Stream_Net_GetStatus(Soundhandle, StreamStatus, BufferUsed, Bitrate, Flags);
//writeln(BufferUsed);
case StreamStatus of
FSOUND_STREAM_NET_READY: Result:=STREAM_READY;
FSOUND_STREAM_NET_ERROR: Result:=STREAM_NOTFOUND;
FSOUND_STREAM_NET_CONNECTING: Result:=STREAM_BUFFERING;
FSOUND_STREAM_NET_BUFFERING:Result:=STREAM_BUFFERING;
FSOUND_STREAM_NET_NOTCONNECTED: Result:=STREAM_NOTFOUND;
end;
if Result=STREAM_READY then begin
FSOUND_Stream_Play (FSOUND_FREE,Soundhandle); // Start playing
FSOUND_SetVolume(0, volume);
fplaying:=true;
end else begin
write('error: can''t open stream');
end;
end else result:=STREAM_BUFFERING;
end;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function TFModPlayerClass.next_track: byte;
var r:byte;
begin
r:=127;
if fplaying then begin
if FCurrentTrack<Playlist.ItemCount-1 then begin
r:=play(CurrentTrack+1);
end;
end;
result:=r;
end;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
procedure TFModPlayerClass.mute;
begin
if FSOUND_GetMute(0)=false then FSOUND_SetMute(FSOUND_ALL, true) else FSOUND_SetMute(FSOUND_ALL, false);
end;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function TFModPlayerClass.Get_TrackLength:longint;
begin
if (Soundhandle<>nil) and (FSOUND_Stream_GetOpenState(soundhandle)=0) then begin
result:=FSOUND_Stream_GetLengthMs(Soundhandle);
end;
end;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function TFModPlayerClass.get_time: longint;
begin
if (Soundhandle<>nil) and (FSOUND_Stream_GetOpenState(soundhandle)=0) then begin
get_time:=FSOUND_Stream_GetTime(Soundhandle);
end;
end;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function TFModPlayerClass.get_timestr:string;
begin
if (Soundhandle<>nil) and (FSOUND_Stream_GetOpenState(soundhandle)=0) then begin
result:=MSecondsToFmtStr(FSOUND_Stream_GetTime(Soundhandle));
end;
end;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function TFModPlayerClass.Get_TimeRemainingStr: string;
begin
if (Soundhandle<>nil) and (FSOUND_Stream_GetOpenState(soundhandle)=0)
then
begin
result:= '-' + MSecondsToFmtStr(
FSOUND_Stream_GetLengthMs(Soundhandle) -
FSOUND_Stream_GetTime(Soundhandle));
end;
end;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function TFModPlayerClass.get_fileposition: longint;
begin
result:=(FSOUND_Stream_GetPosition(Soundhandle)*100) div FSOUND_Stream_GetLength(soundhandle);
end;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function TFModPlayerClass.get_filelength: longint;
begin
get_filelength:=FSOUND_Stream_GetLength(soundhandle);
end;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function TFModPlayerClass.muted: boolean;
begin
if FSOUND_GetMute(0)=true then result:=true else result:=false;
end;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
procedure TFModPlayerClass.set_time(ms: longint);
begin
if fplaying then FSOUND_Stream_SetTime(Soundhandle,ms);
end;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
procedure TFModPlayerClass.set_fileposition(fpos: longint);
begin
if fplaying then FSOUND_Stream_SetPosition(Soundhandle,(fpos*FSOUND_Stream_GetLength(soundhandle)) div 100);
end;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
procedure TFModPlayerClass.set_volume(vol: byte);
{set volume from 0 to 100}
var i:integer;
begin
FVolume:=vol;
i:=((vol*255) div 100);
FSOUND_SetVolume(0, i);
end;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
initialization
fmod_load('');
finalization
FMOD_Unload;
end.
|
unit UCTRLNoAccount;
{$mode delphi}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls,
Buttons, UCommon.UI, UCoreObjects;
type
{ TCTRLNoAccounts }
TCTRLNoAccounts = class(TApplicationForm)
btnGetAcc: TBitBtn;
lblGetFirstAccount: TLabel;
private
FPBalanceSummary : PBalanceSummary;
public
property BalanceSummary : PBalanceSummary read FPBalanceSummary write FPBalanceSummary;
procedure ActivateFirstTime; override;
end;
implementation
{$R *.lfm}
const
GNoAccountsText = 'No Accounts';
GHasAccountsText = 'You own %d accounts';
procedure TCTRLNoAccounts.ActivateFirstTime;
begin
case FPBalanceSummary^.TotalPASA of
0: lblGetFirstAccount.Caption := GNoAccountsText;
else lblGetFirstAccount.Caption := Format(GHasAccountsText, [FPBalanceSummary^.TotalPASA]);
end;
end;
end.
|
unit Pessoa;
interface
type
TPessoa = class
private
FIdade: Integer;
FNome: String;
FTelefone: String;
procedure SetIdade(const Value: Integer);
procedure SetNome(const Value: String);
procedure SetTelefone(const Value: String);
public
constructor Create;
property Nome : String read FNome write SetNome;
property Telefone : String read FTelefone write SetTelefone;
property Idade : Integer read FIdade write SetIdade;
end;
implementation
{ TPessoa }
constructor TPessoa.Create;
begin
FNome := 'Teste1';
FTelefone := '123456789';
FIdade := 12;
end;
procedure TPessoa.SetIdade(const Value: Integer);
begin
FIdade := Value;
end;
procedure TPessoa.SetNome(const Value: String);
begin
FNome := Value;
end;
procedure TPessoa.SetTelefone(const Value: String);
begin
FTelefone := Value;
end;
end.
|
unit TicklerGlobals;
interface
uses TicklerTypes, ffsUserTable;
var
CurrentUser : TffsUserRecord;
CurrentLend : TLenderInfoRecord;
GlobalZoom : integer;
CurrentSemaphore: Integer;
// User
procedure SetBackDoorUser;
procedure ClearCurrentUser;
function FormatZip(z:string):string;
procedure SetDocID(s:string);
function GetDocID:string;
implementation
uses TCWODT, ffsutils, sysutils;
var CurrDocID:string;
procedure SetDocID(s:string);
begin
CurrDocID := s;
end;
function GetDocID:string;
var x : integer;
begin
x := strtointdef(CurrDocID,0);
if x = 0 then
result := ''
else
begin
if not CurrentLend.DocidNo then
result := inttostr(x+1)
else
result := inttostr(x);
end;
end;
procedure SetBackDoorUser;
begin
fillchar(currentuser, sizeof(currentuser),0);
CurrentUser.PUserName := SysAdmin;
CurrentUser.PUserTable := true;
CurrentUser.PLenderGroups := true;
CurrentUser.PAccessGroups := true;
CurrentUser.PRealName := 'System Administrator';
end;
procedure ClearCurrentUser;
begin
fillchar(CurrentUser, sizeof(currentUser), 0);
CurrentUser.PUserGroup := 'INQUIRE';
CurrentUser.PUserName := 'NOONE';
end;
function FormatZip(z:string):string;
var s : string;
p : integer;
begin
s := z;
if length(s) > 5 then
begin
if length(s) = 6 then s := copy(s,1,5)
else
begin
p := pos('-',s);
if (p > 0) and (p <> 6) then delete(s,p,1);
p := pos('-',s);
if p = 0 then insert('-',s,6);
end;
end;
result := s;
end;
initialization
ClearCurrentUser;
GlobalZoom := 2; // 25%
end.
|
unit mmmReferencePharmaceuticalInformation;
{* Справочная фармацевтическая информация }
// Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\Medic\mmmReferencePharmaceuticalInformation.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "TmmmReferencePharmaceuticalInformation" MUID: (490C47190273)
{$Include w:\garant6x\implementation\Garant\nsDefine.inc}
interface
{$If NOT Defined(Admin) AND NOT Defined(Monitorings)}
uses
l3IntfUses
, mmmTree
, l3Tree_TLB
;
type
TmmmReferencePharmaceuticalInformation = class(TmmmTree)
{* Справочная фармацевтическая информация }
protected
function MakeRoot: Il3RootNode; override;
{* Создаёт корень дерева }
end;//TmmmReferencePharmaceuticalInformation
{$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings)
implementation
{$If NOT Defined(Admin) AND NOT Defined(Monitorings)}
uses
l3ImplUses
, l3StringIDEx
, nsTypes
//#UC START# *490C47190273impl_uses*
//#UC END# *490C47190273impl_uses*
;
const
{* Локализуемые строки Local }
str_mmmiHelp: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'mmmiHelp'; rValue : 'Руководство пользователя');
{* 'Руководство пользователя' }
function TmmmReferencePharmaceuticalInformation.MakeRoot: Il3RootNode;
{* Создаёт корень дерева }
//#UC START# *4909EF6E0361_490C47190273_var*
const
c_Documents: array [0..3] of Longint = (52390025, 52390014, 52390003, 52390001);
//#UC END# *4909EF6E0361_490C47190273_var*
begin
//#UC START# *4909EF6E0361_490C47190273_impl*
Result := inherited MakeRoot;
nsAddMainMenuDocumentItem(Result, Ord(ns_mntDocument), c_Documents);
//AddItem(Result, ns_mntHelp, str_mmmiHelp);
//#UC END# *4909EF6E0361_490C47190273_impl*
end;//TmmmReferencePharmaceuticalInformation.MakeRoot
initialization
str_mmmiHelp.Init;
{* Инициализация str_mmmiHelp }
{$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings)
end.
|
unit U_SortClass;
interface
uses
U_Sort.DTO.Retangle, U_SortInterface,
FMX.Layouts, System.UITypes, System.SysUtils, FMX.Forms, System.Classes;
type
TSortClass = class(TInterfacedObject, ISortInterface)
private
const
fQtdRet : Integer = 50;
var
fCor : Cardinal;
fCorBorda : Cardinal;
fCorMudanca : Cardinal;
fLargura : Integer;
fLarguraBorda : Integer;
fRaio : Integer;
fTempo : Integer;
fNomes : TStringList;
fFinalizado : Boolean;
procedure criaRetangulo(posicao, posX, altura : integer); Overload;
procedure criaRetangulo(nome : String; altura : integer); Overload;
procedure preencheTela();
procedure colorChange(ret01, ret02 : TRetangulo);
protected
var
fOwner : TLayout;
function algoritmo() : Boolean; Virtual; Abstract;
function findRectangle(posicao : Integer) : TRetangulo;
function getDelay(aTempo : Single) : Integer;
procedure troca(ret01, ret02 : TRetangulo);
property Distancia : Integer read fLargura;
public
constructor Create(Owner : TLayout; delay : Single);
procedure sort();
property Finalizado : boolean read fFinalizado write fFinalizado;
end;
implementation
{ TSortClass }
procedure TSortClass.colorChange(ret01, ret02 : TRetangulo);
begin
if ret01.Fill.Color = fCor then
begin
ret01.Fill.Color := fCorMudanca;
ret02.Fill.Color := fCorMudanca;
end else begin
ret01.Fill.Color := fCor;
ret02.Fill.Color := fCor;
end;
end;
constructor TSortClass.Create(Owner : TLayout; delay : Single);
var
I: Integer;
begin
inherited Create();
Self.fFinalizado := False;
fNomes := TStringList.Create();
fNomes.Clear;
fOwner := Owner;
fCor := TAlphaColors.Hotpink;
fCorBorda := TAlphaColors.Black;
fCorMudanca := TAlphaColors.Skyblue;
fLarguraBorda := 1;
fLargura := trunc(Owner.Size.Width / fQtdRet);
fRaio := trunc(fLargura * 0.20);
fTempo := getDelay(delay);
for I := 0 to fOwner.ControlsCount - 1 do
begin
fNomes.Add(fOwner.Controls[I].Name);
end;
preencheTela();
end;
procedure TSortClass.criaRetangulo(nome : String; altura: integer);
var
ret : TRetangulo;
begin
ret := TRetangulo(fOwner.FindComponent(nome));
ret.Fill.Color := fCor;
ret.Height := altura;
ret.Position.Y := fOwner.Height - altura;
end;
procedure TSortClass.criaRetangulo(posicao, posX, altura: integer);
var
retangulo : TRetangulo;
begin
retangulo := TRetangulo.Create(fOwner);
retangulo.Fill.Color := fCor;
retangulo.Stroke.Color := fCorBorda;
retangulo.Height := altura;
retangulo.Position.X := posX;
retangulo.Position.Y := fOwner.Height - altura;
retangulo.Width := fLargura;
retangulo.XRadius := fRaio;
retangulo.YRadius := fRaio;
retangulo.Name := 'Ret' + posX.ToString;
retangulo.Posicao := posicao;
fOwner.AddObject(retangulo);
end;
function TSortClass.findRectangle(posicao: Integer): TRetangulo;
begin
Result := TRetangulo(fOwner.FindComponent('Ret' + intToStr(posicao * fLargura)));
end;
function TSortClass.getDelay(aTempo: Single): Integer;
begin
Result := trunc(1000 / (2 * aTempo));
end;
procedure TSortClass.preencheTela;
var
posX : Integer;
tamanho : Integer;
i : Integer;
begin
Randomize;
if fNomes.Count <= 0 then
begin
posX := 0;
for i := 1 to fQtdRet do
begin
repeat
tamanho := Random(490) + 10
until ((tamanho mod 5) = 0);
criaRetangulo(i - 1, posX, tamanho);
inc(posX, fLargura);
end;
end else begin
for i := 0 to fNomes.Count - 1 do
begin
repeat
tamanho := Random(490) + 10
until ((tamanho mod 5) = 0);
criaRetangulo(fNomes.Strings[i], tamanho);
end;
end;
Application.ProcessMessages;
end;
procedure TSortClass.sort;
var
alg : TThread;
begin
Self.fFinalizado := False;
alg := TThread.CreateAnonymousThread(
procedure
begin
Self.fFinalizado := Self.algoritmo();
end);
alg.Start();
end;
procedure TSortClass.troca(ret01, ret02 : TRetangulo);
var
aux : Single;
begin
try
colorChange(ret01, ret02);
Application.ProcessMessages;
Sleep(fTempo);
aux := ret01.Height;
ret01.Height := ret02.Height;
ret02.Height := aux;
ret01.Position.Y := fOwner.Height - ret01.Height;
ret02.Position.Y := fOwner.Height - ret02.Height;
ret01.Repaint;
ret02.Repaint;
fOwner.Repaint;
finally
Sleep(fTempo);
colorChange(ret01, ret02);
Application.ProcessMessages;
end;
end;
end.
|
unit uMap;
interface
uses
Windows, SysUtils, StrUtils, Classes, Graphics, Dialogs, Controls,
// selfmade units
uImage, uTileMask, uActors, uMapCommon, uNPC, uSigns, uCommon, uFOVHeader,
uHint, UItems, Ammunition;
const
arsize = 511;
ScrWd = 800;
ScrHg = 600;
type
TLightSource = class(THODObject)
private
FXpos: Word;
FYpos: Word;
FLightRadius: Word;
FActor: TActor;
procedure SetLightRadius(const Value: Word);
procedure SetXpos(const Value: Word);
procedure SetYpos(const Value: Word);
procedure SetPosition(const Value: TPoint);
function GetPosition: TPoint;
public
//** Конструктор.
constructor Create(AX, AY, ARadius: word; Actor: TActor = nil);
procedure Edit(AX, AY, ARadius: word);
property Xpos: Word read FXpos write SetXpos;
property Ypos: Word read FYpos write SetYpos;
property Position: TPoint read GetPosition write SetPosition;
property LightRadius: Word read FLightRadius write SetLightRadius;
procedure UpdateFromActor();
end;
TLights = class(TObjList)
private
function GetItems(Index: Integer): TLightSource;
procedure SetItems(Index: Integer; const Value: TLightSource);
public
property Items[Index: Integer]: TLightSource read GetItems write SetItems; default;
end;
TMap = class(THODObject)
private
FFovMap: FOV_MAP;
FLights: TLights;
FTilemask: TTilemask;
FWidth, FHeight: Word;
FImage: TImage;
FHintBack: TBitmap;
procedure SetHeight(const Value: Word);
procedure SetWidth(const Value: Word);
procedure LoadProjectiles();
function GetMapDcr(AX, AY: Word): Cardinal;
function GetMapIdx(AX, AY: Word): Cardinal;
function GetMapObj(AX, AY: Word): Cardinal;
procedure SetMapDcr(AX, AY: Word; const Value: Cardinal);
procedure SetMapObj(AX, AY: Word; const Value: Cardinal);
public
Hint: THint;
SZ, OD: TPoint;
Shots, Fireball, Stun: TImages;
List: TStringList;
HeroImage: TBitMap;
MapMem: TStringList;
MapTiles, MapDecors, MapObjects: array[0..arsize] of TBitMap;
// MapIdx, MapDcr, MapObj, MapItm: array[0..1023, 0..1023] of Cardinal;
MapDyn: array[0..1023, 0..1023] of TActor;
MapViz, FOVViz: array[0..1023, 0..1023] of Boolean;
Cell: array[0..32, 0..32, 0..3] of Word;
MapItems: array[0..1023, 0..1023] of TMapItem;
TheItems: TMapItemList;
//** Конструктор.
constructor Create;
destructor Destroy; override;
function CellMask(x, y: Word; Mode: ncellmode): Boolean;
function getpcell(ax, ay: integer): pFOV_CELL;
function HeroFovRadius(): Integer;
function IsCellFlagOn(AX, AY, AF: Word): Boolean;
function IsHeroCell(x, y: Word): Boolean;
function LoadCell(const FileName: string): TPoint;
function LoadSaved(): Boolean;
function SetupMapSave(W, H, ID, Seed, Kind: Integer): Integer;
procedure AddCell(const FileName: string; ax, ay: Integer);
procedure AddRoom(const S: string);
procedure Clear;
procedure ClearCell;
procedure ClearGraphics;
procedure Display;
procedure Gen(W, H, ID, Seed: Integer);
procedure GenBeaRLib(W, H, ID, Seed: Integer);
procedure HorzMirrCell();
procedure Load(const FileName: string);
procedure LoadGraphics(const ADT: string);
function PutObject(X, Y, obj: Word): Boolean;
procedure DrawHints();
procedure RenderMiniMap;
procedure SetCellFlag(AX, AY, AF: Integer);
procedure SetMapIdx(AX, AY: Word; const Idx: Cardinal);
function SetupHero(X, Y: Word; IsLoad: Boolean = False): Boolean;
procedure VertMirrCell();
property Height: Word read FHeight write SetHeight;
property Lights: TLights read FLights;
property Tilemask: TTilemask read FTilemask;
property Width: Word read FWidth write SetWidth;
function GetMapItem(AX, AY: Word; out MapItem: TMapItem): Boolean;
function GetMapItemBaseId(AX, AY: Word): Integer;
function PutMapItem(AX, AY: Word; BaseItemID: Integer;
APref: TPrefix = NoPrefix; ASuff: TSuffix = NoSuffix): Boolean; overload;
function PutMapItem(AX, AY: Word; Item: TInvItem): Boolean; overload;
property MapIdx[AX, AY: Word]: Cardinal read GetMapIdx write SetMapIdx;
property MapDcr[AX, AY: Word]: Cardinal read GetMapDcr write SetMapDcr;
property MapObj[AX, AY: Word]: Cardinal read GetMapObj write SetMapObj;
//property MapItm[AX, AY: Word]: Cardinal read GetMapItm write SetMapItm;
end;
//type
// TBeaRLibMap = array of Char;
//procedure GenMap(x, y, ID: Integer; var A: TBeaRLibMap; S: Integer); stdcall;
//external 'BeaRLibMG.dll';
//
//function SetRandSeed(Seed: Integer; doSet: Boolean): Integer; stdcall;
//external 'BeaRLibMG.dll';
var
Map: TMap;
implementation
uses
//delphi units
Math, ImgList,
// BearLib MapGen
uBeaRLibMG, uMapGenerator,
// own units
// common
uVars, uUtils, uAdvMap,
// specific
uSCR, uMain, uBox, uScript, uInvBox, PCImage, uAdvStr, uColors, uGUI, uScene,
uIni, uFog, uEffects, uTest, uAlerts, uSkillTree, uSceneSkill;
type
TGenMapProc = procedure(x, y, ID: Integer; var A: TBeaRLibMap; S: Integer); stdcall;
TSetRandSeedFunc = function (Seed: Integer; doSet: Boolean): Integer; stdcall;
var
DR: TBeaRLibMap;
procedure GenMap_dyn(W, H, ID, Seed: Integer);
var
GenMapProc: TGenMapProc;
SetRandSeedFunc: TSetRandSeedFunc;
HLib: THandle;
begin
HLib := 0;
try
HLib := LoadLibrary('BeaRLibMG.dll');
if HLib > HINSTANCE_ERROR then
begin
SetRandSeedFunc := GetProcAddress(HLib, 'SetRandSeed');
if not Assigned(SetRandSeedFunc) then
ShowMessage('Library Method not found');
GenMapProc := GetProcAddress(HLib, 'GenMap');
if Assigned(GenMapProc) then
begin
SetRandSeedFunc(Seed, True);
GenMapProc(W, H, ID, DR, W * H);
end
else
ShowMessage('Library Method not found');
end
else
ShowMessage('Can not load library BeaRLibMG.dll');
except
if HLib > HINSTANCE_ERROR then
FreeLibrary(HLib);
end;
if HLib > HINSTANCE_ERROR then
FreeLibrary(HLib);
end;
{ TMap }
procedure TMap.SetCellFlag(AX, AY, AF: Integer);
begin
if Length(FFovMap.Cells) > ay * Width + ax then
getpcell(AX, AY)^.Flags := AF;
end;
procedure TMap.SetHeight(const Value: Word);
begin
FHeight := Value;
VM.SetInt('Map.Y', Value);
VM.SetInt('Hero.Map.' + VM.GetStr('Hero.Dungeon') + '.Height', Value);
end;
procedure TMap.SetMapDcr(AX, AY: Word; const Value: Cardinal);
begin
Layer[lyDcr][AX, AY] := Value;
end;
procedure TMap.SetMapIdx(AX, AY: Word; const Idx: Cardinal);
begin
Layer[lyMap][AX, AY] := idx;
if CellMask(AX, AY, cmViewable) then
SetCellFlag(AX, AY, FOV_CELL_VISIBLE)
else
SetCellFlag(AX, AY, FOV_CELL_OPAQUE);
end;
procedure TMap.SetMapObj(AX, AY: Word; const Value: Cardinal);
begin
PutObject(AX, AY, Value);
end;
function TMap.SetupHero(X, Y: Word; IsLoad: Boolean = False): Boolean;
begin
Result := IsLoad;
if not IsLoad then
Result := PutObject(x, y, 55);
if Result then
begin
VM.SetInt('Hero.X', x);
VM.SetInt('Hero.Y', y);
FLights[0].Edit(x, y, HeroFovRadius);
end;
end;
function TMap.SetupMapSave(W, H, ID, Seed, Kind: Integer): Integer;
var
s: string;
x, y: Integer;
// cell: pfov_cell;
begin
Result := RandSeed;
Width := W;
Height := H;
VM.SetInt('Map.Width', Width);
VM.SetInt('Map.Height', Height);
FFovMap.cells := nil; // just in case, help doesn't describe how setlength clears array
SetLength(FFovMap.cells, W * H);
FFovMap.width := W;
FFovMap.height := H;
for y := 0 to H - 1 do
for x := 0 to W - 1 do
SetCellFlag(x, y, FOV_CELL_VISIBLE);
S := 'Hero.Map.' + VM.GetStr('Hero.Dungeon');
VM.SetInt(S + '.Kind', Kind);
VM.SetInt(S + '.Code', ID);
if seed <> -1 then
RandSeed := seed // setup common random for all, it is already stored
else
VM.SetInt(S + '.Seed', Result); // need to be stored;
FLights.FreeClear();
FLights.Add(TLightSource.Create(0,0,0)); // reserve lightsource for hero
end;
procedure TMap.SetWidth(const Value: Word);
begin
FWidth := Value;
VM.SetInt('Map.X', Value);
VM.SetInt('Hero.Map.' + VM.GetStr('Hero.Dungeon') + '.Width', Value);
end;
procedure TMap.AddCell(const FileName: string; ax, ay: Integer);
var
l, x, y, Z: Integer;
begin
LoadCell(FileName);
for l := 0 to 3 do
for y := ay to ay + 32 do
for x := ax to ax + 32 do
begin
Z := Cell[x - ax, y - ay, l];
if Z > 0 then
case l of
0: SetMapIdx(x, y, Z);
1: MapDcr[x, y] := Z;
2: PutObject(x, y, Z);
3: PutMapItem(x, y, Z);
end;
end;
end;
procedure TMap.Clear;
var
x, y: Word;
begin
Actors.FreeClear;
TheItems.FreeClear;
for y := 0 to 1023 do
for x := 0 to 1023 do
begin
MapIdx[x, y] := 0;
MapDcr[x, y] := 0;
MapObj[x, y] := 0;
// MapItm[x, y] := 0;
MapItems[x, y] := nil;
MapViz[x, y] := False;
MapDyn[x, y] := nil;
end;
end;
procedure TMap.ClearCell;
var
l, x, y: Integer;
begin
for l := 0 to 3 do
for x := 0 to 32 do
for y := 0 to 32 do
Cell[x, y, l] := 0;
end;
procedure TMap.ClearGraphics;
var
i: Word;
Bmp: TBitMap;
begin
Bmp := TBitMap.Create;
Bmp.LoadFromFile(Path + 'Data\Images\Empty.bmp');
Bmp.Transparent := True;
for i := 0 to arsize do
begin
MapTiles[i].Assign(Bmp);
MapTiles[i].Transparent := False;
MapDecors[i].Assign(Bmp);
MapObjects[i].Assign(Bmp);
end;
Bmp.Free;
end;
constructor TMap.Create;
var
i, R: Word;
begin
FLights := TLights.Create();
MapMem := TStringList.Create;
FImage := TImage.Create;
LoadProjectiles();
HeroImage := TBitMap.Create;
for i := 0 to ArSize do
begin
MapTiles[i] := TBitMap.Create;
MapDecors[i] := TBitMap.Create;
MapDecors[i].Transparent := True;
MapObjects[i] := TBitMap.Create;
MapObjects[i].Transparent := True;
end;
List := TStringList.Create;
FHintBack := TBitmap.Create;
FHintBack.LoadFromFile('Data\Images\GUI\BG.bmp');
Hint := THint.Create;
TheItems := TMapItemList.Create;
end;
destructor TMap.Destroy;
var
i: Word;
begin
FreeAndNil(Hint);
FreeAndNil(FHintBack);
FLights.FreeClear();
FreeAndNil(FLights);
FreeAndNil(FTilemask);
TheItems.FreeClear;
FreeAndNil(TheItems);
Actors.FreeClear();
for i := 0 to High(Shots) do
Shots[i].Free;
for i := 0 to High(Fireball) do
Fireball[i].Free;
for i := 0 to High(Stun) do
Stun[i].Free;
for i := 0 to arsize do
begin
MapTiles[i].Free;
MapDecors[i].Free;
MapObjects[i].Free;
end;
HeroImage.Free;
FImage.Free;
MapMem.Free;
List.Free;
inherited;
end;
procedure TMap.Display;
var
x, y, C, R, i: Integer;
Min, Max, PG, H: TPoint;
// A, D: Integer;
U, Z: Shortint;
// Ячейку X, Y видно
procedure VizCell(x, y: Integer);
begin
FOVViz[x, y] := True;
MapViz[x, y] := True;
end;
// Линия FOV
procedure LineTo(x, y: Integer);
var
i, l, ax, ay: Integer;
LR: Real;
begin
l := Math.Max(Abs(H.x - x), Abs(H.y - y));
for i := 1 to l do
begin
LR := i / l;
ax := H.x + Round((x - H.x) * LR);
ay := H.y + Round((y - H.y) * LR);
//ax := Round(H.x + (x - H.x) * LR);
//ay := Round(H.y + (y - H.y) * LR);
// VizCell(ax, ay);
if not CellMask(x, y, cmViewable) and not (MapObj[ax, ay] in [72..79]) then
Break;
end;
end;
// Отображаем видимую ячейку на экране
procedure DrawCell(x1, y1, x2, y2: Integer; O: Boolean = True);
var
C, S, Y: Integer;
MapItem: TMapItem;
begin
if (x2 < 0) or (y2 < 0) then
Exit;
with SCR.BG.Canvas do
begin
// if under tree then draw actors first
Draw(x1, y1, MapTiles[MapIdx[x2, y2]]);
C := MapDcr[x2, y2];
if (C > 0) then
Draw(x1, y1, MapDecors[C]);
C := MapObj[x2, y2];
if (O and (C > 7)) then
Draw(x1, y1, MapObjects[C]);
// C := MyGetWord(MapItm[x2, y2], 0);
if GetMapItem(x2, y2, MapItem) then
Draw(X1 + 8, Y1 + 8, InvBox.SmallInvBitmap[MapItem.Item.ImageIndex]);
if MapDyn[x2, y2] <> nil then
Draw(x1, y1, MapDyn[x2, y2].GetGraphic);
// if (MapDyn[x2, y2] <> nil) and (MapDyn[x2, y2] is tprojectile) then
// Draw(x1, y1, MapDyn[x2, y2].GetGraphic);
// if ((VM.GetInt('Shot.DX') <> 0) or (VM.GetInt('Shot.DY') <> 0)) and
// (x2 = VM.GetInt('Shot.X')) and (y2 = VM.GetInt('Shot.Y')) then
// begin
// y := (VM.GetInt('Shot.DY'));
// case (VM.GetInt('Shot.DX')) of
// -1: s := 7 - (y + 1);
// 0: s := (y + 1) * 2;
// 1: s := y + 2;
// end;
// Draw(x1, y1, Shots[s]);
// end;
end;
end;
// Отображаем предмет на полу возле героя
procedure DrawFloor(X, Y: Integer);
var
I, W: Integer;
S: string;
MapItem: TMapItem;
begin
if GetMapItem(X, Y, MapItem) then
with SCR.BG.Canvas do
begin
S := MapItem.Item.Name;
Font.Size := 14;
Font.Color := cLightRare;
W := TextWidth(S);
TextOut(792 - W, 512, S);
Draw(772 - W, 514, InvBox.SmallInvBitmap[MapItem.Item.ImageIndex]);
end;
end;
procedure DisplayAlert;
begin
SCR.BG.Canvas.Font.Color := AlertColor;
SCR.BG.Canvas.TextOut((Z * 32) -
(SCR.BG.Canvas.TextWidth(AlertMessage) div 2) - 16, 320, AlertMessage);
end;
// Отображаем всю видимую матрицу
procedure View;
var
x, y, f: Word;
FOVReady: Boolean;
procedure DrawHero();
begin
with SCR.BG.Canvas do
if (VM.GetInt('Hero.HP') > 0) then
Draw(((Z - 1) * 32) + U, 280, HeroImage)
else
Draw(((Z - 1) * 32) + U, 280, MapDecors[15]);
end;
begin
FOVReady := Length(FFovMap.Cells) <> 0;
for x := Min.x to Max.x do
for y := Min.y to Max.y do
//if FOVViz[x, y] {and (GetDist(H.x, H.y, x, y) <= R)} then
// if FOVViz[x, y] and MapViz[x, y] and (GetDist(H.x, H.y, x, y) <= R) then
begin
if FOVReady then
begin
f := getpcell(x, y)^.Flags;
if ((f and FOV_CELL_VISIBLE <> 0) or ((f and FOV_CELL_VISITED <> 0))) then
// if (getpcell(x, y)^.Flags and FOV_CELL_VISIBLE = 0) then
begin
PG.x := ((x - H.x) * 32) + U;
PG.y := ((y - H.y) * 32) - 4;
// if hero_cell and under_tree then drawsome floor tile + DrawHero();
DrawCell(PG.x + ((Z - 1) * 32), PG.y + 284, x, y);
if ((f and FOV_CELL_VISITED <> 0) and (f and FOV_CELL_VISIBLE = 0)) then
SCR.BG.Canvas.Draw(PG.x + ((Z - 1) * 32), PG.y + 284, uFog.Fog);
end;
end;
end;
// if NOT under_tree then
DrawHero();
//DrawFloor(H.x, H.y);
end;
// Показывает посещенные тайлы
procedure DrawTransparent;
var
x, y: Word;
begin
Min.x := H.x - 12;
if Min.x < 0 then
Min.x := 0;
Max.x := H.x + 12;
if Max.x >= Width then
Max.x := Width - 1;
Min.y := H.y - 9;
if Min.y < 0 then
Min.y := 0;
Max.y := H.y + 9;
if Max.y >= Height then
Max.y := Height - 1;
for x := Min.x to Max.x do
for y := Min.y to Max.y do
if not FOVViz[x, y] {or (GetDist(H.x, H.y, x, y) > R)} then
begin
PG.x := ((x - H.x) * 32) + U;
PG.y := ((y - H.y) * 32) - 4;
// if MapViz[x, y] then
with SCR.BG.Canvas do
begin
DrawCell(PG.x + ((Z - 1) * 32), PG.y + 284, x, y, False);
// Draw(PG.x + ((Z - 1) * 32), PG.y + 284, uFog.Fog);
end;
end;
end;
begin
Z := 13;
U := 0;
if IsRightFrame then
begin
Z := 7;
U := -8;
end;
if IsLeftFrame or (ShowLogLevel = 2) then
begin
Z := 19;
U := 8;
end;
R := HeroFovRadius();
r := 15; // for testing
H.x := VM.GetInt('Hero.X');
H.y := VM.GetInt('Hero.Y');
Min.x := Math.Max(H.x - R, 0);
Max.x := Math.Min(H.x + R, Width - 1);
Min.y := Math.Max(H.y - R, 0);
Max.y := Math.Min(H.y + R, Height - 1);
if True then
begin
FLights[0].Edit(H.x, H.y, HeroFovRadius);
for i := FLights.Count - 1 downto 0 do
begin
FLights[i].UpdateFromActor();
if (MaxPointDistance(H, FLights[i].Position) <= FLights[i].FLightRadius)
or Assigned(FLights[i].FActor) then
CalcFOVC(FFovMap, FLights[i].FXpos, FLights[i].FYpos, FLights[i].FLightRadius);
end;
// for y := Min.y to Max.y do
// for x := Min.x to Max.x do
// FOVViz[x, y] := False;
// FOVViz[H.x, H.y] := True;
// for i := Min.x to Max.x do
// LineTo(i, Min.y);
// for i := Min.y to Max.y do
// LineTo(Max.x, i);
// for i := Max.x downto Min.x do
// LineTo(i, Max.y);
// for i := Max.y downto Min.y do
// LineTo(Min.x, i);
end
else
for x := Min.x to Max.x do
for y := Min.y to Max.y do
if (GetDist(H.x, H.y, x, y) <= R) then
// VizCell(x, y);
if (Length(FFovMap.Cells) <> 0) then
SetCellFlag(x, y, FOV_CELL_VISIBLE);
View;
DrawFloor(H.x, H.y);
// if IsVMap then
// DrawTransparent;
Effects.Render;
RenderMiniMap;
SceneSkill.Skill.RenderAsLine(SCR.BG.Canvas);
GUI.ShowLog;
DisplayAlert;
DrawHints;
end;
procedure TMap.AddRoom(const S: string);
var
SR: TSplitResult;
l, F, K: string;
begin
AdvStr.AdvString := S;
SR := AdvStr.Split(',');
l := Trim(SR[0]);
if (Length(l) = 1) then
l := '0' + l;
while True do
begin
K := IntToStr(Rand(0, 19));
if (Length(K) = 1) then
K := '0' + K;
F := 'Random\Random' + l + '-' + K + '.map';
if FileExists(Path + 'Data\Maps\' + F) and (MapMem.IndexOf(F) <= 0) then
begin
AddCell(F, StrToInt(Trim(SR[1])), StrToInt(Trim(SR[2])));
MapMem.Append(F);
Exit;
end;
end;
end;
procedure TMap.GenBeaRLib(W, H, ID, Seed: Integer);
var
i, x, y, fx, fy: Integer;
F, T: Boolean;
OldSeed: Integer;
TilesFName: string;
begin
T := True;
case id of
6{G_HIVE}, 16{G_DARK_ROOMS}, 17{G_DOOM_ROOMS}: TilesFName := 'Data\Maps\Drom.bmp';
10{G_FOREST}, 11{G_SWAMP}, 15{G_BROKEN_VILLAGE}: TilesFName := 'Data\Maps\Forest.bmp';
else
TilesFName := 'Data\Maps\Drom.bmp';
end;
LoadGraphics(Path + TilesFName);
Clear;
SetLength(DR, W * H);
OldSeed := SetupMapsave(W, H, ID, seed, 2);
// SetRandSeed(RandSeed, True);
// GenMap(W, H, ID, DR, W * H);
// GenMap_dyn(W, H, ID, RandSeed);
// SetRandSeed(RandSeed, True);
GenMap(W, H, ID, DR, RandSeed);
RandSeed := OldSeed;
Tilemask.BuildGroups;
for x := 0 to W - 1 do
for y := 0 to H - 1 do
begin
// MapItm[x, y] := 0;
MapItems[x, y] := nil;
fx := Rand(0, 2048);
if (fx > 159) then
MapDcr[x, y] := 0
else
MapDcr[x, y] := fx;
case DR[x * H + y] of
'.':
begin
if MapDcr[x, y] in [32..63] then
MapDcr[x, y] := 0;
SetMapIdx(x, y, tilemask.GetRandbyMask(BuildMask([cmPassable, cmViewable])));
end;
'#':
begin
if not (MapDcr[x, y] in [32..63]) then
MapDcr[x, y] := 0;
PutObject(x, y, 0);
// MapItm[x, y] := 0;
MapItems[x, y] := nil;
SetMapIdx(x, y, tilemask.GetRandbyMask(BuildMask([])));
SetCellFlag(x, y, FOV_CELL_OPAQUE);
end;
'<':
begin
SetMapIdx(x, y, tilemask.GetRandbyMask(BuildMask([cmPassable, cmViewable])));
SetupHero(X, Y);
T := False;
Continue;
end;
'>':
begin
SetMapIdx(x, y, tilemask.GetRandbyMask(BuildMask([cmPassable, cmViewable])));
PutObject(x, y, 63);
T := False;
Continue;
end;
'+':
begin
PutObject(x, y, 64);
// MapItm[x, y] := 0;
MapItems[x, y] := nil;
MapDcr[x, y] := 0;
SetMapIdx(x, y, tilemask.GetRandbyMask(BuildMask([cmPassable, cmViewable])));
Continue;
end;
'-':
begin
PutObject(x, y, 72);
// MapItm[x, y] := 0;
MapItems[x, y] := nil;
MapDcr[x, y] := 0;
SetMapIdx(x, y, tilemask.GetRandbyMask(BuildMask([cmPassable, cmViewable])));
Continue;
end;
'T':
begin
MapDcr[x, y] := 0;
SetMapIdx(x, y, tilemask.GetRandbyMask(BuildMask([cmWood]), True));
Continue;
end;
'~':
begin
MapDcr[x, y] := 0;
// MapItm[x, y] := 0;
MapItems[x, y] := nil;
SetMapIdx(x, y, tilemask.GetRandbyMask(BuildMask([cmWater]), True));
Continue;
end
else
SetMapIdx(x, y, tilemask.GetRandbyMask(BuildMask([cmPassable, cmViewable])));
end;
// Объекты
fx := Rand(0, 2048);
if CellMask(x, y, cmPassable) and CellMask(x, y, cmViewable) then
if (fx in [0..7, 9..11, 23, 30, 31, 39, 40..46]) then
fx := 9
else if (fx in [17..50]) then
case fx of
// Эти объекты удалять точно!
// 23, 30, 31, 39, 40..46 : MapObj[x, y] := 0;
// Этих объектов должно быть меньше
17..22, 28: if (Random(4) = 0) then
fx := 0;
end
else if (fx < 120) or (fx > 121) then
fx := 0
else
else
fx := 0;
PutObject(x, y, fx);
end;
F := False;
i := 0;
if T then
repeat
x := Rand(2, W - 2);
y := Rand(2, H - 2);
if CellMask(x, y, cmPassable) then
F := SetupHero(X, Y);
Inc(i);
until F or (i = 1000);
F := False;
i := 0;
if T then
repeat
fx := Rand(5, W - 5);
fy := Rand(5, H - 5);
if CellMask(fx, fy, cmPassable) and (fx <> x) and (fy <> y) then
F := PutObject(fx, fy, 63);
Inc(i);
until F or (i = 1000);
GUI.MakePC;
GUI.MakeMiniMap;
SCR.Display;
end;
function TMap.GetMapDcr(AX, AY: Word): Cardinal;
begin
Result := Layer[lyDcr][AX, AY];
end;
function TMap.GetMapIdx(AX, AY: Word): Cardinal;
begin
Result := Layer[lyMap][AX, AY];
end;
function TMap.GetMapItem(AX, AY: Word; out MapItem: TMapItem): Boolean;
begin
MapItem := MapItems[AX, AY];
Result := Assigned(MapItem);
end;
function TMap.GetMapItemBaseId(AX, AY: Word): Integer;
var
MapItem: TMapItem;
begin
if GetMapItem(AX, AY, MapItem) then
Result := MapItem.Item.BaseItemID
else
Result := 0;
end;
function TMap.GetMapObj(AX, AY: Word): Cardinal;
begin
Result := Layer[lyObj][AX, AY];
end;
// why pfovcell: we need to change the cell when executing this func, but it is not allowed to change by value, only via pointer
function TMap.getpcell(ax, ay: integer): pFOV_CELL;
begin
Result := @FFovMap.cells[ay * Width + ax];
end;
procedure TMap.Gen(W, H, ID, Seed: Integer);
var
A, i, x, y, Cr: Integer;
KR, VB, HS: TSplitResult;
Bmp: TBitMap;
S: string;
SL: TStringList;
PCSet, ExitSet: Boolean;
OldSeed: Integer;
begin
VM.SetStr('Map.Tileset', 'Data\Maps\Drom.bmp');
LoadGraphics(Path + VM.GetStr('Map.Tileset'));
Clear;
OldSeed := setupMapsave(W, H, ID, seed, 1);
MapMem.Clear;
//
Tilemask.BuildGroups;
for x := 0 to Width do
for y := 0 to Height do
begin
SetMapIdx(x, y, Tilemask.GetRandbyMask(BuildMask([])));
MapDcr[x, y] := 0;
PutObject(x, y, 0);
// MapItm[x, y] := 0;
MapItems[x, y] := nil;
end;
//
SL := TStringList.Create;
SL.LoadFromFile(Path + 'Data\GenMaps.ini');
// AdvStr.AdvString := SL[Rand(0, SL.Count - 1)];
AdvStr.AdvString := SL[0];
KR := AdvStr.Split('|');
for i := 0 to High(KR) do
begin
if (Pos('!', KR[i]) > 0) then
begin
if (Rand(1, 2) = 1) then
KR[i] := '0,0,0'
else
Delete(KR[i], 1, 1);
end;
if (Pos('~', KR[i]) > 0) then
begin
AdvStr.AdvString := KR[i];
VB := AdvStr.Split(',');
AdvStr.AdvString := VB[0];
S := '';
for A := 1 to High(VB) do
S := S + VB[A] + ',';
Delete(S, Length(S), 1);
HS := AdvStr.Split('~');
KR[i] := HS[Rand(0, High(HS))] + ',' + S;
end;
if (Pos('*', KR[i]) > 0) then
begin
AdvStr.AdvString := KR[i];
VB := AdvStr.Split('*');
KR[i] := VB[0];
for A := 1 to High(VB) do
AddRoom(VB[A]);
end;
AddRoom(KR[i]);
end;
// Удаляем лишние двери
for x := 0 to Width do
for y := 0 to Height do
if (MapObj[x, y] >= 64) and (MapObj[x, y] <= 71) then
begin
if CellMask(x - 1, y, cmPassable) and not CellMask(x + 1, y, cmPassable)
and not cellmask(x, y - 1, cmPassable) and not cellmask(x, y + 1,
cmPassable) then
PutObject(x, y, 0);
if CellMask(x + 1, y, cmPassable) and not CellMask(x - 1, y, cmPassable)
and not cellmask(x, y - 1, cmPassable) and not cellmask(x, y + 1,
cmPassable) then
PutObject(x, y, 0);
if CellMask(x, y - 1, cmPassable) and not CellMask(x + 1, y, cmPassable)
and not cellmask(x - 1, y, cmPassable) and not cellmask(x, y + 1,
cmPassable) then
PutObject(x, y, 0);
if CellMask(x, y + 1, cmPassable) and not CellMask(x - 1, y, cmPassable)
and not cellmask(x + 1, y, cmPassable) and not cellmask(x, y - 1,
cmPassable) then
PutObject(x, y, 0);
end;
// Удаляем лишние двери
for x := 0 to Width do
for y := 0 to Height do
begin
if (MapObj[x + 3, y] in [64..71]) and (Rand(1, 2) = 1) then
PutObject(x, y, 0);
if (MapObj[x, y + 3] in [64..71]) and (Rand(1, 2) = 1) then
PutObject(x, y, 0);
end;
// monsters and pc
PCSet := False;
ExitSet := False;
for x := 2 to Width - 2 do
for y := 2 to Height - 2 do
begin
if not pcset and cellmask(x, y, cmPassable) and (Random(9) = 0) then
pcset := SetupHero(x, y);
if not Exitset and cellmask(x, y, cmPassable) and (Random(9) = 0) then
Exitset := PutObject(x, y, 63);
end;
RandSeed := OldSeed; // restore randomness to make random monsters
for x := 2 to Width - 2 do
for y := 2 to Height - 2 do
if MapObj[x, y] = 9 then
PutObject(x, y, 9);
// Удаляем лишние объекты по периметру карты
for x := 0 to Width do
begin
if (MapObj[x, 0] > 0) then
PutObject(x, 0, 0);
if (MapObj[x, Width] > 0) then
PutObject(x, Width, 0);
end;
for y := 0 to Height do
begin
if (MapObj[0, y] > 0) then
PutObject(0, y, 0);
if (MapObj[Height, y] > 0) then
PutObject(Height, y, 0);
end;
//
Bmp := TBitMap.Create;
Bmp.Width := Width + 1;
Bmp.Height := Height + 1;
for x := 0 to Width do
for y := 0 to Height do
if not CellMask(x, y, cmPassable) then
Bmp.Canvas.Pixels[x, y] := $000000;
Bmp.Free;
//
SL.Free;
//
GUI.MakePC;
GUI.MakeMiniMap;
SCR.Display;
// MapMem.SaveToFile('maps.txt');
end;
procedure TMap.Load(const FileName: string);
var
Ob, x, y , i, ID, j, k{, xP, yP}: Integer;
L1, L2, L3: Integer;
SR: TSplitResult;
// Script: string;
const
Max = 5;
begin
if not FileExists(Path + 'Data\Maps\' + FileName) then
begin
Error('КРИТИЧЕСКАЯ ОШИБКА: Не могу загрузить карту ' + Path + 'Data\Maps\' +
FileName + '!');
Halt;
end;
List.Clear;
List.LoadFromFile(Path + 'Data\Maps\' + FileName);
VM.SetStr('Map.Name', Trim(List[0]));
AdvStr.AdvString := List[1];
SetupMapSave(StrToInt(AdvStr.IniKey(',')), StrToInt(AdvStr.IniValue(',')), 0, RandSeed, 0);
AdvStr.AdvString := List[2];
VM.SetStr('Map.Tileset', Trim(List[3]));
LoadGraphics(Path + Trim(List[3]));
SetupHero(StrToInt(AdvStr.IniKey(',')), StrToInt(AdvStr.IniValue(',')), True);
Clear;
//
//
for y := Max to Height + Max - 1 do
begin
AdvStr.AdvString := List[y];
SR := AdvStr.Split(',');
for x := 0 to Width - 1 do
SetMapIdx(x, y - Max, StrToInt(SR[x]));
end;
L1 := Max + Height;
for y := L1 + 1 to Height + L1 do
begin
AdvStr.AdvString := List[y];
SR := AdvStr.Split(',');
for x := 0 to Width - 1 do
MapDcr[x, y - L1 - 1] := StrToInt(SR[x]);
end;
L2 := Max + Height * 2 + 1;
for i := L2 + 1 to Height + L2 do
begin
y := i - L2 - 1;
AdvStr.AdvString := List[i];
SR := AdvStr.Split(',');
for x := 0 to Width - 1 do
begin
Ob := StrToInt(SR[x]);
PutObject(x, y, Ob);
end;
end;
L3 := Max + Height * 3 + 2;
for y := L3 + 1 to Height + L3 do
begin
AdvStr.AdvString := List[y];
SR := AdvStr.Split(',');
for x := 0 to Width - 1 do
// MapItm[x, y - L3 - 1] := StrToInt(SR[x]);
if SR[x] <> '0' then
PutMapItem(X, y - L3 - 1, StrToInt(SR[x]));
end;
j := List.IndexOf(NPCmapsectionname);
k := List.IndexOf(SignsMapSectionName);
if (j <> -1) and (k <> -1) then
For i := j + 1 to k - 1 do
begin
CNPC.Split(List[i], x, y, ID);
(mapdyn[x, y] as TNPC).NPCID := ID;
end;
if (k <> -1) then
For i := k + 1 to List.count - 1 do
begin
CSign.Split(List[i], x, y, ID);
SignList.Add(CSign.Create(x, y, ID));
end;
//
GUI.MakePC;
GUI.MakeMiniMap;
SCR.Display;
end;
function TMap.LoadCell(const FileName: string): TPoint;
var
x, y, W, H {, i, j, U, xP, yP}: Word;
// DD: TSplitResult;
L1, L2, L3: Integer;
SR: TSplitResult;
const
Max = 5;
begin
ClearCell;
List.Clear;
List.LoadFromFile(Path + 'Data\Maps\' + FileName);
AdvStr.AdvString := List[1];
W := StrToInt(AdvStr.IniKey(','));
H := StrToInt(AdvStr.IniValue(','));
Result.x := W;
Result.y := H;
for y := Max to H + Max - 1 do
begin
AdvStr.AdvString := List[y];
SR := AdvStr.Split(',');
for x := 0 to W - 1 do
Cell[x, y - Max, 0] := StrToInt(SR[x]);
end;
L1 := Max + H;
for y := L1 + 1 to H + L1 do
begin
AdvStr.AdvString := List[y];
SR := AdvStr.Split(',');
for x := 0 to W - 1 do
Cell[x, y - L1 - 1, 1] := StrToInt(SR[x]);
end;
L2 := Max + H * 2 + 1;
for y := L2 + 1 to H + L2 do
begin
AdvStr.AdvString := List[y];
SR := AdvStr.Split(',');
for x := 0 to W - 1 do
Cell[x, y - L2 - 1, 2] := StrToInt(SR[x]);
end;
L3 := Max + H * 3 + 2;
for y := L3 + 1 to H + L3 do
begin
AdvStr.AdvString := List[y];
SR := AdvStr.Split(',');
for x := 0 to W - 1 do
Cell[x, y - L3 - 1, 3] := StrToInt(SR[x]);
end;
// Трансформация загруженной ячейки (например, верт. зеркализация)
if (Rand(1, 3) = 1) then
HorzMirrCell();
if (Rand(1, 3) = 1) then
VertMirrCell();
end;
function TMap.HeroFovRadius: Integer;
begin
Result := VM.GetInt('Hero.Rad') + VM.GetInt('Hero.AdvRad') + VM.GetInt('Hero.TimeRad') - VM.GetInt('Hero.Blind');
if Result < 0 then
Result := 0;
if Result > 8 then
Result := 8;
end;
procedure TMap.HorzMirrCell;
var
x, y, Z: Byte;
begin
for y := 0 to Height - 1 do
for x := 0 to (Width - 1) div 2 do
for Z := 0 to 3 do
Swap(Cell[x, y, Z], Cell[Width - x - 1, y, Z]);
end;
procedure TMap.VertMirrCell;
var
x, y, Z: Byte;
begin
for x := 0 to Width - 1 do
for y := 0 to (Height - 1) div 2 do
for Z := 0 to 3 do
Swap(Cell[x, y, Z], Cell[x, Height - y - 1, Z]);
end;
procedure TMap.LoadGraphics(const ADT: string);
var
T: TBitmap;
I: Integer;
begin
ClearGraphics;
SplitBMP(MapTiles, ADT);
if Assigned(Tilemask) then
FreeAndNil(FTilemask);
FTilemask := TTilemask.Create(ADT);
SplitBMP(MapDecors, Path + 'Data\Images\Decors.bmp');
SplitBMP(MapObjects, Path + 'Data\Images\Objects.bmp');
// Постобработка тайлов дверей
T := TBitmap.Create;
try
for I := 64 to 79 do
begin
T.Assign(MapTiles[73]);
T.Canvas.Draw(0, 0, MapObjects[I]);
MapObjects[I].Assign(T);
MapObjects[I].TransparentColor := MapObjects[I].Canvas.Pixels[16, 16];
MapObjects[I].Transparent := True;
if (I in [72..79]) then
begin
T.Assign(MapTiles[45]);
T.Canvas.Draw(0, 0, MapObjects[I]);
MapObjects[I].Assign(T);
end;
end;
finally
T.Free;
end;
end;
function TMap.LoadSaved: Boolean;
var
S: string;
W, H, Code, Seed: Integer;
begin
Result := False;
S := VM.GetStr('Hero.Dungeon');
if VM.IsVar('Hero.Map.' + S + '.Kind') then
begin
W := VM.GetInt('Hero.Map.' + S + '.Width');
H := VM.GetInt('Hero.Map.' + S + '.Height');
Code := VM.GetInt('Hero.Map.' + S + '.Code');
seed := VM.GetInt('Hero.Map.' + S + '.Seed');
case VM.GetInt('Hero.Map.' + S + '.Kind') of
1: Gen(W, H, Code, Seed);
2: GenBeaRLib(W, H, Code, Seed);
end;
Result := True;
end;
end;
function TMap.PutMapItem(AX, AY: Word; BaseItemID: Integer;
APref: TPrefix = NoPrefix; ASuff: TSuffix = NoSuffix): Boolean;
begin
if BaseItemID = 0 then
Result := PutMapItem(AX, AY, nil)
else
Result := PutMapItem(AX, AY, TInvItem.Create(BaseItemID, APref, ASuff));
end;
function TMap.PutMapItem(AX, AY: Word; Item: TInvItem): Boolean;
var
MapItem: TMapItem;
begin
Result := Assigned(Item);
if Result then
begin
MapItem := TMapItem.Create(AX, AY, -1, Item);
MapItem.Idx := TheItems.Add(MapItem);
// new item hides old
MapItems[AX, AY] := MapItem;
end
else
MapItems[AX, AY] := nil;
end;
function TMap.PutObject(X, Y, obj: Word): Boolean;
var
Cr: Integer;
begin
// object cannot be placed on water
Result := not CellMask(x, y, cmWater);
if not Result then
Exit;
case obj of
0 : if CellMask(x, y, cmViewable) then SetCellFlag(x, y, FOV_CELL_HIDDEN);
29: FLights.Add(TLightSource.Create(x, y, 5));
9:
begin
Cr := Creatures.GetRandomFitDung(VM.GetInt('Hero.Dungeon'));
Obj := 0;
mapdyn[x, y] := Actors.AddMob(creatures[Cr]);
mapdyn[x, y].SetXY(x, y);
end;
11:
begin
Obj := 0;
mapdyn[x, y] := Actors.AddNPC();
mapdyn[x, y].SetXY(x, y);
end;
55:
begin
VM.SetInt('Hero.UpX', x);
VM.SetInt('Hero.UpY', y);
end;
63:
begin
VM.SetInt('Hero.DnX', x);
VM.SetInt('Hero.DnY', y);
end;
64..71: SetCellFlag(x, y, FOV_CELL_OPAQUE);
72..79: SetCellFlag(x, y, FOV_CELL_VISIBLE);
end;
Layer[lyObj][x, y] := obj;
end;
function TMap.CellMask(x, y: Word; Mode: ncellmode): Boolean;
begin
Result := Tilemask[mapIdx[x, y], Mode];
end;
function TMap.IsCellFlagOn(AX, AY, AF: Word): Boolean;
begin
Result := getpcell(Ax, Ay)^.Flags and AF = AF;
end;
function TMap.IsHeroCell(x, y: Word): Boolean;
begin
Result := (vm.GetInt('hero.x') = x) and (vm.GetInt('hero.Y') = y);
end;
procedure TMap.RenderMiniMap;
var
A, B, U, X, Y: Integer;
begin
// Миникарта и герой
with GUI do
if IsShowMinimap then
begin
U := 792 - MiniMap.Width;
BitBlt(BGDC, U, 8, SCR.BG.Width - 8, MiniMap.Height + 8,
GUI.MiniMap.Canvas.Handle, 0, 0, SRCCOPY);
with GUI.MiniMap do
begin
Width := Self.Width;
Height := Self.Height;
end;
with SCR.BG do
for x := 0 to Self.Width - 1 do
for y := 0 to Self.Height - 1 do
if IsCellFlagOn(x, y, FOV_CELL_VISITED) then
if not CellMask(x, y, cmPassable) then
Canvas.Pixels[U + x, y + 8] := clBlack
else
Canvas.Pixels[U + x, y + 8] := clGray;
// Маркеры на миникарте
begin
A := VM.GetInt('Hero.DnX');
B := VM.GetInt('Hero.DnY');
if IsCellFlagOn(A, B, FOV_CELL_VISITED) or IsTest then
SCR.BG.Canvas.Draw(U + A - 3, B + 5, DMark);
A := VM.GetInt('Hero.UpX');
B := VM.GetInt('Hero.UpY');
if (A > 0) and (B > 0) then
SCR.BG.Canvas.Draw(U + A - 3, B + 5, UMark);
SCR.BG.Canvas.Draw(U + VM.GetInt('Hero.X') - 3, VM.GetInt('Hero.Y') + 5,
MMark);
end;
end;
end;
procedure TMap.LoadProjectiles;
begin
FImage.Split(Path + 'Data\Images\StunImg.bmp', Stun, 32, True); // Stun
FImage.Split(Path + 'Data\Images\Fireball.png', FireBall, 32, True); // Fireballs
FImage.Split(Path + 'Data\Images\Shot.png', Shots, 32, True); // Arrows and bolts
end;
procedure TMap.DrawHints;
var
S: string;
X, C: Integer;
InvItem: TInvItem;
const
K: array[0..6] of string = ('Персонаж (C)','Инвентарь (I)','Журнал заданий (Q)',
'Дерево навыков (A)','Сообщения (L)','Миникарта (M)','Статистика (S)');
begin
if (MouseY < 565) or IsMenu then Exit;
X := -27;
if IsMouseInRect(0, 565, 120, 582) then Hint.ShowString(X, 560, 0, 'Здоровье ' + VM.GetStrInt('Hero.HP') + '/' +
VM.GetStrInt('Hero.MHP'), True, Point(0, 0), FHintBack);
if IsMouseInRect(0, 583, 120, 600) then Hint.ShowString(X, 560, 0, 'Мана ' + VM.GetStrInt('Hero.MP') + '/' +
VM.GetStrInt('Hero.MMP'), True, Point(0, 0), FHintBack);
X := 795;
if IsMouseInRect(680, 565, 800, 582) then Hint.ShowString(X, 560, 0, 'Опыт ' + VM.GetStrInt('Hero.Exp') + '/' +
VM.GetStrInt('Hero.NextExp'), True, Point(0, 0), FHintBack);
if IsMouseInRect(121, 565, 448, 600) then
begin
X := (MouseX - 121) div 33;
// ID := InvBox.Belt.InvItems[X].BaseItemID;
C := X + 1;
if (C > 9) then C := 0;
if InvBox.IsItemPresent(izBelt, X, InvItem) then
Hint.ShowString(120 + (X * 33), 560, 0, Format('%s(%d)', [InvItem.Name, C]), True, Point(0, 0), FHintBack);
end;
if IsMouseInRect(449, 565, 679, 600) then
begin
X := (MouseX - 449) div 33;
Hint.ShowString(450 + (X * 33), 560, 0, K[X], True, Point(0, 0), FHintBack);
end;
if IsMouseInRect(680, 583, 800, 600) then
begin
case VM.GetInt('Hero.Hunger') of
0..200: S := 'Очень голоден';
201..400: S := 'Голоден';
401..650: S := 'Сыт';
else S := 'Насыщен';
end;
if IsTest then S := S + ' (' + VM.GetStrInt('Hero.Hunger') + '/1000)';
Hint.ShowString(X, 560, 0, S, True, Point(0, 0), FHintBack);
end;
end;
{ TLightSource }
constructor TLightSource.Create(AX, AY, ARadius: Word; Actor: TActor = nil);
begin
inherited Create();
Edit(AX, AY, ARadius);
FActor := Actor;
end;
procedure TLightSource.Edit(AX, AY, ARadius: word);
begin
Xpos := AX;
Ypos := AY;
LightRadius := ARadius;
end;
function TLightSource.GetPosition: TPoint;
begin
Result := Point(Xpos, Ypos);
end;
procedure TLightSource.SetLightRadius(const Value: Word);
begin
FLightRadius := Value;
end;
procedure TLightSource.SetPosition(const Value: TPoint);
begin
Xpos := Value.X;
Ypos := Value.Y;
end;
procedure TLightSource.SetXpos(const Value: Word);
begin
FXpos := Value;
end;
procedure TLightSource.SetYpos(const Value: Word);
begin
FYpos := Value;
end;
procedure TLightSource.UpdateFromActor;
begin
if Assigned(FActor) then
begin
FXpos := FActor.X;
FYpos := FActor.Y;
// FLightRadius := FActor.;
end;
end;
{ TLights }
function TLights.GetItems(Index: Integer): TLightSource;
begin
Result := inherited GetItem(Index) as TLightSource;
end;
procedure TLights.SetItems(Index: Integer; const Value: TLightSource);
begin
inherited SetItem(Index, Value);
end;
initialization
Map := TMap.Create;
finalization
Map.Free;
end.
|
unit SelTalle;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, ActnList, ImgList, Menus, ComCtrls, ToolWin, Grids, DBGrids,
Db, DBTables, StdCtrls;
type
TFSelTalle = class(TForm)
MainMenu1: TMainMenu;
Ventana1: TMenuItem;
Salir1: TMenuItem;
Ordenar1: TMenuItem;
porCodigo1: TMenuItem;
porNombre1: TMenuItem;
ActionList1: TActionList;
Codigo: TAction;
Nombre: TAction;
Panel1: TPanel;
DS: TDataSource;
DBGrid1: TDBGrid;
Selec: TAction;
Seleccionar1: TMenuItem;
CoolBar1: TCoolBar;
ToolBar1: TToolBar;
Fin: TToolButton;
ToolButton4: TToolButton;
ToolButton2: TToolButton;
ToolButton3: TToolButton;
ToolButton1: TToolButton;
edCodigo: TEdit;
edNom: TEdit;
Buscar1: TMenuItem;
PorCodigo2: TMenuItem;
PorNombre2: TMenuItem;
N1: TMenuItem;
ImageList1: TImageList;
ToolButton5: TToolButton;
procedure CerrarExecute(Sender: TObject);
procedure SelecExecute(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure edCodigoChange(Sender: TObject);
procedure edNomChange(Sender: TObject);
procedure FormKeyPress(Sender: TObject; var Key: Char);
procedure CodigoExecute(Sender: TObject);
procedure NombreExecute(Sender: TObject);
procedure FinClick(Sender: TObject);
procedure FormActivate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
FSelTalle: TFSelTalle;
implementation
uses
Main, DataMod;
{$R *.DFM}
procedure TFSelTalle.CerrarExecute(Sender: TObject);
begin
ModalResult := mrCancel;
end;
procedure TFSelTalle.SelecExecute(Sender: TObject);
begin
ModalResult := mrOK;
end;
procedure TFSelTalle.FormCreate(Sender: TObject);
begin
( Ds.DataSet ).Open;
end;
procedure TFSelTalle.FormDestroy(Sender: TObject);
begin
( Ds.DataSet ).Close;
end;
procedure TFSelTalle.edCodigoChange(Sender: TObject);
begin
( Ds.DataSet ).DisableControls;
try
Screen.cursor := crHourGlass;
TTable( Ds.DataSet ).locate( 'CODIGO', edCodigo.text, [locaseinsensitive]);
finally
( Ds.DataSet ).EnableControls;
Screen.Cursor := crDefault;
end;
end;
procedure TFSelTalle.edNomChange(Sender: TObject);
begin
( Ds.DataSet ).DisableControls;
try
Screen.cursor := crHourGlass;
TTable( Ds.DataSet ).locate( 'DENOMINA', edNom.text, [locaseinsensitive]);
finally
( Ds.DataSet ).EnableControls;
Screen.Cursor := crDefault;
end;
end;
procedure TFSelTalle.FormKeyPress(Sender: TObject; var Key: Char);
begin
if Key = #13 then
ModalResult := mrOK;
end;
procedure TFSelTalle.CodigoExecute(Sender: TObject);
begin
if TTable( Ds.DataSet ).IndexName <> 'PrimaryKey' then
TTable( Ds.DataSet ).IndexName := 'PrimaryKey';
end;
procedure TFSelTalle.NombreExecute(Sender: TObject);
begin
if TTable( Ds.DataSet ).IndexName <> 'Denomina' then
TTable( Ds.DataSet ).IndexName := 'Denomina';
end;
procedure TFSelTalle.FinClick(Sender: TObject);
begin
Close;
end;
procedure TFSelTalle.FormActivate(Sender: TObject);
begin
if DM.TTalle.IndexName = 'PrimaryKey' then
ActiveControl := edCodigo
else
ActiveControl := edNom;
end;
end.
|
unit pageloader;
{$mode delphi}
interface
uses
Classes, SysUtils,
browsermodules, browserconfig;
type
{ TPageLoader }
TPageLoader = class
public
Contents: string;
LastPageURL: string;
ContentsList: TStringList;
DebugInfo: TStringList;
constructor Create;
destructor Destroy; override;
procedure LoadFromURL(AURL: string);
procedure LoadBinaryResource(AURL: string; var ADest: TMemoryStream);
function URLToAbsoluteURL(AInput: string): string;
end;
TOnPageLoadProgress = procedure (APercent: Integer) of object;
{ TPageLoaderThread }
TPageLoaderThread = class(TThread)
private
FOnPageLoadProgress: TOnPageLoadProgress;
public
PageLoader: TPageLoader;
Progress: Integer;
URL: string;
destructor Destroy; override;
procedure Execute; override;
procedure CallPageLoadProgress;
property OnPageLoadProgress: TOnPageLoadProgress read FOnPageLoadProgress write FOnPageLoadProgress;
end;
implementation
uses httpsend;
{ TPageLoaderThread }
destructor TPageLoaderThread.Destroy;
begin
inherited Destroy;
end;
procedure TPageLoaderThread.Execute;
var
lModule: TBrowserModule;
lNewContents: string;
i: Integer;
begin
PageLoader.LoadFromURL(URL);
// Run all modules which might want to change the HTML
for i := 0 to GetBrowserModuleCount() - 1 do
begin
lModule := GetBrowserModule(i);
if not lModule.Activated then Continue;
if lModule.HandleOnPageLoad(PageLoader.Contents, lNewContents) then
begin
PageLoader.Contents := lNewContents;
writeln(PageLoader.Contents);
end;
end;
end;
procedure TPageLoaderThread.CallPageLoadProgress;
begin
end;
{ TPageLoader }
constructor TPageLoader.Create;
begin
ContentsList := TStringList.Create;
DebugInfo := TStringList.Create;
end;
destructor TPageLoader.Destroy;
begin
ContentsList.Free;
DebugInfo.Free;
inherited Destroy;
end;
procedure TPageLoader.LoadFromURL(AURL: string);
var
Client: THttpSend;
J: Integer;
begin
// If there is no protocol, add http
J := Pos(':', AURL);
if (J = 0) then LastPageURL := 'http://' + AURL
else LastPageURL := AURL;
Client := THttpSend.Create;
try
Client.Headers.Add('Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8');
Client.Headers.Add('Accept-Language: en-gb,en;q=0.5');
// Client.Headers.Add('Accept-Encoding: gzip,deflate');
Client.Headers.Add('Accept-Charset: utf-8;q=0.7,*;q=0.7'); // ISO-8859-1,
Client.UserAgent := FPBrowserConfig.UserAgent;
Client.HttpMethod('GET', LastPageURL);
// Client.Headers;
Client.Document.Position := 0;
ContentsList.Clear();
ContentsList.LoadFromStream(Client.Document);
DebugInfo.Clear();
DebugInfo.Add(Format('Loading page: %s', [LastPageURL]));
DebugInfo.Add('');
DebugInfo.Add('HTTP Headers:');
DebugInfo.Add('');
DebugInfo.AddStrings(Client.Headers);
DebugInfo.Add('');
Contents := ContentsList.Text;
finally
Client.Free;
end;
end;
procedure TPageLoader.LoadBinaryResource(AURL: string; var ADest: TMemoryStream);
var
Client: THttpSend;
i: Integer;
begin
Client := THttpSend.Create;
try
Client.Headers.Add('Accept: image/png, image/jpeg, image/gif');
Client.Headers.Add('Accept-Language: en-gb,en;q=0.5');
// Client.Headers.Add('Accept-Encoding: gzip,deflate');
Client.Headers.Add('Accept-Charset: utf-8;q=0.7,*;q=0.7'); // ISO-8859-1,
// Client.UserAgent := AUserAgent;
Client.HttpMethod('GET', AURL);
Client.Document.Position := 0;
ADest := TMemoryStream.Create;
ADest.CopyFrom(Client.Document, Client.Document.Size);
DebugInfo.Add(Format('Loading image: %s Size: %d', [AURL, ADest.Size]));
finally
Client.Free;
end;
end;
function TPageLoader.URLToAbsoluteURL(AInput: string): string;
var
J: Integer;
begin
// Add the base URL if the URL is relative
J := Pos(':', UpperCase(AInput));
if J = 0 then
begin
if (Length(LastPageURL) > 0) and
(LastPageURL[Length(LastPageURL)] = '/') then
Result := LastPageURL + Copy(AInput, 2, Length(AInput)-1)
else
Result := LastPageURL + AInput;
end
else
Result := AInput;
end;
end.
|
{=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=]
Copyright (c) 2013, Jarl K. <Slacky> Holta || http://github.com/WarPie
All rights reserved.
For more info see: Copyright.txt
[=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=}
(*
Sorting Array of TEA using an array for weight!
*)
procedure __SortATEA(var Arr:T2DExtArray; Weight:TExtArray; Left, Right:Integer);
var
i,j: Integer;
pivot:Extended;
tmp:TExtArray;
begin
i:=Left;
j:=Right;
pivot := Weight[(left+right) shr 1];
repeat
while pivot > Weight[i] do i:=i+1;
while pivot < Weight[j] do j:=j-1;
if i<=j then begin
tmp:= Arr[i];
Arr[i] := Arr[j];
Arr[j] := tmp;
Exch(Weight[i], Weight[j]);
j:=j-1;
i:=i+1;
end;
until (i>j);
if (Left < j) then __SortATEA(Arr, Weight, Left,j);
if (i < Right) then __SortATEA(Arr, Weight, i,Right);
end;
procedure SortATEAByLength(var Arr:T2DExtArray);
var
i,Hi: Integer;
Weight:TExtArray;
begin
Hi := Length(Arr);
if Hi <= 1 then Exit;
SetLength(Weight, Hi);
for i := 0 to Hi-1 do Weight[i] := Length(Arr[i]);
__SortATEA(Arr, Weight, Low(Arr), High(Arr));
SetLength(Weight, 0);
end;
procedure SortATEAByMean(var Arr:T2DExtArray);
var
i,Hi: Integer;
Weight:TExtArray;
begin
Hi := Length(Arr);
if Hi <= 1 then Exit;
SetLength(Weight, Hi);
for i := 0 to Hi-1 do
Weight[i] := SumTEA(Arr[i]) / Length(Arr[i]);
__SortATEA(Arr, Weight, Low(Arr), High(Arr));
SetLength(Weight, 0);
end;
procedure SortATEAByFirst(var Arr:T2DExtArray);
var
i,Hi: Integer;
Weight:TExtArray;
begin
Hi := Length(Arr);
if Hi <= 1 then Exit;
SetLength(Weight, Hi);
for i := 0 to Hi-1 do
Weight[i] := Arr[i][0];
__SortATEA(Arr, Weight, Low(Arr), High(Arr));
SetLength(Weight, 0);
end;
procedure SortATEAByIndex(var Arr:T2DExtArray; index:Int32);
var
i,Hi,M: Integer;
Weight:TExtArray;
begin
Hi := Length(Arr);
if Hi <= 1 then Exit;
SetLength(Weight, Hi);
for i := 0 to Hi-1 do
begin
if index <= -1 then
M := Max(0,High(Arr[i]) + index)
else
M := Min(High(Arr[i]), index);
Weight[i] := Arr[i][M];
end;
__SortATEA(Arr, Weight, Low(Arr), High(Arr));
SetLength(Weight, 0);
end;
|
unit UPCBankStorage;
interface
uses
UStorage, UPCBank;
type
TPCBankStorage = class
private
FStorage : TStorage;
FStorageClass: TStorageClass;
FBank : TPCBank;
{$IF DEFINED(CIRCULAR_REFERENCE_PROBLEM)}
procedure SetBank(const Value: TPCBank);
{$ENDIF}
function GetStorage: TStorage;
procedure SetStorageClass(const Value: TStorageClass);
protected
Function DoSaveBank : Boolean; virtual; abstract;
Function DoRestoreBank(max_block : Int64) : Boolean; virtual; abstract;
public
Function SaveBank : Boolean;
Function RestoreBank(max_block : Int64) : Boolean;
{$IF DEFINED(CIRCULAR_REFERENCE_PROBLEM)}
Property Bank : TPCBank read FBank write SetBank;
{$ENDIF}
Property Storage : TStorage read GetStorage;
Property StorageClass : TStorageClass read FStorageClass write SetStorageClass;
end;
implementation
function TPCBank.GetStorage: TStorage;
begin
if Not Assigned(FStorage) then begin
if Not Assigned(FStorageClass) then raise Exception.Create('StorageClass not defined');
FStorage := FStorageClass.Create(Self);
{$IF DEFINED(CIRCULAR_REFERENCE_PROBLEM)}
FStorage.Bank := Self;
{$ENDIF}
end;
Result := FStorage;
end;
function TStorage.SaveBank: Boolean;
begin
Result := true;
If FIsMovingBlockchain then Exit;
{$IF DEFINED(CIRCULAR_REFERENCE_PROBLEM)}
if Not TPCSafeBox.MustSafeBoxBeSaved(Bank.BlocksCount) then exit; // No save
Try
Result := DoSaveBank;
FBank.SafeBox.CheckMemory;
Except
On E:Exception do begin
TLog.NewLog(lterror,Classname,'Error saving Bank: '+E.Message);
Raise;
end;
End;
{$ENDIF}
end;
{$IF DEFINED(CIRCULAR_REFERENCE_PROBLEM)}
procedure TStorage.SetBank(const Value: TPCBank);
begin
FBank := Value;
end;
{$ENDIF}
function TStorage.RestoreBank(max_block: Int64): Boolean;
begin
Result := DoRestoreBank(max_block);
end;
procedure TPCBank.SetStorageClass(const Value: TStorageClass);
begin
if FStorageClass=Value then exit;
FStorageClass := Value;
if Assigned(FStorage) then FreeAndNil(FStorage);
end;
end.
|
//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
{$IFNDEF _CHAKRACOMMONWINDOWS_H_}
{$DEFINE _CHAKRACOMMONWINDOWS_H_}
type
/// <summary>
/// Called by the runtime to load the source code of the serialized script.
/// The caller must keep the script buffer valid until the JsSerializedScriptUnloadCallback.
/// This callback is only supported by the Win32 version of the API
/// </summary>
/// <param name="sourceContext">The context passed to Js[Parse|Run]SerializedScriptWithCallback</param>
/// <param name="scriptBuffer">The script returned.</param>
/// <returns>
/// true if the operation succeeded, false otherwise.
/// </returns>
JsSerializedScriptLoadSourceCallback = function(sourceContext: JsSourceContext; var scriptBuffer: PWideChar): boolean; stdcall;
/// <summary>
/// Parses a script and returns a function representing the script.
/// </summary>
/// <remarks>
/// Requires an active script context.
/// </remarks>
/// <param name="script">The script to parse.</param>
/// <param name="sourceContext">
/// A cookie identifying the script that can be used by debuggable script contexts.
/// </param>
/// <param name="sourceUrl">The location the script came from.</param>
/// <param name="result">A function representing the script code.</param>
/// <returns>
/// The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.
/// </returns>
function JsParseScript(const script: PWideChar; sourceContext: JsSourceContext; const sourceUrl: PWideChar; var result: JsValueRef): JsErrorCode;
stdcall; external CHAKRA_LIB {$IFDEF MACOS} name '_JsParseScript' {$ENDIF};
/// <summary>
/// Parses a script and returns a function representing the script.
/// </summary>
/// <remarks>
/// Requires an active script context.
/// </remarks>
/// <param name="script">The script to parse.</param>
/// <param name="sourceContext">
/// A cookie identifying the script that can be used by debuggable script contexts.
/// </param>
/// <param name="sourceUrl">The location the script came from.</param>
/// <param name="parseAttributes">Attribute mask for parsing the script</param>
/// <param name="result">A function representing the script code.</param>
/// <returns>
/// The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.
/// </returns>
function JsParseScriptWithAttributes(const script: PWideChar; sourceContext: JsSourceContext; const sourceUrl: PWideChar; parseAttributes: JsParseScriptAttributes; var result: JsValueRef): JsErrorCode;
stdcall; external CHAKRA_LIB {$IFDEF MACOS} name '_JsParseScriptWithAttributes' {$ENDIF};
/// <summary>
/// Executes a script.
/// </summary>
/// <remarks>
/// Requires an active script context.
/// </remarks>
/// <param name="script">The script to run.</param>
/// <param name="sourceContext">
/// A cookie identifying the script that can be used by debuggable script contexts.
/// </param>
/// <param name="sourceUrl">The location the script came from.</param>
/// <param name="result">The result of the script, if any. This parameter can be null.</param>
/// <returns>
/// The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.
/// </returns>
function JsRunScript(const script: PWideChar; sourceContext: JsSourceContext; const sourceUrl: PWideChar; var result: JsValueRef): JsErrorCode;
stdcall; external CHAKRA_LIB {$IFDEF MACOS} name '_JsRunScript' {$ENDIF};
/// <summary>
/// Executes a module.
/// </summary>
/// <remarks>
/// Requires an active script context.
/// </remarks>
/// <param name="script">The module script to parse and execute.</param>
/// <param name="sourceContext">
/// A cookie identifying the script that can be used by debuggable script contexts.
/// </param>
/// <param name="sourceUrl">The location the module script came from.</param>
/// <param name="result">The result of executing the module script, if any. This parameter can be null.</param>
/// <returns>
/// The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.
/// </returns>
function JsExperimentalApiRunModule(const script: PWideChar; sourceContext: JsSourceContext; const sourceUrl: PWideChar; var result: JsValueRef): JsErrorCode;
stdcall; external CHAKRA_LIB {$IFDEF MACOS} name '_JsExperimentalApiRunModule' {$ENDIF};
/// <summary>
/// Serializes a parsed script to a buffer than can be reused.
/// </summary>
/// <remarks>
/// <para>
/// <c>JsSerializeScript</c> parses a script and then stores the parsed form of the script in a
/// runtime-independent format. The serialized script then can be deserialized in any
/// runtime without requiring the script to be re-parsed.
/// </para>
/// <para>
/// Requires an active script context.
/// </para>
/// </remarks>
/// <param name="script">The script to serialize.</param>
/// <param name="buffer">The buffer to put the serialized script into. Can be null.</param>
/// <param name="bufferSize">
/// On entry, the size of the buffer, in bytes; on exit, the size of the buffer, in bytes,
/// required to hold the serialized script.
/// </param>
/// <returns>
/// The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.
/// </returns>
function JsSerializeScript( const script: PWideChar; buffer: PByte; bufferSize: cardinal): JsErrorCode;
stdcall; external CHAKRA_LIB {$IFDEF MACOS} name '_JsSerializeScript' {$ENDIF};
/// <summary>
/// Parses a serialized script and returns a function representing the script.
/// Provides the ability to lazy load the script source only if/when it is needed.
/// </summary>
/// <remarks>
/// <para>
/// Requires an active script context.
/// </para>
/// <para>
/// The runtime will hold on to the buffer until all instances of any functions created from
/// the buffer are garbage collected. It will then call scriptUnloadCallback to inform the
/// caller it is safe to release.
/// </para>
/// </remarks>
/// <param name="scriptLoadCallback">Callback called when the source code of the script needs to be loaded.</param>
/// <param name="scriptUnloadCallback">Callback called when the serialized script and source code are no longer needed.</param>
/// <param name="buffer">The serialized script.</param>
/// <param name="sourceContext">
/// A cookie identifying the script that can be used by debuggable script contexts.
/// This context will passed into scriptLoadCallback and scriptUnloadCallback.
/// </param>
/// <param name="sourceUrl">The location the script came from.</param>
/// <param name="result">A function representing the script code.</param>
/// <returns>
/// The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.
/// </returns>
function JsParseSerializedScriptWithCallback(scriptLoadCallback: JsSerializedScriptLoadSourceCallback; scriptUnloadCallback: JsSerializedScriptUnloadCallback; buffer: PByte; sourceContext: JsSourceContext; const sourceUrl: PWideChar; var result: JsValueRef): JsErrorCode;
stdcall; external CHAKRA_LIB {$IFDEF MACOS} name '_JsParseSerializedScriptWithCallback' {$ENDIF};
/// <summary>
/// Runs a serialized script.
/// Provides the ability to lazy load the script source only if/when it is needed.
/// </summary>
/// <remarks>
/// <para>
/// Requires an active script context.
/// </para>
/// <para>
/// The runtime will hold on to the buffer until all instances of any functions created from
/// the buffer are garbage collected. It will then call scriptUnloadCallback to inform the
/// caller it is safe to release.
/// </para>
/// </remarks>
/// <param name="scriptLoadCallback">Callback called when the source code of the script needs to be loaded.</param>
/// <param name="scriptUnloadCallback">Callback called when the serialized script and source code are no longer needed.</param>
/// <param name="buffer">The serialized script.</param>
/// <param name="sourceContext">
/// A cookie identifying the script that can be used by debuggable script contexts.
/// This context will passed into scriptLoadCallback and scriptUnloadCallback.
/// </param>
/// <param name="sourceUrl">The location the script came from.</param>
/// <param name="result">
/// The result of running the script, if any. This parameter can be null.
/// </param>
/// <returns>
/// The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.
/// </returns>
function JsRunSerializedScriptWithCallback(scriptLoadCallback: JsSerializedScriptLoadSourceCallback; scriptUnloadCallback: JsSerializedScriptUnloadCallback; buffer: PByte; sourceContext: JsSourceContext; const sourceUrl: PWideChar; var result: JsValueRef): JsErrorCode;
stdcall; external CHAKRA_LIB {$IFDEF MACOS} name '_JsRunSerializedScriptWithCallback' {$ENDIF};
/// <summary>
/// Parses a serialized script and returns a function representing the script.
/// </summary>
/// <remarks>
/// <para>
/// Requires an active script context.
/// </para>
/// <para>
/// The runtime will hold on to the buffer until all instances of any functions created from
/// the buffer are garbage collected.
/// </para>
/// </remarks>
/// <param name="script">The script to parse.</param>
/// <param name="buffer">The serialized script.</param>
/// <param name="sourceContext">
/// A cookie identifying the script that can be used by debuggable script contexts.
/// </param>
/// <param name="sourceUrl">The location the script came from.</param>
/// <param name="result">A function representing the script code.</param>
/// <returns>
/// The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.
/// </returns>
function JsParseSerializedScript(const script: PWideChar; buffer: PByte; sourceContext: JsSourceContext; const sourceUrl: PWideChar; var result: JsValueRef): JsErrorCode;
stdcall; external CHAKRA_LIB {$IFDEF MACOS} name '_JsParseSerializedScript' {$ENDIF};
/// <summary>
/// Runs a serialized script.
/// </summary>
/// <remarks>
/// <para>
/// Requires an active script context.
/// </para>
/// <para>
/// The runtime will hold on to the buffer until all instances of any functions created from
/// the buffer are garbage collected.
/// </para>
/// </remarks>
/// <param name="script">The source code of the serialized script.</param>
/// <param name="buffer">The serialized script.</param>
/// <param name="sourceContext">
/// A cookie identifying the script that can be used by debuggable script contexts.
/// </param>
/// <param name="sourceUrl">The location the script came from.</param>
/// <param name="result">
/// The result of running the script, if any. This parameter can be null.
/// </param>
/// <returns>
/// The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.
/// </returns>
function JsRunSerializedScript(const script: PWideChar; buffer: PByte; sourceContext: JsSourceContext; const sourceUrl: PWideChar; var result: JsValueRef): JsErrorCode;
stdcall; external CHAKRA_LIB {$IFDEF MACOS} name '_JsRunSerializedScript' {$ENDIF};
/// <summary>
/// Gets the property ID associated with the name.
/// </summary>
/// <remarks>
/// <para>
/// Property IDs are specific to a context and cannot be used across contexts.
/// </para>
/// <para>
/// Requires an active script context.
/// </para>
/// </remarks>
/// <param name="name">
/// The name of the property ID to get or create. The name may consist of only digits.
/// </param>
/// <param name="propertyId">The property ID in this runtime for the given name.</param>
/// <returns>
/// The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.
/// </returns>
function JsGetPropertyIdFromName(const name: PWideChar; var propertyId: JsPropertyIdRef): JsErrorCode;
stdcall; external CHAKRA_LIB {$IFDEF MACOS} name '_JsGetPropertyIdFromName' {$ENDIF};
/// <summary>
/// Gets the name associated with the property ID.
/// </summary>
/// <remarks>
/// <para>
/// Requires an active script context.
/// </para>
/// <para>
/// The returned buffer is valid as long as the runtime is alive and cannot be used
/// once the runtime has been disposed.
/// </para>
/// </remarks>
/// <param name="propertyId">The property ID to get the name of.</param>
/// <param name="name">The name associated with the property ID.</param>
/// <returns>
/// The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.
/// </returns>
function JsGetPropertyNameFromId(propertyId: JsPropertyIdRef; var name: PWideChar): JsErrorCode;
stdcall; external CHAKRA_LIB {$IFDEF MACOS} name '_JsGetPropertyNameFromId' {$ENDIF};
/// <summary>
/// Creates a string value from a string pointer.
/// </summary>
/// <remarks>
/// Requires an active script context.
/// </remarks>
/// <param name="stringValue">The string pointer to convert to a string value.</param>
/// <param name="stringLength">The length of the string to convert.</param>
/// <param name="value">The new string value.</param>
/// <returns>
/// The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.
/// </returns>
function JsPointerToString(const stringValue: PWideChar; stringLength: NativeUInt; var value: JsValueRef): JsErrorCode;
stdcall; external CHAKRA_LIB {$IFDEF MACOS} name '_JsPointerToString' {$ENDIF};
/// <summary>
/// Retrieves the string pointer of a string value.
/// </summary>
/// <remarks>
/// <para>
/// This function retrieves the string pointer of a string value. It will fail with
/// <c>JsErrorInvalidArgument</c> if the type of the value is not string. The lifetime
/// of the string returned will be the same as the lifetime of the value it came from, however
/// the string pointer is not considered a reference to the value (and so will not keep it
/// from being collected).
/// </para>
/// <para>
/// Requires an active script context.
/// </para>
/// </remarks>
/// <param name="value">The string value to convert to a string pointer.</param>
/// <param name="stringValue">The string pointer.</param>
/// <param name="stringLength">The length of the string.</param>
/// <returns>
/// The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.
/// </returns>
function JsStringToPointer(value: JsValueRef; var stringValue: PWideChar; var stringLength: NativeUInt): JsErrorCode;
stdcall; external CHAKRA_LIB {$IFDEF MACOS} name '_JsStringToPointer' {$ENDIF};
{$ENDIF} // _CHAKRACOMMONWINDOWS_H_
|
unit eInterestSimulator.Controller.Sistema;
interface
uses
eInterestSimulator.Controller.Interfaces, System.Generics.Collections,
eInterestSimulator.Model.Interfaces;
type
TControllerSistema = class(TInterfacedObject, iControllerSistema)
private
FDicionarioSistemas: TDictionary<TTypeSistema, iSistema>;
function SistemasLiberados: TDictionary<TTypeSistema, iSistema>;
function SistemasLiberadosList: TList<iSistema>;
procedure AdicionaSistemas;
public
constructor Create;
destructor Destroy; override;
class function New: iControllerSistema;
end;
implementation
uses
eInterestSimulator.Model.Calculadora.Factory, System.SysUtils,
eInterestSimulator.Model.Simulador.Factory,
eInterestSimulator.Model.Sistema;
{ TControllerSistema }
constructor TControllerSistema.Create;
begin
AdicionaSistemas;
end;
procedure TControllerSistema.AdicionaSistemas;
begin
FDicionarioSistemas := TDictionary<TTypeSistema, iSistema>.Create;
FDicionarioSistemas.Add(tpAlemao, TModelSistema.New.Descricao('Alemão')
.Habilitado(False).TipoSistema(tpAlemao));
FDicionarioSistemas.Add(tpAmericano, TModelSistema.New.Descricao('Americano')
.Habilitado(False).TipoSistema(tpAmericano));
FDicionarioSistemas.Add(tpAmortizacaoConstante,
TModelSistema.New.Descricao('Amortização Constante').Habilitado(False)
.TipoSistema(tpAmortizacaoConstante));
FDicionarioSistemas.Add(tpAmortizacaoMisto,
TModelSistema.New.Descricao('Amortização Misto').Habilitado(False)
.TipoSistema(tpAmortizacaoMisto));
FDicionarioSistemas.Add(tpPagamentoUnico,
TModelSistema.New.Descricao('Pagamento Único').Habilitado(True)
.TipoSistema(tpPagamentoUnico));
FDicionarioSistemas.Add(tpPagamentoVariavel,
TModelSistema.New.Descricao('Pagamento Variável').Habilitado(False)
.TipoSistema(tpPagamentoVariavel));
FDicionarioSistemas.Add(tpPrice,
TModelSistema.New.Descricao('Price (Francês)').Habilitado(False)
.TipoSistema(tpPrice));
end;
destructor TControllerSistema.Destroy;
begin
FDicionarioSistemas.Free;
inherited;
end;
class function TControllerSistema.New: iControllerSistema;
begin
Result := Self.Create;
end;
function TControllerSistema.SistemasLiberadosList: TList<iSistema>;
var
Sistema: iSistema;
FSistemasLiberados: TList<iSistema>;
begin
FSistemasLiberados := TList<iSistema>.Create;
for Sistema in FDicionarioSistemas.Values do
begin
if Sistema.Habilitado() then
FSistemasLiberados.Add(Sistema);
end;
{TODO -oRenatoPradebon -cGeneral : aqui tem um problema memory leak que eu não consegui resolver}
Result := TList<iSistema>.Create(FSistemasLiberados);
FreeandNil(FSistemasLiberados);
end;
function TControllerSistema.SistemasLiberados
: TDictionary<TTypeSistema, iSistema>;
begin
Result := FDicionarioSistemas;
end;
end.
|
unit karnov_hw;
interface
uses {$IFDEF WINDOWS}windows,{$ENDIF}
m68000,main_engine,controls_engine,gfx_engine,rom_engine,pal_engine,
ym_2203,ym_3812,m6502,sound_engine,mcs51;
function iniciar_karnov:boolean;
implementation
const
//Karnov
karnov_rom:array[0..5] of tipo_roms=(
(n:'dn08-6.j15';l:$10000;p:0;crc:$4c60837f),(n:'dn11-6.j20';l:$10000;p:$1;crc:$cd4abb99),
(n:'dn07-.j14';l:$10000;p:$20000;crc:$fc14291b),(n:'dn10-.j18';l:$10000;p:$20001;crc:$a4a34e37),
(n:'dn06-5.j13';l:$10000;p:$40000;crc:$29d64e42),(n:'dn09-5.j17';l:$10000;p:$40001;crc:$072d7c49));
karnov_mcu:tipo_roms=(n:'dn-5.k14';l:$1000;p:$0;crc:$d056de4e);
karnov_sound:tipo_roms=(n:'dn05-5.f3';l:$8000;p:$8000;crc:$fa1a31a8);
karnov_char:tipo_roms=(n:'dn00-.c5';l:$8000;p:$0;crc:$0ed77c6d);
karnov_tiles:array[0..3] of tipo_roms=(
(n:'dn04-.d18';l:$10000;p:0;crc:$a9121653),(n:'dn01-.c15';l:$10000;p:$10000;crc:$18697c9e),
(n:'dn03-.d15';l:$10000;p:$20000;crc:$90d9dd9c),(n:'dn02-.c18';l:$10000;p:$30000;crc:$1e04d7b9));
karnov_sprites:array[0..7] of tipo_roms=(
(n:'dn12-.f8';l:$10000;p:$00000;crc:$9806772c),(n:'dn14-5.f11';l:$8000;p:$10000;crc:$ac9e6732),
(n:'dn13-.f9';l:$10000;p:$20000;crc:$a03308f9),(n:'dn15-5.f12';l:$8000;p:$30000;crc:$8933fcb8),
(n:'dn16-.f13';l:$10000;p:$40000;crc:$55e63a11),(n:'dn17-5.f15';l:$8000;p:$50000;crc:$b70ae950),
(n:'dn18-.f16';l:$10000;p:$60000;crc:$2ad53213),(n:'dn19-5.f18';l:$8000;p:$70000;crc:$8fd4fa40));
karnov_proms:array[0..1] of tipo_roms=(
(n:'dn-21.k8';l:$400;p:$0;crc:$aab0bb93),(n:'dn-20.l6';l:$400;p:$400;crc:$02f78ffb));
//Chelnov
chelnov_rom:array[0..5] of tipo_roms=(
(n:'ee08-e.j16';l:$10000;p:0;crc:$8275cc3a),(n:'ee11-e.j19';l:$10000;p:$1;crc:$889e40a0),
(n:'ee07.j14';l:$10000;p:$20000;crc:$51465486),(n:'ee10.j18';l:$10000;p:$20001;crc:$d09dda33),
(n:'ee06-e.j13';l:$10000;p:$40000;crc:$55acafdb),(n:'ee09-e.j17';l:$10000;p:$40001;crc:$303e252c));
chelnov_sound:tipo_roms=(n:'ee05-.f3';l:$8000;p:$8000;crc:$6a8936b4);
chelnov_mcu:tipo_roms=(n:'ee-e.k14';l:$1000;p:$0;crc:$b7045395);
chelnov_char:tipo_roms=(n:'ee00-e.c5';l:$8000;p:$0;crc:$e06e5c6b);
chelnov_tiles:array[0..3] of tipo_roms=(
(n:'ee04-.d18';l:$10000;p:0;crc:$96884f95),(n:'ee01-.c15';l:$10000;p:$10000;crc:$f4b54057),
(n:'ee03-.d15';l:$10000;p:$20000;crc:$7178e182),(n:'ee02-.c18';l:$10000;p:$30000;crc:$9d7c45ae));
chelnov_sprites:array[0..3] of tipo_roms=(
(n:'ee12-.f8';l:$10000;p:$00000;crc:$9b1c53a5),(n:'ee13-.f9';l:$10000;p:$20000;crc:$72b8ae3e),
(n:'ee14-.f13';l:$10000;p:$40000;crc:$d8f4bbde),(n:'ee15-.f15';l:$10000;p:$60000;crc:$81e3e68b));
chelnov_proms:array[0..1] of tipo_roms=(
(n:'ee21.k8';l:$400;p:$0;crc:$b1db6586),(n:'ee20.l6';l:$400;p:$400;crc:$41816132));
//DIP
karnov_dip:array [0..9] of def_dip=(
(mask:$3;name:'Coin A';number:4;dip:((dip_val:0;dip_name:'2C 1C'),(dip_val:3;dip_name:'1C 1C'),(dip_val:2;dip_name:'1C 2C'),(dip_val:1;dip_name:'1C 3C'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$c;name:'Coin B';number:4;dip:((dip_val:0;dip_name:'2C 1C'),(dip_val:$c;dip_name:'1C 1C'),(dip_val:8;dip_name:'1C 2C'),(dip_val:4;dip_name:'1C 3C'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$20;name:'Flip Screen';number:2;dip:((dip_val:$20;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$40;name:'Cabinet';number:2;dip:((dip_val:0;dip_name:'Upright'),(dip_val:$40;dip_name:'Cocktail'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$300;name:'Lives';number:4;dip:((dip_val:$100;dip_name:'1'),(dip_val:$300;dip_name:'3'),(dip_val:$200;dip_name:'5'),(dip_val:0;dip_name:'Infinite'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$c00;name:'Bonus Life';number:4;dip:((dip_val:$c00;dip_name:'50 "K"'),(dip_val:$800;dip_name:'70 "K"'),(dip_val:$400;dip_name:'90 "K"'),(dip_val:0;dip_name:'100 "K"'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$3000;name:'Difficulty';number:4;dip:((dip_val:$2000;dip_name:'Easy'),(dip_val:$3000;dip_name:'Normal'),(dip_val:$1000;dip_name:'Hard'),(dip_val:0;dip_name:'Hardest'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$4000;name:'Demo Sounds';number:2;dip:((dip_val:0;dip_name:'Off'),(dip_val:$4000;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$8000;name:'Time Speed';number:2;dip:((dip_val:$8000;dip_name:'Normal'),(dip_val:0;dip_name:'Fast'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),());
chelnov_dip:array [0..8] of def_dip=(
(mask:$3;name:'Coin A';number:4;dip:((dip_val:0;dip_name:'1C 6C'),(dip_val:3;dip_name:'1C 2C'),(dip_val:2;dip_name:'1C 3C'),(dip_val:1;dip_name:'1C 4C'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$c;name:'Coin B';number:4;dip:((dip_val:0;dip_name:'1C 4C'),(dip_val:$c;dip_name:'1C 1C'),(dip_val:8;dip_name:'2C 1C'),(dip_val:4;dip_name:'3C 1C'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$20;name:'Demo Sounds';number:2;dip:((dip_val:$20;dip_name:'On'),(dip_val:$0;dip_name:'Off'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$40;name:'Flip Screen';number:2;dip:((dip_val:0;dip_name:'On'),(dip_val:$40;dip_name:'Off'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$80;name:'Cainet';number:2;dip:((dip_val:0;dip_name:'Upright'),(dip_val:$80;dip_name:'Cocktail'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$300;name:'Lives';number:4;dip:((dip_val:$100;dip_name:'1'),(dip_val:$300;dip_name:'3'),(dip_val:$200;dip_name:'5'),(dip_val:0;dip_name:'Infinite'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$c00;name:'Difficulty';number:4;dip:((dip_val:$800;dip_name:'Easy'),(dip_val:$c00;dip_name:'Normal'),(dip_val:$400;dip_name:'Hard'),(dip_val:0;dip_name:'Hardest'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$1000;name:'Allow Continue';number:2;dip:((dip_val:$0;dip_name:'No'),(dip_val:$1000;dip_name:'Yes'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),());
var
rom:array[0..$2ffff] of word;
ram:array[0..$1fff] of word;
sprite_ram,sprite_ram2:array[0..$7ff] of word;
background_ram,video_ram:array[0..$3ff] of word;
sound_latch,mcu_p0,mcu_p1,mcu_p2:byte;
scroll_x,scroll_y,maincpu_to_mcu,mcu_to_maincpu:word;
procedure eventos_karnov;
begin
if event.arcade then begin
//P1 + P2
if arcade_input.up[0] then marcade.in0:=(marcade.in0 and $fffe) else marcade.in0:=(marcade.in0 or $1);
if arcade_input.down[0] then marcade.in0:=(marcade.in0 and $fffd) else marcade.in0:=(marcade.in0 or $2);
if arcade_input.left[0] then marcade.in0:=(marcade.in0 and $fffb) else marcade.in0:=(marcade.in0 or $4);
if arcade_input.right[0] then marcade.in0:=(marcade.in0 and $fff7) else marcade.in0:=(marcade.in0 or $8);
if arcade_input.but0[0] then marcade.in0:=(marcade.in0 and $ffef) else marcade.in0:=(marcade.in0 or $10);
if arcade_input.but1[0] then marcade.in0:=(marcade.in0 and $ffdf) else marcade.in0:=(marcade.in0 or $20);
if arcade_input.but2[0] then marcade.in0:=(marcade.in0 and $ffbf) else marcade.in0:=(marcade.in0 or $40);
if arcade_input.up[1] then marcade.in0:=(marcade.in0 and $feff) else marcade.in0:=(marcade.in0 or $100);
if arcade_input.down[1] then marcade.in0:=(marcade.in0 and $fdff) else marcade.in0:=(marcade.in0 or $200);
if arcade_input.left[1] then marcade.in0:=(marcade.in0 and $fbff) else marcade.in0:=(marcade.in0 or $400);
if arcade_input.right[1] then marcade.in0:=(marcade.in0 and $f7ff) else marcade.in0:=(marcade.in0 or $800);
if arcade_input.but0[1] then marcade.in0:=(marcade.in0 and $efff) else marcade.in0:=(marcade.in0 or $1000);
if arcade_input.but1[1] then marcade.in0:=(marcade.in0 and $dfff) else marcade.in0:=(marcade.in0 or $2000);
if arcade_input.but2[1] then marcade.in0:=(marcade.in0 and $bfff) else marcade.in0:=(marcade.in0 or $4000);
//SYSTEM
if arcade_input.start[0] then marcade.in1:=(marcade.in1 and $fb) else marcade.in1:=(marcade.in1 or $4);
if arcade_input.start[1] then marcade.in1:=(marcade.in1 and $f7) else marcade.in1:=(marcade.in1 or $8);
//Coin
if arcade_input.coin[1] then begin
marcade.in2:=(marcade.in2 and $df);
mcs51_0.change_irq0(ASSERT_LINE);
end else marcade.in2:=(marcade.in2 or $20);
if arcade_input.coin[0] then begin
marcade.in2:=(marcade.in2 and $bf);
mcs51_0.change_irq0(ASSERT_LINE);
end else marcade.in2:=(marcade.in2 or $40);
end;
end;
procedure update_video_karnov;
var
f,atrib,nchar,nchar2,x,y:word;
color:byte;
extra,fx,fy:boolean;
begin
for f:=$0 to $3ff do begin
y:=f shr 5;
x:=f and $1f;
//Chars
if gfx[0].buffer[f] then begin
atrib:=video_ram[f];
nchar:=atrib and $3ff;
color:=atrib shr 14;
put_gfx_trans(x*8,y*8,nchar,color shl 3,1,0);
gfx[0].buffer[f]:=false;
end;
//Tiles
if gfx[1].buffer[f] then begin
atrib:=background_ram[f];
nchar:=atrib and $7ff;
color:=atrib shr 12;
put_gfx(x*16,y*16,nchar,(color shl 4)+$200,2,1);
gfx[1].buffer[f]:=false;
end;
end;
scroll_x_y(2,3,scroll_x,scroll_y);
//Sprites
for f:=0 to $1ff do begin
y:=sprite_ram2[f*4];
if ((y and $8000)=0) then continue;
atrib:=sprite_ram2[(f*4)+1];
if ((atrib and $1)=0) then continue;
y:=y and $1ff;
nchar:=sprite_ram2[(f*4)+3];
color:=nchar shr 12;
nchar:=nchar and $fff;
x:=sprite_ram2[(f*4)+2] and $1ff;
extra:=(atrib and $10)<>0;
fy:=(atrib and $2)<>0;
fx:=(atrib and $4)<>0;
if extra then begin
y:=y+16;
nchar:=nchar and $ffe;
end;
//Convert the co-ords..
x:=(x+16) and $1ff;
y:=(y+16) and $1ff;
x:=(256-x) and $1ff;
y:=(256-y) and $1ff;
// Y Flip determines order of multi-sprite
if (extra and fy) then begin
nchar2:=nchar;
nchar:=nchar+1;
end else nchar2:=nchar+1;
put_gfx_sprite(nchar,(color shl 4)+256,fx,fy,2);
actualiza_gfx_sprite(x,y,3,2);
// 1 more sprite drawn underneath
if extra then begin
put_gfx_sprite(nchar2,(color shl 4)+256,fx,fy,2);
actualiza_gfx_sprite(x,y+16,3,2);
end;
end;
actualiza_trozo(0,0,256,256,1,0,0,256,256,3);
actualiza_trozo_final(0,8,256,240,3);
end;
procedure karnov_principal;
var
frame_m,frame_s,frame_mcu:single;
f:byte;
begin
init_controls(false,false,false,true);
frame_m:=m68000_0.tframes;
frame_s:=m6502_0.tframes;
frame_mcu:=mcs51_0.tframes;
while EmuStatus=EsRuning do begin
for f:=0 to $ff do begin
m68000_0.run(frame_m);
frame_m:=frame_m+m68000_0.tframes-m68000_0.contador;
m6502_0.run(frame_s);
frame_s:=frame_s+m6502_0.tframes-m6502_0.contador;
mcs51_0.run(frame_mcu);
frame_mcu:=frame_mcu+mcs51_0.tframes-mcs51_0.contador;
case f of
30:marcade.in1:=marcade.in1 and $7f;
247:begin
marcade.in1:=marcade.in1 or $80;
m68000_0.irq[7]:=ASSERT_LINE;
update_video_karnov;
end;
end;
end;
eventos_karnov;
video_sync;
end;
end;
function karnov_getword(direccion:dword):word;
begin
case direccion of
$0..$5ffff:karnov_getword:=rom[direccion shr 1];
$60000..$63fff:karnov_getword:=ram[(direccion and $3fff) shr 1];
$80000..$80fff:karnov_getword:=sprite_ram[(direccion and $fff) shr 1];
$a0000..$a07ff:karnov_getword:=video_ram[(direccion and $7ff) shr 1];
$c0000:karnov_getword:=marcade.in0;
$c0002:karnov_getword:=marcade.in1;
$c0004:karnov_getword:=marcade.dswa;
$c0006:karnov_getword:=mcu_to_maincpu;
end;
end;
procedure karnov_putword(direccion:dword;valor:word);
begin
case direccion of
0..$5ffff:; //ROM
$60000..$63fff:ram[(direccion and $3fff) shr 1]:=valor;
$80000..$80fff:sprite_ram[(direccion and $fff) shr 1]:=valor;
$a0000..$a0fff:if video_ram[(direccion and $7ff) shr 1]<>valor then begin
video_ram[(direccion and $7ff) shr 1]:=valor;
gfx[0].buffer[(direccion and $7ff) shr 1]:=true;
end;
$a1000..$a17ff:if background_ram[(direccion and $7ff) shr 1]<>valor then begin
background_ram[(direccion and $7ff) shr 1]:=valor;
gfx[1].buffer[(direccion and $7ff) shr 1]:=true;
end;
$a1800..$a1fff:begin
direccion:=(direccion and $7ff) shr 1;
direccion:=((direccion and $1f) shl 5) or ((direccion and $3e0) shr 5);
if background_ram[direccion and $3ff]<>valor then begin
background_ram[direccion and $3ff]:=valor;
gfx[1].buffer[direccion and $3ff]:=true;
end;
end;
$c0000:m68000_0.irq[6]:=CLEAR_LINE;
$c0002:begin
sound_latch:=valor and $ff;
m6502_0.change_nmi(PULSE_LINE);
end;
$c0004:copymemory(@sprite_ram2,@sprite_ram,$800*2);
$c0006:begin
maincpu_to_mcu:=valor;
mcs51_0.change_irq1(ASSERT_LINE);
end;
$c0008:begin
scroll_x:=valor and $1ff;
main_screen.flip_main_screen:=(valor and $8000)<>0;
end;
$c000a:scroll_y:=valor and $1ff;
$c000e:m68000_0.irq[7]:=CLEAR_LINE;
end;
end;
function karnov_snd_getbyte(direccion:word):byte;
begin
case direccion of
$0..$5ff,$8000..$ffff:karnov_snd_getbyte:=mem_snd[direccion];
$800:karnov_snd_getbyte:=sound_latch;
end;
end;
procedure karnov_snd_putbyte(direccion:word;valor:byte);
begin
case direccion of
$0..$5ff:mem_snd[direccion]:=valor;
$1000:ym2203_0.Control(valor);
$1001:ym2203_0.Write(valor);
$1800:ym3812_0.control(valor);
$1801:ym3812_0.write(valor);
$8000..$ffff:; //ROM
end;
end;
procedure karnov_sound_update;
begin
ym3812_0.update;
ym2203_0.update;
end;
function in_port0:byte;
begin
in_port0:=mcu_p0;
end;
function in_port1:byte;
begin
in_port1:=mcu_p1;
end;
function in_port3:byte;
begin
//COIN
in_port3:=marcade.in2;
end;
procedure out_port0(valor:byte);
begin
mcu_p0:=valor;
end;
procedure out_port1(valor:byte);
begin
mcu_p1:=valor;
end;
procedure out_port2(valor:byte);
begin
if (((mcu_p2 and 1)<>0) and ((valor and 1)=0)) then mcs51_0.change_irq0(CLEAR_LINE);
if (((mcu_p2 and 2)<>0) and ((valor and 2)=0)) then mcs51_0.change_irq1(CLEAR_LINE);
if (((mcu_p2 and 4)<>0) and ((valor and 4)=0)) then m68000_0.irq[6]:=ASSERT_LINE;
if (((mcu_p2 and $10)<>0) and ((valor and $10)=0)) then mcu_p0:=maincpu_to_mcu shr 0;
if (((mcu_p2 and $20)<>0) and ((valor and $20)=0)) then mcu_p1:=maincpu_to_mcu shr 8;
if (((mcu_p2 and $40)<>0) and ((valor and $40)=0)) then mcu_to_maincpu:=(mcu_to_maincpu and $ff00) or (mcu_p0 shl 0);
if (((mcu_p2 and $80)<>0) and ((valor and $80)=0)) then mcu_to_maincpu:=(mcu_to_maincpu and $00ff) or (mcu_p1 shl 8);
mcu_p2:=valor;
end;
procedure snd_irq(irqstate:byte);
begin
m6502_0.change_irq(irqstate);
end;
//Main
procedure reset_karnov;
begin
m68000_0.reset;
mcs51_0.reset;
m6502_0.reset;
ym3812_0.reset;
ym2203_0.reset;
reset_audio;
marcade.in0:=$ffff;
marcade.in1:=$7f;
marcade.in2:=$ff;
sound_latch:=0;
mcu_p0:=0;
mcu_p1:=0;
mcu_p2:=0;
mcu_to_maincpu:=0;
maincpu_to_mcu:=0;
end;
function iniciar_karnov:boolean;
const
ps_x:array[0..15] of dword=(16*8+0, 16*8+1, 16*8+2, 16*8+3, 16*8+4, 16*8+5, 16*8+6, 16*8+7,
0, 1, 2, 3, 4, 5, 6, 7);
ps_y:array[0..15] of dword=(0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8,
8*8, 9*8, 10*8, 11*8, 12*8, 13*8, 14*8, 15*8 );
var
memoria_temp:array[0..$7ffff] of byte;
f:word;
ctemp1,ctemp2,ctemp3,ctemp4:byte;
colores:tpaleta;
procedure convert_chars;
begin
init_gfx(0,8,8,$400);
gfx[0].trans[0]:=true;
gfx_set_desc_data(3,0,8*8,$6000*8,$4000*8,$2000*8);
convert_gfx(0,0,@memoria_temp,@ps_x[8],@ps_y,false,false);
end;
procedure convert_tiles(num_gfx,mul:byte);
begin
init_gfx(num_gfx,16,16,$800*mul);
gfx[num_gfx].trans[0]:=true;
gfx_set_desc_data(4,0,16*16,($30000*mul)*8,0,($10000*mul)*8,($20000*mul)*8);
convert_gfx(num_gfx,0,@memoria_temp,@ps_x,@ps_y,false,false);
end;
begin
llamadas_maquina.bucle_general:=karnov_principal;
llamadas_maquina.reset:=reset_karnov;
iniciar_karnov:=false;
iniciar_audio(false);
screen_init(1,256,256,true);
screen_init(2,512,512,true);
screen_mod_scroll(2,512,256,511,512,256,511);
screen_init(3,512,512,false,true);
iniciar_video(256,240);
//Main CPU
m68000_0:=cpu_m68000.create(10000000,256);
m68000_0.change_ram16_calls(karnov_getword,karnov_putword);
//Sound CPU
m6502_0:=cpu_m6502.create(1500000,256,TCPU_M6502);
m6502_0.change_ram_calls(karnov_snd_getbyte,karnov_snd_putbyte);
m6502_0.init_sound(karnov_sound_update);
//MCU
mcs51_0:=cpu_mcs51.create(8000000,256);
mcs51_0.change_io_calls(in_port0,in_port1,nil,in_port3,out_port0,out_port1,out_port2,nil);
//Sound Chips
ym3812_0:=ym3812_chip.create(YM3526_FM,3000000);
ym3812_0.change_irq_calls(snd_irq);
ym2203_0:=ym2203_chip.create(1500000,0.25,0.25);
case main_vars.tipo_maquina of
219:begin //Karnov
//MCU ROM
if not(roms_load(mcs51_0.get_rom_addr,karnov_mcu)) then exit;
//cargar roms
if not(roms_load16w(@rom,karnov_rom)) then exit;
//cargar sonido
if not(roms_load(@mem_snd,karnov_sound)) then exit;
//convertir chars
if not(roms_load(@memoria_temp,karnov_char)) then exit;
convert_chars;
//tiles
if not(roms_load(@memoria_temp,karnov_tiles)) then exit;
convert_tiles(1,1);
//sprites
if not(roms_load(@memoria_temp,karnov_sprites)) then exit;
convert_tiles(2,2);
//Paleta
if not(roms_load(@memoria_temp,karnov_proms)) then exit;
//DIP
marcade.dswa:=$ffbf;
marcade.dswa_val:=@karnov_dip;
end;
220:begin //Chelnov
//MCU ROM
if not(roms_load(mcs51_0.get_rom_addr,chelnov_mcu)) then exit;
//cargar roms
if not(roms_load16w(@rom,chelnov_rom)) then exit;
//cargar sonido
if not(roms_load(@mem_snd,chelnov_sound)) then exit;
//convertir chars
if not(roms_load(@memoria_temp,chelnov_char)) then exit;
convert_chars;
//tiles
if not(roms_load(@memoria_temp,chelnov_tiles)) then exit;
convert_tiles(1,1);
//sprites
if not(roms_load(@memoria_temp,chelnov_sprites)) then exit;
convert_tiles(2,2);
//Paleta
if not(roms_load(@memoria_temp,chelnov_proms)) then exit;
//DIP
marcade.dswa:=$ff7f;
marcade.dswa_val:=@chelnov_dip;
end;
end;
//poner la paleta
for f:=0 to $3ff do begin
// red
ctemp1:=(memoria_temp[f] shr 0) and $01;
ctemp2:=(memoria_temp[f] shr 1) and $01;
ctemp3:=(memoria_temp[f] shr 2) and $01;
ctemp4:=(memoria_temp[f] shr 3) and $01;
colores[f].r:=$e*ctemp1+$1f*ctemp2+$43*ctemp3+$8f*ctemp4;
// green
ctemp1:=(memoria_temp[f] shr 4) and $01;
ctemp2:=(memoria_temp[f] shr 5) and $01;
ctemp3:=(memoria_temp[f] shr 6) and $01;
ctemp4:=(memoria_temp[f] shr 7) and $01;
colores[f].g:=$e*ctemp1+$1f*ctemp2+$43*ctemp3+$8f*ctemp4;
// blue
ctemp1:=(memoria_temp[f+$400] shr 0) and $01;
ctemp2:=(memoria_temp[f+$400] shr 1) and $01;
ctemp3:=(memoria_temp[f+$400] shr 2) and $01;
ctemp4:=(memoria_temp[f+$400] shr 3) and $01;
colores[f].b:=$e*ctemp1+$1f*ctemp2+$43*ctemp3+$8f*ctemp4;
end;
set_pal(colores,$400);
//final
reset_karnov;
iniciar_karnov:=true;
end;
end.
|
{
$Project$
$Workfile$
$Revision$
$DateUTC$
$Id$
This file is part of the Indy (Internet Direct) project, and is offered
under the dual-licensing agreement described on the Indy website.
(http://www.indyproject.org/)
Copyright:
(c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved.
}
{
$Log$
}
{
Rev 1.4 10/26/2004 9:36:28 PM JPMugaas
Updated ref.
Rev 1.3 4/19/2004 5:05:54 PM JPMugaas
Class rework Kudzu wanted.
Rev 1.2 2004.02.03 5:45:32 PM czhower
Name changes
Rev 1.1 10/19/2003 2:27:06 PM DSiders
Added localization comments.
Rev 1.0 2/19/2003 10:13:28 PM JPMugaas
Moved parsers to their own classes.
}
unit IdFTPListParseCiscoIOS;
interface
{$i IdCompilerDefines.inc}
uses
Classes,
IdFTPList, IdFTPListParseBase,IdFTPListTypes;
{
I think this FTP Server is embedded in the Cisco routers.
The Cisco IOS router FTP Server only returns filenames, not dirs.
You set up a root dir and then you can only access that.
You might be able to update something such as flash RAM by specifying
pathes with uploads.
}
type
TIdCiscoIOSFTPListItem = class(TIdMinimalFTPListItem);
TIdFTPLPCiscoIOS = class(TIdFTPLPNList)
protected
class function MakeNewItem(AOwner : TIdFTPListItems) : TIdFTPListItem; override;
public
class function GetIdent : String; override;
class function CheckListing(AListing : TStrings; const ASysDescript : String = ''; const ADetails : Boolean = True): Boolean; override;
end;
// RLebeau 2/14/09: this forces C++Builder to link to this unit so
// RegisterFTPListParser can be called correctly at program startup...
(*$HPPEMIT '#pragma link "IdFTPListParseCiscoIOS"'*)
implementation
uses
IdGlobal, IdFTPCommon, IdGlobalProtocols, SysUtils;
{ TIdFTPLPCiscoIOS }
class function TIdFTPLPCiscoIOS.CheckListing(AListing: TStrings;
const ASysDescript: String; const ADetails: Boolean): Boolean;
begin
// Identifier obtained from
// http://www.cisco.com/univercd/cc/td/doc/product/access/acs_serv/as5800/sc_3640/features.htm#xtocid210805
// 1234567890
Result := TextStartsWith(ASysDescript, 'Cisco IOS '); {do not localize}
end;
class function TIdFTPLPCiscoIOS.GetIdent: String;
begin
Result := 'Cisco IOS'; {do not localize}
end;
class function TIdFTPLPCiscoIOS.MakeNewItem(AOwner: TIdFTPListItems): TIdFTPListItem;
begin
Result := TIdCiscoIOSFTPListItem.Create(AOwner);
end;
initialization
RegisterFTPListParser(TIdFTPLPCiscoIOS);
finalization
UnRegisterFTPListParser(TIdFTPLPCiscoIOS);
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 OraBarConn;
interface
uses Ora, dxBar, Classes, Graphics, Controls, Forms, OraClasses;
const
CON_SUCCESS = 0;
CON_FAILED = 1;
type
TLoginParams = record
Server,
UserName,
Password,
ConnectionString,
HomeName: string;
ConnectionMode: string;
OraSession : TOraSession;
end;
PLoginParams = ^TLoginParams;
TBarConnection = class(TdxBarButton)
private
FSession : TOraSession;
FLastError : String;
FLoginParams: TLoginParams;
FCount: Integer;
function GetIsAlive: Boolean;
function GetIsConnected: Boolean;
procedure SetSession(ASession: TOraSession);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy(); override;
function Connect(AParams : PLoginParams) : Integer;
property Session: TOraSession read FSession write SetSession;
property IsConnected : Boolean read GetIsConnected;
property IsAlive : Boolean read GetIsAlive;
property LastError : String read FLastError;
property Count: integer read FCount write FCount;
end;
implementation
uses SysUtils;
constructor TBarConnection.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FSession := TOraSession.Create(nil);
FLastError := '';
end;
destructor TBarConnection.Destroy;
begin
inherited;
end;
function TBarConnection.Connect(AParams : PLoginParams): Integer;
begin
FLoginParams := AParams^;
FLastError := '';
with FLoginParams do
begin
FSession.Server := Server;
FSession.Username := UserName;
FSession.Password := Password;
FSession.ConnectString := ConnectionString;
FSession.HomeName := HomeName;
if ConnectionMode = 'Normal' then
FSession.ConnectMode := cmNormal;
if ConnectionMode = 'SysDBA' then
FSession.ConnectMode := cmSysDBA;
if ConnectionMode = 'SysOper' then
FSession.ConnectMode := cmSysOper;
end;
FSession.LoginPrompt := false;
try
FSession.Connect();
Result := CON_SUCCESS;
except
on E : Exception do
begin
FLastError := E.Message;
Result := CON_FAILED;
end;
end;
end;
procedure TBarConnection.SetSession(ASession: TOraSession);
begin
FSession := ASession;
if FSession.Connected = false then
begin
try
FSession.LoginPrompt := false;
FSession.Connect();
except
on E : Exception do
begin
FLastError := E.Message;
end;
end;
end;
end;
function TBarConnection.GetIsAlive: Boolean;
begin
Result := False;
if IsConnected then Result := FSession.Connected;
end;
function TBarConnection.GetIsConnected: Boolean;
begin
Result := FSession.Connected;
end;
end.
|
{$I tdl_dire.inc}
{$IFDEF USEOVERLAYS}
{$O+,F+}
{$ENDIF}
unit tdl_cons;
{Implements mechanisms for interacting with the user,
including a message console, simple pop-up dialogs, etc.}
interface
uses
objects,
strings,
TDL_glob,
TDL_conf,
totSYS,
totWIN,
totFAST,
totMSG,
totLOOK,
totIO1,
support;
type
messageType=(info,warning,error,fatal);
{Object for logging messages to a file}
PLog=^TLog;
TLog=object(TObject)
logname:string;
Constructor Init(name:string);
Destructor Done; virtual;
Procedure Commit(msg:string);
private
loghandle:text;
end;
{Message console object. Messages are tagged with info, warning, or error
and show up on a virtual screen in different colors. All messages except
info are also logged atomically to the application logfile. If verboselog
is set, then info messages are logged as well.}
PMConsole=^TMConsole;
TMConsole=object(TObject)
verboseLog:boolean; {if true, "info" messages get written to log}
ConScreen,savescreen:PScreenOBJ;
{colors for the console. Default values work for both color and MDA.}
_cnormal,_creverse,_chigh,_cunderline,_cblink:byte;
Constructor Init(logfname:string);
Destructor Done; virtual;
Procedure Show;
Procedure Hide;
Procedure LogMsg(m:messageType;msg:string);
private
fileLog:PLog;
end;
var
MsgConsole:PMConsole;
FStatus:PWinOBJ;
DOSScreen:PScreenObj;
Procedure PopUserMessage(class:messagetype;s:string);
Procedure PopAbout;
Procedure PopHelp;
Function PromptYN(msg:string):boolean;
Function PromptForFilename(blurb:string):string;
procedure die(s:string);
procedure recordKeyState;
procedure restoreKeyState;
procedure pause;
procedure pauseForUser; {uses DOS and BIOS only}
procedure tmpScreenSave;
procedure tmpScreenRestore;
function setVESA(mode:word):word;
implementation
uses
totINPUT,
totIO2;
var
keyState:word;
tmpScreen:PScreenObj;
function setVESA(mode:word):word; assembler;
asm
mov bx,mode
mov mode,0
mov ax,4f02h
int 10h
cmp al,4fh
je @FunctionSupported
mov mode,1 {function not supported}
jmp @done
@FunctionSupported:
cmp ah,01h
jne @done
mov mode,2
@done:
mov ax,mode
end;
procedure die(s:string);
begin
msgConsole^.logMsg(fatal,s);
end;
procedure recordKeyState;
begin
keyState:=key.vLastKey;
end;
procedure restoreKeyState;
begin
key.vLastKey:=keyState;
end;
procedure pause;
begin
recordKeyState;
key.getkey;
restoreKeyState;
end;
procedure pauseForUser; assembler;
asm
push ds
jmp @startit
@msg:
DB 'Press a key to return to the TDL.$'
@startit:
push cs
pop ds
mov dx,offset @msg
mov ah,09h
int 21h
xor ax,ax
int 16h
pop ds
end;
{Okay, so the nil pointer stuff is to prevent if I call tmpScreenSave two or
more times in a row, or try to dispose of it before creating it.
Save me from myself.}
procedure tmpScreenSave;
begin
if tmpScreen=nil
then tmpScreen:=new(PScreenOBJ,init);
tmpScreen^.save;
end;
procedure tmpScreenRestore;
begin
if tmpScreen<>nil then begin
tmpScreen^.display;
dispose(tmpScreen,done);
tmpScreen:=nil;
end;
end;
procedure helpdata; external;
{$L helpdata.obj}
procedure help_40c; external;
{$L help_40c.obj}
Procedure PopHelp;
const
x1=1;
y1=4;
margin:byte=72;
curx:byte=x1;
cury:byte=y1;
var
c:^char;
col:byte;
{$IFDEF USEOVERLAYS}
placeholder:string[40];
{$ENDIF}
begin
{This simple text wrapping algo is not smart enough to look ahead to the
next word boundary; it only does margin wrapping. On the to-do list.}
margin:=screen.width-(screen.width div 10);
curx:=x1;
cury:=y1;
screen.TitledBox(1,1,Screen.Width,Screen.Depth,
LookTOT^.vmenuborder,LookTOT^.vmenutitle,LookTOT^.vmenuborder,
6,'Total DOS Launcher Help');
{$IFDEF USEOVERLAYS}
placeholder:='help text not present when debugging$';
c:=@placeholder;
{$ELSE}
if screen.width<80
then c:=@help_40c
else c:=@helpdata;
{$ENDIF}
col:=LookTOT^.vmenulonorm;
while c^ <> '$' do begin
case c^ of
#13:curx:=x1;
#10:inc(cury);
'~':if col=LookTOT^.vmenulonorm
then col:=LookTOT^.vmenulohot
else col:=LookTOT^.vmenulonorm;
'$':break;
else begin
screen.writeat(curx,cury,col,c^);
inc(curx);
if (c^=#32) and (curx>margin) then begin
curx:=x1;
inc(cury);
end;
end;
end;
inc(word(c)); {advance pointer}
end;
screen.writecenter(screen.depth,LookTOT^.vmenulohot,'Press any key to dismiss');
key.getkey;
end;
Constructor TLog.Init;
begin
Inherited Init;
logname:=name;
assign(loghandle,logname);
if not fileexists(logname)
then rewrite(loghandle)
else append(loghandle);
writeln(loghandle,stdDate+': Log opening');
close(loghandle);
end;
Destructor TLog.Done;
begin
append(loghandle);
writeln(loghandle,stdDate+': Log closing');
close(loghandle);
Inherited Done;
end;
Procedure TLog.commit(msg:string);
begin
append(loghandle);
writeln(loghandle,msg);
close(loghandle);
end;
Constructor TMConsole.Init;
begin
Inherited Init;
_cnormal:=$07;
_creverse:=$70;
_chigh:=$0f;
_cunderline:=$01;
_cblink:=$8c;
if logfname<>''
then new(fileLog,init(logfname))
else fileLog:=nil;
verboseLog:=false;
new(ConScreen,init);
ConScreen^.create(Monitor^.Width,Monitor^.Depth,$08);
ConScreen^.writeAt(1,1,_creverse,'Debug message console. Only recent entries displayed. Press a key to dismiss. ');
end;
Destructor TMConsole.Done;
begin
logMsg(info,'Debug Console closing...');
dispose(ConScreen,done);
if fileLog<>nil then dispose(fileLog,done);
Inherited Done;
end;
Procedure TMConsole.Show;
begin
new(savescreen,init);
savescreen^.save;
ConScreen^.gotoxy(ConScreen^.vwidth,ConScreen^.vDepth);
ConScreen^.Display;
end;
Procedure TMConsole.Hide;
begin
savescreen^.display;
dispose(savescreen,done);
end;
Procedure TMConsole.LogMsg;
var
color:byte;
begin
{prepend a standardized date onto the message to help with troubleshooting}
msg:=stdDate+': '+msg;
{first, make sure it gets into the log file if it is important}
if fileLog<>nil then case m of
info:if verboseLog then fileLog^.Commit(msg);
warning:fileLog^.Commit('Warning: '+msg);
error :fileLog^.Commit('=ERROR= '+msg);
fatal :fileLog^.Commit('=FATAL= '+msg);
end;
{then, insert it into the message console}
ConScreen^.Scroll(up,1,2,ConScreen^.Width,ConScreen^.Depth);
case m of
info:color:=_cnormal;
warning:color:=_chigh;
error,
fatal:color:=_cblink;
end;
{full message committed to file log; truncate for screen printing}
if length(msg)>Monitor^.Width then byte(msg[0]):=Monitor^.Width;
ConScreen^.WriteAt(1,ConScreen^.Depth,color,msg);
{if we have a fatal error,
MAYDAY MAYDAY TOPBENCH IS BUDDY-SPIKED ABORT ABORT ABORT}
if m=fatal then begin
RestoreDOSScreen;
system.writeln('FATAL ERROR: '+msg);
if fileLog<>nil
then system.writeln('It might be prudent to check '+fileLog^.logname+' for clues.');
halt(1);
end;
end;
Procedure PopUserMessage(class:messagetype;s:string);
const
maxlines=8;
var
foomsg:PMessageObj;
loop:byte;
ts:string[12];
margin:byte;
numlines:byte;
wrapped:array[0..maxlines-1] of titleStrType;
begin
{reformat message to wrap lines if it exceeds our margin}
margin:=round(Monitor^.width * 0.66);
if length(s)<margin then begin
numlines:=1;
wrapped[0]:=s;
wrapped[1]:=''; {workaround until I can fix this properly}
end else begin
for numlines:=0 to maxlines-1 do begin
{Trim leading spaces from any wrapped line.
Two attempts is enough, for those who space twice after punctuation.}
if s[1]=#32 then delete(s,1,1);
if s[1]=#32 then delete(s,1,1);
if length(s)<margin then begin
wrapped[numlines]:=s;
break;
end;
if s='' then break;
for loop:=0 to length(s) do begin
if loop>margin then begin
if s[loop]=#32
then break;
end;
end;
wrapped[numlines]:=copy(s,0,loop);
delete(s,0,loop);
end;
end;
case class of
info :ts:='Information';
warning:ts:='Warning:';
error :ts:='Error!';
end;
new(foomsg,init(2,ts));
with foomsg^ do begin
for loop:=0 to numlines do addline(wrapped[loop]);
addline(' ');
show;
MsgConsole^.LogMsg(class,s);
end;
dispose(foomsg,done);
end;
Procedure PopAbout;
var
foomsg:PMessageObj;
loop:byte;
avgobjsize:word;
s:string[20];
begin
new(foomsg,init(2,TDLTitleFull));
with foomsg^ do begin
for loop:=0 to numAboutLines-1 do AddLine(strpas(AboutText[loop]));
show;
end;
dispose(foomsg,done);
end;
function PromptYN(msg:string):boolean;
var
PromptWin:PPromptOBJ;
result:tAction;
begin
new(promptwin,Init(1,''));
with PromptWin^ do begin
AddLine(msg);
AddLine(' ');
SetOption(1,' ~Y~es ',89,Finished);
SetOption(2,' ~N~o ',78,Escaped);
Result := Show;
end;
PromptYN:=(Result = Finished);
dispose(promptwin,done);
end;
Function PromptForFilename(blurb:string):string;
var
PromptWin:PWinOBJ;
fname:PLateralIOOBJ;
wid:byte;
begin
new(PromptWin,init);
wid:=Monitor^.width;
with PromptWin^ do begin
SetSize(4,2,wid-5,4,1);
SetTitle(blurb);
SetClose(false);
draw;
screen.writeplain(1,1,'Filename: ');
end;
new(fname,init(10,1,wid-10,127));
with fname^ do begin
SetLabel('Filename: ');
Activate;
PromptForFilename:=GetValue;
end;
dispose(fname,done);
dispose(PromptWin,done);
end;
end. |
{ *************************************************************************** }
{ }
{ This file is part of the XPde project }
{ }
{ Copyright (c) 2002 Jose Leon Serna <ttm@xpde.com> }
{ }
{ This program is free software; you can redistribute it and/or }
{ modify it under the terms of the GNU General Public }
{ License as published by the Free Software Foundation; either }
{ version 2 of the License, or (at your option) any later version. }
{ }
{ This program is distributed in the hope that it will be useful, }
{ but WITHOUT ANY WARRANTY; without even the implied warranty of }
{ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU }
{ General Public License for more details. }
{ }
{ You should have received a copy of the GNU General Public License }
{ along with this program; see the file COPYING. If not, write to }
{ the Free Software Foundation, Inc., 59 Temple Place - Suite 330, }
{ Boston, MA 02111-1307, USA. }
{ }
{ *************************************************************************** }
unit uXPDesktop;
interface
{ TODO : All this must use the XPFS, once is finished }
uses
Classes, uXPShellListView, uRegistry,
QGraphics, uCommon, SysUtils,
QDialogs, uXPIPC;
type
//Inherits from the shelllistview
TXPDesktop=class(TXPShellListView)
public
procedure IPCNotification(Sender:TObject; msg:integer; data: integer);
procedure setup;
procedure configureBackground;
function getSystemImage(Sender:TObject; const itemindex:integer):integer;
function getSystemCaption(Sender:TObject; const itemindex:integer):string;
constructor Create(AOwner:TComponent);override;
destructor Destroy;override;
end;
implementation
{ TXPDesktop }
//Configures the background
procedure TXPDesktop.configureBackground;
var
registry: TRegistry;
bImage: string;
method: integer;
color: TColor;
wallpapers_dir: string;
begin
//Read configurations from the registry
registry:=TRegistry.Create;
try
registry.RootKey:=HKEY_CURRENT_USER;
if registry.OpenKey('Software/XPde/Desktop/Background', false) then begin
bImage:=registry.ReadString('Image');
method:=registry.ReadInteger('Method');
color:=stringtocolor(registry.ReadString('Color'));
if (bImage<>'') and (bImage<>'none') then begin
self.color:=color;
setbackgroundimage(bImage,method);
end
else setbackgroundcolor(color);
end
else begin
wallpapers_dir:=getSystemInfo(XP_WALLPAPERS_DIR);
if (fileexists(wallpapers_dir+'/default.png')) then begin
setbackgroundimage(wallpapers_dir+'/default.png',2);
end
else setbackgroundcolor(clHighLight);
end;
finally
registry.free;
end;
end;
constructor TXPDesktop.Create(AOwner: TComponent);
begin
inherited;
//Setups the IPC component to receive notifications from changes on the desktop configuration
XPIPC.setupApplication;
XPIPC.OnNotification:=IPCNotification;
end;
destructor TXPDesktop.Destroy;
begin
inherited;
end;
function TXPDesktop.getSystemCaption(Sender: TObject;
const itemindex: integer): string;
begin
//Returns a system caption
case itemindex of
0: result:='My Documents';
1: result:='My Computer';
2: result:='My Home';
3: result:='My Network Places';
4: result:='Recycle Bin';
end;
end;
function TXPDesktop.getSystemImage(Sender: TObject;
const itemindex: integer): integer;
begin
//Returns a system image
result:=itemindex+2;
end;
//If the desktop must be refreshed
procedure TXPDesktop.IPCNotification(Sender: TObject; msg, data: integer);
begin
case msg of
XPDE_DESKTOPCHANGED: begin
configurebackground;
redraw();
end;
end;
end;
procedure TXPDesktop.setup;
var
desktop_dir: string;
begin
IconLocationsKey:='Software/XPde/Desktop/IconLocations';
//Configures the background
configureBackground;
OnGetSystemImage:=getSystemimage;
OnGetSystemCaption:=getSystemCaption;
//Sets the desktop directory
SystemIcons:=5;
desktop_dir:=getSystemInfo(XP_DESKTOP_DIR);
forcedirectories(desktop_dir);
Directory:=desktop_dir;
end;
end.
|
{
Clever Internet Suite
Copyright (C) 2014 Clever Components
All Rights Reserved
www.CleverComponents.com
}
unit clOAuth;
interface
{$I clVer.inc}
uses
{$IFNDEF DELPHIXE2}
Classes, SysUtils, Dialogs, ShellAPI, Windows,{$IFDEF DEMO} Forms, clEncoder, clEncryptor, clCertificate, clHtmlParser,{$ENDIF}
{$ELSE}
System.Classes, System.SysUtils, Vcl.Dialogs, Winapi.ShellAPI, Winapi.Windows,
{$IFDEF DEMO} Vcl.Forms, clEncoder, clEncryptor, clCertificate, clHtmlParser,{$ENDIF}
{$ENDIF}
clHttp, clHttpRequest, clJson, clSimpleHttpServer, clHttpUtils, clUriUtils{$IFDEF LOGGER}, clLogger{$ENDIF};
type
EclOAuthError = class(Exception)
private
FErrorCode: Integer;
public
constructor Create(const AErrorMsg: string; AErrorCode: Integer; ADummy: Boolean = False);
property ErrorCode: Integer read FErrorCode;
end;
TclAuthorizationFlowType = (afAuthCodeFlow, afImplicitGrantFlow, afClientCredentialsFlow, afUserPasswordFlow, afRefreshTokenFlow);
TclAuthorizationEndPointType = (apEnterCodeForm, apLocalWebServer, apWebApplication);
TclOAuthTokenEndPoint = (tpUsePost, tpUseGet);
TclAuthorizationResponseType = (rtAuthCode, rtAuthToken, rtExtension);
TclOAuth = class;
TclOAuthToken = class
private
FRefreshToken: string;
FTokenType: string;
FAccessToken: string;
FExpiresIn: string;
FScope: string;
protected
function GetAuthorization: string; virtual;
public
procedure Parse(AResponse: TclJSONBase); virtual;
procedure Clear; virtual;
function ToJson: TclJSONObject; virtual;
{$IFDEF DELPHI2009}
function ToString: string; override;
{$ELSE}
function ToString: string; virtual;
{$ENDIF}
property AccessToken: string read FAccessToken write FAccessToken;
property TokenType: string read FTokenType write FTokenType;
property ExpiresIn: string read FExpiresIn write FExpiresIn;
property RefreshToken: string read FRefreshToken write FRefreshToken;
property Scope: string read FScope write FScope;
property Authorization: string read GetAuthorization;
end;
TclOAuthAuthorizationEndPoint = class
private
FOAuth: TclOAuth;
FRedirectUrl: string;
protected
procedure LaunchBrowser(const AUrl: string);
public
function Authorize(AResponseType: TclAuthorizationResponseType): TclJSONObject; overload; virtual; abstract;
function Authorize(const ARequestUri: string): TclJSONObject; overload; virtual; abstract;
function GetAuthorizationUrl(AResponseType: TclAuthorizationResponseType): string;
property RedirectUrl: string read FRedirectUrl write FRedirectUrl;
property OAuth: TclOAuth read FOAuth write FOAuth;
end;
TclOAuthAuthorizationFlow = class
private
FOAuth: TclOAuth;
FAuthorizationEndPoint: TclOAuthAuthorizationEndPoint;
protected
procedure CheckOAuthError(AHttp: TclHttp; AResponse: TStrings);
function CreateToken: TclOAuthToken;
function SendTokenRequest(AHttp: TclHttp; ARequest: TclHttpRequest): TclJSONBase;
public
function RequestToken: TclOAuthToken; overload; virtual; abstract;
function RequestToken(const ARequestUri: string): TclOAuthToken; overload; virtual;
function GetAuthorizationUrl: string; virtual;
property OAuth: TclOAuth read FOAuth write FOAuth;
property AuthorizationEndPoint: TclOAuthAuthorizationEndPoint read FAuthorizationEndPoint write FAuthorizationEndPoint;
end;
TclOAuthRedirectEvent = procedure(Sender: TObject; var ARedirectUrl: string) of object;
TclLaunchBrowserEvent = procedure(Sender: TObject; const AUrl: string; var Handled: Boolean) of object;
TclShowEnterCodeFormEvent = procedure(Sender: TObject; var AuthorizationCode: string; var Handled: Boolean) of object;
TclCreateAuthorizationFlowEvent = procedure(Sender: TObject; AuthFlowType: TclAuthorizationFlowType; var AuthFlow: TclOAuthAuthorizationFlow) of object;
TclCreateAuthorizationEndPointEvent = procedure(Sender: TObject; AuthEndPointType: TclAuthorizationEndPointType; var AuthEndPoint: TclOAuthAuthorizationEndPoint) of object;
TclCreateOAuthTokenEvent = procedure(Sender: TObject; var AuthToken: TclOAuthToken) of object;
TclOAuthCodeFlow = class(TclOAuthAuthorizationFlow)
private
function SendAuthCodeTokenRequest(AuthResponse: TclJSONObject; const ARedirectUrl: string): TclJSONBase;
function GetAuthorizationToken(AuthResponse: TclJSONObject): TclOAuthToken;
public
function RequestToken: TclOAuthToken; overload; override;
function RequestToken(const ARequestUri: string): TclOAuthToken; overload; override;
function GetAuthorizationUrl: string; override;
end;
TclImplicitGrantFlow = class(TclOAuthAuthorizationFlow)
public
function RequestToken: TclOAuthToken; overload; override;
function RequestToken(const ARequestUri: string): TclOAuthToken; overload; override;
function GetAuthorizationUrl: string; override;
end;
TclRefreshTokenFlow = class(TclOAuthAuthorizationFlow)
private
function GetRefreshToken: TclJSONBase;
public
function RequestToken: TclOAuthToken; override;
end;
TclClientCredentialsFlow = class(TclOAuthAuthorizationFlow)
protected
function GetAuthToken: TclJSONBase; virtual;
public
function RequestToken: TclOAuthToken; override;
end;
TclUserPasswordFlow = class(TclClientCredentialsFlow)
protected
function GetAuthToken: TclJSONBase; override;
end;
TclEnterCodeFormEndPoint = class(TclOAuthAuthorizationEndPoint)
private
function ShowEnterCodeForm: string;
function BuildAuthInfo(AResponseType: TclAuthorizationResponseType; const AuthResponse: string): TclJSONObject;
public
function Authorize(AResponseType: TclAuthorizationResponseType): TclJSONObject; overload; override;
function Authorize(const ARequestUri: string): TclJSONObject; overload; override;
end;
TclLocalWebServerEndPoint = class(TclOAuthAuthorizationEndPoint)
private
function ExtractUrlPart(const AUrl: string; ADelimiter: Char): string;
function ParseAuthResult(const ARequestUri: string): TclJSONObject;
function AcceptRedirect(AServer: TclSimpleHttpServer): TclJSONObject;
function GetRedirectUrl(const AUrl: string; APort: Integer): string;
public
function Authorize(AResponseType: TclAuthorizationResponseType): TclJSONObject; overload; override;
function Authorize(const ARequestUri: string): TclJSONObject; overload; override;
end;
TclWebApplicationEndPoint = class(TclLocalWebServerEndPoint)
public
function Authorize(AResponseType: TclAuthorizationResponseType): TclJSONObject; overload; override;
end;
TclOAuth = class(TComponent)
private
FAuthUrl: string;
FScope: string;
FClientID: string;
FTokenUrl: string;
FAuthorizationFlow: TclAuthorizationFlowType;
FAuthorizationEndPoint: TclAuthorizationEndPointType;
FClientSecret: string;
FRedirectUrl: string;
FToken: TclOAuthToken;
FHttpClient: TclHttp;
FOwnHttpClient: TclHttp;
FRequest: TclHttpRequest;
FOwnRequest: TclHttpRequest;
FUserAgent: string;
FEnterCodeFormCaption: string;
FState: string;
FLocalWebServerPort: Integer;
FHttpServer: TclSimpleHttpServer;
FOwnHttpServer: TclSimpleHttpServer;
FSuccessHtmlResponse: string;
FFailedHtmlResponse: string;
FPassword: string;
FUserName: string;
FOnRedirect: TclOAuthRedirectEvent;
FOnCreateAuthorizationFlow: TclCreateAuthorizationFlowEvent;
FOnShowEnterCodeForm: TclShowEnterCodeFormEvent;
FOnLaunchBrowser: TclLaunchBrowserEvent;
FOnCreateAuthorizationEndPoint: TclCreateAuthorizationEndPointEvent;
FOnCreateToken: TclCreateOAuthTokenEvent;
FTokenEndPoint: TclOAuthTokenEndPoint;
FEscapeRedirectUrl: Boolean;
procedure SetAuthUrl(const Value: string);
procedure SetClientID(const Value: string);
procedure SetClientSecret(const Value: string);
procedure SetAuthorizationFlow(const Value: TclAuthorizationFlowType);
procedure SetRedirectUrl(const Value: string);
procedure SetScope(const Value: string);
procedure SetTokenUrl(const Value: string);
procedure SetAuthorizationEndPoint(const Value: TclAuthorizationEndPointType);
function CreateAuthEndPoint(AuthEndPointType: TclAuthorizationEndPointType): TclOAuthAuthorizationEndPoint;
function CreateAuthFlow(AuthFlowType: TclAuthorizationFlowType): TclOAuthAuthorizationFlow;
procedure SetHttpClient(const Value: TclHttp);
procedure SetRequest(const Value: TclHttpRequest);
procedure SetState(const Value: string);
procedure SetHttpServer(const Value: TclSimpleHttpServer);
procedure SetPassword(const Value: string);
procedure SetUserName(const Value: string);
procedure SetTokenEndPoint(const Value: TclOAuthTokenEndPoint);
protected
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure DoRedirect(var ARedirectUrl: string); virtual;
procedure DoLaunchBrowser(const AUrl: string; var Handled: Boolean); virtual;
procedure DoShowEnterCodeForm(var AuthorizationCode: string; var Handled: Boolean); virtual;
procedure DoCreateAuthorizationFlow(AuthFlowType: TclAuthorizationFlowType; var AuthFlow: TclOAuthAuthorizationFlow); virtual;
procedure DoCreateAuthorizationEndPoint(AuthEndPointType: TclAuthorizationEndPointType; var AuthEndPoint: TclOAuthAuthorizationEndPoint); virtual;
procedure DoCreateToken(var AuthToken: TclOAuthToken); virtual;
procedure RequestAuthorization(AuthFlowType: TclAuthorizationFlowType); virtual;
function GetHttpClient: TclHttp;
function GetRequest: TclHttpRequest;
function GetHttpServer: TclSimpleHttpServer;
function GetToken: TclOAuthToken;
procedure ClearToken;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function GetAuthorization: string; overload;
function GetAuthorization(const ARequestUri: string): string; overload;
function GetAuthorizationUrl: string;
function RefreshAuthorization: string; overload;
function RefreshAuthorization(AToken: TclOAuthToken): string; overload;
procedure Close; virtual;
procedure SetToken(AToken: TclOAuthToken); overload;
procedure SetToken(AToken: TclJSONBase); overload;
procedure SetToken(const AToken: string); overload;
property Token: TclOAuthToken read FToken;
published
property HttpClient: TclHttp read FHttpClient write SetHttpClient;
property Request: TclHttpRequest read FRequest write SetRequest;
property HttpServer: TclSimpleHttpServer read FHttpServer write SetHttpServer;
property UserAgent: string read FUserAgent write FUserAgent;
property EnterCodeFormCaption: string read FEnterCodeFormCaption write FEnterCodeFormCaption;
property LocalWebServerPort: Integer read FLocalWebServerPort write FLocalWebServerPort default 0;
property SuccessHtmlResponse: string read FSuccessHtmlResponse write FSuccessHtmlResponse;
property FailedHtmlResponse: string read FFailedHtmlResponse write FFailedHtmlResponse;
property EscapeRedirectUrl: Boolean read FEscapeRedirectUrl write FEscapeRedirectUrl default True;
property AuthorizationFlow: TclAuthorizationFlowType read FAuthorizationFlow write SetAuthorizationFlow default afAuthCodeFlow;
property AuthorizationEndPoint: TclAuthorizationEndPointType read FAuthorizationEndPoint write SetAuthorizationEndPoint default apLocalWebServer;
property TokenEndPoint: TclOAuthTokenEndPoint read FTokenEndPoint write SetTokenEndPoint default tpUsePost;
property AuthUrl: string read FAuthUrl write SetAuthUrl;
property TokenUrl: string read FTokenUrl write SetTokenUrl;
property RedirectUrl: string read FRedirectUrl write SetRedirectUrl;
property ClientID: string read FClientID write SetClientID;
property ClientSecret: string read FClientSecret write SetClientSecret;
property Scope: string read FScope write SetScope;
property State: string read FState write SetState;
property UserName: string read FUserName write SetUserName;
property Password: string read FPassword write SetPassword;
property OnRedirect: TclOAuthRedirectEvent read FOnRedirect write FOnRedirect;
property OnLaunchBrowser: TclLaunchBrowserEvent read FOnLaunchBrowser write FOnLaunchBrowser;
property OnShowEnterCodeForm: TclShowEnterCodeFormEvent read FOnShowEnterCodeForm write FOnShowEnterCodeForm;
property OnCreateAuthorizationFlow: TclCreateAuthorizationFlowEvent read FOnCreateAuthorizationFlow write FOnCreateAuthorizationFlow;
property OnCreateAuthorizationEndPoint: TclCreateAuthorizationEndPointEvent read FOnCreateAuthorizationEndPoint write FOnCreateAuthorizationEndPoint;
property OnCreateToken: TclCreateOAuthTokenEvent read FOnCreateToken write FOnCreateToken;
end;
resourcestring
DefaultOAuthAgent = 'CleverComponents OAUTH 2.0';
DefaultEnterCodeFormCaption = 'Enter Authorization Code';
DefaultSuccessHtmlResponse = '<html><body><h3 style="color:green;margin:30px">OAuth Authorization Successful!</h3></body></html>';
DefaultFailedHtmlResponse = '<html><body><h3 style="color:red;margin:30px">OAuth Authorization Failed!</h3></body></html>';
CreateAuthorizationEndPointError = 'Cannot create authorization end point';
CreateAuthorizationFlowError = 'Cannot create authorization flow';
CreateOAuthTokenError = 'Cannot create OAuth token';
ParseOAuthTokenError = 'OAuth JSON response is invalid';
AuthorizationCodeError = 'Athorization code is invalid';
RefreshFailed = 'Refresh token failed. You must first authenticate';
const
CreateAuthorizationEndPointErrorCode = -10;
CreateAuthorizationFlowErrorCode = -11;
CreateOAuthTokenErrorCode = -12;
ParseOAuthTokenErrorCode = -13;
AuthorizationCodeErrorCode = -14;
RefreshFailedCode = -15;
implementation
{ TclOAuth }
procedure TclOAuth.ClearToken;
begin
FreeAndNil(FToken);
end;
procedure TclOAuth.Close;
begin
GetHttpClient().Close();
GetHttpServer().Close();
ClearToken();
end;
constructor TclOAuth.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FAuthorizationFlow := afAuthCodeFlow;
FAuthorizationEndPoint := apLocalWebServer;
FUserAgent := DefaultOAuthAgent;
FEnterCodeFormCaption := DefaultEnterCodeFormCaption;
FLocalWebServerPort := 0;
FSuccessHtmlResponse := DefaultSuccessHtmlResponse;
FFailedHtmlResponse := DefaultFailedHtmlResponse;
FTokenEndPoint := tpUsePost;
FEscapeRedirectUrl := True;
end;
function TclOAuth.CreateAuthEndPoint(AuthEndPointType: TclAuthorizationEndPointType): TclOAuthAuthorizationEndPoint;
begin
Result := nil;
DoCreateAuthorizationEndPoint(AuthEndPointType, Result);
if (Result <> nil) then Exit;
case AuthEndPointType of
apEnterCodeForm: Result := TclEnterCodeFormEndPoint.Create();
apLocalWebServer: Result := TclLocalWebServerEndPoint.Create();
apWebApplication: Result := TclWebApplicationEndPoint.Create();
end;
if (Result = nil) then
begin
raise EclOAuthError.Create(CreateAuthorizationEndPointError, CreateAuthorizationEndPointErrorCode);
end;
end;
function TclOAuth.CreateAuthFlow(AuthFlowType: TclAuthorizationFlowType): TclOAuthAuthorizationFlow;
begin
Result := nil;
DoCreateAuthorizationFlow(AuthFlowType, Result);
if (Result <> nil) then Exit;
case AuthFlowType of
afAuthCodeFlow: Result := TclOAuthCodeFlow.Create();
afImplicitGrantFlow: Result := TclImplicitGrantFlow.Create();
afRefreshTokenFlow: Result := TclRefreshTokenFlow.Create();
afClientCredentialsFlow: Result := TclClientCredentialsFlow.Create();
afUserPasswordFlow: Result := TclUserPasswordFlow.Create();
end;
if (Result = nil) then
begin
raise EclOAuthError.Create(CreateAuthorizationFlowError, CreateAuthorizationFlowErrorCode);
end;
end;
destructor TclOAuth.Destroy;
begin
Close();
FreeAndNil(FOwnHttpClient);
FreeAndNil(FOwnRequest);
FreeAndNil(FOwnHttpServer);
inherited Destroy();
end;
procedure TclOAuth.DoCreateAuthorizationEndPoint(AuthEndPointType: TclAuthorizationEndPointType; var AuthEndPoint: TclOAuthAuthorizationEndPoint);
begin
if Assigned(OnCreateAuthorizationEndPoint) then
begin
OnCreateAuthorizationEndPoint(Self, AuthEndPointType, AuthEndPoint);
end;
end;
procedure TclOAuth.DoCreateAuthorizationFlow(AuthFlowType: TclAuthorizationFlowType; var AuthFlow: TclOAuthAuthorizationFlow);
begin
if Assigned(OnCreateAuthorizationFlow) then
begin
OnCreateAuthorizationFlow(Self, AuthFlowType, AuthFlow);
end;
end;
procedure TclOAuth.DoCreateToken(var AuthToken: TclOAuthToken);
begin
if Assigned(OnCreateToken) then
begin
OnCreateToken(Self, AuthToken);
end;
end;
procedure TclOAuth.DoLaunchBrowser(const AUrl: string; var Handled: Boolean);
begin
if Assigned(OnLaunchBrowser) then
begin
OnLaunchBrowser(Self, AUrl, Handled);
end;
end;
procedure TclOAuth.DoRedirect(var ARedirectUrl: string);
begin
if Assigned(OnRedirect) then
begin
OnRedirect(Self, ARedirectUrl);
end;
end;
procedure TclOAuth.DoShowEnterCodeForm(var AuthorizationCode: string; var Handled: Boolean);
begin
if Assigned(OnShowEnterCodeForm) then
begin
OnShowEnterCodeForm(Self, AuthorizationCode, Handled);
end;
end;
function TclOAuth.GetAuthorization: string;
begin
{$IFDEF DEMO}
{$IFNDEF STANDALONEDEMO}
if FindWindow('TAppBuilder', nil) = 0 then
begin
MessageBox(0, 'This demo version can be run under Delphi/C++Builder IDE only. ' +
'Please visit www.clevercomponents.com to purchase your ' +
'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST);
ExitProcess(1);
end else
{$ENDIF}
begin
{$IFNDEF IDEDEMO}
IsHttpDemoDisplayed := True;
IsHttpRequestDemoDisplayed := True;
IsEncoderDemoDisplayed := True;
IsEncryptorDemoDisplayed := True;
IsCertDemoDisplayed := True;
IsHtmlDemoDisplayed := True;
{$ENDIF}
end;
{$ENDIF}
if (Token <> nil) then
begin
Result := Token.Authorization;
Exit;
end;
RequestAuthorization(AuthorizationFlow);
Result := Token.Authorization;
end;
function TclOAuth.GetAuthorization(const ARequestUri: string): string;
var
end_point: TclOAuthAuthorizationEndPoint;
flow: TclOAuthAuthorizationFlow;
begin
flow := nil;
end_point := nil;
try
flow := CreateAuthFlow(AuthorizationFlow);
flow.OAuth := Self;
end_point := CreateAuthEndPoint(AuthorizationEndPoint);
end_point.OAuth := Self;
flow.AuthorizationEndPoint := end_point;
SetToken(flow.RequestToken(ARequestUri));
if (FToken = nil) then
begin
raise EclOAuthError.Create(CreateOAuthTokenError, CreateOAuthTokenErrorCode);
end;
Result := Token.Authorization;
finally
end_point.Free();
flow.Free();
end;
end;
function TclOAuth.GetAuthorizationUrl: string;
var
end_point: TclOAuthAuthorizationEndPoint;
flow: TclOAuthAuthorizationFlow;
begin
flow := nil;
end_point := nil;
try
flow := CreateAuthFlow(AuthorizationFlow);
flow.OAuth := Self;
end_point := CreateAuthEndPoint(AuthorizationEndPoint);
end_point.OAuth := Self;
flow.AuthorizationEndPoint := end_point;
Result := flow.GetAuthorizationUrl();
finally
end_point.Free();
flow.Free();
end;
end;
function TclOAuth.GetHttpClient: TclHttp;
begin
Result := FHttpClient;
if (Result = nil) then
begin
if (FOwnHttpClient = nil) then
begin
FOwnHttpClient := TclHttp.Create(nil);
FOwnHttpClient.UserAgent := UserAgent;
end;
Result := FOwnHttpClient;
end;
end;
function TclOAuth.GetHttpServer: TclSimpleHttpServer;
begin
Result := FHttpServer;
if (Result = nil) then
begin
if (FOwnHttpServer = nil) then
begin
FOwnHttpServer := TclSimpleHttpServer.Create(nil);
FOwnHttpServer.ServerName := UserAgent;
FOwnHttpServer.ResponseVersion := hvHttp1_1;
FOwnHttpServer.KeepConnection := False;
FOwnHttpServer.ResponseHeader.ContentType := 'text/html';
end;
Result := FOwnHttpServer;
end;
end;
function TclOAuth.GetRequest: TclHttpRequest;
begin
Result := FRequest;
if (Result = nil) then
begin
if (FOwnRequest = nil) then
begin
FOwnRequest := TclHttpRequest.Create(nil);
FOwnRequest.Header.CharSet := 'utf-8';
end;
Result := FOwnRequest;
end;
end;
function TclOAuth.GetToken: TclOAuthToken;
begin
Result := nil;
DoCreateToken(Result);
if (Result = nil) then
begin
Result := TclOAuthToken.Create();
end;
end;
procedure TclOAuth.SetToken(AToken: TclJSONBase);
begin
SetToken(GetToken());
try
Token.Parse(AToken);
except
ClearToken();
raise;
end;
end;
procedure TclOAuth.SetToken(const AToken: string);
var
json: TclJSONBase;
begin
json := TclJSONBase.Parse(AToken);
try
SetToken(json);
finally
json.Free();
end;
end;
procedure TclOAuth.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if (AComponent = FHttpClient) and (Operation = opRemove) then
begin
FHttpClient := nil;
end else
if (AComponent = FRequest) and (Operation = opRemove) then
begin
FRequest := nil;
end else
if (AComponent = FHttpServer) and (Operation = opRemove) then
begin
FHttpServer := nil;
end;
end;
function TclOAuth.RefreshAuthorization: string;
var
refresh_token: string;
begin
if (Token = nil) then
begin
raise EclOAuthError.Create(RefreshFailed, RefreshFailedCode);
end;
refresh_token := Token.RefreshToken;
RequestAuthorization(afRefreshTokenFlow);
if (Token.RefreshToken = '') then
begin
Token.RefreshToken := refresh_token;
end;
Result := Token.Authorization;
end;
function TclOAuth.RefreshAuthorization(AToken: TclOAuthToken): string;
begin
SetToken(AToken);
Result := RefreshAuthorization();
end;
procedure TclOAuth.RequestAuthorization(AuthFlowType: TclAuthorizationFlowType);
var
end_point: TclOAuthAuthorizationEndPoint;
flow: TclOAuthAuthorizationFlow;
begin
flow := nil;
end_point := nil;
try
flow := CreateAuthFlow(AuthFlowType);
flow.OAuth := Self;
end_point := CreateAuthEndPoint(AuthorizationEndPoint);
end_point.OAuth := Self;
flow.AuthorizationEndPoint := end_point;
SetToken(flow.RequestToken());
if (FToken = nil) then
begin
raise EclOAuthError.Create(CreateOAuthTokenError, CreateOAuthTokenErrorCode);
end;
finally
end_point.Free();
flow.Free();
end;
end;
procedure TclOAuth.SetAuthUrl(const Value: string);
begin
if (FAuthUrl <> Value) then
begin
FAuthUrl := Value;
Close();
end;
end;
procedure TclOAuth.SetClientID(const Value: string);
begin
if (FClientID <> Value) then
begin
FClientID := Value;
Close();
end;
end;
procedure TclOAuth.SetClientSecret(const Value: string);
begin
if (FClientSecret <> Value) then
begin
FClientSecret := Value;
Close();
end;
end;
procedure TclOAuth.SetHttpClient(const Value: TclHttp);
begin
if (FHttpClient <> Value) then
begin
if (FHttpClient <> nil) then
begin
FHttpClient.RemoveFreeNotification(Self);
end;
FHttpClient := Value;
if (FHttpClient <> nil) then
begin
FHttpClient.FreeNotification(Self);
end;
end;
FreeAndNil(FOwnHttpClient);
end;
procedure TclOAuth.SetHttpServer(const Value: TclSimpleHttpServer);
begin
if (FHttpServer <> Value) then
begin
if (FHttpServer <> nil) then
begin
FHttpServer.RemoveFreeNotification(Self);
end;
FHttpServer := Value;
if (FHttpServer <> nil) then
begin
FHttpServer.FreeNotification(Self);
end;
end;
FreeAndNil(FOwnHttpServer);
end;
procedure TclOAuth.SetPassword(const Value: string);
begin
if (FPassword <> Value) then
begin
FPassword := Value;
Close();
end;
end;
procedure TclOAuth.SetAuthorizationEndPoint(const Value: TclAuthorizationEndPointType);
begin
if (FAuthorizationEndPoint <> Value) then
begin
FAuthorizationEndPoint := Value;
Close();
end;
end;
procedure TclOAuth.SetAuthorizationFlow(const Value: TclAuthorizationFlowType);
begin
if (FAuthorizationFlow <> Value) then
begin
FAuthorizationFlow := Value;
Close();
end;
end;
procedure TclOAuth.SetRedirectUrl(const Value: string);
begin
if (FRedirectUrl <> Value) then
begin
FRedirectUrl := Value;
Close();
end;
end;
procedure TclOAuth.SetRequest(const Value: TclHttpRequest);
begin
if (FRequest <> Value) then
begin
if (FRequest <> nil) then
begin
FRequest.RemoveFreeNotification(Self);
end;
FRequest := Value;
if (FRequest <> nil) then
begin
FRequest.FreeNotification(Self);
end;
end;
FreeAndNil(FOwnRequest);
end;
procedure TclOAuth.SetScope(const Value: string);
begin
if (FScope <> Value) then
begin
FScope := Value;
Close();
end;
end;
procedure TclOAuth.SetState(const Value: string);
begin
if (FState <> Value) then
begin
FState := Value;
Close();
end;
end;
procedure TclOAuth.SetToken(AToken: TclOAuthToken);
begin
ClearToken();
FToken := AToken;
end;
procedure TclOAuth.SetTokenEndPoint(const Value: TclOAuthTokenEndPoint);
begin
if (FTokenEndPoint <> Value) then
begin
FTokenEndPoint := Value;
Close();
end;
end;
procedure TclOAuth.SetTokenUrl(const Value: string);
begin
if (FTokenUrl <> Value) then
begin
FTokenUrl := Value;
Close();
end;
end;
procedure TclOAuth.SetUserName(const Value: string);
begin
if (FUserName <> Value) then
begin
FUserName := Value;
Close();
end;
end;
{ TclOAuthToken }
function TclOAuthToken.ToJson: TclJSONObject;
begin
Result := TclJSONObject.Create();
try
Result.AddMember('refresh_token', TclJSONString.Create(FRefreshToken));
Result.AddMember('token_type', TclJSONString.Create(FTokenType));
Result.AddMember('access_token', TclJSONString.Create(FAccessToken));
Result.AddMember('expires_in', TclJSONValue.Create(FExpiresIn));
Result.AddMember('scope', TclJSONString.Create(FScope));
except
Result.Free();
raise;
end;
end;
function TclOAuthToken.ToString: string;
var
json: TclJSONBase;
begin
json := ToJson();
try
Result := json.GetJSONString();
finally
json.Free();
end;
end;
procedure TclOAuthToken.Clear;
begin
FRefreshToken := '';
FTokenType := '';
FAccessToken := '';
FExpiresIn := '';
FScope := '';
end;
function TclOAuthToken.GetAuthorization: string;
begin
if SameText(TokenType, 'bearer') then
begin
Result := 'Bearer ' + AccessToken;
end else
begin
Result := 'OAuth ' + AccessToken;
end;
end;
procedure TclOAuthToken.Parse(AResponse: TclJSONBase);
var
obj: TclJSONObject;
begin
Clear();
if not (AResponse is TclJSONObject) then
begin
raise EclOAuthError.Create(ParseOAuthTokenError, ParseOAuthTokenErrorCode);
end;
obj := (AResponse as TclJSONObject);
FRefreshToken := obj.ValueByName('refresh_token');
FTokenType := obj.ValueByName('token_type');
FAccessToken := obj.ValueByName('access_token');
FExpiresIn := obj.ValueByName('expires_in');
FScope := obj.ValueByName('scope');
end;
{ TclOAuthCodeFlow }
function TclOAuthCodeFlow.SendAuthCodeTokenRequest(AuthResponse: TclJSONObject; const ARedirectUrl: string): TclJSONBase;
var
http: TclHttp;
req: TclHttpRequest;
item: TclFormFieldRequestItem;
begin
http := OAuth.GetHttpClient();
Assert(http <> nil);
req := OAuth.GetRequest();
Assert(req <> nil);
req.Clear();
req.AddFormFieldIfNeed('grant_type', 'authorization_code');
req.AddFormFieldIfNeed('code', AuthResponse.ValueByName('code'));
req.AddFormFieldIfNeed('client_id', OAuth.ClientID);
req.AddFormFieldIfNeed('client_secret', OAuth.ClientSecret);
item := req.AddFormFieldIfNeed('redirect_uri', ARedirectUrl);
if (item <> nil) then
begin
item.Canonicalized := OAuth.EscapeRedirectUrl;
end;
Result := SendTokenRequest(http, req);
end;
function TclOAuthCodeFlow.GetAuthorizationUrl: string;
begin
Assert(OAuth <> nil);
Assert(AuthorizationEndPoint <> nil);
Result := AuthorizationEndPoint.GetAuthorizationUrl(rtAuthCode);
end;
function TclOAuthCodeFlow.GetAuthorizationToken(AuthResponse: TclJSONObject): TclOAuthToken;
var
token_resp: TclJSONBase;
begin
{$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'GetAuthorizationToken');{$ENDIF}
{$IFDEF LOGGER}clPutLogMessage(Self, edInside, 'GetAuthorizationToken, AuthResponse: ' + AuthResponse.GetJSONString());{$ENDIF}
Result := CreateToken();
try
token_resp := SendAuthCodeTokenRequest(AuthResponse, AuthorizationEndPoint.RedirectUrl);
try
Result.Parse(token_resp);
finally
token_resp.Free();
end;
except
Result.Free();
raise;
end;
{$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'GetAuthorizationToken'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'GetAuthorizationToken', E); raise; end; end;{$ENDIF}
end;
function TclOAuthCodeFlow.RequestToken(const ARequestUri: string): TclOAuthToken;
var
auth_resp: TclJSONObject;
begin
Assert(OAuth <> nil);
Assert(AuthorizationEndPoint <> nil);
auth_resp := AuthorizationEndPoint.Authorize(ARequestUri);
try
Result := GetAuthorizationToken(auth_resp);
finally
auth_resp.Free();
end;
end;
function TclOAuthCodeFlow.RequestToken: TclOAuthToken;
var
auth_resp: TclJSONObject;
begin
{$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'RequestToken');{$ENDIF}
Assert(OAuth <> nil);
Assert(AuthorizationEndPoint <> nil);
auth_resp := AuthorizationEndPoint.Authorize(rtAuthCode);
try
Result := GetAuthorizationToken(auth_resp);
finally
auth_resp.Free();
end;
{$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'RequestToken'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'RequestToken', E); raise; end; end;{$ENDIF}
end;
{ TclEnterCodeFormEndPoint }
function TclEnterCodeFormEndPoint.Authorize(const ARequestUri: string): TclJSONObject;
begin
Result := nil;
Assert(False);
end;
function TclEnterCodeFormEndPoint.BuildAuthInfo(AResponseType: TclAuthorizationResponseType;
const AuthResponse: string): TclJSONObject;
const
cJsonResponseTypeName: array[TclAuthorizationResponseType] of string = ('code', 'access_token', 'extension');
var
pair: TclJSONPair;
begin
Result := TclJSONObject.Create();
try
pair := TclJSONPair.Create();
Result.AddMember(pair);
pair.Name := cJsonResponseTypeName[AResponseType];
pair.Value := TclJSONString.Create(AuthResponse);
except
Result.Free();
raise;
end;
end;
function TclEnterCodeFormEndPoint.Authorize(AResponseType: TclAuthorizationResponseType): TclJSONObject;
var
auth_url: string;
begin
Assert(OAuth <> nil);
RedirectUrl := OAuth.RedirectUrl;
auth_url := GetAuthorizationUrl(AResponseType);
LaunchBrowser(auth_url);
Result := BuildAuthInfo(AResponseType, ShowEnterCodeForm());
end;
function TclEnterCodeFormEndPoint.ShowEnterCodeForm: string;
var
handled: Boolean;
begin
Result := '';
handled := False;
OAuth.DoShowEnterCodeForm(Result, handled);
if (not handled) then
begin
Result := InputBox(OAuth.EnterCodeFormCaption, OAuth.EnterCodeFormCaption, Result);
end;
Result := Trim(Result);
if (Result = '') then
begin
raise EclOAuthError.Create(AuthorizationCodeError, AuthorizationCodeErrorCode);
end;
end;
{ TclImplicitGrantFlow }
function TclImplicitGrantFlow.GetAuthorizationUrl: string;
begin
Assert(OAuth <> nil);
Assert(AuthorizationEndPoint <> nil);
Result := AuthorizationEndPoint.GetAuthorizationUrl(rtAuthToken);
end;
function TclImplicitGrantFlow.RequestToken: TclOAuthToken;
var
token_response: TclJSONObject;
begin
Assert(OAuth <> nil);
Assert(AuthorizationEndPoint <> nil);
Result := CreateToken();
try
token_response := AuthorizationEndPoint.Authorize(rtAuthToken);
try
Result.Parse(token_response);
finally
token_response.Free();
end;
except
Result.Free();
raise;
end;
end;
function TclImplicitGrantFlow.RequestToken(const ARequestUri: string): TclOAuthToken;
var
token_response: TclJSONObject;
begin
Assert(OAuth <> nil);
Assert(AuthorizationEndPoint <> nil);
Result := CreateToken();
try
token_response := AuthorizationEndPoint.Authorize(ARequestUri);
try
Result.Parse(token_response);
finally
token_response.Free();
end;
except
Result.Free();
raise;
end;
end;
{ TclOAuthAuthorizationFlow }
procedure TclOAuthAuthorizationFlow.CheckOAuthError(AHttp: TclHttp; AResponse: TStrings);
var
json: TclJSONBase;
error, error_description: string;
begin
if (AHttp.StatusCode < 400) then Exit;
if (system.Pos('json', AHttp.ResponseHeader.ContentType) < 1) then
begin
raise EclHttpError.Create(AHttp.StatusText, AHttp.StatusCode, AResponse.Text);
end;
json := TclJSONBase.Parse(AResponse.Text);
try
if not (json is TclJSONObject) then
begin
raise EclHttpError.Create(AHttp.StatusText, AHttp.StatusCode, AResponse.Text);
end;
error_description := Trim((json as TclJSONObject).ValueByName('error_description'));
if (error_description = '') then
begin
error_description := AResponse.Text;
end;
error := Trim((json as TclJSONObject).ValueByName('error'));
raise EclHttpError.Create(error, AHttp.StatusCode, error_description);
finally
json.Free();
end;
end;
function TclOAuthAuthorizationFlow.CreateToken: TclOAuthToken;
begin
Result := OAuth.GetToken();
end;
function TclOAuthAuthorizationFlow.GetAuthorizationUrl: string;
begin
Result := '';
Assert(False);
end;
function TclOAuthAuthorizationFlow.RequestToken(const ARequestUri: string): TclOAuthToken;
begin
Result := nil;
Assert(False);
end;
function TclOAuthAuthorizationFlow.SendTokenRequest(AHttp: TclHttp; ARequest: TclHttpRequest): TclJSONBase;
var
resp: TStrings;
begin
resp := TStringList.Create();
try
AHttp.SilentHTTP := True;
case OAuth.TokenEndPoint of
tpUsePost: AHttp.Post(OAuth.TokenUrl, ARequest, resp);
tpUseGet: AHttp.Get(OAuth.TokenUrl, ARequest, resp)
else
Assert(False);
end;
CheckOAuthError(AHttp, resp);
Result := TclJSONBase.Parse(resp.Text);
finally
resp.Free();
end;
end;
{ TclLocalWebServerEndPoint }
function TclLocalWebServerEndPoint.Authorize(const ARequestUri: string): TclJSONObject;
var
error, error_description: string;
begin
Result := ParseAuthResult(ARequestUri);
try
error := Trim(Result.ValueByName('error'));
if (error <> '') then
begin
error_description := Trim(Result.ValueByName('error_description'));
raise EclHttpError.Create(error, 401, error_description);
end;
except
Result.Free();
raise;
end;
end;
function TclLocalWebServerEndPoint.ExtractUrlPart(const AUrl: string; ADelimiter: Char): string;
var
ind: Integer;
begin
Result := AUrl;
ind := system.Pos(ADelimiter, Result);
if (ind > 0) then
begin
Result := system.Copy(Result, ind + 1, MaxInt);
end;
end;
function TclLocalWebServerEndPoint.ParseAuthResult(const ARequestUri: string): TclJSONObject;
var
req: TclHttpRequest;
i: Integer;
stream: TStream;
item: TclHttpRequestItem;
pair: TclJSONPair;
auth: string;
begin
req := OAuth.GetRequest();
Assert(req <> nil);
auth := ExtractUrlPart(ARequestUri, '?');
auth := ExtractUrlPart(auth, '#');
Result := TclJSONObject.Create();
try
stream := TStringStream.Create(auth);
try
req.RequestStream := stream;
finally
stream.Free();
end;
for i := 0 to req.Items.Count - 1 do
begin
item := req.Items[i];
if (item is TclFormFieldRequestItem) then
begin
pair := TclJSONPair.Create();
Result.AddMember(pair);
pair.Name := (item as TclFormFieldRequestItem).FieldName;
pair.Value := TclJSONString.Create((item as TclFormFieldRequestItem).FieldValue);
end;
end;
except
Result.Free();
raise;
end;
end;
function TclLocalWebServerEndPoint.GetRedirectUrl(const AUrl: string; APort: Integer): string;
var
portStr: string;
uri: TclUrlParser;
begin
portStr := ':' + IntToStr(APort);
Result := AUrl;
if (Pos(portStr, Result) < 1) then
begin
uri := TclUrlParser.Create();
try
uri.Parse(AUrl, '');
Result := StringReplace(Result, uri.Host, uri.Host + portStr, []);
finally
uri.Free();
end;
end;
OAuth.DoRedirect(Result);
end;
function TclLocalWebServerEndPoint.Authorize(AResponseType: TclAuthorizationResponseType): TclJSONObject;
var
server: TclSimpleHttpServer;
auth_url: string;
listen_port: Integer;
begin
{$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'Authorize');{$ENDIF}
Assert(OAuth <> nil);
server := OAuth.GetHttpServer();
Assert(server <> nil);
listen_port := server.Listen(OAuth.LocalWebServerPort);
RedirectUrl := GetRedirectUrl(OAuth.RedirectUrl, listen_port);
auth_url := GetAuthorizationUrl(AResponseType);
LaunchBrowser(auth_url);
Result := AcceptRedirect(server);
{$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'Authorize'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'Authorize', E); raise; end; end;{$ENDIF}
end;
function TclLocalWebServerEndPoint.AcceptRedirect(AServer: TclSimpleHttpServer): TclJSONObject;
var
error, error_description: string;
i: Integer;
begin
{$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'AcceptRedirect');{$ENDIF}
for i := 0 to 2 do
begin
AServer.AcceptRequest();
{$IFDEF LOGGER}clPutLogMessage(Self, edInside, 'AcceptRedirect, accepted, requestUri: ' + AServer.RequestUri);{$ENDIF}
Result := ParseAuthResult(AServer.RequestUri);
try
{$IFDEF LOGGER}clPutLogMessage(Self, edInside, 'AcceptRedirect, result parsed');{$ENDIF}
error := Trim(Result.ValueByName('error'));
if (error <> '') then
begin
error_description := Trim(Result.ValueByName('error_description'));
{$IFDEF LOGGER}clPutLogMessage(Self, edInside, 'AcceptRedirect, 401 error: ' + error_description);{$ENDIF}
AServer.SendResponse(401, error, OAuth.FailedHtmlResponse);
raise EclHttpError.Create(error, 401, error_description);
end else
if (Trim(Result.ValueByName('code')) <> '') or (Trim(Result.ValueByName('access_token')) <> '') then
begin
{$IFDEF LOGGER}clPutLogMessage(Self, edInside, 'AcceptRedirect, 200 OK');{$ENDIF}
AServer.SendResponse(200, 'OK', OAuth.SuccessHtmlResponse);
Break;
end else
begin
{$IFDEF LOGGER}clPutLogMessage(Self, edInside, 'AcceptRedirect, 404 error');{$ENDIF}
AServer.SendResponse(404, 'Not found', OAuth.FailedHtmlResponse);
end;
except
Result.Free();
raise;
end;
end;
{$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'AcceptRedirect'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'AcceptRedirect', E); raise; end; end;{$ENDIF}
end;
{ TclOAuthAuthorizationEndPoint }
function TclOAuthAuthorizationEndPoint.GetAuthorizationUrl(AResponseType: TclAuthorizationResponseType): string;
const
cOAuthResponseTypeName: array[TclAuthorizationResponseType] of string = ('code', 'token', '');
var
req: TclHttpRequest;
item: TclFormFieldRequestItem;
begin
Assert(OAuth <> nil);
req := OAuth.GetRequest();
Assert(req <> nil);
req.Clear();
req.AddFormFieldIfNeed('response_type', cOAuthResponseTypeName[AResponseType]);
req.AddFormFieldIfNeed('client_id', OAuth.ClientID);
item := req.AddFormFieldIfNeed('redirect_uri', RedirectUrl);
if (item <> nil) then
begin
item.Canonicalized := OAuth.EscapeRedirectUrl;
end;
req.AddFormFieldIfNeed('scope', OAuth.Scope);
req.AddFormFieldIfNeed('state', OAuth.State);
Result := OAuth.AuthUrl + '?' + Trim(req.RequestSource.Text);
end;
procedure TclOAuthAuthorizationEndPoint.LaunchBrowser(const AUrl: string);
var
handled: Boolean;
begin
Assert(OAuth <> nil);
handled := False;
OAuth.DoLaunchBrowser(AUrl, handled);
if (not handled) then
begin
ShellExecute(0, 'open', PChar(AUrl), nil, nil, SW_SHOWNORMAL);
end;
end;
{ TclRefreshTokenFlow }
function TclRefreshTokenFlow.GetRefreshToken: TclJSONBase;
var
http: TclHttp;
req: TclHttpRequest;
begin
http := OAuth.GetHttpClient();
Assert(http <> nil);
req := OAuth.GetRequest();
Assert(req <> nil);
Assert(OAuth.Token <> nil);
req.Clear();
req.AddFormFieldIfNeed('grant_type', 'refresh_token');
req.AddFormFieldIfNeed('refresh_token', OAuth.Token.RefreshToken);
req.AddFormFieldIfNeed('client_id', OAuth.ClientID);
req.AddFormFieldIfNeed('client_secret', OAuth.ClientSecret);
req.AddFormFieldIfNeed('scope', OAuth.Scope);
Result := SendTokenRequest(http, req);
end;
function TclRefreshTokenFlow.RequestToken: TclOAuthToken;
var
token_resp: TclJSONBase;
begin
Assert(OAuth <> nil);
Result := CreateToken();
try
token_resp := GetRefreshToken();
try
Result.Parse(token_resp);
finally
token_resp.Free();
end;
except
Result.Free();
raise;
end;
end;
{ TclClientCredentialsFlow }
function TclClientCredentialsFlow.GetAuthToken: TclJSONBase;
var
http: TclHttp;
req: TclHttpRequest;
begin
http := OAuth.GetHttpClient();
Assert(http <> nil);
req := OAuth.GetRequest();
Assert(req <> nil);
req.Clear();
req.AddFormFieldIfNeed('grant_type', 'client_credentials');
req.AddFormFieldIfNeed('scope', OAuth.Scope);
http.UserName := OAuth.UserName;
http.Password := OAuth.Password;
Result := SendTokenRequest(http, req);
end;
function TclClientCredentialsFlow.RequestToken: TclOAuthToken;
var
token_resp: TclJSONBase;
begin
Assert(OAuth <> nil);
Result := CreateToken();
try
token_resp := GetAuthToken();
try
Result.Parse(token_resp);
finally
token_resp.Free();
end;
except
Result.Free();
raise;
end;
end;
{ TclUserPasswordFlow }
{ TclUserPasswordFlow }
function TclUserPasswordFlow.GetAuthToken: TclJSONBase;
var
http: TclHttp;
req: TclHttpRequest;
begin
http := OAuth.GetHttpClient();
Assert(http <> nil);
req := OAuth.GetRequest();
Assert(req <> nil);
req.Clear();
req.AddFormFieldIfNeed('grant_type', 'password');
req.AddFormFieldIfNeed('username', OAuth.UserName);
req.AddFormFieldIfNeed('password', OAuth.Password);
req.AddFormFieldIfNeed('scope', OAuth.Scope);
http.UserName := OAuth.UserName;
http.Password := OAuth.Password;
Result := SendTokenRequest(http, req);
end;
{ EclOAuthError }
constructor EclOAuthError.Create(const AErrorMsg: string; AErrorCode: Integer; ADummy: Boolean);
begin
inherited Create(AErrorMsg);
FErrorCode := AErrorCode;
end;
{ TclWebApplicationEndPoint }
function TclWebApplicationEndPoint.Authorize(AResponseType: TclAuthorizationResponseType): TclJSONObject;
begin
Assert(False);
Result := nil;
end;
end.
|
// Set Component Properties Expert
// Original Author: Robert Wachtel (rwachtel@gmx.de)
unit GX_SetComponentProps;
{$I GX_CondDefine.inc}
interface
uses
Classes, Controls, ToolsAPI, GX_OtaUtils;
type
TSetComponentPropsNotifier = class(TBaseIdeNotifier, IOTAIDENotifier50)
private
FOutputMessages: TStringList;
procedure AddMessageToList(const sModuleFileName, sFormat: string; const Args: array of const);
function CheckAndSetComponent(const ModuleFileName: string; Component: IOTAComponent): Boolean;
function CheckChildComponents(RootComponent: IOTAComponent; const ModuleFileName: string): Boolean;
protected
procedure AfterCompile(Succeeded: Boolean; IsCodeInsight: Boolean); reintroduce; overload;
procedure BeforeCompile(const Project: IOTAProject; IsCodeInsight: Boolean; var Cancel: Boolean); reintroduce; overload;
public
constructor Create;
destructor Destroy; override;
end;
TSetComponentPropsSettings = class(TObject)
private
FComponents: TStringList;
FGxSetComponentPropsNotifier: TSetComponentPropsNotifier;
FProperties: TStringList;
FPropertyTypes: TStringList;
FSimulate: Boolean;
FValues: TStringList;
FVerbose: Boolean;
FOnlyOpenFiles: Boolean;
public
constructor Create;
destructor Destroy; override;
function AddNotifierToIDE: Boolean;
class procedure FreeMe;
class function GetInstance: TSetComponentPropsSettings;
procedure RemoveNotifierFromIDE;
property Components: TStringList read FComponents;
property Properties: TStringList read FProperties;
property PropertyTypes: TStringList read FPropertyTypes;
property Simulate: Boolean read FSimulate write FSimulate;
property Values: TStringList read FValues;
property Verbose: Boolean read FVerbose write FVerbose;
property OnlyOpenFiles: Boolean read FOnlyOpenFiles write FOnlyOpenFiles;
end;
implementation
uses
SysUtils, TypInfo,
GX_Experts, Gx_GenericUtils, GX_ConfigurationInfo,
GX_SetComponentPropsConfig, GX_SetComponentPropsStatus;
type
TSetComponentPropsExpert = class(TGX_Expert)
protected
procedure SetActive(New: Boolean); override;
public
constructor Create; override;
destructor Destroy; override;
procedure Execute(Sender: TObject); override;
procedure Configure; override;
function GetActionCaption: string; override;
class function GetName: string; override;
function HasConfigOptions: Boolean; override;
function HasMenuItem: Boolean; override;
procedure InternalLoadSettings(Settings: TExpertSettings); override;
procedure InternalSaveSettings(Settings: TExpertSettings); override;
function IsDefaultActive: Boolean; override;
end;
var
GxSetComponentPropsSettings: TSetComponentPropsSettings = nil;
{TSetComponentPropsExpert}
// Get an instance of the settings container (TSetComponentPropsSettings)
constructor TSetComponentPropsExpert.Create;
begin
inherited;
TSetComponentPropsSettings.GetInstance; // Get an instance of the settings container
end;
// Be sure to free the settings conatiner (TSetComponentPropsSettings)
destructor TSetComponentPropsExpert.Destroy;
begin
Active := False; // Prevent re-creating TSetComponentPropsSettings later when setting Active=False
TSetComponentPropsSettings.FreeMe;
inherited;
end;
// When the menu item is clicked, open the configuration dialog
procedure TSetComponentPropsExpert.Execute(Sender: TObject);
begin
Configure;
end;
// Action taken when user clicks the Configure button on the Experts tab of menu item GExperts/GExperts Configuration...
procedure TSetComponentPropsExpert.Configure;
begin
with TfmSetComponentPropsConfig.Create(nil) do
begin
try
SetSettings;
if ShowModal = mrOK then
GetSettings;
finally
Release;
end;
end;
end;
// Returns the string displayed on the GExperts menu item
function TSetComponentPropsExpert.GetActionCaption: string;
resourcestring
SMenuCaption = 'Set Component Properties...';
begin
Result := SMenuCaption;
end;
// Used to determine the unique keyword used to save the active state and shortcut into the registry
class function TSetComponentPropsExpert.GetName: string;
begin
Result := 'SetComponentProperties';
end;
// This expert should have a configure button in the configuration dialog
function TSetComponentPropsExpert.HasConfigOptions: Boolean;
begin
Result := True;
end;
// This expert does not have a visible menu item in the GExperts top level menu
function TSetComponentPropsExpert.HasMenuItem: Boolean;
begin
Result := False;
end;
// Gets the expert settings from the registry
procedure TSetComponentPropsExpert.InternalLoadSettings(Settings: TExpertSettings);
var
Instance: TSetComponentPropsSettings;
begin
inherited;
Instance := TSetComponentPropsSettings.GetInstance;
Instance.Simulate := Settings.ReadBool('Simulate', True);
Instance.Verbose := Settings.ReadBool('Verbose', True);
Settings.ReadStrings('Components', Instance.Components, 'Components');
Settings.ReadStrings('Properties', Instance.Properties, 'Properties');
Settings.ReadStrings('Values', Instance.Values, 'Values');
Settings.ReadStrings('Property Types', Instance.PropertyTypes, 'PropertyTypes');
Assert((Instance.Components.Count = Instance.Properties.Count) and
(Instance.Components.Count = Instance.Values.Count));
end;
// Saves the expert settings to the registry
procedure TSetComponentPropsExpert.InternalSaveSettings(Settings: TExpertSettings);
var
Instance: TSetComponentPropsSettings;
begin
inherited;
Instance := TSetComponentPropsSettings.GetInstance;
Settings.WriteBool('Simulate', Instance.Simulate);
Settings.WriteBool('Verbose', Instance.Verbose);
Settings.WriteStrings('Components', Instance.Components, 'Components');
Settings.WriteStrings('Properties', Instance.Properties, 'Properties');
Settings.WriteStrings('Values', Instance.Values, 'Values');
Settings.WriteStrings('Property Types', Instance.PropertyTypes, 'PropertyTypes');
end;
// Called to clean up the expert when it is disabled at runtime or destroyed on shutdown.
procedure TSetComponentPropsExpert.SetActive(New: Boolean);
begin
if New <> Active then
begin
inherited;
if New then
TSetComponentPropsSettings.GetInstance.AddNotifierToIDE
else
TSetComponentPropsSettings.GetInstance.RemoveNotifierFromIDE;
end;
end;
{TGxSetComponentPropsSettings}
// Initialize all settings
constructor TSetComponentPropsSettings.Create;
begin
inherited;
FComponents := TStringList.Create;
FProperties := TStringList.Create;
FValues := TStringList.Create;
FPropertyTypes := TStringList.Create;
FSimulate := True;
FVerbose := True;
FOnlyOpenFiles := True;
FGxSetComponentPropsNotifier := nil;
end;
// Free all lists and the notifier in the IDE
destructor TSetComponentPropsSettings.Destroy;
begin
RemoveNotifierFromIDE;
FreeAndNil(FComponents);
FreeAndNil(FProperties);
FreeAndNil(FValues);
FreeAndNil(FPropertyTypes);
inherited;
end;
// Register the notifier in the IDE
function TSetComponentPropsSettings.AddNotifierToIDE: Boolean;
begin
if Assigned(FGxSetComponentPropsNotifier) then
RemoveNotifierFromIDE;
FGxSetComponentPropsNotifier := TSetComponentPropsNotifier.Create;
Result := FGxSetComponentPropsNotifier.AddNotifierToIDE;
end;
// Class procedure to Free the settings container
class procedure TSetComponentPropsSettings.FreeMe;
begin
FreeAndNil(GxSetComponentPropsSettings);
end;
// Class function to get a singleton instance of the settings container
class function TSetComponentPropsSettings.GetInstance: TSetComponentPropsSettings;
begin
if not Assigned(GxSetComponentPropsSettings) then
GxSetComponentPropsSettings := TSetComponentPropsSettings.Create;
Result := GxSetComponentPropsSettings;
end;
// Remove the notifier from the IDE and set the var to nil
procedure TSetComponentPropsSettings.RemoveNotifierFromIDE;
begin
if Assigned(FGxSetComponentPropsNotifier) then
begin
FGxSetComponentPropsNotifier.RemoveNotifierFromIDE;
FGxSetComponentPropsNotifier := nil;
end;
end;
{TSetComponentPropsNotifier}
// Create a list for the output messages
constructor TSetComponentPropsNotifier.Create;
begin
inherited;
FOutputMessages := TStringList.Create;
end;
// Free the output messages list before destroying
destructor TSetComponentPropsNotifier.Destroy;
begin
FreeAndNil(FOutputMessages);
inherited;
end;
// Add a message to the output message list
procedure TSetComponentPropsNotifier.AddMessageToList(const
sModuleFileName, sFormat: string; const Args: array of const);
begin
FOutputMessages.Add(sModuleFileName + '|' + Format(sFormat, Args));
end;
// After compilation, add any pending mesages to the message view
procedure TSetComponentPropsNotifier.AfterCompile(Succeeded: Boolean; IsCodeInsight: Boolean);
var
sFileName, sMessage: string;
begin
if (IsCodeInsight = False) and TSetComponentPropsSettings.GetInstance.Verbose then
begin
if FOutputMessages.Count > 0 then
begin
GxOtaWriteTitleMessage('Properties set before compilation by GExperts Set Component Properties:');
if TSetComponentPropsSettings.GetInstance.Simulate then
GxOtaWriteTitleMessage('Simulation Mode: No property changes are being made');
end;
while FOutputMessages.Count > 0 do
begin
sFileName := Copy(FOutputMessages[0], 1, Pos('|', FOutputMessages[0]) - 1);
sMessage := Copy(FOutputMessages[0], Pos('|', FOutputMessages[0]) + 1, MaxInt);
GxOtaWriteToolMessage(sFileName, sMessage, '', 0, 0);
FOutputMessages.Delete(0);
end;
end;
end;
// Iterate all modules of the current project before compiling and
// look for components and properties to be set
procedure TSetComponentPropsNotifier.BeforeCompile(const Project: IOTAProject;
IsCodeInsight: Boolean; var Cancel: Boolean);
var
ModuleInfo: IOTAModuleInfo;
Module: IOTAModule;
FormEditor: IOTAFormEditor;
RootComponent: IOTAComponent;
IndexProjectModules: Integer;
CurrentEditor: IOTAEditor;
Settings: TSetComponentPropsSettings;
FileName: string;
FileChanged: Boolean;
FileWasOpen: Boolean;
begin
FOutputMessages.Clear;
Settings := TSetComponentPropsSettings.GetInstance;
if IsCodeInsight = False then
begin
try
CurrentEditor := GxOtaGetCurrentEditor;
if Settings.Verbose then
TfmSetComponentPropsStatus.GetInstance.Show;
// Iterate all modules of the current project and get forms and datamodules
for IndexProjectModules := 0 to Pred(Project.GetModuleCount) do
begin
ModuleInfo := Project.GetModule(IndexProjectModules);
FileName := ModuleInfo.FileName;
FileChanged := False;
if Settings.Verbose then
TfmSetComponentPropsStatus.GetInstance.ProcessedFile := FileName;
if (not IsDcp(FileName)) and (FileName <> '') then
begin
FileWasOpen := GxOtaIsFileOpen(FileName);
if Settings.OnlyOpenFiles then
begin
if not FileWasOpen then
Continue;
end;
try
Module := ModuleInfo.OpenModule;
if Assigned(Module) then
begin
FormEditor := GxOtaGetFormEditorFromModule(Module);
if Assigned(FormEditor) then
begin
RootComponent := FormEditor.GetRootComponent;
if Assigned(RootComponent) then begin
FileChanged := FileChanged or CheckAndSetComponent(ModuleInfo.FileName, RootComponent);
FileChanged := FileChanged or CheckChildComponents(RootComponent, ModuleInfo.FileName);
if (not FileChanged) and (not FileWasOpen) then
Module.CloseModule(True)
else if FileChanged and (not FileWasOpen) then
GxOtaOpenFile(FileName);
end;
end;
end;
except
on EFOpenError do
begin
// Ignore exceptions about non-existing modules
end;
else
begin
// Other exceptions are re-raised
raise;
end;
end;
end;
end;
if Assigned(CurrentEditor) then
CurrentEditor.Show;
finally
TfmSetComponentPropsStatus.ReleaseMe;
end;
end;
end;
// Check a given component for properties to be set
function TSetComponentPropsNotifier.CheckAndSetComponent(const
ModuleFileName: string; Component: IOTAComponent): Boolean;
var
NativeComponent: TComponent;
IndexComponents: Integer;
cName, cClass, cProperty, cValue: string;
Settings: TSetComponentPropsSettings;
PropType: TTypeKind;
CurrentValue: string;
NormalizedValue: string;
begin
Result := False;
NativeComponent := GxOtaGetNativeComponent(Component);
Settings := TSetComponentPropsSettings.GetInstance;
if Assigned(NativeComponent) then
begin
IndexComponents := 0;
while IndexComponents < Settings.Components.Count do
begin
cName := NativeComponent.Name;
cClass := Settings.Components[IndexComponents];
cProperty := Settings.Properties[IndexComponents];
cValue := Settings.Values[IndexComponents];
cValue := AnsiDequotedStr(cValue, #39);
if (cValue= #39#39) then
cValue := '';
if InheritsFromClass(NativeComponent.ClassType, cClass) then
begin
PropType := Component.GetPropTypeByName(cProperty);
if PropType = tkUnknown then
AddMessageToList(ModuleFileName, 'Unknown property name %s for class %s', [cProperty, cClass])
else
begin
try
CurrentValue := GxOtaGetComponentPropertyAsString(Component, cProperty);
NormalizedValue := GxOtaNormalizePropertyValue(Component, cProperty, cValue);
if CurrentValue <> NormalizedValue then
begin
Result := True;
if Settings.Verbose then
AddMessageToList(ModuleFileName, '%s %s: Setting %s to %s', [cClass, cName, cProperty, cValue]);
if not Settings.Simulate then
if (not GxOtaSetComponentPropertyAsString(Component, cProperty, cValue)) then
AddMessageToList(ModuleFileName, '%s %s: Setting %s to %s failed', [cClass, cName, cProperty, cValue]);
end;
except
on E: Exception do
AddMessageToList(ModuleFileName, '%s %s: Setting %s to %s failed with exception %s', [cClass, cName, cProperty, cValue, QuotedStr(E.Message)]);
end;
end;
end;
Inc(IndexComponents);
end;
end;
end;
// Iterate all child components of a given RootComponent
function TSetComponentPropsNotifier.CheckChildComponents(
RootComponent: IOTAComponent; const ModuleFileName: string): Boolean;
var
IndexComponents: Integer;
Component: IOTAComponent;
begin
Result := False;
if Assigned(RootComponent) then
begin
// Iterate over the immediate child components
for IndexComponents := 0 to Pred(RootComponent.GetComponentCount) do
begin
Component := RootComponent.GetComponent(IndexComponents);
if Assigned(Component) then
Result := Result or CheckAndSetComponent(ModuleFileName, Component);
end;
end;
end;
function TSetComponentPropsExpert.IsDefaultActive: Boolean;
begin
Result := False;
end;
initialization
RegisterGX_Expert(TSetComponentPropsExpert);
end.
|
unit WorldTest1Form;
interface
uses
Kernel, Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ComCtrls, Population, ToolWin, ExtCtrls, World, Menus, Buttons, StdCtrls;
type
TWorldTestForm = class(TForm)
MapImage: TImage;
PopupMenu: TPopupMenu;
Panel3: TPanel;
SpeedButton4: TSpeedButton;
SpeedButton5: TSpeedButton;
SpeedButton6: TSpeedButton;
ShowTowns: TSpeedButton;
Label1: TLabel;
SpeedButton1: TSpeedButton;
Timer: TTimer;
Image1: TImage;
Panel4: TPanel;
Image2: TImage;
Shape1: TShape;
Money: TLabel;
Date: TLabel;
procedure FormCreate(Sender: TObject);
procedure MapImageMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure FormResize(Sender: TObject);
procedure MapImageMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure MapImageMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure SpeedButton2Click(Sender: TObject);
procedure ShowTownsClick(Sender: TObject);
procedure PopupMenuPopup(Sender: TObject);
procedure TimerTimer(Sender: TObject);
procedure MapImageDblClick(Sender: TObject);
private
fWorld : TInhabitedWorld;
Company : TCompany;
fx, fy : integer;
fDelta : TPoint;
fDrag : TPoint;
fDown : boolean;
Grnd : TBitmap;
GridSize : integer;
ItemDelete : TMenuItem;
private
procedure PaintMap( x, y, dx, dy : integer );
procedure PaintFacilities;
procedure PaintTowns;
private
procedure OnItemClick( Sender : TObject );
procedure DeleteFacility( Sender : TObject );
end;
var
WorldTestForm: TWorldTestForm;
implementation
{$R *.DFM}
uses
ClassStorage, Simtst1blks, PopulatedBlock, WorkCenterBlock, Trade,
PublicFacility, BlockView, Construction;
const
TownCount = 25;
var
TownColors : array[0..TownCount - 1] of TColor;
function FormatMoney( money : string ) : string;
var
i : integer;
begin
result := money;
for i := length(result) downto 1 do
if (i mod 3 = 0) and (i < length(result))
then insert( ',', result, length(result) - i + 1 )
end;
// TWorldTestForm
procedure TWorldTestForm.FormCreate(Sender: TObject);
var
Town : TTown;
i, j, k : integer;
x, y : integer;
Item : TMenuItem;
begin
randomize;
InitTheClassStorage;
TMetaFluid.Create( 'Test', 'Test', 'Sample Fluid', 0, 100 ).Register( 'Fluids' );
Population.RegisterMetaInstances;
Construction.RegisterMetaInstances;
with TMetaBlockUnderConstruction.Create( '1x1 construction', 40, 10, 200, 0, 0, TBlockUnderConstruction ) do
begin
xSize := 1;
ySize := 1;
Register( 'Blocks' );
end;
with TMetaBlockUnderConstruction.Create( '2x2 construction', 41, 20, 400, 0, 0, TBlockUnderConstruction ) do
begin
xSize := 2;
ySize := 2;
Register( 'Blocks' );
end;
with TMetaBlockUnderConstruction.Create( '3x3 construction', 42, 40, 900, 0, 0, TBlockUnderConstruction ) do
begin
xSize := 3;
ySize := 3;
Register( 'Blocks' );
end;
with TMetaBlockUnderConstruction.Create( '4x4 construction', 43, 130, 1600, 100, 1000, TBlockUnderConstruction ) do
begin
xSize := 4;
ySize := 4;
Register( 'Blocks' );
end;
with TMetaPopulatedBlock.Create( 'HighClassBuilding', 101, pkHigh, 50, TPopulatedBlock ) do
begin
xSize := 1;
ySize := 1;
Register( 'Blocks' );
end;
with TMetaFacility.Create( '0A', 'Small Building (high class)', TFacility ) do
begin
XSize := 1;
YSize := 1;
Level := 120;
EvlStages.Insert( TEvlStage.Create( 'Normal', 'Normal', 'Suddenly achieved', TheClassStorage.ClassById['Blocks', '1x1 construction'] as TMetaBlock ));
EvlStages.Insert( TEvlStage.Create( 'Normal', 'Normal', 'Suddenly achieved', TheClassStorage.ClassById['Blocks', 'HighClassBuilding'] as TMetaBlock ));
Register( 'Facilities' );
end;
with TMetaPopulatedBlock.Create( 'MiddleClassBuilding', 102, pkMiddle, 200, TPopulatedBlock ) do
begin
xSize := 2;
ySize := 2;
Register( 'Blocks' );
end;
with TMetaFacility.Create( '0B', 'Medium Building (middle class)', TFacility ) do
begin
XSize := 2;
YSize := 2;
Level := 110;
EvlStages.Insert( TEvlStage.Create( 'Normal', 'Normal', 'Suddenly achieved', TheClassStorage.ClassById['Blocks', '2x2 construction'] as TMetaBlock ));
EvlStages.Insert( TEvlStage.Create( 'Normal', 'Normal', 'Suddenly achieved', TheClassStorage.ClassById['Blocks', 'MiddleClassBuilding'] as TMetaBlock ));
Register( 'Facilities' );
end;
with TMetaPopulatedBlock.Create( 'LowClassBuilding', 103, pkLow, 400, TPopulatedBlock ) do
begin
xSize := 3;
ySize := 3;
Register( 'Blocks' );
end;
with TMetaFacility.Create( '0C', 'Large Building (low class)', TFacility ) do
begin
XSize := 3;
YSize := 3;
Level := 140;
EvlStages.Insert( TEvlStage.Create( 'Normal', 'Normal', 'Suddenly achieved', TheClassStorage.ClassById['Blocks', '3x3 construction'] as TMetaBlock ));
EvlStages.Insert( TEvlStage.Create( 'Normal', 'Normal', 'Suddenly achieved', TheClassStorage.ClassById['Blocks', 'LowClassBuilding'] as TMetaBlock ));
Register( 'Facilities' );
end;
with TMetaWorkCenter.Create( 'Factory', 104, [40, 100, 500], TWorkCenter ) do
begin
xSize := 4;
ySize := 4;
Register( 'Blocks' );
end;
with TMetaFacility.Create( '0D', 'Factory of Nothing', TFacility ) do
begin
XSize := 4;
YSize := 4;
Level := 14;
EvlStages.Insert( TEvlStage.Create( 'Normal', 'Normal', 'Suddenly achieved', TheClassStorage.ClassById['Blocks', '4x4 construction'] as TMetaBlock ));
EvlStages.Insert( TEvlStage.Create( 'Normal', 'Normal', 'Suddenly achieved', TheClassStorage.ClassById['Blocks', 'Factory'] as TMetaBlock ));
Register( 'Facilities' );
end;
// Public Facilities
with TMetaPublicFacilityInfo.Create( 'Police' ) do
begin
Name := 'Police Dep.';
Importance := 100;
ModStrength := 10;
Register( tidClassFamily_PublicFacilities )
end;
with TMetaPublicFacilityInfo.Create( 'Fire' ) do
begin
Name := 'Fire Dep.';
Importance := 30;
ModStrength := 10;
Register( tidClassFamily_PublicFacilities )
end;
with TMetaPublicFacilityInfo.Create( 'Health' ) do
begin
Name := 'Health';
Importance := 70;
ModStrength := 10;
Register( tidClassFamily_PublicFacilities )
end;
with TMetaPublicFacilityInfo.Create( 'School' ) do
begin
Name := 'School';
Importance := 80;
ModFact := 0.1;
ModStrength := 10;
Register( tidClassFamily_PublicFacilities )
end;
with TMetaPublicFacility.Create( 'PoliceStation', 110, TPublicFacility ) do
begin
Kind := TheClassStorage.ClassById[tidClassFamily_PublicFacilities, 'Police'] as TMetaPublicFacilityInfo;
Strength := 1000;
XSize := 1;
YSize := 1;
Register( 'Blocks' );
end;
with TMetaFacility.Create( 'PoliceStation', 'Police Station', TFacility ) do
begin
XSize := 1;
YSize := 1;
Level := 100;
EvlStages.Insert( TEvlStage.Create( 'Normal', 'Normal', 'Suddenly achieved', TheClassStorage.ClassById['Blocks', '1x1 construction'] as TMetaBlock ));
EvlStages.Insert( TEvlStage.Create( 'Normal', 'Normal', 'Suddenly achieved', TheClassStorage.ClassById['Blocks', 'PoliceStation'] as TMetaBlock ));
Register( 'Facilities' );
end;
with TMetaPublicFacility.Create( 'FireStation', 111, TPublicFacility ) do
begin
Kind := TheClassStorage.ClassById[tidClassFamily_PublicFacilities, 'Fire'] as TMetaPublicFacilityInfo;
Strength := 2000;
XSize := 2;
YSize := 2;
Register( 'Blocks' );
end;
with TMetaFacility.Create( 'FireStation', 'Fire Station', TFacility ) do
begin
XSize := 2;
YSize := 2;
Level := 100;
EvlStages.Insert( TEvlStage.Create( 'Normal', 'Normal', 'Suddenly achieved', TheClassStorage.ClassById['Blocks', '2x2 construction'] as TMetaBlock ));
EvlStages.Insert( TEvlStage.Create( 'Normal', 'Normal', 'Suddenly achieved', TheClassStorage.ClassById['Blocks', 'FireStation'] as TMetaBlock ));
Register( 'Facilities' );
end;
with TMetaPublicFacility.Create( 'Hospital', 112, TPublicFacility ) do
begin
Kind := TheClassStorage.ClassById[tidClassFamily_PublicFacilities, 'Health'] as TMetaPublicFacilityInfo;
Strength := 2000;
XSize := 2;
YSize := 2;
Register( 'Blocks' );
end;
with TMetaFacility.Create( 'Hospital', 'Hospital', TFacility ) do
begin
XSize := 2;
YSize := 2;
Level := 100;
EvlStages.Insert( TEvlStage.Create( 'Normal', 'Normal', 'Suddenly achieved', TheClassStorage.ClassById['Blocks', '2x2 construction'] as TMetaBlock ));
EvlStages.Insert( TEvlStage.Create( 'Normal', 'Normal', 'Suddenly achieved', TheClassStorage.ClassById['Blocks', 'Hospital'] as TMetaBlock ));
Register( 'Facilities' );
end;
with TMetaPublicFacility.Create( 'Clinic', 113, TPublicFacility ) do
begin
Kind := TheClassStorage.ClassById[tidClassFamily_PublicFacilities, 'Health'] as TMetaPublicFacilityInfo;
Strength := 100;
XSize := 1;
YSize := 1;
Register( 'Blocks' );
end;
with TMetaFacility.Create( 'Clinic', 'Clinic', TFacility ) do
begin
XSize := 1;
YSize := 1;
Level := 100;
EvlStages.Insert( TEvlStage.Create( 'Normal', 'Normal', 'Suddenly achieved', TheClassStorage.ClassById['Blocks', '1x1 construction'] as TMetaBlock ));
EvlStages.Insert( TEvlStage.Create( 'Normal', 'Normal', 'Suddenly achieved', TheClassStorage.ClassById['Blocks', 'Clinic'] as TMetaBlock ));
Register( 'Facilities' );
end;
with TMetaPublicFacility.Create( 'School', 114, TPublicFacility ) do
begin
Kind := TheClassStorage.ClassById[tidClassFamily_PublicFacilities, 'School'] as TMetaPublicFacilityInfo;
Strength := 100;
XSize := 2;
YSize := 2;
Register( 'Blocks' );
end;
with TMetaFacility.Create( 'School', 'School', TFacility ) do
begin
XSize := 2;
YSize := 2;
Level := 100;
EvlStages.Insert( TEvlStage.Create( 'Normal', 'Normal', 'Suddenly achieved', TheClassStorage.ClassById['Blocks', '2x2 construction'] as TMetaBlock ));
EvlStages.Insert( TEvlStage.Create( 'Normal', 'Normal', 'Suddenly achieved', TheClassStorage.ClassById['Blocks', 'School'] as TMetaBlock ));
Register( 'Facilities' );
end;
RegisterTownHall( 'TownHall', 12, 3, 3 );
RegisterTradeCenter( 'TradeCenter', 14, 2, 2 );
GridSize := 25;
fWorld := TInhabitedWorld.Create( 200, 200 );
k := 0;
for i := 0 to trunc(sqrt(TownCount)) - 1 do
for j := 0 to trunc(sqrt(TownCount)) - 1 do
begin
TownColors[k] := random( $00FFFFFF );
x := (fWorld.xSize div (trunc(sqrt(TownCount))))*succ(i) - (fWorld.xSize div (trunc(sqrt(TownCount)))) div 2 + (1 - 2*random(2))*random(10);
y := (fWorld.ySize div (trunc(sqrt(TownCount))))*succ(j) - (fWorld.ySize div (trunc(sqrt(TownCount)))) div 2 + (1 - 2*random(2))*random(10);
Town := TInhabitedTown.Create( 'TownHall', 'TradeCenter', x, y, fWorld );
Town.Name := 'Guamuta ' + IntToStr(k + 1);
fWorld.Towns.Insert( Town );
inc( k );
end;
Company := TCompany.Create;
Company.Budget := 50*1000*1000;
Company.Name := 'Zonzom Corp.';
fWorld.Companies.Insert( Company );
MapImage.Picture.Bitmap := TBitmap.Create;
MapImage.Picture.Bitmap.Width := MapImage.Width;
MapImage.Picture.Bitmap.Height := MapImage.Height;
for i := 0 to pred(TheClassStorage.ClassCount['Facilities']) do
if (TheClassStorage.ClassByIdx['Facilities', i] as TMetaFacility).InTown
then
begin
Item := TMenuItem.Create( PopupMenu );
PopupMenu.Items.Add( Item );
with Item, (TheClassStorage.ClassByIdx['Facilities', i] as TMetaFacility) do
begin
Caption := 'Build ' + Name + ' $' + FormatMoney(IntToStr(round(Price/1000))) + 'K';
Tag := i;
OnClick := OnItemClick;
end;
end;
Item := TMenuItem.Create( PopupMenu );
with Item do
begin
Caption := '-';
end;
PopupMenu.Items.Add( Item );
ItemDelete := TMenuItem.Create( PopupMenu );
with ItemDelete do
begin
Caption := 'Delete';
OnClick := DeleteFacility;
end;
PopupMenu.Items.Add( ItemDelete );
Grnd := TBitmap.Create;
Grnd.LoadFromFile( ExtractFilePath(Application.ExeName) + 'ground.bmp' );
for i := 0 to fWorld.xSize - 1 do
for j := 0 to fWorld.ySize - 1 do
fWorld.GroundMap[i, j] := fWorld.NearestTown( i, j ).Id;
fDelta.x := fWorld.xSize div 2;
fDelta.y := fWorld.ySize div 2;
Left := 0;
Top := 0;
Width := Screen.Width;
Height := Screen.Height;
end;
procedure TWorldTestForm.MapImageMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
if Button = mbRight
then
begin
fx := fDelta.x + x div GridSize;
fy := fDelta.y + y div GridSize;
PopupMenu.Popup( ClientOrigin.x + x, ClientOrigin.y + y );
end
else
begin
fDown := false;
PaintFacilities;
PaintTowns;
{
if (abs(x - fDrag.x) div GridSize > 0) or (abs(y - fDrag.y) div GridSize > 0)
then
begin
dec( fDelta.x, (x - fDrag.x) div GridSize );
dec( fDelta.y, (y - fDrag.y) div GridSize );
PaintMap;
end;
}
end;
end;
procedure TWorldTestForm.PaintMap( x, y, dx, dy : integer );
var
xi, yi : integer;
begin
with MapImage.Picture.Bitmap.Canvas do
begin
for yi := y to y + dy - 1 do
for xi := x to x + dx - 1 do
begin
if (xi < fWorld.xSize - 1) and (yi < fWorld.ySize - 1) and (xi > 0) and (yi > 0)
then
if fWorld.ObjectMap[xi, yi] = nil
then
begin
Brush.Color := Grnd.Canvas.Pixels[xi mod 100, yi mod 100];
Pen.Color := Brush.Color;
end
else
begin
Brush.Color := clBlack;
Pen.Color := clSilver;
end
else
begin
Pen.Color := clBlack;
Brush.Color := clBlack;
end;
Pen.Width := 1;
Rectangle( GridSize*(xi - fDelta.x), GridSize*(yi - fDelta.y), GridSize*(xi - fDelta.x) + GridSize, GridSize*(yi - fDelta.y) + GridSize );
if ShowTowns.Down
then
begin
Pen.Color := TownColors[fWorld.GroundMap[xi, yi] - 1];
//Pen.Width := 2;
MoveTo( GridSize*(xi - fDelta.x) + GridSize, GridSize*(yi - fDelta.y) );
LineTo( GridSize*(xi - fDelta.x), GridSize*(yi - fDelta.y) + GridSize );
MoveTo( GridSize*(xi - fDelta.x), GridSize*(yi - fDelta.y) );
LineTo( GridSize*(xi - fDelta.x) + GridSize, GridSize*(yi - fDelta.y) + GridSize );
end;
end;
end;
end;
procedure TWorldTestForm.PaintFacilities;
function FindMetaBlock( id : TMetaBlockNumId ) : TMetaBlock;
var
i : integer;
count : integer;
begin
i := 0;
count := TheClassStorage.ClassCount['Blocks'];
while (i < count) and (TMetaBlock(TheClassStorage.ClassByIdx['Blocks', i]).NumId <> Id) do
inc( i );
if i < count
then result := TMetaBlock(TheClassStorage.ClassByIdx['Blocks', i])
else result := nil;
end;
var
Report : TObjectReport;
BlockId : TMetaBlockNumId;
MBlock : TMetaBlock;
x, y : word;
i : integer;
begin
try
Report := fWorld.GetObjectsInArea( fDelta.x, fDelta.y, MapImage.Width div GridSize - 1, MapImage.Height div GridSize - 1);
for i := 0 to pred(length(Report) div 4) do
begin
BlockId := TMetaBlockNumId(Report[4*i + 1]);
x := TMetaBlockNumId(Report[4*i + 3]);
y := TMetaBlockNumId(Report[4*i + 4]);
MBlock := FindMetaBlock( BlockId );
with MapImage.Picture.Bitmap.Canvas do
begin
Brush.Color := TownColors[fWorld.FacilityAt( x, y ).Town.Id - 1];
if (BlockId >= 40) and (BlockId <= 50)
then
begin
Brush.Style := bsClear;
Pen.Color := clRed;
end
else
begin
Brush.Style := bsSolid;
Pen.Color := clBlack;
end;
Rectangle( (x - fDelta.x)*GridSize, (y - fDelta.y)*GridSize, (x + MBlock.xSize - fDelta.x)*GridSize, (y + MBlock.ySize - fDelta.y)*GridSize );
end;
end;
//Panel4.Caption := IntToStr(length(Report) div 4) + ' utilities on screen';
except
end;
end;
procedure TWorldTestForm.PaintTowns;
var
i : integer;
begin
with MapImage.Picture.Bitmap.Canvas do
begin
Brush.Color := clBlack;
Font.Color := clWhite;
end;
for i := 0 to pred(fWorld.Towns.Count) do
with TTown(fWorld.Towns[i]) do
if (xPos > fDelta.x) and (xPos < fDelta.x + MapImage.Width div GridSize) and
(yPos > fDelta.y) and (yPos < fDelta.y + MapImage.Height div GridSize)
then
with MapImage.Picture.Bitmap.Canvas do
begin
TextOut( (xPos - fDelta.x)*GridSize, (yPos - fDelta.y)*GridSize, Name );
end;
end;
procedure TWorldTestForm.FormResize(Sender: TObject);
begin
MapImage.Picture.Bitmap.Width := MapImage.Width;
MapImage.Picture.Bitmap.Height := MapImage.Height;
if fDelta.x < 0
then fDelta.x := 0;
if fDelta.y < 0
then fDelta.y := 0;
if fDelta.x + MapImage.Width div GridSize - 1 > fWorld.xSize
then fDelta.x := fWorld.xSize - MapImage.Width div GridSize;
if fDelta.y + MapImage.Height div GridSize - 1 > fWorld.xSize
then fDelta.y := fWorld.ySize - MapImage.Height div GridSize;
PaintMap( fDelta.x, fDelta.y, MapImage.Width div GridSize + 1, MapImage.Height div GridSize + 1 );
PaintFacilities;
PaintTowns;
end;
procedure TWorldTestForm.MapImageMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
fDown := true;
fDrag.x := x;
fDrag.y := y;
end;
procedure TWorldTestForm.MapImageMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
var
R1, R2 : TRect;
oldDelta : TPoint;
begin
if fDown and ((abs(x - fDrag.x) div GridSize > 0) or (abs(y - fDrag.y) div GridSize > 0))
then
begin
oldDelta := fDelta;
dec( fDelta.x, (x - fDrag.x) div GridSize );
dec( fDelta.y, (y - fDrag.y) div GridSize );
if fDelta.x < 0
then fDelta.x := 0;
if fDelta.y < 0
then fDelta.y := 0;
if fDelta.x + MapImage.Width div GridSize - 1 > fWorld.xSize
then fDelta.x := fWorld.xSize - MapImage.Width div GridSize;
if fDelta.y + MapImage.Height div GridSize - 1 > fWorld.xSize
then fDelta.y := fWorld.ySize - MapImage.Height div GridSize;
x := GridSize*(oldDelta.x - fDelta.x) + fDrag.x;
y := GridSize*(oldDelta.y - fDelta.y) + fDrag.y;
if x > fDrag.x
then
begin
R1.Left := 0;
R1.Right := MapImage.Width - ((x - fDrag.x) div GridSize)*GridSize;
R2.Left := ((x - fDrag.x) div GridSize)*GridSize;
R2.Right := MapImage.Width;
end
else
begin
R1.Left := -((x - fDrag.x) div GridSize)*GridSize;
R1.Right := MapImage.Width;
R2.Left := 0;
R2.Right := MapImage.Width + ((x - fDrag.x) div GridSize)*GridSize;
end;
if y > fDrag.y
then
begin
R1.Top := 0;
R1.Bottom := MapImage.Height - ((y - fDrag.y) div GridSize)*GridSize;
R2.Top := ((y - fDrag.y) div GridSize)*GridSize;
R2.Bottom := MapImage.Height;
end
else
begin
R1.Top := -((y - fDrag.y) div GridSize)*GridSize;
R1.Bottom := MapImage.Height;
R2.Top := 0;
R2.Bottom := MapImage.Height + ((y - fDrag.y) div GridSize)*GridSize;
end;
MapImage.Picture.Bitmap.Canvas.CopyRect( R2, MapImage.Picture.Bitmap.Canvas, R1 );
if x > fDrag.x
then PaintMap( fDelta.x, fDelta.y, (x - fDrag.x) div GridSize, MapImage.Height div GridSize + 1 )
else PaintMap( fDelta.x + MapImage.Width div GridSize - abs(x - fDrag.x) div GridSize, fDelta.y, abs(x - fDrag.x) div GridSize + 1, MapImage.Height div GridSize + 1 );
if y > fDrag.y
then PaintMap( fDelta.x, fDelta.y, MapImage.Width div GridSize + 1, (y - fDrag.y) div GridSize )
else PaintMap( fDelta.x, fDelta.y + MapImage.Height div GridSize - abs(y - fDrag.y) div GridSize, MapImage.Width div GridSize + 1, abs(y - fDrag.y) div GridSize + 1 );
//PaintMap( fDelta.x, fDelta.y, MapImage.Width div GridSize + 1, MapImage.Height div GridSize + 1 );
fDrag.x := x;
fDrag.y := y;
end;
end;
procedure TWorldTestForm.OnItemClick( Sender : TObject );
begin
fDown := false;
with TheClassStorage.ClassByIdx['Facilities', (Sender as TComponent).Tag] as TMetaFacility do
begin
fWorld.NewFacility( Id, 1, fx, fy );
PaintMap( fx, fy, xSize, ySize );
end;
PaintFacilities;
PaintTowns;
end;
procedure TWorldTestForm.DeleteFacility( Sender : TObject );
var
x, y, dx, dy : integer;
begin
with fWorld.FacilityAt( fx, fy ), MetaFacility do
begin
x := xPos;
y := yPos;
dx := xSize;
dy := ySize;
end;
fWorld.DelFacility( fx, fy );
PaintMap( x, y, dx, dy );
fDown := false;
end;
procedure TWorldTestForm.SpeedButton2Click(Sender: TObject);
begin
GridSize := (Sender as TComponent).Tag;
if fDelta.x + MapImage.Width div GridSize - 1 > fWorld.xSize
then fDelta.x := fWorld.xSize - MapImage.Width div GridSize;
if fDelta.y + MapImage.Height div GridSize - 1 > fWorld.xSize
then fDelta.y := fWorld.ySize - MapImage.Height div GridSize;
PaintMap( fDelta.x, fDelta.y, MapImage.Width div GridSize + 1, MapImage.Height div GridSize + 1 );
PaintFacilities;
PaintTowns;
end;
procedure TWorldTestForm.ShowTownsClick(Sender: TObject);
begin
PaintMap( fDelta.x, fDelta.y, MapImage.Width div GridSize + 1, MapImage.Height div GridSize + 1 );
PaintFacilities;
PaintTowns;
end;
procedure TWorldTestForm.PopupMenuPopup(Sender: TObject);
var
F : TFacility;
begin
F := fWorld.FacilityAt( fx, fy );
ItemDelete.Enabled := (F <> nil) and (F.Company <> nil);
end;
procedure TWorldTestForm.TimerTimer(Sender: TObject);
begin
fWorld.VirtualTimeTick( 1 );
fWorld.Simulate;
PaintFacilities;
PaintTowns;
if BlockViewer.Visible
then BlockViewer.RefreshContent;
Money.Caption := '$' + FormatMoney(IntToStr(round(Company.Budget)));
Date.Caption := DateToStr( fWorld.VirtualTime );
end;
procedure TWorldTestForm.MapImageDblClick(Sender: TObject);
var
F : TFacility;
begin
F := fWorld.FacilityAt( fDelta.x + fDrag.x div GridSize, fDelta.y + fDrag.y div GridSize );
if F <> nil
then BlockViewer.Facility := F;
end;
end.
|
unit SensorFrame;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, IniFiles, Misc;
type
TFrameSensor = class(TFrame)
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
gbSensor: TGroupBox;
edFactoryNum: TEdit;
edBusNumber: TEdit;
edNetNumber: TEdit;
cbOn: TCheckBox;
stPressure: TStaticText;
stTemperature: TStaticText;
stCount: TStaticText;
edCoeffK: TEdit;
Label6: TLabel;
Label7: TLabel;
edCoeffB: TEdit;
private
{ Private declarations }
Section:String;
function Get_TARDir: String;
public
{ Public declarations }
AdrList:TList;
BusNumber:Integer;
NetNumber:Integer;
SumPressure,P:Double;
SumTemperature,T:Double;
CoeffK,CoeffB:Double;
QueryCnt,MeasureCnt:Integer;
ValidTP:Boolean;
tt,pp:array[0..4] of Double;
xx,yy:array[0..12] of Double;
procedure LoadFromIniSection(Ini:TIniFile; const Section:String);
procedure WriteToIni(Ini:TIniFile);
function Validate:Boolean;
function LoadCoeffsFromTAR:Boolean;
procedure TimerProc;
destructor Destroy;override;
property TARDir:String read Get_TARDir;
end;
TAddress=class(TObject)
Host:String;
Port:Integer;
constructor Create(const Host:String; Port:Integer);
end;
implementation
{$R *.DFM}
uses Main;
{ TFrameSensor }
destructor TFrameSensor.Destroy;
var
i:Integer;
begin
if AdrList<>nil then begin
for i:=0 to AdrList.Count-1 do TObject(AdrList[i]).Free;
AdrList.Free;
end;
inherited;
end;
function TFrameSensor.Get_TARDir: String;
begin
Result:=TFormMain(Owner).TARDir;
end;
function TFrameSensor.LoadCoeffsFromTAR: Boolean;
var
i:Integer;
TAR:TextFile;
FileName:String;
begin
// Загрузка коэффициентов из *.TAR - файла
try
FileName:=TARDir+edFactoryNum.Text+'.tar';
AssignFile(TAR,FileName);
Reset(TAR);
try
for i:=1 to 4 do Read(TAR,tt[i]);
for i:=1 to 4 do Read(TAR,pp[i]);
for i:=1 to 12 do begin
Read(TAR,xx[i]);
Read(TAR,yy[i]);
end;
finally
Close(TAR);
end;
except
Result:=False;
exit;
end;
Result:=True;
end;
procedure TFrameSensor.LoadFromIniSection(Ini: TIniFile;
const Section: String);
var
i,Cnt:Integer;
begin
AdrList:=TList.Create;
Self.Section:=Section;
cbOn.Checked:=Ini.ReadInteger(Section,'On',1)<>0;
edFactoryNum.Text:=Ini.ReadString(Section,'FactoryNum','000000');
edBusNumber.Text:=Ini.ReadString(Section,'BusNumber','1');
edNetNumber.Text:=Ini.ReadString(Section,'NetNumber','1');
edCoeffK.Text:=Ini.ReadString(Section,'CoeffK','1');
edCoeffB.Text:=Ini.ReadString(Section,'CoeffB','0');
Cnt:=Ini.ReadInteger(Section,'DataCopies',0);
for i:=1 to Cnt do begin
AdrList.Add(TAddress.Create(
Ini.ReadString(Section,'Host'+IntToStr(i),''),
Ini.ReadInteger(Section,'Port'+IntToStr(i),0)
));
end;
end;
procedure TFrameSensor.TimerProc;
var
Coeff:Double;
begin
stCount.Caption:=IntToStr(MeasureCnt)+' из '+IntToStr(QueryCnt)+' ';
if MeasureCnt>0 then begin
Coeff:=1/MeasureCnt;
P:=SumPressure*Coeff*CoeffK+CoeffB;
T:=SumTemperature*Coeff;
stPressure.Caption:=Format('%2.3f ',[P]);
stTemperature.Caption:=Format('%2.3f ',[T]);
SumPressure:=0;
SumTemperature:=0;
ValidTP:=True;
end
else begin
stPressure.Caption:='';
stTemperature.Caption:='';
ValidTP:=False;
end;
MeasureCnt:=0;
QueryCnt:=0;
end;
function TFrameSensor.Validate: Boolean;
procedure ErrorMsg(const Msg:String);
begin
Application.MessageBox(PChar(Msg),'Ошибка',MB_ICONINFORMATION or MB_OK);
raise Exception.Create('');
end;
begin
Result:=False;
try
if not LoadCoeffsFromTAR then begin
edFactoryNum.SetFocus;
ErrorMsg('Ошибка при загрузке коэффициентов');
end;
try
CoeffK:=StrToFloat(edCoeffK.Text);
except
edCoeffK.SetFocus;
raise;
end;
try
CoeffB:=StrToFloat(edCoeffB.Text);
except
edCoeffB.SetFocus;
raise;
end;
try
BusNumber:=StrToInt(edBusNumber.Text);
if (BusNumber<0) or (255<BusNumber)
then ErrorMsg('Значение номера датчика на шине должно быть от 0 до 255');
except
edBusNumber.SetFocus;
raise;
end;
try
NetNumber:=StrToInt(edNetNumber.Text);
if (NetNumber<0) or (255<NetNumber)
then ErrorMsg('Локальный код датчика должен быть числом от 0 до 255');
except
edNetNumber.SetFocus;
raise;
end;
except
exit;
end;
Result:=True;
end;
procedure TFrameSensor.WriteToIni(Ini: TIniFile);
begin
Ini.WriteInteger(Section,'On',Integer(cbOn.Checked));
Ini.WriteString(Section,'FactoryNum',edFactoryNum.Text);
Ini.WriteString(Section,'BusNumber',edBusNumber.Text);
Ini.WriteString(Section,'NetNumber',edNetNumber.Text);
Ini.WriteString(Section,'CoeffK',edCoeffK.Text);
Ini.WriteString(Section,'CoeffB',edCoeffB.Text);
end;
{ TAddress }
constructor TAddress.Create(const Host: String; Port: Integer);
begin
inherited Create;
Self.Host:=Host;
Self.Port:=Port;
end;
end.
|
unit l3Units;
{* Модуль описывающий работу с различными единицами измерения. }
{ Библиотека "Эверест" }
{ Автор: Люлин А.В. © }
{ Модуль: l3Units - работа с различными единицами измерения}
{ Начат: 12.12.96 }
{ $Id: l3Units.pas,v 1.32 2014/05/20 16:49:24 lulin Exp $ }
// $Log: l3Units.pas,v $
// Revision 1.32 2014/05/20 16:49:24 lulin
// - пытаемся восстановить компилируемость под XE.
//
// Revision 1.31 2014/05/20 16:18:07 lulin
// - пытаемся восстановить компилируемость под XE.
//
// Revision 1.30 2014/05/20 15:51:49 lulin
// - пытаемся восстановить компилируемость под XE.
//
// Revision 1.29 2013/05/24 15:59:50 lulin
// - пытаемся портироваться под XE4.
//
// Revision 1.28 2012/06/14 10:19:19 dinishev
// {Requestlink:371197572}
//
// Revision 1.27 2011/11/01 10:12:14 lulin
// {RequestLink:290953660}
//
// Revision 1.26 2011/10/14 15:23:34 dinishev
// {Requestlink:281520291}
//
// Revision 1.25 2011/07/20 11:16:03 lulin
// {RequestLink:228688745}.
//
// Revision 1.24 2010/01/19 20:16:33 lulin
// {RequestLink:178717800}. Заготовочка.
//
// Revision 1.23 2008/08/26 11:22:08 lulin
// - чистка кода.
//
// Revision 1.22 2008/02/27 17:25:04 lulin
// - подгоняем код под модель.
//
// Revision 1.21 2007/11/28 13:59:46 dinishev
// Bug fix: возникало переполнение
//
// Revision 1.20 2007/08/14 19:31:59 lulin
// - оптимизируем очистку памяти.
//
// Revision 1.19 2007/04/02 06:17:55 lulin
// - убрана неправильная зависимость.
//
// Revision 1.18 2006/11/03 11:00:47 lulin
// - объединил с веткой 6.4.
//
// Revision 1.17.4.1 2006/10/20 09:40:45 lulin
// - cleanup.
//
// Revision 1.17 2006/06/06 13:47:57 lulin
// - стараемся уменьшить число вызовов GDI.
//
// Revision 1.16 2005/05/27 12:06:04 lulin
// - убраны лишние зависимости.
//
// Revision 1.15 2005/05/26 16:01:48 lulin
// - избавил базовую канву вывода от знания о константах Эвереста.
//
// Revision 1.14 2005/05/24 12:48:20 lulin
// - для канвы используем интерфейс, а не объект.
//
// Revision 1.13 2005/04/16 11:41:27 lulin
// - слил с веткой. Теперь из ветки можно вытягивать ТОЛЬКО Everest.
//
// Revision 1.12.2.1 2005/04/13 10:20:04 lulin
// - cleanup.
//
// Revision 1.12 2005/02/22 12:27:44 lulin
// - рефакторинг работы с Tl3Point и Tl3Rect.
//
// Revision 1.11 2004/12/04 11:40:38 mmorozov
// new: overload function l3SRect;
//
// Revision 1.10 2003/11/13 11:53:48 law
// - new method: Tl3Point.IsNull.
//
// Revision 1.9 2003/09/17 14:12:59 law
// - bug fix: integer overflow, кода отрисовывается закрывающееся окно (OIT500004649).
//
// Revision 1.8 2003/05/22 13:10:10 law
// - cleanup.
//
// Revision 1.7 2003/05/21 15:55:59 law
// - new behavior: правую границу блока рисуем "в бесконечности".
//
// Revision 1.6 2003/04/15 13:26:49 law
// - new unit: evUnits.
//
// Revision 1.5 2002/09/18 07:24:03 law
// - cleanup: evDefine.inc -> l3Define.inc.
//
// Revision 1.4 2002/07/23 15:26:58 law
// - rename proc: evRectBnd -> l3RectBnd.
//
// Revision 1.3 2002/07/11 12:03:15 law
// - rename proc: evPoint -> l3Point, evRect -> l3Rect.
//
// Revision 1.2 2002/07/11 07:06:21 law
// - new behavior: защита от экспериментаторов и пидарасов.
//
// Revision 1.1 2002/07/09 12:49:23 law
// - rename unit: evUnits -> l3Units.
//
// Revision 1.34 2002/07/09 11:12:42 law
// - new type: Tl3Inch.
//
// Revision 1.33 2002/01/08 13:54:14 law
// - rename type: TevOrientation -> Tl3Orientation.
//
// Revision 1.32 2002/01/05 11:09:36 law
// - cleanup.
//
// Revision 1.31 2001/11/23 17:25:21 law
// - cleanup.
//
// Revision 1.30 2001/09/19 15:55:21 law
// - new behavior: начата работа над возможностью сворачивать и разворачивать блоки документа.
//
// Revision 1.29 2001/09/07 08:53:02 law
// - rename procedures: evPointX -> l3PointX, evPointY -> l3PointY.
//
// Revision 1.28 2001/08/31 12:59:06 law
// - comments & cleanup.
//
// Revision 1.27 2001/08/31 08:50:07 law
// - cleanup: первые шаги к кроссплатформенности.
//
// Revision 1.26 2001/07/27 15:46:04 law
// - comments: xHelpGen.
//
// Revision 1.25 2001/04/20 14:03:52 law
// - cleanup: def_cm* => def_inch*, evCm2Pixel -> evCm2Inch.
//
// Revision 1.24 2001/04/20 11:19:14 law
// - new const: добавлены константы def_inch*.
//
// Revision 1.23 2001/04/05 08:57:37 law
// - cleanup: использование модулей WinTypes и WinProcs заменен на Windows.
//
// Revision 1.22 2001/03/27 08:01:58 law
// - TevPoint -> Tl3Point, TevRect -> Tl3Rect.
//
// Revision 1.21 2001/03/11 17:08:22 law
// - дописаны комментарии для XHelpGen.
//
// Revision 1.20 2001/02/27 17:11:35 law
// - дописаны комментарии.
//
// Revision 1.19 2000/12/15 15:10:39 law
// - вставлены директивы Log.
//
{$Include l3Define.inc }
interface
uses
Windows,
//l3Types,
l3Interfaces
;
type
Tl3SPoint = Tl3_SPoint;
Tl3_SRect = {$IfDef XE4}packed record{$Else}packed object{$EndIf}
public
{public fields}
R : packed record
Case Byte of
0: (Left, Top, Right, Bottom : Integer);
1: (TopLeft, BottomRight: Tl3SPoint);
2: (bRt: array [Boolean] of Tl3SPoint);
3: (WR: Windows.TRect);
end;{R}
public
// public properties
property Left: Integer
read R.Left
write R.Left;
{-}
property Right: Integer
read R.Right
write R.Right;
{-}
property Top: Integer
read R.Top
write R.Top;
{-}
property Bottom: Integer
read R.Bottom
write R.Bottom;
{-}
property TopLeft: Tl3SPoint
read R.TopLeft
write R.TopLeft;
{-}
property BottomRight: Tl3SPoint
read R.BottomRight
write R.BottomRight;
{-}
public
// public methods
procedure InitPoint(const P1, P2: TPoint);
{* - инициализирует прямоугольник типом TPoint. }
procedure InitRect(const Rect: Windows.TRect);
{* - инициализирует прямоугольник типом Windows.TRect. }
function IntersectsWith(const Rt: Tl3_SRect): Boolean;
{* - проверяет пересечение Self с Rt. }
function InitClientRect(Wnd: hWnd): Boolean;
{* - инициализирует прямоугольник клиентской областью Wnd. }
procedure OffsetPt(const Pt: Tl3SPoint);
{* - сдвинуть прямоугольник на Pt. }
procedure Offset(aX, aY: Integer);
{* - сдвинуть прямоугольник на (X, Y). }
function ContainsPt(const Pt: Tl3SPoint): Boolean;
{* - содержит ли прямоугольник точку Pt. }
procedure InflatePt(const Pt: Tl3SPoint);
{* - увеличивает размеры прямоугольника на P. }
procedure Inflate(X, Y: Integer);
{* - увеличивает размеры прямоугольника на (X, Y). }
procedure Inflate1(X: Integer);
{* - увеличивает размеры прямоугольника на (X, X). }
function IsEmpty: Boolean;
{* - проверяет не пустой ли прямоугольник. }
function Invert(DC: hDC): Boolean;
{* - инвертировать прямоугольник на DC. }
function CreateRgn: hRgn;
{* - создать регион содержащий данный прямоугольник. }
function EQ(const Rt: Tl3_SRect): Boolean;
{* - проверяет равенство двух прямоугольников. }
procedure MakeZoom(Z: Integer);
{* - увеличивает координаты прямоугольника на Z %. }
procedure MakeDezoom(Z: Integer);
{* - уменьшает координаты прямоугольника на Z %. }
function Invalidate(Wnd: hWnd; Erase: Boolean): Boolean;
{* - метит прямоугольник в окне Wnd для обновления. }
function GetRgn(Rgn: hRgn): Integer;
{* - инициализирует прямоугольник максимальными размерами региона Rgn. }
function IntersectClip(DC: hDC): Integer;
{* - устанавливает область отсечения контексту DC.}
function GetClip(DC: hDC): Boolean;
{* -инициализирут прямоугольник значением области отсечения. }
function AddPt(const Pt: Tl3SPoint): Tl3_SRect;
{* - сдвинуть прямоугольник на Pt и вернуть Result. }
function SubPt(const Pt: Tl3SPoint): Tl3_SRect;
{* - сдвинуть прямоугольник на -Pt и вернуть Result. }
end;//Tl3_SRect
Tl3SRect = Tl3_SRect;
Tl3Point = Tl3_Point;
Tl3Rect = Tl3_Rect;
function l3Point(X, Y: Integer): Tl3Point;
function l3Rect(aLeft, aTop, aRight, aBottom: Integer): Tl3Rect;
overload;
function l3Rect(const TopLeft, BottomRight: Tl3_Point): Tl3Rect;
overload;
function l3RectBnd(const TopLeft, Extent: Tl3_Point): Tl3Rect;
function l3SRectBnd(const TopLeft, Extent: Tl3_SPoint): Tl3SRect;
function l3SPoint(X, Y: Integer): Tl3SPoint;
{* - "конструктор" для Tl3SPoint. }
function l3SBounds(ALeft, ATop, AWidth, AHeight: Integer): Tl3SRect;
{-}
function l3SRect(Left, Top, Right, Bottom: Integer): Tl3SRect;
overload;
function l3SRect(const TopLeft, BottomRight: Tl3SPoint): Tl3SRect;
overload;
function l3SRect(aRect : TRect) : Tl3SRect;
overload;
function l3Point1(X: Integer): Tl3Point;
function l3PointX(X: Integer): Tl3Point;
function l3PointY(Y: Integer): Tl3Point;
function l3PointD0(A, B: Integer; D: Boolean): Tl3Point;
function Point1(X: Integer): Tl3SPoint;
function PointX(X: Integer): Tl3SPoint;
function PointY(Y: Integer): Tl3SPoint;
function evInchZoom(Zoom: Integer; Inch: Integer): Integer;
function evInchDezoom(Zoom: Integer; Inch: Integer): Integer;
function evPixelZoom(Zoom: Integer; Pixel: Integer): Integer;
function evPixelDezoom(Zoom: Integer; Pixel: Integer): Integer;
function l3IntersectRect(const SR1, SR2: Tl3Rect): Tl3Rect;
overload;
function l3IntersectRect(const SR1, SR2: Tl3SRect): Tl3SRect;
overload;
{* - пересекает два прямоугольника. }
const
l3Point0 : Tl3Point = (P: (X: 0; Y: 0));
l3Point_1 : Tl3Point = (P: (X: -1; Y: -1));
l3SPoint0 : Tl3SPoint = (P: (X: 0; Y: 0));
l3Rect0 : Tl3Rect = (R: (Left: 0; Top: 0; Right: 0; Bottom: 0));
l3SRect1 : Tl3SRect = (R: (Left: 0; Top: 0; Right: 1; Bottom: 1));
l3SRect0 : Tl3SRect = (R: (Left: 0; Top: 0; Right: 0; Bottom: 0));
implementation
uses
l3MinMax,
l3Math,
l3Const,
l3Base
;
function l3IntersectRect(const SR1, SR2: Tl3Rect): Tl3Rect;
{* - пересекает два прямоугольника. }
var
l_Res : Boolean;
begin
with Result do
begin
R.Top := Max(SR1.R.Top, SR2.R.Top);
R.Bottom := Min(SR1.R.Bottom, SR2.R.Bottom);
l_Res := (R.Top < R.Bottom);
if l_Res then
begin
R.Left := Max(SR1.R.Left, SR2.R.Left);
R.Right := Min(SR1.R.Right, SR2.R.Right);
l_Res := (R.Left < R.Right);
end;//l_Res
end;//with Result
if not l_Res then
l3FillChar(Result, SizeOf(Result));
end;
function l3IntersectRect(const SR1, SR2: Tl3SRect): Tl3SRect;
{* - пересекает два прямоугольника. }
begin
Windows.IntersectRect(Result.R.WR, SR1.R.WR, SR2.R.WR);
end;
function evInchZoom(Zoom: Integer; Inch: Integer): Integer;
{-}
begin
if (Zoom <> 100) then
Result := l3MulDiv(Inch, Zoom, 100)
else
Result := Inch;
end;
function evInchDezoom(Zoom: Integer; Inch: Integer): Integer;
{-}
begin
if (Zoom <> 100) AND (Zoom > 0) then
Result := l3MulDiv(Inch, 100, Zoom)
else
Result := Inch;
end;
function evPixelZoom(Zoom: Integer; Pixel: Integer): Integer;
{-}
begin
if (Zoom <> 100) then
Result := l3MulDiv(Pixel, Zoom, 100)
else
Result := Pixel;
end;
function evPixelDezoom(Zoom: Integer; Pixel: Integer): Integer;
{-}
begin
if (Zoom <> 100) AND (Zoom > 0) then
Result := l3MulDiv(Pixel, 100, Zoom)
else
Result := Pixel;
end;
function l3Point(X, Y: Integer): Tl3Point;
begin
Result.X := X;
Result.Y := Y;
end;
function l3Point1(X: Integer): Tl3Point;
begin
Result.P.X := X;
Result.P.Y := X;
end;
function l3PointX(X: Integer): Tl3Point;
begin
Result.P.X := X;
Result.P.Y := 0;
end;
function l3PointY(Y: Integer): Tl3Point;
begin
Result.P.X := 0;
Result.P.Y := Y;
end;
function l3PointD0(A, B: Integer; D: Boolean): Tl3Point;
begin
Result.P.bPt[D] := A;
Result.P.bPt[not D] := B;
end;
function Point1(X: Integer): Tl3SPoint;
begin
Result.P.X := X;
Result.P.Y := X;
end;
function PointX(X: Integer): Tl3SPoint;
begin
Result.P.X := X;
Result.P.Y := 0;
end;
function PointY(Y: Integer): Tl3SPoint;
begin
Result.P.X := 0;
Result.P.Y := Y;
end;
function l3Rect(aLeft, aTop, aRight, aBottom: Integer): Tl3Rect;
begin
Result.R.Left := aLeft;
Result.R.Right := aRight;
Result.R.Top := aTop;
Result.R.Bottom := aBottom;
end;
function l3Rect(const TopLeft, BottomRight: Tl3_Point): Tl3Rect;
begin
Result.R.TopLeft := TopLeft;
Result.R.BottomRight := BottomRight;
end;
function l3RectBnd(const TopLeft, Extent: Tl3_Point): Tl3Rect;
begin
Result.R.TopLeft := TopLeft;
Result.R.BottomRight := Tl3Point(TopLeft).Add(Extent);
end;
function l3SRectBnd(const TopLeft, Extent: Tl3_SPoint): Tl3SRect;
begin
Result.R.TopLeft := Tl3SPoint(TopLeft);
Result.R.BottomRight := Tl3SPoint(TopLeft).Add(Extent);
end;
function l3SPoint(X, Y: Integer): Tl3SPoint;
begin
Result.P.X := X;
Result.P.Y := Y;
end;
function l3SBounds(ALeft, ATop, AWidth, AHeight: Integer): Tl3SRect;
begin
with Result do
begin
Left := ALeft;
Top := ATop;
Right := ALeft + AWidth;
Bottom := ATop + AHeight;
end;
end;
function l3SRect(Left, Top, Right, Bottom: Integer): Tl3SRect;
begin
Result.R.Left := Left;
Result.R.Top := Top;
Result.R.Right := Right;
Result.R.Bottom := Bottom;
end;
function l3SRect(const TopLeft, BottomRight: Tl3SPoint): Tl3SRect;
begin
Result.R.TopLeft := TopLeft;
Result.R.BottomRight := BottomRight;
end;
function l3SRect(aRect : TRect) : Tl3SRect;
// overload;
begin
Result.R.Left := aRect.Left;
Result.R.Top := aRect.Top;
Result.R.Right := aRect.Right;
Result.R.Bottom := aRect.Bottom;
end;
// start object Tl3SRect
procedure Tl3SRect.InitPoint(const P1, P2: TPoint);
{-инициализирует прямоугольник типом TPoint}
begin
R.Left := P1.X;
R.Top := P1.Y;
R.Right := P2.X;
R.Bottom := P2.Y;
end;
procedure Tl3SRect.InitRect(const Rect: Windows.TRect);
{-инициализирует прямоугольник типом Windows.TRect}
begin
R.WR := Rect;
end;
function Tl3SRect.IntersectsWith(const Rt: Tl3_SRect): Boolean;
{-проверяет пересечение Self с Rt}
var
OutR : Windows.TRect;
begin
Result := Boolean(Windows.IntersectRect(OutR, R.WR, Rt.R.WR));
end;
function Tl3SRect.InitClientRect(Wnd: hWnd): Boolean;
{-инициализирует прямоугольник клиентской областью Wnd}
begin
Windows.GetClientRect(Wnd, R.WR);
Result := true;
end;
procedure Tl3SRect.OffsetPt(const Pt: Tl3SPoint);
{-сдвинуть прямоугольник на Pt}
begin
R.TopLeft.Inc(Pt);
R.BottomRight.Inc(Pt);
end;
procedure Tl3SRect.Offset(aX, aY: Integer);
{-сдвинуть прямоугольник на (X, Y)}
begin
Inc(R.Top, aY);
Inc(R.Bottom, aY);
Inc(R.Left, aX);
Inc(R.Right, aX);
end;
function Tl3SRect.ContainsPt(const Pt: Tl3SPoint): Boolean;
{-содержит ли прямоугольник точку Pt}
begin
Result := Windows.PtInRect(Self.R.WR, TPoint(Pt));
end;
procedure Tl3SRect.InflatePt(const Pt: Tl3SPoint);
{-увеличивает размеры прямоугольника на P}
begin
R.TopLeft.Dec(Pt);
R.BottomRight.Inc(Pt);
end;
procedure Tl3SRect.Inflate(X, Y: Integer);
{-увеличивает размеры прямоугольника на (X, Y)}
begin
Dec(R.Left, X);
Inc(R.Right, X);
Dec(R.Top, Y);
Inc(R.Bottom, Y);
end;
procedure Tl3SRect.Inflate1(X: Integer);
{-увеличивает размеры прямоугольника на (X, X)}
begin
Dec(R.Left, X);
Inc(R.Right, X);
Dec(R.Top, X);
Inc(R.Bottom, X);
end;
function Tl3SRect.IsEmpty: Boolean;
{-проверяет не пустой ли прямоугольник}
begin
Result := Windows.IsRectEmpty(R.WR);
end;
function Tl3SRect.Invert(DC: hDC): Boolean;
{-инвертировать прямоугольник на DC}
begin
Windows.InvertRect(DC, R.WR);
Result := true;
end;
function Tl3SRect.CreateRgn: hRgn;
{-создать регион содержащий данный прямоугольник}
begin
Result := Windows.CreateRectRgnIndirect(R.WR);
if (Result <> 0) then
l3System.IncRgnCount;
end;
function Tl3SRect.EQ(const Rt: Tl3_SRect): Boolean;
{-проверяет равенство двух прямоугольников}
begin
Result := Windows.EqualRect(R.WR, Rt.R.WR);
end;
procedure Tl3SRect.MakeZoom(Z: Integer);
{-увеличивает координаты прямоугольника на Z %}
begin
R.TopLeft.MakeZoom(Z);
R.BottomRight.MakeZoom(Z);
end;
procedure Tl3SRect.MakeDezoom(Z: Integer);
{-уменьшает координаты прямоугольника на Z %}
begin
R.TopLeft.MakeDezoom(Z);
R.BottomRight.MakeDezoom(Z);
end;
function Tl3SRect.Invalidate(Wnd: hWnd; Erase: Boolean): Boolean;
{-}
begin
Windows.InvalidateRect(Wnd, @Self, Erase);
Result := true;
end;
function Tl3SRect.GetRgn(Rgn: hRgn): Integer;
{-инициализирует прямоугольник максимальными размерами региона Rgn}
begin
Result := Windows.GetRgnBox(Rgn, R.WR);
end;
function Tl3SRect.IntersectClip(DC: hDC): Integer;
{-устанавливает область отсечения контексту DC}
begin
with R do
Result := Windows.IntersectClipRect(DC, Left, Top, Right, Bottom);
end;
function Tl3SRect.GetClip(DC: hDC): Boolean;
{-инициализирут прямоугольник значением области отсечения}
begin
Result := (GetClipBox(DC, R.WR) <> Windows.ERROR);
end;
function Tl3SRect.AddPt(const Pt: Tl3SPoint): Tl3SRect;
{-сдвинуть прямоугольник на Pt и вернуть Result}
begin
Result.R.Left := R.Left + Pt.P.X;
Result.R.Right := R.Right + Pt.P.X;
Result.R.Top := R.Top + Pt.P.Y;
Result.R.Bottom := R.Bottom + Pt.P.Y;
end;
function Tl3SRect.SubPt(const Pt: Tl3SPoint): Tl3SRect;
{-сдвинуть прямоугольник на -Pt и вернуть Result}
begin
Result.R.Left := R.Left - Pt.P.X;
Result.R.Right := R.Right - Pt.P.X;
Result.R.Top := R.Top - Pt.P.Y;
Result.R.Bottom := R.Bottom - Pt.P.Y;
end;
end.
|
unit uWebPages;
interface
uses
// Indy
IdContext, IdCustomHTTPServer, IdHttpServer;
procedure RegisterWebPage(const AFileName: string; AEvent: TIdHTTPCommandEvent);
procedure UnRegisterWebPage(const AFileName: string);
function ExecuteWebPage(const AFileName: string; AContext: TIdContext;
ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo): Boolean;
function GetMimeType(const FileName: string): string;
{ For copy and paste, makes adding new pages easier.
procedure IdHTTPServer1CommandGet(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);
}
implementation
uses
// Codegear
SysUtils, Registry, Windows,
Generics.Collections;
type
PMethod = ^TMethod;
var
Dictionary: TDictionary<string,PMethod>;
procedure RegisterWebPage(const AFileName: string; AEvent: TIdHTTPCommandEvent);
function Add(const AMethod): PMethod;
var
m: TMethod;
p: PMethod;
begin
m := TMethod(AMethod);
New(p);
p^.Data := m.Data;
p^.Code := m.Code;
Result := p;
end;
begin
if not Dictionary.ContainsKey(AFileName) then
Dictionary.Add(AFileName, Add(AEvent));
end;
procedure UnRegisterWebPage(const AFileName: string);
var
p: PMethod;
begin
if Dictionary.ContainsKey(AFileName) then
begin
p := Dictionary.Items[AFileName];
Dispose(p);
Dictionary.Remove(AFileName);
end;
end;
function ExecuteWebPage(const AFileName: string; AContext: TIdContext;
ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo): Boolean;
procedure CallEvent(AEvent: TIdHTTPCommandEvent);
begin
if Assigned(Aevent) then
begin
try
AEvent(AContext, ARequestInfo, AResponseInfo);
except
on e: exception do
AResponseInfo.ContentText := AResponseInfo.ContentText +
Format(#13'%s: %s',[e.ClassName, e.Message]);
end;
end;
end;
var
p: PMethod;
begin
Result := Dictionary.ContainsKey(AFileName);
if Result then
begin
p := Dictionary.Items[AFileName];
CallEvent(TIdHTTPCommandEvent(p^));
end;
end;
var
_MimeTypes: TDictionary<string,string>;
_MimeLock : TMultiReadExclusiveWriteSynchronizer;
function GetMimeType(const FileName: string): string;
var
Key: string;
begin
Result := 'text/html';
Key := ExtractFileExt(FileName);
//search in cache first:
_MimeLock.BeginRead;
try
if _MimeTypes.TryGetValue(Key, Result) then
Exit;
finally
_MimeLock.EndRead;
end;
//else search in registry and add to cache
with TRegistry.Create do
try
RootKey := HKEY_CLASSES_ROOT;
if KeyExists(Key) then
begin
OpenKey(Key, False);
Result := ReadString('Content Type');
_MimeLock.BeginWrite;
try
_MimeTypes.AddOrSetValue(Key, Result);
finally
_MimeLock.EndWrite;
end;
CloseKey;
end;
finally
Free;
end;
end;
initialization
Dictionary := TDictionary<string,PMethod>.Create;
_MimeTypes := TDictionary<string,string>.Create;
_MimeLock := TMultiReadExclusiveWriteSynchronizer.Create;
finalization
_MimeLock.BeginWrite;
_MimeLock.Free;
_MimeTypes.Free;
Dictionary.Free;
end.
|
unit Constants;
interface
const
pickaxeType = $0E85;
ingotType = $1BEF;
oneOrePileType = $19B7;
twoOresPileType = $19BA;
threeOresPileType = $19B8;
fourOresPileType = $19B9;
oneSausageType = $09C0;
luteType = $0EB3;
logPileType = $1BDD;
tinkerToolsType = $1EBC;
sawType = $1034;
scrollsType = $0E34;
bottleType = $0F0E;
emptyBottleColor = $0000;
lesserPoisonBottleColor = $0049;
nightshadeType = $0F88;
daggerType = $0F51;
shaftsType = $1BD4;
foldedClothType = $175D;
sewingKitType = $0F9D;
clothBoxType = $1422;
clothBoxColor = $0041;
antidoteClothBoxColor = $009B;
tameHarpType = $0EB2;
tameHarpColor = $0185;
tinkersToolsType = $1EBC;
springsType = $105D;
clockPartsType = $104F;
ceramicColor = $00F2;
starSapphireType = $0F0F;
emeraldType = $0F10;
sapphireType = $0F11;
rubyType = $0F13;
citrineType = $0F15;
amethystType = $0F16;
tourmalineType = $0F18;
diamondType = $0F26;
mapRollType = $14ED;
fishingPoleType = $0DBF;
greenFishType = $09CC;
brownFishType = $09CD;
purpleFishType = $09CE;
yellowFishType = $09CF;
shipContainerType = $3EAE;
rawFishSteakType = $097A;
fishSteakType = $097B;
fryPanType = $097F;
sulfurousAshType = $0F8C;
bloodyBandageType = $0E20;
cleanBandageType = $0E21;
magicArrowScrollsType = $1F32;
shepherdsCrookType = $0E81;
pigType = $00CB;
var
orePileTypes: array of Cardinal;
logPileTypes: array of Cardinal;
gemStoneTypes: array of Cardinal;
fishTypes: array of Cardinal;
treeTileTypes: array of Cardinal;
implementation
initialization
begin
SetLength(orePileTypes, 4);
orePileTypes[0] := oneOrePileType;
orePileTypes[1] := twoOresPileType;
orePileTypes[2] := threeOresPileType;
orePileTypes[3] := fourOresPileType;
SetLength(logPileTypes, 1);
logPileTypes[0] := logPileType;
SetLength(gemStoneTypes, 8);
gemStoneTypes[0] := amethystType;
gemStoneTypes[1] := citrineType;
gemStoneTypes[2] := diamondType;
gemStoneTypes[3] := emeraldType;
gemStoneTypes[4] := rubyType;
gemStoneTypes[5] := sapphireType;
gemStoneTypes[6] := starSapphireType;
gemStoneTypes[7] := tourmalineType;
SetLength(fishTypes, 4);
fishTypes[0] := greenFishType;
fishTypes[1] := brownFishType;
fishTypes[2] := purpleFishType;
fishTypes[3] := yellowFishType;
SetLength(treeTileTypes, 40);
treeTileTypes[0] := 3274;
treeTileTypes[1] := 3275;
treeTileTypes[2] := 3277;
treeTileTypes[3] := 3280;
treeTileTypes[4] := 3283;
treeTileTypes[5] := 3286;
treeTileTypes[6] := 3288;
treeTileTypes[7] := 3290;
treeTileTypes[8] := 3293;
treeTileTypes[9] := 3296;
treeTileTypes[10] := 3299;
treeTileTypes[11] := 3302;
treeTileTypes[12] := 3320;
treeTileTypes[13] := 3323;
treeTileTypes[14] := 3326;
treeTileTypes[15] := 3329;
treeTileTypes[16] := 3393;
treeTileTypes[17] := 3394;
treeTileTypes[18] := 3395;
treeTileTypes[19] := 3396;
treeTileTypes[20] := 3415;
treeTileTypes[21] := 3416;
treeTileTypes[22] := 3417;
treeTileTypes[23] := 3418;
treeTileTypes[24] := 3419;
treeTileTypes[25] := 3438;
treeTileTypes[26] := 3439;
treeTileTypes[27] := 3440;
treeTileTypes[28] := 3441;
treeTileTypes[29] := 3442;
treeTileTypes[30] := 3460;
treeTileTypes[31] := 3461;
treeTileTypes[32] := 3462;
treeTileTypes[33] := 3476;
treeTileTypes[34] := 3478;
treeTileTypes[35] := 3480;
treeTileTypes[36] := 3482;
treeTileTypes[37] := 3484;
treeTileTypes[38] := 3492;
treeTileTypes[39] := 3496;
end;
end.
|
unit tests.generics.dictionary;
{$mode objfpc}
interface
uses
fpcunit, testregistry, Classes, SysUtils, Generics.Defaults, Generics.Collections;
Type
TMySimpleDict = Class(Specialize TDictionary<Integer,String>);
{$IFDEF FPC}
EDictionary = EListError;
TMyPair = specialize TPair<Integer,String>;
{$ENDIF}
{ TTestSimpleDictionary }
TTestSimpleDictionary = Class(TTestCase)
Private
FDict : TMySimpleDict;
FnotifyMessage : String;
FCurrentKeyNotify : Integer;
FCurrentValueNotify : Integer;
FExpectKeys : Array of Integer;
FExpectValues : Array of String;
FExpectValueAction,
FExpectKeyAction: Array of TCollectionNotification;
procedure DoAdd(aCount: Integer; aOffset: Integer=0);
procedure DoAdd2;
Procedure DoneExpectKeys;
Procedure DoneExpectValues;
procedure DoGetValue(aKey: Integer; Match: String; ExceptionClass: TClass=nil);
procedure DoKeyNotify(ASender: TObject; {$ifdef fpc}constref{$else}const{$endif} AItem: Integer; AAction: TCollectionNotification);
procedure DoValueNotify(ASender: TObject; {$ifdef fpc}constref{$else}const{$endif} AItem: String; AAction: TCollectionNotification);
Public
Procedure SetExpectKeys(aMessage : string; AKeys : Array of Integer; AActions : Array of TCollectionNotification; DoReverse : Boolean = False);
Procedure SetExpectValues(aMessage : string; AKeys : Array of String; AActions : Array of TCollectionNotification; DoReverse : Boolean = False);
Procedure SetUp; override;
Procedure TearDown; override;
Property Dict : TMySimpleDict Read FDict;
Published
Procedure TestEmpty;
Procedure TestAdd;
Procedure TestClear;
Procedure TestTryGetValue;
Procedure TestGetValue;
Procedure TestSetValue;
Procedure TestAddDuplicate;
Procedure TestAddOrSet;
Procedure TestContainsKey;
Procedure TestContainsValue;
Procedure TestDelete;
Procedure TestToArray;
procedure TestKeys;
Procedure TestValues;
Procedure TestEnumerator;
Procedure TestNotification;
procedure TestNotificationDelete;
procedure TestValueNotification;
procedure TestValueNotificationDelete;
procedure TestKeyValueNotificationSet;
end;
implementation
{ TTestSimpleDictionary }
procedure TTestSimpleDictionary.SetUp;
begin
inherited SetUp;
FDict:=TMySimpleDict.Create;
FCurrentKeyNotify:=0;
FCurrentValueNotify:=0;
FExpectKeys:=[];
FExpectKeyAction:=[];
FExpectValues:=[];
FExpectValueAction:=[];
end;
procedure TTestSimpleDictionary.TearDown;
begin
// So we don't get clear messages
FDict.OnKeyNotify:=Nil;
FDict.OnValueNotify:=Nil;
FreeAndNil(FDict);
inherited TearDown;
end;
procedure TTestSimpleDictionary.TestEmpty;
begin
AssertNotNull('Have dictionary',Dict);
AssertEquals('empty dictionary',0,Dict.Count);
end;
procedure TTestSimpleDictionary.DoAdd(aCount : Integer; aOffset : Integer=0);
Var
I : Integer;
begin
if aOffset=-1 then
aOffset:=Dict.Count;
For I:=aOffset+1 to aOffset+aCount do
Dict.Add(I,IntToStr(i));
end;
procedure TTestSimpleDictionary.TestAdd;
begin
DoAdd(1);
AssertEquals('Count OK',1,Dict.Count);
AssertTrue('Has added value',Dict.ContainsKey(1));
DoAdd(1,1);
AssertEquals('Count OK',2,Dict.Count);
AssertTrue('Has added value',Dict.ContainsKey(2));
end;
procedure TTestSimpleDictionary.TestClear;
begin
DoAdd(3);
AssertEquals('Count OK',3,Dict.Count);
Dict.Clear;
AssertEquals('Count after clear OK',0,Dict.Count);
end;
procedure TTestSimpleDictionary.TestTryGetValue;
Var
I : integer;
SI,A : string;
begin
DoAdd(3);
For I:=1 to 3 do
begin
SI:=IntToStr(I);
AssertTrue('Have value '+SI,Dict.TryGetValue(I,A));
AssertEquals('Value is correct '+SI,SI,A);
end;
AssertFalse('Have no value 4',Dict.TryGetValue(4,A));
end;
procedure TTestSimpleDictionary.DoGetValue(aKey: Integer; Match: String; ExceptionClass: TClass);
Var
EC : TClass;
A,EM : String;
begin
EC:=Nil;
try
A:=Dict.Items[aKey];
except
On E : Exception do
begin
EC:=E.ClassType;
EM:=E.Message;
end
end;
if ExceptionClass=Nil then
begin
if EC<>Nil then
Fail('Got exception '+EC.ClassName+' with message: '+EM);
AssertEquals('Value is correct for '+IntToStr(aKey),Match,A)
end
else
begin
if EC=Nil then
Fail('Expected exception '+ExceptionClass.ClassName+' but got none');
if EC<>ExceptionClass then
Fail('Expected exception class '+ExceptionClass.ClassName+' but got '+EC.ClassName+' with message '+EM);
end;
end;
procedure TTestSimpleDictionary.DoKeyNotify(ASender: TObject; {$ifdef fpc}constref{$else}const{$endif} AItem: Integer; AAction: TCollectionNotification);
begin
Writeln(FnotifyMessage+' Notification',FCurrentKeyNotify);
AssertSame(FnotifyMessage+' Correct sender', FDict,aSender);
if (FCurrentKeyNotify>=Length(FExpectKeys)) then
Fail(FnotifyMessage+' Too many notificiations');
AssertEquals(FnotifyMessage+' Notification Key no '+IntToStr(FCurrentKeyNotify),FExpectKeys[FCurrentKeyNotify],aItem);
Inc(FCurrentKeyNotify);
end;
procedure TTestSimpleDictionary.DoValueNotify(ASender: TObject; {$ifdef fpc}constref{$else}const{$endif} AItem: String; AAction: TCollectionNotification);
begin
Writeln(FnotifyMessage+' value Notification',FCurrentValueNotify);
AssertSame(FnotifyMessage+' value Correct sender', FDict,aSender);
if (FCurrentValueNotify>=Length(FExpectValues)) then
Fail(FnotifyMessage+' Too many value notificiations');
AssertEquals(FnotifyMessage+' Notification value no '+IntToStr(FCurrentValueNotify),FExpectValues[FCurrentValueNotify],aItem);
Inc(FCurrentValueNotify);
end;
procedure TTestSimpleDictionary.SetExpectKeys(aMessage: string; AKeys: array of Integer;
AActions: array of TCollectionNotification; DoReverse: Boolean = False);
Var
I,L : integer;
begin
FnotifyMessage:=aMessage;
FCurrentKeyNotify:=0;
L:=Length(aKeys);
AssertEquals('SetExpectkeys: Lengths arrays equal',l,Length(aActions));
SetLength(FExpectKeys,L);
SetLength(FExpectKeyAction,L);
Dec(L);
if DoReverse then
For I:=0 to L do
begin
FExpectKeys[L-i]:=AKeys[i];
FExpectKeyAction[L-i]:=AActions[I];
end
else
For I:=0 to L do
begin
FExpectKeys[i]:=AKeys[i];
FExpectKeyAction[i]:=AActions[I];
end;
end;
procedure TTestSimpleDictionary.SetExpectValues(aMessage: string; AKeys: array of String;
AActions: array of TCollectionNotification; DoReverse: Boolean);
Var
I,L : integer;
begin
FnotifyMessage:=aMessage;
FCurrentValueNotify:=0;
L:=Length(aKeys);
AssertEquals('SetExpectValues: Lengths arrays equal',l,Length(aActions));
SetLength(FExpectValues,L);
SetLength(FExpectValueAction,L);
Dec(L);
if DoReverse then
For I:=0 to L do
begin
FExpectValues[L-i]:=AKeys[i];
FExpectValueAction[L-i]:=AActions[I];
end
else
For I:=0 to L do
begin
FExpectValues[i]:=AKeys[i];
FExpectValueAction[i]:=AActions[I];
end;
end;
procedure TTestSimpleDictionary.TestGetValue;
Var
I : integer;
begin
DoAdd(3);
For I:=1 to 3 do
DoGetValue(I,IntToStr(I));
DoGetValue(4,'4',EDictionary);
end;
procedure TTestSimpleDictionary.TestSetValue;
begin
TestGetValue;
Dict.Items[3]:='Six';
DoGetValue(3,'Six');
end;
procedure TTestSimpleDictionary.DoAdd2;
begin
Dict.Add(2,'A new 2');
end;
procedure TTestSimpleDictionary.DoneExpectKeys;
begin
AssertEquals(FnotifyMessage+' Expected number of keys seen',Length(FExpectKeys),FCurrentKeyNotify);
end;
procedure TTestSimpleDictionary.DoneExpectValues;
begin
AssertEquals(FnotifyMessage+' Expected number of values seen',Length(FExpectValues),FCurrentValueNotify);
end;
procedure TTestSimpleDictionary.TestAddDuplicate;
begin
DoAdd(3);
AssertException('Cannot add duplicate',EDictionary,@DoAdd2);
end;
procedure TTestSimpleDictionary.TestAddOrSet;
begin
DoAdd(3);
Dict.AddOrSetValue(2,'a new 2');
DoGetValue(2,'a new 2');
end;
procedure TTestSimpleDictionary.TestContainsKey;
Var
I : Integer;
begin
DoAdd(3);
For I:=1 to 3 do
AssertTrue('Has '+IntToStr(i),Dict.ContainsKey(I));
AssertFalse('Has not 4',Dict.ContainsKey(4));
end;
procedure TTestSimpleDictionary.TestContainsValue;
Var
I : Integer;
begin
DoAdd(3);
For I:=1 to 3 do
AssertTrue('Has '+IntToStr(i),Dict.ContainsValue(IntToStr(i)));
AssertFalse('Has not 4',Dict.ContainsValue('4'));
end;
procedure TTestSimpleDictionary.TestDelete;
begin
DoAdd(3);
Dict.Remove(2);
AssertEquals('Count',2,Dict.Count);
AssertFalse('Has not 2',Dict.ContainsKey(2));
end;
procedure TTestSimpleDictionary.TestToArray;
Var
{$ifdef fpc}
A : specialize TArray<TMyPair>;
{$else}
A : specialize TArray<TMySimpleDict.TMyPair>;
{$endif}
I : Integer;
SI : String;
begin
DoAdd(3);
A:=Dict.ToArray;
AssertEquals('Length Ok',3,Length(A));
For I:=1 to 3 do
begin
SI:=IntToStr(I);
AssertEquals('key '+SI,I,A[i-1].Key);
AssertEquals('Value '+SI,SI,A[i-1].Value);
end;
end;
procedure TTestSimpleDictionary.TestKeys;
Var
A : Array of Integer;
I : Integer;
SI : String;
begin
DoAdd(3);
A:=Dict.Keys.ToArray;
AssertEquals('Length Ok',3,Length(A));
For I:=1 to 3 do
begin
SI:=IntToStr(I);
AssertEquals('key '+SI,I,A[i-1]);
end;
end;
procedure TTestSimpleDictionary.TestValues;
Var
A : Array of String;
I : Integer;
SI : String;
begin
DoAdd(3);
A:=Dict.Values.ToArray;
AssertEquals('Length Ok',3,Length(A));
For I:=1 to 3 do
begin
SI:=IntToStr(I);
AssertEquals('Value '+SI,SI,A[i-1]);
end;
end;
procedure TTestSimpleDictionary.TestEnumerator;
Var
{$ifdef fpc}
A : TMyPair;
{$else}
A : TMySimpleDict.TMyPair;
{$endif}
I : Integer;
SI : String;
begin
DoAdd(3);
I:=1;
For A in Dict do
begin
SI:=IntToStr(I);
AssertEquals('key '+SI,I,A.Key);
AssertEquals('Value '+SI,SI,A.Value);
Inc(I);
end;
end;
procedure TTestSimpleDictionary.TestNotification;
begin
Dict.OnKeyNotify:=@DoKeyNotify;
SetExpectKeys('Add',[1,2,3],[cnAdded,cnAdded,cnAdded]);
DoAdd(3);
DoneExpectKeys;
end;
procedure TTestSimpleDictionary.TestNotificationDelete;
begin
DoAdd(3);
Dict.OnKeyNotify:=@DoKeyNotify;
SetExpectKeys('Clear',[1,2,3],[cnRemoved,cnRemoved,cnRemoved],{$IFDEF FPC}true{$ELSE}False{$endif});
Dict.Clear;
DoneExpectKeys;
end;
procedure TTestSimpleDictionary.TestValueNotification;
begin
Dict.OnValueNotify:=@DoValueNotify;
SetExpectValues('Add',['1','2','3'],[cnAdded,cnAdded,cnAdded]);
DoAdd(3);
DoneExpectValues;
end;
procedure TTestSimpleDictionary.TestValueNotificationDelete;
begin
DoAdd(3);
Dict.OnValueNotify:=@DoValueNotify;
SetExpectValues('Clear',['1','2','3'],[cnRemoved,cnRemoved,cnRemoved],{$IFDEF FPC}true{$ELSE}False{$endif});
Dict.Clear;
DoneExpectValues;
end;
procedure TTestSimpleDictionary.TestKeyValueNotificationSet;
begin
DoAdd(3);
Dict.OnValueNotify:=@DoValueNotify;
Dict.OnKeyNotify:=@DoKeyNotify;
SetExpectValues('Set',['2','Six'],[cnRemoved,cnAdded]);
SetExpectKeys('Set',[],[]);
Dict[2]:='Six';
DoneExpectKeys;
DoneExpectValues;
end;
begin
RegisterTest(TTestSimpleDictionary);
end.
|
unit vg_platform_win;
interface
uses
Windows, CommDlg, Messages, Variants, ActiveX, MMSystem, ShellAPI,
MultiMon, Classes, SysUtils, vg_scene, vg_forms;
type
{$IFDEF FPC}
TvgLongint = DWORD;
{$ELSE}
TvgLongint = Longint;
{$ENDIF}
MySTGMEDIUM = record // for compatible
Tymed : DWord;
Case Integer Of
0 : (HBITMAP : hBitmap; UnkForRelease : Pointer {IUnknown});
1 : (HMETAFILEPICT : THandle );
2 : (HENHMETAFILE : THandle );
3 : (HGLOBAL : hGlobal );
4 : (lpszFileName : POleStr );
5 : (stm : Pointer{IStream} );
6 : (stg : Pointer{IStorage} );
end;
TDropTarget = class(TComponent, IDropTarget)
private
Form: TvgCustomForm;
function GetDataObject: TvgDragObject;
function DragEnter(const dataObj: IDataObject; grfKeyState: TvgLongint;
pt: TPoint; var dwEffect: TvgLongint): HResult; stdcall;
function DragOver(grfKeyState: TvgLongint; pt: TPoint;
var dwEffect: TvgLongint): HResult; stdcall;
function DragLeave: HResult; stdcall;
function Drop(const dataObj: IDataObject; grfKeyState: TvgLongint; pt: TPoint;
var dwEffect: TvgLongint): HResult; stdcall;
end;
TFormatEtcArray = array of TFormatEtc;
TDataObjectInfo = record
FormatEtc: TFormatEtc;
StgMedium: TStgMedium;
OwnedByDataObject: Boolean
end;
TDataObjectInfoArray = array of TDataObjectInfo;
TDropSource = class(TComponent, IDataObject, IDropSource)
private
Data: TvgDragObject;
Formats: TDataObjectInfoArray;
// IDropSource implementation
function QueryContinueDrag(fEscapePressed: bool;
grfKeyState: Longint): HRESULT; stdcall;
function GiveFeedback(dwEffect: Longint): HRESULT; stdcall;
// IDataObject implementation
function GetData(const FormatEtcIn: TFormatEtc;
out Medium: TStgMedium):HRESULT; stdcall;
function GetDataHere(const FormatEtc: TFormatEtc;
out Medium: TStgMedium):HRESULT; stdcall;
function QueryGetData(const FormatEtc: TFormatEtc): HRESULT; stdcall;
function GetCanonicalFormatEtc(const FormatEtc: TFormatEtc;
out FormatEtcout: TFormatEtc): HRESULT; stdcall;
{$IFDEF FPC}
function SetData(const FormatEtc: TFormatEtc; const Medium: TStgMedium;
fRelease: Bool): HRESULT; stdcall;
{$ELSE}
function SetData(const FormatEtc: TFormatEtc; var Medium: TStgMedium;
fRelease: Bool): HRESULT; stdcall;
{$ENDIF}
function EnumFormatEtc(dwDirection: TvgLongint;
out EnumFormatEtc: IEnumFormatEtc): HRESULT; stdcall;
function dAdvise(const FormatEtc: TFormatEtc; advf: TvgLongint;
const advsink: IAdviseSink; out dwConnection: TvgLongint): HRESULT; stdcall;
function dUnadvise(dwConnection: TvgLongint): HRESULT; stdcall;
function EnumdAdvise(out EnumAdvise: IEnumStatData): HRESULT; stdcall;
{ For IDropSourceHelper }
function FindFormatEtc(TestFormatEtc: TFormatEtc): integer;
function EqualFormatEtc(FormatEtc1, FormatEtc2: TFormatEtc): Boolean;
function HGlobalClone(HGlobal: THandle): THandle;
function LoadGlobalBlock(Format: TClipFormat;
var MemoryBlock: Pointer): Boolean;
function SaveGlobalBlock(Format: TClipFormat;
MemoryBlock: Pointer; MemoryBlockSize: integer): Boolean;
function RetrieveOwnedStgMedium(Format: TFormatEtc; var StgMedium: TStgMedium): HRESULT;
function StgMediumIncRef(const InStgMedium: TStgMedium;
var OutStgMedium: TStgMedium; CopyInMedium: Boolean): HRESULT;
function CanonicalIUnknown(TestUnknown: IUnknown): IUnknown;
end;
TvgPlatformWin = class(TvgPlatform)
private
FWindowClass: TWndClassW;
procedure UpdateLayer(AForm: TvgCustomForm);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
{ App }
procedure Run; override;
procedure Terminate; override;
function HandleMessage: boolean; override;
procedure WaitMessage; override;
{ Timer }
function CreateTimer(Interval: integer; TimerFunc: TvgTimerProc): THandle; override;
function DestroyTimer(Timer: THandle): boolean; override;
function GetTick: single; override;
{ Window }
function CreateWindow(AForm: TvgCustomForm): THandle; override;
procedure DestroyWindow(AForm: TvgCustomForm); override;
procedure ReleaseWindow(AForm: TvgCustomForm); override;
procedure ShowWindow(AForm: TvgCustomForm); override;
procedure HideWindow(AForm: TvgCustomForm); override;
function ShowWindowModal(AForm: TvgCustomForm): TModalResult; override;
procedure InvalidateWindowRect(AForm: TvgCustomForm; R: TvgRect); override;
procedure SetWindowRect(AForm: TvgCustomForm; ARect: TvgRect); override;
function GetWindowRect(AForm: TvgCustomForm): TvgRect; override;
function GetClientSize(AForm: TvgCustomForm): TvgPoint; override;
procedure SetWindowCaption(AForm: TvgCustomForm; ACaption: WideString); override;
procedure SetCapture(AForm: TvgCustomForm); override;
procedure ReleaseCapture(AForm: TvgCustomForm); override;
function ClientToScreen(AForm: TvgCustomForm; const Point: TvgPoint): TvgPoint; override;
function ScreenToClient(AForm: TvgCustomForm; const Point: TvgPoint): TvgPoint; override;
{ Drag and Drop }
procedure BeginDragDrop(AForm: TvgCustomForm; const Data: TvgDragObject; ABitmap: TvgBitmap); override;
{ Clipboard }
procedure SetClipboard(Value: Variant); override;
function GetClipboard: Variant; override;
{ Mouse }
function GetMousePos: TvgPoint; override;
{ Screen }
function GetScreenSize: TvgPoint; override;
{ International }
function GetCurrentLangID: string; override;
{ Dialogs }
function DialogOpenFiles(var FileName: WideString; AInitDir: WideString; AllowMulti: boolean): boolean; override;
end;
implementation
uses
vgPtrList,
vgObjectList
;
const
WM_ADDUPDATERECT = WM_USER + 123;
WM_RELEASEFORM = WM_USER + 125;
var
WindowAtom: TAtom;
WindowAtomString: string;
DropAtom: TAtom;
DropAtomString: string;
CF_VGOBJECT: Longint;
NoStaysOpenList: TvgObjectList;
function HBmpFromBitmap(Bitmap: TvgBitmap): THandle;
var
BitmapInfo: TBitmapInfo;
BitmapHandle: cardinal;
BitmapBits: Pointer;
begin
with BitmapInfo.bmiHeader do
begin
biSize := SizeOf(TBitmapInfoHeader);
biPlanes := 1;
biBitCount := 32;
biCompression := BI_RGB;
biWidth := Bitmap.Width;
if biWidth <= 0 then biWidth := 1;
biHeight := -Bitmap.Height;
if biHeight >= 0 then biHeight := -1;
end;
Result := CreateDIBSection(0, BitmapInfo, DIB_RGB_COLORS, Pointer(BitmapBits), 0, 0);
if BitmapBits <> nil then
begin
Move(Bitmap.StartLine^, BitmapBits^, Bitmap.Width * Bitmap.Height * 4);
end;
end;
{ TvgPlatformWin }
constructor TvgPlatformWin.Create;
begin
inherited;
WindowAtomString := Format('VPF%.8X',[GetCurrentProcessID]);
WindowAtom := GlobalAddAtom(PChar(WindowAtomString));
DropAtomString := Format('VPFDROP%.8X',[GetCurrentProcessID]);
DropAtom := GlobalAddAtom(PChar(DropAtomString));
CF_VGOBJECT := RegisterClipBoardFormat(PChar('WindowAtomString'));
NoStaysOpenList := TvgObjectList.Create;
Application := TvgApplication.Create(nil);
end;
destructor TvgPlatformWin.Destroy;
begin
FreeAndNil(Application);
FreeAndNil(NoStaysOpenList);
inherited;
end;
{ App =========================================================================}
procedure TvgPlatformWin.Run;
begin
Application.RealCreateForms;
repeat
try
Application.HandleMessage;
except
Application.HandleException(Self);
end;
until Application.Terminated;
end;
procedure TvgPlatformWin.Terminate;
begin
PostQuitMessage(0);
end;
function TvgPlatformWin.HandleMessage: boolean;
var
Msg: TMsg;
begin
Result := false;
if PeekMessage(Msg, 0, 0, 0, PM_REMOVE) then
begin
Result := true;
if Msg.Message <> WM_QUIT then
begin
TranslateMessage(Msg);
DispatchMessage(Msg);
end
else
Application.Terminated := true;
end;
end;
procedure TvgPlatformWin.WaitMessage;
begin
Windows.WaitMessage;
end;
{ Timer =======================================================================}
type
PWin32TimerInfo = ^TWin32Timerinfo;
TWin32TimerInfo = record
TimerID: UINT; // the windows timer ID for this timer
TimerFunc: TvgTimerProc; // owner function to handle timer
end;
var
FTimerData : TvgPtrList; // list of PWin32Timerinfo
procedure TimerCallBackProc(window_hwnd : hwnd; msg : Longint; idEvent: UINT; dwTime: Longint); stdcall;
Var
TimerInfo: PWin32TimerInfo;
n: Integer;
begin
n := FTimerData.Count;
while (n > 0) do
begin
dec(n);
TimerInfo := FTimerData[n];
if TimerInfo^.TimerID = idEvent then
begin
TimerInfo^.TimerFunc;
break;
end;
end;
end;
function TvgPlatformWin.CreateTimer(Interval: integer;
TimerFunc: TvgTimerProc): THandle;
var
TimerInfo: PWin32TimerInfo;
begin
Result := 0;
if (Interval > 0) and (Assigned(TimerFunc)) then
begin
New(TimerInfo);
TimerInfo^.TimerFunc := TimerFunc;
TimerInfo^.TimerID := Windows.SetTimer(0, 0, Interval, @TimerCallBackProc);
if TimerInfo^.TimerID=0 then
dispose(TimerInfo)
else
begin
if FTimerData = nil then
FTimerData := TvgPtrList.Create;
FTimerData.Add(TimerInfo);
Result := TimerInfo^.TimerID;
end;
end;
end;
function TvgPlatformWin.DestroyTimer(Timer: THandle): boolean;
var
n : integer;
TimerInfo : PWin32Timerinfo;
begin
Result:= false;
if FTimerData = nil then Exit;
n := FTimerData.Count;
while (n > 0) do
begin
dec(n);
TimerInfo := FTimerData[n];
if (TimerInfo^.TimerID = UINT(Timer)) then
begin
Result := Boolean(Windows.KillTimer(0, UINT(Timer)));
FTimerData.Delete(n);
Dispose(TimerInfo);
end;
end;
end;
function TvgPlatformWin.GetTick: single;
begin
Result := timeGetTime / 1000;
end;
{ Window ======================================================================}
type
PRgnRects = ^TRgnRects;
TRgnRects = array [0..0] of TRect;
type
PBlendFunction = ^TBlendFunction;
_BLENDFUNCTION = packed record
BlendOp: BYTE;
BlendFlags: BYTE;
SourceConstantAlpha: BYTE;
AlphaFormat: BYTE;
end;
TBlendFunction = _BLENDFUNCTION;
BLENDFUNCTION = _BLENDFUNCTION;
const
WS_EX_LAYERED = $00080000;
LWA_COLORKEY = $00000001;
LWA_ALPHA = $00000002;
ULW_COLORKEY = $00000001;
ULW_ALPHA = $00000002;
ULW_OPAQUE = $00000004;
var
UpdateLayeredWindow: function (hWnd: HWND; hdcDst: HDC; pptDst: PPOINT;
psize: PSIZE; hdcSrc: HDC; pptSrc: PPOINT; crKey: COLORREF;
pblend: PBlendFunction; dwFlags: Longint): BOOL; stdcall;
User32Lib: THandle;
function FindWindow(Handle: HWnd): TvgCustomForm;
begin
Result := nil;
if (Handle <> 0) then
begin
if GlobalFindAtom(PChar(WindowAtomString)) = WindowAtom then
Result := Pointer(GetProp(Handle, MakeIntAtom(WindowAtom)))
else
Result := nil;
end;
end;
function FindDropTarget(Handle: HWnd): TDropTarget;
begin
Result := nil;
if (Handle <> 0) then
begin
if GlobalFindAtom(PChar(DropAtomString)) = DropAtom then
Result := Pointer(GetProp(Handle, MakeIntAtom(DropAtom)))
else
Result := nil;
end;
end;
function KeysToShiftState(Keys: Word): TShiftState;
begin
Result := [];
if Keys and MK_SHIFT <> 0 then Include(Result, ssShift);
if Keys and MK_CONTROL <> 0 then Include(Result, ssCtrl);
if Keys and MK_LBUTTON <> 0 then Include(Result, ssLeft);
if Keys and MK_RBUTTON <> 0 then Include(Result, ssRight);
if Keys and MK_MBUTTON <> 0 then Include(Result, ssMiddle);
if GetKeyState(VK_MENU) < 0 then Include(Result, ssAlt);
end;
function KeyDataToShiftState(KeyData: Longint): TShiftState;
const
AltMask = $20000000;
{$IFDEF LINUX}
CtrlMask = $10000000;
ShiftMask = $08000000;
{$ENDIF}
begin
Result := [];
if GetKeyState(VK_SHIFT) < 0 then Include(Result, ssShift);
if GetKeyState(VK_CONTROL) < 0 then Include(Result, ssCtrl);
if KeyData and AltMask <> 0 then Include(Result, ssAlt);
{$IFDEF LINUX}
if KeyData and CtrlMask <> 0 then Include(Result, ssCtrl);
if KeyData and ShiftMask <> 0 then Include(Result, ssShift);
{$ENDIF}
end;
function WMPaint(hwnd: HWND; uMsg: UINT; wParam: WPARAM; lParam: LPARAM): LRESULT; stdcall;
var
i, rgnStatus: integer;
rgn: HRgn;
rgnSize: integer;
rgnData: PRgnData;
R: windows.TRect;
Wnd: TvgCustomForm;
UpdateRects: array of TvgRect;
PS: TPaintStruct;
begin
Wnd := FindWindow(hwnd);
if Wnd = nil then
begin
Result := DefWindowProcW(hwnd, uMsg, wParam, lParam); // Default result if nothing happens
Exit;
end;
rgn := CreateRectRgn(0, 0, 1, 1);
rgnStatus := GetUpdateRgn(Wnd.Handle, rgn, false);
if (rgnStatus = 2) or (rgnStatus = 3) then
begin
rgnSize := GetRegionData(rgn, $FFFF, nil);
if rgnSize > 0 then
begin
l3System.GetLocalMem(rgnData, rgnSize);
rgnSize := GetRegionData(rgn, rgnSize, rgnData);
if rgnSize = rgnSize then
begin
SetLength(UpdateRects, rgnData.rdh.nCount);
for i := 0 to rgnData.rdh.nCount - 1 do
begin
R := PRgnRects(@rgnData.buffer[0])[i];
with R do
UpdateRects[i] := vgRect(left, top, right, bottom);
end;
end;
l3System.FreeLocalMem(rgnData, rgnSize);
Wnd.Context := BeginPaint(Wnd.Handle, PS);
Wnd.PaintRects(UpdateRects);
Wnd.Context := 0;
EndPaint(Wnd.Handle, PS);
Result := DefWindowProcW(hwnd, uMsg, wParam, lParam); // Default result if nothing happens
end
else
begin
Result := DefWindowProcW(hwnd, uMsg, wParam, lParam); // Default result if nothing happens
end;
end
else
begin
Result := DefWindowProcW(hwnd, uMsg, wParam, lParam); // Default result if nothing happens
end;
DeleteObject(rgn);
end;
function WndProc(hwnd: HWND; uMsg: UINT; wParam: WPARAM; lParam: LPARAM): LRESULT; stdcall;
var
UpdateRects: array of TvgRect;
Wnd: TvgCustomForm;
procedure ProcessUpdateMessages;
var
Msg: TMsg;
begin
SetLength(UpdateRects, 1);
UpdateRects[0] := vgRect(TSmallPoint(cardinal(wParam)).X, TSmallPoint(cardinal(wParam)).Y,
TSmallPoint(cardinal(lParam)).X, TSmallPoint(cardinal(lParam)).Y);
while PeekMessage(Msg, hwnd, WM_ADDUPDATERECT, WM_ADDUPDATERECT, PM_REMOVE) do
begin
if Msg.message = WM_QUIT then
begin
{ Repost WM_QUIT messages }
PostQuitMessage(Msg.WParam);
Break;
end;
SetLength(UpdateRects, Length(UpdateRects) + 1);
UpdateRects[High(UpdateRects)] := vgRect(TSmallPoint(cardinal(Msg.wParam)).X, TSmallPoint(cardinal(Msg.wParam)).Y,
TSmallPoint(cardinal(Msg.lParam)).X, TSmallPoint(cardinal(Msg.lParam)).Y);
end;
end;
procedure CloseNoStaysOpen;
var
i: integer;
begin
if not Wnd.StaysOpen then Exit;
if NoStaysOpenList.Count > 0 then
begin
for i := NoStaysOpenList.Count - 1 downto 0 do
TvgCustomForm(NoStaysOpenList[i]).Close;
end;
end;
var
PS: TPaintStruct;
R: TRect;
P: TPoint;
H: boolean;
Key: Word;
Ch: WideChar;
tme: TTRACKMOUSEEVENT;
begin
Wnd := FindWindow(hwnd);
if (Wnd <> nil) then
begin
case uMsg of
WM_ACTIVATE:
begin
if not (fsRecreating in Wnd.FormState) then
begin
if wParam > 0 then
Wnd.Activate
else
begin
Wnd.Deactivate;
CloseNoStaysOpen;
end;
end;
Result := 0;
end;
WM_MOUSEACTIVATE:
begin
if not (fsRecreating in Wnd.FormState) then
begin
if not Wnd.ShowActivated then
Result := MA_NOACTIVATE
else
Result := DefWindowProcW(hwnd, uMsg, wParam, lParam); // Default result if nothing happens
end;
end;
WM_ERASEBKGND:
begin
Result := 1;
end;
WM_PAINT:
begin
Result := WMPaint(hwnd, uMsg, wParam, lParam);
end;
WM_ADDUPDATERECT:
begin
ProcessUpdateMessages;
Wnd.PaintRects(UpdateRects);
TvgPlatformWin(Platform).UpdateLayer(Wnd);
end;
WM_WINDOWPOSCHANGED:
begin
Result := DefWindowProcW(hwnd, uMsg, wParam, lParam); // Default result if nothing happens
GetWindowRect(hWnd, R);
Wnd.SetBounds(R.Left, R.Top, R.Right - R.Left, R.Bottom - R.Top);
end;
WM_CLOSE:
begin
Wnd.Close;
end;
WM_LBUTTONDOWN:
begin
CloseNoStaysOpen;
GetCursorPos(P);
ScreenToClient(Wnd.Handle, P);
Wnd.MouseDown(mbLeft, KeysToShiftState(wParam), P.X, P.Y);
end;
WM_LBUTTONUP:
begin
GetCursorPos(P);
ScreenToClient(Wnd.Handle, P);
Wnd.MouseUp(mbLeft, KeysToShiftState(wParam), P.X, P.Y);
end;
WM_RBUTTONDOWN:
begin
CloseNoStaysOpen;
GetCursorPos(P);
ScreenToClient(Wnd.Handle, P);
Wnd.MouseDown(mbRight, KeysToShiftState(wParam), P.X, P.Y);
end;
WM_RBUTTONUP:
begin
GetCursorPos(P);
ScreenToClient(Wnd.Handle, P);
Wnd.MouseUp(mbRight, KeysToShiftState(wParam), P.X, P.Y);
end;
WM_MOUSEMOVE:
begin
GetCursorPos(P);
ScreenToClient(Wnd.Handle, P);
Wnd.MouseMove(KeysToShiftState(wParam), P.X, P.Y);
tme.cbSize := SizeOf(tme);
tme.hwndTrack := Result;
tme.dwFlags := TME_LEAVE;
tme.dwHoverTime := 1;
TrackMouseEvent(tme);
end;
WM_MOUSELEAVE:
begin
Wnd.MouseLeave;
end;
WM_MOUSEWHEEL:
begin
H := false;
Wnd.MouseWheel(KeysToShiftState(wParam), TSmallPoint(cardinal(wParam)).Y, H);
Result := Integer(H = true);
end;
WM_GETDLGCODE:
begin
Result := DLGC_WANTTAB or dlgc_WantArrows or DLGC_WANTCHARS;
end;
WM_CHAR:
begin
Ch := WideChar(wParam);
Key := 0;
Wnd.KeyDown(Key, Ch, KeyDataToShiftState(lParam));
Wnd.KeyUp(Key, Ch, KeyDataToShiftState(lParam));
Result := 0;
end;
WM_KEYDOWN:
begin
Ch := #0;
Key := wParam;
Wnd.KeyDown(Key, Ch, KeyDataToShiftState(lParam));
Result := 0;
end;
WM_KEYUP:
begin
Ch := #0;
Key := wParam;
Wnd.KeyUp(Key, Ch, KeyDataToShiftState(lParam));
Result := 0;
end;
WM_RELEASEFORM:
begin
FreeAndNil(Wnd);
end;
else
Result := DefWindowProcW(hwnd, uMsg, wParam, lParam); // Default result if nothing happens
end
end
else
Result := DefWindowProcW(hwnd, uMsg, wParam, lParam); // Default result if nothing happens
end;
function TvgPlatformWin.CreateWindow(AForm: TvgCustomForm): THandle;
var
DropTarget: TDropTarget;
Style, ExStyle: cardinal;
begin
FillChar(FWindowClass, SizeOf(FWindowClass), 0);
FWindowClass.style := CS_OWNDC;
FWindowClass.lpfnWndProc := @WndProc;
FWindowClass.cbClsExtra := 0;
FWindowClass.cbWndExtra := 0;
FWindowClass.hInstance := hInstance;
FWindowClass.hIcon := LoadIcon(hInstance, PChar('DEFAULTICON'));
FWindowClass.hCursor := LoadCursor(0, IDC_ARROW);
FWindowClass.hbrBackground := GetStockObject(NULL_BRUSH);
FWindowClass.lpszMenuName := nil;
FWindowClass.lpszClassName := PWideChar(WideString('VPF' + AForm.ClassName));
Windows.RegisterClassW(FWindowClass);
Style := 0;
ExStyle := 0;
if AForm.Transparency then
begin
Style := Style or WS_POPUP;
ExStyle := ExStyle or WS_EX_LAYERED;
if (Application.MainForm <> nil) and (AForm <> Application.MainForm) then
ExStyle := ExStyle or WS_EX_TOOLWINDOW; // disable taskbar
end
else
begin
case AForm.BorderStyle of
bsNone:
begin
Style := Style or WS_POPUP or WS_SYSMENU;
ExStyle := ExStyle {or WS_EX_TOOLWINDOW}; // disable taskbar
end;
bsSingle, bsToolWindow:
Style := Style or (WS_CAPTION or WS_BORDER);
bsSizeable, bsSizeToolWin:
Style := Style or (WS_CAPTION or WS_THICKFRAME);
end;
if AForm.BorderStyle in [bsToolWindow, bsSizeToolWin] then
ExStyle := ExStyle or WS_EX_TOOLWINDOW;
if AForm.BorderStyle <> bsNone then
begin
if biMinimize in AForm.BorderIcons then Style := Style or WS_MINIMIZEBOX;
if biMaximize in AForm.BorderIcons then Style := Style or WS_MAXIMIZEBOX;
if biSystemMenu in AForm.BorderIcons then Style := Style or WS_SYSMENU;
end;
end;
{ if not AForm.ShowActivated then
ExStyle := ExStyle or WS_EX_NOACTIVATE;}
Result := Windows.CreateWindowExW(ExStyle,
FWindowClass.lpszClassName, PWideChar(AForm.Caption),
Style,
round(AForm.Left), round(AForm.Top),
round(AForm.Width), round(AForm.Height),
GetDesktopWindow,
0, hInstance, nil);
SetProp(Result, MakeIntAtom(WindowAtom), THandle(AForm));
DropTarget := TDropTarget.Create(nil);
DropTarget.Form := AForm;
SetProp(Result, MakeIntAtom(DropAtom), THandle(DropTarget));
RegisterDragDrop(Result, DropTarget);
if AForm.Transparency then
UpdateLayer(AForm);
end;
procedure TvgPlatformWin.DestroyWindow(AForm: TvgCustomForm);
var
DropTarget: TDropTarget;
begin
HideWindow(AForm);
RevokeDragDrop(AForm.Handle);
DropTarget := FindDropTarget(AForm.Handle);
if DropTarget <> nil then
FreeAndNil(DropTarget);
Windows.DestroyWindow(AForm.Handle);
end;
procedure TvgPlatformWin.ReleaseWindow(AForm: TvgCustomForm);
begin
PostMessage(AForm.Handle, WM_RELEASEFORM, 0, 0);
end;
procedure TvgPlatformWin.InvalidateWindowRect(AForm: TvgCustomForm; R: TvgRect);
var
WR: TRect;
Wnd: TvgCustomForm;
begin
R := vgRect(Trunc(R.Left), Trunc(R.Top), Trunc(R.Right) + 1, Trunc(R.Bottom) + 1);
if not vgIntersectRect(R, vgRect(0, 0, AForm.Width, AForm.Height)) then Exit;
Wnd := FindWindow(AForm.Handle);
if Wnd.Transparency then
begin
PostMessage(AForm.Handle, WM_ADDUPDATERECT, Integer(SmallPoint(round(R.Left), round(R.Top))), Integer(SmallPoint(round(R.Right), round(R.Bottom))));
end
else
begin
WR := Rect(Trunc(R.Left), Trunc(R.Top), Trunc(R.Right), Trunc(R.Bottom));
Windows.InvalidateRect(AForm.Handle, @WR, false);
end;
end;
procedure TvgPlatformWin.UpdateLayer(AForm: TvgCustomForm);
var
Blend: TBLENDFUNCTION;
Origin, Size, BitmapOrigin: Windows.TPoint;
i, j: integer;
SaveBits: PvgColorRecArray;
begin
if AForm.Canvas = nil then Exit;
if AForm.Canvas.Handle = 0 then Exit;
Origin := Point(AForm.Left, AForm.Top);
Size := Point(AForm.Width, AForm.Height);
{ Update }
with Blend do
begin
BlendOp := AC_SRC_OVER;
AlphaFormat := $01; //AC_SRC_ALPHA;
BlendFlags := 0;
SourceConstantAlpha := $FF;
end;
BitmapOrigin := Point(0, 0);
UpdateLayeredWindow(AForm.Handle, 0, @Origin, @Size, AForm.Canvas.Handle, @BitmapOrigin, $00000000, @Blend, ULW_ALPHA);
end;
function TvgPlatformWin.GetWindowRect(AForm: TvgCustomForm): TvgRect;
var
R: TRect;
begin
Windows.GetWindowRect(AForm.Handle, R);
with R do
Result := vgRect(Left, Top, Right, Bottom);
end;
procedure TvgPlatformWin.SetWindowRect(AForm: TvgCustomForm; ARect: TvgRect);
begin
with ARect do
if not AForm.ShowActivated then
SetWindowPos(AForm.Handle, 0, round(Left), round(Top), round(Right - Left), round(Bottom - Top), SWP_NOACTIVATE)
else
SetWindowPos(AForm.Handle, 0, round(Left), round(Top), round(Right - Left), round(Bottom - Top), 0)
end;
procedure TvgPlatformWin.SetWindowCaption(AForm: TvgCustomForm;
ACaption: WideString);
begin
SetWindowTextW(AForm.Handle, PWideChar(ACaption));
end;
procedure TvgPlatformWin.ReleaseCapture(AForm: TvgCustomForm);
begin
Windows.ReleaseCapture;
end;
procedure TvgPlatformWin.SetCapture(AForm: TvgCustomForm);
begin
Windows.SetCapture(AForm.Handle);
end;
function TvgPlatformWin.GetClientSize(AForm: TvgCustomForm): TvgPoint;
var
R: TRect;
begin
GetClientRect(AForm.Handle, R);
Result := vgPoint(R.Right - R.Left, R.Bottom - R.Top);
end;
procedure TvgPlatformWin.HideWindow(AForm: TvgCustomForm);
begin
if NoStaysOpenList.IndexOf(AForm) >= 0 then
NoStaysOpenList.Remove(AForm);
Windows.ShowWindow(AForm.Handle, SW_HIDE);
end;
procedure TvgPlatformWin.ShowWindow(AForm: TvgCustomForm);
begin
if not AForm.ShowActivated then
Windows.ShowWindow(AForm.Handle, SW_SHOWNOACTIVATE)
else
Windows.ShowWindow(AForm.Handle, SW_SHOW);
if AForm.Transparency then
UpdateLayer(AForm);
if AForm.TopMost then
SetWindowPos(AForm.Handle, HWND_TOPMOST, 0, 0, 0, 0, SWP_FRAMECHANGED or SWP_NOACTIVATE or SWP_NOMOVE or SWP_NOSIZE);
if not AForm.StaysOpen and (NoStaysOpenList.IndexOf(AForm) < 0) then
NoStaysOpenList.Add(AForm);
end;
type
PTaskWindow = ^TTaskWindow;
TTaskWindow = record
Next: PTaskWindow;
Window: HWnd;
end;
var
TaskActiveWindow: HWnd = 0;
TaskFirstWindow: HWnd = 0;
TaskFirstTopMost: HWnd = 0;
TaskWindowList: PTaskWindow = nil;
function DoDisableWindow(Window: HWnd; Data: Longint): Bool; stdcall;
var
P: PTaskWindow;
begin
if (Window <> TaskActiveWindow) and IsWindowVisible(Window) and
IsWindowEnabled(Window) then
begin
New(P);
P^.Next := TaskWindowList;
P^.Window := Window;
TaskWindowList := P;
EnableWindow(Window, False);
end;
Result := True;
end;
procedure EnableTaskWindows(WindowList: Pointer);
var
P: PTaskWindow;
begin
while WindowList <> nil do
begin
P := WindowList;
if IsWindow(P^.Window) then EnableWindow(P^.Window, True);
WindowList := P^.Next;
Dispose(P);
end;
end;
function DisableTaskWindows(ActiveWindow: HWnd): Pointer;
var
SaveActiveWindow: HWND;
SaveWindowList: Pointer;
begin
Result := nil;
SaveActiveWindow := TaskActiveWindow;
SaveWindowList := TaskWindowList;
TaskActiveWindow := ActiveWindow;
TaskWindowList := nil;
try
try
EnumThreadWindows(GetCurrentThreadID, @DoDisableWindow, 0);
Result := TaskWindowList;
except
EnableTaskWindows(TaskWindowList);
raise;
end;
finally
TaskWindowList := SaveWindowList;
TaskActiveWindow := SaveActiveWindow;
end;
end;
function TvgPlatformWin.ShowWindowModal(AForm: TvgCustomForm): TModalResult;
var
WindowList: Pointer;
ActiveWindow: HWnd;
begin
if GetCapture <> 0 then SendMessage(GetCapture, WM_CANCELMODE, 0, 0);
Windows.ReleaseCapture;
ActiveWindow := GetActiveWindow;
WindowList := DisableTaskWindows(0);
AForm.Show;
AForm.ModalResult := mrNone;
repeat
Application.HandleMessage;
if Application.Terminated then
AForm.ModalResult := mrCancel
else
if AForm.ModalResult <> mrNone then
AForm.CloseModal;
until AForm.ModalResult <> mrNone;
AForm.Hide;
EnableTaskWindows(WindowList);
if ActiveWindow <> 0 then SetActiveWindow(ActiveWindow);
Result := AForm.ModalResult;
end;
function TvgPlatformWin.ClientToScreen(AForm: TvgCustomForm; const Point: TvgPoint): TvgPoint;
var
P: TPoint;
begin
P := Classes.Point(round(Point.X), round(Point.Y));
Windows.ClientToScreen(AForm.Handle, P);
Result := vgPoint(P.X, P.Y);
end;
function TvgPlatformWin.ScreenToClient(AForm: TvgCustomForm; const Point: TvgPoint): TvgPoint;
var
P: TPoint;
begin
P := Classes.Point(round(Point.X), round(Point.Y));
Windows.ScreenToClient(AForm.Handle, P);
Result := vgPoint(P.X, P.Y);
end;
{ Drag and Drop ===============================================================}
const
IID_IDropTargetHelper: TGUID = (
D1:$4657278b; D2:$411b; D3:$11d2; D4:($83,$9a,$00,$c0,$4f,$d9,$18,$d0));
SID_IDropTargetHelper = '{4657278B-411B-11d2-839A-00C04FD918D0}';
CLSID_DragDropHelper: TGUID = (
D1:$4657278a; D2:$411b; D3:$11d2; D4:($83,$9a,$00,$c0,$4f,$d9,$18,$d0));
type
{_$EXTERNALSYM IDropTargetHelper}
IDropTargetHelper = interface(IUnknown)
[SID_IDropTargetHelper]
function DragEnter(hwndTarget: HWND; const DataObj: IDataObject;
var pt: TPoint; dwEffect: Longint): HResult; stdcall;
function DragLeave: HResult; stdcall;
function DragOver(var pt: TPoint; dwEffect: Longint): HResult; stdcall;
function Drop(const DataObj: IDataObject; var pt: TPoint;
dwEffect: Longint): HResult; stdcall;
function Show(Show: BOOL): HResult; stdcall;
end;
var
FDropTargetHelper: IDropTargetHelper;
FDataObj: IDataObject;
function TDropTarget.GetDataObject: TvgDragObject;
var
formatEtc: TFORMATETC;
stgMedium: TSTGMEDIUM;
str: wideString;
drop: HDrop;
i, numFiles: integer;
buffer : array[0..MAX_PATH] of widechar;
begin
FillChar(Result, SizeOf(Result), 0);
if not Assigned(FDataObj) then Exit;
// get file name first
with formatEtc do
begin
cfFormat := CF_HDROP;
ptd := nil;
dwAspect := DVASPECT_CONTENT;
lindex := -1;
tymed := TYMED_HGLOBAL;
end;
// get VG
formatEtc.cfFormat := CF_VGOBJECT;
if FDataObj.GetData(formatEtc, stgMedium) = S_OK then
begin
Result := TDropSource(stgMedium.hGlobal).Data;
Exit;
end;
// files
str := '';
formatEtc.cfFormat := CF_HDROP;
if FDataObj.GetData(formatEtc, stgMedium) = S_OK then
begin
try
{Lock the global memory handle to get a pointer to the data}
drop := HDrop(GlobalLock(stgMedium.hGlobal));
{ Replace Text }
numFiles := DragQueryFile(drop, $FFFFFFFF, nil, 0);
SetLength(Result.Files, numFiles);
for i := 0 to numFiles - 1 do
begin
DragQueryFileW(drop, i, @buffer, sizeof(buffer));
Result.Files[i] := buffer;
if i = 0 then
Result.Data := Result.Files[0];
end;
finally
{Finished with the pointer}
GlobalUnlock(stgMedium.hGlobal);
{Free the memory}
ReleaseStgMedium({$IFDEF FPC}@{$ENDIF}stgMedium);
end;
Exit;
end;
// get text
formatEtc.cfFormat := CF_UNICODETEXT;
if FDataObj.GetData(formatEtc, stgMedium) = S_OK then
begin
try
{Lock the global memory handle to get a pointer to the data}
str := PWideChar(GlobalLock(stgMedium.hGlobal));
Result.Data := str;
finally
{Finished with the pointer}
GlobalUnlock(stgMedium.hGlobal);
{Free the memory}
ReleaseStgMedium({$IFDEF FPC}@{$ENDIF}stgMedium);
end;
Exit;
end;
end;
function TDropTarget.DragEnter(const dataObj: IDataObject; grfKeyState: TvgLongint;
pt: TPoint; var dwEffect: TvgLongint): HResult;
begin
try
FDataObj := dataObj;
Result := S_OK;
dwEffect := DROPEFFECT_NONE;
if (Succeeded(CoCreateInstance(CLSID_DragDropHelper, nil, CLSCTX_INPROC_SERVER,
IDropTargetHelper, FDropTargetHelper))) and
(FDropTargetHelper <> nil) then
begin
if (Failed(FDropTargetHelper.DragEnter(Form.Handle, DataObj, pt, dwEffect))) then
FDropTargetHelper := nil;
end;
except
dwEffect := DROPEFFECT_NONE;
Result := E_UNEXPECTED;
end;
end;
function TDropTarget.DragOver(grfKeyState: TvgLongint; pt: TPoint;
var dwEffect: TvgLongint): HResult;
var
P: TvgPoint;
Accept: boolean;
begin
try
dwEffect := DROPEFFECT_NONE;
Result := S_OK;
Windows.ScreenToClient(Form.Handle, pt);
P := vgPoint(pt.X, pt.Y);
Accept := false;
Form.DragOver(GetDataObject, P, Accept);
if Accept then
dwEffect := DROPEFFECT_LINK;
if FDropTargetHelper <> nil then
FDropTargetHelper.DragOver(pt, dwEffect);
except
dwEffect := DROPEFFECT_NONE;
Result := E_UNEXPECTED;
end;
end;
function TDropTarget.DragLeave: HResult;
begin
Form.DragLeave;
if (FDropTargetHelper <> nil) then
FDropTargetHelper.DragLeave;
FDropTargetHelper := nil;
FDataObj := nil;
Result := S_OK;
end;
function TDropTarget.Drop(const dataObj: IDataObject; grfKeyState: TvgLongint; pt: TPoint;
var dwEffect: TvgLongint): HResult;
var
P: TvgPoint;
begin
try
if (dataObj = nil) then Exit;
Windows.ScreenToClient(Form.Handle, pt);
P := vgPoint(pt.X, pt.Y);
Form.DragDrop(GetDataObject, P);
if (FDropTargetHelper <> nil) then
FDropTargetHelper.Drop(DataObj, pt, dwEffect)
finally
FDataObj := nil;
FDropTargetHelper := nil;
end;
end;
{ TDropSource }
{ IDropSource }
function TDropSource.QueryContinueDrag(fEscapePressed: bool;
grfKeyState: Integer): HRESULT;
var
ContinueDrop: Boolean;
begin
if fEscapePressed then
Result := DRAGDROP_S_CANCEL
else
if (grfKeyState and (MK_LBUTTON or MK_RBUTTON) = 0) then
begin
ContinueDrop := true;
if ContinueDrop then
Result := DRAGDROP_S_DROP
else
Result := DRAGDROP_S_CANCEL;
end
else
Result := S_OK;
end;
function TDropSource.GiveFeedback(dwEffect: Integer): HRESULT;
begin
Result := S_OK; //DRAGDROP_S_USEDEFAULTCURSORS;
end;
{ IDataObject }
function TDropSource.dAdvise(const FormatEtc: TFormatEtc; advf: TvgLongint;
const advsink: IAdviseSink; out dwConnection: TvgLongint): HRESULT;
begin
Result := OLE_E_ADVISENOTSUPPORTED;
end;
function TDropSource.dUnadvise(dwConnection: TvgLongint): HRESULT;
begin
Result := OLE_E_ADVISENOTSUPPORTED;
end;
function TDropSource.EnumdAdvise(out EnumAdvise: IEnumStatData): HRESULT;
begin
Result := OLE_E_ADVISENOTSUPPORTED;
end;
function TDropSource.EnumFormatEtc(dwDirection: TvgLongint;
out EnumFormatEtc: IEnumFormatEtc): HRESULT;
begin
if (dwDirection = DATADIR_GET) then
Result := S_OK
else
if (dwDirection = DATADIR_SET) then
Result := E_NOTIMPL;
end;
function TDropSource.GetCanonicalFormatEtc(const FormatEtc: TFormatEtc;
out FormatEtcout: TFormatEtc): HRESULT;
begin
Result := DATA_S_SAMEFORMATETC;
end;
function TDropSource.EqualFormatEtc(FormatEtc1, FormatEtc2: TFormatEtc): Boolean;
begin
Result := (FormatEtc1.cfFormat = FormatEtc2.cfFormat) and
(FormatEtc1.ptd = FormatEtc2.ptd) and
(FormatEtc1.dwAspect = FormatEtc2.dwAspect) and
(FormatEtc1.lindex = FormatEtc2.lindex) and
(FormatEtc1.tymed = FormatEtc2.tymed)
end;
function TDropSource.FindFormatEtc(TestFormatEtc: TFormatEtc): integer;
var
i: integer;
Found: Boolean;
begin
i := 0;
Found := False;
Result := -1;
while (i < Length(Formats)) and not Found do
begin
Found := EqualFormatEtc(Formats[i].FormatEtc, TestFormatEtc);
if Found then
Result := i;
Inc(i);
end
end;
function TDropSource.HGlobalClone(HGlobal: THandle): THandle;
// Returns a global memory block that is a copy of the passed memory block.
var
Size: LongWord;
Data, NewData: PChar;
begin
Size := GlobalSize(HGlobal);
Result := GlobalAlloc(GPTR, Size);
Data := GlobalLock(hGlobal);
try
NewData := GlobalLock(Result);
try
Move(Data, NewData, Size);
finally
GlobalUnLock(Result);
end
finally
GlobalUnLock(hGlobal)
end
end;
function TDropSource.LoadGlobalBlock(Format: TClipFormat;
var MemoryBlock: Pointer): Boolean;
var
FormatEtc: TFormatEtc;
StgMedium: TStgMedium;
GlobalObject: Pointer;
begin
Result := False;
FormatEtc.cfFormat := Format;
FormatEtc.ptd := nil;
FormatEtc.dwAspect := DVASPECT_CONTENT;
FormatEtc.lindex := -1;
FormatEtc.tymed := TYMED_HGLOBAL;
if Succeeded(QueryGetData(FormatEtc)) and Succeeded(GetData(FormatEtc, StgMedium)) then
begin
MemoryBlock := AllocMem( GlobalSize(StgMedium.hGlobal));
GlobalObject := GlobalLock(StgMedium.hGlobal);
try
if Assigned(MemoryBlock) and Assigned(GlobalObject) then
begin
Move(GlobalObject^, MemoryBlock^, GlobalSize(StgMedium.hGlobal));
end
finally
GlobalUnLock(StgMedium.hGlobal);
end
end;
end;
function TDropSource.SaveGlobalBlock(Format: TClipFormat;
MemoryBlock: Pointer; MemoryBlockSize: integer): Boolean;
var
FormatEtc: TFormatEtc;
StgMedium: TStgMedium;
GlobalObject: Pointer;
begin
FormatEtc.cfFormat := Format;
FormatEtc.ptd := nil;
FormatEtc.dwAspect := DVASPECT_CONTENT;
FormatEtc.lindex := -1;
FormatEtc.tymed := TYMED_HGLOBAL;
StgMedium.tymed := TYMED_HGLOBAL;
MySTGMEDIUM(StgMedium).unkForRelease := nil;
StgMedium.hGlobal := GlobalAlloc(GHND or GMEM_SHARE, MemoryBlockSize);
GlobalObject := GlobalLock(StgMedium.hGlobal);
try
try
Move(MemoryBlock^, GlobalObject^, MemoryBlockSize);
Result := Succeeded( SetData(FormatEtc, StgMedium, True))
except
Result := False;
end
finally
GlobalUnLock(StgMedium.hGlobal);
end
end;
function TDropSource.RetrieveOwnedStgMedium(Format: TFormatEtc; var StgMedium: TStgMedium): HRESULT;
var
i: integer;
begin
Result := E_INVALIDARG;
i := FindFormatEtc(Format);
if (i > -1) and Formats[i].OwnedByDataObject then
Result := StgMediumIncRef(Formats[i].StgMedium, StgMedium, False)
end;
function TDropSource.StgMediumIncRef(const InStgMedium: TStgMedium;
var OutStgMedium: TStgMedium; CopyInMedium: Boolean): HRESULT;
begin
Result := S_OK;
// Simply copy all fields to start with.
OutStgMedium := InStgMedium;
case InStgMedium.tymed of
TYMED_HGLOBAL:
begin
if CopyInMedium then
begin
// Generate a unique copy of the data passed
OutStgMedium.hGlobal := HGlobalClone(InStgMedium.hGlobal);
if OutStgMedium.hGlobal = 0 then
Result := E_OUTOFMEMORY
end else
// Don't generate a copy just use ourselves and the copy previoiusly saved
MySTGMEDIUM(OutStgMedium).unkForRelease := Pointer(Self as IDataObject) // Does increase RefCount
end;
TYMED_FILE:
begin
if CopyInMedium then
begin
OutStgMedium.lpszFileName := CoTaskMemAlloc(lstrLenW(InStgMedium.lpszFileName));
//!! StrCopyW(PWideChar(OutStgMedium.lpszFileName), PWideChar(InStgMedium.lpszFileName))
end
else
MySTGMEDIUM(OutStgMedium).unkForRelease := Pointer(Self as IDataObject) // Does increase RefCount
end;
TYMED_ISTREAM:
IUnknown(MySTGMEDIUM(OutStgMedium).stm)._AddRef;
TYMED_ISTORAGE:
IUnknown( MySTGMEDIUM(OutStgMedium).stg)._AddRef;
TYMED_GDI:
if not CopyInMedium then
MySTGMEDIUM(OutStgMedium).unkForRelease := Pointer(Self as IDataObject) // Does not increase RefCount
else
Result := DV_E_TYMED; // Don't know how to copy GDI objects right now
TYMED_MFPICT:
if not CopyInMedium then
MySTGMEDIUM(OutStgMedium).unkForRelease := Pointer(Self as IDataObject) // Does not increase RefCount
else
Result := DV_E_TYMED; // Don't know how to copy MetaFile objects right now
TYMED_ENHMF:
if not CopyInMedium then
MySTGMEDIUM(OutStgMedium).unkForRelease := Pointer(Self as IDataObject) // Does not increase RefCount
else
Result := DV_E_TYMED; // Don't know how to copy enhanced metafiles objects right now
else
Result := DV_E_TYMED
end;
// I still have to do this. The Compiler will call _Release on the above Self as IDataObject
// casts which is not what is necessary. The DataObject is released correctly.
if Assigned(MySTGMEDIUM(OutStgMedium).unkForRelease) and (Result = S_OK) then
IUnknown(MySTGMEDIUM(OutStgMedium).unkForRelease)._AddRef
end;
function TDropSource.GetData(const FormatEtcIn: TFormatEtc;
out Medium: TStgMedium): HRESULT;
var
Global: cardinal;
P: Pointer;
W: WideString;
B: TvgBitmap;
BitmapHandle: cardinal;
begin
FillChar(Medium, SizeOf(Medium), 0);
Result := DV_E_FORMATETC;
if QueryGetData(FormatEtcIn) <> S_OK then Exit;
if FormatEtcIn.cfFormat = CF_VGOBJECT then
begin
Medium.tymed := TYMED_HGLOBAL;
Medium.hGlobal := Cardinal(Self);
Result := S_OK;
Exit;
end;
case FormatEtcIn.cfFormat of
CF_UNICODETEXT:
begin
W := Data.Data;
Global := GlobalAlloc(0, (Length(W) + 1) * 2);
P := GlobalLock(Global);
try
Move(PWideChar(W)^, P^, GlobalSize(Global));
finally
GlobalUnlock(Global);
end;
Medium.tymed := TYMED_HGLOBAL;
Medium.hGlobal := Global;
Result := S_OK;
end;
CF_BITMAP:
begin
if VarIsObject(Data.Data) and (VariantToObject(Data.Data) is TvgBitmap) then
begin
B := TvgBitmap(VariantToObject(Data.Data));
BitmapHandle := HBmpFromBitmap(B);
if BitmapHandle <> 0 then
begin
Medium.tymed := TYMED_GDI;
Medium.hBitmap := BitmapHandle;
Result := S_OK;
end;
end
end;
end;
if Result <> S_OK then
if Assigned(Formats) then
begin
{ Do we support this type of Data? }
Result := QueryGetData(FormatEtcIn);
if Result = S_OK then
begin
// If the data is owned by the IDataObject just retrieve and return it.
if RetrieveOwnedStgMedium(FormatEtcIn, Medium) = E_INVALIDARG then
Result := E_UNEXPECTED
end
end
end;
function TDropSource.GetDataHere(const FormatEtc: TFormatEtc;
out Medium: TStgMedium): HRESULT;
begin
Result := E_NOTIMPL;
end;
function TDropSource.QueryGetData(const FormatEtc: TFormatEtc): HRESULT;
var
i: integer;
FormatAvailable, Handled: Boolean;
begin
Result:= DV_E_FORMATETC;
if FormatEtc.cfFormat = CF_VGOBJECT then
begin
Result := S_OK;
Exit;
end;
case FormatEtc.cfFormat of
CF_UNICODETEXT:
begin
if VarIsStr(Data.Data) and not VarIsObject(Data.Data) then
Result := S_OK;
end;
CF_BITMAP:
begin
if VarIsObject(Data.Data) and (VariantToObject(Data.Data) is TvgBitmap) then
Result := S_OK;
end;
end;
if Result <> S_OK then
begin
if Assigned(Formats) then
begin
i := 0;
Result := DV_E_FORMATETC;
while (i < Length(Formats)) and (Result = DV_E_FORMATETC) do
begin
if Formats[i].FormatEtc.cfFormat = formatetc.cfFormat then
begin
if (Formats[i].FormatEtc.dwAspect = formatetc.dwAspect) then
begin
if (Formats[i].FormatEtc.tymed and formatetc.tymed <> 0) then
Result := S_OK
else
Result := DV_E_TYMED;
end else
Result := DV_E_DVASPECT;
end else
Result := DV_E_FORMATETC;
Inc(i)
end
end
else
Result := E_UNEXPECTED;
end;
end;
function TDropSource.CanonicalIUnknown(TestUnknown: IUnknown): IUnknown;
// Uses COM object identity: An explicit call to the IUnknown::QueryInterface
// method, requesting the IUnknown interface, will always return the same
// pointer.
begin
if Assigned(TestUnknown) then
begin
if Supports(TestUnknown, IUnknown, Result) then
IUnknown(Result)._Release // Don't actually need it just need the pointer value
else
Result := TestUnknown
end else
Result := TestUnknown
end;
{$IFDEF FPC}
function TDropSource.SetData(const FormatEtc: TFormatEtc;
const Medium: TStgMedium; fRelease: Bool): HRESULT;
{$ELSE}
function TDropSource.SetData(const FormatEtc: TFormatEtc;
var Medium: TStgMedium; fRelease: Bool): HRESULT;
{$ENDIF}
var
Index: integer;
begin
// See if we already have a format of that type available.
Index := FindFormatEtc(FormatEtc);
if Index > - 1 then
begin
// Yes we already have that format type stored. Just use the TClipboardFormat
// in the List after releasing the data
ReleaseStgMedium(Formats[Index].StgMedium);
FillChar(Formats[Index].StgMedium, SizeOf(Formats[Index].StgMedium), #0);
end else
begin
// It is a new format so create a new TDataObjectInfo record and store it in
// the Format array
SetLength(Formats, Length(Formats) + 1);
Formats[Length(Formats) - 1].FormatEtc := FormatEtc;
Index := Length(Formats) - 1;
end;
// The data is owned by the TClipboardFormat object
Formats[Index].OwnedByDataObject := True;
if fRelease then
begin
// We are simply being given the data and we take control of it.
Formats[Index].StgMedium := Medium;
Result := S_OK
end
else
// We need to reference count or copy the data and keep our own references
// to it.
Result := StgMediumIncRef(Medium, Formats[Index].StgMedium, True);
// Can get a circular reference if the client calls GetData then calls
// SetData with the same StgMedium. Because the unkForRelease and for
// the IDataObject can be marshalled it is necessary to get pointers that
// can be correctly compared.
// See the IDragSourceHelper article by Raymond Chen at MSDN.
if Assigned(MySTGMEDIUM(Formats[Index].StgMedium).unkForRelease) then
begin
if CanonicalIUnknown(Self) =
CanonicalIUnknown(IUnknown( MySTGMEDIUM(Formats[Index].StgMedium).unkForRelease)) then
begin
IUnknown( MySTGMEDIUM(Formats[Index].StgMedium).unkForRelease)._Release;
MySTGMEDIUM(Formats[Index].StgMedium).unkForRelease := nil
end;
end;
end;
{ Platform DragDrop }
type
PSHDRAGIMAGE = ^TSHDRAGIMAGE;
{_$EXTERNALSYM _SHDRAGIMAGE}
_SHDRAGIMAGE = packed record
sizeDragImage: TSize; { The length and Width of the rendered image }
ptOffset: TPoint; { The Offset from the mouse cursor to the upper left corner of the image }
hbmpDragImage: HBitmap; { The Bitmap containing the rendered drag images }
crColorKey: COLORREF; { The COLORREF that has been blitted to the background of the images }
end;
TSHDRAGIMAGE = _SHDRAGIMAGE;
{_$EXTERNALSYM SHDRAGIMAGE}
SHDRAGIMAGE = _SHDRAGIMAGE;
const
IID_IDragSourceHelper: TGUID = (
D1:$de5bf786; D2:$477a; D3:$11d2; D4:($83,$9d,$00,$c0,$4f,$d9,$18,$d0));
SID_IDragSourceHelper = '{DE5BF786-477A-11d2-839D-00C04FD918D0}';
type
{_$EXTERNALSYM IDragSourceHelper}
IDragSourceHelper = interface(IUnknown)
[SID_IDragSourceHelper]
function InitializeFromBitmap(var shdi: TSHDRAGIMAGE;
const DataObj: IDataObject): HResult; stdcall;
function InitializeFromWindow(hwnd: HWND; var pt: TPoint;
const DataObj: IDataObject): HResult; stdcall;
end;
procedure TvgPlatformWin.BeginDragDrop(AForm: TvgCustomForm; const Data: TvgDragObject; ABitmap: TvgBitmap);
var
D: TDropSource;
DropEffect: Longint;
DragSourceHelper: IDragSourceHelper;
shDragImage: TSHDRAGIMAGE;
begin
D := TDropSource.Create(nil);
D.Data := Data;
if (Succeeded(CoCreateInstance(CLSID_DragDropHelper, nil, CLSCTX_INPROC_SERVER,
IDragSourceHelper, DragSourceHelper))) and (DragSourceHelper <> nil) then
begin
Fillchar(shDragImage, SizeOf(shDragImage), 0);
shDragImage.sizeDragImage.cx := ABitmap.Width;
shDragImage.sizeDragImage.cy := ABitmap.Height;
shDragImage.ptOffset.X := (ABitmap.Width div 2);
shDragImage.ptOffset.Y := (ABitmap.Height div 2);
shDragImage.hbmpDragImage := HBmpFromBitmap(ABitmap);
if not Succeeded(DragSourceHelper.InitializeFromBitmap(shDragImage, D)) then
DeleteObject(shDragImage.hbmpDragImage);
end;
DoDragDrop(D, D, DROPEFFECT_LINK or DROPEFFECT_COPY or DROPEFFECT_MOVE, {$IFDEF FPC}@{$ENDIF}DropEffect);
if Assigned(DragSourceHelper) then
DragSourceHelper := nil;
FreeAndNil(D);
end;
{ Clipboard }
function TvgPlatformWin.GetClipboard: Variant;
var
Data: THandle;
W: WideString;
begin
Result := NULL;
OpenClipboard(0);
Data := GetClipboardData(CF_UNICODETEXT);
if Data <> 0 then
begin
W := PWideChar(GlobalLock(Data));
Result := W;
GlobalUnlock(Data);
end;
CloseClipboard;
end;
procedure TvgPlatformWin.SetClipboard(Value: Variant);
var
Data: THandle;
DataPtr: Pointer;
W: WideString;
begin
if not VarIsObject(Value) and VarIsStr(Value) then
begin
OpenClipboard(0);
EmptyClipboard;
try
W := Value;
Data := GlobalAlloc(GMEM_MOVEABLE + GMEM_DDESHARE, (Length(W) + 1) * 2);
try
DataPtr := GlobalLock(Data);
try
Move(PWideChar(W)^, DataPtr^, GlobalSize(Data));
SetClipboardData(CF_UNICODETEXT, Data);
finally
GlobalUnlock(Data);
end;
except
GlobalFree(Data);
raise;
end;
finally
CloseClipboard;
end;
end;
end;
{ Mouse }
function TvgPlatformWin.GetMousePos: TvgPoint;
var
P: TPoint;
begin
GetCursorPos(P);
Result := vgPoint(P.X, P.Y);
end;
{ Screen }
function TvgPlatformWin.GetScreenSize: TvgPoint;
var
R: TRect;
begin
Windows.GetWindowRect(GetDesktopWindow, R);
Result := vgPoint(R.Right, R.Bottom);
end;
function TvgPlatformWin.GetCurrentLangID: string;
var
Lang, FallbackLang: string;
Buffer: array[1..4] of {$ifdef Wince}WideChar{$else}char{$endif};
Country: string;
UserLCID: LCID;
begin
//defaults
Lang := '';
FallbackLang:='';
UserLCID := GetUserDefaultLCID;
if GetLocaleInfo(UserLCID, LOCALE_SABBREVLANGNAME, @Buffer[1], 4)<>0 then
FallbackLang := lowercase(copy(Buffer,1,2));
if GetLocaleInfo(UserLCID, LOCALE_SABBREVCTRYNAME, @Buffer[1], 4)<>0 then begin
Country := copy(Buffer,1,2);
// some 2 letter codes are not the first two letters of the 3 letter code
// there are probably more, but first let us see if there are translations
if (Buffer='PRT') then Country:='PT';
Lang := FallbackLang+'_'+Country;
end;
Result := FallbackLang;
end;
function TvgPlatformWin.DialogOpenFiles;
const
FileNameBufferLen = 1000;
var
Flags: DWord;
OpenFile: TOpenFilenameW;
FileNameBuffer: PWideChar;
FileNameBufferSize: Integer;
InitialDir, Filter, DefaultExt: WideString;
begin
Result := false;
InitialDir := AInitDir;
if (FileName <> '') and (FileName[length(FileName)] = PathDelim) then
begin
// if the filename contains a directory, set the initial directory
// and clear the filename
InitialDir := Copy(FileName, 1, Length(FileName) - 1);
FileName := '';
end;
DefaultExt := '*';
FileNameBuffer := AllocMem(FileNameBufferLen * 2 + 2);
if Length(FileName) > FileNameBufferLen then
FileNameBufferSize := FileNameBufferLen
else
FileNameBufferSize := Length(FileName);
Move(PWideChar(FileName)^, FileNameBuffer^, FileNameBufferSize * 2);
Filter := 'All File Types(*.*)'+#0+'*.*'+#0; // Default -> avoid empty combobox
FillChar(OpenFile, SizeOf(OpenFile), 0);
OpenFile.hInstance := hInstance;
with OpenFile do
begin
lStructSize := SizeOf(OpenFile);
hWndOwner := 0;
nFilterIndex := 0;
lpStrFile := FileNameBuffer;
lpstrFilter := PWideChar(Filter);
lpstrTitle := PWideChar(WideString('Title'));
lpstrInitialDir := PWideChar(InitialDir);
lpstrDefExt := PWideChar(DefaultExt);
lpStrFile := FileNameBuffer;
nMaxFile := FileNameBufferLen + 1; // Size in TCHARs
Flags := OFN_EXPLORER;
if AllowMulti then Flags := Flags or OFN_ALLOWMULTISELECT;
end;
Result := GetOpenFileNameW({$IFDEF FPC}@{$ENDIF}OpenFile);
if Result then
FileName := FileNameBuffer;
l3System.FreeLocalMem(FileNameBuffer);
end;
initialization
OleInitialize(nil);
User32Lib := LoadLibrary(User32);
if User32Lib <> 0 then
@UpdateLayeredWindow := GetProcAddress(User32Lib, 'UpdateLayeredWindow');
DefaultPlatformClass := TvgPlatformWin;
finalization
if FTimerData <> nil then
FreeAndNil(FTimerData);
if User32Lib <> 0 then
FreeLibrary(User32Lib);
end.
|
//
// ABActionsC.h
// AddressBook Framework
//
// Copyright (c) 2003 Apple Computer. All rights reserved.
//
{ Pascal Translation: Peter N Lewis, <peter@stairways.com.au>, 2004 }
{
Modified for use with Free Pascal
Version 210
Please report any bugs to <gpc@microbizz.nl>
}
{$mode macpas}
{$packenum 1}
{$macro on}
{$inline on}
{$calling mwpascal}
unit ABActions;
interface
{$setc UNIVERSAL_INTERFACES_VERSION := $0342}
{$setc GAP_INTERFACES_VERSION := $0210}
{$ifc not defined USE_CFSTR_CONSTANT_MACROS}
{$setc USE_CFSTR_CONSTANT_MACROS := TRUE}
{$endc}
{$ifc defined CPUPOWERPC and defined CPUI386}
{$error Conflicting initial definitions for CPUPOWERPC and CPUI386}
{$endc}
{$ifc defined FPC_BIG_ENDIAN and defined FPC_LITTLE_ENDIAN}
{$error Conflicting initial definitions for FPC_BIG_ENDIAN and FPC_LITTLE_ENDIAN}
{$endc}
{$ifc not defined __ppc__ and defined CPUPOWERPC}
{$setc __ppc__ := 1}
{$elsec}
{$setc __ppc__ := 0}
{$endc}
{$ifc not defined __i386__ and defined CPUI386}
{$setc __i386__ := 1}
{$elsec}
{$setc __i386__ := 0}
{$endc}
{$ifc defined __ppc__ and __ppc__ and defined __i386__ and __i386__}
{$error Conflicting definitions for __ppc__ and __i386__}
{$endc}
{$ifc defined __ppc__ and __ppc__}
{$setc TARGET_CPU_PPC := TRUE}
{$setc TARGET_CPU_X86 := FALSE}
{$elifc defined __i386__ and __i386__}
{$setc TARGET_CPU_PPC := FALSE}
{$setc TARGET_CPU_X86 := TRUE}
{$elsec}
{$error Neither __ppc__ nor __i386__ is defined.}
{$endc}
{$setc TARGET_CPU_PPC_64 := FALSE}
{$ifc defined FPC_BIG_ENDIAN}
{$setc TARGET_RT_BIG_ENDIAN := TRUE}
{$setc TARGET_RT_LITTLE_ENDIAN := FALSE}
{$elifc defined FPC_LITTLE_ENDIAN}
{$setc TARGET_RT_BIG_ENDIAN := FALSE}
{$setc TARGET_RT_LITTLE_ENDIAN := TRUE}
{$elsec}
{$error Neither FPC_BIG_ENDIAN nor FPC_LITTLE_ENDIAN are defined.}
{$endc}
{$setc ACCESSOR_CALLS_ARE_FUNCTIONS := TRUE}
{$setc CALL_NOT_IN_CARBON := FALSE}
{$setc OLDROUTINENAMES := FALSE}
{$setc OPAQUE_TOOLBOX_STRUCTS := TRUE}
{$setc OPAQUE_UPP_TYPES := TRUE}
{$setc OTCARBONAPPLICATION := TRUE}
{$setc OTKERNEL := FALSE}
{$setc PM_USE_SESSION_APIS := TRUE}
{$setc TARGET_API_MAC_CARBON := TRUE}
{$setc TARGET_API_MAC_OS8 := FALSE}
{$setc TARGET_API_MAC_OSX := TRUE}
{$setc TARGET_CARBON := TRUE}
{$setc TARGET_CPU_68K := FALSE}
{$setc TARGET_CPU_MIPS := FALSE}
{$setc TARGET_CPU_SPARC := FALSE}
{$setc TARGET_OS_MAC := TRUE}
{$setc TARGET_OS_UNIX := FALSE}
{$setc TARGET_OS_WIN32 := FALSE}
{$setc TARGET_RT_MAC_68881 := FALSE}
{$setc TARGET_RT_MAC_CFM := FALSE}
{$setc TARGET_RT_MAC_MACHO := TRUE}
{$setc TYPED_FUNCTION_POINTERS := TRUE}
{$setc TYPE_BOOL := FALSE}
{$setc TYPE_EXTENDED := FALSE}
{$setc TYPE_LONGLONG := TRUE}
uses MacTypes,ABAddressBook,CFBase;
{$ALIGN MAC68K}
// --------------------------------------------------------------------------------
// Action Support
// --------------------------------------------------------------------------------
// This API allows developers to populate AddressBook.app's roll-over menus with custom
// entries. Your CFBundle must implement a function named ABActionRegisterCallbacks which
// will return a pointer to an ABActionCallbacks struct. This struct should be filled out
// as follows:
//
// version: The version of this structure is 0.
//
// proprty: A pointer to a function that returns the AddressBook property this action applies
// to. Only items with labels may have actions at this time. (emails, phones, birthdays, etc)
//
// title: A pointer to a function which returns a copy of the title to be displayed. This function
// takes two parameters, the selected person and item identifier. The item identifier will be NULL
// for single value properties. AddressBook will release this string when it's done with it.
//
// enabled: A pointer to a function which returns YES if the action should be enabled for the
// passed ABPersonRef and item identifier. The item identifier will be NULL for single value
// properties. This field may be NULL. Actions with NULL enabled callbacks will always be enabled.
//
// selected. A pointer to a function which will be called when the user selects this action.
// It's passed an ABPersonRef and item identifier. The item identifier will be NULL for single
// value properties.
//
// Action plugins are stored in ~/Library/Address Book Plug-Ins or /Library/Address Book Plug-Ins
//
// There can be only 1 Action plug in per bundle.
type ABActionGetPropertyCallback = function: CFStringRef;
type ABActionCopyTitleCallback = function( person: ABPersonRef; identifier: CFStringRef ): CFStringRef;
type ABActionEnabledCallback = function( person: ABPersonRef; identifier: CFStringRef ): Boolean;
type ABActionSelectedCallback = procedure( person: ABPersonRef; identifier: CFStringRef );
type ABActionCallbacks = record
version: CFIndex;
proprty: ABActionGetPropertyCallback;
title: ABActionCopyTitleCallback;
enabled: ABActionEnabledCallback;
selected: ABActionSelectedCallback;
end;
// Your CFBundle MUST include a function named ABActionRegisterCallbacks which returns a pointer
// to a filled out ABActionCallbacks struct:
//
// ABActionCallbacks* ABActionRegisterCallbacks(void);
end.
|
unit TimerUtils;
// Copyright (c) 1996 Hitzel Cruz & Jorge Romero Gomez, Merchise.
interface
{$LONGSTRINGS ON}
{$BOOLEVAL OFF}
uses
Windows, MMSystem, Messages, SysUtils, Classes, Forms;
// Timers --------------------------------------------------------------------------------------
type
ETimerError = class( Exception );
type
TNotifyProc = procedure of object;
// TSimpleTimer
type
TTicker =
class
protected
fInterval : integer;
fResolution : integer;
fEnabled : boolean;
fOntimer : TNotifyProc;
fPostTicks : boolean;
public
constructor Create; // This is an abstract class!
destructor Destroy; override;
public
procedure Pause;
procedure Resume;
protected
procedure Update; virtual; abstract;
procedure Timer; virtual;
protected
procedure SetEnabled( aEnabled : boolean ); virtual;
procedure SetOnTimer( aProc : TNotifyProc ); virtual;
procedure SetPostTicks( TicksPosted : boolean ); virtual;
procedure SetInterval( aInterval : integer ); virtual; abstract;
procedure SetResolution( aInterval : integer ); virtual; abstract;
published
property Interval : integer read fInterval write SetInterval;
property Resolution : integer read fResolution write SetResolution;
property Enabled : boolean read fEnabled write SetEnabled;
property OnTimer : TNotifyProc read fOnTimer write SetOnTimer;
property PostTicks : boolean read fPostTicks write SetPostTicks;
end;
type
TSimpleTimer =
class( TTicker )
protected
WndHandle : HWnd;
TimerId : integer;
public
constructor Create;
destructor Destroy; override;
protected
procedure Update; override;
procedure SetInterval( aInterval : integer ); override;
procedure SetResolution( aInterval : integer ); override;
procedure InternalWndProc( var Msg : TMessage );
end;
// TEnhancedTimer
type
TEnhancedTimer =
class( TTicker )
protected
WndHandle : HWnd;
TimerId : integer;
public
constructor Create;
destructor Destroy; override;
protected
procedure Update; override;
procedure SetInterval( aInterval : integer ); override;
procedure SetResolution( aInterval : integer ); override;
procedure SetPostTicks( TicksPosted : boolean ); override;
procedure InternalWndProc( var Msg : TMessage );
end;
// TTrustedEnhTimer
type
TTrustedEnhTimer = class;
TTimerThread =
class( TThread )
private
fOwner : TTrustedEnhTimer;
TimerId : integer;
Event : THandle;
public
constructor Create( aOwner : TTrustedEnhTimer );
destructor Destroy; override;
public
procedure InitTicking;
procedure ResetTicking;
protected
procedure Timer;
procedure Execute; override;
end;
TTrustedEnhTimer =
class( TTicker )
protected
fTimerThread : TTimerThread;
fLostEvents : integer;
public
constructor Create;
destructor Destroy; override;
protected
procedure Update; override;
procedure Timer; override;
procedure SetInterval( aInterval : integer ); override;
procedure SetResolution( aInterval : integer ); override;
public
property LostEvents : integer read fLostEvents;
end;
// Miscellaneous -------------------------------------------------------------------------------
function TimerMinResolution : integer;
function TimerMaxResolution : integer;
function EnhTimerMinResolution : integer;
function EnhTimerMaxResolution : integer;
function AdjustInterval( Interval, MinResolution, MaxResolution : integer ) : integer;
function TicksToTime( Ticks : longint ) : string;
// Stopwatches ---------------------------------------------------------------------------------
type
TStopWatch =
class
procedure Reset;
procedure Start;
procedure Stop;
function ElapsedTicks : longint;
function ElapsedTime : string;
private
fStartedAt : longint;
fLastPeriod : longint;
end;
implementation
uses
NumUtils, mr_StrUtils;
// Stopwatches ---------------------------------------------------------------------------------
procedure TStopWatch.Reset;
begin
fStartedAt := timeGetTime;
fLastPeriod := 0;
end;
procedure TStopWatch.Start;
begin
fStartedAt := longint(timeGetTime) - fLastPeriod;
fLastPeriod := 0;
end;
procedure TStopWatch.Stop;
begin
fLastPeriod := longint(timeGetTime) - fStartedAt;
fStartedAt := 0;
end;
function TStopWatch.ElapsedTicks : longint;
begin
if fStartedAt = 0
then Result := fLastPeriod
else Result := longint(timeGetTime) - fStartedAt;
end;
function TStopWatch.ElapsedTime : string;
begin
Result := TicksToTime( ElapsedTicks );
end;
// Timers --------------------------------------------------------------------------------------
const
defEnabled = false;
defInterval = 1;
constructor TTicker.Create;
begin
inherited;
fInterval := defInterval;
fEnabled := defEnabled;
fResolution := TimerMinResolution;
end;
destructor TTicker.Destroy;
begin
Enabled := false;
inherited;
end;
procedure TTicker.Pause;
begin
Enabled := false;
end;
procedure TTicker.Resume;
begin
Enabled := true;
end;
procedure TTicker.SetPostTicks( TicksPosted : boolean );
begin
end;
procedure TTicker.SetOnTimer( aProc : TNotifyProc );
begin
fOnTimer := aProc;
Update;
end;
procedure TTicker.SetEnabled( aEnabled : boolean );
begin
if fEnabled <> aEnabled
then
begin
fEnabled := aEnabled;
Update;
end;
end;
procedure TTicker.Timer;
begin
if Assigned( fOnTimer )
then fOnTimer;
end;
// TSimpleTimer
constructor TSimpleTimer.Create;
begin
inherited;
fPostTicks := true;
WndHandle := AllocateHwnd( InternalWndProc );
end;
destructor TSimpleTimer.Destroy;
begin
DeallocateHwnd( WndHandle );
inherited;
end;
procedure TSimpleTimer.InternalWndProc( var Msg : TMessage );
begin
with Msg do
if Msg = WM_TIMER
then
try
Timer;
except
Application.HandleException( Self );
end
else Result := DefWindowProc( WndHandle, Msg, wParam, lParam );
end;
procedure TSimpleTimer.Update;
begin
if TimerId <> 0
then
begin
KillTimer( WndHandle, TimerId );
TimerId := 0;
end;
if Enabled and Assigned( fOnTimer ) and ( fInterval <> 0 )
then TimerId := SetTimer( WndHandle, 1, fInterval, nil );
end;
procedure TSimpleTimer.SetInterval( aInterval : integer );
begin
if fInterval <> aInterval
then
begin
fInterval := AdjustInterval( aInterval, TimerMinResolution, TimerMaxResolution );
Update;
end;
end;
procedure TSimpleTimer.SetResolution( aInterval : integer );
begin
end;
var
tc : TTimeCaps;
etInterval : integer;
// TEnhancedTimer
constructor TEnhancedTimer.Create;
begin
inherited;
fResolution := TimerMinResolution;
fInterval := etInterval;
fEnabled := defEnabled;
timeBeginPeriod( etInterval );
WndHandle := AllocateHwnd( InternalWndProc );
end;
destructor TEnhancedTimer.Destroy;
begin
Enabled := false;
DeallocateHwnd( WndHandle );
timeEndPeriod( etInterval );
inherited;
end;
const
WM_INTERNALTIMER = WM_USER + 56789;
procedure TEnhancedTimer.InternalWndProc( var Msg : TMessage );
begin
with Msg do
if Msg = WM_INTERNALTIMER
then
try
Timer;
except
Application.HandleException( Self );
end
else Result := DefWindowProc( WndHandle, Msg, wParam, lParam );
end;
procedure TimerEvent( uTimerId, uMessage : UINT; dwUser, dw1, dw2 : DWORD ); stdcall;
var
Timer : TEnhancedTimer absolute dwUser;
begin
with Timer do
if PostTicks
then PostMessage( WndHandle, WM_INTERNALTIMER, 0, 0 )
else SendMessage( WndHandle, WM_INTERNALTIMER, 0, 0 );
end;
procedure TEnhancedTimer.Update;
var
Msg : TMsg;
begin
if ( TimerId <> 0 ) and ( timeKillEvent( TimerId ) = TIMERR_NOERROR )
then
repeat
// Empty message queue...
until not PeekMessage( Msg, WndHandle, WM_INTERNALTIMER, WM_INTERNALTIMER, PM_REMOVE );
if Enabled and Assigned( fOnTimer ) and ( fInterval <> 0 )
then TimerId := timeSetEvent( fInterval, fResolution, TimerEvent, Integer( Self ), TIME_PERIODIC )
else TimerId := 0;
end;
procedure TEnhancedTimer.SetPostTicks( TicksPosted : boolean );
begin
fPostTicks := TicksPosted;
end;
procedure TEnhancedTimer.SetInterval( aInterval : integer );
begin
if fInterval <> aInterval
then
begin
fInterval := Max( EnhTimerMinResolution, aInterval );
Update;
end;
end;
procedure TEnhancedTimer.SetResolution( aInterval : integer );
begin
if fResolution <> aInterval
then
begin
if aInterval < 0
then Resolution := 0;
fResolution := aInterval;
Update;
end;
end;
// TTimerThread
constructor TTimerThread.Create( aOwner : TTrustedEnhTimer );
begin
inherited Create( false );
fOwner := aOwner;
FreeOnTerminate := false;
Event := CreateEvent( nil, false, false, 'TimerThreadEvent' );
end;
destructor TTimerThread.Destroy;
begin
Suspend;
ResetTicking;
ResetEvent( Event );
CloseHandle( Event );
inherited;
end;
procedure TrustedTimerEvent( uTimerId, uMessage : UINT; dwUser, dw1, dw2 : DWORD ); stdcall;
var
Timer : TTrustedEnhTimer absolute dwUser;
begin
with Timer do
begin
Inc( fLostEvents );
SetEvent( fTimerThread.Event );
end;
end;
procedure TTimerThread.InitTicking;
begin
if TimerId <> 0
then ResetTicking;
with fOwner do
TimerId := timeSetEvent( fInterval, fResolution, TrustedTimerEvent, integer( fOwner ), TIME_PERIODIC );
if TimerId = 0
then raise ETimerError.Create( 'Could not allocate timer event' );
end;
procedure TTimerThread.ResetTicking;
begin
if TimerId <> 0
then
begin
timeKillEvent( TimerId );
TimerId := 0;
end;
end;
procedure TTimerThread.Execute;
begin
while not Terminated do
begin
if ( TimerId <> 0 ) and ( WaitForSingleObject( Event, INFINITE ) = WAIT_OBJECT_0 )
then Synchronize( Timer );
end;
end;
procedure TTimerThread.Timer;
begin
fOwner.Timer;
end;
// TTrustedEnhTimer
constructor TTrustedEnhTimer.Create;
begin
inherited;
fTimerThread := TTimerThread.Create( Self );
fResolution := TimerMinResolution;
fInterval := etInterval;
fEnabled := defEnabled;
timeBeginPeriod( etInterval );
end;
destructor TTrustedEnhTimer.Destroy;
begin
Enabled := false;
fTimerThread.Free;
timeEndPeriod( etInterval );
inherited;
end;
procedure TTrustedEnhTimer.Update;
begin
fTimerThread.ResetTicking;
if Enabled and Assigned( fOnTimer ) and ( fInterval <> 0 )
then fTimerThread.InitTicking;
end;
procedure TTrustedEnhTimer.Timer;
begin
Dec( fLostEvents );
inherited;
fLostEvents := 0;
end;
procedure TTrustedEnhTimer.SetInterval( aInterval : integer );
begin
if fInterval <> aInterval
then
begin
fInterval := Max( EnhTimerMinResolution, aInterval );
Update;
end;
end;
procedure TTrustedEnhTimer.SetResolution( aInterval : integer );
begin
if fResolution <> aInterval
then
begin
if aInterval < 0
then Resolution := 0;
fResolution := aInterval;
Update;
end;
end;
// Miscellaneous
function TimerMinResolution : integer;
begin
Result := 55; //!!!!
end;
function TimerMaxResolution : integer;
begin
Result := MaxInt; //!!!!
end;
function EnhTimerMinResolution : integer;
begin
Result := tc.wPeriodMin;
end;
function EnhTimerMaxResolution : integer;
begin
Result := tc.wPeriodMax;
end;
function AdjustInterval( Interval, MinResolution, MaxResolution : integer ) : integer;
begin
Result := Max( Min( MaxResolution, NearestMult( Interval, MinResolution ) ), MinResolution );
end;
function TicksToTime( Ticks : longint ) : string;
var
Hundredths : integer;
Seconds : integer;
Minutes : integer;
Hours : integer;
begin
Hundredths := ( Ticks mod 1000 ) div 10;
Ticks := Ticks div 1000;
Seconds := Ticks mod 60;
Ticks := Ticks div 60;
Minutes := Ticks mod 60;
Hours := Ticks div 60;
Result := IntToStr( Hours ) + ':' + NumToStr( Minutes, 10, 2 ) + ':' + NumToStr( Seconds, 10, 2 ) + '.' + NumToStr( Hundredths, 10, 2 );
end;
initialization
if timeGetDevCaps( @tc, sizeof( TTimeCaps ) ) <> TIMERR_NOERROR
then etInterval := 0
else etInterval := Min( Max( tc.wPeriodMin, defInterval ), tc.wPeriodMax );
end.
|
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// author this port to delphi - Marat Shaymardanov, Tomsk 2007, 2018
//
// You can freely use this code in any project
// if sending any postcards with postage stamp to my address:
// Frunze 131/1, 56, Russia, Tomsk, 634021
unit UnitTest;
interface
uses pbPublic, pbInput, pbOutput;
procedure TestAll;
implementation
procedure TestVarint;
type
TVarintCase = record
bytes: array [1..10] of Byte; // Encoded bytes.
size: Integer; // Encoded size, in bytes.
value: Int64; // Parsed value.
end;
const
VarintCases: array [0..7] of TVarintCase = (
// 32-bit values
(bytes: ($00, $00, $00, $00, $00, $00, $00, $00, $00, $00); size: 1; value: 0),
(bytes: ($01, $00, $00, $00, $00, $00, $00, $00, $00, $00); size: 1; value: 1),
(bytes: ($7f, $00, $00, $00, $00, $00, $00, $00, $00, $00); size: 1; value: 127),
(bytes: ($a2, $74, $00, $00, $00, $00, $00, $00, $00, $00); size: 2; value: 14882),
(bytes: ($ff, $ff, $ff, $ff, $0f, $00, $00, $00, $00, $00); size: 5; value: -1),
// 64-bit
(bytes: ($be, $f7, $92, $84, $0b, $00, $00, $00, $00, $00); size: 5; value: 2961488830),
(bytes: ($be, $f7, $92, $84, $1b, $00, $00, $00, $00, $00); size: 5; value: 7256456126),
(bytes: ($80, $e6, $eb, $9c, $c3, $c9, $a4, $49, $00, $00); size: 8; value: 41256202580718336)
);
var
i, j: Integer;
t: TVarintCase;
pb: TProtoBufInput;
buf: AnsiString;
i64: Int64;
int: Integer;
begin
for i := 0 to 7 do
begin
t := VarintCases[i];
// создать тестовый буфер
SetLength(buf, t.size);
for j := 1 to t.size do buf[j] := AnsiChar(t.bytes[j]);
pb := TProtoBufInput.Create(@buf[1], t.size);
try
if i < 5 then
begin
int := pb.readRawVarint32;
Assert(t.value = int, 'Test Varint fails');
end
else
begin
i64 := pb.readRawVarint64;
Assert(t.value = i64, 'Test Varint fails');
end;
finally
pb.Free;
end;
end;
end;
procedure TestReadLittleEndian32;
type
TLittleEndianCase = record
bytes: array [1..4] of Byte; // Encoded bytes.
value: Integer; // Parsed value.
end;
const
LittleEndianCases: array [0..5] of TLittleEndianCase = (
(bytes: ($78, $56, $34, $12); value: $12345678),
(bytes: ($f0, $de, $bc, $9a); value: Integer($9abcdef0)),
(bytes: ($ff, $00, $00, $00); value: 255),
(bytes: ($ff, $ff, $00, $00); value: 65535),
(bytes: ($4e, $61, $bc, $00); value: 12345678),
(bytes: ($b2, $9e, $43, $ff); value: -12345678)
);
var
i, j: Integer;
t: TLittleEndianCase;
pb: TProtoBufInput;
buf: AnsiString;
int: Integer;
begin
for i := 0 to 5 do
begin
t := LittleEndianCases[i];
SetLength(buf, 4);
for j := 1 to 4 do buf[j] := AnsiChar(t.bytes[j]);
pb := TProtoBufInput.Create(@buf[1], 4);
try
int := pb.readRawLittleEndian32;
Assert(t.value = int, 'Test readRawLittleEndian32 fails');
finally
pb.Free;
end;
end;
end;
procedure TestReadLittleEndian64;
type
TLittleEndianCase = record
bytes: array [1..8] of Byte; // Encoded bytes.
value: Int64; // Parsed value.
end;
const
LittleEndianCases: array [0..3] of TLittleEndianCase = (
(bytes: ($67, $45, $23, $01, $78, $56, $34, $12); value: $1234567801234567),
(bytes: ($f0, $de, $bc, $9a, $78, $56, $34, $12); value: $123456789abcdef0),
(bytes: ($79, $df, $0d, $86, $48, $70, $00, $00); value: 123456789012345),
(bytes: ($87, $20, $F2, $79, $B7, $8F, $FF, $FF); value: -123456789012345)
);
var
i, j: Integer;
t: TLittleEndianCase;
pb: TProtoBufInput;
buf: AnsiString;
int: Int64;
begin
for i := 0 to 3 do
begin
t := LittleEndianCases[i];
SetLength(buf, 8);
for j := 1 to 8 do buf[j] := AnsiChar(t.bytes[j]);
pb := TProtoBufInput.Create(@buf[1], 8);
try
int := pb.readRawLittleEndian64;
Assert(t.value = int, 'Test readRawLittleEndian64 fails');
finally
pb.Free;
end;
end;
end;
procedure TestDecodeZigZag;
begin
(* 32 *)
Assert( 0 = decodeZigZag32(0));
Assert(-1 = decodeZigZag32(1));
Assert( 1 = decodeZigZag32(2));
Assert(-2 = decodeZigZag32(3));
Assert(Integer($3FFFFFFF) = decodeZigZag32(Integer($7FFFFFFE)));
Assert(Integer($C0000000) = decodeZigZag32(Integer($7FFFFFFF)));
Assert(Integer($7FFFFFFF) = decodeZigZag32(Integer($FFFFFFFE)));
Assert(Integer($80000000) = decodeZigZag32(Integer($FFFFFFFF)));
(* 64 *)
Assert( 0 = decodeZigZag64(0));
Assert(-1 = decodeZigZag64(1));
Assert( 1 = decodeZigZag64(2));
Assert(-2 = decodeZigZag64(3));
Assert($000000003FFFFFFF = decodeZigZag64($000000007FFFFFFE));
Assert(Int64($FFFFFFFFC0000000) = decodeZigZag64(Int64($000000007FFFFFFF)));
Assert(Int64($000000007FFFFFFF) = decodeZigZag64(Int64($00000000FFFFFFFE)));
Assert(Int64($FFFFFFFF80000000) = decodeZigZag64(Int64($00000000FFFFFFFF)));
Assert(Int64($7FFFFFFFFFFFFFFF) = decodeZigZag64(Int64($FFFFFFFFFFFFFFFE)));
Assert(Int64($8000000000000000) = decodeZigZag64(Int64($FFFFFFFFFFFFFFFF)));
end;
procedure TestReadString;
const
TEST_string = AnsiString('Тестовая строка');
TEST_empty_string = AnsiString('');
TEST_integer = 12345678;
TEST_single = 12345.123;
TEST_double = 1234567890.123;
var
out_pb: TProtoBufOutput;
in_pb: TProtoBufInput;
tag, t: Integer;
text: AnsiString;
int: Integer;
dbl: Double;
flt: Single;
delta: Extended;
begin
out_pb := TProtoBufOutput.Create;
out_pb.writeString(1, TEST_string);
out_pb.writeString(2, TEST_empty_string);
out_pb.writeFixed32(3, TEST_integer);
out_pb.writeFloat(4, TEST_single);
out_pb.writeDouble(5, TEST_double);
out_pb.SaveToFile('test.dmp');
in_pb := TProtoBufInput.Create();
in_pb.LoadFromFile('test.dmp');
// TEST_string
tag := makeTag(1, WIRETYPE_LENGTH_DELIMITED);
t := in_pb.readTag;
Assert(tag = t);
text := in_pb.readString;
Assert(TEST_string = text);
// TEST_empty_string
tag := makeTag(2, WIRETYPE_LENGTH_DELIMITED);
t := in_pb.readTag;
Assert(tag = t);
text := in_pb.readString;
Assert(TEST_empty_string = text);
// TEST_integer
tag := makeTag(3, WIRETYPE_FIXED32);
t := in_pb.readTag;
Assert(tag = t);
int := in_pb.readFixed32;
Assert(TEST_integer = int);
// TEST_single
tag := makeTag(4, WIRETYPE_FIXED32);
t := in_pb.readTag;
Assert(tag = t);
flt := in_pb.readFloat;
delta := TEST_single - flt;
Assert(abs(delta) < 0.001);
// TEST_double
tag := makeTag(5, WIRETYPE_FIXED64);
t := in_pb.readTag;
Assert(tag = t);
dbl := in_pb.readDouble;
{$OVERFLOWCHECKS ON}
delta := dbl - TEST_double;
Assert(abs(delta) < 0.000001);
end;
procedure TestMemoryLeak;
const
Mb = 1024 * 1024;
var
in_pb: TProtoBufInput;
buf_size: Integer;
s: AnsiString;
i: Integer;
begin
buf_size := 64 * Mb;
SetLength(s, buf_size);
for i := 0 to 200 do
begin
in_pb := TProtoBufInput.Create(PAnsiChar(s), Length(s), False);
in_pb.Free;
end;
end;
procedure TestAll;
begin
TestVarint;
TestReadLittleEndian32;
TestReadLittleEndian64;
TestDecodeZigZag;
TestReadString;
TestMemoryLeak;
end;
end.
|
unit save_rtf_dialog;
interface
uses Messages, Windows, SysUtils, Classes, Controls, StdCtrls, Graphics,
ExtCtrls, Buttons, Dialogs;
type
TOpenPictureDialog = class(TSaveDialog)
private
SkipImages, SkipCover, SkipDescr, EncCompat, ImgCompat:TCheckBox;
FChecksPanel: TPanel;
function GetSkipImages:boolean;
function GetSkipCover:boolean;
function GetSkipDescr:boolean;
function GetEncCompat:boolean;
function GetImgCompat:boolean;
protected
procedure DoClose; override;
procedure DoShow; override;
public
property DoSkipImages:boolean read GetSkipImages;
property DoSkipCover:boolean read GetSkipCover;
property DoSkipDescr:boolean read GetSkipDescr;
property DoEncCompat:boolean read GetEncCompat;
property DoImgCompat:boolean read GetImgCompat;
constructor Create(AOwner: TComponent); override;
function Execute: Boolean; override;
Procedure OnImgClick(sender: TObject);
Procedure OnImgKey(Sender: TObject; var Key: Char);
end;
const
RegistryKey='Software\Grib Soft\FB to RTF\1.0';
implementation
uses Consts, Math, Forms, CommDlg, Dlgs,Registry;
{$R MyExtdlg.res}
function TOpenPictureDialog.GetSkipImages;
Begin
result:= SkipImages.checked;
end;
function TOpenPictureDialog.GetSkipCover;
Begin
result:= SkipCover.checked;
end;
function TOpenPictureDialog.GetSkipDescr;
Begin
result:= SkipDescr.checked;
end;
function TOpenPictureDialog.GetEncCompat;
Begin
result:= EncCompat.checked;
end;
function TOpenPictureDialog.GetImgCompat;
Begin
result:= ImgCompat.checked;
end;
procedure TOpenPictureDialog.OnImgClick;
Begin
SkipCover.Enabled:=not SkipImages.Checked;
end;
procedure TOpenPictureDialog.OnImgKey;
Begin
OnImgClick(SkipImages);
end;
constructor TOpenPictureDialog.Create(AOwner: TComponent);
Var
Reg:TRegistry;
begin
inherited Create(AOwner);
Options:=[ofOverwritePrompt,ofEnableSizing];
FChecksPanel:=TPanel.Create(Self);
with FChecksPanel do
Begin
Name := 'PicturePanel';
Caption := '';
SetBounds(10, 150, 200, 200);
BevelOuter := bvNone;
BorderWidth := 6;
TabOrder := 1;
SkipImages:=TCheckBox.Create(Self);
With SkipImages do Begin
Name := 'SkipImages';
Caption := 'No images';
Left:=0;
Top:=0;
TabOrder := 1;
Width:=94;
Parent:=FChecksPanel;
end;
SkipImages.OnClick:=OnImgClick;
SkipImages.OnKeyPress:=OnImgKey;
SkipCover:=TCheckBox.Create(Self);
With SkipCover do Begin
Name := 'SkipCover';
Caption := 'No cover image';
Left:=94;
Top:=0;
TabOrder := 2;
Width:=120;
Parent:=FChecksPanel;
end;
SkipDescr:=TCheckBox.Create(Self);
With SkipDescr do Begin
Name := 'SkipDescr';
Caption := 'Skip description';
Left:=214;
Top:=0;
TabOrder := 3;
Width:=180;
Parent:=FChecksPanel;
end;
EncCompat:=TCheckBox.Create(Self);
With EncCompat do Begin
Name := 'EncCompat';
Caption := 'Compatible encoding';
Left:=340;
Top:=0;
TabOrder := 4;
Width:=180;
Parent:=FChecksPanel;
end;
ImgCompat:=TCheckBox.Create(Self);
With ImgCompat do Begin
Name := 'ImgCompat';
Caption := 'Compatible images';
Left:=500;
Top:=0;
TabOrder := 4;
Width:=180;
Parent:=FChecksPanel;
end;
end;
Reg:=TRegistry.Create(KEY_READ);
Try
Try
if Reg.OpenKeyReadOnly(RegistryKey) then
Begin
SkipImages.Checked:=Reg.ReadBool('Skip images');
SkipCover.Checked:=Reg.ReadBool('Skip cover');
SkipDescr.Checked:=Reg.ReadBool('Skip description');
EncCompat.Checked:=Reg.ReadBool('Encoding compat');
ImgCompat.Checked:=Reg.ReadBool('Image compat');
OnImgClick(SkipImages);
end;
Finally
Reg.Free;
end;
Except
end;
Filter:='Rich text files (*.rtf)|*.rtf|All files (*.*)|*.*';
Title:='FB2 to rtf v0.11 by GribUser';
DefaultExt:='rtf';
end;
procedure TOpenPictureDialog.DoShow;
var
PreviewRect, StaticRect: TRect;
begin
GetClientRect(Handle, PreviewRect);
StaticRect := GetStaticRect;
{ Move preview area to right of static area }
PreviewRect.Top:= StaticRect.Top + (StaticRect.Bottom - StaticRect.Top);
Inc(PreviewRect.Left, 10);
FChecksPanel.BoundsRect := PreviewRect;
// FPreviewButton.Left := FPaintPanel.BoundsRect.Right - FPreviewButton.Width - 2;
// FImageCtrl.Picture := nil;
// FSavedFilename := '';
// FPaintPanel.Caption := srNone;
FChecksPanel.ParentWindow := Handle;
inherited DoShow;
end;
procedure TOpenPictureDialog.DoClose;
begin
inherited DoClose;
{ Hide any hint windows left behind }
Application.HideHint;
end;
function TOpenPictureDialog.Execute;
Var
Reg:TRegistry;
begin
Template := 'DLGTEMPLATE2';
Options:=[ofOverwritePrompt,ofEnableSizing];
Result := inherited Execute;
if Result then
Begin
Reg:=TRegistry.Create(KEY_ALL_ACCESS);
Try
if Reg.OpenKey(RegistryKey,True) then
Begin
Reg.WriteBool('Skip images',SkipImages.Checked);
Reg.WriteBool('Skip cover',SkipCover.Checked);
Reg.WriteBool('Skip description',SkipDescr.Checked);
Reg.WriteBool('Encoding compat',EncCompat.Checked);
Reg.WriteBool('Image compat',ImgCompat.Checked);
end;
Finally
Reg.Free;
end;
end;
end;
end.
|
unit IdHeaderCoderPlain;
interface
{$i IdCompilerDefines.inc}
uses
IdGlobal, IdHeaderCoderBase;
type
TIdHeaderCoderPlain = class(TIdHeaderCoder)
public
class function Decode(const ACharSet: string; const AData: TIdBytes): String; override;
class function Encode(const ACharSet, AData: String): TIdBytes; override;
class function CanHandle(const ACharSet: String): Boolean; override;
end;
// RLebeau 4/17/10: this forces C++Builder to link to this unit so
// RegisterHeaderCoder can be called correctly at program startup...
(*$HPPEMIT '#pragma link "IdHeaderCoderPlain"'*)
implementation
uses
SysUtils;
class function TIdHeaderCoderPlain.Decode(const ACharSet: string; const AData: TIdBytes): String;
begin
Result := BytesToStringRaw(AData);
end;
class function TIdHeaderCoderPlain.Encode(const ACharSet, AData: String): TIdBytes;
begin
Result := ToBytes(AData, Indy8BitEncoding);
end;
class function TIdHeaderCoderPlain.CanHandle(const ACharSet: String): Boolean;
begin
Result := TextStartsWith(ACharSet, 'ISO'); {do not localize}
if Result then begin
// 'ISO-2022-JP' is handled by TIdHeaderCoder2022JP
Result := not TextIsSame(ACharSet, 'ISO-2022-JP'); {do not localize}
Exit;
end;
if not Result then begin
Result := TextStartsWith(ACharSet, 'WINDOWS'); {do not localize}
if not Result then begin
Result := TextStartsWith(ACharSet, 'KOI8'); {do not localize}
if not Result then begin
Result := TextStartsWith(ACharSet, 'GB2312'); {do not localize}
if not Result then begin
Result := TextIsSame(ACharSet, 'US-ASCII');
end;
end;
end;
end;
end;
initialization
RegisterHeaderCoder(TIdHeaderCoderPlain);
finalization
UnregisterHeaderCoder(TIdHeaderCoderPlain);
end.
|
unit uGame;
interface
uses
glr_core,
uPlayer,
uGUI;
type
{ TGame }
TGame = class (TglrGame)
protected
Gui: TArenaGUIManager;
Player: TArenaPlayer;
public
procedure OnFinish; override;
procedure OnInput(Event: PglrInputEvent); override;
procedure OnPause; override;
procedure OnRender; override;
procedure OnResize(aNewWidth, aNewHeight: Integer); override;
procedure OnResume; override;
procedure OnStart; override;
procedure OnUpdate(const dt: Double); override;
end;
var
Game: TGame;
implementation
uses
glr_render,
glr_math,
uAssets,
uColors;
{ TGame }
procedure TGame.OnStart;
begin
Render.SetClearColor(Colors.Background);
Assets := TArenaAssets.Create();
Assets.Init();
Gui := TArenaGUIManager.Create();
Gui.Init();
Player := TArenaPlayer.Create();
Player.Spawn(Vec3f(0, 0, 3));
end;
procedure TGame.OnFinish;
begin
Player.Free();
Gui.DeInit();
Gui.Free();
Assets.DeInit();
Assets.Free();
end;
procedure TGame.OnInput(Event: PglrInputEvent);
begin
if (Player <> nil) then
Player.OnInputReceived(Event);
// Calls when engine receives some input info
end;
procedure TGame.OnUpdate(const dt: Double);
begin
Player.Update(dt);
Gui.Update(dt);
end;
procedure TGame.OnRender;
begin
Assets.MainCamera.Update();
Assets.MainMaterial.Bind();
Assets.SpriteBatch.Start();
Player.Render(Assets.SpriteBatch);
Assets.SpriteBatch.Finish();
Gui.Render();
end;
procedure TGame.OnPause;
begin
// Calls when app' window has lost focus
end;
procedure TGame.OnResume;
begin
// Calls when app' window was focused
end;
procedure TGame.OnResize(aNewWidth, aNewHeight: Integer);
begin
// Calls when window has changed size
end;
end.
|
unit uOrcamentoVO;
interface
uses
System.SysUtils, uOrcamentoItemVO, uOrcamentoItemModuloVO, uOrcamentoOcorrenciaVO,
uOrcamentoVectoVO, System.Generics.Collections,
uClassValidacao, uOrcamentoEmailVO, uKeyField, uTableName, uUsuarioVO, uTipo,
uTipoVO, uClienteVO, uContatoVO;
type
[TableName('Orcamento')]
TOrcamentoVO = class
private
FObservacao: string;
FIdProspect: Integer;
FObservacaoEmail: string;
FIdUsuario: Integer;
FId: Integer;
FNumero: Integer;
FData: TDate;
FOrcamentoItemModulo: TObjectList<TOrcamentoItemModuloVO>;
FOrcamentoOcorrencia: TObjectList<TOrcamentoOcorrenciaVO>;
FOrcamentoItem: TObjectList<TOrcamentoItemVO>;
FOrcamentoVecto: TObjectList<TOrcamentoVectoVO>;
FIdCliente: Integer;
FSituacao: Integer;
FIdFormaPagto: Integer;
FFantasia: string;
FCnpjCpf: string;
FRazaoSocial: string;
FContato: string;
FEndereco: string;
FTelefone: string;
FOrcamentoEmail: TObjectList<TOrcamentoEmailVO>;
FUsuario: TUsuarioVO;
FIdTipo: Integer;
FTipo: TTipoVO;
FSituacaoDescricao: string;
FTotalOrcamento: Currency;
FTotalMensalidade: Currency;
FEmailEnviado: Boolean;
FSubTipo: Integer;
FDataSituacao: TDate;
FLogradouro: string;
FBairro: string;
FContatoCompraVendaFone: string;
FContatoCompraVenda: string;
FContatoFinanceiroFone: string;
FContatoFinanceiro: string;
FIdCidade: Integer;
FRepresentanteLegalCPF: string;
FRepresentanteLegal: string;
FCEP: string;
FIE: string;
FFone2: string;
FFoneOutro: string;
FFone1: string;
FCelular: string;
FCliente: TClienteVO;
FEnquadramento: string;
FListaContato: TObjectList<TContatoVO>;
procedure SetData(const Value: TDate);
procedure SetId(const Value: Integer);
procedure SetIdProspect(const Value: Integer);
procedure SetIdUsuario(const Value: Integer);
procedure SetNumero(const Value: Integer);
procedure SetObservacao(const Value: string);
procedure SetObservacaoEmail(const Value: string);
procedure SetOrcamentoOcorrencia(const Value: TObjectList<TOrcamentoOcorrenciaVO>);
procedure SetOrcamentoItem(const Value: TObjectList<TOrcamentoItemVO>);
procedure SetOrcamentoItemModulo(
const Value: TObjectList<TOrcamentoItemModuloVO>);
procedure SetOrcamentoVecto(const Value: TObjectList<TOrcamentoVectoVO>);
function GetTotalLiquido: Currency;
function GetTotalParcelas: Currency;
procedure SetIdCliente(const Value: Integer);
procedure SetSituacao(const Value: Integer);
procedure SetIdFormaPagto(const Value: Integer);
procedure SetCnpjCpf(const Value: string);
procedure SetContato(const Value: string);
procedure SetEndereco(const Value: string);
procedure SetFantasia(const Value: string);
procedure SetRazaoSocial(const Value: string);
procedure SetTelefone(const Value: string);
procedure SetOrcamentoEmail(const Value: TObjectList<TOrcamentoEmailVO>);
procedure SetUsuario(const Value: TUsuarioVO);
procedure SetIdTipo(const Value: Integer);
procedure SetTipo(const Value: TTipoVO);
procedure SetSituacaoDescricao(const Value: string);
procedure SetTotalMensalidade(const Value: Currency);
procedure SetTotalOrcamento(const Value: Currency);
procedure SetEmailEnviado(const Value: Boolean);
procedure SetSubTipo(const Value: Integer);
procedure SetDataSituacao(const Value: TDate);
procedure SetBairro(const Value: string);
procedure SetCelular(const Value: string);
procedure SetCEP(const Value: string);
procedure SetContatoCompraVenda(const Value: string);
procedure SetContatoCompraVendaFone(const Value: string);
procedure SetContatoFinanceiro(const Value: string);
procedure SetContatoFinanceiroFone(const Value: string);
procedure SetFone1(const Value: string);
procedure SetFone2(const Value: string);
procedure SetFoneOutro(const Value: string);
procedure SetIdCidade(const Value: Integer);
procedure SetIE(const Value: string);
procedure SetLogradouro(const Value: string);
procedure SetRepresentanteLegal(const Value: string);
procedure SetRepresentanteLegalCPF(const Value: string);
procedure SetCliente(const Value: TClienteVO);
procedure SetEnquadramento(const Value: string);
procedure SetListaContato(const Value: TObjectList<TContatoVO>);
public
[KeyField('Orc_Id')]
property Id: Integer read FId write SetId;
[FieldName('Orc_Numero')]
property Numero: Integer read FNumero write SetNumero;
[FieldName('Orc_Data')]
property Data: TDate read FData write SetData;
[FieldName('Orc_Usuario')]
property IdUsuario: Integer read FIdUsuario write SetIdUsuario;
[FieldNull('Orc_Prospect')]
property IdProspect: Integer read FIdProspect write SetIdProspect;
[FieldNull('Orc_Cliente')]
property IdCliente: Integer read FIdCliente write SetIdCliente;
[FieldName('Orc_Observacao')]
property Observacao: string read FObservacao write SetObservacao;
[FieldName('Orc_ObservacaoEmail')]
property ObservacaoEmail: string read FObservacaoEmail write SetObservacaoEmail;
[FieldName('Orc_Situacao')]
property Situacao: Integer read FSituacao write SetSituacao;
[FieldNull('Orc_FormaPagto')]
property IdFormaPagto: Integer read FIdFormaPagto write SetIdFormaPagto;
[FieldName('Orc_RazaoSocial')]
property RazaoSocial: string read FRazaoSocial write SetRazaoSocial;
[FieldName('Orc_Fantasia')]
property Fantasia: string read FFantasia write SetFantasia;
[FieldName('Orc_Endereco')]
property Endereco: string read FEndereco write SetEndereco;
[FieldName('Orc_Telefone')]
property Telefone: string read FTelefone write SetTelefone;
[FieldName('Orc_Contato')]
property Contato: string read FContato write SetContato;
[FieldName('Orc_Dcto')]
property CnpjCpf: string read FCnpjCpf write SetCnpjCpf;
[ForeignFey('Orc_Usuario')]
property Usuario: TUsuarioVO read FUsuario write SetUsuario;
[FieldNull('Orc_Tipo')]
property IdTipo: Integer read FIdTipo write SetIdTipo;
[FieldNull('Orc_SubTipo')]
property SubTipo: Integer read FSubTipo write SetSubTipo;
[FieldNull('Orc_EmailEnviado')]
property EmailEnviado: Boolean read FEmailEnviado write SetEmailEnviado;
[FieldName('Orc_DataSituacao')]
property DataSituacao: TDate read FDataSituacao write SetDataSituacao;
[FieldName('Orc_Logradouro')]
property Logradouro: string read FLogradouro write SetLogradouro;
[FieldName('Orc_Bairro')]
property Bairro: string read FBairro write SetBairro;
[FieldName('Orc_CEP')]
property CEP: string read FCEP write SetCEP;
[FieldNull('Orc_Cidade')]
property IdCidade: Integer read FIdCidade write SetIdCidade;
[FieldName('Orc_Fone1')]
property Fone1: string read FFone1 write SetFone1;
[FieldName('Orc_Fone2')]
property Fone2: string read FFone2 write SetFone2;
[FieldName('Orc_Celular')]
property Celular: string read FCelular write SetCelular;
[FieldName('Orc_FoneOutro')]
property FoneOutro: string read FFoneOutro write SetFoneOutro;
[FieldName('Orc_ContatoFinanceiro')]
property ContatoFinanceiro: string read FContatoFinanceiro write SetContatoFinanceiro;
[FieldName('Orc_ContatoFinanceiroFone')]
property ContatoFinanceiroFone: string read FContatoFinanceiroFone write SetContatoFinanceiroFone;
[FieldName('Orc_ContatoCompraVenda')]
property ContatoCompraVenda: string read FContatoCompraVenda write SetContatoCompraVenda;
[FieldName('Orc_ContatoCompraVendaFone')]
property ContatoCompraVendaFone: string read FContatoCompraVendaFone write SetContatoCompraVendaFone;
[FieldName('Orc_IE')]
property IE: string read FIE write SetIE;
[FieldName('Orc_RepreLegal')]
property RepresentanteLegal: string read FRepresentanteLegal write SetRepresentanteLegal;
[FieldName('Orc_RepreLegalCPF')]
property RepresentanteLegalCPF: string read FRepresentanteLegalCPF write SetRepresentanteLegalCPF;
[FieldName('Orc_Enquadramento')]
property Enquadramento: string read FEnquadramento write SetEnquadramento;
property SituacaoDescricao: string read FSituacaoDescricao write SetSituacaoDescricao;
property Tipo: TTipoVO read FTipo write SetTipo;
property TotalOrcamento: Currency read FTotalOrcamento write SetTotalOrcamento;
property TotalMensalidade: Currency read FTotalMensalidade write SetTotalMensalidade;
property TotalLiquido: Currency read GetTotalLiquido;
property TotalParcelas: Currency read GetTotalParcelas;
property OrcamentoItem: TObjectList<TOrcamentoItemVO> read FOrcamentoItem write SetOrcamentoItem;
property OrcamentoItemModulo: TObjectList<TOrcamentoItemModuloVO> read FOrcamentoItemModulo write SetOrcamentoItemModulo;
property OrcamentoOcorrencia: TObjectList<TOrcamentoOcorrenciaVO> read FOrcamentoOcorrencia write SetOrcamentoOcorrencia;
property OrcamentoVecto: TObjectList<TOrcamentoVectoVO> read FOrcamentoVecto write SetOrcamentoVecto;
Property OrcamentoEmail: TObjectList<TOrcamentoEmailVO> read FOrcamentoEmail write SetOrcamentoEmail;
property Cliente: TClienteVO read FCliente write SetCliente;
property ListaContato: TObjectList<TContatoVO> read FListaContato write SetListaContato;
constructor create;
destructor destroy; override;
end;
TListaOrcamento = TObjectList<TOrcamentoVO>;
implementation
{ TOrcamentoVO }
constructor TOrcamentoVO.create;
begin
inherited create;
FOrcamentoItem := TObjectList<TOrcamentoItemVO>.Create;
FOrcamentoItemModulo := TObjectList<TOrcamentoItemModuloVO>.Create;
FOrcamentoOcorrencia := TObjectList<TOrcamentoOcorrenciaVO>.Create;
FOrcamentoVecto := TObjectList<TOrcamentoVectoVO>.Create;
FOrcamentoEmail := TObjectList<TOrcamentoEmailVO>.Create;
FListaContato := TObjectList<TContatoVO>.Create;
FUsuario := TUsuarioVO.Create;
FTipo := TTipoVO.Create;
FCliente := TClienteVO.create;
end;
destructor TOrcamentoVO.destroy;
begin
FreeAndNil(FOrcamentoItem);
FreeAndNil(FOrcamentoItemModulo);
FreeAndNil(FOrcamentoOcorrencia);
FreeAndNil(FOrcamentoVecto);
FreeAndNil(FOrcamentoEmail);
FreeAndNil(FListaContato);
FreeAndNil(FUsuario);
FreeAndNil(FTipo);
FreeAndNil(FCliente);
inherited;
end;
function TOrcamentoVO.GetTotalLiquido: Currency;
var
Item: TOrcamentoItemVO;
begin
Result := 0;
for Item in OrcamentoItem do
Result := Result + (Item.ValorLicencaImpl - Item.ValorDescImpl);
end;
function TOrcamentoVO.GetTotalParcelas: Currency;
var
Item: TOrcamentoVectoVO;
begin
Result := 0;
for Item in OrcamentoVecto do
Result := Result + Item.Valor;
end;
procedure TOrcamentoVO.SetBairro(const Value: string);
begin
FBairro := Value;
end;
procedure TOrcamentoVO.SetCelular(const Value: string);
begin
FCelular := Value;
end;
procedure TOrcamentoVO.SetCEP(const Value: string);
begin
FCEP := Value;
end;
procedure TOrcamentoVO.SetCliente(const Value: TClienteVO);
begin
FCliente := Value;
end;
procedure TOrcamentoVO.SetCnpjCpf(const Value: string);
begin
FCnpjCpf := Value;
end;
procedure TOrcamentoVO.SetContato(const Value: string);
begin
FContato := Value;
end;
procedure TOrcamentoVO.SetContatoCompraVenda(const Value: string);
begin
FContatoCompraVenda := Value;
end;
procedure TOrcamentoVO.SetContatoCompraVendaFone(const Value: string);
begin
FContatoCompraVendaFone := Value;
end;
procedure TOrcamentoVO.SetContatoFinanceiro(const Value: string);
begin
FContatoFinanceiro := Value;
end;
procedure TOrcamentoVO.SetContatoFinanceiroFone(const Value: string);
begin
FContatoFinanceiroFone := Value;
end;
procedure TOrcamentoVO.SetData(const Value: TDate);
begin
FData := Value;
end;
procedure TOrcamentoVO.SetDataSituacao(const Value: TDate);
begin
FDataSituacao := Value;
end;
procedure TOrcamentoVO.SetEmailEnviado(const Value: Boolean);
begin
FEmailEnviado := Value;
end;
procedure TOrcamentoVO.SetEndereco(const Value: string);
begin
FEndereco := Value;
end;
procedure TOrcamentoVO.SetEnquadramento(const Value: string);
begin
FEnquadramento := Value;
end;
procedure TOrcamentoVO.SetFantasia(const Value: string);
begin
FFantasia := Value;
end;
procedure TOrcamentoVO.SetFone1(const Value: string);
begin
FFone1 := Value;
end;
procedure TOrcamentoVO.SetFone2(const Value: string);
begin
FFone2 := Value;
end;
procedure TOrcamentoVO.SetFoneOutro(const Value: string);
begin
FFoneOutro := Value;
end;
procedure TOrcamentoVO.SetId(const Value: Integer);
begin
FId := Value;
end;
procedure TOrcamentoVO.SetIdCidade(const Value: Integer);
begin
FIdCidade := Value;
end;
procedure TOrcamentoVO.SetIdCliente(const Value: Integer);
begin
FIdCliente := Value;
end;
procedure TOrcamentoVO.SetIdFormaPagto(const Value: Integer);
begin
FIdFormaPagto := Value;
end;
procedure TOrcamentoVO.SetIdProspect(const Value: Integer);
begin
FIdProspect := Value;
end;
procedure TOrcamentoVO.SetIdTipo(const Value: Integer);
begin
FIdTipo := Value;
end;
procedure TOrcamentoVO.SetIdUsuario(const Value: Integer);
begin
FIdUsuario := Value;
end;
procedure TOrcamentoVO.SetIE(const Value: string);
begin
FIE := Value;
end;
procedure TOrcamentoVO.SetListaContato(const Value: TObjectList<TContatoVO>);
begin
FListaContato := Value;
end;
procedure TOrcamentoVO.SetLogradouro(const Value: string);
begin
FLogradouro := Value;
end;
procedure TOrcamentoVO.SetNumero(const Value: Integer);
begin
FNumero := Value;
end;
procedure TOrcamentoVO.SetObservacao(const Value: string);
begin
FObservacao := Value;
end;
procedure TOrcamentoVO.SetObservacaoEmail(const Value: string);
begin
FObservacaoEmail := Value;
end;
procedure TOrcamentoVO.SetOrcamentoEmail(
const Value: TObjectList<TOrcamentoEmailVO>);
begin
FOrcamentoEmail := Value;
end;
procedure TOrcamentoVO.SetOrcamentoItem(
const Value: TObjectList<TOrcamentoItemVO>);
begin
FOrcamentoItem := Value;
end;
procedure TOrcamentoVO.SetOrcamentoItemModulo(
const Value: TObjectList<TOrcamentoItemModuloVO>);
begin
FOrcamentoItemModulo := Value;
end;
procedure TOrcamentoVO.SetOrcamentoOcorrencia(
const Value: TObjectList<TOrcamentoOcorrenciaVO>);
begin
FOrcamentoOcorrencia := Value;
end;
procedure TOrcamentoVO.SetOrcamentoVecto(
const Value: TObjectList<TOrcamentoVectoVO>);
begin
FOrcamentoVecto := Value;
end;
procedure TOrcamentoVO.SetRazaoSocial(const Value: string);
begin
FRazaoSocial := Value;
end;
procedure TOrcamentoVO.SetRepresentanteLegal(const Value: string);
begin
FRepresentanteLegal := Value;
end;
procedure TOrcamentoVO.SetRepresentanteLegalCPF(const Value: string);
begin
FRepresentanteLegalCPF := Value;
end;
procedure TOrcamentoVO.SetSituacao(const Value: Integer);
begin
// 1 - Em Analise
// 2 - Aprovado
// 3 - Não Aprovado
if Value in [1, 2, 3, 4] then
FSituacao := Value
else
FSituacao := 1;
end;
procedure TOrcamentoVO.SetSituacaoDescricao(const Value: string);
begin
FSituacaoDescricao := Value;
end;
procedure TOrcamentoVO.SetSubTipo(const Value: Integer);
begin
FSubTipo := Value;
end;
procedure TOrcamentoVO.SetTelefone(const Value: string);
begin
FTelefone := Value;
end;
procedure TOrcamentoVO.SetTipo(const Value: TTipoVO);
begin
FTipo := Value;
end;
procedure TOrcamentoVO.SetTotalMensalidade(const Value: Currency);
begin
FTotalMensalidade := Value;
end;
procedure TOrcamentoVO.SetTotalOrcamento(const Value: Currency);
begin
FTotalOrcamento := Value;
end;
procedure TOrcamentoVO.SetUsuario(const Value: TUsuarioVO);
begin
FUsuario := Value;
end;
end.
|
unit timer_engine;
interface
uses dialogs;
const
MAX_TIMERS=14;
type
exec_type_param=procedure(param0:byte);
exec_type_simple=procedure;
ttimers=record
execute_param:exec_type_param; //call function
execute_simple:exec_type_simple; //sound call function
time_final:single; //Final time to call function
actual_time:single; //Actual time
cpu:byte; //CPU asociada al timer y dispositivo asociado
enabled:boolean; // Running?
param0:byte; //Parametros
end;
tautofire_proc=procedure(autofire_index:byte;autofire_status:boolean);
timer_eng=class
constructor create;
destructor free;
public
timer:array[0..MAX_TIMERS] of ttimers;
autofire_timer:byte;
autofire_on:boolean;
autofire_status,autofire_enabled:array [0..11] of boolean;
function init(cpu:byte;time:single;exec_simple:exec_type_simple;exec_param:exec_type_param;ena:boolean;param0:byte=0):byte;
procedure update(time_add:word;cpu:byte);
procedure enabled(timer_num:byte;state:boolean);
procedure reset(timer_num:byte);
procedure clear;
procedure autofire_init;
private
timer_count:integer;
end;
var
timers:timer_eng;
implementation
uses controls_engine,cpu_misc,main_engine;
procedure auto_fire;
begin
//P1
if timers.autofire_enabled[0] then begin
if timers.autofire_status[0] then arcade_input.but0[0]:=not(arcade_input.but0[0])
else arcade_input.but0[0]:=false;
event.arcade:=true;
end;
if timers.autofire_enabled[1] then begin
if timers.autofire_status[1] then arcade_input.but1[0]:=not(arcade_input.but1[0])
else arcade_input.but1[0]:=false;
event.arcade:=true;
end;
if timers.autofire_enabled[2] then begin
if timers.autofire_status[2] then arcade_input.but2[0]:=not(arcade_input.but2[0])
else arcade_input.but2[0]:=false;
event.arcade:=true;
end;
if timers.autofire_enabled[3] then begin
if timers.autofire_status[3] then arcade_input.but3[0]:=not(arcade_input.but3[0])
else arcade_input.but3[0]:=false;
event.arcade:=true;
end;
if timers.autofire_enabled[4] then begin
if timers.autofire_status[4] then arcade_input.but4[0]:=not(arcade_input.but4[0])
else arcade_input.but4[0]:=false;
event.arcade:=true;
end;
if timers.autofire_enabled[5] then begin
if timers.autofire_status[5] then arcade_input.but5[0]:=not(arcade_input.but5[0])
else arcade_input.but5[0]:=false;
event.arcade:=true;
end;
//P2
if timers.autofire_enabled[6] then begin
if timers.autofire_status[6] then arcade_input.but0[1]:=not(arcade_input.but0[1])
else arcade_input.but0[1]:=false;
event.arcade:=true;
end;
if timers.autofire_enabled[7] then begin
if timers.autofire_status[7] then arcade_input.but1[1]:=not(arcade_input.but1[1])
else arcade_input.but1[1]:=false;
event.arcade:=true;
end;
if timers.autofire_enabled[8] then begin
if timers.autofire_status[8] then arcade_input.but2[1]:=not(arcade_input.but2[1])
else arcade_input.but2[1]:=false;
event.arcade:=true;
end;
if timers.autofire_enabled[9] then begin
if timers.autofire_status[9] then arcade_input.but3[1]:=not(arcade_input.but3[1])
else arcade_input.but3[1]:=false;
event.arcade:=true;
end;
if timers.autofire_enabled[10] then begin
if timers.autofire_status[10] then arcade_input.but4[1]:=not(arcade_input.but4[1])
else arcade_input.but4[1]:=false;
event.arcade:=true;
end;
if timers.autofire_enabled[11] then begin
if timers.autofire_status[11] then arcade_input.but5[1]:=not(arcade_input.but5[1])
else arcade_input.but5[1]:=false;
event.arcade:=true;
end;
end;
constructor timer_eng.create;
begin
self.clear;
end;
destructor timer_eng.free;
begin
end;
procedure timer_eng.autofire_init;
begin
self.autofire_timer:=self.init(cpu_info[0].num_cpu,1,auto_fire,nil,timers.autofire_on);
self.timer[self.autofire_timer].time_final:=cpu_info[0].clock/1000;
end;
function timer_eng.init(cpu:byte;time:single;exec_simple:exec_type_simple;exec_param:exec_type_param;ena:boolean;param0:byte=0):byte;
begin
self.timer_count:=self.timer_count+1;
if self.timer_count=MAX_TIMERS then MessageDlg('Superados el maximo de timer', mtInformation,[mbOk], 0);
self.timer[self.timer_count].cpu:=cpu;
self.timer[self.timer_count].time_final:=time;
self.timer[self.timer_count].execute_param:=exec_param;
self.timer[self.timer_count].execute_simple:=exec_simple;
self.timer[self.timer_count].enabled:=ena;
self.timer[self.timer_count].param0:=param0;
init:=self.timer_count;
end;
procedure timer_eng.update(time_add:word;cpu:byte);
var
f:integer;
begin
for f:=self.timer_count downto 0 do begin
if (self.timer[f].enabled and (cpu=self.timer[f].cpu)) then begin
self.timer[f].actual_time:=self.timer[f].actual_time+time_add;
//Atencion!!! si desactivo el timer dentro de la funcion, ya no tiene que hacer nada!
while ((self.timer[f].actual_time>=self.timer[f].time_final) and self.timer[f].enabled) do begin
if @self.timer[f].execute_simple<>nil then self.timer[f].execute_simple
else self.timer[f].execute_param(self.timer[f].param0);
self.timer[f].actual_time:=self.timer[f].actual_time-self.timer[f].time_final;
end;
end;
end;
end;
procedure timer_eng.enabled(timer_num:byte;state:boolean);
begin
//Esto le sienta mal a Jackal!!!
//if (state and not(self.timer[timer_num].enabled)) then self.timer[timer_num].actual_time:=0;
self.timer[timer_num].enabled:=state;
end;
procedure timer_eng.clear;
var
f:byte;
begin
self.timer_count:=-1;
for f:=0 to MAX_TIMERS do begin
self.timer[f].time_final:=0;
self.timer[f].actual_time:=0;
self.timer[f].execute_param:=nil;
self.timer[f].execute_simple:=nil;
self.timer[f].cpu:=0;
self.timer[f].enabled:=false;
end;
for f:=0 to 11 do autofire_status[f]:=false;
end;
procedure timer_eng.reset(timer_num:byte);
begin
self.timer[timer_num].actual_time:=0;
end;
end.
|
unit Protocol;
interface
type
TVisualClassId = word;
TCompanyId = word;
const
NullObject = 0;
const
MapChunkSize = 64;
const
RepSeparator = ':';
ScopeSeparator = '::';
StatusTextSeparator = ':-:';
LineBreak = #13#10;
TabSpace = #9;
const
BINSignature : word = $F0F0;
// Error codes
const
NOERROR = 0;
ERROR_Unknown = 1;
ERROR_CannotInstantiate = 2;
ERROR_AreaNotClear = 3;
ERROR_UnknownClass = 4;
ERROR_UnknownCompany = 5;
ERROR_UnknownCluster = 6;
ERROR_UnknownTycoon = 7;
ERROR_CannotCreateTycoon = 8;
ERROR_FacilityNotFound = 9;
ERROR_TycoonNameNotUnique = 10;
ERROR_CompanyNameNotUnique = 11;
ERROR_InvalidUserName = 12;
ERROR_InvalidPassword = 13;
ERROR_InvalidCompanyId = 14;
ERROR_AccessDenied = 15;
ERROR_CannotSetupEvents = 16;
ERROR_AccountActive = 17;
ERROR_AccountDisabled = 18;
ERROR_InvalidLogonData = 19;
ERROR_ModelServerIsDown = 20;
ERROR_UnknownCircuit = 21;
ERROR_CannotCreateSeg = 22;
ERROR_CannotBreakSeg = 23;
ERROR_LoanNotGranted = 24;
ERROR_InvalidMoneyValue = 25;
ERROR_InvalidProxy = 26;
ERROR_RequestDenied = 27;
ERROR_ZoneMissmatch = 28;
ERROR_InvalidParameter = 29;
ERROR_InsuficientSpace = 30;
ERROR_CannotRegisterEvents = 31;
ERROR_NotEnoughRoom = 32;
ERROR_TooManyFacilities = 33;
ERROR_BuildingTooClose = 34;
// Politics errors
ERROR_POLITICS_NOTALLOWED = 100;
ERROR_POLITICS_REJECTED = 101;
ERROR_POLITICS_NOTIME = 102;
// Logon Error
ERROR_AccountAlreadyExists = 110;
ERROR_UnexistingAccount = 112;
ERROR_SerialMaxed = 113;
ERROR_InvalidSerial = 114;
ERROR_SubscriberIdNotFound = 115;
// Account status
const
ACCOUNT_Valid = 0;
ACCOUNT_UnknownError = 1;
ACCOUNT_Unexisting = 2;
ACCOUNT_InvalidName = 3;
ACCOUNT_InvalidPassword = 4;
ACCOUNT_Forbiden = 5;
// Supported circuits identifiers
const
cirRoads = 1;
cirRailRoads = 2;
// Actor pools
const
poolIdTrains = 1;
poolTrainsInterval = 1000;
// RDO Hooks
const
tidRDOHook_InterfaceServer = 'InterfaceServer';
tidRDOHook_NewsServer = 'NewsServer';
tidRDOHook_InterfaceEvents = 'InterfaceEvents';
tidRDOHook_Trains = 'Trains';
const
tidLastViewX = 'LastX.';
tidLastViewY = 'LastY.';
type
TStatusKind = (sttMain, sttSecondary, sttHint);
TFacilityChange = (fchStatus, fchStructure, fchDestruction);
TUserListChange = (uchInclusion, uchExclusion);
TMsgCompositionState = (mstIdle, mstComposing, mstAFK);
TCargoKind = (carPeople, carLight, carHeavy);
TErrorCode = integer;
const
CompositionTimeOut = 10000;
// IRDOInterfaceServerEvents
// -------------------------
//
// Client events interface (method implementation MUST be published)
// The following interface, IRDOInterfaceServerEvents, can be used to enforce
// the existence of these methods in the object registered under the
// tidRDOHook_InterfaceEvents hook.
//
// procedure InitClient( Date : TDateTime; Money : widestring; FailureLevel : integer );
// :: This is called by the IS after a succesfull log on to initialize data in
// the client. Date is the current (virtual) date, Money the current budget
// of the user and FailureLevel and indicator of bankrupcy (0-Normal, 1-Warning,
// 2-ALERT!)
//
// procedure RefreshArea( x, y, dx, dy : integer );
// :: This is called by the IS to refresh some dirty area in the map.
//
// procedure RefreshObject( ObjId, KindOfChange : integer );
// :: Indicates that the focused object ObjId has been modified so its image
// in the client must be updated. KindOfChange is a TFacilityChange.
//
// procedure RefreshTycoon( Money : widestring );
// :: The user (or tycoon) data was modified.
//
// procedure RefreshDate( Date : TDateTime );
// :: Virtual date changed.
//
// procedure EndOfPeriod( FailureLevel : integer );
// :: Indicates the conclusion of an economic period. Tax collection and other
// events occur then. FailureLevel must be updated (see InitClient)
//
// procedure TycoonRetired( FailureLevel : integer );
// :: Notifies the user that he or she was widthdrawn from the game. That is,
// when he or she loses the game.
//
// procedure ChatMsg( From, Msg : widestring );
// :: A chat msg was received. From is the name of the user the message comes
// from. Msg is the message itself.
//
// procedure MoveTo( x, y : integer );
// :: The IS commands the client to display the cell (x, y).
//
// procedure NotifyCompanionship( Names : widestring );
// :: The IS notifies a change in the Companionship list. Companionship are viewing
// the same area (or part of it) in the map. The list uses #13#10 as separators.
// Notification Kinds
const
ntkMessageBox = 0;
ntkURLFrame = 1;
ntkChatMessage = 2;
ntkSound = 3;
ntkGenericEvent = 4;
const
gevnId_RefreshBuildPage = 1;
// Model status
const
mstBusy = $00000001;
mstNotBusy = $00000002;
mstError = $00000004;
type
IRDOInterfaceServerEvents =
interface
procedure InitClient( Date : TDateTime; Money : widestring; FailureLevel, TycoonId : integer );
procedure RefreshArea( x, y, dx, dy : integer; ExtraInfo : widestring );
procedure RefreshObject( ObjId, KindOfChange : integer; ExtraInfo : widestring );
procedure RefreshTycoon( Money, NetProfit : widestring; Ranking, FacCount, FacMax : integer );
procedure RefreshDate( Date : TDateTime );
procedure RefreshSeason( Season : integer );
procedure EndOfPeriod( FailureLevel : integer );
procedure TycoonRetired( FailureLevel : integer );
procedure ChatMsg( From, Msg : widestring );
procedure VoiceMsg( From, Msg : widestring; TxId, NewTx : integer );
procedure VoiceRequestGranted( RequestId : integer );
procedure NewMail( MsgCount : integer );
procedure MoveTo( x, y : integer );
procedure NotifyCompanionship( Names : widestring );
procedure NotifyUserListChange( Name : widestring; Change : TUserListChange );
procedure NotifyChannelListChange( Name, Password : widestring; Change : TUserListChange );
procedure NotifyChannelChange( Name : widestring );
procedure NotifyMsgCompositionState( Name : widestring; State : TMsgCompositionState );
{$ifDef Train}
procedure ActorPoolModified( ActorPoolId : integer; Data : widestring );
{$endif}
procedure ShowNotification( Kind : integer; Title, Body : widestring; Options : integer );
procedure ModelStatusChanged( Status : integer );
function AnswerStatus : olevariant;
end;
// InterfaceServer
// ---------------
//
// The following properties and methods can be called via RDO to the Interface Server
// object (registered under tidRDOHook_InterfaceServer):
//
// property WorldName : string
// :: Contains the name of the world
//
// property WorldURL : string
// :: Base URL for this world. All relative URLs are completed by adding this
// string to the begining (no "/" is needed.)
//
// property WorldXSize : integer
// :: Width of the world, in ground cells.
//
// property WorldYSize : integer
// :: Height of the world, in ground cells.
//
// function AccountStatus( UserName, Password : widestring ) : OleVariant;
// :: Returns the account status (see ACCOUNT_XXXX)
//
// function Logon( UserName, Password : widestring ) : OleVariant;
// :: Logs on the user UserName. Returns an Id to a ClientView object.
//
// ClientView
// ----------
//
// For each client logged to the IS there is one ClientView object. The Id
// of the ClientView is obtained as a result of a call to the Logon function
// to the InterfaceServer object. The following properties and methods can
// be ivoked to a ClientView via RDO.
//
// property UserName : string
// :: Name that was used to log on.
//
// property x1, y1, x2, y2 : integer
// :: Portion of the map the client is currently viewing.
//
// procedure SetViewedArea( x, y, dx, dy : integer );
// :: Informs the ClientView that the Client has moved to a diferent location
// in the map. (x, y) is the origin of the viewport, (dx, dy) is its size.
//
// function ObjectsInArea( x, y, dx, dy : integer ) : OleVariant;
// :: Returns the objects that are in somre area of the map. The result is a
// widestring in the form:
//
// result = obj1 + #13#10 + obj2 + #13#10 + ... + objN
//
// where:
// obj1 = classId + #13#10 + companyId + #13#10 + xPos + #13#10 + yPos
//
// where:
// classId : integer(ASCII) :: Id of the visual class of the object
// companyId : integer(ASCII) :: Id of the company the object belongs to
// xPos : integer(ASCII) :: x coordinate of the object
// yPos : integer(ASCII) :: y coordinate of the object
//
// function ObjectAt( x, y : integer ) : OleVariant;
// :: Returns the object Id (integer) of the object at location (x, y).
//
// function ObjectStatusText( kind : TStatusKind; Id : TObjId ) : OleVariant;
// :: Returns the status text of the object specified in the Id parameter.
//
// procedure FocusObject( Id : TObjId );
// :: Focuses the object specified in the Id parameter. After calling FocusObject
// over one object, the RefreshObject event will occur every time the object is
// modified.
//
// procedure UnfocusObject( Id : TObjId );
// :: Removes the object from the focus list.
//
// function SwitchFocus( From : TObjId; toX, toY : integer ) : OleVariant;
// :: SwitchFocus encapsulates calls to ObjectAt, FocusObject and UnfocusObject
// in the server side. It can be replaced in the client side by:
//
// if Focus <> NullObject
// then ClientViewProxy.UnfocusObject( Focus );
// Focus := ClientViewProxy.ObjectAt( xTo, yTo );
// if Focus <> NullObject
// then ClientViewProxy.FocusObject( Focus );
//
// function GetCompanyList : OleVariant;
// :: Returns a widestring containing a list of the companies the user has.
// the result is in the form:
//
// '[' + Company1_Name + ',' + Company1_Id + ']' + ... + '[' + CompanyN_Name + ',' + CompanyN_Id + ']'
//
// where:
// Company_Name : string :: Readable name of the company.
// Company_Id : integer(ASCII) :: Id of the company (same as in ObjectsInArea)
//
// NOTE: An empty company list is '[]'
//
// function NewCompany( name, cluster : widestring ) : OleVariant;
// :: Creates a new company for the user. The result, if succesfull, is a company pair
// is same format as GetCompanyList.
//
// function NewFacility( FacilityId : widestring; CompanyId : integer; x, y : integer ) : OleVariant;
// :: Creates a new facility on the map. FacilityId is the MetaFacilityId (or ClassId)
// of the facility, CompanyId is the Id of the Company that owns the facility,
// x and y the position in the map. The result can be one of the following codes:
// NOERROR, ERROR_Unkbown, ERROR_AreaNotClear, ERROR_UnknownClass, ERROR_UnknownCompany.
//
// function SayThis( Dest, Msg : widestring ) : OleVariant;
// :: Sends a chat message to the users listed in Dest. Usernames must be sepparated
// by ';'. An empty Dest generates a message that is received by everyone.
//
// function Chase( UserName : widestring ) : OleVariant;
// :: Starts the chase of one user by linking the client's viewport to this user's
// viewport.
//
// function StopChase : OleVariant;
// :: Stops the chase.
//
// function RegisterEvents( ClientAddress : widestring; ClientPort : integer ) : OleVariant;
// :: Creates a proxy of the tidRDOHook_InterfaceEvents object running in the Client RDO
// server. ClientAddress and ClientPort are the ones of this RDO server.
//
// function Logoff : OleVariant;
// :: Logs off the user.
//
type
TSecurityId = string;
const
SecIdItemSeparator = '-';
function GrantAccess( RequesterId, SecurityId : TSecurityId ) : boolean;
// Building zones
const
tidSurface_Zones = 'ZONES';
tidSurface_Towns = 'TOWNS';
type
TZoneType = byte;
const
znNone = 0;
znReserved = 1;
znResidential = 2;
znHiResidential = 3;
znMidResidential = 4;
znLoResidential = 5;
znIndustrial = 6;
znCommercial = 7;
znCivics = 8;
znOffices = 9;
function ZoneMatches( ZoneA, ZoneB : TZoneType ) : boolean;
// Events
const
tidEventField_Date = 'Date';
tidEventField_Text = 'Text';
tidEventField_Kind = 'Kind';
tidEventField_URL = 'URL';
const
tidInvention_WaterQuest = 'WaterQuest';
// Cookies
function ComposeLinkCookie( name : string; x, y : integer; select : boolean ) : string;
function ParseLinkCookie( link : string; out name : string; out x, y : integer; out select : boolean ) : boolean;
// AccountDesc
const
AccDesc_NobMask = $0000FFFF;
AccDesc_ModMask = $FFFF0000;
const
AccMod_UnknownUser = $8000;
AccMod_Support = $0001;
AccMod_Developer = $0002;
AccMod_Publisher = $0004;
AccMod_Ambassador = $0008;
AccMod_GameMaster = $0010;
AccMod_Trial = $0020;
AccMod_Newbie = $0040;
AccMod_Veteran = $0080;
function ComposeAccDesc( Nobility, Modifiers : integer ) : integer;
procedure BreakAccDesc( AccDesc : integer; out Nobility, Modifiers : word );
function ComposeChatUser(const name : string; const id: cardinal; const AFK: boolean) : string;
function ParseChatUser(const ChatUser : string; out name : string; out id: cardinal;out AFK: boolean): boolean;
const
tidDSId_Nobpoints = 'NobPoints';
implementation
uses
SysUtils, CompStringsParser, mr_StrUtils, MathUtils;
function GrantAccess( RequesterId, SecurityId : TSecurityId ) : boolean;
begin
result := system.pos( SecIdItemSeparator + RequesterId + SecIdItemSeparator, SecurityId ) > 0;
end;
function ZoneMatches( ZoneA, ZoneB : TZoneType ) : boolean;
begin
case ZoneA of
znNone :
result := true;
znReserved :
result := true;//false;
znResidential :
result := ZoneB in [znHiResidential, znMidResidential, znLoResidential];
else
result := (ZoneB = ZoneA) or (ZoneB = znNone)
end;
end;
function ComposeLinkCookie( name : string; x, y : integer; select : boolean ) : string;
begin
result := name + ',' + IntToStr(x) + ',' + IntToStr(y) + ',' + IntToStr(integer(select));
end;
function ParseLinkCookie( link : string; out name : string; out x, y : integer; out select : boolean ) : boolean;
var
p : integer;
begin
if link <> ''
then
try
p := length(link);
select := boolean(StrToInt(GetPrevStringUpTo( link, p, ',' )));
y := StrToInt(GetPrevStringUpTo( link, p, ',' ));
x := StrToInt(GetPrevStringUpTo( link, p, ',' ));
name := copy(link, 1, p-1);
result := true;
except
result := false;
end
else result := false;
end;
function ComposeAccDesc( Nobility, Modifiers : integer ) : integer;
begin
Nobility := min( Nobility, AccDesc_NobMask );
result := Nobility and AccDesc_NobMask or (Modifiers shl 16 and AccDesc_ModMask);
end;
procedure BreakAccDesc( AccDesc : integer; out Nobility, Modifiers : word );
begin
Nobility := AccDesc and AccDesc_NobMask;
Modifiers := (AccDesc and AccDesc_ModMask) shr 16;
end;
function ComposeChatUser(const name : string; const id: cardinal; const AFK: boolean) : string;
var
AFKNumber : integer;
begin
if AFK
then
AFKNumber := 1
else
AFKNumber := 0;
result := format('%s/%d/%d', [name, id, AFKNumber]);
end;
function ParseChatUser(const ChatUser : string; out name : string; out id: cardinal;out AFK: boolean): boolean;
var
i : integer;
s : string;
begin
if trim(ChatUser)<>''
then
begin
i := system.pos('/', ChatUser);
if i>0
then
begin
name := trim(copy(ChatUser, 1, i-1));
try
s := copy(ChatUser, i+1, length(ChatUser)-i+1);
i := system.pos('/', s);
if (i>0)
then
begin
id := strtoint(copy(s, 1, i-1));
AFK := s[length(s)]='1';
end
else id := strtoint(s);
except
id := 0;
end;
end
else
begin
name := ChatUser;
id := 0;
end;
result := name<>'';
end
else result := false;
end;
end.
|
unit URLUtils;
interface
uses
Windows;
const
InvalidTime : TFileTime = ( dwLowDateTime : 0; dwHighDateTime : 0 );
type
TDownloadNotifyProc = function ( Progress: Longint; ProgressMax : Longint; StatusCode: Longint; StatusText: PWideChar ) : HRESULT of object;
function GetURLLastModified( const URL : string ) : TFileTime;
function DownloadURLToFile( const URL, Dest : string; NotifyProc : TDownloadNotifyProc ) : boolean;
function DownloadURLToCacheFile( const URL : string; NotifyProc : TDownloadNotifyProc ) : string;
implementation
uses
ActiveX, UrlMon, SysUtils;
type
TBindStatusCallback =
class( TInterfacedObject, IBindStatusCallback)
public
constructor Create( NotifyProc : TDownloadNotifyProc );
private
fNotifyProc : TDownloadNotifyProc;
private
function OnStartBinding(dwReserved: Longint; pib: IBinding): HResult; stdcall;
function GetPriority(out pnPriority: Longint): HResult; stdcall;
function OnLowResource(reserved: Longint): HResult; stdcall;
function OnProgress(ulProgress: Longint; ulProgressMax: Longint; ulStatusCode: Longint; szStatusText: PWideChar): HResult; stdcall;
function OnStopBinding( hRes: HResult; szError: PWideChar ): HResult; stdcall;
function GetBindInfo(out grfBINDF: Longint; var pbindinfo: TBindInfo): HResult; stdcall;
function OnDataAvailable(grfBSCF: Longint; dwSize: Longint; var pformatetc: TFormatEtc; var pstgmed: TSTGMEDIUM): HResult; stdcall;
function OnObjectAvailable(const iid: TGUID; const punk: IUnknown): HResult; stdcall;
end;
constructor TBindStatusCallback.Create( NotifyProc : TDownloadNotifyProc );
begin
inherited Create;
fNotifyProc := NotifyProc;
end;
function TBindStatusCallback.OnStartBinding(dwReserved: Longint; pib: IBinding): HResult;
begin
Result := S_OK;
end;
function TBindStatusCallback.GetPriority(out pnPriority: Longint): HResult;
begin
pnPriority := THREAD_PRIORITY_NORMAL;
Result := S_OK;
end;
function TBindStatusCallback.OnLowResource(reserved: Longint): HResult;
begin
Result := S_OK;
end;
function TBindStatusCallback.OnProgress(ulProgress: Longint; ulProgressMax: Longint; ulStatusCode: Longint; szStatusText: PWideChar): HResult;
begin
if Assigned( fNotifyProc )
then Result := fNotifyProc( ulProgress, ulProgressMax, ulStatusCode, szStatusText )
else Result := S_OK;
end;
function TBindStatusCallback.OnStopBinding( hRes: HResult; szError: PWideChar ): HResult;
begin
Result := S_OK;
end;
function TBindStatusCallback.GetBindInfo(out grfBINDF: Longint; var pbindinfo: TBindInfo): HResult;
begin
Result := E_INVALIDARG;
end;
function TBindStatusCallback.OnDataAvailable(grfBSCF: Longint; dwSize: Longint; var pformatetc: TFormatEtc; var pstgmed: TSTGMEDIUM): HResult;
begin
Result := S_OK;
end;
function TBindStatusCallback.OnObjectAvailable(const iid: TGUID; const punk: IUnknown): HResult;
begin
Result := S_OK;
end;
function GetURLLastModified( const URL : string ) : TFileTime;
var
Moniker : IMoniker;
WideURL : widestring;
BindCtx : IBindCtx;
hRes : HRESULT;
begin
WideURL := URL;
if CreateURLMoniker( nil, pwidechar(WideURL), Moniker ) = S_OK
then
begin
if CreateBindCtx( 0, BindCtx ) = S_OK
then
begin
hRes := Moniker.GetTimeOfLastChange( BindCtx, nil, Result );
if hRes <> S_OK
then Result := InvalidTime;
end
else Result := InvalidTime;
end
else Result := InvalidTime;
end;
function DownloadURLToFile( const URL, Dest : string; NotifyProc : TDownloadNotifyProc ) : boolean;
var
StatusCallback : TBindStatusCallback;
begin
StatusCallback := TBindStatusCallback.Create( NotifyProc );
Result := URLDownloadToFile( nil, pchar(URL), pchar(Dest), 0, StatusCallback ) = S_OK;
end;
function DownloadURLToCacheFile( const URL : string; NotifyProc : TDownloadNotifyProc ) : string;
var
StatusCallback : TBindStatusCallback;
Storage : array[0..pred(MAX_PATH)] of char;
begin
StatusCallback := TBindStatusCallback.Create( NotifyProc );
if URLDownloadToCacheFile( nil, pchar(URL), pchar(@Storage), MAX_PATH, 0, StatusCallback ) = S_OK
then Result := Storage
else Result := '';
end;
end.
|
unit MainForm;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Grids, API, DeleteForm, EditForm,
SearchForm;
type
TForm1 = class(TForm)
Label1: TLabel;
SortBy: TComboBox;
MainTable: TStringGrid;
AddButton: TButton;
DelButton: TButton;
CreateButton: TButton;
SearchButton: TButton;
ShowAllButton: TButton;
procedure FormCreate(Sender: TObject);
procedure AddButtonClick(Sender: TObject);
procedure DelButtonClick(Sender: TObject);
procedure GetRowData(out Data : API.TData);
procedure FillTable(const List : API.TList);
procedure CreateButtonClick(Sender: TObject);
procedure setSize;
procedure SortByChange(Sender: TObject);
procedure SearchButtonClick(Sender: TObject);
procedure ShowAllButtonClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
uses
AddForm;
{$R *.dfm}
procedure TForm1.setSize;
begin
if MainTable.RowCount < 10 then
begin
MainTable.ColWidths[0] := 0;
MainTable.ColWidths[1] := 200;
MainTable.ColWidths[2] := 200;
MainTable.ColWidths[3] := 200;
MainTable.ColWidths[4] := 200;
MainTable.ColWidths[5] := 345;
end
else
begin
MainTable.ColWidths[0] := 0;
MainTable.ColWidths[1] := 149;
MainTable.ColWidths[2] := 149;
MainTable.ColWidths[3] := 149;
MainTable.ColWidths[4] := 149;
MainTable.ColWidths[5] := 149;
end;
end;
procedure TForm1.ShowAllButtonClick(Sender: TObject);
var
List :API.TList;
i:byte;
begin
SortBy.ItemIndex:=0;
API.LoadList(List);
if List.head=nil then
begin
for i := 0 to MainTable.ColCount-1 do
MainTable.Cells[i,1]:='';
end
else FillTable(List);
end;
procedure TForm1.SortByChange(Sender: TObject);
var
List: API.TList;
i, j, cnt: integer;
begin
if MainTable.Cells[0,1] = '' then
begin
ShowMessage('Нечего сортировать!');
SortBy.ItemIndex := 0;
exit;
end;
case SortBy.ItemIndex of
0:
begin
API.LoadList(List);
if List.Head = nil then
begin
for I := 0 to MainTable.ColCount - 1 do
MainTable.Cells[i,1] := '';
end
else FillTable(List);
end;
1:
begin
cnt := MainTable.RowCount;
for j := 1 to cnt - 1 do
for i := j+1 to Cnt do
begin
if AnsiLowerCase(MainTable.Cells[2, i]) < AnsiLowerCase(MainTable.Cells[2, j]) then
with MainTable do
begin
Rows[Cnt] := Rows[i];
Rows[i] := Rows[j];
Rows[j] := Rows[Cnt];
end;
end;
end;
2:
begin
cnt := MainTable.RowCount;
for j := 1 to cnt - 1 do
for i := j+1 to Cnt do
begin
if AnsiLowerCase(MainTable.Cells[3, i]) < AnsiLowerCase(MainTable.Cells[3, j]) then
with MainTable do
begin
Rows[Cnt] := Rows[i];
Rows[i] := Rows[j];
Rows[j] := Rows[Cnt];
end;
end;
end;
end;
end;
procedure TForm1.FillTable(const List :API.TList);
var
curr: API.ptr;
cnt, i: integer;
begin
MainTable.RowCount := 2;
if List.Head = nil then
begin
for i := 0 to MainTable.ColCount - 1 do
MainTable.Cells[i,1] := '';
exit;
end;
Curr := List.Head;
cnt := 1;
while curr <> nil do
begin
with MainTable do
begin
cells[0,cnt] := curr.data.ID;
cells[1,cnt] := curr.data.DataType;
cells[2,cnt] := curr.data.Name;
cells[3,cnt] := curr.data.Author;
cells[4,cnt] := curr.data.cost;
cells[5,cnt] := curr.data.Other;
end;
curr := curr.next;
inc(cnt);
MainTable.RowCount := cnt;
end;
MainTable.Selection := tGridRect(Rect(1,1,1,1));
end;
procedure TForm1.AddButtonClick(Sender: TObject);
var
List: API.TList;
begin
AddForm.Form2.Position := poScreenCenter;
AddForm.Form2.ShowModal;
API.LoadList(List);
setSize;
FillTable(List);
end;
procedure TForm1.CreateButtonClick(Sender: TObject);
var
data: API.TData;
List: API.TList;
begin
GetRowData(Data);
if data.ID = '' then
begin
ShowMessage('Нет данных для редактрования!');
exit;
end;
Form4.data := data;
Form4.Position := poScreenCenter;
Form4.ShowModal;
API.LoadList(List);
setSize;
FillTable(List);
end;
procedure TForm1.DelButtonClick(Sender: TObject);
var
Data: API.TData;
List: API.TList;
i: byte;
begin
GetRowData(Data);
if data.ID = '' then
begin
ShowMessage('Нет данных для удаления!');
exit;
end;
Form3.data := data;
DeleteForm.Form3.Position := poScreenCenter;
Form3.ShowModal;
LoadList(List);
setSize;
FillTable(List);
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
Form1.Position := poScreenCenter;
MainTable.Cells[1,0] := 'Тип';
MainTable.Cells[2,0] := 'Наименование';
MainTable.Cells[3,0] := 'Автор';
MainTable.Cells[4,0] := 'Цена';
MainTable.Cells[5,0] := 'Примечание';
API.LoadList(List);
setSize;
FillTable(List);
end;
procedure TForm1.GetRowData(out Data :API.TData);
var
TableCol, TableRow :integer;
begin
TableCol := 0;
TableRow := MainTable.Row;
Data.ID := MainTable.Cells[TableCol, TableRow];
Data.DataType := MainTable.Cells[TableCol+1, TableRow];
Data.Name := MainTable.Cells[TableCol+2,TableRow];
Data.Author := MainTable.Cells[TableCol+3,TableRow];
Data.cost := MainTable.Cells[TableCol+4,TableRow];
Data.Other := MainTable.Cells[TableCol+5,TableRow];
end;
procedure TForm1.SearchButtonClick(Sender: TObject);
var
FoundData : API.TDataArr;
i, cnt :integer;
begin
if MainTable.Cells[0,1]='' then
begin
ShowMessage('Нет данных для поиска!');
exit;
end;
Form5.Position := poScreenCenter;
Form5.ShowModal;
if not((Form5.Value='') or (Form5.Field=-1)) then
begin
API.FillDataArr(FoundData, Form5.Field, Form5.Value);
if length(FoundData.DataArr)=0 then
ShowMessage('По вашему запросу ничего не найдено!')
else
begin
with MainTable do
for i:=0 to ColCount-1 do
Cols[i].Clear;
MainTable.Cells[1,0] := 'Тип';
MainTable.Cells[2,0] := 'Наименование';
MainTable.Cells[3,0] := 'Автор';
MainTable.Cells[4,0] := 'Цена';
MainTable.Cells[5,0] := 'Примечание';
MainTable.RowCount:= 2;
cnt:=1;
for i := 0 to length(FoundData.DataArr)-1 do
begin
MainTable.Cells[0, cnt]:=FoundData.DataArr[i].ID;
MainTable.Cells[1, cnt]:=FoundData.DataArr[i].DataType;
MainTable.Cells[2, cnt]:=FoundData.DataArr[i].Name;
MainTable.Cells[3, cnt]:=FoundData.DataArr[i].Author;
MainTable.Cells[4, cnt]:=FoundData.DataArr[i].cost;
MainTable.Cells[5, cnt]:=FoundData.DataArr[i].Other;
cnt := cnt+1;
MainTable.RowCount:= cnt;
end;
end;
end;
end;
end.
|
unit libswresample;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
interface
Uses
ffmpeg_types, libavutil;
{$I ffmpeg.inc}
(* *
* @defgroup lswr libswresample
* @{
*
* Audio resampling, sample format conversion and mixing library.
*
* Interaction with lswr is done through SwrContext, which is
* allocated with swr_alloc() or swr_alloc_set_opts(). It is opaque, so all parameters
* must be set with the @ref avoptions API.
*
* The first thing you will need to do in order to use lswr is to allocate
* SwrContext. This can be done with swr_alloc() or swr_alloc_set_opts(). If you
* are using the former, you must set options through the @ref avoptions API.
* The latter function provides the same feature, but it allows you to set some
* common options in the same statement.
*
* For example the following code will setup conversion from planar float sample
* format to interleaved signed 16-bit integer, downsampling from 48kHz to
* 44.1kHz and downmixing from 5.1 channels to stereo (using the default mixing
* matrix). This is using the swr_alloc() function.
* @code
* SwrContext *swr = swr_alloc();
* av_opt_set_channel_layout(swr, "in_channel_layout", AV_CH_LAYOUT_5POINT1, 0);
* av_opt_set_channel_layout(swr, "out_channel_layout", AV_CH_LAYOUT_STEREO, 0);
* av_opt_set_int(swr, "in_sample_rate", 48000, 0);
* av_opt_set_int(swr, "out_sample_rate", 44100, 0);
* av_opt_set_sample_fmt(swr, "in_sample_fmt", AV_SAMPLE_FMT_FLTP, 0);
* av_opt_set_sample_fmt(swr, "out_sample_fmt", AV_SAMPLE_FMT_S16, 0);
* @endcode
*
* The same job can be done using swr_alloc_set_opts() as well:
* @code
* SwrContext *swr = swr_alloc_set_opts(NULL, // we're allocating a new context
* AV_CH_LAYOUT_STEREO, // out_ch_layout
* AV_SAMPLE_FMT_S16, // out_sample_fmt
* 44100, // out_sample_rate
* AV_CH_LAYOUT_5POINT1, // in_ch_layout
* AV_SAMPLE_FMT_FLTP, // in_sample_fmt
* 48000, // in_sample_rate
* 0, // log_offset
* NULL); // log_ctx
* @endcode
*
* Once all values have been set, it must be initialized with swr_init(). If
* you need to change the conversion parameters, you can change the parameters
* using @ref AVOptions, as described above in the first example; or by using
* swr_alloc_set_opts(), but with the first argument the allocated context.
* You must then call swr_init() again.
*
* The conversion itself is done by repeatedly calling swr_convert().
* Note that the samples may get buffered in swr if you provide insufficient
* output space or if sample rate conversion is done, which requires "future"
* samples. Samples that do not require future input can be retrieved at any
* time by using swr_convert() (in_count can be set to 0).
* At the end of conversion the resampling buffer can be flushed by calling
* swr_convert() with NULL in and 0 in_count.
*
* The samples used in the conversion process can be managed with the libavutil
* @ref lavu_sampmanip "samples manipulation" API, including av_samples_alloc()
* function used in the following example.
*
* The delay between input and output, can at any time be found by using
* swr_get_delay().
*
* The following code demonstrates the conversion loop assuming the parameters
* from above and caller-defined functions get_input() and handle_output():
* @code
* uint8_t **input;
* int in_samples;
*
* while (get_input(&input, &in_samples)) {
* uint8_t *output;
* int out_samples = av_rescale_rnd(swr_get_delay(swr, 48000) +
* in_samples, 44100, 48000, AV_ROUND_UP);
* av_samples_alloc(&output, NULL, 2, out_samples,
* AV_SAMPLE_FMT_S16, 0);
* out_samples = swr_convert(swr, &output, out_samples,
* input, in_samples);
* handle_output(output, out_samples);
* av_freep(&output);
* }
* @endcode
*
* When the conversion is finished, the conversion
* context and everything associated with it must be freed with swr_free().
* A swr_close() function is also available, but it exists mainly for
* compatibility with libavresample, and is not required to be called.
*
* There will be no memory leak if the data is not completely flushed before
* swr_free().
*)
// #include <stdint.h>
// #include "libavutil/channel_layout.h"
// #include "libavutil/frame.h"
// #include "libavutil/samplefmt.h"
// #include "libswresample/version.h"
const
(* *
* @name Option constants
* These constants are used for the @ref avoptions interface for lswr.
* @{
*
*)
SWR_FLAG_RESAMPLE = 1;
/// < Force resampling even if equal sample rate
// TODO use int resample ?
// long term TODO can we enable this dynamically?
type
(* * Dithering algorithms *)
SwrDitherType = ( //
SWR_DITHER_NONE = 0, SWR_DITHER_RECTANGULAR, SWR_DITHER_TRIANGULAR, SWR_DITHER_TRIANGULAR_HIGHPASS,
SWR_DITHER_NS = 64,
/// < not part of API/ABI
SWR_DITHER_NS_LIPSHITZ, SWR_DITHER_NS_F_WEIGHTED, SWR_DITHER_NS_MODIFIED_E_WEIGHTED, SWR_DITHER_NS_IMPROVED_E_WEIGHTED,
SWR_DITHER_NS_SHIBATA, SWR_DITHER_NS_LOW_SHIBATA, SWR_DITHER_NS_HIGH_SHIBATA, SWR_DITHER_NB
/// < not part of API/ABI
);
(* * Resampling Engines *)
SwrEngine = ( //
SWR_ENGINE_SWR, (* *< SW Resampler *)
SWR_ENGINE_SOXR, (* *< SoX Resampler *)
SWR_ENGINE_NB
/// < not part of API/ABI
);
(* * Resampling Filter Types *)
SwrFilterType = ( //
SWR_FILTER_TYPE_CUBIC, (* *< Cubic *)
SWR_FILTER_TYPE_BLACKMAN_NUTTALL, (* *< Blackman Nuttall windowed sinc *)
SWR_FILTER_TYPE_KAISER (* *< Kaiser windowed sinc *)
);
type
(* *
* The libswresample context. Unlike libavcodec and libavformat, this structure
* is opaque. This means that if you would like to set options, you must use
* the @ref avoptions API and cannot directly set values to members of the
* structure.
*)
pSwrContext = ^SwrContext;
SwrContext = record
end;
(* *
* Get the AVClass for SwrContext. It can be used in combination with
* AV_OPT_SEARCH_FAKE_OBJ for examining options.
*
* @see av_opt_find().
* @return the AVClass of SwrContext
*)
// const AVClass *swr_get_class(void);
function swr_get_class(): pAVClass; cdecl; external swresample_dll;
(* *
* @name SwrContext constructor functions
* @{
*)
(* *
* Allocate SwrContext.
*
* If you use this function you will need to set the parameters (manually or
* with swr_alloc_set_opts()) before calling swr_init().
*
* @see swr_alloc_set_opts(), swr_init(), swr_free()
* @return NULL on error, allocated context otherwise
*)
// struct SwrContext *swr_alloc(void);
function swr_alloc(): pSwrContext; cdecl; external swresample_dll;
(* *
* Initialize context after user parameters have been set.
* @note The context must be configured using the AVOption API.
*
* @see av_opt_set_int()
* @see av_opt_set_dict()
*
* @param[in,out] s Swr context to initialize
* @return AVERROR error code in case of failure.
*)
// int swr_init(struct SwrContext *s);
function swr_init(s: pSwrContext): int; cdecl; external swresample_dll;
(* *
* Check whether an swr context has been initialized or not.
*
* @param[in] s Swr context to check
* @see swr_init()
* @return positive if it has been initialized, 0 if not initialized
*)
// int swr_is_initialized(struct SwrContext *s);
function swr_is_initialized(s: pSwrContext): int; cdecl; external swresample_dll;
(* *
* Allocate SwrContext if needed and set/reset common parameters.
*
* This function does not require s to be allocated with swr_alloc(). On the
* other hand, swr_alloc() can use swr_alloc_set_opts() to set the parameters
* on the allocated context.
*
* @param s existing Swr context if available, or NULL if not
* @param out_ch_layout output channel layout (AV_CH_LAYOUT_* )
* @param out_sample_fmt output sample format (AV_SAMPLE_FMT_* ).
* @param out_sample_rate output sample rate (frequency in Hz)
* @param in_ch_layout input channel layout (AV_CH_LAYOUT_* )
* @param in_sample_fmt input sample format (AV_SAMPLE_FMT_* ).
* @param in_sample_rate input sample rate (frequency in Hz)
* @param log_offset logging level offset
* @param log_ctx parent logging context, can be NULL
*
* @see swr_init(), swr_free()
* @return NULL on error, allocated context otherwise
*)
// struct SwrContext *swr_alloc_set_opts(struct SwrContext *s,
// int64_t out_ch_layout, enum AVSampleFormat out_sample_fmt, int out_sample_rate,
// int64_t in_ch_layout, enum AVSampleFormat in_sample_fmt, int in_sample_rate,
// int log_offset, void *log_ctx);
function swr_alloc_set_opts(s: pSwrContext; out_ch_layout: int64_t; out_sample_fmt: AVSampleFormat; out_sample_rate: int;
in_ch_layout: int64_t; in_sample_fmt: AVSampleFormat; in_sample_rate: int; log_offset: int; log_ctx: Pointer): pSwrContext; cdecl;
external swresample_dll;
(* *
* @}
*
* @name SwrContext destructor functions
* @{
*)
(* *
* Free the given SwrContext and set the pointer to NULL.
*
* @param[in] s a pointer to a pointer to Swr context
*)
// void swr_free(struct SwrContext **s);
procedure swr_free(var s: pSwrContext); cdecl; external swresample_dll;
(* *
* Closes the context so that swr_is_initialized() returns 0.
*
* The context can be brought back to life by running swr_init(),
* swr_init() can also be used without swr_close().
* This function is mainly provided for simplifying the usecase
* where one tries to support libavresample and libswresample.
*
* @param[in,out] s Swr context to be closed
*)
// void swr_close(struct SwrContext *s);
procedure swr_close(s: pSwrContext); cdecl; external swresample_dll;
(* *
* @}
*
* @name Core conversion functions
* @{
*)
(* * Convert audio.
*
* in and in_count can be set to 0 to flush the last few samples out at the
* end.
*
* If more input is provided than output space, then the input will be buffered.
* You can avoid this buffering by using swr_get_out_samples() to retrieve an
* upper bound on the required number of output samples for the given number of
* input samples. Conversion will run directly without copying whenever possible.
*
* @param s allocated Swr context, with parameters set
* @param out output buffers, only the first one need be set in case of packed audio
* @param out_count amount of space available for output in samples per channel
* @param in input buffers, only the first one need to be set in case of packed audio
* @param in_count number of input samples available in one channel
*
* @return number of samples output per channel, negative value on error
*)
// int swr_convert(struct SwrContext *s, uint8_t **out, int out_count,
// const uint8_t **in , int in_count);
function swr_convert(s: pSwrContext; _out: ppuint8_t; out_count: int; const _in: ppuint8_t; in_count: int): int; cdecl; external swresample_dll;
(* *
* Convert the next timestamp from input to output
* timestamps are in 1/(in_sample_rate * out_sample_rate) units.
*
* @note There are 2 slightly differently behaving modes.
* @li When automatic timestamp compensation is not used, (min_compensation >= FLT_MAX)
* in this case timestamps will be passed through with delays compensated
* @li When automatic timestamp compensation is used, (min_compensation < FLT_MAX)
* in this case the output timestamps will match output sample numbers.
* See ffmpeg-resampler(1) for the two modes of compensation.
*
* @param s[in] initialized Swr context
* @param pts[in] timestamp for the next input sample, INT64_MIN if unknown
* @see swr_set_compensation(), swr_drop_output(), and swr_inject_silence() are
* function used internally for timestamp compensation.
* @return the output timestamp for the next output sample
*)
// int64_t swr_next_pts(struct SwrContext *s, int64_t pts);
function swr_next_pts(s: pSwrContext; pts: int64_t): int64_t; cdecl; external swresample_dll;
(* *
* @}
*
* @name Low-level option setting functions
* These functons provide a means to set low-level options that is not possible
* with the AVOption API.
* @{
*)
(* *
* Activate resampling compensation ("soft" compensation). This function is
* internally called when needed in swr_next_pts().
*
* @param[in,out] s allocated Swr context. If it is not initialized,
* or SWR_FLAG_RESAMPLE is not set, swr_init() is
* called with the flag set.
* @param[in] sample_delta delta in PTS per sample
* @param[in] compensation_distance number of samples to compensate for
* @return >= 0 on success, AVERROR error codes if:
* @li @c s is NULL,
* @li @c compensation_distance is less than 0,
* @li @c compensation_distance is 0 but sample_delta is not,
* @li compensation unsupported by resampler, or
* @li swr_init() fails when called.
*)
// int swr_set_compensation(struct SwrContext *s, int sample_delta, int compensation_distance);
function swr_set_compensation(s: pSwrContext; sample_delta: int; compensation_distance: int): int; cdecl; external swresample_dll;
(* *
* Set a customized input channel mapping.
*
* @param[in,out] s allocated Swr context, not yet initialized
* @param[in] channel_map customized input channel mapping (array of channel
* indexes, -1 for a muted channel)
* @return >= 0 on success, or AVERROR error code in case of failure.
*)
// int swr_set_channel_mapping(struct SwrContext *s, const int *channel_map);
function swr_set_channel_mapping(s: pSwrContext; const channel_map: pint): int; cdecl; external swresample_dll;
(* *
* Generate a channel mixing matrix.
*
* This function is the one used internally by libswresample for building the
* default mixing matrix. It is made public just as a utility function for
* building custom matrices.
*
* @param in_layout input channel layout
* @param out_layout output channel layout
* @param center_mix_level mix level for the center channel
* @param surround_mix_level mix level for the surround channel(s)
* @param lfe_mix_level mix level for the low-frequency effects channel
* @param rematrix_maxval if 1.0, coefficients will be normalized to prevent
* overflow. if INT_MAX, coefficients will not be
* normalized.
* @param[out] matrix mixing coefficients; matrix[i + stride * o] is
* the weight of input channel i in output channel o.
* @param stride distance between adjacent input channels in the
* matrix array
* @param matrix_encoding matrixed stereo downmix mode (e.g. dplii)
* @param log_ctx parent logging context, can be NULL
* @return 0 on success, negative AVERROR code on failure
*)
// int swr_build_matrix(uint64_t in_layout, uint64_t out_layout,
// double center_mix_level, double surround_mix_level,
// double lfe_mix_level, double rematrix_maxval,
// double rematrix_volume, double *matrix,
// int stride, enum AVMatrixEncoding matrix_encoding,
// void *log_ctx);
function swr_build_matrix(in_layout: uint64_t; out_layout: uint64_t; center_mix_level: double; surround_mix_level: double;
lfe_mix_level: double; rematrix_maxval: double; rematrix_volume: double; var matrix: double; stride: int;
matrix_encoding: AVMatrixEncoding; log_ctx: Pointer): int; cdecl; external swresample_dll;
(* *
* Set a customized remix matrix.
*
* @param s allocated Swr context, not yet initialized
* @param matrix remix coefficients; matrix[i + stride * o] is
* the weight of input channel i in output channel o
* @param stride offset between lines of the matrix
* @return >= 0 on success, or AVERROR error code in case of failure.
*)
// int swr_set_matrix(struct SwrContext *s, const double *matrix, int stride);
function swr_set_matrix(s: pSwrContext; const matrix: pdouble; stride: int): int; cdecl; external swresample_dll;
(* *
* @}
*
* @name Sample handling functions
* @{
*)
(* *
* Drops the specified number of output samples.
*
* This function, along with swr_inject_silence(), is called by swr_next_pts()
* if needed for "hard" compensation.
*
* @param s allocated Swr context
* @param count number of samples to be dropped
*
* @return >= 0 on success, or a negative AVERROR code on failure
*)
// int swr_drop_output(struct SwrContext *s, int count);
function swr_drop_output(s: pSwrContext; count: int): int; cdecl; external swresample_dll;
(* *
* Injects the specified number of silence samples.
*
* This function, along with swr_drop_output(), is called by swr_next_pts()
* if needed for "hard" compensation.
*
* @param s allocated Swr context
* @param count number of samples to be dropped
*
* @return >= 0 on success, or a negative AVERROR code on failure
*)
// int swr_inject_silence(struct SwrContext *s, int count);
function swr_inject_silence(s: pSwrContext; count: int): int; cdecl; external swresample_dll;
(* *
* Gets the delay the next input sample will experience relative to the next output sample.
*
* Swresample can buffer data if more input has been provided than available
* output space, also converting between sample rates needs a delay.
* This function returns the sum of all such delays.
* The exact delay is not necessarily an integer value in either input or
* output sample rate. Especially when downsampling by a large value, the
* output sample rate may be a poor choice to represent the delay, similarly
* for upsampling and the input sample rate.
*
* @param s swr context
* @param base timebase in which the returned delay will be:
* @li if it's set to 1 the returned delay is in seconds
* @li if it's set to 1000 the returned delay is in milliseconds
* @li if it's set to the input sample rate then the returned
* delay is in input samples
* @li if it's set to the output sample rate then the returned
* delay is in output samples
* @li if it's the least common multiple of in_sample_rate and
* out_sample_rate then an exact rounding-free delay will be
* returned
* @returns the delay in 1 / @c base units.
*)
// int64_t swr_get_delay(struct SwrContext *s, int64_t base);
function swr_get_delay(s: pSwrContext; base: int64_t): int64_t; cdecl; external swresample_dll;
(* *
* Find an upper bound on the number of samples that the next swr_convert
* call will output, if called with in_samples of input samples. This
* depends on the internal state, and anything changing the internal state
* (like further swr_convert() calls) will may change the number of samples
* swr_get_out_samples() returns for the same number of input samples.
*
* @param in_samples number of input samples.
* @note any call to swr_inject_silence(), swr_convert(), swr_next_pts()
* or swr_set_compensation() invalidates this limit
* @note it is recommended to pass the correct available buffer size
* to all functions like swr_convert() even if swr_get_out_samples()
* indicates that less would be used.
* @returns an upper bound on the number of samples that the next swr_convert
* will output or a negative value to indicate an error
*)
// int swr_get_out_samples(struct SwrContext *s, int in_samples);
function swr_get_out_samples(s: pSwrContext; in_samples: int): int; cdecl; external swresample_dll;
(* *
* @}
*
* @name Configuration accessors
* @{
*)
(* *
* Return the @ref LIBSWRESAMPLE_VERSION_INT constant.
*
* This is useful to check if the build-time libswresample has the same version
* as the run-time one.
*
* @returns the unsigned int-typed version
*)
// unsigned swresample_version(void);
function swresample_version(): unsigned; cdecl; external swresample_dll;
(* *
* Return the swr build-time configuration.
*
* @returns the build-time @c ./configure flags
*)
// const char *swresample_configuration(void);
function swresample_configuration(): pAnsiChar; cdecl; external swresample_dll;
(* *
* Return the swr license.
*
* @returns the license of libswresample, determined at build-time
*)
// const char *swresample_license(void);
function swresample_license(): pAnsiChar; cdecl; external swresample_dll;
(* *
* @}
*
* @name AVFrame based API
* @{
*)
(* *
* Convert the samples in the input AVFrame and write them to the output AVFrame.
*
* Input and output AVFrames must have channel_layout, sample_rate and format set.
*
* If the output AVFrame does not have the data pointers allocated the nb_samples
* field will be set using av_frame_get_buffer()
* is called to allocate the frame.
*
* The output AVFrame can be NULL or have fewer allocated samples than required.
* In this case, any remaining samples not written to the output will be added
* to an internal FIFO buffer, to be returned at the next call to this function
* or to swr_convert().
*
* If converting sample rate, there may be data remaining in the internal
* resampling delay buffer. swr_get_delay() tells the number of
* remaining samples. To get this data as output, call this function or
* swr_convert() with NULL input.
*
* If the SwrContext configuration does not match the output and
* input AVFrame settings the conversion does not take place and depending on
* which AVFrame is not matching AVERROR_OUTPUT_CHANGED, AVERROR_INPUT_CHANGED
* or the result of a bitwise-OR of them is returned.
*
* @see swr_delay()
* @see swr_convert()
* @see swr_get_delay()
*
* @param swr audio resample context
* @param output output AVFrame
* @param input input AVFrame
* @return 0 on success, AVERROR on failure or nonmatching
* configuration.
*)
// int swr_convert_frame(SwrContext *swr, AVFrame *output, const AVFrame *input);
function swr_convert_frame(swr: pSwrContext; output: pAVFrame; const input: pAVFrame): int; cdecl; external swresample_dll;
(* *
* Configure or reconfigure the SwrContext using the information
* provided by the AVFrames.
*
* The original resampling context is reset even on failure.
* The function calls swr_close() internally if the context is open.
*
* @see swr_close();
*
* @param swr audio resample context
* @param output output AVFrame
* @param input input AVFrame
* @return 0 on success, AVERROR on failure.
*)
// int swr_config_frame(SwrContext *swr, const AVFrame *out, const AVFrame *in);
function swr_config_frame(swr: pSwrContext; const _out: pAVFrame; const _in: pAVFrame): int; cdecl; external swresample_dll;
implementation
end.
|
unit MFichas.Model.Venda.State.Finalizar;
interface
uses
System.SysUtils,
MFichas.Model.Venda.Interfaces;
type
TModelVendaStateFinalizar = class(TInterfacedObject, iModelVendaMetodos)
private
constructor Create;
public
destructor Destroy; override;
class function New: iModelVendaMetodos;
function Abrir : iModelVendaMetodosAbrir;
function Pagar : iModelVendaMetodosPagar;
function Finalizar: iModelVendaMetodosFinalizar;
function &End : iModelVenda;
end;
implementation
{ TModelVendaStateFinalizar }
function TModelVendaStateFinalizar.&End: iModelVenda;
begin
end;
function TModelVendaStateFinalizar.Abrir: iModelVendaMetodosAbrir;
begin
end;
constructor TModelVendaStateFinalizar.Create;
begin
end;
destructor TModelVendaStateFinalizar.Destroy;
begin
inherited;
end;
function TModelVendaStateFinalizar.Finalizar: iModelVendaMetodosFinalizar;
begin
raise Exception.Create(
'Não é possível usar o método de finalização de venda.' + sLineBreak +
'Não existe nenhuma venda aberta para ser finalizada.'
);
end;
class function TModelVendaStateFinalizar.New: iModelVendaMetodos;
begin
Result := Self.Create;
end;
function TModelVendaStateFinalizar.Pagar: iModelVendaMetodosPagar;
begin
raise Exception.Create(
'Não é possível adicionar um pagamento.' + sLineBreak +
'Não existe nenhuma venda em aberto.'
);
end;
end.
|
{ Date Created: 5/22/00 11:17:33 AM }
unit InfoPULLLISTLOOKUPTable;
interface
uses
Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf;
type
TInfoPULLLISTLOOKUPRecord = record
PItemNumber: String[1];
PSI: String[2];
PDescription: String[20];
PAbbreviation: String[12];
End;
TInfoPULLLISTLOOKUPBuffer = class(TDataBuf)
protected
function PtrIndex(Index:integer):Pointer;override;
public
Data: TInfoPULLLISTLOOKUPRecord
end;
TEIInfoPULLLISTLOOKUP = (InfoPULLLISTLOOKUPPrimaryKey);
TInfoPULLLISTLOOKUPTable = class( TDBISAMTableAU )
private
FDFItemNumber: TStringField;
FDFSI: TStringField;
FDFDescription: TStringField;
FDFAbbreviation: TStringField;
procedure SetPItemNumber(const Value: String);
function GetPItemNumber:String;
procedure SetPSI(const Value: String);
function GetPSI:String;
procedure SetPDescription(const Value: String);
function GetPDescription:String;
procedure SetPAbbreviation(const Value: String);
function GetPAbbreviation:String;
function GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string;
procedure SetEnumIndex(Value: TEIInfoPULLLISTLOOKUP);
function GetEnumIndex: TEIInfoPULLLISTLOOKUP;
protected
function CreateField( const FieldName : string ): TField;
procedure CreateFields; virtual;
procedure SetActive(Value: Boolean); override;
procedure LoadFieldDefs(AStringList:TStringList);override;
procedure LoadIndexDefs(AStringList:TStringList);override;
public
function GetDataBuffer:TInfoPULLLISTLOOKUPRecord;
procedure StoreDataBuffer(ABuffer:TInfoPULLLISTLOOKUPRecord);
property DFItemNumber: TStringField read FDFItemNumber;
property DFSI: TStringField read FDFSI;
property DFDescription: TStringField read FDFDescription;
property DFAbbreviation: TStringField read FDFAbbreviation;
property PItemNumber: String read GetPItemNumber write SetPItemNumber;
property PSI: String read GetPSI write SetPSI;
property PDescription: String read GetPDescription write SetPDescription;
property PAbbreviation: String read GetPAbbreviation write SetPAbbreviation;
procedure Validate; virtual;
published
property Active write SetActive;
property EnumIndex: TEIInfoPULLLISTLOOKUP read GetEnumIndex write SetEnumIndex;
end; { TInfoPULLLISTLOOKUPTable }
procedure Register;
implementation
function TInfoPULLLISTLOOKUPTable.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 { TInfoPULLLISTLOOKUPTable.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; { TInfoPULLLISTLOOKUPTable.GenerateNewFieldName }
function TInfoPULLLISTLOOKUPTable.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; { TInfoPULLLISTLOOKUPTable.CreateField }
procedure TInfoPULLLISTLOOKUPTable.CreateFields;
begin
FDFItemNumber := CreateField( 'ItemNumber' ) as TStringField;
FDFSI := CreateField( 'SI' ) as TStringField;
FDFDescription := CreateField( 'Description' ) as TStringField;
FDFAbbreviation := CreateField( 'Abbreviation' ) as TStringField;
end; { TInfoPULLLISTLOOKUPTable.CreateFields }
procedure TInfoPULLLISTLOOKUPTable.SetActive(Value: Boolean);
begin
inherited SetActive(Value);
if Active then
CreateFields;
end; { TInfoPULLLISTLOOKUPTable.SetActive }
procedure TInfoPULLLISTLOOKUPTable.Validate;
begin
{ Enter Validation Code Here }
end; { TInfoPULLLISTLOOKUPTable.Validate }
procedure TInfoPULLLISTLOOKUPTable.SetPItemNumber(const Value: String);
begin
DFItemNumber.Value := Value;
end;
function TInfoPULLLISTLOOKUPTable.GetPItemNumber:String;
begin
result := DFItemNumber.Value;
end;
procedure TInfoPULLLISTLOOKUPTable.SetPSI(const Value: String);
begin
DFSI.Value := Value;
end;
function TInfoPULLLISTLOOKUPTable.GetPSI:String;
begin
result := DFSI.Value;
end;
procedure TInfoPULLLISTLOOKUPTable.SetPDescription(const Value: String);
begin
DFDescription.Value := Value;
end;
function TInfoPULLLISTLOOKUPTable.GetPDescription:String;
begin
result := DFDescription.Value;
end;
procedure TInfoPULLLISTLOOKUPTable.SetPAbbreviation(const Value: String);
begin
DFAbbreviation.Value := Value;
end;
function TInfoPULLLISTLOOKUPTable.GetPAbbreviation:String;
begin
result := DFAbbreviation.Value;
end;
procedure TInfoPULLLISTLOOKUPTable.LoadFieldDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('ItemNumber, String, 1, N');
Add('SI, String, 2, N');
Add('Description, String, 20, N');
Add('Abbreviation, String, 12, N');
end;
end;
procedure TInfoPULLLISTLOOKUPTable.LoadIndexDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('PrimaryKey, ItemNumber;SI, Y, Y, N, N');
end;
end;
procedure TInfoPULLLISTLOOKUPTable.SetEnumIndex(Value: TEIInfoPULLLISTLOOKUP);
begin
case Value of
InfoPULLLISTLOOKUPPrimaryKey : IndexName := '';
end;
end;
function TInfoPULLLISTLOOKUPTable.GetDataBuffer:TInfoPULLLISTLOOKUPRecord;
var buf: TInfoPULLLISTLOOKUPRecord;
begin
fillchar(buf, sizeof(buf), 0);
buf.PItemNumber := DFItemNumber.Value;
buf.PSI := DFSI.Value;
buf.PDescription := DFDescription.Value;
buf.PAbbreviation := DFAbbreviation.Value;
result := buf;
end;
procedure TInfoPULLLISTLOOKUPTable.StoreDataBuffer(ABuffer:TInfoPULLLISTLOOKUPRecord);
begin
DFItemNumber.Value := ABuffer.PItemNumber;
DFSI.Value := ABuffer.PSI;
DFDescription.Value := ABuffer.PDescription;
DFAbbreviation.Value := ABuffer.PAbbreviation;
end;
function TInfoPULLLISTLOOKUPTable.GetEnumIndex: TEIInfoPULLLISTLOOKUP;
var iname : string;
begin
iname := uppercase(indexname);
if iname = '' then result := InfoPULLLISTLOOKUPPrimaryKey;
end;
(********************************************)
(************ Register Component ************)
(********************************************)
procedure Register;
begin
RegisterComponents( 'Info Tables', [ TInfoPULLLISTLOOKUPTable, TInfoPULLLISTLOOKUPBuffer ] );
end; { Register }
function TInfoPULLLISTLOOKUPBuffer.PtrIndex(index:integer):Pointer;
begin
result := nil;
case index of
1 : result := @Data.PItemNumber;
2 : result := @Data.PSI;
3 : result := @Data.PDescription;
4 : result := @Data.PAbbreviation;
end;
end;
end. { InfoPULLLISTLOOKUPTable }
|
unit RESTRequest4D.Request.Params;
interface
uses RESTRequest4D.Request.Params.Intf, REST.Client, REST.Types, System.Classes;
type
TRequestParams = class(TInterfacedObject, IRequestParams)
private
FParams: TStrings;
FRESTRequest: TRESTRequest;
function Clear: IRequestParams;
function Add(const AName, AValue: string; const AKind: TRESTRequestParameterKind = TRESTRequestParameterKind.pkQUERY): IRequestParams; overload;
function Add(const AName: string; const AValue: Currency; const AKind: TRESTRequestParameterKind = TRESTRequestParameterKind.pkQUERY): IRequestParams; overload;
function Add(const AName: string; const AValue: TStream): IRequestParams; overload;
public
constructor Create(const ARESTRequest: TRESTRequest);
destructor Destroy; override;
end;
implementation
uses System.SysUtils;
{ TRequestParams }
function TRequestParams.Add(const AName, AValue: string; const AKind: TRESTRequestParameterKind): IRequestParams;
begin
Result := Self;
if (not AName.Trim.IsEmpty) and (not AValue.Trim.IsEmpty) then
begin
FParams.Add(AName);
FRESTRequest.AddParameter(AName, AValue, AKind);
end;
end;
function TRequestParams.Add(const AName: string; const AValue: Currency; const AKind: TRESTRequestParameterKind): IRequestParams;
begin
Result := Self.Add(AName, CurrToStr(AValue), AKind);
end;
function TRequestParams.Add(const AName: string; const AValue: TStream): IRequestParams;
begin
Result := Self;
if not Assigned(AValue) then
Exit;
with FRESTRequest.Params.AddItem do
begin
Name := AName;
SetStream(AValue);
Value := AValue.ToString;
Kind := TRESTRequestParameterKind.pkFILE;
ContentType := TRESTContentType.ctAPPLICATION_OCTET_STREAM;
end;
end;
function TRequestParams.Clear: IRequestParams;
var
I: Integer;
begin
Result := Self;
for I := 0 to Pred(FParams.Count) do
FRESTRequest.Params.Delete(FRESTRequest.Params.ParameterByName(FParams[I]));
end;
constructor TRequestParams.Create(const ARESTRequest: TRESTRequest);
begin
inherited Create;
FParams := TStringList.Create;
FRESTRequest := ARESTRequest;
end;
destructor TRequestParams.Destroy;
begin
FParams.Free;
inherited;
end;
end.
|
unit evGraphicFileSupport;
interface
uses
Classes,
imageenio;
const
cioSupportedGraphicsFiles = [ioBMP, ioJPEG, ioGIF, ioPNG];
function evIsGraphicFile(const aFileName: string): Boolean;
function evIsGraphicFileStream(const aStream: TStream): Boolean;
function evAddSupportedGraphicsFilters(const aSource: string): string;
implementation
uses
SysUtils;
function evIsGraphicFileStream(const aStream: TStream): Boolean;
var
l_FileType : TIOFileType;
begin
l_FileType := FindStreamFormat(aStream);
Result := l_FileType in cioSupportedGraphicsFiles;
end;
function evIsGraphicFile(const aFileName: string): Boolean;
var
l_Ext: string;
begin
l_Ext := LowerCase(ExtractFileExt(aFileName));
Result := (l_Ext = '.bmp') or (l_Ext = '.jpg') or (l_Ext = '.gif') or (l_Ext = '.png');
end;
function evAddSupportedGraphicsFilters(const aSource: string): string;
begin
Result := aSource + '|BMP-פאיכ (*.bmp)|*.bmp|PNG-פאיכ (*.png)|*.png|JPG-פאיכ (*.jpg)|*.jpg|GIF-פאיכ (*.gif)|*.gif'
end;
end.
|
unit FindUnit.DelphiVlcWrapper;
interface
uses
Windows;
type
TDelphiVLCWrapper = class(TObject)
private
class procedure FindEditorHandle;
public
class function GetEditorRect: TRect;
end;
implementation
uses
Classes, Messages;
var
FFound: Boolean;
FEditHandler: Cardinal;
{ TDelphiVLCWrapper }
function EnumChildProc(AHandle: THandle; Params: integer): BOOL; stdcall;
var
Buffer: array[0..255] of Char;
Caption: array[0..255] of Char;
Item: string;
begin
if FFound then
Exit;
Result := True;
GetClassName(AHandle, Buffer, SizeOf(Buffer)-1);
SendMessage(AHandle, WM_GETTEXT, 256, Integer(@Caption));
Item := Buffer;
if Item = 'TEditControl' then
begin
FEditHandler := AHandle;
FFound := True;
Exit;
end;
EnumChildWindows(AHandle, @EnumChildProc, 0)
end;
class procedure TDelphiVLCWrapper.FindEditorHandle;
var
DelphiHand: Cardinal;
begin
FFound := False;
DelphiHand := FindWindow('TAppBuilder', nil);
EnumChildWindows(DelphiHand, @EnumChildProc, 0);
FFound := True;
end;
class function TDelphiVLCWrapper.GetEditorRect: TRect;
begin
if not FFound then
FindEditorHandle;
if not Windows.GetWindowRect(FEditHandler, Result) then
begin
Result.Left := 20;
Result.Top := 20;
Result.Right := 20;
end;
end;
end.
|
TObject = class
constructor Create;
procedure Free;
end;
TPersistent = class(TObject)
procedure Assign(Source: TPersistent);
end;
TComponent = class(TPersistent)
function FindComponent(AName: String): TComponent;
constructor Create(AOwner: TComponent);
property Owner: TComponent; read write;
procedure DestroyComponents;
procedure Destroying;
procedure FreeNotification(AComponent: TComponent);
procedure InsertComponent(AComponent: TComponent);
procedure RemoveComponent(AComponent: TComponent);
property Components[Index: Integer]: TComponent; read;
property ComponentCount: Integer; read;
property ComponentIndex: Integer; read write;
property ComponentState: Byte; read;
property DesignInfo: Longint; read write;
property Name: String; read write;
property Tag: Longint; read write;
end;
TStrings = class(TPersistent)
function Add(S: String): Integer;
procedure Append(S: String);
procedure AddStrings(Strings: TStrings);
procedure Clear;
procedure Delete(Index: Integer);
function IndexOf(const S: String): Integer;
procedure Insert(Index: Integer; S: String);
property Count: Integer; read;
property Text: String; read write;
property CommaText: String; read write;
procedure LoadFromFile(FileName: String);
procedure SaveToFile(FileName: String);
property Strings[Index: Integer]: String; read write;
property Objects[Index: Integer]: TObject; read write;
end;
TNotifyEvent = procedure(Sender: TObject);
TStringList = class(TStrings)
function Find(S: String; var Index: Integer): Boolean;
procedure Sort;
property Duplicates: TDuplicates; read write;
property Sorted: Boolean; read write;
property OnChange: TNotifyEvent; read write;
property OnChanging: TNotifyEvent; read write;
end;
TStream = class(TObject)
function Read(Buffer: String; Count: Longint): Longint;
function Write(Buffer: String; Count: Longint): Longint;
function Seek(Offset: Longint; Origin: Word): Longint;
procedure ReadBuffer(Buffer: String; Count: Longint);
procedure WriteBuffer(Buffer: String; Count: Longint);
function CopyFrom(Source: TStream; Count: Longint): Longint;
property Position: Longint; read write;
property Size: Longint; read write;
end;
THandleStream = class(TStream)
constructor Create(AHandle: Integer);
property Handle: Integer; read;
end;
TFileStream = class(THandleStream)
constructor Create(Filename: String; Mode: Word);
end;
TGraphicsObject = class(TPersistent)
property OnChange: TNotifyEvent; read write;
end;
TFontStyle = (fsBold, fsItalic, fsUnderline, fsStrikeOut);
TFontStyles = set of TFontStyle;
TFont = class(TGraphicsObject)
constructor Create;
property Handle: Integer; read;
property Color: Integer; read write;
property Height: Integer; read write;
property Name: String; read write;
property Pitch: Byte; read write;
property Size: Integer; read write;
property PixelsPerInch: Integer; read write;
property Style: TFontStyles; read write;
end;
TCanvas = class(TPersistent)
procedure Arc(X1, Y1, X2, Y2, X3, Y3, X4, Y4: Integer);
procedure Chord(X1, Y1, X2, Y2, X3, Y3, X4, Y4: Integer);
procedure Draw(X, Y: Integer; Graphic: TGraphic);
procedure Ellipse(X1, Y1, X2, Y2: Integer);
procedure FloodFill(X, Y: Integer; Color: TColor; FillStyle: Byte);
procedure LineTo(X, Y: Integer);
procedure MoveTo(X, Y: Integer);
procedure Pie(X1, Y1, X2, Y2, X3, Y3, X4, Y4: Integer);
procedure Rectangle(X1, Y1, X2, Y2: Integer);
procedure Refresh;
procedure RoundRect(X1, Y1, X2, Y2, X3, Y3: Integer);
function TextHeight(Text: String): Integer;
procedure TextOut(X, Y: Integer; Text: String);
function TextWidth(Text: String): Integer;
property Handle: Integer; read write;
property Pixels: Integer Integer Integer; read write;
property Brush: TBrush; read;
property CopyMode: Byte; read write;
property Font: TFont; read;
property Pen: TPen; read;
end;
TPenMode = (pmBlack, pmWhite, pmNop, pmNot, pmCopy, pmNotCopy, pmMergePenNot, pmMaskPenNot, pmMergeNotPen, pmMaskNotPen, pmMerge, pmNotMerge, pmMask, pmNotMask, pmXor, pmNotXor);
TPenStyle = (psSolid, psDash, psDot, psDashDot, psDashDotDot, psClear, psInsideFrame);
TPen = class(TGraphicsObject)
constructor Create;
property Color: TColor; read write;
property Mode: TPenMode; read write;
property Style: TPenStyle; read write;
property Width: Integer; read write;
end;
TBrushStyle = (bsSolid, bsClear, bsHorizontal, bsVertical, bsFDiagonal, bsBDiagonal, bsCross, bsDiagCross);
TBrush = class(TGraphicsObject)
constructor Create;
property Color: TColor; read write;
property Style: TBrushStyle; read write;
end;
TGraphic = class(TPersistent)
procedure LoadFromFile(const Filename: String);
procedure SaveToFile(const Filename: String);
property Empty: Boolean; read write;
property Height: Integer; read write;
property Modified: Boolean; read write;
property Width: Integer; read write;
property OnChange: TNotifyEvent; read write;
end;
TBitmap = class(TGraphic)
procedure LoadFromStream(Stream: TStream);
procedure SaveToStream(Stream: TStream);
property Canvas: TCanvas; read write;
property Handle: HBITMAP; read write;
end;
TAlign = (alNone, alTop, alBottom, alLeft, alRight, alClient);
TControl = class(TComponent)
constructor Create(AOwner: TComponent);
procedure BringToFront;
procedure Hide;
procedure Invalidate;
procedure Refresh;
procedure Repaint;
procedure SendToBack;
procedure Show;
procedure Update;
procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer);
property Left: Integer; read write;
property Top: Integer; read write;
property Width: Integer; read write;
property Height: Integer; read write;
property Hint: String; read write;
property Align: TAlign; read write;
property ClientHeight: Longint; read write;
property ClientWidth: Longint; read write;
property ShowHint: Boolean; read write;
property Visible: Boolean; read write;
property Enabled: Boolean; read write;
property Hint: String; read write;
property Cursor: Integer; read write;
end;
TWinControl = class(TControl)
property Parent: TWinControl; read write;
property ParentBackground: Boolean; read write;
property Handle: Longint; read write;
property Showing: Boolean; read;
property TabOrder: Integer; read write;
property TabStop: Boolean; read write;
function CanFocus: Boolean;
function Focused: Boolean;
property Controls[Index: Integer]: TControl; read;
property ControlCount: Integer; read;
end;
TGraphicControl = class(TControl)
end;
TCustomControl = class(TWinControl)
end;
TScrollBarKind = (sbHorizontal, sbVertical);
TScrollBarInc = SmallInt;
TScrollingWinControl = class(TWinControl)
procedure ScrollInView(AControl: TControl);
end;
TFormBorderStyle = (bsNone, bsSingle, bsSizeable, bsDialog, bsToolWindow, bsSizeToolWin);
TBorderIcon = (biSystemMenu, biMinimize, biMaximize, biHelp);
TBorderIcons = set of TBorderIcon;
TPosition = (poDesigned, poDefault, poDefaultPosOnly, poDefaultSizeOnly, poScreenCenter, poDesktopCenter, poMainFormCenter, poOwnerFormCenter);
TCloseAction = (caNone, caHide, caFree, caMinimize);
TCloseEvent = procedure(Sender: TObject; var Action: TCloseAction);
TCloseQueryEvent = procedure(Sender: TObject; var CanClose: Boolean);
TEShiftState = (ssShift, ssAlt, ssCtrl, ssLeft, ssRight, ssMiddle, ssDouble);
TShiftState = set of TEShiftState;
TKeyEvent = procedure(Sender: TObject; var Key: Word; Shift: TShiftState);
TKeyPressEvent = procedure(Sender: TObject; var Key: Char);
TForm = class(TScrollingWinControl)
constructor CreateNew(AOwner: TComponent);
procedure Close;
procedure Hide;
procedure Show;
function ShowModal: Integer;
procedure Release;
property Active: Boolean; read;
property ActiveControl: TWinControl; read write;
property BorderIcons: TBorderIcons; read write;
property BorderStyle: TFormBorderStyle; read write;
property Caption: String; read write;
property AutoScroll: Boolean; read write;
property Color: TColor; read write;
property Font: TFont; read write;
property FormStyle: TFormStyle; read write;
property KeyPreview: Boolean; read write;
property Position: TPosition; read write;
property OnActivate: TNotifyEvent; read write;
property OnClick: TNotifyEvent; read write;
property OnDblClick: TNotifyEvent; read write;
property OnClose: TCloseEvent; read write;
property OnCloseQuery: TCloseQueryEvent; read write;
property OnCreate: TNotifyEvent; read write;
property OnDestroy: TNotifyEvent; read write;
property OnDeactivate: TNotifyEvent; read write;
property OnHide: TNotifyEvent; read write;
property OnKeyDown: TKeyEvent; read write;
property OnKeyPress: TKeyPressEvent; read write;
property OnKeyUp: TKeyEvent; read write;
property OnResize: TNotifyEvent; read write;
property OnShow: TNotifyEvent; read write;
end;
TCustomLabel = class(TGraphicControl)
end;
TAlignment = (taLeftJustify, taRightJustify, taCenter);
TLabel = class(TCustomLabel)
property Alignment: TAlignment; read write;
property AutoSize: Boolean; read write;
property Caption: String; read write;
property Color: TColor; read write;
property FocusControl: TWinControl; read write;
property Font: TFont; read write;
property WordWrap: Boolean; read write;
property OnClick: TNotifyEvent; read write;
property OnDblClick: TNotifyEvent; read write;
end;
TCustomEdit = class(TWinControl)
procedure Clear;
procedure ClearSelection;
procedure SelectAll;
property Modified: Boolean; read write;
property SelLength: Integer; read write;
property SelStart: Integer; read write;
property SelText: String; read write;
property Text: String; read write;
end;
TBorderStyle = TFormBorderStyle;
TEditCharCase = (ecNormal, ecUpperCase, ecLowerCase);
TEdit = class(TCustomEdit)
property AutoSelect: Boolean; read write;
property AutoSize: Boolean; read write;
property BorderStyle: TBorderStyle; read write;
property CharCase: TEditCharCase; read write;
property Color: TColor; read write;
property Font: TFont; read write;
property HideSelection: Boolean; read write;
property MaxLength: Integer; read write;
property PasswordChar: Char; read write;
property ReadOnly: Boolean; read write;
property Text: String; read write;
property OnChange: TNotifyEvent; read write;
property OnClick: TNotifyEvent; read write;
property OnDblClick: TNotifyEvent; read write;
property OnKeyDown: TKeyEvent; read write;
property OnKeyPress: TKeyPressEvent; read write;
property OnKeyUp: TKeyEvent; read write;
end;
TNewEdit = class(TEdit)
end;
TCustomMemo = class(TCustomEdit)
property Lines: TStrings; read write;
end;
TScrollStyle = (ssNone, ssHorizontal, ssVertical, ssBoth);
TMemo = class(TCustomMemo)
property Lines: TStrings; read write;
property Alignment: TAlignment; read write;
property BorderStyle: TBorderStyle; read write;
property Color: TColor; read write;
property Font: TFont; read write;
property HideSelection: Boolean; read write;
property MaxLength: Integer; read write;
property ReadOnly: Boolean; read write;
property ScrollBars: TScrollStyle; read write;
property WantReturns: Boolean; read write;
property WantTabs: Boolean; read write;
property WordWrap: Boolean; read write;
property OnChange: TNotifyEvent; read write;
property OnClick: TNotifyEvent; read write;
property OnDblClick: TNotifyEvent; read write;
property OnKeyDown: TKeyEvent; read write;
property OnKeyPress: TKeyPressEvent; read write;
property OnKeyUp: TKeyEvent; read write;
end;
TNewMemo = class(TMemo)
end;
TCustomComboBox = class(TWinControl)
property DroppedDown: Boolean; read write;
property Items: TStrings; read write;
property ItemIndex: Integer; read write;
end;
TComboBoxStyle = (csDropDown, csSimple, csDropDownList, csOwnerDrawFixed, csOwnerDrawVariable);
TComboBox = class(TCustomComboBox)
property Style: TComboBoxStyle; read write;
property Color: TColor; read write;
property DropDownCount: Integer; read write;
property Font: TFont; read write;
property MaxLength: Integer; read write;
property Sorted: Boolean; read write;
property Text: String; read write;
property OnChange: TNotifyEvent; read write;
property OnClick: TNotifyEvent; read write;
property OnDblClick: TNotifyEvent; read write;
property OnDropDown: TNotifyEvent; read write;
property OnKeyDown: TKeyEvent; read write;
property OnKeyPress: TKeyPressEvent; read write;
property OnKeyUp: TKeyEvent; read write;
end;
TNewComboBox = class(TComboBox)
end;
TButtonControl = class(TWinControl)
end;
TButton = class(TButtonControl)
property Cancel: Boolean; read write;
property Caption: String; read write;
property Default: Boolean; read write;
property Font: TFont; read write;
property ModalResult: Longint; read write;
property OnClick: TNotifyEvent; read write;
end;
TNewButton = class(TButton)
end;
TCustomCheckBox = class(TButtonControl)
end;
TCheckBoxState = (cbUnchecked, cbChecked, cbGrayed);
TCheckBox = class(TCustomCheckBox)
property Alignment: TAlignment; read write;
property AllowGrayed: Boolean; read write;
property Caption: String; read write;
property Checked: Boolean; read write;
property Color: TColor; read write;
property Font: TFont; read write;
property State: TCheckBoxState; read write;
property OnClick: TNotifyEvent; read write;
end;
TNewCheckBox = class(TCheckBox)
end;
TRadioButton = class(TButtonControl)
property Alignment: TAlignment; read write;
property Caption: String; read write;
property Checked: Boolean; read write;
property Color: TColor; read write;
property Font: TFont; read write;
property OnClick: TNotifyEvent; read write;
property OnDblClick: TNotifyEvent; read write;
end;
TNewRadioButton = class(TRadioButton)
end;
TCustomListBox = class(TWinControl)
property Items: TStrings; read write;
property ItemIndex: Integer; read write;
property SelCount: Integer; read;
property Selected[Index: Integer]: Boolean; read write;
end;
TListBoxStyle = (lbStandard, lbOwnerDrawFixed, lbOwnerDrawVariable);
TListBox = class(TCustomListBox)
property BorderStyle: TBorderStyle; read write;
property Color: TColor; read write;
property Font: TFont; read write;
property MultiSelect: Boolean; read write;
property Sorted: Boolean; read write;
property Style: TListBoxStyle; read write;
property OnClick: TNotifyEvent; read write;
property OnDblClick: TNotifyEvent; read write;
property OnKeyDown: TKeyEvent; read write;
property OnKeyPress: TKeyPressEvent; read write;
property OnKeyUp: TKeyEvent; read write;
end;
TNewListBox = class(TListBox)
end;
TBevelShape = (bsBox, bsFrame, bsTopLine, bsBottomLine, bsLeftLine, bsRightLine, bsSpacer);
TBevelStyle = (bsLowered, bsRaised);
TBevel = class(TGraphicControl)
property Shape: TBevelShape; read write;
property Style: TBevelStyle; read write;
end;
TCustomPanel = class(TCustomControl)
end;
TPanelBevel = (bvNone, bvLowered, bvRaised, bvSpace);
TBevelWidth = Longint;
TBorderWidth = Longint;
TPanel = class(TCustomPanel)
property Alignment: TAlignment; read write;
property BevelInner: TPanelBevel; read write;
property BevelOuter: TPanelBevel; read write;
property BevelWidth: TBevelWidth; read write;
property BorderWidth: TBorderWidth; read write;
property BorderStyle: TBorderStyle; read write;
property Caption: String; read write;
property Color: TColor; read write;
property Font: TFont; read write;
property OnClick: TNotifyEvent; read write;
property OnDblClick: TNotifyEvent; read write;
end;
TNewStaticText = class(TWinControl)
function AdjustHeight: Integer;
property AutoSize: Boolean; read write;
property Caption: String; read write;
property Color: TColor; read write;
property FocusControl: TWinControl; read write;
property Font: TFont; read write;
property ForceLTRReading: Boolean; read write;
property ShowAccelChar: Boolean; read write;
property WordWrap: Boolean; read write;
property OnClick: TNotifyEvent; read write;
property OnDblClick: TNotifyEvent; read write;
end;
TCheckItemOperation = (coUncheck, coCheck, coCheckWithChildren);
TNewCheckListBox = class(TCustomListBox)
function AddCheckBox(const ACaption, ASubItem: String; ALevel: Byte; AChecked, AEnabled, AHasInternalChildren, ACheckWhenParentChecked: Boolean; AObject: TObject): Integer;
function AddGroup(ACaption, ASubItem: String; ALevel: Byte; AObject: TObject): Integer;
function AddRadioButton(const ACaption, ASubItem: String; ALevel: Byte; AChecked, AEnabled: Boolean; AObject: TObject): Integer;
function CheckItem(const Index: Integer; const AOperation: TCheckItemOperation): Boolean;
property Checked[Index: Integer]: Boolean; read write;
property State[Index: Integer]: TCheckBoxState; read write;
property ItemCaption[Index: Integer]: String; read write;
property ItemEnabled[Index: Integer]: Boolean; read write;
property ItemLevel[Index: Integer]: Byte; read;
property ItemObject[Index: Integer]: TObject; read write;
property ItemSubItem[Index: Integer]: String; read write;
property Flat: Boolean; read write;
property MinItemHeight: Integer; read write;
property Offset: Integer; read write;
property OnClickCheck: TNotifyEvent; read write;
property BorderStyle: TBorderStyle; read write;
property Color: TColor; read write;
property Font: TFont; read write;
property Sorted: Boolean; read write;
property OnClick: TNotifyEvent; read write;
property OnDblClick: TNotifyEvent; read write;
property OnKeyDown: TKeyEvent; read write;
property OnKeyPress: TKeyPressEvent; read write;
property OnKeyUp: TKeyEvent; read write;
property ShowLines: Boolean; read write;
property WantTabs: Boolean; read write;
property RequireRadioSelection: Boolean; read write;
end;
TNewProgressBarState = (npbsNormal, npbsError, npbsPaused);
TNewProgressBarStyle = (npbstNormal, npbstMarquee);
TNewProgressBar = class(TWinControl)
property Min: Longint; read write;
property Max: Longint; read write;
property Position: Longint; read write;
property State: TNewProgressBarState; read write;
property Style: TNewProgressBarStyle; read write;
property Visible: Boolean; read write;
end;
TRichEditViewer = class(TMemo)
property RTFText: AnsiString; write;
property UseRichEdit: Boolean; read write;
end;
TPasswordEdit = class(TCustomEdit)
property AutoSelect: Boolean; read write;
property AutoSize: Boolean; read write;
property BorderStyle: TBorderStyle; read write;
property Color: TColor; read write;
property Font: TFont; read write;
property HideSelection: Boolean; read write;
property MaxLength: Integer; read write;
property Password: Boolean; read write;
property ReadOnly: Boolean; read write;
property Text: String; read write;
property OnChange: TNotifyEvent; read write;
property OnClick: TNotifyEvent; read write;
property OnDblClick: TNotifyEvent; read write;
property OnKeyDown: TKeyEvent; read write;
property OnKeyPress: TKeyPressEvent; read write;
property OnKeyUp: TKeyEvent; read write;
end;
TCustomFolderTreeView = class(TWinControl)
procedure ChangeDirectory(const Value: String; const CreateNewItems: Boolean);
procedure CreateNewDirectory(const ADefaultName: String);
property: Directory: String; read write;
end;
TFolderRenameEvent = procedure(Sender: TCustomFolderTreeView; var NewName: String; var Accept: Boolean);
TFolderTreeView = class(TCustomFolderTreeView)
property OnChange: TNotifyEvent; read write;
property OnRename: TFolderRenameEvent; read write;
end;
TStartMenuFolderTreeView = class(TCustomFolderTreeView)
procedure SetPaths(const AUserPrograms, ACommonPrograms, AUserStartup, ACommonStartup: String);
property OnChange: TNotifyEvent; read write;
property OnRename: TFolderRenameEvent; read write;
end;
TBitmapImage = class(TGraphicControl)
property AutoSize: Boolean; read write;
property BackColor: TColor; read write;
property Center: Boolean; read write;
property Bitmap: TBitmap; read write;
property ReplaceColor: TColor; read write;
property ReplaceWithColor: TColor; read write;
property Stretch: Boolean; read write;
property OnClick: TNotifyEvent; read write;
property OnDblClick: TNotifyEvent; read write;
end;
TNewNotebook = class(TWinControl)
function FindNextPage(CurPage: TNewNotebookPage; GoForward: Boolean): TNewNotebookPage;
property PageCount: Integer; read write;
property Pages[Index: Integer]: TNewNotebookPage; read;
property ActivePage: TNewNotebookPage; read write;
end;
TNewNotebookPage = class(TCustomControl)
property Color: TColor; read write;
property Notebook: TNewNotebook; read write;
property PageIndex: Integer; read write;
end;
TWizardPageNotifyEvent = procedure(Sender: TWizardPage);
TWizardPageButtonEvent = function(Sender: TWizardPage): Boolean;
TWizardPageCancelEvent = procedure(Sender: TWizardPage; var ACancel, AConfirm: Boolean);
TWizardPageShouldSkipEvent = function(Sender: TWizardPage): Boolean;
TWizardPage = class(TComponent)
property ID: Integer; read;
property Caption: String; read write;
property Description: String; read write;
property Surface: TNewNotebookPage; read write;
property SurfaceHeight: Integer; read write;
property SurfaceWidth: Integer; read write;
property OnActivate: TWizardPageNotifyEvent; read write;
property OnBackButtonClick: TWizardPageButtonEvent; read write;
property OnCancelButtonClick: TWizardPageCancelEvent; read write;
property OnNextButtonClick: TWizardPageButtonEvent; read write;
property OnShouldSkipPage: TWizardPageShouldSkipEvent; read write;
end;
TInputQueryWizardPage = class(TWizardPage)
function Add(const APrompt: String; const APassword: Boolean): Integer;
property Edits[Index: Integer]: TPasswordEdit; read;
property PromptLabels[Index: Integer]: TNewStaticText; read;
property SubCaptionLabel: TNewStaticText; read;
property Values[Index: Integer]: String; read write;
end;
TInputOptionWizardPage = class(TWizardPage)
function Add(const ACaption: String): Integer;
function AddEx(const ACaption: String; const ALevel: Byte; const AExclusive: Boolean): Integer;
property CheckListBox: TNewCheckListBox; read;
property SelectedValueIndex: Integer; read write;
property SubCaptionLabel: TNewStaticText; read;
property Values[Index: Integer]: Boolean; read write;
end;
TInputDirWizardPage = class(TWizardPage)
function Add(const APrompt: String): Integer;
property Buttons[Index: Integer]: TNewButton; read;
property Edits[Index: Integer]: TEdit; read;
property PromptLabels[Index: Integer]: TNewStaticText; read;
property SubCaptionLabel: TNewStaticText; read;
property Values[Index: Integer]: String; read write;
end;
TInputFileWizardPage = class(TWizardPage)
function Add(const APrompt, AFilter, ADefaultExtension: String): Integer;
property Buttons[Index: Integer]: TNewButton; read;
property Edits[Index: Integer]: TEdit; read;
property PromptLabels[Index: Integer]: TNewStaticText; read;
property SubCaptionLabel: TNewStaticText; read;
property Values[Index: Integer]: String; read write;
property IsSaveButton[Index: Integer]: Boolean; read write;
end;
TOutputMsgWizardPage = class(TWizardPage)
property MsgLabel: TNewStaticText; read;
end;
TOutputMsgMemoWizardPage = class(TWizardPage)
property RichEditViewer: TRichEditViewer; read;
property SubCaptionLabel: TNewStaticText; read;
end;
TOutputProgressWizardPage = class(TWizardPage)
procedure Hide;
property Msg1Label: TNewStaticText; read;
property Msg2Label: TNewStaticText; read;
property ProgressBar: TNewProgressBar; read;
procedure SetProgress(const Position, Max: Longint);
procedure SetText(const Msg1, Msg2: String);
procedure Show;
end;
TUIStateForm = class(TForm)
end;
TSetupForm = class(TUIStateForm)
procedure Center;
procedure CenterInsideControl(const Ctl: TWinControl; const InsideClientArea: Boolean);
procedure FlipControlsIfNeeded;
property ControlsFlipped: Boolean; read;
property FlipControlsOnShow: Boolean; read write;
property RightToLeft: Boolean; read;
end;
TMainForm = class(TSetupForm)
procedure ShowAboutBox;
end;
TWizardForm = class(TSetupForm)
property CancelButton: TNewButton; read;
property NextButton: TNewButton; read;
property BackButton: TNewButton; read;
property Notebook1: TNotebook; read;
property Notebook2: TNotebook; read;
property WelcomePage: TNewNotebookPage; read;
property InnerPage: TNewNotebookPage; read;
property FinishedPage: TNewNotebookPage; read;
property LicensePage: TNewNotebookPage; read;
property PasswordPage: TNewNotebookPage; read;
property InfoBeforePage: TNewNotebookPage; read;
property UserInfoPage: TNewNotebookPage; read;
property SelectDirPage: TNewNotebookPage; read;
property SelectComponentsPage: TNewNotebookPage; read;
property SelectProgramGroupPage: TNewNotebookPage; read;
property SelectTasksPage: TNewNotebookPage; read;
property ReadyPage: TNewNotebookPage; read;
property PreparingPage: TNewNotebookPage; read;
property InstallingPage: TNewNotebookPage; read;
property InfoAfterPage: TNewNotebookPage; read;
property DiskSpaceLabel: TNewStaticText; read;
property DirEdit: TEdit; read;
property GroupEdit: TNewEdit; read;
property NoIconsCheck: TNewCheckBox; read;
property PasswordLabel: TNewStaticText; read;
property PasswordEdit: TPasswordEdit; read;
property PasswordEditLabel: TNewStaticText; read;
property ReadyMemo: TNewMemo; read;
property TypesCombo: TNewComboBox; read;
property Bevel: TBevel; read;
property WizardBitmapImage: TBitmapImage; read;
property WelcomeLabel1: TNewStaticText; read;
property InfoBeforeMemo: TRichEditViewer; read;
property InfoBeforeClickLabel: TNewStaticText; read;
property MainPanel: TPanel; read;
property Bevel1: TBevel; read;
property PageNameLabel: TNewStaticText; read;
property PageDescriptionLabel: TNewStaticText; read;
property WizardSmallBitmapImage: TBitmapImage; read;
property ReadyLabel: TNewStaticText; read;
property FinishedLabel: TNewStaticText; read;
property YesRadio: TNewRadioButton; read;
property NoRadio: TNewRadioButton; read;
property WizardBitmapImage2: TBitmapImage; read;
property WelcomeLabel2: TNewStaticText; read;
property LicenseLabel1: TNewStaticText; read;
property LicenseMemo: TRichEditViewer; read;
property InfoAfterMemo: TRichEditViewer; read;
property InfoAfterClickLabel: TNewStaticText; read;
property ComponentsList: TNewCheckListBox; read;
property ComponentsDiskSpaceLabel: TNewStaticText; read;
property BeveledLabel: TNewStaticText; read;
property StatusLabel: TNewStaticText; read;
property FilenameLabel: TNewStaticText; read;
property ProgressGauge: TNewProgressBar; read;
property SelectDirLabel: TNewStaticText; read;
property SelectStartMenuFolderLabel: TNewStaticText; read;
property SelectComponentsLabel: TNewStaticText; read;
property SelectTasksLabel: TNewStaticText; read;
property LicenseAcceptedRadio: TNewRadioButton; read;
property LicenseNotAcceptedRadio: TNewRadioButton; read;
property UserInfoNameLabel: TNewStaticText; read;
property UserInfoNameEdit: TNewEdit; read;
property UserInfoOrgLabel: TNewStaticText; read;
property UserInfoOrgEdit: TNewEdit; read;
property PreparingErrorBitmapImage: TBitmapImage; read;
property PreparingLabel: TNewStaticText; read;
property FinishedHeadingLabel: TNewStaticText; read;
property UserInfoSerialLabel: TNewStaticText; read;
property UserInfoSerialEdit: TNewEdit; read;
property TasksList: TNewCheckListBox; read;
property RunList: TNewCheckListBox; read;
property DirBrowseButton: TNewButton; read;
property GroupBrowseButton: TNewButton; read;
property SelectDirBitmapImage: TBitmapImage; read;
property SelectGroupBitmapImage: TBitmapImage; read;
property SelectDirBrowseLabel: TNewStaticText; read;
property SelectStartMenuFolderBrowseLabel: TNewStaticText; read;
property PreparingYesRadio: TNewRadioButton; read;
property PreparingNoRadio: TNewRadioButton; read;
property PreparingMemo: TNewMemo; read;
property CurPageID: Integer; read;
function AdjustLabelHeight(ALabel: TNewStaticText): Integer;
procedure IncTopDecHeight(AControl: TControl; Amount: Integer);
property PrevAppDir: String; read;
end;
TUninstallProgressForm = class(TSetupForm)
property OuterNotebook: TNewNotebook; read;
property InnerPage: TNewNotebookPage; read;
property InnerNotebook: TNewNotebook; read;
property InstallingPage: TNewNotebookPage; read;
property MainPanel: TPanel; read;
property PageNameLabel: TNewStaticText; read;
property PageDescriptionLabel: TNewStaticText; read;
property WizardSmallBitmapImage: TBitmapImage; read;
property Bevel1: TBevel; read;
property StatusLabel: TNewStaticText; read;
property ProgressBar: TNewProgressBar; read;
property BeveledLabel: TNewStaticText; read;
property Bevel: TBevel; read;
property CancelButton: TNewButton; read;
end; |
{ Date Created: 5/25/00 5:01:01 PM }
unit InfoDIRYCODETable;
interface
uses
Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf;
type
TInfoDIRYCODERecord = record
PCode: String[6];
PDescription: String[30];
PLeadTime: String[4];
End;
TInfoDIRYCODEBuffer = class(TDataBuf)
protected
function PtrIndex(Index:integer):Pointer;override;
public
Data: TInfoDIRYCODERecord
end;
TEIInfoDIRYCODE = (InfoDIRYCODEPrimaryKey);
TInfoDIRYCODETable = class( TDBISAMTableAU )
private
FDFCode: TStringField;
FDFDescription: TStringField;
FDFLeadTime: TStringField;
procedure SetPCode(const Value: String);
function GetPCode:String;
procedure SetPDescription(const Value: String);
function GetPDescription:String;
procedure SetPLeadTime(const Value: String);
function GetPLeadTime:String;
function GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string;
procedure SetEnumIndex(Value: TEIInfoDIRYCODE);
function GetEnumIndex: TEIInfoDIRYCODE;
protected
function CreateField( const FieldName : string ): TField;
procedure CreateFields; virtual;
procedure SetActive(Value: Boolean); override;
procedure LoadFieldDefs(AStringList:TStringList);override;
procedure LoadIndexDefs(AStringList:TStringList);override;
public
function GetDataBuffer:TInfoDIRYCODERecord;
procedure StoreDataBuffer(ABuffer:TInfoDIRYCODERecord);
property DFCode: TStringField read FDFCode;
property DFDescription: TStringField read FDFDescription;
property DFLeadTime: TStringField read FDFLeadTime;
property PCode: String read GetPCode write SetPCode;
property PDescription: String read GetPDescription write SetPDescription;
property PLeadTime: String read GetPLeadTime write SetPLeadTime;
procedure Validate; virtual;
published
property Active write SetActive;
property EnumIndex: TEIInfoDIRYCODE read GetEnumIndex write SetEnumIndex;
end; { TInfoDIRYCODETable }
procedure Register;
implementation
function TInfoDIRYCODETable.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 { TInfoDIRYCODETable.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; { TInfoDIRYCODETable.GenerateNewFieldName }
function TInfoDIRYCODETable.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; { TInfoDIRYCODETable.CreateField }
procedure TInfoDIRYCODETable.CreateFields;
begin
FDFCode := CreateField( 'Code' ) as TStringField;
FDFDescription := CreateField( 'Description' ) as TStringField;
FDFLeadTime := CreateField( 'LeadTime' ) as TStringField;
end; { TInfoDIRYCODETable.CreateFields }
procedure TInfoDIRYCODETable.SetActive(Value: Boolean);
begin
inherited SetActive(Value);
if Active then
CreateFields;
end; { TInfoDIRYCODETable.SetActive }
procedure TInfoDIRYCODETable.Validate;
begin
{ Enter Validation Code Here }
end; { TInfoDIRYCODETable.Validate }
procedure TInfoDIRYCODETable.SetPCode(const Value: String);
begin
DFCode.Value := Value;
end;
function TInfoDIRYCODETable.GetPCode:String;
begin
result := DFCode.Value;
end;
procedure TInfoDIRYCODETable.SetPDescription(const Value: String);
begin
DFDescription.Value := Value;
end;
function TInfoDIRYCODETable.GetPDescription:String;
begin
result := DFDescription.Value;
end;
procedure TInfoDIRYCODETable.SetPLeadTime(const Value: String);
begin
DFLeadTime.Value := Value;
end;
function TInfoDIRYCODETable.GetPLeadTime:String;
begin
result := DFLeadTime.Value;
end;
procedure TInfoDIRYCODETable.LoadFieldDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('Code, String, 6, N');
Add('Description, String, 30, N');
Add('LeadTime, String, 4, N');
end;
end;
procedure TInfoDIRYCODETable.LoadIndexDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('PrimaryKey, Code, Y, Y, N, N');
end;
end;
procedure TInfoDIRYCODETable.SetEnumIndex(Value: TEIInfoDIRYCODE);
begin
case Value of
InfoDIRYCODEPrimaryKey : IndexName := '';
end;
end;
function TInfoDIRYCODETable.GetDataBuffer:TInfoDIRYCODERecord;
var buf: TInfoDIRYCODERecord;
begin
fillchar(buf, sizeof(buf), 0);
buf.PCode := DFCode.Value;
buf.PDescription := DFDescription.Value;
buf.PLeadTime := DFLeadTime.Value;
result := buf;
end;
procedure TInfoDIRYCODETable.StoreDataBuffer(ABuffer:TInfoDIRYCODERecord);
begin
DFCode.Value := ABuffer.PCode;
DFDescription.Value := ABuffer.PDescription;
DFLeadTime.Value := ABuffer.PLeadTime;
end;
function TInfoDIRYCODETable.GetEnumIndex: TEIInfoDIRYCODE;
var iname : string;
begin
iname := uppercase(indexname);
if iname = '' then result := InfoDIRYCODEPrimaryKey;
end;
(********************************************)
(************ Register Component ************)
(********************************************)
procedure Register;
begin
RegisterComponents( 'Info Tables', [ TInfoDIRYCODETable, TInfoDIRYCODEBuffer ] );
end; { Register }
function TInfoDIRYCODEBuffer.PtrIndex(index:integer):Pointer;
begin
result := nil;
case index of
1 : result := @Data.PCode;
2 : result := @Data.PDescription;
3 : result := @Data.PLeadTime;
end;
end;
end. { InfoDIRYCODETable }
|
unit uModel.Dao.TV;
interface
uses
uEntityTV,
FireDAC.Comp.Client, uFiredac;
type
TModelDaoTV = class
private
Firedac : TFiredac;
FThis: TEntityTV;
FDS_TVs: TFDMemTable;
FDS_ProdutosNotTV: TFDMemTable;
FDS_ProdutosCadTV: TFDMemTable;
public
constructor Create;
destructor Destroy; override;
class function New: TModelDaoTV;
function This: TEntityTV;
function Recharge_DS_TVs: TModelDaoTV;
function Recharge_DS_ProdutosNotTV: TModelDaoTV;
function Recharge_DS_ProdutosCadTV: TModelDaoTV;
function DS_TVs: TFDMemTable;
function DS_ProdutosNotTV: TFDMemTable;
function DS_ProdutosCadTV: TFDMemTable;
end;
implementation
uses
System.SysUtils, Data.DB, FireDAC.Comp.DataSet, uDm;
{ TModelDaoTV }
constructor TModelDaoTV.Create;
begin
FThis := TEntityTV.New;
FDS_TVs := TFDMemTable.Create(Nil);
FDS_ProdutosNotTV := TFDMemTable.Create(Nil);
FDS_ProdutosCadTV := TFDMemTable.Create(Nil);
end;
destructor TModelDaoTV.Destroy;
begin
FThis.DisposeOf;
inherited;
end;
function TModelDaoTV.DS_ProdutosCadTV: TFDMemTable;
begin
Result := FDS_ProdutosCadTV;
end;
function TModelDaoTV.DS_ProdutosNotTV: TFDMemTable;
begin
Result := FDS_ProdutosNotTV;
end;
function TModelDaoTV.DS_TVs: TFDMemTable;
begin
Result := FDS_TVs;
end;
class function TModelDaoTV.New: TModelDaoTV;
begin
Result := Self.Create;
end;
function TModelDaoTV.Recharge_DS_ProdutosCadTV: TModelDaoTV;
var
vDataSet: TFDDataSet;
begin
Result := Self;
vDataSet := Firedac
.Active(False)
.SQLClear
.SQL(' select codbarra, descricao,vrvenda, unidade from produtos ')
.SQL(' where codbarra in (select codproduto from tv_prod where codtv = :IDTV) ')
.SQL(' group by codbarra, descricao, vrvenda, unidade')
.AddParan('IDTV',This.IDtv)
.Open
.DataSet;
if FDS_ProdutosCadTV.Active then
begin
FDS_ProdutosCadTV.EmptyDataSet;
FDS_ProdutosCadTV.Close;
end;
TFDMemTable(FDS_ProdutosCadTV).CloneCursor(vDataSet);
FDS_ProdutosCadTV.Filtered := False;
end;
function TModelDaoTV.Recharge_DS_ProdutosNotTV: TModelDaoTV;
var
vDataSet: TFDDataSet;
begin
vDataSet := Firedac
.Active(False)
.SQLClear
.SQL(' select codbarra, descricao,vrvenda,unidade from produtos p ')
.SQL(' where codbarra not in ')
.SQL(' (select codproduto from tv_prod where codtv = :IDTV) ')
.SQL(' group by codbarra,descricao,vrvenda,unidade')
.AddParan('IDTV',This.IDtv)
.Open
.DataSet;
if FDS_ProdutosNotTV.Active then
begin
FDS_ProdutosNotTV.EmptyDataSet;
FDS_ProdutosNotTV.Close;
end;
TFDMemTable(FDS_ProdutosNotTV).CloneCursor(vDataSet);
FDS_ProdutosNotTV.Filtered := False;
end;
function TModelDaoTV.Recharge_DS_TVs: TModelDaoTV;
var
vDataSet: TFDDataSet;
begin
Result := Self;
vDataSet := Firedac
.Active(False)
.SQLClear
.SQL('select IdTv,Descricao from tvs')
.Open
.DataSet;
if FDS_TVs.Active then
begin
FDS_TVs.EmptyDataSet;
FDS_TVs.Close;
end;
TFDMemTable(DS_TVs).CloneCursor(vDataSet);
FDS_TVs.Open;
FDS_TVs.Filtered := False;
end;
function TModelDaoTV.This: TEntityTV;
begin
Result := FThis;
end;
end.
|
unit fcLinesEditor;
{
//
// Property editor for line editing
//
// Copyright (c) 1999 by Woll2Woll Software
}
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, fcCommon, ComCtrls;
type
TLinesEditorForm = class(TForm)
OKButton: TButton;
CancelButton: TButton;
GroupBox1: TGroupBox;
LinesMemo: TMemo;
LinesLabel: TLabel;
procedure LinesMemoChange(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
function fcExecuteLinesEditor(Lines: TStringList): Boolean;
function fcExecuteTextEditor(Component: TPersistent; PropName: string;
ACaption: string): Boolean;
var
LinesEditorForm: TLinesEditorForm;
implementation
{$R *.DFM}
function fcExecuteLinesEditor(Lines: TStringList): Boolean;
begin
result := False;
with TLinesEditorForm.Create(nil) do
begin
LinesMemo.Lines.Assign(Lines);
if ShowModal = mrOK then
begin
Lines.Assign(LinesMemo.Lines);
result := True;
end;
Free;
end;
end;
function fcExecuteTextEditor(Component: TPersistent; PropName: string;
ACaption: string): Boolean;
begin
result := False;
with TLinesEditorForm.Create(nil) do
begin
Caption := ACaption;
LinesMemo.Text := fcGetStrProp(Component, PropName);
if ShowModal = mrOK then
begin
fcSetStrProp(Component, PropName, LinesMemo.Text);
result := True;
end;
Free;
end;
end;
procedure TLinesEditorForm.LinesMemoChange(Sender: TObject);
begin
LinesLabel.Caption := 'Lines: ' + InttoStr(LinesMemo.Lines.Count);
end;
end.
|
{ Subroutine SST_MEM_ALLOC_NAMESP (SIZE,P)
*
* Allocate memory that will be tied to the current most local name space.
* SIZE is the amount of memory to allocate, and P is returned pointing to the
* start of the new memory area.
}
module sst_MEM_ALLOC_NAMESP;
define sst_mem_alloc_namesp;
%include 'sst2.ins.pas';
procedure sst_mem_alloc_namesp ( {allocate memory tied to current name space}
in size: sys_int_adr_t; {amount of memory to allocate}
out p: univ_ptr); {pointer to start of new memory area}
begin
util_mem_grab (size, sst_names_p^.mem_p^, false, p);
end;
|
unit NLDPictureReg;
interface
uses Classes, NLDPicture;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('NLDelphi', [TNLDPicture]);
end;
end.
|
unit DAO.FinanceiroEmpresa;
interface
uses FireDAC.Comp.Client, System.SysUtils, DAO.Conexao, Model.FinanceiroEmpresa;
type
TFinanceiroEmpresaDAO = class
private
FConexao: TConexao;
public
constructor Create();
function GetID(iID: Integer): Integer;
function Insert(aFinanceiros: TFinanceiroEmpresa): Boolean;
function Update(aFinanceiros: TFinanceiroEmpresa): Boolean;
function Delete(aFinanceiros: TFinanceiroEmpresa): Boolean;
function Localizar(aParam: Array of variant): TFDQuery;
end;
const
TABLENAME = 'cadastro_financeiro_empresa';
implementation
function TFinanceiroEmpresaDAO.Insert(aFinanceiros: TFinanceiroEmpresa): Boolean;
var
sSQL: String;
FDQuery: TFDQuery;
begin
try
Result := False;
FDQuery := FConexao.ReturnQuery;
aFinanceiros.Sequencia := GetID(aFinanceiros.ID);
sSQL := 'INSERT INTO ' + TABLENAME + '(ID_EMPRESA, SEQ_FINANCEIRO, DES_TIPO_CONTA, COD_BANCO, ' +
'NUM_AGENCIA, NUM_CONTA, COD_OPERACAO) ' +
'VALUES (:pID_EMPRESA, :pSEQ_FINANCEIRO, :pDES_TIPO_CONTA, :pCOD_BANCO, :pNUM_AGENCIA, ' +
':pNUM_CONTA, :pCOD_OPERACAO);';
FDQuery.ExecSQL(sSQL,[aFinanceiros.ID, aFinanceiros.Sequencia, aFinanceiros.TipoConta,
aFinanceiros.Banco, aFinanceiros.Agencia, aFinanceiros.Conta, aFinanceiros.Operacao]);
Result := True;
finally
FDQuery.Free;
end;
end;
function TFinanceiroEmpresaDAO.Localizar(aParam: array of variant): TFDQuery;
var
FDQuery: TFDQuery;
begin
FDQuery := FConexao.ReturnQuery();
if Length(aParam) < 2 then Exit;
FDQuery.SQL.Clear;
FDQuery.SQL.Add('select * from ' + TABLENAME);
if aParam[0] = 'ID' then
begin
FDQuery.SQL.Add('WHERE ID_EMPRESA = :ID_EMPRESA');
FDQuery.ParamByName('ID_EMPRESA').AsInteger := aParam[1];
end;
if aParam[0] = 'SEQUENCIA' then
begin
FDQuery.SQL.Add('WHERE ID_EMPRESA = :ID_EMPRESA AND SEQ_FINANCEIRO = :SEQ_FINANCEIRO');
FDQuery.ParamByName('ID_EMPRESA').AsInteger := aParam[1];
FDQuery.ParamByName('SEQ_FINANCEIRO').AsInteger := aParam[2];
end;
if aParam[0] = 'TIPO' then
begin
FDQuery.SQL.Add('WHERE DES_TIPO_CONTA LIKE :DES_TIPO_CONTA');
FDQuery.ParamByName('DES_TIPO_CONTA').AsString := aParam[1];
end;
if aParam[0] = 'BANCO' then
begin
FDQuery.SQL.Add('WHERE COD_BANCO = :COD_BANCO');
FDQuery.ParamByName('COD_BANCO').AsString := aParam[1];
end;
if aParam[0] = 'AGENCIA' then
begin
FDQuery.SQL.Add('WHERE COD_AGENCIA = :COD_AGENCIA');
FDQuery.ParamByName('COD_AGENCIA').AsString := aParam[1];
end;
if aParam[0] = 'CONTA' then
begin
FDQuery.SQL.Add('WHERE NUM_CONTA = :NUM_CONTA');
FDQuery.ParamByName('NUM_CONTA').AsString := aParam[1];
end;
if aParam[0] = 'FILTRO' then
begin
FDQuery.SQL.Add('WHERE ' + aParam[1]);
end;
if aParam[0] = 'APOIO' then
begin
FDQuery.SQL.Clear;
FDQuery.SQL.Add('SELECT ' + aParam[1] + ' FROM ' + TABLENAME + ' ' + aParam[2]);
end;
FDQuery.Open();
Result := FDQuery;end;
function TFinanceiroEmpresaDAO.Update(aFinanceiros: TFinanceiroEmpresa): Boolean;
var
sSQL: String;
FDQuery: TFDQuery;
begin
try
Result := False;
FDQuery := FConexao.ReturnQuery;
sSQL := 'UPDATE ' + TABLENAME + 'SET ' +
'DES_TIPO_CONTA = :pDES_TIPO_CONTA, ' +
'COD_BANCO = :pCOD_BANCO, NUM_AGENCIA = :pNUM_AGENCIA, NUM_CONTA = :pNUM_CONTA, COD_OPERACAO = :pCOD_OPERACAO ' +
'WHERE ID_EMPRESA = :pID_EMPRESA AND SEQ_FINANCEIRO = :pSEQ_FINANCEIRO;';
FDQuery.ExecSQL(sSQL,[aFinanceiros.TipoConta, aFinanceiros.Banco, aFinanceiros.Agencia, aFinanceiros.Conta,
aFinanceiros.Operacao, aFinanceiros.ID, aFinanceiros.Sequencia]);
Result := True;
finally
FDQuery.Free;
end;
end;
constructor TFinanceiroEmpresaDAO.Create;
begin
FConexao := TConexao.Create;
end;
function TFinanceiroEmpresaDAO.Delete(aFinanceiros: TFinanceiroEmpresa): Boolean;
var
sSQL : String;
FDQuery: TFDQuery;
begin
try
Result := False;
FDQuery := FConexao.ReturnQuery;
if aFinanceiros.Sequencia = -1 then
begin
sSQL := 'DELETE FROM ' + TABLENAME + ' ' +
'WHERE ID_EMPRESA = :pID_EMPRESA';
FDQuery.ExecSQL(sSQL,[aFinanceiros.ID]);
end
else
begin
sSQL := 'DELETE FROM ' + TABLENAME + ' ' +
'WHERE ID_EMPRESA = :pID_EMPRESA AND SEQ_FINANCEIRO = :pSEQ_FINANCEIRO';
FDQuery.ExecSQL(sSQL,[aFinanceiros.ID, aFinanceiros.Sequencia]);
end;
Result := True;
finally
FDQuery.Free;
end;
end;
function TFinanceiroEmpresaDAO.GetID(iID: Integer): Integer;
var
FDQuery: TFDQuery;
begin
try
FDQuery := FConexao.ReturnQuery();
FDQuery.Open('select coalesce(max(SEQ_FINANCEIRO),0) + 1 from ' + TABLENAME + ' WHERE ID_EMPRESA = ' + iID.toString);
try
Result := FDQuery.Fields[0].AsInteger;
finally
FDQuery.Close;
end;
finally
FDQuery.Free;
end;end;
end.
|
unit bubblebobble_hw;
interface
uses {$IFDEF WINDOWS}windows,{$ENDIF}
nz80,main_engine,controls_engine,gfx_engine,ym_2203,ym_3812,
m680x,rom_engine,pal_engine,sound_engine;
function iniciar_bublbobl:boolean;
implementation
const
bublbobl_rom:array[0..1] of tipo_roms=(
(n:'a78-06-1.51';l:$8000;p:0;crc:$567934b6),(n:'a78-05-1.52';l:$10000;p:$8000;crc:$9f8ee242));
bublbobl_rom2:tipo_roms=(n:'a78-08.37';l:$8000;p:0;crc:$ae11a07b);
bublbobl_chars:array[0..11] of tipo_roms=(
(n:'a78-09.12';l:$8000;p:0;crc:$20358c22),(n:'a78-10.13';l:$8000;p:$8000;crc:$930168a9),
(n:'a78-11.14';l:$8000;p:$10000;crc:$9773e512),(n:'a78-12.15';l:$8000;p:$18000;crc:$d045549b),
(n:'a78-13.16';l:$8000;p:$20000;crc:$d0af35c5),(n:'a78-14.17';l:$8000;p:$28000;crc:$7b5369a8),
(n:'a78-15.30';l:$8000;p:$40000;crc:$6b61a413),(n:'a78-16.31';l:$8000;p:$48000;crc:$b5492d97),
(n:'a78-17.32';l:$8000;p:$50000;crc:$d69762d5),(n:'a78-18.33';l:$8000;p:$58000;crc:$9f243b68),
(n:'a78-19.34';l:$8000;p:$60000;crc:$66e9438c),(n:'a78-20.35';l:$8000;p:$68000;crc:$9ef863ad));
bublbobl_snd: tipo_roms=(n:'a78-07.46';l:$8000;p:0;crc:$4f9a26e8);
bublbobl_prom: tipo_roms=(n:'a71-25.41';l:$100;p:0;crc:$2d0f8545);
bublbobl_mcu_rom:tipo_roms=(n:'a78-01.17';l:$1000;p:$0;crc:$b1bfb53d);
//Dip
bublbobl_dip_a:array [0..5] of def_dip=(
(mask:$5;name:'Mode';number:4;dip:((dip_val:$4;dip_name:'Game - English'),(dip_val:$5;dip_name:'Game - Japanese'),(dip_val:$1;dip_name:'Test (Grid and Inputs)'),(dip_val:$0;dip_name:'Test (RAM and Sound)/Pause'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$2;name:'Flip Screen';number:2;dip:((dip_val:$2;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$8;name:'Demo Sounds';number:2;dip:((dip_val:$0;dip_name:'Off'),(dip_val:$8;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$30;name:'Coin A';number:4;dip:((dip_val:$10;dip_name:'2C 1C'),(dip_val:$30;dip_name:'1C 1C'),(dip_val:$0;dip_name:'2C 3C'),(dip_val:$20;dip_name:'1C 2C'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$c0;name:'Coin B';number:4;dip:((dip_val:$40;dip_name:'2C 1C'),(dip_val:$c0;dip_name:'1C 1C'),(dip_val:$0;dip_name:'2C 3C'),(dip_val:$80;dip_name:'1C 2C'),(),(),(),(),(),(),(),(),(),(),(),())),());
bublbobl_dip_b:array [0..4] of def_dip=(
(mask:$3;name:'Difficulty';number:4;dip:((dip_val:$2;dip_name:'Easy'),(dip_val:$3;dip_name:'Normal'),(dip_val:$1;dip_name:'Hard'),(dip_val:$0;dip_name:'Very Hard'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$c;name:'Bonus Life';number:4;dip:((dip_val:$8;dip_name:'20K 80K 300K'),(dip_val:$c;dip_name:'30K 100K 400K'),(dip_val:$4;dip_name:'40K 200K 500K'),(dip_val:$0;dip_name:'50K 250K 500K'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$30;name:'Lives';number:4;dip:((dip_val:$10;dip_name:'1'),(dip_val:$0;dip_name:'2'),(dip_val:$30;dip_name:'3'),(dip_val:$20;dip_name:'5'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$80;name:'ROM Type';number:2;dip:((dip_val:$80;dip_name:'IC52=512kb, IC53=none'),(dip_val:$0;dip_name:'IC52=256kb, IC53=256kb'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),());
var
memoria_rom:array [0..3,$0..$3fff] of byte;
mem_mcu:array[0..$fff] of byte;
mem_prom:array[0..$ff] of byte;
banco_rom,sound_stat,sound_latch:byte;
sound_nmi,video_enable:boolean;
ddr1,ddr2,ddr3,ddr4:byte;
port1_in,port1_out,port2_in,port2_out,port3_in,port3_out,port4_in,port4_out:byte;
procedure update_video_bublbobl;
var
nchar,color:word;
sx,x,goffs,gfx_offs:word;
flipx,flipy:boolean;
prom_line,atrib,atrib2,offs:byte;
xc,yc,sy,y,gfx_attr,gfx_num:byte;
begin
fill_full_screen(1,$100);
if video_enable then begin
sx:=0;
for offs:=0 to $bf do begin
if ((memoria[$dd00+(offs*4)]=0) and (memoria[$dd01+(offs*4)]=0) and (memoria[$dd02+(offs*4)]=0) and (memoria[$dd03+(offs*4)]=0)) then continue;
gfx_num:=memoria[$dd01+(offs*4)];
gfx_attr:=memoria[$dd03+(offs*4)];
prom_line:=$80+((gfx_num and $e0) shr 1);
gfx_offs:=(gfx_num and $1f) shl 7;
if ((gfx_num and $a0)=$a0) then gfx_offs:=gfx_offs or $1000;
sy:=256-memoria[$dd00+(offs*4)];
for yc:=0 to $1f do begin
atrib2:=mem_prom[prom_line+(yc shr 1)];
if (atrib2 and $08)<>0 then continue; // NEXT
if (atrib2 and $04)=0 then sx:=memoria[$dd02+(offs*4)]+((gfx_attr and $40) shl 2); // next column
for xc:=0 to 1 do begin
goffs:=gfx_offs+(xc shl 6)+((yc and 7) shl 1)+((atrib2 and $03) shl 4);
atrib:=memoria[$c001+goffs];
nchar:=memoria[$c000+goffs]+((atrib and $03) shl 8)+((gfx_attr and $0f) shl 10);
color:=(atrib and $3c) shl 2;
flipx:=(atrib and $40)<>0;
flipy:=(atrib and $80)<>0;
x:=sx+xc*8;
y:=sy+yc*8;
put_gfx_sprite(nchar,color,flipx,flipy,0);
actualiza_gfx_sprite(x,y,1,0);
end;
end;
sx:=sx+16;
end;
end;
actualiza_trozo_final(0,16,256,224,1);
end;
procedure eventos_bublbobl;
begin
if event.arcade then begin
//P1
if arcade_input.left[0] then marcade.in1:=(marcade.in1 and $fe) else marcade.in1:=(marcade.in1 or $1);
if arcade_input.right[0] then marcade.in1:=(marcade.in1 and $fd) else marcade.in1:=(marcade.in1 or $2);
if arcade_input.but0[0] then marcade.in1:=(marcade.in1 and $ef) else marcade.in1:=(marcade.in1 or $10);
if arcade_input.but1[0] then marcade.in1:=(marcade.in1 and $df) else marcade.in1:=(marcade.in1 or $20);
if arcade_input.start[0] then marcade.in1:=(marcade.in1 and $bf) else marcade.in1:=(marcade.in1 or $40);
//P2
if arcade_input.left[1] then marcade.in2:=(marcade.in2 and $fe) else marcade.in2:=(marcade.in2 or $1);
if arcade_input.right[1] then marcade.in2:=(marcade.in2 and $fd) else marcade.in2:=(marcade.in2 or $2);
if arcade_input.but0[1] then marcade.in2:=(marcade.in2 and $ef) else marcade.in2:=(marcade.in2 or $10);
if arcade_input.but1[1] then marcade.in2:=(marcade.in2 and $df) else marcade.in2:=(marcade.in2 or $20);
if arcade_input.start[1] then marcade.in2:=(marcade.in2 and $bf) else marcade.in2:=(marcade.in2 or $40);
//SYS
if arcade_input.coin[0] then marcade.in0:=(marcade.in0 or $4) else marcade.in0:=(marcade.in0 and $fb);
if arcade_input.coin[1] then marcade.in0:=(marcade.in0 or $8) else marcade.in0:=(marcade.in0 and $f7);
end;
end;
procedure bublbobl_principal;
var
frame_m,frame_mi,frame_s,frame_mcu:single;
f:word;
begin
init_controls(false,false,false,true);
frame_m:=z80_0.tframes;
frame_mi:=z80_1.tframes;
frame_s:=z80_2.tframes;
frame_mcu:=m6800_0.tframes;
while EmuStatus=EsRuning do begin
for f:=0 to 263 do begin
//main
z80_0.run(frame_m);
frame_m:=frame_m+z80_0.tframes-z80_0.contador;
//segunda cpu
z80_1.run(frame_mi);
frame_mi:=frame_mi+z80_1.tframes-z80_1.contador;
//sonido
z80_2.run(frame_s);
frame_s:=frame_s+z80_2.tframes-z80_2.contador;
//mcu
m6800_0.run(frame_mcu);
frame_mcu:=frame_mcu+m6800_0.tframes-m6800_0.contador;
case f of
15:update_video_bublbobl;
239:begin
z80_1.change_irq(HOLD_LINE);
m6800_0.change_irq(HOLD_LINE);
end;
end;
end;
eventos_bublbobl;
video_sync;
end;
end;
function bbsnd_getbyte(direccion:word):byte;
begin
case direccion of
0..$8fff:bbsnd_getbyte:=mem_snd[direccion];
$9000:bbsnd_getbyte:=ym2203_0.status;
$9001:bbsnd_getbyte:=ym2203_0.read;
$a000:bbsnd_getbyte:=ym3812_0.status;
$a001:bbsnd_getbyte:=ym3812_0.read;
$b000:bbsnd_getbyte:=sound_latch;
end;
end;
procedure bbsnd_putbyte(direccion:word;valor:byte);
begin
case direccion of
0..$7fff:; //ROM
$8000..$8fff:mem_snd[direccion]:=valor;
$9000:ym2203_0.control(valor);
$9001:ym2203_0.write(valor);
$a000:YM3812_0.control(valor);
$a001:YM3812_0.write(valor);
$b000:sound_stat:=valor;
$b002:begin
sound_nmi:=false;
z80_2.change_nmi(CLEAR_LINE);
end;
end;
end;
function bublbobl_getbyte(direccion:word):byte;
begin
case direccion of
0..$7fff,$c000..$f7ff,$fc00..$ffff:bublbobl_getbyte:=memoria[direccion];
$8000..$bfff:bublbobl_getbyte:=memoria_rom[banco_rom,(direccion and $3fff)];
$f800..$f9ff:bublbobl_getbyte:=buffer_paleta[direccion and $1ff];
$fa00:bublbobl_getbyte:=sound_stat;
end;
end;
procedure bublbobl_putbyte(direccion:word;valor:byte);
procedure cambiar_color(dir:word);
var
tmp_color:byte;
color:tcolor;
begin
tmp_color:=buffer_paleta[dir];
color.r:=pal4bit(tmp_color shr 4);
color.g:=pal4bit(tmp_color);
tmp_color:=buffer_paleta[1+dir];
color.b:=pal4bit(tmp_color shr 4);
set_pal_color(color,dir shr 1);
end;
begin
case direccion of
0..$bfff:; //ROM
$c000..$f7ff,$fc00..$ffff:memoria[direccion]:=valor;
$f800..$f9ff:if buffer_paleta[direccion and $1ff]<>valor then begin
buffer_paleta[direccion and $1ff]:=valor;
cambiar_color(direccion and $1fe);
end;
$fa00:if not(sound_nmi) then begin
z80_2.change_nmi(ASSERT_LINE);
sound_latch:=valor;
sound_nmi:=true;
end;
$fa03:if valor<>0 then z80_2.change_reset(ASSERT_LINE)
else z80_2.change_reset(CLEAR_LINE);
$fb40:begin
banco_rom:=(valor xor 4) and 7;
if (valor and $10)<>0 then z80_1.change_reset(CLEAR_LINE)
else z80_1.change_reset(ASSERT_LINE);
if (valor and $20)<>0 then m6800_0.change_reset(CLEAR_LINE)
else m6800_0.change_reset(ASSERT_LINE);
video_enable:=(valor and $40)<>0;
main_screen.flip_main_screen:=(valor and $80)<>0;
end;
end;
end;
function bb_misc_getbyte(direccion:word):byte;
begin
case direccion of
0..$7fff:bb_misc_getbyte:=mem_misc[direccion];
$e000..$f7ff:bb_misc_getbyte:=memoria[direccion];
end;
end;
procedure bb_misc_putbyte(direccion:word;valor:byte);
begin
case direccion of
0..$7fff:; //ROM
$e000..$f7ff:memoria[direccion]:=valor;
end;
end;
procedure bb_sound_update;
begin
ym2203_0.update;
ym3812_0.update;
end;
procedure snd_irq(irqstate:byte);
begin
z80_2.change_irq(irqstate);
end;
function mcu_getbyte(direccion:word):byte;
begin
case direccion of
$0:mcu_getbyte:=ddr1;
$1:mcu_getbyte:=ddr2;
$2:begin //port1
port1_in:=marcade.in0;
mcu_getbyte:=(port1_out and ddr1) or (port1_in and not(ddr1));
end;
$3:mcu_getbyte:=(port2_out and ddr2) or (port2_in and not(ddr2)); //port2
$4:mcu_getbyte:=ddr3;
$5:mcu_getbyte:=ddr4;
$6:mcu_getbyte:=(port3_out and ddr3) or (port3_in and not(ddr3)); //port3
$7:mcu_getbyte:=(port4_out and ddr4) or (port4_in and not(ddr4)); //port4
$40..$ff:mcu_getbyte:=m6800_0.internal_ram[direccion];
$f000..$ffff:mcu_getbyte:=mem_mcu[direccion and $fff];
end;
end;
procedure mcu_putbyte(direccion:word;valor:byte);
var
address:word;
begin
case direccion of
$0:ddr1:=valor;
$1:ddr2:=valor;
$2:begin //port1
if (((port1_out and $40)<>0) and ((not(valor) and $40)<>0)) then begin
z80_0.im2_lo:=memoria[$fc00];
z80_0.change_irq(HOLD_LINE);
end;
port1_out:=valor;
end;
$3:begin //port2
if (((not(port2_out) and $10)<>0) and ((valor and $10)<>0)) then begin
address:=port4_out or ((valor and $0f) shl 8);
if (port1_out and $80)<>0 then begin //read
if ((address and $0800)=$0000) then begin
case (address and $3) of
0:port3_in:=marcade.dswa;
1:port3_in:=marcade.dswb;
2:port3_in:=marcade.in1;
3:port3_in:=marcade.in2;
end;
end else begin
if ((address and $0c00)=$0c00) then port3_in:=memoria[$fc00+(address and $03ff)];
end;
end else begin //write
if ((address and $0c00)=$0c00) then memoria[$fc00+(address and $03ff)]:=port3_out;
end;
end;
port2_out:=valor;
end;
$4:ddr3:=valor;
$5:ddr4:=valor;
$6:port3_out:=valor;
$7:port4_out:=valor;
$40..$ff:m6800_0.internal_ram[direccion]:=valor;
$f000..$ffff:; //ROM
end;
end;
//Main
procedure reset_bublbobl;
begin
z80_0.reset;
z80_1.reset;
z80_2.reset;
m6800_0.reset;
ym2203_0.reset;
ym3812_0.reset;
reset_audio;
banco_rom:=0;
sound_nmi:=false;
sound_stat:=0;
marcade.in0:=$b3;
marcade.in1:=$ff;
marcade.in2:=$ff;
sound_latch:=0;
ddr1:=0;ddr2:=0;ddr3:=0;ddr4:=0;
port1_in:=0;port1_out:=0;port2_in:=0;port2_out:=0;port3_in:=0;port3_out:=0;port4_in:=0;port4_out:=0;
end;
function iniciar_bublbobl:boolean;
var
f:dword;
memoria_temp:array[0..$7ffff] of byte;
const
pc_x:array[0..7] of dword=(3, 2, 1, 0, 8+3, 8+2, 8+1, 8+0);
pc_y:array[0..7] of dword=(0*16, 1*16, 2*16, 3*16, 4*16, 5*16, 6*16, 7*16);
begin
llamadas_maquina.bucle_general:=bublbobl_principal;
llamadas_maquina.reset:=reset_bublbobl;
llamadas_maquina.fps_max:=59.185606;
iniciar_bublbobl:=false;
iniciar_audio(false);
screen_init(1,512,256,false,true);
iniciar_video(256,224);
//Main CPU
z80_0:=cpu_z80.create(6000000,264);
z80_0.change_ram_calls(bublbobl_getbyte,bublbobl_putbyte);
//Second CPU
z80_1:=cpu_z80.create(6000000,264);
z80_1.change_ram_calls(bb_misc_getbyte,bb_misc_putbyte);
//Sound CPU
z80_2:=cpu_z80.create(3000000,264);
z80_2.change_ram_calls(bbsnd_getbyte,bbsnd_putbyte);
z80_2.init_sound(bb_sound_update);
//MCU
m6800_0:=cpu_m6800.create(4000000,264,TCPU_M6801);
m6800_0.change_ram_calls(mcu_getbyte,mcu_putbyte);
//Sound Chip
ym2203_0:=ym2203_chip.create(3000000,0.25,0.25);
ym2203_0.change_irq_calls(snd_irq);
ym3812_0:=ym3812_chip.create(YM3526_FM,3000000,0.5);
ym3812_0.change_irq_calls(snd_irq);
//cargar roms
if not(roms_load(@memoria_temp,bublbobl_rom)) then exit;
//poner las roms y los bancos de rom
copymemory(@memoria[0],@memoria_temp[0],$8000);
for f:=0 to 3 do copymemory(@memoria_rom[f,0],@memoria_temp[$8000+(f*$4000)],$4000);
//Segunda CPU
if not(roms_load(@mem_misc,bublbobl_rom2)) then exit;
//MCU
if not(roms_load(@mem_mcu,bublbobl_mcu_rom)) then exit;
//sonido
if not(roms_load(@mem_snd,bublbobl_snd)) then exit;
//proms video
if not(roms_load(@mem_prom,bublbobl_prom)) then exit;
//convertir chars
if not(roms_load(@memoria_temp,bublbobl_chars)) then exit;
for f:=0 to $7ffff do memoria_temp[f]:=not(memoria_temp[f]); //invertir las roms
init_gfx(0,8,8,$4000);
gfx[0].trans[15]:=true;
gfx_set_desc_data(4,0,16*8,0,4,$4000*16*8+0,$4000*16*8+4);
convert_gfx(0,0,@memoria_temp,@pc_x,@pc_y,false,false);
//DIP
marcade.dswa:=$fe;
marcade.dswb:=$ff;
marcade.dswa_val:=@bublbobl_dip_a;
marcade.dswb_val:=@bublbobl_dip_b;
//final
reset_bublbobl;
iniciar_bublbobl:=true;
end;
end.
|
unit App;
{ Based on 020_shaded_objects.cpp example from oglplus (http://oglplus.org/) }
{$INCLUDE 'Sample.inc'}
interface
uses
System.Classes,
Neslib.Ooogles,
Neslib.FastMath,
Sample.App,
Sample.Geometry;
type
TShape = class abstract
private
FProgram: TGLProgram;
FVerts: TGLBuffer;
FNormals: TGLBuffer;
FTexCoords: TGLBuffer;
FIndices: TGLBuffer;
FAttrVerts: TGLVertexAttrib;
FAttrNormals: TGLVertexAttrib;
FAttrTexCoords: TGLVertexAttrib;
FUniProjectionMatrix: TGLUniform;
FUniCameraMatrix: TGLUniform;
FUniModelMatrix: TGLUniform;
FUniLightPos: TGLUniform;
public
constructor Create(const AVertexShader, AFragmentShader: TGLShader;
const AVerts, ANormals: TArray<TVector3>;
const ATexCoords: TArray<TVector2>; const AIndices: TArray<UInt16>);
destructor Destroy; override;
procedure SetProjection(const AProjection: TMatrix4);
procedure Render(const ALight: TVector3; const ACamera, AModel: TMatrix4); virtual;
end;
type
TSphere = class(TShape)
private
FSphere: TSphereGeometry;
public
constructor Create(const AVertexShader, AFragmentShader: TGLShader);
procedure Render(const ALight: TVector3; const ACamera, AModel: TMatrix4); override;
end;
type
TCube = class(TShape)
private
FCube: TCubeGeometry;
public
constructor Create(const AVertexShader, AFragmentShader: TGLShader);
procedure Render(const ALight: TVector3; const ACamera, AModel: TMatrix4); override;
end;
type
TTorus = class(TShape)
private
FTorus: TTorusGeometry;
public
constructor Create(const AVertexShader, AFragmentShader: TGLShader);
procedure Render(const ALight: TVector3; const ACamera, AModel: TMatrix4); override;
end;
type
TShadedObjectsApp = class(TApplication)
private
FSphere: TSphere;
FCubeX: TCube;
FCubeY: TCube;
FCubeZ: TCube;
FTorus: TTorus;
private
class function CreateFragmentShader(const ASource: RawByteString): TGLShader; static;
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;
const
// The common first part of all fragment shader sources
FS_PROLOGUE =
'precision mediump float;'#10+
'varying vec2 vertTexCoord;'#10+
'varying vec3 vertNormal;'#10+
'varying vec3 vertLight;'#10+
'void main(void)'#10+
'{'#10+
' float Len = dot(vertLight, vertLight);'#10+
' float Dot = Len > 0.0 ? dot('#10+
' vertNormal, '#10+
' normalize(vertLight)'#10+
' ) / Len : 0.0;'#10+
' float Intensity = 0.2 + max(Dot, 0.0) * 4.0;';
const
// The common last part of all fragment shader sources
FS_EPILOGUE =
' gl_FragColor = vec4(Color * Intensity, 1.0);'#10+
'}';
const
// The part calculating the color for the black/white checker shader
FS_BW_CHECKER =
' float c = floor(mod('#10+
' 1.0 +'#10+
' floor(mod(vertTexCoord.x * 8.0, 2.0)) +'#10+
' floor(mod(vertTexCoord.y * 8.0, 2.0)), '#10+
' 2.0));'#10+
' vec3 Color = vec3(c, c, c);';
const
// The part calculating the color for the yellow/black strips shader
FS_YB_STRIPS =
' float m = floor(mod((vertTexCoord.x + vertTexCoord.y) * 16.0, 2.0));'#10+
' vec3 Color = mix('#10+
' vec3(0.0, 0.0, 0.0),'#10+
' vec3(1.0, 1.0, 0.0),'#10+
' m);';
const
// The part calculating the color for the white/orange strips shader
FS_WO_VSTRIPS =
' float m = floor(mod(vertTexCoord.x * 8.0, 2.0));'#10+
' vec3 Color = mix('#10+
' vec3(1.0, 0.6, 0.1),'#10+
' vec3(1.0, 0.9, 0.8),'#10+
' m);';
const
// The part calculating the color for the blue/red circles shader
FS_BR_CIRCLES =
' vec2 center = vertTexCoord - vec2(0.5, 0.5);'#10+
' float m = floor(mod(sqrt(length(center)) * 16.0, 2.0));'#10+
' vec3 Color = mix('#10+
' vec3(1.0, 0.0, 0.0),'#10+
' vec3(0.0, 0.0, 1.0),'#10+
' m);';
const
// The part calculating the color for the white/green spiral shader
FS_WG_SPIRALS =
' vec2 center = (vertTexCoord - vec2(0.5, 0.5)) * 16.0;'#10+
' float l = length(center);'#10+
' float t = atan(center.y, center.x) / (2.0 * asin(1.0));'#10+
' float m = floor(mod(l + t, 2.0));'#10+
' vec3 Color = mix('#10+
' vec3(0.0, 1.0, 0.0),'#10+
' vec3(1.0, 1.0, 1.0),'#10+
' m);';
{ TShadedObjectsApp }
class function TShadedObjectsApp.CreateFragmentShader(
const ASource: RawByteString): TGLShader;
begin
Result.New(TGLShaderType.Fragment);
Result.SetSource(FS_PROLOGUE + ASource + FS_EPILOGUE);
Result.Compile;
end;
procedure TShadedObjectsApp.Initialize;
var
VertexShader: TGLShader;
begin
VertexShader.New(TGLShaderType.Vertex,
'uniform mat4 ProjectionMatrix, CameraMatrix, ModelMatrix;'#10+
'attribute vec3 Position;'#10+
'attribute vec3 Normal;'#10+
'attribute vec2 TexCoord;'#10+
'varying vec2 vertTexCoord;'#10+
'varying vec3 vertNormal;'#10+
'varying vec3 vertLight;'#10+
'uniform vec3 LightPos;'#10+
'void main(void)'#10+
'{'#10+
' vertTexCoord = TexCoord;'#10+
' gl_Position = ModelMatrix * vec4(Position, 1.0);'#10+
' vertNormal = mat3(ModelMatrix) * Normal;'#10+
' vertLight = LightPos - gl_Position.xyz;'#10+
' gl_Position = ProjectionMatrix * CameraMatrix * gl_Position;'#10+
'}');
VertexShader.Compile;
FSphere := TSphere.Create(VertexShader, CreateFragmentShader(FS_YB_STRIPS));
FCubeX := TCube.Create(VertexShader, CreateFragmentShader(FS_BW_CHECKER));
FCubeY := TCube.Create(VertexShader, CreateFragmentShader(FS_BR_CIRCLES));
FCubeZ := TCube.Create(VertexShader, CreateFragmentShader(FS_WG_SPIRALS));
FTorus := TTorus.Create(VertexShader, CreateFragmentShader(FS_WO_VSTRIPS));
{ Vertex shader no longer needed }
VertexShader.Delete;
gl.ClearColor(0.5, 0.5, 0.5, 0);
gl.ClearDepth(1);
gl.Enable(TGLCapability.DepthTest);
end;
procedure TShadedObjectsApp.KeyDown(const AKey: Integer; const AShift: TShiftState);
begin
{ Terminate app when Esc key is pressed }
if (AKey = vkEscape) then
Terminate;
end;
procedure TShadedObjectsApp.Render(const ADeltaTimeSec, ATotalTimeSec: Double);
var
Light: TVector3;
Camera, Model, Rotate, M1, M2: TMatrix4;
begin
{ Clear the color and depth buffer }
gl.Clear([TGLClear.Color, TGLClear.Depth]);
Light.Init(2, 2, 2);
{ Set the matrix for camera orbiting the origin }
OrbitCameraMatrix(TVector3.Zero, 6.0, Radians(ATotalTimeSec * 15),
Radians(FastSin(Pi * ATotalTimeSec / 3) * 45), Camera);
{ Render the shapes }
Model.Init;
FSphere.Render(Light, Camera, Model);
Model.InitTranslation(2, 0, 0);
Rotate.InitRotationX(Radians(ATotalTimeSec * 45));
FCubeX.Render(Light, Camera, Model * Rotate);
Model.InitTranslation(0, 2, 0);
Rotate.InitRotationY(Radians(ATotalTimeSec * 90));
FCubeY.Render(Light, Camera, Model * Rotate);
Model.InitTranslation(0, 0, 2);
Rotate.InitRotationZ(Radians(ATotalTimeSec * 135));
FCubeZ.Render(Light, Camera, Model * Rotate);
Model.InitTranslation(-1, -1, -1);
Rotate.InitRotation(Vector3(1, 1, 1), Radians(ATotalTimeSec * 45));
M1.InitRotationY(Radians(45));
M2.InitRotationX(Radians(45));
FTorus.Render(Light, Camera, Model * Rotate * M1 * M2);
end;
procedure TShadedObjectsApp.Resize(const AWidth, AHeight: Integer);
var
ProjectionMatrix: TMatrix4;
begin
inherited;
ProjectionMatrix.InitPerspectiveFovRH(Radians(60), AWidth / AHeight, 1, 50);
FSphere.SetProjection(ProjectionMatrix);
FCubeX.SetProjection(ProjectionMatrix);
FCubeY.SetProjection(ProjectionMatrix);
FCubeZ.SetProjection(ProjectionMatrix);
FTorus.SetProjection(ProjectionMatrix);
end;
procedure TShadedObjectsApp.Shutdown;
begin
{ Release resources }
FSphere.Free;
FCubeX.Free;
FCubeY.Free;
FCubeZ.Free;
FTorus.Free;
end;
{ TShape }
constructor TShape.Create(const AVertexShader, AFragmentShader: TGLShader;
const AVerts, ANormals: TArray<TVector3>; const ATexCoords: TArray<TVector2>;
const AIndices: TArray<UInt16>);
begin
inherited Create;
FProgram.New(AVertexShader, AFragmentShader);
FProgram.Link;
FProgram.Use;
{ Fragment shader no longer needed. Vertex shader is shared though. }
AFragmentShader.Delete;
{ Positions }
FVerts.New(TGLBufferType.Vertex);
FVerts.Bind;
FVerts.Data<TVector3>(AVerts);
FAttrVerts.Init(FProgram, 'Position');
{ Normals }
FNormals.New(TGLBufferType.Vertex);
FNormals.Bind;
FNormals.Data<TVector3>(ANormals);
FAttrNormals.Init(FProgram, 'Normal');
{ Texture coordinates }
FTexCoords.New(TGLBufferType.Vertex);
FTexCoords.Bind;
FTexCoords.Data<TVector2>(ATexCoords);
FAttrTexCoords.Init(FProgram, 'TexCoord');
{ Indices }
FIndices.New(TGLBufferType.Index);
FIndices.Bind;
FIndices.Data<UInt16>(AIndices);
{ Uniforms }
FUniProjectionMatrix.Init(FProgram, 'ProjectionMatrix');
FUniCameraMatrix.Init(FProgram, 'CameraMatrix');
FUniModelMatrix.Init(FProgram, 'ModelMatrix');
FUniLightPos.Init(FProgram, 'LightPos');
end;
destructor TShape.Destroy;
begin
FProgram.Delete;
FVerts.Delete;
FNormals.Delete;
FTexCoords.Delete;
FIndices.Delete;
inherited;
end;
procedure TShape.Render(const ALight: TVector3; const ACamera,
AModel: TMatrix4);
begin
FProgram.Use;
FUniLightPos.SetValue(ALight);
FUniCameraMatrix.SetValue(ACamera);
FUniModelMatrix.SetValue(AModel);
FVerts.Bind;
FAttrVerts.SetConfig(TGLDataType.Float, 3);
FAttrVerts.Enable;
FNormals.Bind;
FAttrNormals.SetConfig(TGLDataType.Float, 3);
FAttrNormals.Enable;
FTexCoords.Bind;
FAttrTexCoords.SetConfig(TGLDataType.Float, 2);
FAttrTexCoords.Enable;
FIndices.Bind;
end;
procedure TShape.SetProjection(const AProjection: TMatrix4);
begin
FProgram.Use;
FUniProjectionMatrix.SetValue(AProjection);
end;
{ TSphere }
constructor TSphere.Create(const AVertexShader, AFragmentShader: TGLShader);
begin
FSphere.Generate;
inherited Create(AVertexShader, AFragmentShader, FSphere.Positions,
FSphere.Normals, FSphere.TexCoords, FSphere.Indices);
FSphere.Clear;
end;
procedure TSphere.Render(const ALight: TVector3; const ACamera,
AModel: TMatrix4);
begin
inherited;
FSphere.DrawWithBoundIndexBuffer;
end;
{ TCube }
constructor TCube.Create(const AVertexShader, AFragmentShader: TGLShader);
begin
FCube.Generate;
inherited Create(AVertexShader, AFragmentShader, FCube.Positions,
FCube.Normals, FCube.TexCoords, FCube.Indices);
FCube.Clear;
end;
procedure TCube.Render(const ALight: TVector3; const ACamera, AModel: TMatrix4);
begin
inherited;
FCube.DrawWithBoundIndexBuffer;
end;
{ TTorus }
constructor TTorus.Create(const AVertexShader, AFragmentShader: TGLShader);
begin
FTorus.Generate;
inherited Create(AVertexShader, AFragmentShader, FTorus.Positions,
FTorus.Normals, FTorus.TexCoords, FTorus.Indices);
FTorus.Clear;
end;
procedure TTorus.Render(const ALight: TVector3; const ACamera,
AModel: TMatrix4);
begin
inherited;
FTorus.DrawWithBoundIndexBuffer;
end;
end.
|
unit Unit1;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Effects,
FMX.Filter.Effects, FMX.StdCtrls, FMX.Layouts;
type
TForm1 = class(TForm)
ImageControl1: TImageControl;
Layout1: TLayout;
TrackBar1: TTrackBar;
HueAdjustEffect1: THueAdjustEffect;
TrackBar2: TTrackBar;
ContrastEffect1: TContrastEffect;
TrackBar3: TTrackBar;
Layout2: TLayout;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
procedure TrackBar1Change(Sender: TObject);
procedure TrackBar2Change(Sender: TObject);
procedure TrackBar3Change(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.fmx}
procedure TForm1.TrackBar1Change(Sender: TObject);
begin
ContrastEffect1.Enabled := False;
HueAdjustEffect1.Enabled := True;
HueAdjustEffect1.Hue := TrackBar1.Value;
end;
procedure TForm1.TrackBar2Change(Sender: TObject);
begin
HueAdjustEffect1.Enabled := False;
ContrastEffect1.Enabled := True;
ContrastEffect1.Contrast := TrackBar2.Value;
end;
procedure TForm1.TrackBar3Change(Sender: TObject);
begin
HueAdjustEffect1.Enabled := False;
ContrastEffect1.Enabled := True;
ContrastEffect1.Brightness := TrackBar3.Value;
end;
end.
|
unit jc.logFile;
interface
uses
Classes, SysUtils, jc.Libs.Interfaces;
type
TjcLog = class(TInterfacedObject, IJcLog)
private
class var FError: Exception;
class var FSender: TObject;
FCustomMsg: String;
FDirPath: String;
FFileName: string;
public
constructor Create;
destructor Destroy; override;
class function New(Sender: TObject = nil; E: Exception = nil): IJcLog; overload;
class function New(AFileName: String = ''): IJcLog; overload;
function CatchException(Sender: TObject; E: Exception): IJcLog;
function CustomMsg(Msg: String): IJcLog;
function SaveLog(Alog: String = ''): IJcLog;
function SaveError: IJcLog;
function ShowLog(Alog: String = ''): IJcLog;
function ShowError: IJcLog;
end;
implementation
{ TjcLog }
uses jc.Utils, System.UITypes, Vcl.Dialogs;
class function TjcLog.New(Sender: TObject = nil; E: Exception = nil): IJcLog;
begin
if E <> nil then
FError := E;
if Sender <> nil then
FSender := Sender;
Result := Self.Create;
end;
class function TjcLog.New(AFileName: String): IJcLog;
begin
if trim(AFileName) <> '' then
FFileName := AFileName;
Result := Self.Create;
end;
constructor TjcLog.Create;
begin
FCustomMsg := EmptyStr;
FDirPath := getPathApplication + 'logs' + PathDelim;
if not DirectoryExists(FDirPath) then
CreateDir(FDirPath);
end;
function TjcLog.CustomMsg(Msg: String): IJcLog;
begin
FCustomMsg := Msg;
Result := Self;
end;
destructor TjcLog.Destroy;
begin
inherited;
end;
function TjcLog.CatchException(Sender: TObject; E: Exception): IJcLog;
begin
if E <> nil then
FError := E;
if Sender <> nil then
FSender := Sender;
Result := Self;
end;
function TjcLog.SaveLog(Alog: String = ''): IJcLog;
var
tFile: TextFile;
begin
result := self;
if FFileName = EmptyStr then
FFileName := FormatDateTime('dd-mm-yyyy', now) + '_log' + '.txt';
FFileName := FDirPath + FFileName;
TThread.Queue(nil,
procedure
begin
AssignFile(tFile, FFileName);
try
if FileExists(FFileName) then
Append(tFile)
else
ReWrite(tFile);
if FCustomMsg <> EmptyStr then
WriteLn(tFile, FormatDateTime('hh:mm:ss', Now) +' '+ FCustomMsg)
else
WriteLn(tFile, FormatDateTime('hh:mm:ss', Now) +' '+ Alog);
finally
CloseFile(tFile);
end;
end
);
end;
function TjcLog.SaveError: IJcLog;
var
tFile: TextFile;
begin
result := self;
if FFileName = EmptyStr then
FFileName := FormatDateTime('dd-mm-yyyy', now) + '_errors' + '.txt';
FFileName := FDirPath + FFileName;
TThread.Queue(nil,
procedure
begin
AssignFile(tFile, FFileName);
try
if FileExists(FFileName) then
Append(tFile)
else
ReWrite(tFile);
WriteLn(tFile, 'Time.............: ' + FormatDateTime('hh:mm:ss', Now));
WriteLn(tFile, 'Message..........: ' + FCustomMsg);
WriteLn(tFile, 'Error............: ' + FError.Message);
WriteLn(tFile, 'Class Exception..: ' + FError.ClassName);
WriteLn(tFile, 'User.............: ' + '');
WriteLn(tFile, 'Windows Version..: ' + '');
WriteLn(tFile, '');
finally
CloseFile(tFile);
end;
end
);
end;
function TjcLog.ShowLog(Alog: String = ''): IJcLog;
begin
if FCustomMsg <> EmptyStr then
MessageDlg(FCustomMsg, mtInformation, [mbOK], 0)
else
MessageDlg(Alog, mtInformation, [mbOK], 0);
result := self;
end;
function TjcLog.ShowError: IJcLog;
var
sBuilder: TStringBuilder;
begin
result := self;
sBuilder := TStringBuilder.Create;
try
sBuilder
.AppendLine(FCustomMsg)
.AppendLine(EmptyStr)
.AppendLine('Error: ' + FError.Message);
MessageDlg(sBuilder.ToString, mtError, [mbOK], 0);
finally
sBuilder.Free;
end;
end;
end.
|
namespace Sugar.Json;
interface
uses
Sugar,
Sugar.Json,
Sugar.Collections,
{$IF ECHOES}
System.Linq;
{$ELSEIF COOPER}
com.remobjects.elements.linq;
{$ELSEIF TOFFEE}
Sugar.Linq,
RemObjects.Elements.Linq;
{$ENDIF}
type
JsonArray = public class (JsonNode, ISequence<JsonNode>)
private
fItems: List<JsonNode>;
method GetItem(&Index: Integer): JsonNode;
method SetItem(&Index: Integer; Value: JsonNode);
public
constructor;
constructor(aItems: List<JsonNode>);
method &Add(Value: JsonNode);
method Insert(&Index: Integer; Value: JsonNode);
method Clear;
method &RemoveAt(&Index: Integer);
method ToStrings: not nullable sequence of String;
method ToStringList: not nullable List<String>;
method ToJson: String; override;
{$IF COOPER}
method &iterator: java.util.&Iterator<JsonNode>;
{$ELSEIF ECHOES}
method GetNonGenericEnumerator: System.Collections.IEnumerator; implements System.Collections.IEnumerable.GetEnumerator;
method GetEnumerator: System.Collections.Generic.IEnumerator<JsonNode>;
{$ELSEIF TOFFEE}
method countByEnumeratingWithState(aState: ^NSFastEnumerationState) objects(stackbuf: ^JsonNode) count(len: NSUInteger): NSUInteger;
{$ENDIF}
class method Load(JsonString: String): JsonArray;
property Count: Integer read fItems.Count; override;
property Item[&Index: Integer]: JsonNode read GetItem write SetItem; default; override;
end;
implementation
constructor JsonArray;
begin
fItems := new List<JsonNode>();
end;
constructor JsonArray(aItems: List<JsonNode>);
begin
fItems := aItems;
end;
method JsonArray.GetItem(&Index: Integer): JsonNode;
begin
exit fItems[&Index];
end;
method JsonArray.SetItem(&Index: Integer; Value: JsonNode);
begin
SugarArgumentNullException.RaiseIfNil(Value, "Value");
fItems[&Index] := Value;
end;
method JsonArray.Add(Value: JsonNode);
begin
fItems.Add(Value);
end;
method JsonArray.Insert(&Index: Integer; Value: JsonNode);
begin
fItems.Insert(&Index, Value);
end;
method JsonArray.Clear;
begin
fItems.Clear;
end;
method JsonArray.RemoveAt(&Index: Integer);
begin
fItems.RemoveAt(&Index);
end;
class method JsonArray.Load(JsonString: String): JsonArray;
begin
var Serializer := new JsonDeserializer(JsonString);
var lValue := Serializer.Deserialize;
if not (lValue is JsonArray) then
raise new SugarInvalidOperationException("String does not contains valid Json array");
result := lValue as JsonArray;
end;
method JsonArray.ToJson: String;
begin
var Serializer := new JsonSerializer(self);
exit Serializer.Serialize;
end;
{$IF COOPER}
method JsonArray.&iterator: java.util.Iterator<JsonNode>;
begin
exit Iterable<JsonNode>(fItems).iterator;
end;
{$ELSEIF ECHOES}
method JsonArray.GetNonGenericEnumerator: System.Collections.IEnumerator;
begin
exit GetEnumerator;
end;
method JsonArray.GetEnumerator: System.Collections.Generic.IEnumerator<JsonNode>;
begin
exit System.Collections.Generic.IEnumerable<JsonNode>(fItems).GetEnumerator;
end;
{$ELSEIF TOFFEE}
method JsonArray.countByEnumeratingWithState(aState: ^NSFastEnumerationState) objects(stackbuf: ^JsonNode) count(len: NSUInteger): NSUInteger;
begin
exit NSArray(fItems).countByEnumeratingWithState(aState) objects(^id(stackbuf)) count(len);
end;
{$ENDIF}
method JsonArray.ToStrings: not nullable sequence of String;
begin
result := self.Where(i -> i is JsonStringValue).Select(i -> i.StringValue) as not nullable;
end;
method JsonArray.ToStringList: not nullable List<String>;
begin
result := ToStrings().ToList() as not nullable;
end;
end. |
(*
* iocp WebSocket 服务消息 JSON 封装单元
*)
unit iocp_WsJSON;
interface
{$I in_iocp.inc}
uses
{$IFDEF DELPHI_XE7UP}
Winapi.Windows, System.Classes,
System.SysUtils, System.Variants, Data.DB, {$ELSE}
Windows, Classes, SysUtils, Variants, DB, {$ENDIF}
iocp_base, iocp_senders, iocp_msgPacks;
type
// 说明:这是简单的 JSON 封装,只支持单记录!
TCustomJSON = class(TBasePack)
private
FText: AnsiString; // JSON 文本
function GetAsRecord(const Index: String): TCustomJSON;
function GetJSONText: AnsiString;
procedure SetAsRecord(const Index: String; const Value: TCustomJSON);
procedure SetJSONText(const Value: AnsiString);
procedure WriteToBuffers(var JSON: AnsiString; WriteExtra: Boolean);
protected
// 检查名称的合法性
procedure CheckFieldName(const Value: AnsiString); override;
// 刷新 FText
procedure InterRefresh; override;
// 保存变量表到内存流
procedure SaveToMemStream(Stream: TMemoryStream; WriteExtra: Boolean); override;
// 扫描内存块,建变量表
procedure ScanBuffers(ABuffer: PAnsiChar; ASize: Cardinal; ReadExtra: Boolean); override;
// 写额外字段
procedure WriteSystemInfo(var Buffer: PAnsiChar); virtual;
public
procedure Clear; override;
public
property B[const Name: String]: Boolean read GetAsBoolean write SetAsBoolean;
property D[const Name: String]: TDateTime read GetAsDateTime write SetAsDateTime;
property F[const Name: String]: Double read GetAsFloat write SetAsFloat;
property I[const Name: String]: Integer read GetAsInteger write SetAsInteger;
property I64[const Name: String]: Int64 read GetAsInt64 write SetAsInt64;
property R[const Name: String]: TCustomJSON read GetAsRecord write SetAsRecord; // 记录
property S[const Name: String]: String read GetAsString write SetAsString;
property V[const Name: String]: Variant read GetAsVariant write SetAsVariant; // 变长
property Text: AnsiString read GetJSONText write SetJSONText; // 改为读写
end;
TBaseJSON = class(TCustomJSON)
protected
FAttachment: TStream; // 附件流
FMsgId: Int64; // 消息Id
private
function GetAction: Integer;
function GetHasAttachment: Boolean;
procedure SetAction(const Value: Integer);
procedure SetAttachment(const Value: TStream);
protected
// 扫描内存块,建变量表
procedure ScanBuffers(ABuffer: PAnsiChar; ASize: Cardinal; ReadExtra: Boolean); override;
// 写额外字段
procedure WriteSystemInfo(var Buffer: PAnsiChar); override;
public
constructor Create(AOwner: TObject);
destructor Destroy; override;
procedure Close; virtual;
public
// 预设属性
property Action: Integer read GetAction write SetAction;
property Attachment: TStream read FAttachment write SetAttachment;
property HasAttachment: Boolean read GetHasAttachment;
property MsgId: Int64 read FMsgId;
end;
// 发送用的 JSON 消息
TSendJSON = class(TBaseJSON)
protected
FDataSet: TDataSet; // 要发送的数据集(当附件)
FFrameSize: Int64; // 帧长度
FServerMode: Boolean; // 服务端使用
private
procedure InterSendDataSet(ASender: TBaseTaskSender);
procedure SetDataSet(Value: TDataset);
protected
procedure InternalSend(ASender: TBaseTaskSender; AMasking: Boolean);
protected
property DataSet: TDataSet read FDataSet write SetDataSet; // 服务端公开
public
procedure Close; override;
end;
implementation
uses
iocp_Winsock2, iocp_lists, http_utils, iocp_utils;
{ TCustomJSON }
procedure TCustomJSON.CheckFieldName(const Value: AnsiString);
var
i: Integer;
begin
inherited;
for i := 1 to Length(Value) do
if (Value[i] in ['''', '"', ':', ',', '{', '}']) then
raise Exception.Create('变量名称不合法.');
end;
procedure TCustomJSON.Clear;
begin
inherited;
FText := '';
end;
function TCustomJSON.GetAsRecord(const Index: String): TCustomJSON;
var
Stream: TStream;
begin
// 先转为流,再转为 TCustomJSON
Stream := GetAsStream(Index);
if Assigned(Stream) then
try
Result := TCustomJSON.Create;
Result.Initialize(Stream);
finally
Stream.Free;
end
else
Result := nil;
end;
function TCustomJSON.GetJSONText: AnsiString;
begin
if (FList.Count = 0) then
Result := '[]'
else begin
if (FText = '') then
WriteToBuffers(FText, True);
Result := FText;
end;
end;
procedure TCustomJSON.InterRefresh;
begin
// 内容改变,删除 FText
if (FText <> '') then
FText := '';
end;
procedure TCustomJSON.SaveToMemStream(Stream: TMemoryStream; WriteExtra: Boolean);
var
JSON: AnsiString;
begin
// 写入流
WriteToBuffers(JSON, WriteExtra);
Stream.Write(JSON[1], Length(JSON));
end;
procedure TCustomJSON.ScanBuffers(ABuffer: PAnsiChar; ASize: Cardinal; ReadExtra: Boolean);
procedure ExtractStream(var Stream: TMemoryStream;
var p: PAnsiChar; iLen: Integer);
begin
// 提取内容到流
// 注:Stream.Position := 0;
Stream := TMemoryStream.Create;
Stream.Size := iLen;
Inc(p, 2);
System.Move(p^, Stream.Memory^, iLen);
Inc(p, iLen);
end;
procedure GetFieldData(var p: PAnsiChar; var DataType: TElementType;
var Str: AnsiString; var Stream: TMemoryStream;
var VarValue: Variant);
var
pa: PAnsiChar;
Len: Integer;
begin
// 读取带长度描述的字段内容,格式:
// {"Length":5,"Data":"abcde"}
pa := nil;
Len := 0;
Inc(p, 8); // 到 : 前位置附近
repeat
case p^ of
':':
if (Len = 0) then // 长度位置
pa := p + 1
else // 内容位置
if CompareBuffer(p - 9, ',"Stream":"') then // Stream
begin
DataType := etStream;
ExtractStream(Stream, p, Len);
end else
if CompareBuffer(p - 9, ',"Record":"') then // JSON 记录
begin
DataType := etRecord;
ExtractStream(Stream, p, Len);
end else
if CompareBuffer(p - 9, ',"String":"') then // 字符串
begin
DataType := etString;
Inc(p, 2);
SetString(Str, p, Len);
Inc(p, Len);
end else
begin // ',"Variant":"' -- Variant 类型
DataType := etVariant;
Inc(p, 2);
VarValue := BufferToVariant(p, Len, True); // 自动解压
Inc(p, Len);
end;
',': begin // 取长度
SetString(Str, pa, p - pa);
Len := StrToInt(Str);
Inc(p, 8);
end;
end;
Inc(p);
until (p^ = '}');
end;
procedure AddJSONField(const AName: String; AValue: AnsiString; StringType: Boolean);
begin
// 增加一个变量/字段
if StringType then // DateTime 用 String 表示
SetAsString(AName, AValue)
else
if (AValue = 'True') then
SetAsBoolean(AName, True)
else
if (AValue = 'False') then
SetAsBoolean(AName, False)
else
if (AValue = 'Null') or (AValue = '""') or (AValue = '') then
SetAsString(AName, '')
else
if (Pos('.', AValue) > 0) then // 普通数字
SetAsFloat(AName, StrToFloat(AValue))
else
if (Length(AValue) < 10) then // 2147 4836 47
SetAsInteger(AName, StrToInt(AValue))
else
if (AValue[1] in ['0'..'9', '-', '+']) then
SetAsInt64(AName, StrToInt64(AValue));
end;
var
Level: Integer; // 括号层次
DblQuo: Boolean; // 双引号
WaitVal: Boolean; // 等待字段值
p, pEnd: PAnsiChar;
pD, pD2: PAnsiChar;
DataType: TElementType; // 数据类型
FldName: AnsiString; // 字段名称
FldValue: AnsiString; // String 字段值
VarValue: Variant; // Variant 字段值
Stream: TMemoryStream; // Stream 字段值
JSONRec: TCustomJSON; // 记录字段值
begin
// 扫描一段内存,分析出 JSON 字段、字段值
// (全部值转为字符串,不支持数组,否则异常)
// 扫描范围
p := ABuffer;
pEnd := PAnsiChar(p + ASize);
// 数据开始、结束位置
pD := nil;
pD2 := nil;
Level := 0; // 层次
DblQuo := False;
WaitVal := False; // 等待字段值
// 遍历,提取字段、值
repeat
(* {"Id":123,"Name":"我","Boolean":True,"Stream":Null,
"_Variant":{"Length":5,"Data":"aaaa"},"_zzz":2345} *)
case p^ of // 特殊符号在双引号后当作名称或内容的一部分
'{':
if (DblQuo = False) then // 括号外
begin
Inc(Level);
if (Level > 1) then // 内层,存放 Variant 数据
begin
DblQuo := False;
WaitVal := False;
// 分析内层的内容
GetFieldData(p, DataType, FldValue, Stream, VarValue);
case DataType of
etString:
SetAsString(FldName, FldValue);
etStream: // 数据流
SetAsStream(FldName, Stream);
etRecord: begin // 记录类型
JSONRec := TCustomJSON.Create;
JSONRec.Initialize(Stream);
SetAsRecord(FldName, JSONRec);
end;
etVariant: // Variant
SetAsVariant(FldName, VarValue);
end;
Dec(Level); // 回外层
end;
end;
'"': // 外层:Level = 1
if (DblQuo = False) then
DblQuo := True
else
if ((p + 1)^ in [':', ',', '}']) then // 引号结束
begin
DblQuo := False;
pD2 := p;
end;
':': // 外层,括号:"Name":”
if (DblQuo = False) and (Level = 1) then
begin
WaitVal := True;
SetString(FldName, pD, pD2 - pD);
FldName := TrimRight(FldName);
pD := nil;
pD2 := nil;
end;
',', '}': // 值结束:xx," xx"," xx},"
if (p^ = '}') or (p^ = ',') and ((p + 1)^ = '"') then
if (DblQuo = False) and WaitVal then // Length(FldName) > 0
begin
if (pD2 = nil) then // 前面没有引号
begin
SetString(FldValue, pD, p - pD);
AddJSONField(FldName, Trim(FldValue), False);
end else
begin
SetString(FldValue, pD, pD2 - pD);
AddJSONField(FldName, FldValue, True); // 不要 Trim(FldValue)
end;
pD := nil;
pD2 := nil;
WaitVal := False;
end;
else
if (DblQuo or WaitVal) and (pD = nil) then // 名称、内容开始
pD := p;
end;
Inc(p);
until (p > pEnd);
end;
procedure TCustomJSON.SetAsRecord(const Index: String; const Value: TCustomJSON);
var
Variable: TListVariable;
begin
Variable.Data := Value;
SetField(etRecord, Index, @Variable);
end;
procedure TCustomJSON.SetJSONText(const Value: AnsiString);
begin
// 用 JSON 文本初始化变量表
Clear;
if (Value <> '') then
ScanBuffers(PAnsiChar(Value), Length(Value), False);
end;
procedure TCustomJSON.WriteSystemInfo(var Buffer: PAnsiChar);
begin
// Empty
end;
procedure TCustomJSON.WriteToBuffers(var JSON: AnsiString; WriteExtra: Boolean);
const
BOOL_VALUES: array[Boolean] of AnsiString = ('False', 'True');
FIELD_TYPES: array[etString..etVariant] of AnsiString = (
',"String":"', ',"Record":"', ',"Stream":"', ',"Variant":"');
function SetFieldNameLength(var Addr: PAnsiChar; AName: AnsiString;
ASize: Integer; AType: TElementType): Integer;
var
S: AnsiString;
begin
// 写入字段长度描述
// 可能含保留符,加入长度信息,其他解析器可能无法识别
// 格式:"VarName":{"Length":1234,"String":"???"}
S := '"' + AName + '":{"Length":' + IntToStr(ASize) + FIELD_TYPES[AType];
Result := Length(S);
System.Move(S[1], Addr^, Result);
Inc(Addr, Result);
end;
var
i: Integer;
p: PAnsiChar;
begin
// 保存消息到 JSON 文本(不支持数组)
// 1. JSON 长度 = 每字段多几个字符的描述 +
// INIOCP_JSON_HEADER + JSON_CHARSET_UTF8 + MsgOwner
SetLength(JSON, Integer(FSize) + FList.Count * 25 + 80);
p := PAnsiChar(JSON);
// 2. 写标志性字段
WriteSystemInfo(p);
// 3. 加入列表字段
for i := 0 to FList.Count - 1 do
with Fields[i] do
case VarType of
etNull:
VarToJSON(p, Name, 'Null', True, False, i = FList.Count - 1);
etBoolean:
VarToJSON(p, Name, BOOL_VALUES[AsBoolean], True, False, i = FList.Count - 1);
etCardinal..etInt64:
VarToJSON(p, Name, AsString, True, False, i = FList.Count - 1);
etDateTime: // 当作字符串
VarToJSON(p, Name, AsString, False, False, i = FList.Count - 1);
etString, etRecord,
etStream, etVariant: begin // 其他类型未用
// 加入字段名称、长度
SetFieldNameLength(p, Name, Size, VarType);
if (Size > 0) then // 加入内容: "内容"
case VarType of
etString: begin
System.Move(AsString[1], p^, Size); // 复制内容
Inc(p, Size); // 前移
end;
etRecord, etStream: begin // 直接用流写入,减少复制次数
TStream(DataRef).Position := 0;
TStream(DataRef).Read(p^, Size);
Inc(p, Size); // 前移
end;
etVariant: begin // 复制内容
System.Move(DataRef^, p^, Size);
Inc(p, Size); // 前移
end;
end;
if (i = FList.Count - 1) then
PThrChars(p)^ := AnsiString('"}}')
else
PThrChars(p)^ := AnsiString('"},');
Inc(p, 3);
end;
end;
// 4. 删除多余空间
Delete(JSON, p - PAnsiChar(JSON) + 1, Length(JSON));
end;
{ TBaseJSON }
procedure TBaseJSON.Close;
begin
// 关闭附件流
if Assigned(FAttachment) then
begin
FAttachment.Free;
FAttachment := nil;
end;
end;
constructor TBaseJSON.Create(AOwner: TObject);
begin
inherited Create;
FOwner := UInt64(AOwner);
FMsgId := GetUTCTickCount;
end;
destructor TBaseJSON.Destroy;
begin
Close;
inherited; // 自动 Clear;
end;
function TBaseJSON.GetAction: Integer;
begin
Result := GetAsInteger('__action'); // 操作类型
end;
function TBaseJSON.GetHasAttachment: Boolean;
begin
Result := GetAsBoolean('__has_attach'); // 是否带附件
end;
procedure TBaseJSON.ScanBuffers(ABuffer: PAnsiChar; ASize: Cardinal; ReadExtra: Boolean);
begin
inherited;
// 修改消息宿主(大写)
FOwner := GetAsInt64('__MSG_OWNER');
end;
procedure TBaseJSON.SetAction(const Value: Integer);
begin
SetAsInteger('__action', Value); // 操作类型
end;
procedure TBaseJSON.SetAttachment(const Value: TStream);
begin
// 设置附件流,加一个 __has_attach 变量
Close; // 释放现有的流
FAttachment := Value;
SetAsBoolean('__has_attach', Assigned(FAttachment) and (FAttachment.Size > 0));
end;
procedure TBaseJSON.WriteSystemInfo(var Buffer: PAnsiChar);
var
S: AnsiString;
begin
// 写入系统信息字段:InIOCP 标志、宿主(大写)
// {"_InIOCP_Ver":2.8,"__MSG_OWNER":12345678,
S := INIOCP_JSON_FLAG + '"__MSG_OWNER":' + IntToStr(UInt64(FOwner)) + ',';
System.Move(S[1], Buffer^, Length(S));
Inc(Buffer, Length(S));
end;
{ TSendJSON }
procedure TSendJSON.Close;
begin
inherited;
if Assigned(FDataSet) then
FDataSet := nil;
end;
procedure TSendJSON.InternalSend(ASender: TBaseTaskSender; AMasking: Boolean);
var
JSON: TMemoryStream;
begin
// 发送数据
if (FList.Count = 0) then
Exit;
// 1. 字段内容转换到 JSON 流
JSON := TMemoryStream.Create;
SaveToStream(JSON, True); // 自动清除变量表
FFrameSize := JSON.Size;
// 2. 发送
ASender.Masking := AMasking; // 掩码设置
ASender.OpCode := ocText; // JSON 当作文本,不能改
ASender.Send(JSON, FFrameSize, True); // 自动释放
// 3. 发送附件:数据流或数据集
if Assigned(FAttachment) then // 3.1 数据流
try
FFrameSize := FAttachment.Size; // 改变
if (FFrameSize = 0) then
FAttachment.Free // 直接释放
else begin
if (FServerMode = False) then
Sleep(10);
ASender.OpCode := ocBiary; // 附件 当作二进制,不能改
ASender.Send(FAttachment, FFrameSize, True); // 自动释放
end;
finally
FAttachment := nil; // 已经释放
end
else
if Assigned(FDataSet) then // 3.2 数据集
try
if (FServerMode = False) then
Sleep(10);
InterSendDataSet(ASender);
finally
FDataSet.Active := False;
FDataSet := nil;
end;
// 快速投放时,服务端可能几个消息粘连在一起(Win7 64 位容易出现),
// 致接收异常,面的消息被放弃
if (FServerMode = False) then
Sleep(10);
end;
procedure TSendJSON.InterSendDataSet(ASender: TBaseTaskSender);
procedure MarkFrameSize(AData: PWsaBuf; AFrameSize: Integer; ALastFrame: Byte);
var
pb: PByte;
begin
// 服务端:构造 WebSocket 帧信息
// 忽略 RSV1/RSV2/RSV3
pb := PByte(AData^.buf);
pb^ := ALastFrame + Byte(ocBiary); // 有后继帧(高位 = 0),附件
Inc(pb);
pb^ := 126; // 用 126,客户端从 3、4字节取长度
Inc(pb);
TByteAry(pb)[0] := TByteAry(@AFrameSize)[1];
TByteAry(pb)[1] := TByteAry(@AFrameSize)[0];
// 发送内容长度
AData^.len := AFrameSize + 4;
end;
var
XData: PWsaBuf; // 填充空间
i, k, n, m, Idx: integer;
EmptySize, Offset: Integer;
p: PAnsiChar;
Desc, JSON: AnsiString;
Names: TStringAry;
Field: TField;
begin
// 快速把数据集转为 JSON(忽略 Blob 字段内容)
// 注意:不带数据描述,每字段长度不能超过 IO_BUFFER_SIZE
if not DataSet.Active or DataSet.IsEmpty then
Exit;
Dataset.DisableControls;
Dataset.First;
try
// 1. 先保存字段描述到数组(字段名区分大小写)
n := 5; // 整条记录的 JSON 长度,开始为 Length('["},]')
k := Dataset.FieldCount;
SetLength(Names, k);
for i := 0 to k - 1 do
begin
Field := Dataset.Fields[i];
if (i = 0) then
begin
Desc := '{"' + LowerCase(Field.FieldName) + '":"'; // 用小写
end else
Desc := '","' + LowerCase(Field.FieldName) + '":"';
Names[i] := Desc;
Inc(n, Length(Desc) + Field.Size + 10);
end;
// 2. 每条记录转为 JSON,缓存满时发送
XData := ASender.Data; // 发送器的填充空间
// 数组开始,帧描述 4 字节
(XData.buf + 4)^ := AnsiChar('[');
EmptySize := IO_BUFFER_SIZE - 5; // 空间长度
Offset := 5; // 写入位移
while not Dataset.Eof do
begin
SetLength(JSON, n); // 预设记录空间
p := PAnsiChar(JSON);
Idx := 0; // 内容的实际长度
// 记录 -> JSON
for i := 0 to k - 1 do
begin
Field := Dataset.Fields[i];
if (i = k - 1) then // [{"Id":"1","Name":"我"},{"Id":"2","Name":"你"}]
Desc := Names[i] + Field.Text + '"}'
else
Desc := Names[i] + Field.Text;
m := Length(Desc);
System.Move(Desc[1], p^, m);
Inc(p, m);
Inc(Idx, m);
end;
Inc(Idx); // 记录后紧跟符号 , 或 ]
Delete(JSON, Idx + 1, n - Idx); // 删除多余内容
// 空间不足 -> 先发送已填写的内容
if (Idx > EmptySize) then
begin
MarkFrameSize(XData, Offset - 4, 0); // 设置帧信息
ASender.SendBuffers; // 立刻发送!
EmptySize := IO_BUFFER_SIZE - 4; // 复原
Offset := 4; // 复原
end;
// 下一条记录
Dataset.Next;
// 加入 JSON,下次满时发送
if Dataset.Eof then
JSON[Idx] := AnsiChar(']') // 结束符
else
JSON[Idx] := AnsiChar(','); // 未结束
System.Move(JSON[1], (XData.buf + Offset)^, Idx);
Dec(EmptySize, Idx); // 空间-
Inc(Offset, Idx); // 位移+
end;
// 发送最后一帧
if (Offset > 4) then
begin
MarkFrameSize(XData, Offset - 4, Byte($80)); // 设置帧信息
ASender.SendBuffers; // 立刻发送!
end;
finally
Dataset.EnableControls;
end;
end;
procedure TSendJSON.SetDataSet(Value: TDataset);
begin
Close; // 关闭现有附件
FDataSet := Value;
SetAsBoolean('__has_attach', Assigned(Value) and Value.Active and not Value.IsEmpty);
end;
end.
|
unit RunUtils;
interface
function GetCommandApp( const CommandLine : string ) : string;
function GetCommandParams( const CommandLine : string ) : string;
implementation
uses
StrUtils;
function GetCommandApp( const CommandLine : string ) : string;
var
SpacePos : integer;
begin
SpacePos := System.Pos( ' ', CommandLine );
if SpacePos <> 0
then Result := LeftStr( CommandLine, SpacePos -1 )
else Result := '';
end;
function GetCommandParams( const CommandLine : string ) : string;
var
SpacePos : integer;
begin
SpacePos := System.Pos( ' ', CommandLine );
if SpacePos <> 0
then Result := RightStr( CommandLine, length( CommandLine ) - SpacePos + 1 )
else Result := '';
end;
end.
|
unit ScrollF;
interface
uses
Qt, SysUtils, Classes, QGraphics, QControls, QForms, QDialogs;
type
TForm2 = class(TForm)
procedure FormPaint(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form2: TForm2;
implementation
{$R *.xfm}
procedure TForm2.FormPaint(Sender: TObject);
begin
{draw a yellow line}
Canvas.Pen.Width := 30;
Canvas.Pen.Color := clYellow;
Canvas.MoveTo (30 - HorzScrollbar.Position, 30 - VertScrollbar.Position);
Canvas.LineTo (1970 - HorzScrollbar.Position, 1970 - VertScrollbar.Position);
{draw a blue line}
Canvas.Pen.Color := clNavy;
Canvas.MoveTo (30 - HorzScrollbar.Position, 1970 - VertScrollbar.Position);
Canvas.LineTo (1970 - HorzScrollbar.Position, 30 - VertScrollbar.Position);
{draw a fuchsia square}
Canvas.Pen.Color := clFuchsia;
Canvas.Brush.Style := bsClear;
Canvas.Rectangle (500 - HorzScrollbar.Position, 500 - VertScrollbar.Position,
1500 - HorzScrollbar.Position, 1500 - VertScrollbar.Position);
end;
end.
|
unit G2Mobile.View.Clientes;
interface
uses
System.SysUtils,
System.Types,
System.UITypes,
System.Classes,
System.Variants,
FMX.Types,
FMX.Controls,
FMX.Forms,
FMX.Graphics,
FMX.Dialogs,
FMX.ListView.Types,
FMX.ListView.Appearances,
FMX.ListView.Adapters.Base,
FMX.Objects,
FMX.StdCtrls,
FMX.ListView,
FMX.Effects,
FMX.Edit,
FMX.Controls.Presentation,
FMX.TabControl,
FMX.Layouts,
System.Rtti,
FMX.Grid.Style,
FMX.Grid,
FMX.ScrollBox;
type
TFrmClientes = class(TForm)
LayoutClientPesq: TLayout;
TabControl1: TTabControl;
TabItem1: TTabItem;
Layout1: TLayout;
Layout2: TLayout;
Rectangle3: TRectangle;
Button1: TButton;
edtPesq: TEdit;
SearchEditButton1: TSearchEditButton;
ShadowEffect2: TShadowEffect;
ListView1: TListView;
TabItem2: TTabItem;
ShadowEffect3: TShadowEffect;
Rectangle4: TRectangle;
img_negativo: TImage;
img_positivo: TImage;
TabControl2: TTabControl;
TabItem3: TTabItem;
Layout3: TLayout;
Rectangle2: TRectangle;
Label3: TLabel;
Button2: TButton;
ShadowEffect1: TShadowEffect;
Rectangle1: TRectangle;
VertScrollBox1: TVertScrollBox;
lay_EnderecoCliente: TLayout;
Rectangle5: TRectangle;
lbl_Cidade: TLabel;
lbl_Endereco: TLabel;
lbl_Bairro: TLabel;
Layout4: TLayout;
Image2: TImage;
Label10: TLabel;
Label5: TLabel;
Label7: TLabel;
lay_FinanceiroCliente: TLayout;
Rectangle7: TRectangle;
lbl_vlrAberto: TLabel;
Label14: TLabel;
lbl_CredDisponivel: TLabel;
Label16: TLabel;
Label17: TLabel;
lbl_Credito: TLabel;
Layout6: TLayout;
Image1: TImage;
lay_InfoCliente: TLayout;
Rectangle6: TRectangle;
Label1: TLabel;
Label11: TLabel;
Label2: TLabel;
Label4: TLabel;
Label9: TLabel;
lbl_Email: TLabel;
lbl_Telefone: TLabel;
lbl_PesoText: TLabel;
lbl_Codigo: TLabel;
lbl_UltimaVisita: TLabel;
lbl_QntCaixaText: TLabel;
lbl_CpfCnpj: TLabel;
lbl_NomeRazao: TLabel;
lbl_NomeFantasia: TLabel;
Layout5: TLayout;
Image3: TImage;
Rectangle8: TRectangle;
Label6: TLabel;
Image4: TImage;
TabItem4: TTabItem;
Label8: TLabel;
Button3: TButton;
ListView2: TListView;
ShadowEffect4: TShadowEffect;
img_aberto: TImage;
img_vencido: TImage;
lay_ItensTitulo: TLayout;
Layout8: TLayout;
Label12: TLabel;
Rectangle9: TRectangle;
Image5: TImage;
strList_TituloCliente: TStringGrid;
cod_prod: TStringColumn;
nome_prod: TStringColumn;
unid_item: TStringColumn;
qtd_prod: TStringColumn;
QTD_REAL: TStringColumn;
PESO: TStringColumn;
valor_item: TStringColumn;
valortotal_item: TStringColumn;
procedure FormCreate(Sender: TObject);
procedure ListView1ItemClick(const Sender: TObject; const AItem: TListViewItem);
procedure Button2Click(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure edtPesqChangeTracking(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure Rectangle8Click(Sender: TObject);
procedure ListView2ItemClick(const Sender: TObject; const AItem: TListViewItem);
procedure Image5Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
FrmClientes: TFrmClientes;
implementation
{$R *.fmx}
uses
G2Mobile.Model.Clientes,
uFrmUtilFormate,
G2Mobile.Model.TitulosCliente,
Form_Mensagem,
G2Mobile.View.Inicio,
G2Mobile.View.Main;
procedure TFrmClientes.Button1Click(Sender: TObject);
begin
FrmMain.MudarCabecalho('Início');
FrmMain.FormOpen(TFrmInicio);
end;
procedure TFrmClientes.Button2Click(Sender: TObject);
begin
TabControl1.TabIndex := 0;
end;
procedure TFrmClientes.Button3Click(Sender: TObject);
begin
TabControl2.TabIndex := 0;
end;
procedure TFrmClientes.edtPesqChangeTracking(Sender: TObject);
begin
sbList.Text := edtPesq.Text;
end;
procedure TFrmClientes.FormCreate(Sender: TObject);
begin
img_positivo.Visible := false;
img_negativo.Visible := false;
img_aberto.Visible := false;
img_vencido.Visible := false;
ListViewSearch(ListView1);
TabControl1.TabPosition := TTabPosition.None;
TabControl2.TabPosition := TTabPosition.None;
TabControl1.TabIndex := 0;
TModelClientes.new.PopulaListView(ListView1, img_positivo, img_negativo, edtPesq.Text);
end;
procedure TFrmClientes.Image5Click(Sender: TObject);
begin
lay_ItensTitulo.Visible := false;
end;
procedure TFrmClientes.ListView1ItemClick(const Sender: TObject; const AItem: TListViewItem);
var
List: TStringList;
txt : TListItemText;
begin
with AItem do
begin
txt := TListItemText(Objects.FindDrawable('cod_cliente'));
try
List := TStringList.Create;
TModelClientes.new.PopulaCampos(txt.TagString.ToInteger, List);
lbl_Codigo.Text := FormatFloat('0000', StrToFloat(List[0]));
lbl_NomeFantasia.Text := List[1];
lbl_NomeRazao.Text := List[2];
lbl_CpfCnpj.Text := FormataDoc(List[3]);
lbl_Telefone.Text := formatelefone(List[4]);
lbl_UltimaVisita.Text := List[5];
lbl_Email.Text := List[6];
lbl_Endereco.Text := List[7];
lbl_Bairro.Text := List[8];
lbl_Cidade.Text := List[9];
lbl_Credito.Text := FormatFloat('R$ #,##0.00', StrToFloat(List[10]));
lbl_CredDisponivel.Text := FormatFloat('R$ #,##0.00', StrToFloat(List[11]));
lbl_vlrAberto.Text := FormatFloat('R$ #,##0.00', StrToFloat(List[12]));
if StrToFloat(List[11]) < 0 then
lbl_CredDisponivel.TextSettings.FontColor := $FFF60000
else
lbl_CredDisponivel.TextSettings.FontColor := $FF0C76C1;
finally
FreeAndNil(List);
end;
TabControl2.TabIndex := 0;
TabControl1.TabIndex := 1;
end
end;
procedure TFrmClientes.ListView2ItemClick(const Sender: TObject; const AItem: TListViewItem);
var
List: TStringList;
txt : TListItemText;
begin
with AItem do
begin
lay_ItensTitulo.Visible := true;
txt := TListItemText(Objects.FindDrawable('codped'));
ClearStringGrid(strList_TituloCliente);
TModelTitulosCliente.new.CodPedcar(txt.TagString.ToInteger).PopulaItemTituloStringGrid(strList_TituloCliente);
end
end;
procedure TFrmClientes.Rectangle8Click(Sender: TObject);
begin
lay_ItensTitulo.Visible := false;
TModelTitulosCliente.new.CodCliente(lbl_Codigo.Text.ToInteger).PopulaListView(ListView2, img_aberto, img_vencido);
if ListView2.Items.Count = 0 then
begin
Exibir_Mensagem('SUCESSO', 'ALERTA', 'Parabéns!', 'Cliente não possui titulos abertos!', 'OK', '', $FFDF5447,
$FFDF5447);
Frm_Mensagem.Show;
abort;
end;
TabControl2.TabIndex := 1;
end;
end.
|
unit HashPool;
interface
uses HashUnit;
//note pour Mestoph -> dans SetHashSize la taille choisit doit etre "arrondi" au prochain nombre premier pour la meilleure efficacité
type
PHashItem=^THashItem;
THashItem=record
This:Pointer; //pointeur sur l'objet
HashCode:Cardinal; //si tu garde le hash ici l'unité seraplus generique ca serait p-e mieux vu que c'est pas le seul endroti ou ca a servir , faut voir
Next:PHashItem;
end;
THashTable=class //Warning : rndhash NEED to be Initialized !!!!!!!
private
HashSize:cardinal;
HashList:array Of PHashItem;
EntryCount:Longint;
CycleIt:longint; // num d'entree dans le tableau
CycleObj:PHashItem;//PointerActuel;
public
Constructor Create(pHashSize:integer);
Destructor Destroy;override;
Function AddHashEntry(HashCode:cardinal;Data: Pointer):boolean;overload;
Function AddHashEntry(HashStr:string;Data: Pointer):boolean;overload;
function RemoveHashEntry(EName:string):pointer;
Function GetEntryCount:Longint;
Function SearchByHash(HashCode:cardinal):Pointer;
Function SearchByName(EName:string):pointer;
Procedure ResetCycling;
Function GetNextEntry:Pointer;
end;
implementation
constructor THashTable.Create(pHashSize:integer);
var i:longint;
begin
EntryCount:=0;
HashSize:=pHashSize;
Setlength(HashList,HashSize);
for i:=0 to Hashsize-1 do
begin
// new(HashList[i]);
// HashList[i]^.This:=nil;
// HashList[i]^.Next:=nil;
end;
end;
destructor THashTable.Destroy;
var i:longint;
Next,ActEntry:PHashItem;
begin
for i:=0 to Hashsize-1 do
begin
if Hashlist[i]<>nil then
begin
ActEntry:=HashList[i];
repeat
Next:=ActEntry^.Next;
if ActEntry=nil then break;
// If ActEntry^.This=nil then break;
// if ActEntry^.This^.Data<>nil then Freemem(ActEntry^.This^.Data);
freemem(ActEntry);
ActEntry:=Next;
until ActEntry=nil;
end;
end;
finalize(HashList);
end;
function THashTable.GetEntryCount: Longint;
begin
Result:=EntryCount;
end;
function THashTable.GetNextEntry: Pointer;
begin
Result:=nil;
repeat
if CycleObj=nil then
begin
inc(CycleIt);
CycleObj:=HashList[CycleIt];
end else
begin
Result:=CycleObj^.This;
CycleObj:=CycleObj.Next;
end;
until (Result<>nil) or (CycleIt=(HashSize-1));
end;
procedure THashTable.ResetCycling;
begin
CycleIt:=0;
CycleObj:=HashList[0];
end;
Function THashTable.AddHashEntry(HashStr:string;Data: Pointer):boolean;
begin
Result:=AddHashEntry(RandHash(HashStr),Data);
end;
Function THashTable.AddHashEntry(HashCode:cardinal;Data: Pointer):boolean;
var Num:cardinal;
last,ActEntry:PHashItem;
begin
Result:=false;
num:=HashCode mod HashSize;
if Hashlist[Num]=nil then
begin
new(HashList[num]);
HashList[num]^.This:=nil;
HashList[num]^.Next:=nil;
end;
ActEntry:=HashList[num];
Last:=nil;
repeat
if ActEntry=nil then
begin
new(ActEntry);
ActEntry^.This:=nil;
ActEntry^.Next:=nil;
if Last<>nil then
last^.Next:=ActEntry;
end;
if ActEntry^.This=nil then
begin
ActEntry^.This:=Data;
ActEntry^.HashCode:=HashCode;
Result:=true;
inc(EntryCount);
exit;
end else
begin
if ActEntry^.HashCode=HashCode then
begin
result:=false;
exit; // il esiste deja on l'ajoute pas
end;
last:=Actentry;
ActEntry:=ActEntry^.Next;
end;
until true=false;
end;
function THashTable.RemoveHashEntry(EName:string):pointer;
var num:cardinal;
ActEntry,PrevEntry:PHashItem;
Hash:Cardinal;
begin
Result:=nil;
Hash:=RandHash(EName);
num:=hash mod HashSize;
ActEntry:=HashList[num];
PrevEntry:=ActEntry;
repeat
if ActEntry=nil then exit;
if ActEntry^.This=nil then exit; //ca peu arrivé ca ?
if ActEntry^.HashCode=hash then
begin
break;
end;
PrevEntry:=ActEntry;
ActEntry:=ActEntry^.Next;
until true=false;
//redondant je sait mais je suit crevé todo: a corriger
if HashList[num]=ActEntry then
begin //l'element est le premier
Hashlist[num]:=ActEntry.Next;//si c'est nil ca marche pareil
end else
begin
PrevEntry.Next:=ActEntry.Next;
end;
Result:=ActEntry.This;
dispose(ActEntry);
end;
Function THashTable.SearchByName(EName:string):pointer;
begin
Result:=SearchByHash(RandHash(EName));
end;
function THashTable.SearchByHash(HashCode: cardinal): Pointer;
var num:cardinal;
ActEntry:PHashItem;
begin
result:=nil;
num:=HashCode mod HashSize;
ActEntry:=HashList[num];
repeat
if ActEntry=nil then exit;
if ActEntry^.This=nil then exit;
if ActEntry^.HashCode=HashCode then
begin
result:=ActEntry^.This;
exit;
end;
ActEntry:=ActEntry^.Next;
until true=false;
end;
end.
|
unit uOrcamentoEmailVO;
interface
uses
uKeyField, uTableName, System.Generics.Collections;
type
[TableName('Orcamento_Email')]
TOrcamentoEmailVO = class
private
FEmail: string;
FId: Integer;
FIdOrcamento: Integer;
procedure SetEmail(const Value: string);
procedure SetId(const Value: Integer);
procedure SetIdOrcamento(const Value: Integer);
public
[KeyField('OrcEm_Id')]
property Id: Integer read FId write SetId;
[FieldName('OrcEm_Orcamento')]
property IdOrcamento: Integer read FIdOrcamento write SetIdOrcamento;
[FieldName('OrcEm_Email')]
property Email: string read FEmail write SetEmail;
end;
TListaOrcamentoEmail = TObjectList<TOrcamentoEmailVO>;
implementation
{ TOrcamentoEmailVO }
procedure TOrcamentoEmailVO.SetEmail(const Value: string);
begin
FEmail := Value;
end;
procedure TOrcamentoEmailVO.SetId(const Value: Integer);
begin
FId := Value;
end;
procedure TOrcamentoEmailVO.SetIdOrcamento(const Value: Integer);
begin
FIdOrcamento := Value;
end;
end.
|
unit GameMaster;
interface
uses
GMKernel, Collection;
type
TOnCustomerAdded = procedure (Idx : integer; Alias, Info : string ) of object;
TOnCustomerMessage = procedure (Idx : integer; Msg : string ) of object;
TOnCustomerRemoved = procedure (Idx : integer ) of object;
TOnQueryUsersStatus = procedure ( out Online, Waiting : integer ) of object;
{$M+}
TCustomerInfo =
class
public
constructor Create( aISId : TIServerId; aCustId : TCustomerId );
private
fIServerId : TIServerId;
fCustomerId : TCustomerId;
public
property IServerId : TIServerId read fIServerId;
property CustomerId : TCustomerId read fCustomerId;
end;
TGameMaster =
class(TInterfacedObject, IGameMaster)
public
constructor Create( Name, Password : string );
destructor Destroy; override;
public
procedure setGMConnection( ClientId : integer; aGMConnection : IGMServerConnection );
public
procedure SendMessage( Idx : integer; Msg : string );
procedure NotifyToClient( Idx : integer; notId : integer; Info : string );
procedure NotifyAllClients( notId : integer; Info : string );
procedure UserOnline( Idx : integer );
procedure UserWaiting( Idx : integer );
published //IGameMaster
function AddCustomer( ISId : TIServerId; CustomerId : TCustomerId; ClientInfo : widestring ) : olevariant;
procedure CustomerMsg( ISId : TIServerId; CustomerId : TCustomerId; Msg : WideString );
procedure UnRegisterCustomer( ISId : TIServerId; aCustomerId : TCustomerId );
procedure UnRegisterIServer( aIsId : TIServerId );
private
fCustomers : TLockableCollection;
fGMServerConnection : IGMServerConnection;
fId : TGameMasterId;
fName : string;
fPassword : string;
fIdOnServer : TGameMasterId;
fStatus : integer;
fUsers : integer;
fPending : integer;
fOnCustomerAdded : TOnCustomerAdded;
fOnCustomerMessage : TOnCustomerMessage;
fOnCustomerRemoved : TOnCustomerRemoved;
fOnQueryUsersStatus : TOnQueryUsersStatus;
function getCustomer( IServerId : TIServerId; aCustomerId : TCustomerId ) : TCustomerInfo;
procedure NotifyStatus;
function GetValid : boolean;
public
property Valid : boolean read GetValid;
property Status : integer read fStatus write fStatus;
property Users : integer read fUsers write fUsers;
property Pending : integer read fPending write fPending;
property OnCustomerAdded : TOnCustomerAdded read fOnCustomerAdded write fOnCustomerAdded;
property OnCustomerMessage : TOnCustomerMessage read fOnCustomerMessage write fOnCustomerMessage;
property OnCustomerRemoved : TOnCustomerRemoved read fOnCustomerRemoved write fOnCustomerRemoved;
property OnQueryUsersStatus : TOnQueryUsersStatus read fOnQueryUsersStatus write fOnQueryUsersStatus;
private
procedure syncAddCustomer( const parms : array of const );
procedure syncCustomerMessage( const parms : array of const );
procedure syncCustomerRemoved( const parms : array of const );
procedure syncIntServerRemoved( const parms : array of const );
procedure syncQueryUserStatus( const parms : array of const );
end;
{$M-}
implementation
uses
GMURDOMger, Threads;
// TCustomerInfo
constructor TCustomerInfo.Create( aISId : TIServerId; aCustId : TCustomerId );
begin
inherited Create;
fIServerId := aISId;
fCustomerId := aCustId;
end;
// TGameMaster
constructor TGameMaster.Create( Name, Password : string );
begin
inherited Create;
fCustomers := TLockableCollection.Create( 100, rkBelonguer );
fId := integer(self);
fStatus := GM_STATUS_ONLINE;
fName := Name;
fPassword := Password;
end;
destructor TGameMaster.Destroy;
begin
fCustomers.Free;
inherited;
end;
procedure TGameMaster.setGMConnection( ClientId : integer; aGMConnection : IGMServerConnection );
begin
try
fGMServerConnection := aGMConnection;
fIdOnServer := fGMServerConnection.RegisterGameMaster( ClientId, fId, fName, fPassword);
except
fIdOnServer := INVALID_GAMEMASTER;
end;
end;
procedure TGameMaster.SendMessage( Idx : integer; Msg : string );
begin
try
if fCustomers.IndexOf(TObject(Idx)) <> -1
then fGMServerConnection.SendMessage( TCustomerInfo(Idx).IServerId, TCustomerInfo(Idx).CustomerId, Msg, 0 );
except
end;
end;
procedure TGameMaster.NotifyToClient( Idx : integer; notId : integer; Info : string );
begin
try
if fCustomers.IndexOf(TObject(Idx)) <> -1
then fGMServerConnection.UserNotification( TCustomerInfo(Idx).IServerId, TCustomerInfo(Idx).CustomerId, notId, Info );
except
end;
end;
procedure TGameMaster.NotifyAllClients( notId : integer; Info : string );
var
i : integer;
begin
try
fCustomers.Lock;
try
for i := 0 to pred(fCustomers.Count) do
fGMServerConnection.UserNotification( TCustomerInfo(fCustomers[i]).IServerId, TCustomerInfo(fCustomers[i]).CustomerId, notId, Info );
finally
fCustomers.Unlock;
end;
except
end;
end;
procedure TGameMaster.UserOnline( Idx : integer );
begin
try
if fCustomers.IndexOf(TObject(Idx)) <> -1
then
begin
fGMServerConnection.UserNotification( TCustomerInfo(Idx).IServerId, TCustomerInfo(Idx).CustomerId, GM_NOTIFY_USERONLINE, '' );
end;
except
end;
end;
procedure TGameMaster.UserWaiting( Idx : integer );
begin
try
if fCustomers.IndexOf(TObject(Idx)) <> -1
then fGMServerConnection.UserNotification( TCustomerInfo(Idx).IServerId, TCustomerInfo(Idx).CustomerId, GM_NOTIFY_USERWAITING, '' );
except
end;
end;
function TGameMaster.AddCustomer( ISId : TIServerId; CustomerId : TCustomerId; ClientInfo : widestring ) : olevariant;
var
CustInfo : TCustomerInfo;
begin
try
CustInfo := TCustomerInfo.Create( ISId, CustomerId );
fCustomers.Insert( CustInfo );
result := fPending + 1;
Join( syncAddCustomer, [integer(CustInfo), string(CustomerId), string(ClientInfo)] );
Join( syncQueryUserStatus, [0] );
except
end;
end;
procedure TGameMaster.CustomerMsg( ISId : TIServerId; CustomerId : TCustomerId; Msg : WideString );
var
Cust : TCustomerInfo;
begin
try
Cust := getCustomer( ISId, CustomerId );
Join( syncCustomerMessage, [Cust, string(Msg)] );
except
end;
end;
procedure TGameMaster.UnRegisterCustomer( ISId : TIServerId; aCustomerId : TCustomerId );
var
Cust : TCustomerInfo;
begin
try
Cust := getCustomer( ISId, aCustomerId );
if Cust <> nil
then
begin
Join( syncCustomerRemoved, [cust] );
fCustomers.Delete( Cust );
Join( syncQueryUserStatus, [0] );
end;
except
end;
end;
procedure TGameMaster.UnRegisterIServer( aIsId : TIServerId );
begin
Join( syncIntServerRemoved, [aIsId] );
Join( syncQueryUserStatus, [0] );
end;
function TGameMaster.getCustomer( IServerId : TIServerId; aCustomerId : TCustomerId ) : TCustomerInfo;
var
i : integer;
found : boolean;
begin
try
fCustomers.Lock;
try
i := 0;
found := false;
while (i < fCustomers.Count) and not found do
begin
found := (TCustomerInfo(fCustomers[i]).CustomerId = aCustomerId) and
(TCustomerInfo(fCustomers[i]).IServerId = IServerId);
inc( i );
end;
if found
then result := TCustomerInfo(fCustomers[pred(i)])
else result := nil;
finally
fCustomers.Unlock;
end;
except
result := nil;
end;
end;
procedure TGameMaster.NotifyStatus;
begin
if Assigned(fOnQueryUsersStatus)
then fOnQueryUsersStatus( fUsers, fPending );
fGMServerConnection.NotifyGMStatus( fIdOnServer, fStatus, fUsers, fPending );
end;
function TGameMaster.GetValid : boolean;
begin
result := fIdOnServer <> INVALID_GAMEMASTER;
end;
procedure TGameMaster.syncAddCustomer( const parms : array of const );
var
Index : integer;
Name : string;
Info : string;
begin
Index := parms[0].vInteger;
Name := parms[1].vPchar;
Info := parms[2].vPchar;
if Assigned(fOnCustomerAdded)
then fOnCustomerAdded( Index, Name, Info );
end;
procedure TGameMaster.syncCustomerMessage( const parms : array of const );
var
cust : pointer;
Msg : string;
begin
cust := parms[0].vPointer;
Msg := parms[1].vPchar;
if Assigned(fOnCustomerMessage) and (Cust <> nil)
then fOnCustomerMessage( integer(Cust), Msg );
end;
procedure TGameMaster.syncCustomerRemoved( const parms : array of const );
var
cust : integer;
begin
cust := parms[0].vInteger;
if Assigned(fOnCustomerRemoved)
then fOnCustomerRemoved( integer(cust) );
end;
procedure TGameMaster.syncIntServerRemoved( const parms : array of const );
var
i : integer;
Id : TIServerId;
begin
Id := parms[0].VInteger;
fCustomers.Lock;
try
for i := pred(fCustomers.Count) downto 0 do
if TCustomerInfo(fCustomers[i]).IServerId = Id
then
begin
if Assigned(fOnCustomerRemoved)
then fOnCustomerRemoved( integer(fCustomers[i]) );
fCustomers.AtDelete( i );
end;
finally
fCustomers.Unlock;
end;
end;
procedure TGameMaster.syncQueryUserStatus( const parms : array of const );
begin
NotifyStatus;
end;
end.
|
unit frmMainU;
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.StdCtrls, FMX.Edit, FMX.Controls.Presentation, FMX.ImageSlider,
FMX.Layouts, FMX.ListBox, FMX.ScrollBox, FMX.Memo, FMX.Colors;
type
TfrmMain = class(TForm)
ToolBar: TLayout;
btnAdd: TButton;
btnGoPage: TButton;
Page: TEdit;
OpenDialog: TOpenDialog;
Layout1: TLayout;
Layout2: TLayout;
Button1: TButton;
SpeedButton1: TSpeedButton;
SpeedButton2: TSpeedButton;
Memo1: TMemo;
ImgSlider: TFMXImageSlider;
Layout3: TLayout;
Label2: TLabel;
cbbInterval: TComboBox;
IsAuto: TCheckBox;
chkShowDots: TCheckBox;
Layout4: TLayout;
cpActiveColor: TColorPanel;
cpInactiveColor: TColorPanel;
procedure btnAddClick(Sender: TObject);
procedure btnGoPageClick(Sender: TObject);
procedure IsAutoChange(Sender: TObject);
procedure btnInitClick(Sender: TObject);
procedure btnPrevClick(Sender: TObject);
procedure btnNextClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure cbbIntervalChange(Sender: TObject);
procedure ImgSliderItemClick(Sender: TObject);
procedure ImgSliderItemTap(Sender: TObject; const Point: TPointF);
procedure ImgSliderCanDragBegin(Sender: TObject; var CanBegin: Boolean);
procedure ImgSliderPageAnimationFinish(Sender: TObject; NewPage: Integer);
procedure ImgSliderPageChange(Sender: TObject; NewPage, OldPage: Integer);
procedure chkShowDotsChange(Sender: TObject);
procedure Layout4Resize(Sender: TObject);
procedure cpActiveColorChange(Sender: TObject);
procedure cpInactiveColorChange(Sender: TObject);
procedure FormResize(Sender: TObject);
private
procedure AddBitmap(const FileName: string);
{ Private declarations }
public
{ Public declarations }
end;
var
frmMain: TfrmMain;
implementation
uses
System.IOUtils;
{$R *.fmx}
procedure TfrmMain.btnAddClick(Sender: TObject);
begin
if OpenDialog.Execute then
begin
AddBitmap(OpenDialog.FileName);
end;
end;
procedure TfrmMain.btnGoPageClick(Sender: TObject);
begin
ImgSlider.ActivePage := StrToInt(Page.Text.Trim);
end;
procedure TfrmMain.btnInitClick(Sender: TObject);
begin
ImgSlider.Clear;
end;
procedure TfrmMain.btnNextClick(Sender: TObject);
begin
ImgSlider.Next;
end;
procedure TfrmMain.btnPrevClick(Sender: TObject);
begin
ImgSlider.Prev;
end;
procedure TfrmMain.cbbIntervalChange(Sender: TObject);
const
INTERVALS: array [0..4] of Integer = (
1000, 2000, 3000, 4000, 5000
);
begin
ImgSlider.TimerInterval := INTERVALS[cbbInterval.ItemIndex];
end;
procedure TfrmMain.chkShowDotsChange(Sender: TObject);
begin
ImgSlider.DotsVisible := chkShowDots.IsChecked;
end;
procedure TfrmMain.cpActiveColorChange(Sender: TObject);
begin
ImgSlider.DotActiveColor := cpActiveColor.Color;
end;
procedure TfrmMain.cpInactiveColorChange(Sender: TObject);
begin
ImgSlider.DotInActiveColor := cpInactiveColor.Color;
end;
procedure TfrmMain.FormCreate(Sender: TObject);
begin
ImgSlider.Height:= ClientWidth * 400 / 640;
{$IFDEF MSWINDOWS}
AddBitmap('..\..\Images\image1.jpg');
AddBitmap('..\..\Images\image2.jpg');
AddBitmap('..\..\Images\image3.jpg');
AddBitmap('..\..\Images\image4.jpg');
ImgSlider.ActivePage := 0;
{$ENDIF}
{$IFDEF ANDROID}
AddBitmap('images/image1.jpg');
AddBitmap('images/image2.jpg');
AddBitmap('images/image3.jpg');
AddBitmap('images/image4.jpg');
ImgSlider.ActivePage := 0;
{$ENDIF}
cpActiveColor.Color := ImgSlider.DotActiveColor;
cpInActiveColor.Color := ImgSlider.DotInActiveColor;
end;
procedure TfrmMain.FormResize(Sender: TObject);
begin
ImgSlider.Height:= ClientWidth * 400 / 640;
end;
procedure TfrmMain.ImgSliderCanDragBegin(Sender: TObject;
var CanBegin: Boolean);
begin
// Memo1.Lines.Add('On CanDragBegin');
end;
procedure TfrmMain.ImgSliderItemClick(Sender: TObject);
begin
// Memo1.Lines.Add('On Item Click: '+ TControl(Sender).Tag.ToString);
end;
procedure TfrmMain.ImgSliderItemTap(Sender: TObject; const Point: TPointF);
begin
// Memo1.Lines.Add('On Item Tap: '+ TControl(Sender).Tag.ToString);
end;
procedure TfrmMain.ImgSliderPageAnimationFinish(Sender: TObject; NewPage: Integer);
begin
// Memo1.Lines.Add(
// Format('On PageAnimationFinish, NewPage: %d, OldPage: %d',
// [NewPage, OldPage]));
end;
procedure TfrmMain.ImgSliderPageChange(Sender: TObject; NewPage,
OldPage: Integer);
begin
Memo1.Lines.Add(
Format('On PageChange, OldPage: %d, NewPage: %d',
[OldPage, NewPage]));
end;
procedure TfrmMain.AddBitmap(const FileName: string);
var
Bmp: TBitmap;
p: string;
begin
Bmp := TBitmap.Create;
try
{$IFDEF ANDROID}
p := TPath.Combine(System.IOUtils.TPath.GetDocumentsPath, FileName);
{$ELSE}
p := FileName;
{$ENDIF}
Bmp.LoadFromFile(p);
ImgSlider.Add((ImgSlider.PageCount + 1).ToString, Bmp);
finally
Bmp.Free;
end;
end;
procedure TfrmMain.IsAutoChange(Sender: TObject);
begin
ImgSlider.AutoSlider := IsAuto.IsChecked;
end;
procedure TfrmMain.Layout4Resize(Sender: TObject);
begin
cpActiveColor.Width := Layout4.Width / 2;
cpInactiveColor.Width := Layout4.Width / 2;
end;
end.
|
unit fpcorm_common_constants;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils;
const
{ Byte 0 .. 255 }
c_fo_MinByte: Byte = Low(Byte);
c_fo_MaxByte: Byte = High(Byte);
{ ShortInt -128 .. 127 }
c_fo_MinShortInt: ShortInt = Low(ShortInt);
c_fo_MaxShortInt: ShortInt = High(ShortInt);
{ SmallInt -32768 .. 32767 }
c_fo_MinSmallInt: SmallInt = Low(SmallInt);
c_fo_MaxSmallInt: SmallInt = High(SmallInt);
{ Word 0 .. 65535 }
c_fo_MinWord: Word = Low(Word);
c_fo_MaxWord: Word = High(Word);
{ LongInt -2147483648 .. 2147483647 }
c_fo_MinLongInt: LongInt = Low(LongInt);
c_fo_MaxLongInt: LongInt = High(LongInt);
{ LongWord 0 .. 4294967295 }
c_fo_MinLongWord: LongWord = Low(LongWord);
c_fo_MaxLongWord: LongWord = High(LongWord);
{ Int64 -9223372036854775808 .. 9223372036854775807 }
c_fo_MinInt64: Int64 = Low(Int64);
c_fo_MaxInt64: Int64 = High(Int64);
{ QWord 0 .. 18446744073709551615 }
c_fo_MinQWord: QWord = Low(QWord);
c_fo_MaxQWord: QWord = High(QWord);
{ Single 1.5E-45 .. 3.4E38 }
c_fo_MinSingle: Single = 1.5E-45;
c_fo_MaxSingle: Single = 3.4E38;
{ Double 5.0E-324 .. 1.7E308 }
c_fo_MinDouble: Double = 5.0E-324;
c_fo_MaxDouble: Double = 1.7E308;
{ Extended 1.9E-4932 .. 1.1E4932 }
c_fo_MinExtended: Extended = 1.9E-4932;
c_fo_MaxExtended: Extended = 1.1E4932;
{ Currency -922337203685477.5808 .. 922337203685477.5807 }
{ c_fo_MinCurrency = MinCurrency;
c_fo_MaxCurrency = MaxCurrency; }
{ TDateTime 01/01/0001 12:00:00.000 AM .. 12/31/9999 11:59:59.999 PM }
{ c_fo_MinDateTime = MinDateTime;
c_fo_MaxDateTime = MaxDateTime; }
implementation
end.
|
unit TTSCOLSRTable;
interface
uses
Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf;
type
TTTSCOLSRRecord = record
PLenderNum: String[4];
PCifFlag: String[1];
PLoanNum: String[20];
PColNum: SmallInt;
PEntryNum: String[1];
PSearchKey: String[15];
PBranch: String[8];
PNameA: String[40];
PNameB: String[40];
PCollateral1: String[60];
PCollateral2: String[60];
End;
TTTSCOLSRBuffer = class(TDataBuf)
protected
function PtrIndex(Index:integer):Pointer;override;
public
Data: TTTSCOLSRRecord;
function FieldNameToIndex(s:string):integer;override;
function FieldType(index:integer):TFieldType;override;
end;
TEITTSCOLSR = (TTSCOLSRPrimaryKey, TTSCOLSRByColl, TTSCOLSRByBranchColl);
TTTSCOLSRTable = class( TDBISAMTableAU )
private
FDFLenderNum: TStringField;
FDFCifFlag: TStringField;
FDFLoanNum: TStringField;
FDFColNum: TSmallIntField;
FDFEntryNum: TStringField;
FDFSearchKey: TStringField;
FDFBranch: TStringField;
FDFNameA: TStringField;
FDFNameB: TStringField;
FDFCollateral1: TStringField;
FDFCollateral2: TStringField;
procedure SetPLenderNum(const Value: String);
function GetPLenderNum:String;
procedure SetPCifFlag(const Value: String);
function GetPCifFlag:String;
procedure SetPLoanNum(const Value: String);
function GetPLoanNum:String;
procedure SetPColNum(const Value: SmallInt);
function GetPColNum:SmallInt;
procedure SetPEntryNum(const Value: String);
function GetPEntryNum:String;
procedure SetPSearchKey(const Value: String);
function GetPSearchKey:String;
procedure SetPBranch(const Value: String);
function GetPBranch:String;
procedure SetPNameA(const Value: String);
function GetPNameA:String;
procedure SetPNameB(const Value: String);
function GetPNameB:String;
procedure SetPCollateral1(const Value: String);
function GetPCollateral1:String;
procedure SetPCollateral2(const Value: String);
function GetPCollateral2:String;
function GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string;
procedure SetEnumIndex(Value: TEITTSCOLSR);
function GetEnumIndex: TEITTSCOLSR;
protected
function CreateField( const FieldName : string ): TField;
procedure CreateFields; reintroduce;
procedure SetActive(Value: Boolean); override;
procedure LoadFieldDefs(AStringList:TStringList);override;
procedure LoadIndexDefs(AStringList:TStringList);override;
public
function GetDataBuffer:TTTSCOLSRRecord;
procedure StoreDataBuffer(ABuffer:TTTSCOLSRRecord);
property DFLenderNum: TStringField read FDFLenderNum;
property DFCifFlag: TStringField read FDFCifFlag;
property DFLoanNum: TStringField read FDFLoanNum;
property DFColNum: TSmallIntField read FDFColNum;
property DFEntryNum: TStringField read FDFEntryNum;
property DFSearchKey: TStringField read FDFSearchKey;
property DFBranch: TStringField read FDFBranch;
property DFNameA: TStringField read FDFNameA;
property DFNameB: TStringField read FDFNameB;
property DFCollateral1: TStringField read FDFCollateral1;
property DFCollateral2: TStringField read FDFCollateral2;
property PLenderNum: String read GetPLenderNum write SetPLenderNum;
property PCifFlag: String read GetPCifFlag write SetPCifFlag;
property PLoanNum: String read GetPLoanNum write SetPLoanNum;
property PColNum: SmallInt read GetPColNum write SetPColNum;
property PEntryNum: String read GetPEntryNum write SetPEntryNum;
property PSearchKey: String read GetPSearchKey write SetPSearchKey;
property PBranch: String read GetPBranch write SetPBranch;
property PNameA: String read GetPNameA write SetPNameA;
property PNameB: String read GetPNameB write SetPNameB;
property PCollateral1: String read GetPCollateral1 write SetPCollateral1;
property PCollateral2: String read GetPCollateral2 write SetPCollateral2;
published
property Active write SetActive;
property EnumIndex: TEITTSCOLSR read GetEnumIndex write SetEnumIndex;
end; { TTTSCOLSRTable }
procedure Register;
implementation
function TTTSCOLSRTable.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 { TTTSCOLSRTable.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; { TTTSCOLSRTable.GenerateNewFieldName }
function TTTSCOLSRTable.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; { TTTSCOLSRTable.CreateField }
procedure TTTSCOLSRTable.CreateFields;
begin
FDFLenderNum := CreateField( 'LenderNum' ) as TStringField;
FDFCifFlag := CreateField( 'CifFlag' ) as TStringField;
FDFLoanNum := CreateField( 'LoanNum' ) as TStringField;
FDFColNum := CreateField( 'ColNum' ) as TSmallIntField;
FDFEntryNum := CreateField( 'EntryNum' ) as TStringField;
FDFSearchKey := CreateField( 'SearchKey' ) as TStringField;
FDFBranch := CreateField( 'Branch' ) as TStringField;
FDFNameA := CreateField( 'NameA' ) as TStringField;
FDFNameB := CreateField( 'NameB' ) as TStringField;
FDFCollateral1 := CreateField( 'Collateral1' ) as TStringField;
FDFCollateral2 := CreateField( 'Collateral2' ) as TStringField;
end; { TTTSCOLSRTable.CreateFields }
procedure TTTSCOLSRTable.SetActive(Value: Boolean);
begin
inherited SetActive(Value);
if Active then
CreateFields;
end; { TTTSCOLSRTable.SetActive }
procedure TTTSCOLSRTable.SetPLenderNum(const Value: String);
begin
DFLenderNum.Value := Value;
end;
function TTTSCOLSRTable.GetPLenderNum:String;
begin
result := DFLenderNum.Value;
end;
procedure TTTSCOLSRTable.SetPCifFlag(const Value: String);
begin
DFCifFlag.Value := Value;
end;
function TTTSCOLSRTable.GetPCifFlag:String;
begin
result := DFCifFlag.Value;
end;
procedure TTTSCOLSRTable.SetPLoanNum(const Value: String);
begin
DFLoanNum.Value := Value;
end;
function TTTSCOLSRTable.GetPLoanNum:String;
begin
result := DFLoanNum.Value;
end;
procedure TTTSCOLSRTable.SetPColNum(const Value: SmallInt);
begin
DFColNum.Value := Value;
end;
function TTTSCOLSRTable.GetPColNum:SmallInt;
begin
result := DFColNum.Value;
end;
procedure TTTSCOLSRTable.SetPEntryNum(const Value: String);
begin
DFEntryNum.Value := Value;
end;
function TTTSCOLSRTable.GetPEntryNum:String;
begin
result := DFEntryNum.Value;
end;
procedure TTTSCOLSRTable.SetPSearchKey(const Value: String);
begin
DFSearchKey.Value := Value;
end;
function TTTSCOLSRTable.GetPSearchKey:String;
begin
result := DFSearchKey.Value;
end;
procedure TTTSCOLSRTable.SetPBranch(const Value: String);
begin
DFBranch.Value := Value;
end;
function TTTSCOLSRTable.GetPBranch:String;
begin
result := DFBranch.Value;
end;
procedure TTTSCOLSRTable.SetPNameA(const Value: String);
begin
DFNameA.Value := Value;
end;
function TTTSCOLSRTable.GetPNameA:String;
begin
result := DFNameA.Value;
end;
procedure TTTSCOLSRTable.SetPNameB(const Value: String);
begin
DFNameB.Value := Value;
end;
function TTTSCOLSRTable.GetPNameB:String;
begin
result := DFNameB.Value;
end;
procedure TTTSCOLSRTable.SetPCollateral1(const Value: String);
begin
DFCollateral1.Value := Value;
end;
function TTTSCOLSRTable.GetPCollateral1:String;
begin
result := DFCollateral1.Value;
end;
procedure TTTSCOLSRTable.SetPCollateral2(const Value: String);
begin
DFCollateral2.Value := Value;
end;
function TTTSCOLSRTable.GetPCollateral2:String;
begin
result := DFCollateral2.Value;
end;
procedure TTTSCOLSRTable.LoadFieldDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('LenderNum, String, 4, N');
Add('CifFlag, String, 1, N');
Add('LoanNum, String, 20, N');
Add('ColNum, SmallInt, 0, N');
Add('EntryNum, String, 1, N');
Add('SearchKey, String, 15, N');
Add('Branch, String, 8, N');
Add('NameA, String, 40, N');
Add('NameB, String, 40, N');
Add('Collateral1, String, 60, N');
Add('Collateral2, String, 60, N');
end;
end;
procedure TTTSCOLSRTable.LoadIndexDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('PrimaryKey, LenderNum;CifFlag;LoanNum;ColNum;EntryNum, Y, Y, N, N');
Add('ByColl, LenderNum;SearchKey, N, N, Y, N');
Add('ByBranchColl, LenderNum;Branch;SearchKey, N, N, Y, N');
end;
end;
procedure TTTSCOLSRTable.SetEnumIndex(Value: TEITTSCOLSR);
begin
case Value of
TTSCOLSRPrimaryKey : IndexName := '';
TTSCOLSRByColl : IndexName := 'ByColl';
TTSCOLSRByBranchColl : IndexName := 'ByBranchColl';
end;
end;
function TTTSCOLSRTable.GetDataBuffer:TTTSCOLSRRecord;
var buf: TTTSCOLSRRecord;
begin
fillchar(buf, sizeof(buf), 0);
buf.PLenderNum := DFLenderNum.Value;
buf.PCifFlag := DFCifFlag.Value;
buf.PLoanNum := DFLoanNum.Value;
buf.PColNum := DFColNum.Value;
buf.PEntryNum := DFEntryNum.Value;
buf.PSearchKey := DFSearchKey.Value;
buf.PBranch := DFBranch.Value;
buf.PNameA := DFNameA.Value;
buf.PNameB := DFNameB.Value;
buf.PCollateral1 := DFCollateral1.Value;
buf.PCollateral2 := DFCollateral2.Value;
result := buf;
end;
procedure TTTSCOLSRTable.StoreDataBuffer(ABuffer:TTTSCOLSRRecord);
begin
DFLenderNum.Value := ABuffer.PLenderNum;
DFCifFlag.Value := ABuffer.PCifFlag;
DFLoanNum.Value := ABuffer.PLoanNum;
DFColNum.Value := ABuffer.PColNum;
DFEntryNum.Value := ABuffer.PEntryNum;
DFSearchKey.Value := ABuffer.PSearchKey;
DFBranch.Value := ABuffer.PBranch;
DFNameA.Value := ABuffer.PNameA;
DFNameB.Value := ABuffer.PNameB;
DFCollateral1.Value := ABuffer.PCollateral1;
DFCollateral2.Value := ABuffer.PCollateral2;
end;
function TTTSCOLSRTable.GetEnumIndex: TEITTSCOLSR;
var iname : string;
begin
result := TTSCOLSRPrimaryKey;
iname := uppercase(indexname);
if iname = '' then result := TTSCOLSRPrimaryKey;
if iname = 'BYCOLL' then result := TTSCOLSRByColl;
if iname = 'BYBRANCHCOLL' then result := TTSCOLSRByBranchColl;
end;
(********************************************)
(************ Register Component ************)
(********************************************)
procedure Register;
begin
RegisterComponents( 'TTS Tables', [ TTTSCOLSRTable, TTTSCOLSRBuffer ] );
end; { Register }
function TTTSCOLSRBuffer.FieldNameToIndex(s:string):integer;
const flist:array[1..11] of string = ('LENDERNUM','CIFFLAG','LOANNUM','COLNUM','ENTRYNUM','SEARCHKEY'
,'BRANCH','NAMEA','NAMEB','COLLATERAL1','COLLATERAL2'
);
var x : integer;
begin
s := uppercase(s);
x := 1;
while (x <= 11) and (flist[x] <> s) do inc(x);
if x <= 11 then result := x else result := 0;
end;
function TTTSCOLSRBuffer.FieldType(index:integer):TFieldType;
begin
result := ftUnknown;
case index of
1 : result := ftString;
2 : result := ftString;
3 : result := ftString;
4 : result := ftSmallInt;
5 : result := ftString;
6 : result := ftString;
7 : result := ftString;
8 : result := ftString;
9 : result := ftString;
10 : result := ftString;
11 : result := ftString;
end;
end;
function TTTSCOLSRBuffer.PtrIndex(index:integer):Pointer;
begin
result := nil;
case index of
1 : result := @Data.PLenderNum;
2 : result := @Data.PCifFlag;
3 : result := @Data.PLoanNum;
4 : result := @Data.PColNum;
5 : result := @Data.PEntryNum;
6 : result := @Data.PSearchKey;
7 : result := @Data.PBranch;
8 : result := @Data.PNameA;
9 : result := @Data.PNameB;
10 : result := @Data.PCollateral1;
11 : result := @Data.PCollateral2;
end;
end;
end.
|
unit UnitFrmOptions;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons, Vcl.ComCtrls,
Vcl.ExtCtrls, Vcl.Menus;
type
TfrmOptions = class(TForm)
lblAutoSaveInterval: TLabel;
edtAutosaveInterval: TEdit;
udAutoSaveInterval: TUpDown;
cbxPrompt: TCheckBox;
btnOK: TBitBtn;
btnCancel: TBitBtn;
private
{ Private declarations }
public
{ Public declarations }
Class Function Execute(var iInterval: Integer;
var boolPrompt: Boolean): Boolean;
end;
var
frmOptions: TfrmOptions;
implementation
{$R *.dfm}
{ TfrmOptions }
class function TfrmOptions.Execute(var iInterval: Integer;
var boolPrompt: Boolean): Boolean;
begin
Result := False;
with TfrmOptions.Create(nil) do
begin
try
udAutoSaveInterval.Position := iInterval;
cbxPrompt.Checked := boolPrompt;
if ShowModal = mrOk then
begin
Result := True;
iInterval := udAutoSaveInterval.Position;
boolPrompt := cbxPrompt.Checked;
end;
finally
free
end;
end;
end;
end.
|
{
$Project$
$Workfile$
$Revision$
$DateUTC$
$Id$
This file is part of the Indy (Internet Direct) project, and is offered
under the dual-licensing agreement described on the Indy website.
(http://www.indyproject.org/)
Copyright:
(c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved.
}
{
$Log$
}
{
Rev 1.2 2/23/2005 6:34:30 PM JPMugaas
New property for displaying permissions ina GUI column. Note that this
should not be used like a CHMOD because permissions are different on
different platforms - you have been warned.
Rev 1.1 10/26/2004 11:21:16 PM JPMugaas
Updated refs.
Rev 1.0 7/30/2004 8:03:42 AM JPMugaas
FTP List parser for the Tandem NonStop Guardian file-system.
}
unit IdFTPListParseTandemGuardian;
interface
{$i IdCompilerDefines.inc}
uses
Classes,
IdFTPList, IdFTPListParseBase, IdFTPListTypes;
{
This parser is based on the Tandem NonStop Server with a Guardian file system.
This is primarily based on some correspondances and samples I got from Steeve Howe.
His correspondance is here and I'm noting it in case I need to refer back later:
What are the rules for acceptable filenames on the Tandem?
>>Must start with a character and must be at least on character long.
What charactors can be used?
>>Alpha characters and numerals.
What's the length?
>> 8 characters max.
Can you have file extensions, if so how many and what's the length for
those?
>> No file extensions.
Is the system case insensitive or case-sensitive?
>>All filenames are converted to uppercase (from what I can tell)
What's Code? Is it always a number?
>> Code is the type of file. 101 is an editable file, 100 is an
exacutable, 1000 is an user defined executable, there is a type 1600
and I have seen type 0 (which I think is an unknown binary type of
file)
What's EOF? Is that the file size? I don't know.
>> Yes, That is the file size.
In the Owner column, you have something like this "155, 76". Are
their only numbers and what do the numbers in the column mean (I
assume that there is two). Will the Owner column ever have letters?
>> Never letters.
first byte is group, second is user
it describes user and security level
What is valid for "RWEP" and what do the letters in that mean and what
letters are there?
>> Read, Write, Execute, Purge
some valid letters (there are about 7 and I don't know them all):
N - anyone across system has access
U - only the user has this priviledge
A - anyone on local system has priviledge
G - anyone belonging to same group
- (dash) - only local super.super has access
some further references from Tandem that might help:
http://www.hp.com/go/NTL - General technical reference
http://h30163.www3.hp.com/NTL/library/G06_RVUs/G06_20/Publications/ -HP
G06.20 Publications
hope this helps!
}
{
This parses something like this:
====
File Code EOF Last Modification Owner RWEP
ALV 101 2522 27-Aug-02 13:57:10 155,106 "nnnn"
ALVO 1000 2048 27-Aug-02 13:57:22 155,106 "nunu"
====
}
type
TIdTandemGuardianFTPListItem = class(TIdOwnerFTPListItem)
protected
//this is given as a numbeer like the owner. We keep it as a string
//for consistancy with other FTP list parsers.
FGroupName : String;
//this may be an integer value but I'm not sure
//because one
FCode : LongWord;
//This is the RWEP value
{ It's done like this:
Read, Write, Execute, Purge
some valid letters (there are about 7 and I don't know them all):
N - anyone across system has access
U - only the user has this priviledge
A - anyone on local system has priviledge
G - anyone belonging to same group
- (dash) - only local super.super has access
}
FPermissions : String;
public
property GroupName : String read FGroupName write FGroupName;
property Code : LongWord read FCode write FCode;
property Permissions : String read FPermissions write FPermissions;
end;
TIdFTPLPTandemGuardian = class(TIdFTPListBaseHeader)
protected
class function MakeNewItem(AOwner : TIdFTPListItems) : TIdFTPListItem; override;
class function IsHeader(const AData: String): Boolean; override;
class function ParseLine(const AItem : TIdFTPListItem; const APath : String = ''): Boolean; override;
public
class function GetIdent : String; override;
end;
const
TANDEM_GUARDIAN_ID = 'Tandem NonStop Guardian'; {do not localize}
// RLebeau 2/14/09: this forces C++Builder to link to this unit so
// RegisterFTPListParser can be called correctly at program startup...
(*$HPPEMIT '#pragma link "IdFTPListParseTandemGuardian"'*)
implementation
uses
IdFTPCommon, IdGlobal, IdGlobalProtocols, SysUtils;
{ TIdFTPLPTandemGuardian }
class function TIdFTPLPTandemGuardian.GetIdent: String;
begin
Result := TANDEM_GUARDIAN_ID;
end;
class function TIdFTPLPTandemGuardian.IsHeader(const AData: String): Boolean;
var
LCols : TStrings;
begin
Result := False;
LCols := TStringList.Create;
try
SplitColumns(Trim(AData), LCols);
if LCols.Count = 7 then
begin
Result := (LCols[0] = 'File') and {do not localize}
(LCols[1] = 'Code') and {do not localize}
(LCols[2] = 'EOF') and {do not localize}
(LCols[3] = 'Last') and {do not localize}
(LCols[4] = 'Modification') and {do not localize}
(LCols[5] = 'Owner') and {do not localize}
(LCols[6] = 'RWEP') {do not localize}
end;
finally
FreeAndNil(LCols);
end;
end;
class function TIdFTPLPTandemGuardian.MakeNewItem(AOwner: TIdFTPListItems): TIdFTPListItem;
begin
Result := TIdTandemGuardianFTPListItem.Create(AOwner);
end;
class function TIdFTPLPTandemGuardian.ParseLine(const AItem: TIdFTPListItem;
const APath: String): Boolean;
var
LItem : TIdTandemGuardianFTPListItem;
LLine, LBuffer : String;
LDay, LMonth, LYear : Integer;
begin
{
Parse lines like these:
ALV 101 2522 27-Aug-02 13:57:10 155,106 "nnnn"
ALVO 1000 2048 27-Aug-02 13:57:22 155,106 "nunu"
}
//
{ Note from Steeve Howe:
===
The directories are flat. The Guardian system appears like this:
\<server>.$<volume>.<subvolume>
you can change from server to server, volume to volume, subvolume to
subvolume, but
nothing deeper. what you get from a directory listing then is just the
files within that
subvolume of the volume on the server.
===
}
Result := True;
LItem := AItem as TIdTandemGuardianFTPListItem;
LLine := Trim(LItem.Data);
LItem.ItemType := ditFile;
//name
// Steve Howe advised me that a filename can not have a space and is 8 chars
// with no filename extensions. It is case insensitive.
LItem.FileName := Fetch(LLine);
LLine := TrimLeft(LLine);
//code
LItem.Code := IndyStrToInt(Fetch(LLine), 0);
LLine := TrimLeft(LLine);
//EOF
LItem.Size := IndyStrToInt64(Fetch(LLine), 0);
LLine := TrimLeft(LLine);
//Last Modification
//date
LBuffer := Fetch(LLine);
LLine := TrimLeft(LLine);
LDay := IndyStrToInt(Fetch(LBuffer, '-'), 1); {do not localize}
LMonth := StrToMonth(Fetch(LBuffer, '-')); {do not localize}
LYear := IndyStrToInt(Fetch(LBuffer), 1989);
LYear := Y2Year(LYear);
//time
LItem.ModifiedDate := EncodeDate(LYear, LMonth, LDay);
LBuffer := Fetch(LLine);
LLine := TrimLeft(LLine);
LItem.ModifiedDate := AItem.ModifiedDate + TimeHHMMSS(LBuffer);
LLine := TrimLeft(LLine);
//group,Owner
//Steve how advised me that the first number in this column is a group
//and the number after the comma is an owner
LItem.GroupName := Fetch(LLine, ','); {do not localize}
LLine := TrimLeft(LLine);
LItem.OwnerName := Fetch(LLine);
//RWEP
LItem.Permissions := UnquotedStr(LLine);
LItem.PermissionDisplay := '"' + LItem.Permissions + '"';
end;
initialization
RegisterFTPListParser(TIdFTPLPTandemGuardian);
finalization
UnRegisterFTPListParser(TIdFTPLPTandemGuardian);
end.
|
unit ContentsKeywordsPack;
{* Набор слов словаря для доступа к экземплярам контролов формы Contents }
// Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\View\Document\Forms\ContentsKeywordsPack.pas"
// Стереотип: "ScriptKeywordsPack"
// Элемент модели: "ContentsKeywordsPack" MUID: (4A9D51C4026F_Pack)
{$Include w:\garant6x\implementation\Garant\nsDefine.inc}
interface
{$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL)}
uses
l3IntfUses
;
{$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL)
implementation
{$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL)}
uses
l3ImplUses
, Contents_Form
, tfwPropertyLike
, vtPanel
, tfwScriptingInterfaces
, TypInfo
, tfwTypeInfo
, vtLister
, nscTreeViewWithAdapterDragDrop
{$If Defined(Nemesis)}
, nscContextFilter
{$IfEnd} // Defined(Nemesis)
{$If Defined(Nemesis)}
, nscTasksPanelView
{$IfEnd} // Defined(Nemesis)
, tfwControlString
, kwBynameControlPush
, TtfwClassRef_Proxy
, SysUtils
, TtfwTypeRegistrator_Proxy
, tfwScriptingTypes
//#UC START# *4A9D51C4026F_Packimpl_uses*
//#UC END# *4A9D51C4026F_Packimpl_uses*
;
type
TkwContentsFormBackgroundPanel = {final} class(TtfwPropertyLike)
{* Слово скрипта .TContentsForm.BackgroundPanel }
private
function BackgroundPanel(const aCtx: TtfwContext;
aContentsForm: TContentsForm): TvtPanel;
{* Реализация слова скрипта .TContentsForm.BackgroundPanel }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwContentsFormBackgroundPanel
TkwContentsFormLstBookmarks = {final} class(TtfwPropertyLike)
{* Слово скрипта .TContentsForm.lstBookmarks }
private
function lstBookmarks(const aCtx: TtfwContext;
aContentsForm: TContentsForm): TvtLister;
{* Реализация слова скрипта .TContentsForm.lstBookmarks }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwContentsFormLstBookmarks
TkwContentsFormLstComments = {final} class(TtfwPropertyLike)
{* Слово скрипта .TContentsForm.lstComments }
private
function lstComments(const aCtx: TtfwContext;
aContentsForm: TContentsForm): TvtLister;
{* Реализация слова скрипта .TContentsForm.lstComments }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwContentsFormLstComments
TkwContentsFormLstExternalObjects = {final} class(TtfwPropertyLike)
{* Слово скрипта .TContentsForm.lstExternalObjects }
private
function lstExternalObjects(const aCtx: TtfwContext;
aContentsForm: TContentsForm): TvtLister;
{* Реализация слова скрипта .TContentsForm.lstExternalObjects }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwContentsFormLstExternalObjects
TkwContentsFormContentsTree = {final} class(TtfwPropertyLike)
{* Слово скрипта .TContentsForm.ContentsTree }
private
function ContentsTree(const aCtx: TtfwContext;
aContentsForm: TContentsForm): TnscTreeViewWithAdapterDragDrop;
{* Реализация слова скрипта .TContentsForm.ContentsTree }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwContentsFormContentsTree
TkwContentsFormContextFilter = {final} class(TtfwPropertyLike)
{* Слово скрипта .TContentsForm.ContextFilter }
private
function ContextFilter(const aCtx: TtfwContext;
aContentsForm: TContentsForm): TnscContextFilter;
{* Реализация слова скрипта .TContentsForm.ContextFilter }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwContentsFormContextFilter
TkwContentsFormTasks = {final} class(TtfwPropertyLike)
{* Слово скрипта .TContentsForm.Tasks }
private
function Tasks(const aCtx: TtfwContext;
aContentsForm: TContentsForm): TnscTasksPanelView;
{* Реализация слова скрипта .TContentsForm.Tasks }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwContentsFormTasks
Tkw_Form_Contents = {final} class(TtfwControlString)
{* Слово словаря для идентификатора формы Contents
----
*Пример использования*:
[code]форма::Contents TryFocus ASSERT[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_Form_Contents
Tkw_Contents_Control_BackgroundPanel = {final} class(TtfwControlString)
{* Слово словаря для идентификатора контрола BackgroundPanel
----
*Пример использования*:
[code]контрол::BackgroundPanel TryFocus ASSERT[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_Contents_Control_BackgroundPanel
Tkw_Contents_Control_BackgroundPanel_Push = {final} class(TkwBynameControlPush)
{* Слово словаря для контрола BackgroundPanel
----
*Пример использования*:
[code]контрол::BackgroundPanel:push pop:control:SetFocus ASSERT[code] }
protected
procedure DoDoIt(const aCtx: TtfwContext); override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_Contents_Control_BackgroundPanel_Push
Tkw_Contents_Control_lstBookmarks = {final} class(TtfwControlString)
{* Слово словаря для идентификатора контрола lstBookmarks
----
*Пример использования*:
[code]контрол::lstBookmarks TryFocus ASSERT[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_Contents_Control_lstBookmarks
Tkw_Contents_Control_lstBookmarks_Push = {final} class(TkwBynameControlPush)
{* Слово словаря для контрола lstBookmarks
----
*Пример использования*:
[code]контрол::lstBookmarks:push pop:control:SetFocus ASSERT[code] }
protected
procedure DoDoIt(const aCtx: TtfwContext); override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_Contents_Control_lstBookmarks_Push
Tkw_Contents_Control_lstComments = {final} class(TtfwControlString)
{* Слово словаря для идентификатора контрола lstComments
----
*Пример использования*:
[code]контрол::lstComments TryFocus ASSERT[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_Contents_Control_lstComments
Tkw_Contents_Control_lstComments_Push = {final} class(TkwBynameControlPush)
{* Слово словаря для контрола lstComments
----
*Пример использования*:
[code]контрол::lstComments:push pop:control:SetFocus ASSERT[code] }
protected
procedure DoDoIt(const aCtx: TtfwContext); override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_Contents_Control_lstComments_Push
Tkw_Contents_Control_lstExternalObjects = {final} class(TtfwControlString)
{* Слово словаря для идентификатора контрола lstExternalObjects
----
*Пример использования*:
[code]контрол::lstExternalObjects TryFocus ASSERT[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_Contents_Control_lstExternalObjects
Tkw_Contents_Control_lstExternalObjects_Push = {final} class(TkwBynameControlPush)
{* Слово словаря для контрола lstExternalObjects
----
*Пример использования*:
[code]контрол::lstExternalObjects:push pop:control:SetFocus ASSERT[code] }
protected
procedure DoDoIt(const aCtx: TtfwContext); override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_Contents_Control_lstExternalObjects_Push
Tkw_Contents_Control_ContentsTree = {final} class(TtfwControlString)
{* Слово словаря для идентификатора контрола ContentsTree
----
*Пример использования*:
[code]контрол::ContentsTree TryFocus ASSERT[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_Contents_Control_ContentsTree
Tkw_Contents_Control_ContentsTree_Push = {final} class(TkwBynameControlPush)
{* Слово словаря для контрола ContentsTree
----
*Пример использования*:
[code]контрол::ContentsTree:push pop:control:SetFocus ASSERT[code] }
protected
procedure DoDoIt(const aCtx: TtfwContext); override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_Contents_Control_ContentsTree_Push
Tkw_Contents_Control_ContextFilter = {final} class(TtfwControlString)
{* Слово словаря для идентификатора контрола ContextFilter
----
*Пример использования*:
[code]контрол::ContextFilter TryFocus ASSERT[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_Contents_Control_ContextFilter
Tkw_Contents_Control_ContextFilter_Push = {final} class(TkwBynameControlPush)
{* Слово словаря для контрола ContextFilter
----
*Пример использования*:
[code]контрол::ContextFilter:push pop:control:SetFocus ASSERT[code] }
protected
procedure DoDoIt(const aCtx: TtfwContext); override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_Contents_Control_ContextFilter_Push
Tkw_Contents_Control_Tasks = {final} class(TtfwControlString)
{* Слово словаря для идентификатора контрола Tasks
----
*Пример использования*:
[code]контрол::Tasks TryFocus ASSERT[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_Contents_Control_Tasks
Tkw_Contents_Control_Tasks_Push = {final} class(TkwBynameControlPush)
{* Слово словаря для контрола Tasks
----
*Пример использования*:
[code]контрол::Tasks:push pop:control:SetFocus ASSERT[code] }
protected
procedure DoDoIt(const aCtx: TtfwContext); override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_Contents_Control_Tasks_Push
function TkwContentsFormBackgroundPanel.BackgroundPanel(const aCtx: TtfwContext;
aContentsForm: TContentsForm): TvtPanel;
{* Реализация слова скрипта .TContentsForm.BackgroundPanel }
begin
Result := aContentsForm.BackgroundPanel;
end;//TkwContentsFormBackgroundPanel.BackgroundPanel
class function TkwContentsFormBackgroundPanel.GetWordNameForRegister: AnsiString;
begin
Result := '.TContentsForm.BackgroundPanel';
end;//TkwContentsFormBackgroundPanel.GetWordNameForRegister
function TkwContentsFormBackgroundPanel.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TvtPanel);
end;//TkwContentsFormBackgroundPanel.GetResultTypeInfo
function TkwContentsFormBackgroundPanel.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwContentsFormBackgroundPanel.GetAllParamsCount
function TkwContentsFormBackgroundPanel.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TContentsForm)]);
end;//TkwContentsFormBackgroundPanel.ParamsTypes
procedure TkwContentsFormBackgroundPanel.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству BackgroundPanel', aCtx);
end;//TkwContentsFormBackgroundPanel.SetValuePrim
procedure TkwContentsFormBackgroundPanel.DoDoIt(const aCtx: TtfwContext);
var l_aContentsForm: TContentsForm;
begin
try
l_aContentsForm := TContentsForm(aCtx.rEngine.PopObjAs(TContentsForm));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aContentsForm: TContentsForm : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(BackgroundPanel(aCtx, l_aContentsForm));
end;//TkwContentsFormBackgroundPanel.DoDoIt
function TkwContentsFormLstBookmarks.lstBookmarks(const aCtx: TtfwContext;
aContentsForm: TContentsForm): TvtLister;
{* Реализация слова скрипта .TContentsForm.lstBookmarks }
begin
Result := aContentsForm.lstBookmarks;
end;//TkwContentsFormLstBookmarks.lstBookmarks
class function TkwContentsFormLstBookmarks.GetWordNameForRegister: AnsiString;
begin
Result := '.TContentsForm.lstBookmarks';
end;//TkwContentsFormLstBookmarks.GetWordNameForRegister
function TkwContentsFormLstBookmarks.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TvtLister);
end;//TkwContentsFormLstBookmarks.GetResultTypeInfo
function TkwContentsFormLstBookmarks.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwContentsFormLstBookmarks.GetAllParamsCount
function TkwContentsFormLstBookmarks.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TContentsForm)]);
end;//TkwContentsFormLstBookmarks.ParamsTypes
procedure TkwContentsFormLstBookmarks.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству lstBookmarks', aCtx);
end;//TkwContentsFormLstBookmarks.SetValuePrim
procedure TkwContentsFormLstBookmarks.DoDoIt(const aCtx: TtfwContext);
var l_aContentsForm: TContentsForm;
begin
try
l_aContentsForm := TContentsForm(aCtx.rEngine.PopObjAs(TContentsForm));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aContentsForm: TContentsForm : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(lstBookmarks(aCtx, l_aContentsForm));
end;//TkwContentsFormLstBookmarks.DoDoIt
function TkwContentsFormLstComments.lstComments(const aCtx: TtfwContext;
aContentsForm: TContentsForm): TvtLister;
{* Реализация слова скрипта .TContentsForm.lstComments }
begin
Result := aContentsForm.lstComments;
end;//TkwContentsFormLstComments.lstComments
class function TkwContentsFormLstComments.GetWordNameForRegister: AnsiString;
begin
Result := '.TContentsForm.lstComments';
end;//TkwContentsFormLstComments.GetWordNameForRegister
function TkwContentsFormLstComments.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TvtLister);
end;//TkwContentsFormLstComments.GetResultTypeInfo
function TkwContentsFormLstComments.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwContentsFormLstComments.GetAllParamsCount
function TkwContentsFormLstComments.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TContentsForm)]);
end;//TkwContentsFormLstComments.ParamsTypes
procedure TkwContentsFormLstComments.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству lstComments', aCtx);
end;//TkwContentsFormLstComments.SetValuePrim
procedure TkwContentsFormLstComments.DoDoIt(const aCtx: TtfwContext);
var l_aContentsForm: TContentsForm;
begin
try
l_aContentsForm := TContentsForm(aCtx.rEngine.PopObjAs(TContentsForm));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aContentsForm: TContentsForm : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(lstComments(aCtx, l_aContentsForm));
end;//TkwContentsFormLstComments.DoDoIt
function TkwContentsFormLstExternalObjects.lstExternalObjects(const aCtx: TtfwContext;
aContentsForm: TContentsForm): TvtLister;
{* Реализация слова скрипта .TContentsForm.lstExternalObjects }
begin
Result := aContentsForm.lstExternalObjects;
end;//TkwContentsFormLstExternalObjects.lstExternalObjects
class function TkwContentsFormLstExternalObjects.GetWordNameForRegister: AnsiString;
begin
Result := '.TContentsForm.lstExternalObjects';
end;//TkwContentsFormLstExternalObjects.GetWordNameForRegister
function TkwContentsFormLstExternalObjects.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TvtLister);
end;//TkwContentsFormLstExternalObjects.GetResultTypeInfo
function TkwContentsFormLstExternalObjects.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwContentsFormLstExternalObjects.GetAllParamsCount
function TkwContentsFormLstExternalObjects.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TContentsForm)]);
end;//TkwContentsFormLstExternalObjects.ParamsTypes
procedure TkwContentsFormLstExternalObjects.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству lstExternalObjects', aCtx);
end;//TkwContentsFormLstExternalObjects.SetValuePrim
procedure TkwContentsFormLstExternalObjects.DoDoIt(const aCtx: TtfwContext);
var l_aContentsForm: TContentsForm;
begin
try
l_aContentsForm := TContentsForm(aCtx.rEngine.PopObjAs(TContentsForm));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aContentsForm: TContentsForm : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(lstExternalObjects(aCtx, l_aContentsForm));
end;//TkwContentsFormLstExternalObjects.DoDoIt
function TkwContentsFormContentsTree.ContentsTree(const aCtx: TtfwContext;
aContentsForm: TContentsForm): TnscTreeViewWithAdapterDragDrop;
{* Реализация слова скрипта .TContentsForm.ContentsTree }
begin
Result := aContentsForm.ContentsTree;
end;//TkwContentsFormContentsTree.ContentsTree
class function TkwContentsFormContentsTree.GetWordNameForRegister: AnsiString;
begin
Result := '.TContentsForm.ContentsTree';
end;//TkwContentsFormContentsTree.GetWordNameForRegister
function TkwContentsFormContentsTree.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TnscTreeViewWithAdapterDragDrop);
end;//TkwContentsFormContentsTree.GetResultTypeInfo
function TkwContentsFormContentsTree.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwContentsFormContentsTree.GetAllParamsCount
function TkwContentsFormContentsTree.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TContentsForm)]);
end;//TkwContentsFormContentsTree.ParamsTypes
procedure TkwContentsFormContentsTree.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству ContentsTree', aCtx);
end;//TkwContentsFormContentsTree.SetValuePrim
procedure TkwContentsFormContentsTree.DoDoIt(const aCtx: TtfwContext);
var l_aContentsForm: TContentsForm;
begin
try
l_aContentsForm := TContentsForm(aCtx.rEngine.PopObjAs(TContentsForm));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aContentsForm: TContentsForm : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(ContentsTree(aCtx, l_aContentsForm));
end;//TkwContentsFormContentsTree.DoDoIt
function TkwContentsFormContextFilter.ContextFilter(const aCtx: TtfwContext;
aContentsForm: TContentsForm): TnscContextFilter;
{* Реализация слова скрипта .TContentsForm.ContextFilter }
begin
Result := aContentsForm.ContextFilter;
end;//TkwContentsFormContextFilter.ContextFilter
class function TkwContentsFormContextFilter.GetWordNameForRegister: AnsiString;
begin
Result := '.TContentsForm.ContextFilter';
end;//TkwContentsFormContextFilter.GetWordNameForRegister
function TkwContentsFormContextFilter.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TnscContextFilter);
end;//TkwContentsFormContextFilter.GetResultTypeInfo
function TkwContentsFormContextFilter.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwContentsFormContextFilter.GetAllParamsCount
function TkwContentsFormContextFilter.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TContentsForm)]);
end;//TkwContentsFormContextFilter.ParamsTypes
procedure TkwContentsFormContextFilter.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству ContextFilter', aCtx);
end;//TkwContentsFormContextFilter.SetValuePrim
procedure TkwContentsFormContextFilter.DoDoIt(const aCtx: TtfwContext);
var l_aContentsForm: TContentsForm;
begin
try
l_aContentsForm := TContentsForm(aCtx.rEngine.PopObjAs(TContentsForm));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aContentsForm: TContentsForm : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(ContextFilter(aCtx, l_aContentsForm));
end;//TkwContentsFormContextFilter.DoDoIt
function TkwContentsFormTasks.Tasks(const aCtx: TtfwContext;
aContentsForm: TContentsForm): TnscTasksPanelView;
{* Реализация слова скрипта .TContentsForm.Tasks }
begin
Result := aContentsForm.Tasks;
end;//TkwContentsFormTasks.Tasks
class function TkwContentsFormTasks.GetWordNameForRegister: AnsiString;
begin
Result := '.TContentsForm.Tasks';
end;//TkwContentsFormTasks.GetWordNameForRegister
function TkwContentsFormTasks.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TnscTasksPanelView);
end;//TkwContentsFormTasks.GetResultTypeInfo
function TkwContentsFormTasks.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwContentsFormTasks.GetAllParamsCount
function TkwContentsFormTasks.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TContentsForm)]);
end;//TkwContentsFormTasks.ParamsTypes
procedure TkwContentsFormTasks.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству Tasks', aCtx);
end;//TkwContentsFormTasks.SetValuePrim
procedure TkwContentsFormTasks.DoDoIt(const aCtx: TtfwContext);
var l_aContentsForm: TContentsForm;
begin
try
l_aContentsForm := TContentsForm(aCtx.rEngine.PopObjAs(TContentsForm));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aContentsForm: TContentsForm : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(Tasks(aCtx, l_aContentsForm));
end;//TkwContentsFormTasks.DoDoIt
function Tkw_Form_Contents.GetString: AnsiString;
begin
Result := 'ContentsForm';
end;//Tkw_Form_Contents.GetString
class procedure Tkw_Form_Contents.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TContentsForm);
end;//Tkw_Form_Contents.RegisterInEngine
class function Tkw_Form_Contents.GetWordNameForRegister: AnsiString;
begin
Result := 'форма::Contents';
end;//Tkw_Form_Contents.GetWordNameForRegister
function Tkw_Contents_Control_BackgroundPanel.GetString: AnsiString;
begin
Result := 'BackgroundPanel';
end;//Tkw_Contents_Control_BackgroundPanel.GetString
class procedure Tkw_Contents_Control_BackgroundPanel.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TvtPanel);
end;//Tkw_Contents_Control_BackgroundPanel.RegisterInEngine
class function Tkw_Contents_Control_BackgroundPanel.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::BackgroundPanel';
end;//Tkw_Contents_Control_BackgroundPanel.GetWordNameForRegister
procedure Tkw_Contents_Control_BackgroundPanel_Push.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushString('BackgroundPanel');
inherited;
end;//Tkw_Contents_Control_BackgroundPanel_Push.DoDoIt
class function Tkw_Contents_Control_BackgroundPanel_Push.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::BackgroundPanel:push';
end;//Tkw_Contents_Control_BackgroundPanel_Push.GetWordNameForRegister
function Tkw_Contents_Control_lstBookmarks.GetString: AnsiString;
begin
Result := 'lstBookmarks';
end;//Tkw_Contents_Control_lstBookmarks.GetString
class procedure Tkw_Contents_Control_lstBookmarks.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TvtLister);
end;//Tkw_Contents_Control_lstBookmarks.RegisterInEngine
class function Tkw_Contents_Control_lstBookmarks.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::lstBookmarks';
end;//Tkw_Contents_Control_lstBookmarks.GetWordNameForRegister
procedure Tkw_Contents_Control_lstBookmarks_Push.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushString('lstBookmarks');
inherited;
end;//Tkw_Contents_Control_lstBookmarks_Push.DoDoIt
class function Tkw_Contents_Control_lstBookmarks_Push.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::lstBookmarks:push';
end;//Tkw_Contents_Control_lstBookmarks_Push.GetWordNameForRegister
function Tkw_Contents_Control_lstComments.GetString: AnsiString;
begin
Result := 'lstComments';
end;//Tkw_Contents_Control_lstComments.GetString
class procedure Tkw_Contents_Control_lstComments.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TvtLister);
end;//Tkw_Contents_Control_lstComments.RegisterInEngine
class function Tkw_Contents_Control_lstComments.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::lstComments';
end;//Tkw_Contents_Control_lstComments.GetWordNameForRegister
procedure Tkw_Contents_Control_lstComments_Push.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushString('lstComments');
inherited;
end;//Tkw_Contents_Control_lstComments_Push.DoDoIt
class function Tkw_Contents_Control_lstComments_Push.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::lstComments:push';
end;//Tkw_Contents_Control_lstComments_Push.GetWordNameForRegister
function Tkw_Contents_Control_lstExternalObjects.GetString: AnsiString;
begin
Result := 'lstExternalObjects';
end;//Tkw_Contents_Control_lstExternalObjects.GetString
class procedure Tkw_Contents_Control_lstExternalObjects.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TvtLister);
end;//Tkw_Contents_Control_lstExternalObjects.RegisterInEngine
class function Tkw_Contents_Control_lstExternalObjects.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::lstExternalObjects';
end;//Tkw_Contents_Control_lstExternalObjects.GetWordNameForRegister
procedure Tkw_Contents_Control_lstExternalObjects_Push.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushString('lstExternalObjects');
inherited;
end;//Tkw_Contents_Control_lstExternalObjects_Push.DoDoIt
class function Tkw_Contents_Control_lstExternalObjects_Push.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::lstExternalObjects:push';
end;//Tkw_Contents_Control_lstExternalObjects_Push.GetWordNameForRegister
function Tkw_Contents_Control_ContentsTree.GetString: AnsiString;
begin
Result := 'ContentsTree';
end;//Tkw_Contents_Control_ContentsTree.GetString
class procedure Tkw_Contents_Control_ContentsTree.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TnscTreeViewWithAdapterDragDrop);
end;//Tkw_Contents_Control_ContentsTree.RegisterInEngine
class function Tkw_Contents_Control_ContentsTree.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::ContentsTree';
end;//Tkw_Contents_Control_ContentsTree.GetWordNameForRegister
procedure Tkw_Contents_Control_ContentsTree_Push.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushString('ContentsTree');
inherited;
end;//Tkw_Contents_Control_ContentsTree_Push.DoDoIt
class function Tkw_Contents_Control_ContentsTree_Push.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::ContentsTree:push';
end;//Tkw_Contents_Control_ContentsTree_Push.GetWordNameForRegister
function Tkw_Contents_Control_ContextFilter.GetString: AnsiString;
begin
Result := 'ContextFilter';
end;//Tkw_Contents_Control_ContextFilter.GetString
class procedure Tkw_Contents_Control_ContextFilter.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TnscContextFilter);
end;//Tkw_Contents_Control_ContextFilter.RegisterInEngine
class function Tkw_Contents_Control_ContextFilter.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::ContextFilter';
end;//Tkw_Contents_Control_ContextFilter.GetWordNameForRegister
procedure Tkw_Contents_Control_ContextFilter_Push.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushString('ContextFilter');
inherited;
end;//Tkw_Contents_Control_ContextFilter_Push.DoDoIt
class function Tkw_Contents_Control_ContextFilter_Push.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::ContextFilter:push';
end;//Tkw_Contents_Control_ContextFilter_Push.GetWordNameForRegister
function Tkw_Contents_Control_Tasks.GetString: AnsiString;
begin
Result := 'Tasks';
end;//Tkw_Contents_Control_Tasks.GetString
class procedure Tkw_Contents_Control_Tasks.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TnscTasksPanelView);
end;//Tkw_Contents_Control_Tasks.RegisterInEngine
class function Tkw_Contents_Control_Tasks.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::Tasks';
end;//Tkw_Contents_Control_Tasks.GetWordNameForRegister
procedure Tkw_Contents_Control_Tasks_Push.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushString('Tasks');
inherited;
end;//Tkw_Contents_Control_Tasks_Push.DoDoIt
class function Tkw_Contents_Control_Tasks_Push.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::Tasks:push';
end;//Tkw_Contents_Control_Tasks_Push.GetWordNameForRegister
initialization
TkwContentsFormBackgroundPanel.RegisterInEngine;
{* Регистрация ContentsForm_BackgroundPanel }
TkwContentsFormLstBookmarks.RegisterInEngine;
{* Регистрация ContentsForm_lstBookmarks }
TkwContentsFormLstComments.RegisterInEngine;
{* Регистрация ContentsForm_lstComments }
TkwContentsFormLstExternalObjects.RegisterInEngine;
{* Регистрация ContentsForm_lstExternalObjects }
TkwContentsFormContentsTree.RegisterInEngine;
{* Регистрация ContentsForm_ContentsTree }
TkwContentsFormContextFilter.RegisterInEngine;
{* Регистрация ContentsForm_ContextFilter }
TkwContentsFormTasks.RegisterInEngine;
{* Регистрация ContentsForm_Tasks }
Tkw_Form_Contents.RegisterInEngine;
{* Регистрация Tkw_Form_Contents }
Tkw_Contents_Control_BackgroundPanel.RegisterInEngine;
{* Регистрация Tkw_Contents_Control_BackgroundPanel }
Tkw_Contents_Control_BackgroundPanel_Push.RegisterInEngine;
{* Регистрация Tkw_Contents_Control_BackgroundPanel_Push }
Tkw_Contents_Control_lstBookmarks.RegisterInEngine;
{* Регистрация Tkw_Contents_Control_lstBookmarks }
Tkw_Contents_Control_lstBookmarks_Push.RegisterInEngine;
{* Регистрация Tkw_Contents_Control_lstBookmarks_Push }
Tkw_Contents_Control_lstComments.RegisterInEngine;
{* Регистрация Tkw_Contents_Control_lstComments }
Tkw_Contents_Control_lstComments_Push.RegisterInEngine;
{* Регистрация Tkw_Contents_Control_lstComments_Push }
Tkw_Contents_Control_lstExternalObjects.RegisterInEngine;
{* Регистрация Tkw_Contents_Control_lstExternalObjects }
Tkw_Contents_Control_lstExternalObjects_Push.RegisterInEngine;
{* Регистрация Tkw_Contents_Control_lstExternalObjects_Push }
Tkw_Contents_Control_ContentsTree.RegisterInEngine;
{* Регистрация Tkw_Contents_Control_ContentsTree }
Tkw_Contents_Control_ContentsTree_Push.RegisterInEngine;
{* Регистрация Tkw_Contents_Control_ContentsTree_Push }
Tkw_Contents_Control_ContextFilter.RegisterInEngine;
{* Регистрация Tkw_Contents_Control_ContextFilter }
Tkw_Contents_Control_ContextFilter_Push.RegisterInEngine;
{* Регистрация Tkw_Contents_Control_ContextFilter_Push }
Tkw_Contents_Control_Tasks.RegisterInEngine;
{* Регистрация Tkw_Contents_Control_Tasks }
Tkw_Contents_Control_Tasks_Push.RegisterInEngine;
{* Регистрация Tkw_Contents_Control_Tasks_Push }
TtfwTypeRegistrator.RegisterType(TypeInfo(TContentsForm));
{* Регистрация типа TContentsForm }
TtfwTypeRegistrator.RegisterType(TypeInfo(TvtPanel));
{* Регистрация типа TvtPanel }
TtfwTypeRegistrator.RegisterType(TypeInfo(TvtLister));
{* Регистрация типа TvtLister }
TtfwTypeRegistrator.RegisterType(TypeInfo(TnscTreeViewWithAdapterDragDrop));
{* Регистрация типа TnscTreeViewWithAdapterDragDrop }
{$If Defined(Nemesis)}
TtfwTypeRegistrator.RegisterType(TypeInfo(TnscContextFilter));
{* Регистрация типа TnscContextFilter }
{$IfEnd} // Defined(Nemesis)
{$If Defined(Nemesis)}
TtfwTypeRegistrator.RegisterType(TypeInfo(TnscTasksPanelView));
{* Регистрация типа TnscTasksPanelView }
{$IfEnd} // Defined(Nemesis)
{$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL)
end.
|
{
Wham Packet implementation
updates:
--------
7th Aug 96 - 23:52 - almost ok...
12th Aug 96 - 12:17 - seems like finished...
4th Sep 96 - 02:32 - Some fixes...
}
unit Wham;
interface
uses
Objects,WTypes;
const
WHAMSign = $4D414857; { wham signature }
wptNormal = 0; { normal mail packet }
wptReply = 1; { reply packet }
wptArchive = 2; { archive packet }
wpfEncrypted = 1; { packet has been encrypted - n/a yet }
type
TWHAMInfo = record
Sign : longint; { wham signature }
Version : byte; { packet version }
PakType : byte; { packet type }
Flags : word; { packet flags }
Netflags : word; { allowed netmail flags }
System : string[39]; { system name which packet has been created on }
SysOp : string[39]; { sysop of system }
Addr : TAddr; { netmail addr of system }
Owner : string[39]; { name of the packet owner }
Alias : string[39]; { alias of packet owner }
ProgName : string[39]; { program which created the packet }
Pad : array[1..294] of byte; {512 bytes}
end;
TWHAMArea = record
Name : string[49];
Number : word;
AreaType : byte;
UserStat : byte;
Flags : word;
Total : word;
Pers : word;
Null : array[1..66] of byte; {padding }
end;
TWHAMIndex = record
From : string[39];
Too : string[39];
Subj : string[79];
Area : word;
Date : longint;
Origin : TAddr;
Dest : TAddr;
Flags : word;
mFlags : byte;
mMarks : byte;
Size : longint;
Where : longint;
Filename : string[12];
Null : array[1..49] of byte; {padding}
end;
PWHAMPacket = ^TWHAMPacket;
TWHAMPacket = object(TMsgPacket)
function Load:boolean;virtual;
function ReadMsgText(amsg:PMsg):PMsgText;virtual;
function GetType:TPakType;virtual;
procedure PostMsg(amsg:PMsg; afile:FnameStr);virtual;
procedure OLC(aarealist:PAreaColl);virtual;
procedure UpdateMsgFlags(amsg:PMsg);virtual;
procedure WriteMsgHeader(amsg:Pmsg; anew:boolean);virtual;
procedure MsgToFile(amsg:Pmsg; afile:FnameStr);virtual;
procedure FileToMsg(afile:FnameStr; amsg:PMsg);virtual;
procedure DeleteMsg(amsg:Pmsg);virtual;
end;
implementation
uses XIO,WProcs,XBuf,XStr,XDebug;
const
infoFile : string[12] = 'Info.W';
indexFile : string[12] = 'Index.W';
textFile : string[12] = 'Text.W';
procedure WHAM2Msg(var wm:TWHAMIndex; var msg:TMsg);
begin
ClearBuf(msg,SizeOf(msg));
with wm do begin
Msg.From := From;
Msg.Too := Too;
Msg.Subj := Subj;
Msg.Addr := Origin;
Msg.Date := Date;
Msg.WHere := Where;
Msg.Length := Size;
Msg.Flags := mFlags;
Msg.Marks := mMarks;
end;
end;
{- TWHAMPacket -}
function TWHAMPacket.Load;
var
T:TDosStream;
rec:TWHAMInfo;
areaRec:TWHAMArea;
msgrec:TWHAMIndex;
Pm:PMsg;
Pa:PArea;
curfti:word;
realPacket:boolean;
function mytest(Ph:PArea):boolean;far;
begin
mytest := Ph^.Number = msgrec.Area;
end;
begin
Load := false;
Config := mpcInfo;
T.Init(Where+infoFile,stOpenRead);
if T.Status <> stOK then begin
Debug('info open error');
T.Done;
exit;
end;
T.Read(rec,SizeOf(rec));
if T.Status <> stOK then begin
Debug('info read error');
T.Done;
exit;
end;
case rec.PakType of
wptReply : Config := Config or mpcCanPost or mpcCanDelete or mpcCanOLC;
wptArchive : Config := Config or mpcCanPost or mpcCanDelete;
end; {case}
if rec.Sign <> WHAMSign then begin
Debug('signature mismatch');
T.Done;
exit;
end;
if rec.Flags and wpfEncrypted > 0 then begin
Debug('encrypted packet - cannot handle this');
T.Done;
exit;
end;
with user do begin
Name := rec.Owner;
Alias := rec.Alias;
SysOp := rec.SysOp;
BBS := rec.System;
Netflags := rec.Netflags;
end;
Debug(user.BBS+' loading');
while T.GetPos < T.GetSize do begin
T.Read(areaRec,SizeOf(areaRec));
if T.Status <> stOK then begin
Debug('area broken');
T.Done;
exit;
end;
New(Pa);
ClearBuf(Pa^,SizeOf(TArea));
with Pa^ do begin
Number := areaRec.Number;
Name := areaRec.Name;
Total := areaRec.Total;
Pers := areaRec.Pers;
Flags := areaRec.Flags;
UserStat := areaRec.UserStat;
AreaType := areaRec.areaType;
EchoTag := 'shit';
end;
arealist^.Insert(Pa);
end;
T.Done;
T.Init(Where+indexFile,stOpenRead);
realPacket := T.Status = stOK;
if realPacket then begin
curfti := 0;
while T.GetPos < T.getSize do begin
T.Read(msgrec,SizeOf(msgrec));
if msgrec.Flags and wmfDeleted = 0 then begin
New(Pm);
WHAM2Msg(msgrec,Pm^);
Pm^.Area := arealist^.FirstThat(@mytest);
if Pm^.Area = NIL then Debug('orphaned message!');
Pm^.FTINum := curfti;
inc(curfti);
msglist^.Insert(Pm);
end else Debug('deleted message encountered');
end;
end;
T.Done;
Load := true;
end;
function TWHAMPacket.ReadMsgText(amsg:PMsg):PMsgText;
var
T:TDosStream;
begin
T.Init(Where+textFile,stOpenRead);
T.Seek(amsg^.Where);
ReadMsgText := stream2Text(T,amsg^.Length);
T.Done;
end;
procedure TWHAMPacket.PostMsg;
var
I,O:TDosStream;
fn:FnameStr;
begin
if Config and mpcCanPost = 0 then exit;
I.Init(afile,stOpenRead);
fn := XGetUniqueName(Where,'.WM');
O.Init(Where+fn,stCreate);
CopyStream(I,O,I.getSize);
I.Done;
O.Done;
amsg^.Filename := fn;
WriteMsgHeader(amsg,true);
end;
procedure GetWHAMInfo(var rec:TWHAMInfo);
begin
ClearBuf(rec,SizeOf(rec));
with rec do begin
Sign := WHAMSign;
Flags := 0;
Netflags := 0;
System := user.BBS;
SysOp := user.SysOp;
Owner := user.Name;
Alias := user.Alias;
ProgName := appName+' '+rVersion;
end;
end;
procedure Reply2WHAM(var rr:TMsg; var wm:TWHAMIndex);
begin
end;
procedure TWHAMPacket.WriteMsgHeader;
var
T:TDosStream;
rec:TWHAMIndex;
h:TWHAMInfo;
begin
if Config and mpcCanPost = 0 then exit;
if not XFileExists(Where+infoFile) then begin
if not anew then Abort('TWHAMPacket.WriteReplyHeader','Inconsistency!');
Debug('creating new infoFile');
GetWHAMInfo(h);
T.Init(Where+infoFile,stCreate);
T.Write(h,SizeOf(h));
T.Done;
T.Init(Where+indexFile,stCreate);
end else T.Init(Where+indexFile,stOpen);
if anew then T.Seek(T.GetSize) else begin
while T.GetPos < T.GetSize do begin
T.Read(rec,SizeOf(rec));
if rec.Filename = amsg^.Filename then begin
T.Seek(T.GetPos-SizeOf(rec));
break;
end;
end;
end;
Reply2WHAM(amsg^,rec);
T.Write(rec,SizeOf(rec));
T.Done;
end;
procedure TWHAMPacket.MsgToFile;
begin
CopyFile(Where+amsg^.Filename,afile);
end;
procedure TWHAMPacket.FileToMsg;
begin
CopyFile(afile,Where+amsg^.Filename);
end;
procedure TWHAMPacket.DeleteMsg;
begin
end;
procedure TWHAMPacket.UpdateMsgFlags;
var
T:TDosStream;
apos:longint;
rec:TWHAMIndex;
begin
T.Init(Where+indexFile,stOpen);
apos := amsg^.FTINum*SizeOf(TWHAMIndex);
T.Seek(apos);
T.Read(rec,SizeOf(rec));
rec.mFlags := amsg^.Flags;
rec.mMarks := amsg^.Marks;
T.Seek(apos);
T.Write(rec,SizeOf(rec));
T.Done;
end;
function TWHAMPacket.GetType;
begin
GetType := pakWHAM;
end;
procedure GetReplyHeader(var hdr:TWHAMInfo);
begin
ClearBuf(hdr,SizeOf(hdr));
with hdr do begin
Sign := WHAMSign;
PakType := wptReply;
Owner := user.Name;
Alias := user.Alias;
ProgName := appName+' v'+rVersion;
end;
end;
procedure Area2WHAM(var a:TArea; var w:TWHAMArea);
begin
ClearBuf(w,SizeOf(w));
with w do begin
Name := a.Name;
Number := a.Number;
AreaType := a.AreaType;
UserStat := a.UserStat;
Flags := a.Flags;
end;
end;
procedure TWHAMPacket.OLC;
var
T:TDosStream;
h:TWHAMInfo;
rec:TWHAMArea;
n:integer;
P:PArea;
begin
T.Init(Where+infoFile,stOpen);
if T.Status <> stOK then begin
T.Init(Where+infoFile,stCreate);
GetReplyHeader(h);
T.Write(h,SizeOf(h));
end else T.Seek(SizeOf(h));
for n:=0 to areaList^.Count-1 do begin
P := areaList^.At(n);
if (P^.AreaType <> watInfo) and (P^.UserStat <> wusNone) then begin
Area2WHAM(P^,rec);
T.Write(rec,SizeOf(rec));
end;
end;
T.Done;
end;
end. |
unit UMetodosGerais;
interface
uses
System.SysUtils, System.Classes, Datasnap.DSServer,
Datasnap.DSAuth, Datasnap.DSProviderDataModuleAdapter, FireDAC.Stan.Intf,
FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf,
FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys,
FireDAC.Phys.FB, FireDAC.Phys.FBDef, FireDAC.VCLUI.Wait, FireDAC.Stan.Param,
FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, Data.DB, FireDAC.Comp.DataSet,
FireDAC.Comp.Client, UUtilServidor, FireDAC.Stan.StorageJSON,
FireDAC.Stan.StorageBin, Data.FireDACJSONReflect, UTipos, System.JSON, DataSetConverter4D.Helper,
DataSetConverter4D.Impl;
type
TMetodosGerais = class(TDSServerModule)
Conexao: TFDConnection;
QrGlobal: TFDQuery;
FDStanStorageBinLink1: TFDStanStorageBinLink;
FDStanStorageJSONLink1: TFDStanStorageJSONLink;
QrCidade: TFDQuery;
QrCidadeCODCID: TIntegerField;
QrCidadeNOMCID: TStringField;
QrCidadeESTCID: TStringField;
QrCidadeCEPCID: TStringField;
QrCidadeCODMUN: TStringField;
QrCidadeCODEST: TIntegerField;
QrCidadeDISTRITO: TIntegerField;
QrCidadeUF: TFDQuery;
private
{ Private declarations }
public
{ Public declarations }
function GetIDFromTable(TableName: String): Integer;
function CidadeUF(ID: integer; Fields, Filtro: String): TFDJsonDataSets;
function CidadeUFJSON(ID: integer; Fields, Filtro: String): TJSONArray;
function Cidade(ID: Integer; Recurso, Fields, Filtro: String): TFDJsonDataSets;
function CidadeJSON(ID: Integer; Recurso, Fields, Filtro: String): TJsonArray;
function UpdateCidadeApplyUpdates(ADeltaList: TFDJSONDeltas): TResult;
function UpdateCidadeJSONApplyUpdates(const key: string; jObject: TJSONObject): TResult;
function cancelCidade(const key: String): TResult;
end;
implementation
uses
System.StrUtils;
{%CLASSGROUP 'Vcl.Controls.TControl'}
{$R *.dfm}
{ TMetodosGerais }
function TMetodosGerais.cancelCidade(const key: String): TResult;
begin
result:=TResult.Create();
result.ReturnCode :=0;
Try
UUtilServidor.executaSQL(QrGlobal,'DELETE FROM CIDADE WHERE CODCID='+Key);
result.Valor:='OK';
Except on E:Exception Do
Begin
result.ErrorMessage:=E.Message;
result.ReturnCode:=-1;
End;
End;
end;
function TMetodosGerais.Cidade(ID: Integer; Recurso, Fields,
Filtro: String): TFDJsonDataSets;
var
xSql: String;
begin
Fields := ifThen(Trim(Fields)='','*',Fields);
Recurso := ifThen(Trim(Recurso)='','Basico',Recurso);
Filtro := ifThen(((Trim(Filtro)='0') or (Trim(Filtro)='')),'',' and '+Filtro);
if ID<>0 then
xSql:=' and c.ID='+ID.ToString();
xSql:='SELECT '+Fields+' from'
+' CIDADE c'
+' WHERE 1=1'
+xSql
+Filtro;
pesquisa(QrGlobal,xSql,true);
result:=TFDJSONDataSets.Create;
TFDJSONDataSetsWriter.ListAdd(result, QrGlobal);
end;
function TMetodosGerais.CidadeJSON(ID: Integer; Recurso, Fields,
Filtro: String): TJsonArray;
var
xSql: String;
begin
Fields := ifThen(Trim(Fields)='','*',Fields);
Recurso := ifThen(Trim(Recurso)='','Basico',Recurso);
Filtro := ifThen(((Trim(Filtro)='0') or (Trim(Filtro)='')),'',' and '+Filtro);
if ID<>0 then
xSql:=' and c.CODCID='+ID.ToString();
xSql:='SELECT '+Fields+' from'
+' CIDADE c'
+' WHERE 1=1'
+xSql
+Filtro;
pesquisa(QrGlobal,xSql,true);
result:=QrGlobal.AsJSONArray;
{FxSql:='Select NomCid, EstCID, CepCid from CIDADE where CodCid='+CodCid;
pesquisa(FDM.CDSAux);
if FDM.CDSAux.IsEmpty then
Begin
Application.MessageBox('Cidade não encontrada!','Aviso',mb_Ok+mb_IconWarning);
Result:='';
End
ELse
Result:=FDM.CDSAux.FieldByName('NomCid').AsString+' -'+FDM.CDSAux.FieldByName('ESTCid').AsString+ '|'+StringReplace(FDM.CDSAux.FieldByName('CepCid').AsString,'-','',[rfreplaceALL]);}
end;
function TMetodosGerais.CidadeUF(ID: integer; Fields,
Filtro: String): TFDJsonDataSets;
var
xSql: String;
begin
Fields := ifThen(Trim(Fields)='','*',Fields);
Filtro := ifThen(Trim(Filtro)='0','',Filtro);
if ID<>0 then
xSql:=' and c.ID='+ID.ToString();
xSql:='SELECT '+Fields+' from'
+' CIDADE_UF c'
+' WHERE 1=1'
+xSql
+Filtro;
pesquisa(QrGlobal,xSql,true);
result:=TFDJSONDataSets.Create;
TFDJSONDataSetsWriter.ListAdd(result, QrGlobal);
end;
function TMetodosGerais.CidadeUFJSON(ID: integer; Fields,
Filtro: String): TJSONArray;
var
xSql: String;
begin
Fields := ifThen(Trim(Fields)='','*',Fields);
Filtro := ifThen(Trim(Filtro)='0','',Filtro);
if ID<>0 then
xSql:=' and c.ID='+ID.ToString();
xSql:='SELECT '+Fields+' from'
+' CIDADE_UF c'
+' WHERE 1=1'
+xSql
+Filtro;
pesquisa(QrGlobal,xSql,true);
result:=QrGlobal.AsJSONArray;
end;
function TMetodosGerais.GetIDFromTable(TableName: String): Integer;
begin
pesquisa(QrGlobal,'SELECT GEN_ID(GEN_'+TableName+'_ID ,1) FROM RDB$DATABASE',True);
result:=QrGlobal.Fields[0].AsInteger;
end;
function TMetodosGerais.UpdateCidadeApplyUpdates(
ADeltaList: TFDJSONDeltas): TResult;
var
LApply: IFDJSONDeltasApplyUpdatesMax;
ErrorsCount: Integer;
ErrorsMessage: String;
begin
result:=TResult.Create();
result.ReturnCode :=0;
ErrorsCount :=0;
Try
LApply := TFDJSONDeltasApplyUpdatesMax.Create(ADeltaList);
LApply.ApplyUpdates('CIDADE', QrCidade.Command, 0);
ErrorsCount :=ErrorsCount+LApply.Errors.Count;
ErrorsMessage :=ErrorsMessage+LApply.Errors.Strings.Text+#13;
if ErrorsCount>0 then
raise Exception.Create(ErrorsMessage);
Except
End;
if ErrorsCount = 0 then
result.Valor:=LApply.ValueByName['CIDADE'].FieldByName('CODCID').AsString
else
Begin
result.ErrorMessage:=ErrorsMessage;
result.ReturnCode:=-1;
End;
end;
function TMetodosGerais.UpdateCidadeJSONApplyUpdates(const key: string;
jObject: TJSONObject): TResult;
var
ErrorsCount: Integer;
ErrorsMessage: String;
begin
result:=TResult.Create();
result.ReturnCode :=0;
ErrorsCount :=0;
Try
QrCidade.Params[0].Clear();
QrCidade.Params[0].Value:=key;
QrCidade.Open();
if QrCidade.RecordCount>=1 then
QrCidade.RecordFromJSONObject(jObject)
else
QrCidade.FromJSONObject(jObject);
QrCidade.ApplyUpdates(0);
result.Valor:=QrCidade.FieldByName('CODCID').AsString;
Except on E:Exception Do
Begin
result.ErrorMessage:=E.Message;
result.ReturnCode:=-1;
End;
End;
end;
end.
|
{$include lem_directives.inc}
unit LemDosAnimationSet;
interface
uses
Classes, SysUtils,
UMisc, GR32,
LemCore,
LemTypes,
LemDosStructures,
LemDosCmp,
LemDosBmp,
LemMetaAnimation,
LemAnimationSet;
const
LTR = False;
RTL = True;
const
{-------------------------------------------------------------------------------
dos animations ordered by their appearance in main.dat
the constants below show the exact order
-------------------------------------------------------------------------------}
WALKING = 0;
JUMPING = 1;
WALKING_RTL = 2;
JUMPING_RTL = 3;
DIGGING = 4;
CLIMBING = 5;
CLIMBING_RTL = 6;
DROWNING = 7;
HOISTING = 8;
HOISTING_RTL = 9;
BRICKLAYING = 10;
BRICKLAYING_RTL = 11;
BASHING = 12;
BASHING_RTL = 13;
MINING = 14;
MINING_RTL = 15;
FALLING = 16;
FALLING_RTL = 17;
UMBRELLA = 18;
UMBRELLA_RTL = 19;
SPLATTING = 20;
EXITING = 21;
FRIED = 22;
BLOCKING = 23;
SHRUGGING = 24;
SHRUGGING_RTL = 25;
OHNOING = 26;
EXPLOSION = 27;
AnimationIndices : array[TBasicLemmingAction, LTR..RTL] of Integer = (
(0,0),
(WALKING, WALKING_RTL), // baWalk,
(JUMPING, JUMPING_RTL), // baJumping,
(DIGGING, DIGGING), // baDigging,
(CLIMBING, CLIMBING_RTL), // baClimbing,
(DROWNING, DROWNING), // baDrowning,
(HOISTING, HOISTING_RTL), // baHoisting,
(BRICKLAYING, BRICKLAYING_RTL), // baBricklaying,
(BASHING, BASHING_RTL), // baBashing,
(MINING, MINING_RTL), // baMining,
(FALLING, FALLING_RTL), // baFalling,
(UMBRELLA, UMBRELLA_RTL), // baUmbrella,
(SPLATTING, SPLATTING), // baSplatting,
(EXITING, EXITING), // baExiting,
(FRIED, FRIED), // baFried,
(BLOCKING, BLOCKING), // baBlocking,
(SHRUGGING, SHRUGGING_RTL), // baShrugging,
(OHNOING, OHNOING), // baOhnoing,
(EXPLOSION, EXPLOSION) // baExploding
);
type
{-------------------------------------------------------------------------------
Basic animationset for dos.
-------------------------------------------------------------------------------}
TBaseDosAnimationSet = class(TBaseAnimationSet)
private
fMainDataFile : string;
fAnimationPalette : TArrayOfColor32;
fExplosionMaskBitmap : TBitmap32;
fBashMasksBitmap : TBitmap32;
fBashMasksRTLBitmap : TBitmap32;
fMineMasksBitmap : TBitmap32;
fMineMasksRTLBitmap : TBitmap32;
fCountDownDigitsBitmap : TBitmap32;
protected
procedure DoReadMetaData; override;
procedure DoReadData; override;
procedure DoClearData; override;
public
constructor Create; override;
{ easy references, these point to the MaskAnimations[0..5] }
property ExplosionMaskBitmap : TBitmap32 read fExplosionMaskBitmap;
property BashMasksBitmap : TBitmap32 read fBashMasksBitmap;
property BashMasksRTLBitmap : TBitmap32 read fBashMasksRTLBitmap;
property MineMasksBitmap : TBitmap32 read fMineMasksBitmap;
property MineMasksRTLBitmap : TBitmap32 read fMineMasksRTLBitmap;
property CountDownDigitsBitmap : TBitmap32 read fCountDownDigitsBitmap;
property AnimationPalette: TArrayOfColor32 read fAnimationPalette write fAnimationPalette;
published
property MainDataFile: string read fMainDataFile write fMainDataFile; // must be set by style
end;
implementation
{ TBaseDosAnimationSet }
procedure TBaseDosAnimationSet.DoReadMetaData;
{-------------------------------------------------------------------------------
We dont have to read. It's fixed in this order in the main.dat.
foot positions from ccexpore's emails, see lemming_mechanics pseudo code
o make lemming animations
o make mask animations metadata
-------------------------------------------------------------------------------}
procedure Lem(aImageLocation: Integer; const aDescription: string;
aFrameCount, aWidth, aHeight, aBPP, aFootX, aFootY, aAnimType: Integer);
begin
with fMetaLemmingAnimations.Add do
begin
ImageLocation := aImageLocation;
Description := aDescription;
FrameCount := aFrameCount;
Width := aWidth;
Height := aHeight;
BitsPerPixel := aBPP;
FootX := aFootX;
FootY := aFootY;
AnimationType := aAnimType;
end;
end;
procedure Msk(aImageLocation: Integer; const aDescription: string;
aFrameCount, aWidth, aHeight, aBPP: Integer);
begin
with fMetaMaskAnimations.Add do
begin
ImageLocation := aImageLocation;
Description := aDescription;
FrameCount := aFrameCount;
Width := aWidth;
Height := aHeight;
BitsPerPixel := aBPP;
end;
end;
begin
// place description F W H BPP FX FY animationtype
Lem($0000, 'Walking' , 8, 16, 10, 2, 8, 10, lat_Loop); // 0
Lem($0140, 'Jumping' , 1, 16, 10, 2, 8, 10, lat_Once);
Lem($0168, 'Walking (rtl)' , 8, 16, 10, 2, 8, 10, lat_Loop);
Lem($02A8, 'Jumping (rtl)' , 1, 16, 10, 2, 8, 10, lat_Once);
Lem($02D0, 'Digging' , 16, 16, 14, 3, 8, 12, lat_Loop);
Lem($0810, 'Climbing' , 8, 16, 12, 2, 8, 12, lat_Loop);
Lem($0990, 'Climbing (rtl)' , 8, 16, 12, 2, 8, 12, lat_Loop);
Lem($0B10, 'Drowning' , 16, 16, 10, 2, 8, 10, lat_Once);
Lem($0D90, 'Hoisting' , 8, 16, 12, 2, 8, 12, lat_Once);
Lem($0F10, 'Hoisting (rtl)' , 8, 16, 12, 2, 8, 12, lat_Once);
Lem($1090, 'Building' , 16, 16, 13, 3, 8, 13, lat_Loop); // 10
Lem($1570, 'Building (rtl)' , 16, 16, 13, 3, 8, 13, lat_Loop);
Lem($1A50, 'Bashing' , 32, 16, 10, 3, 8, 10, lat_Loop);
Lem($21D0, 'Bashing (rtl)' , 32, 16, 10, 3, 8, 10, lat_Loop);
Lem($2950, 'Mining' , 24, 16, 13, 3, 8, 13, lat_Loop);
Lem($30A0, 'Mining (rtl)' , 24, 16, 13, 3, 8, 13, lat_Loop);
Lem($37F0, 'Falling' , 4, 16, 10, 2, 8, 10, lat_Loop);
Lem($3890, 'Falling (rtl)' , 4, 16, 10, 2, 8, 10, lat_Loop);
Lem($3930, 'Umbrella' , 8, 16, 16, 3, 8, 16, lat_Loop);
Lem($3C30, 'Umbrella (rtl)' , 8, 16, 16, 3, 8, 16, lat_Loop);
Lem($3F30, 'Splatting' , 16, 16, 10, 2, 8, 10, lat_Once); // 20
Lem($41B0, 'Exiting' , 8, 16, 13, 2, 8, 13, lat_Once);
Lem($4350, 'Vaporizing' , 14, 16, 14, 4, 8, 14, lat_Once);
Lem($4970, 'Blocking' , 16, 16, 10, 2, 8, 10, lat_Loop);
Lem($4BF0, 'Shrugging' , 8, 16, 10, 2, 8, 10, lat_Once);
Lem($4D30, 'Shrugging (rtl)' , 8, 16, 10, 2, 8, 10, lat_Once);
Lem($4E70, 'Oh-No-ing' , 16, 16, 10, 2, 8, 10, lat_Once);
Lem($50F0, 'Exploding' , 1, 32, 32, 3, 16, 25, lat_Once);
// place description F W H BPP
Msk($0000, 'Bashmasks' , 4, 16, 10, 1);
Msk($0050, 'Bashmasks (rtl)' , 4, 16, 10, 1);
Msk($00A0, 'Minemasks' , 2, 16, 13, 1);
Msk($00D4, 'Minemasks (rtl)' , 2, 16, 13, 1);
Msk($0108, 'Explosionmask' , 1, 16, 22, 1);
Msk($0154, 'Countdown digits' , 5, 8, 8, 1); // we only take the digits 5 downto zero
end;
procedure TBaseDosAnimationSet.DoReadData;
var
Fn: string;
Mem: TMemoryStream;
Bmp: TBitmap32;
// MaskBitmap: TBitmap32;
TempBitmap: TBitmap32;
Sections: TDosDatSectionList;
Decompressor: TDosDatDecompressor;
iAnimation, iFrame: Integer;
Planar: TDosPlanarBitmap;
MLA: TMetaLemmingAnimation;
MA: TMetaAnimation;
{X, }Y: Integer;
Pal: TArrayOfColor32;
LocalStream: TStream;
begin
// fried and or vaporizing has high color indices
Assert(Length(AnimationPalette) >= 16);
Pal := Copy(fAnimationPalette);
// ensure metadata
Fn := MainDataFile;//Sty.IncludeCommonPath(Sty.MainDataFile);
Planar := TDosPlanarBitmap.Create;
TempBitmap := TBitmap32.Create;
Sections := TDosDatSectionList.Create;
Decompressor := TDosDatDecompressor.Create;
try
{$ifdef external}if FileExists(Fn) then
LocalStream := TFileStream.Create(Fn, fmOpenRead)
else{$endif}
LocalStream := CreateDataStream(Fn, ldtLemmings);
try
Decompressor.LoadSectionList(LocalStream, Sections, False);
finally
LocalStream.Free;
end;
Decompressor.DecompressSection(Sections[0].CompressedData, Sections[0].DecompressedData);
Mem := Sections[0].DecompressedData;
// windlg('load animations');
with fMetaLemmingAnimations{.HackedList} do
for iAnimation := 0 to Count - 1 do
begin
//Y := 0;
MLA := fMetaLemmingAnimations[ianimation];//List^[iAnimation];
// with MLA do
begin
Bmp := TBitmap32.Create;
fLemmingAnimations.Add(Bmp);
Planar.LoadAnimationFromStream(Mem, Bmp, MLA.ImageLocation,
MLA.Width, MLA.Height, MLA.FrameCount, MLA.BitsPerPixel, Pal);
(*
Bmp.SetSize(MLA.Width, MLA.Height * MLA.FrameCount);
Bmp.Clear(0);
fLemmingAnimations.Add(Bmp);
Mem.Seek(MLA.ImageLocation, soFromBeginning);
for iFrame := 0 to MLA.FrameCount - 1 do
begin
Planar.LoadFromStream(Mem, TempBitmap, -1, MLA.Width, MLA.Height, MLA.BitsPerPixel, Pal);
TempBitmap.DrawTo(Bmp, 0, Y);
Inc(Y, MLA.Height);
end;
//ReplaceColor(Bmp, clBRICK, BrickColor);
{$ifdef develop}
Bmp.SaveToFile('d:\temp\'+'anim_'+leadzerostr(ianimation, 2) + '.bmp');
{$endif}
*)
end;
end;
Pal[0] := 0;
Pal[1] := clMask32; // the ugly pink.
Decompressor.DecompressSection(Sections[1].CompressedData, Sections[1].DecompressedData);
Mem := Sections[1].DecompressedData;
with fMetaMaskAnimations.HackedList do
for iAnimation := 0 to Count - 1 do
begin
Y := 0;
MA := List^[iAnimation];
with MA do
begin
Bmp := TBitmap32.Create;
Bmp.Width := Width;
Bmp.Height := FrameCount * Height;
Bmp.Clear(0);
fMaskAnimations.Add(Bmp);
Mem.Seek(ImageLocation, soFromBeginning);
for iFrame := 0 to FrameCount - 1 do
begin
Planar.LoadFromStream(Mem, TempBitmap, -1, Width, Height, BitsPerPixel, Pal);
TempBitmap.DrawTo(Bmp, 0, Y);
Inc(Y, Height);
end;
//ReplaceColor(Bmp, clBRICK, BrickColor);
//ifdef develop}
//Bmp.SaveToFile('d:\temp\'+'mask_'+ i2s(ianimation) + '.bmp');
//endif}
end;
end;
// refer the "easy access" bitmaps
fBashMasksBitmap := fMaskAnimations[0];
fBashMasksRTLBitmap := fMaskAnimations[1];
fMineMasksBitmap := fMaskAnimations[2];
fMineMasksRTLBitmap := fMaskAnimations[3];
fExplosionMaskBitmap := fMaskAnimations[4];
fCountDownDigitsBitmap := fMaskAnimations[5];
ReplaceColor(fCountDownDigitsBitmap, clMask32, Pal[3]);
finally
// LocalStream.Free;
Sections.Free;
Decompressor.Free;
Planar.Free;
TempBitmap.Free;
end;
end;
procedure TBaseDosAnimationSet.DoClearData;
begin
fLemmingAnimations.Clear;
fMaskAnimations.Clear;
fExplosionMaskBitmap := nil;
fBashMasksBitmap := nil;
fBashMasksRTLBitmap := nil;
fMineMasksBitmap := nil;
fMineMasksRTLBitmap := nil;
fCountDownDigitsBitmap := nil;
end;
constructor TBaseDosAnimationSet.Create;
begin
inherited Create;
//fAnimationPalette := DosInLevelPalette;
end;
end.
|
unit GlassVoiceLaunchUnit1;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, System.Sensors,
FMX.StdCtrls, FMX.Sensors, FMX.Objects, FMX.Ani, Generics.Collections;
type
TForm2 = class(TForm)
StyleBook1: TStyleBook;
MotionSensor1: TMotionSensor;
LineActive: TLine;
LabelX: TLabel;
LabelZ: TLabel;
LineReference: TLine;
FloatAnimationX: TFloatAnimation;
FloatAnimationZ: TFloatAnimation;
procedure MotionSensor1DataChanged(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FloatAnimationXFinish(Sender: TObject);
procedure FloatAnimationZFinish(Sender: TObject);
private
{ Private declarations }
FXSample: TList<Single>;
FZSample: TList<Single>;
const SampleCount = 20;
procedure UpdateZ;
procedure UpdateX;
public
{ Public declarations }
end;
var
Form2: TForm2;
implementation
{$R *.fmx}
function Average(collection: TList<Single>): Single;
var
sample: Single;
begin
result := 0;
for sample in collection do
begin
result := result + sample;
end;
result := result / collection.Count;
end;
procedure TForm2.FloatAnimationXFinish(Sender: TObject);
begin
UpdateX;
end;
procedure TForm2.FloatAnimationZFinish(Sender: TObject);
begin
UpdateZ;
end;
procedure TForm2.FormCreate(Sender: TObject);
var
Test: TList<Integer>;
begin
FXSample := TList<Single>.Create;
FZSample := TList<Single>.Create;
end;
procedure TForm2.UpdateX();
var
x: Single;
begin
if not FloatAnimationX.Running then
begin
x := Average(FXSample);
FXSample.Clear;
LabelX.Text := Format('L/R: %6.2f ', [X]);
FloatAnimationX.Enabled := False;
FloatAnimationX.StopValue := X * 9;
FloatAnimationX.Enabled := True;
end;
end;
procedure TForm2.UpdateZ;
var
z: Single;
begin
if not FloatAnimationZ.Running then
begin
z := Average(FZSample);
FZSample.Clear;
LabelZ.Text := Format('U/D: %6.2f ', [Z]);
FloatAnimationZ.Enabled := False;
FloatAnimationZ.StopValue := LineReference.Position.Y + (Z * (Height div -10));
FloatAnimationZ.Enabled := True;
end;
end;
procedure TForm2.MotionSensor1DataChanged(Sender: TObject);
var
LProp: TCustomMotionSensor.TProperty;
x, z: Single;
begin
for LProp in MotionSensor1.Sensor.AvailableProperties do
begin
{ get the data from the sensor }
case LProp of
TCustomMotionSensor.TProperty.AccelerationX:
begin
x := MotionSensor1.Sensor.AccelerationX;
end;
TCustomMotionSensor.TProperty.AngleAccelX:
begin
x := MotionSensor1.Sensor.AngleAccelX;
end;
TCustomMotionSensor.TProperty.AccelerationZ:
begin
z := MotionSensor1.Sensor.AccelerationZ;
end;
TCustomMotionSensor.TProperty.AngleAccelZ:
begin
z := MotionSensor1.Sensor.AngleAccelZ;
end;
end;
end;
FXSample.Add(X);
FZSample.Add(Z);
end;
end.
|
unit m3DBProxyWriteStream;
{* Поток, пишущий в базу }
// Модуль: "w:\common\components\rtl\Garant\m3\m3DBProxyWriteStream.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "Tm3DBProxyWriteStream" MUID: (49BFC520008A)
{$Include w:\common\components\rtl\Garant\m3\m3Define.inc}
interface
uses
l3IntfUses
, m3DBProxyStream
, l3Interfaces
;
type
Tm3DBProxyWriteStream = class(Tm3DBProxyStream, Il3Rollback)
{* Поток, пишущий в базу }
private
f_NeedCommit: Boolean;
{* Сохранять ли изменения }
protected
function pm_GetIsNewVersion: Boolean; virtual;
procedure Rollback;
{* Откатить данные }
procedure InitFields; override;
procedure BeforeRelease; override;
public
property IsNewVersion: Boolean
read pm_GetIsNewVersion;
{* Новая версия документа }
end;//Tm3DBProxyWriteStream
implementation
uses
l3ImplUses
, SysUtils
, l3Base
//#UC START# *49BFC520008Aimpl_uses*
//#UC END# *49BFC520008Aimpl_uses*
;
function Tm3DBProxyWriteStream.pm_GetIsNewVersion: Boolean;
//#UC START# *49BFE6600304_49BFC520008Aget_var*
//#UC END# *49BFE6600304_49BFC520008Aget_var*
begin
//#UC START# *49BFE6600304_49BFC520008Aget_impl*
Result := false;
//#UC END# *49BFE6600304_49BFC520008Aget_impl*
end;//Tm3DBProxyWriteStream.pm_GetIsNewVersion
procedure Tm3DBProxyWriteStream.Rollback;
{* Откатить данные }
//#UC START# *49C1040A0256_49BFC520008A_var*
//#UC END# *49C1040A0256_49BFC520008A_var*
begin
//#UC START# *49C1040A0256_49BFC520008A_impl*
f_NeedCommit := false;
//#UC END# *49C1040A0256_49BFC520008A_impl*
end;//Tm3DBProxyWriteStream.Rollback
procedure Tm3DBProxyWriteStream.InitFields;
//#UC START# *47A042E100E2_49BFC520008A_var*
//#UC END# *47A042E100E2_49BFC520008A_var*
begin
//#UC START# *47A042E100E2_49BFC520008A_impl*
inherited;
f_NeedCommit := true;
//#UC END# *47A042E100E2_49BFC520008A_impl*
end;//Tm3DBProxyWriteStream.InitFields
procedure Tm3DBProxyWriteStream.BeforeRelease;
//#UC START# *49BFC98902FF_49BFC520008A_var*
//#UC END# *49BFC98902FF_49BFC520008A_var*
begin
//#UC START# *49BFC98902FF_49BFC520008A_impl*
if f_NeedCommit then
try
if DB.IsExclusive then
// - иначе нам не дадут записать новый поток
// как например в случае с Tm3SimpleDB в режиме MakeExclusive
CloseInner;
DB.Commit(Self);
except
on E: Exception do
begin
f_NeedCommit := false;
l3System.Exception2Log(E);
end;//on E: Exception
end//try..except
else
DB.Revert(Self);
inherited;
//#UC END# *49BFC98902FF_49BFC520008A_impl*
end;//Tm3DBProxyWriteStream.BeforeRelease
end.
|
unit jackal_hw;
interface
uses {$IFDEF WINDOWS}windows,{$ENDIF}
m6809,main_engine,controls_engine,gfx_engine,ym_2151,rom_engine,
pal_engine,sound_engine;
function iniciar_jackal:boolean;
implementation
const
jackal_rom:array[0..1] of tipo_roms=(
(n:'j-v02.rom';l:$10000;p:$0;crc:$0b7e0584),(n:'j-v03.rom';l:$4000;p:$10000;crc:$3e0dfb83));
jackal_chars:array[0..3] of tipo_roms=(
(n:'631t04.bin';l:$20000;p:0;crc:$457f42f0),(n:'631t05.bin';l:$20000;p:$1;crc:$732b3fc1),
(n:'631t06.bin';l:$20000;p:$40000;crc:$2d10e56e),(n:'631t07.bin';l:$20000;p:$40001;crc:$4961c397));
jackal_sound:tipo_roms=(n:'631t01.bin';l:$8000;p:$8000;crc:$b189af6a);
jackal_proms:array[0..1] of tipo_roms=(
(n:'631r08.bpr';l:$100;p:0;crc:$7553a172),(n:'631r09.bpr';l:$100;p:$100;crc:$a74dd86c));
//Dip
jackal_dip_a:array [0..2] of def_dip=(
(mask:$0f;name:'Coin A';number:16;dip:((dip_val:$2;dip_name:'4C 1C'),(dip_val:$5;dip_name:'3C 1C'),(dip_val:$8;dip_name:'2C 1C'),(dip_val:$4;dip_name:'3C 2C'),(dip_val:$1;dip_name:'4C 3C'),(dip_val:$f;dip_name:'1C 1C'),(dip_val:$3;dip_name:'3C 4C'),(dip_val:$7;dip_name:'2C 3C'),(dip_val:$e;dip_name:'1C 2C'),(dip_val:$6;dip_name:'2C 5C'),(dip_val:$d;dip_name:'1C 3C'),(dip_val:$c;dip_name:'1C 4C'),(dip_val:$b;dip_name:'1C 5C'),(dip_val:$a;dip_name:'1C 6C'),(dip_val:$9;dip_name:'1C 7C'),(dip_val:$0;dip_name:'Free Play'))),
(mask:$f0;name:'Coin B';number:15;dip:((dip_val:$20;dip_name:'4C 1C'),(dip_val:$50;dip_name:'3C 1C'),(dip_val:$80;dip_name:'2C 1C'),(dip_val:$40;dip_name:'3C 2C'),(dip_val:$10;dip_name:'4C 3C'),(dip_val:$f0;dip_name:'1C 1C'),(dip_val:$30;dip_name:'3C 4C'),(dip_val:$70;dip_name:'2C 3C'),(dip_val:$e0;dip_name:'1C 2C'),(dip_val:$60;dip_name:'2C 5C'),(dip_val:$d0;dip_name:'1C 3C'),(dip_val:$c0;dip_name:'1C 4C'),(dip_val:$b0;dip_name:'1C 5C'),(dip_val:$a0;dip_name:'1C 6C'),(dip_val:$90;dip_name:'1C 7C'),(dip_val:$0;dip_name:'No Coin B'))),());
jackal_dip_b:array [0..4] of def_dip=(
(mask:$3;name:'Lives';number:4;dip:((dip_val:$3;dip_name:'2'),(dip_val:$2;dip_name:'3'),(dip_val:$1;dip_name:'4'),(dip_val:$0;dip_name:'7'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$18;name:'Bonus Life';number:4;dip:((dip_val:$18;dip_name:'30K 150K'),(dip_val:$10;dip_name:'50K 200K'),(dip_val:$8;dip_name:'30K'),(dip_val:$0;dip_name:'50K'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$60;name:'Difficulty';number:4;dip:((dip_val:$60;dip_name:'Easy'),(dip_val:$40;dip_name:'Normal'),(dip_val:$20;dip_name:'Difficult'),(dip_val:$0;dip_name:'Very Difficult'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$80;name:'Demo Sounds';number:2;dip:((dip_val:$80;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),());
jackal_dip_c:array [0..3] of def_dip=(
(mask:$20;name:'Flip Screen';number:2;dip:((dip_val:$20;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$40;name:'Sound Adjustment';number:2;dip:((dip_val:$0;dip_name:'Upright'),(dip_val:$40;dip_name:'Cocktail'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$80;name:'Sound Mode';number:2;dip:((dip_val:$80;dip_name:'Mono'),(dip_val:$0;dip_name:'Stereo'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),());
var
memoria_rom:array[0..1,0..$7fff] of byte;
memoria_zram:array[0..1,0..$3f] of word;
memoria_sprite,memoria_voram:array[0..1,0..$fff] of byte;
banco,scroll_x,scroll_y,scroll_crt,sprite_crt,ram_bank,sprite_bank:byte;
irq_enable:boolean;
procedure update_video_jackal;
procedure draw_sprites(bank:byte;pos:word);
var
sn1,sn2,attr,a,b,c,d,flipx_v,flipy_v:byte;
flipx,flipy:boolean;
nchar,color,x,y:word;
begin
sn1:=memoria_sprite[bank,pos];
sn2:=memoria_sprite[bank,pos+1];
attr:=memoria_sprite[bank,pos+4];
x:=240-(memoria_sprite[bank,pos+2]);
y:=memoria_sprite[bank,pos+3]+((attr and 1) shl 8);
flipy:=(attr and $20)<>0;
flipx:=(attr and $40)<>0;
flipy_v:=(attr and $20) shr 1;
flipx_v:=(attr and $40) shr 2;
color:=(sn2 and $f0)+(bank*$100);
if (attr and $c)<>0 then begin // half-size sprite
nchar:=(sn1*4+((sn2 and (8+4)) shr 2)+((sn2 and (2+1)) shl 10))+(bank*4096);
case (attr and $c) of
$04:begin
put_gfx_sprite_diff(nchar,color,flipx,flipy,1,8,0);
put_gfx_sprite_diff(nchar+1,color,flipx,flipy,1,8,8);
actualiza_gfx_sprite_size(x,y,2,16,16);
end;
$08:begin
put_gfx_sprite_diff(nchar,color,flipx,flipy,1,0,0);
put_gfx_sprite_diff(nchar-2,color,flipx,flipy,1,8,0);
actualiza_gfx_sprite_size(x,y,2,16,8);
end;
$0c:begin
put_gfx_sprite(nchar,color,flipx,flipy,1);
actualiza_gfx_sprite(x+8,y,2,1);
end;
end;
end else begin
nchar:=(sn1+((sn2 and $03) shl 8))+(bank*1024);
if (attr and $10)<>0 then begin
a:=16 xor flipx_v;
b:=0 xor flipx_v;
c:=0 xor flipy_v;
d:=16 xor flipy_v;
put_gfx_sprite_diff(nchar,color,flipx,flipy,2,a,c);
put_gfx_sprite_diff(nchar+1,color,flipx,flipy,2,a,d);
put_gfx_sprite_diff(nchar+2,color,flipx,flipy,2,b,c);
put_gfx_sprite_diff(nchar+3,color,flipx,flipy,2,b,d);
actualiza_gfx_sprite_size(x-16,y,2,32,32);
end else begin
put_gfx_sprite(nchar,color,flipx,flipy,2);
actualiza_gfx_sprite(x,y,2,2);
end;
end;
end;
var
x,y,f,nchar:word;
atrib:byte;
begin
//background
for f:=$0 to $3ff do begin
if gfx[0].buffer[f] then begin
x:=31-(f div 32);
y:=f mod 32;
atrib:=memoria_voram[ram_bank,f];
nchar:=memoria_voram[ram_bank,$400+f]+((atrib and $c0) shl 2)+((atrib and $30) shl 6);
put_gfx_flip(x*8,y*8,nchar,0,1,0,(atrib and $20)<>0,(atrib and $10)<>0);
gfx[0].buffer[f]:=false;
end;
end;
//scroll de varios tipos...
if (scroll_crt and $2)<>0 then begin
//horizontal 8 lineas independientes
//eje X
if (scroll_crt and $4)<>0 then scroll__x_part2(1,2,8,@memoria_zram[ram_bank]);
//Eje Y
if (scroll_crt and $8)<>0 then scroll__y_part2(1,2,8,@memoria_zram[ram_bank]);
end else begin
//Scroll total
scroll_x_y(1,2,scroll_x,scroll_y);
end;
//sprites
for f:=0 to 48 do draw_sprites(1,(sprite_crt and $8)*$100+f*5);
for f:=0 to $ff do draw_sprites(0,(sprite_crt and $8)*$100+f*5);
actualiza_trozo_final(16,8,224,240,2);
end;
procedure eventos_jackal;
begin
if event.arcade then begin
//P1
if arcade_input.left[0] then marcade.in1:=(marcade.in1 and $fe) else marcade.in1:=(marcade.in1 or $1);
if arcade_input.right[0] then marcade.in1:=(marcade.in1 and $fd) else marcade.in1:=(marcade.in1 or $2);
if arcade_input.up[0] then marcade.in1:=(marcade.in1 and $fb) else marcade.in1:=(marcade.in1 or $4);
if arcade_input.down[0] then marcade.in1:=(marcade.in1 and $f7) else marcade.in1:=(marcade.in1 or $8);
if arcade_input.but1[0] then marcade.in1:=(marcade.in1 and $ef) else marcade.in1:=(marcade.in1 or $10);
if arcade_input.but0[0] then marcade.in1:=(marcade.in1 and $df) else marcade.in1:=(marcade.in1 or $20);
//P2
if arcade_input.left[1] then marcade.in2:=(marcade.in2 and $fe) else marcade.in2:=(marcade.in2 or $1);
if arcade_input.right[1] then marcade.in2:=(marcade.in2 and $fd) else marcade.in2:=(marcade.in2 or $2);
if arcade_input.up[1] then marcade.in2:=(marcade.in2 and $fb) else marcade.in2:=(marcade.in2 or $4);
if arcade_input.down[1] then marcade.in2:=(marcade.in2 and $f7) else marcade.in2:=(marcade.in2 or $8);
if arcade_input.but1[1] then marcade.in2:=(marcade.in2 and $ef) else marcade.in2:=(marcade.in2 or $10);
if arcade_input.but0[1] then marcade.in2:=(marcade.in2 and $df) else marcade.in2:=(marcade.in2 or $20);
//SYSTEM
if arcade_input.coin[0] then marcade.in0:=(marcade.in0 and $fe) else marcade.in0:=(marcade.in0 or 1);
if arcade_input.coin[1] then marcade.in0:=(marcade.in0 and $fd) else marcade.in0:=(marcade.in0 or 2);
if arcade_input.start[0] then marcade.in0:=(marcade.in0 and $f7) else marcade.in0:=(marcade.in0 or $8);
if arcade_input.start[1] then marcade.in0:=(marcade.in0 and $ef) else marcade.in0:=(marcade.in0 or $10);
end;
end;
procedure jackal_principal;
var
frame_m,frame_s:single;
f:byte;
begin
init_controls(false,false,false,true);
frame_m:=m6809_0.tframes;
frame_s:=m6809_1.tframes;
while EmuStatus=EsRuning do begin
for f:=0 to 255 do begin
m6809_0.run(frame_m);
frame_m:=frame_m+m6809_0.tframes-m6809_0.contador;
m6809_1.run(frame_s);
frame_s:=frame_s+m6809_1.tframes-m6809_1.contador;
if f=239 then begin
if irq_enable then begin
m6809_0.change_irq(HOLD_LINE);
m6809_1.change_nmi(PULSE_LINE);
end;
update_video_jackal;
end;
end;
eventos_jackal;
video_sync;
end;
end;
function jackal_getbyte(direccion:word):byte;
begin
case direccion of
$10:jackal_getbyte:=marcade.dswa; //dsw1
$11:jackal_getbyte:=marcade.in1;
$12:jackal_getbyte:=marcade.in2;
$13:jackal_getbyte:=marcade.in0+marcade.dswc;
$14,$15:; //Torreta
$18:jackal_getbyte:=marcade.dswb; //dsw2
$20..$5f:jackal_getbyte:=255-memoria_zram[ram_bank,direccion-$20];
$60..$1fff,$c000..$ffff:jackal_getbyte:=memoria[direccion];
$2000..$2fff:jackal_getbyte:=memoria_voram[ram_bank,direccion and $fff];
$3000..$3fff:jackal_getbyte:=memoria_sprite[sprite_bank,direccion and $fff];
$4000..$bfff:jackal_getbyte:=memoria_rom[banco,direccion-$4000];
end;
end;
procedure jackal_putbyte(direccion:word;valor:byte);
begin
case direccion of
$0:scroll_x:=not(valor);
$1:scroll_y:=valor;
$2:scroll_crt:=valor;
$3:sprite_crt:=valor;
$4:begin
irq_enable:=(valor and $2)<>0;
main_screen.flip_main_screen:=(valor and $8)<>0;
end;
$1c:begin
banco:=(valor and $20) shr 5;
ram_bank:=(valor and $10) shr 4;
sprite_bank:=(valor and $8) shr 3;
end;
$20..$5f:memoria_zram[ram_bank,direccion-$20]:=255-valor;
$60..$1fff:memoria[direccion]:=valor;
$2000..$2fff:if memoria_voram[ram_bank,direccion and $fff]<>valor then begin
memoria_voram[ram_bank,direccion and $fff]:=valor;
gfx[0].buffer[direccion and $3ff]:=true;
end;
$3000..$3fff:memoria_sprite[sprite_bank,direccion and $fff]:=valor;
$4000..$ffff:; //ROM
end;
end;
function sound_getbyte(direccion:word):byte;
begin
case direccion of
$2001:sound_getbyte:=ym2151_0.status;
$4000..$43ff:sound_getbyte:=buffer_paleta[direccion and $3ff];
$6000..$7fff:sound_getbyte:=memoria[direccion and $1fff];
$8000..$ffff:sound_getbyte:=mem_snd[direccion];
end;
end;
procedure sound_putbyte(direccion:word;valor:byte);
procedure cambiar_color(dir:word);
var
data:word;
color:tcolor;
begin
data:=buffer_paleta[dir]+(buffer_paleta[dir+1] shl 8);
color.r:=pal5bit(data);
color.g:=pal5bit(data shr 5);
color.b:=pal5bit(data shr 10);
dir:=dir shr 1;
set_pal_color(color,dir);
//Si el color es de los chars, reseteo todo el buffer, al tener 8 bits de profundidad de
//color no cambia en cuando lo pinta
if ((dir>$ff) and (dir<$200)) then fillchar(gfx[0].buffer,$400,1);
end;
begin
case direccion of
$2000:ym2151_0.reg(valor);
$2001:ym2151_0.write(valor);
$4000..$43ff:if buffer_paleta[direccion and $3ff]<>valor then begin
buffer_paleta[direccion and $3ff]:=valor;
cambiar_color(direccion and $3fe);
end;
$6000..$7fff:memoria[direccion and $1fff]:=valor;
$8000..$ffff:; //ROM
end;
end;
procedure sound_instruccion;
begin
ym2151_0.update;
end;
//Main
procedure reset_jackal;
begin
m6809_0.reset;
m6809_1.reset;
ym2151_0.reset;
reset_audio;
marcade.in0:=$1f;
marcade.in1:=$ff;
marcade.in2:=$ff;
irq_enable:=false;
ram_bank:=0;
sprite_bank:=0;
scroll_x:=0;
scroll_y:=0;
scroll_crt:=0;
sprite_crt:=0;
end;
function iniciar_jackal:boolean;
var
f:word;
memoria_temp:array[0..$7ffff] of byte;
const
ps_x:array[0..15] of dword=(0*4, 1*4, 2*4, 3*4, 4*4, 5*4, 6*4, 7*4,
32*8+0*4, 32*8+1*4, 32*8+2*4, 32*8+3*4, 32*8+4*4, 32*8+5*4, 32*8+6*4, 32*8+7*4);
ps_y:array[0..15] of dword=(0*32, 1*32, 2*32, 3*32, 4*32, 5*32, 6*32, 7*32,
16*32, 17*32, 18*32, 19*32, 20*32, 21*32, 22*32, 23*32);
begin
llamadas_maquina.bucle_general:=jackal_principal;
llamadas_maquina.reset:=reset_jackal;
iniciar_jackal:=false;
iniciar_audio(true);
//Pantallas
screen_init(1,256,256);
screen_mod_scroll(1,256,256,255,256,256,255);
screen_init(2,256,512,false,true);
iniciar_video(224,240);
//Main CPU
m6809_0:=cpu_m6809.Create(18432000 div 12,256,TCPU_MC6809E);
m6809_0.change_ram_calls(jackal_getbyte,jackal_putbyte);
//Sound CPU
m6809_1:=cpu_m6809.Create(18432000 div 12,256,TCPU_MC6809E);
m6809_1.change_ram_calls(sound_getbyte,sound_putbyte);
m6809_1.init_sound(sound_instruccion);
//Audio chips
ym2151_0:=ym2151_Chip.create(3579545,0.5);
//cargar roms
if not(roms_load(@memoria_temp,jackal_rom)) then exit;
//Pongo las ROMs en su banco
copymemory(@memoria[$c000],@memoria_temp[$10000],$4000);
copymemory(@memoria_rom[0,0],@memoria_temp[0],$8000);
copymemory(@memoria_rom[1,0],@memoria_temp[$8000],$8000);
//Cargar Sound
if not(roms_load(@mem_snd,jackal_sound)) then exit;
//convertir chars
if not(roms_load16b(@memoria_temp,jackal_chars)) then exit;
init_gfx(0,8,8,4096);
gfx_set_desc_data(8,0,32*8,0,1,2,3,$40000*8+0,$40000*8+1,$40000*8+2,$40000*8+3);
convert_gfx(0,0,@memoria_temp,@ps_x,@ps_y,true,false);
//sprites
init_gfx(1,8,8,4096*2);
gfx[1].trans[0]:=true;
gfx_set_desc_data(4,2,32*8,0,1,2,3);
convert_gfx(1,0,@memoria_temp[$20000],@ps_x,@ps_y,true,false);
convert_gfx(1,4096*8*8,@memoria_temp[$60000],@ps_x,@ps_y,true,false);
//sprites x2
init_gfx(2,16,16,1024*2);
gfx[2].trans[0]:=true;
gfx_set_desc_data(4,2,32*32,0,1,2,3);
convert_gfx(2,0,@memoria_temp[$20000],@ps_x,@ps_y,true,false);
convert_gfx(2,1024*16*16,@memoria_temp[$60000],@ps_x,@ps_y,true,false);
//Color lookup chars
for f:=0 to $ff do gfx[0].colores[f]:=f or $100;
//Color lookup sprites
if not(roms_load(@memoria_temp,jackal_proms)) then exit;
//0..$ff --> banco 0 --> valor
//$100..$1ff --> banco 1 --> valor+$10
for f:=$0 to $1ff do gfx[1].colores[f]:=memoria_temp[f] and $0f+((f shr 8)*$10);
//sprites x2
copymemory(@gfx[2].colores,@gfx[1].colores,$200*2);
//DIP
marcade.dswa:=$ff;
marcade.dswb:=$5f;
marcade.dswc:=$20;
marcade.dswa_val:=@jackal_dip_a;
marcade.dswb_val:=@jackal_dip_b;
marcade.dswc_val:=@jackal_dip_c;
//final
reset_jackal;
iniciar_jackal:=true;
end;
end.
|
{ ***************************************************************************
Copyright (c) 2016-2020 Kike Pérez
Unit : Quick.HttpServer.Types
Description : Http Server Types
Author : Kike Pérez
Version : 1.8
Created : 30/08/2019
Modified : 26/03/2020
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.HttpServer.Types;
{$i QuickLib.inc}
interface
uses
SysUtils,
Generics.Collections;
type
EControlledException = class(Exception)
private
fCallerClass : TClass;
public
constructor Create(aCaller : TObject; const aMessage : string);
property CallerClass : TClass read fCallerClass write fCallerClass;
end;
TController = class(TInterfacedObject);
TControllerClass = class of TController;
TMethodVerb = (mUNKNOWN, mGET, mHEAD, mPOST, mPUT, mDELETE, mOPTIONS, mTRACE, mPATCH);
TMethodVerbs = set of TMethodVerb;
THttpStatusCode = (Accepted = 202,
Ambiguous = 300,
BadGateway = 502,
BadRequest = 400,
Conflict = 409,
Continue = 100,
Created = 201,
ExpectationFailed = 417,
Forbidden = 403,
Found = 302,
GatewayTimeout = 504,
Gone = 410,
HttpVersionNotSupported = 505,
InternalServerError = 500,
LengthRequired = 411,
MethodNotAllowed = 405,
Moved = 301,
MovedPermanently = 301,
MultipleChoices = 300,
NoContent = 204,
NonAuthoritativeInformation = 203,
NotAcceptable = 406,
NotFound = 404,
NotImplemented = 501,
NotModified = 304,
OK = 200,
PartialContent = 206,
PaymentRequired = 402,
PreconditionFailed = 412,
ProxyAuthenticationRequired = 407,
Redirect = 302,
RedirectKeepVerb = 307,
RedirectMethod = 303,
RequestedRangeNotSatisfiable = 416,
RequestEntityTooLarge = 413,
RequestTimeout = 408,
RequestUriTooLong = 414,
ResetContent = 205,
SeeOther = 303,
ServiceUnavailable = 503,
SwitchingProtocols = 101,
TemporaryRedirect = 307,
Unauthorized = 401,
UnsupportedMediaType = 415,
Unused = 306,
UpgradeRequired = 426,
UseProxy = 305);
TMIMETypes = class
private
fMIMEList : TDictionary<string,string>;
procedure FillMIME;
public
constructor Create;
destructor Destroy; override;
function GetExtensionMIMEType(const aExtension : string) : string;
function GetFileMIMEType(const aFilename : string) : string;
procedure AddMIME(const aExtension, aMIMEType : string);
end;
var
MIMETypes : TMIMETypes;
const
MethodVerbStr: array[0..Ord(High(TMethodVerb))] of string = ('UNKNOWN','HEAD','GET','POST','PUT','DELETE','OPTIONS','TRACE','PATCH');
implementation
procedure TMIMETypes.AddMIME(const aExtension, aMIMEType: string);
begin
if not fMIMEList.ContainsKey(aExtension.ToLower) then fMIMEList.Add(aExtension.ToLower,aMIMEType.ToLower);
end;
constructor TMIMETypes.Create;
begin
fMIMEList := TDictionary<string,string>.Create(375);
FillMIME;
end;
destructor TMIMETypes.Destroy;
begin
fMIMEList.Free;
inherited;
end;
procedure TMIMETypes.FillMIME;
begin
{ Animation }
fMIMEList.Add('.nml','animation/narrative');
{ Audio }
fMIMEList.Add('.aac','audio/mp4');
fMIMEList.Add('.aif','audio/x-aiff');
fMIMEList.Add('.aifc','audio/x-aiff');
fMIMEList.Add('.aiff','audio/x-aiff');
fMIMEList.Add('.au','audio/basic');
fMIMEList.Add('.gsm','audio/x-gsm');
fMIMEList.Add('.kar','audio/midi');
fMIMEList.Add('.m3u','audio/mpegurl');
fMIMEList.Add('.m4a','audio/x-mpg');
fMIMEList.Add('.mid','audio/midi');
fMIMEList.Add('.midi','audio/midi');
fMIMEList.Add('.mpega','audio/x-mpg');
fMIMEList.Add('.mp2','audio/x-mpg');
fMIMEList.Add('.mp3','audio/x-mpg');
fMIMEList.Add('.mpga','audio/x-mpg');
fMIMEList.Add('.pls','audio/x-scpls');
fMIMEList.Add('.qcp','audio/vnd.qcelp');
fMIMEList.Add('.ra','audio/x-realaudio');
fMIMEList.Add('.ram','audio/x-pn-realaudio');
fMIMEList.Add('.rm','audio/x-pn-realaudio');
fMIMEList.Add('.sd2','audio/x-sd2');
fMIMEList.Add('.sid','audio/prs.sid');
fMIMEList.Add('.snd','audio/basic');
fMIMEList.Add('.wav','audio/x-wav');
fMIMEList.Add('.wax','audio/x-ms-wax');
fMIMEList.Add('.wma','audio/x-ms-wma');
fMIMEList.Add('.mjf','audio/x-vnd.AudioExplosion.MjuiceMediaFile');
{ Image }
fMIMEList.Add('.art','image/x-jg');
fMIMEList.Add('.bmp','image/bmp');
fMIMEList.Add('.cdr','image/x-coreldraw');
fMIMEList.Add('.cdt','image/x-coreldrawtemplate');
fMIMEList.Add('.cpt','image/x-corelphotopaint');
fMIMEList.Add('.djv','image/vnd.djvu');
fMIMEList.Add('.djvu','image/vnd.djvu');
fMIMEList.Add('.gif','image/gif');
fMIMEList.Add('.ief','image/ief');
fMIMEList.Add('.ico','image/x-icon');
fMIMEList.Add('.jng','image/x-jng');
fMIMEList.Add('.jpg','image/jpeg');
fMIMEList.Add('.jpeg','image/jpeg');
fMIMEList.Add('.jpe','image/jpeg');
fMIMEList.Add('.pat','image/x-coreldrawpattern');
fMIMEList.Add('.pcx','image/pcx');
fMIMEList.Add('.pbm','image/x-portable-bitmap');
fMIMEList.Add('.pgm','image/x-portable-graymap');
fMIMEList.Add('.pict','image/x-pict');
fMIMEList.Add('.png','image/x-png');
fMIMEList.Add('.pnm','image/x-portable-anymap');
fMIMEList.Add('.pntg','image/x-macpaint');
fMIMEList.Add('.ppm','image/x-portable-pixmap');
fMIMEList.Add('.psd','image/x-psd');
fMIMEList.Add('.qtif','image/x-quicktime');
fMIMEList.Add('.ras','image/x-cmu-raster');
fMIMEList.Add('.rf','image/vnd.rn-realflash');
fMIMEList.Add('.rgb','image/x-rgb');
fMIMEList.Add('.rp','image/vnd.rn-realpix');
fMIMEList.Add('.sgi','image/x-sgi');
fMIMEList.Add('.svg','image/svg+xml');
fMIMEList.Add('.svgz','image/svg+xml');
fMIMEList.Add('.targa','image/x-targa');
fMIMEList.Add('.tif','image/x-tiff');
fMIMEList.Add('.webp','image/webp');
fMIMEList.Add('.xbm','image/xbm');
fMIMEList.Add('.xpm','image/x-xpixmap');
fMIMEList.Add('.xwd','image/x-xwindowdump');
{ Text }
fMIMEList.Add('.323','text/h323');
fMIMEList.Add('.xml','text/xml');
fMIMEList.Add('.uls','text/iuls');
fMIMEList.Add('.txt','text/plain');
fMIMEList.Add('.rtx','text/richtext');
fMIMEList.Add('.wsc','text/scriptlet');
fMIMEList.Add('.rt','text/vnd.rn-realtext');
fMIMEList.Add('.htt','text/webviewhtml');
fMIMEList.Add('.htc','text/x-component');
fMIMEList.Add('.vcf','text/x-vcard');
{ Video }
fMIMEList.Add('.asf','video/x-ms-asf');
fMIMEList.Add('.asx','video/x-ms-asf');
fMIMEList.Add('.avi','video/x-msvideo');
fMIMEList.Add('.dl','video/dl');
fMIMEList.Add('.dv','video/dv');
fMIMEList.Add('.flc','video/flc');
fMIMEList.Add('.fli','video/fli');
fMIMEList.Add('.gl','video/gl');
fMIMEList.Add('.lsf','video/x-la-asf');
fMIMEList.Add('.lsx','video/x-la-asf');
fMIMEList.Add('.mng','video/x-mng');
fMIMEList.Add('.mp4','video/mpeg');
fMIMEList.Add('.mpeg','video/x-mpeg2a');
fMIMEList.Add('.mpa','video/mpeg');
fMIMEList.Add('.mpe','video/mpeg');
fMIMEList.Add('.mpg','video/mpeg');
fMIMEList.Add('.ogv','video/ogg');
fMIMEList.Add('.moov','video/quicktime');
fMIMEList.Add('.mov','video/quicktime');
fMIMEList.Add('.mxu','video/vnd.mpegurl');
fMIMEList.Add('.qt','video/quicktime');
fMIMEList.Add('.qtc','video/x-qtc');
fMIMEList.Add('.rv','video/vnd.rn-realvideo');
fMIMEList.Add('.ivf','video/x-ivf');
fMIMEList.Add('.webm','video/webm');
fMIMEList.Add('.wm','video/x-ms-wm');
fMIMEList.Add('.wmp','video/x-ms-wmp');
fMIMEList.Add('.wmv','video/x-ms-wmv');
fMIMEList.Add('.wmx','video/x-ms-wmx');
fMIMEList.Add('.wvx','video/x-ms-wvx');
fMIMEList.Add('.rms','video/vnd.rn-realvideo-secure');
fMIMEList.Add('.movie','video/x-sgi-movie');
{ Application }
fMIMEList.Add('.7z','application/x-7z-compressed');
fMIMEList.Add('.a','application/x-archive');
fMIMEList.Add('.aab','application/x-authorware-bin');
fMIMEList.Add('.aam','application/x-authorware-map');
fMIMEList.Add('.aas','application/x-authorware-seg');
fMIMEList.Add('.abw','application/x-abiword');
fMIMEList.Add('.ace','application/x-ace-compressed');
fMIMEList.Add('.ai','application/postscript');
fMIMEList.Add('.alz','application/x-alz-compressed');
fMIMEList.Add('.ani','application/x-navi-animation');
fMIMEList.Add('.arj','application/x-arj');
fMIMEList.Add('.bat','application/x-msdos-program');
fMIMEList.Add('.bcpio','application/x-bcpio');
fMIMEList.Add('.boz','application/x-bzip2');
fMIMEList.Add('.bz','application/x-bzip');
fMIMEList.Add('.bz2','application/x-bzip2');
fMIMEList.Add('.cab','application/vnd.ms-cab-compressed');
fMIMEList.Add('.cat','application/vnd.ms-pki.seccat');
fMIMEList.Add('.ccn','application/x-cnc');
fMIMEList.Add('.cco','application/x-cocoa');
fMIMEList.Add('.cdf','application/x-cdf');
fMIMEList.Add('.cer','application/x-x509-ca-cert');
fMIMEList.Add('.chm','application/vnd.ms-htmlhelp');
fMIMEList.Add('.chrt','application/vnd.kde.kchart');
fMIMEList.Add('.cil','application/vnd.ms-artgalry');
fMIMEList.Add('.class','application/java-vm');
fMIMEList.Add('.com','application/x-msdos-program');
fMIMEList.Add('.clp','application/x-msclip');
fMIMEList.Add('.cpio','application/x-cpio');
fMIMEList.Add('.cqk','application/x-calquick');
fMIMEList.Add('.crd','application/x-mscardfile');
fMIMEList.Add('.crl','application/pkix-crl');
fMIMEList.Add('.csh','application/x-csh');
fMIMEList.Add('.dar','application/x-dar');
fMIMEList.Add('.dbf','application/x-dbase');
fMIMEList.Add('.dcr','application/x-director');
fMIMEList.Add('.deb','application/x-debian-package');
fMIMEList.Add('.dir','application/x-director');
fMIMEList.Add('.dist','vnd.apple.installer+xml');
fMIMEList.Add('.distz','vnd.apple.installer+xml');
fMIMEList.Add('.dll','application/x-msdos-program');
fMIMEList.Add('.dmg','application/x-apple-diskimage');
fMIMEList.Add('.doc','application/msword');
fMIMEList.Add('.dot','application/msword');
fMIMEList.Add('.dvi','application/x-dvi');
fMIMEList.Add('.dxr','application/x-director');
fMIMEList.Add('.ebk','application/x-expandedbook');
fMIMEList.Add('.eps','application/postscript');
fMIMEList.Add('.evy','application/envoy');
fMIMEList.Add('.exe','application/x-msdos-program');
fMIMEList.Add('.fdf','application/vnd.fdf');
fMIMEList.Add('.fif','application/fractals');
fMIMEList.Add('.flm','application/vnd.kde.kivio');
fMIMEList.Add('.fml','application/x-file-mirror-list');
fMIMEList.Add('.gzip','application/x-gzip');
fMIMEList.Add('.gnumeric','application/x-gnumeric');
fMIMEList.Add('.gtar','application/x-gtar');
fMIMEList.Add('.gz','application/x-gzip');
fMIMEList.Add('.hdf','application/x-hdf');
fMIMEList.Add('.hlp','application/winhlp');
fMIMEList.Add('.hpf','application/x-icq-hpf');
fMIMEList.Add('.hqx','application/mac-binhex40');
fMIMEList.Add('.hta','application/hta');
fMIMEList.Add('.ims','application/vnd.ms-ims');
fMIMEList.Add('.ins','application/x-internet-signup');
fMIMEList.Add('.iii','application/x-iphone');
fMIMEList.Add('.iso','application/x-iso9660-image');
fMIMEList.Add('.jar','application/java-archive');
fMIMEList.Add('.karbon','application/vnd.kde.karbon');
fMIMEList.Add('.kfo','application/vnd.kde.kformula');
fMIMEList.Add('.kon','application/vnd.kde.kontour');
fMIMEList.Add('.kpr','application/vnd.kde.kpresenter');
fMIMEList.Add('.kpt','application/vnd.kde.kpresenter');
fMIMEList.Add('.kwd','application/vnd.kde.kword');
fMIMEList.Add('.kwt','application/vnd.kde.kword');
fMIMEList.Add('.latex','application/x-latex');
fMIMEList.Add('.lha','application/x-lzh');
fMIMEList.Add('.lcc','application/fastman');
fMIMEList.Add('.lrm','application/vnd.ms-lrm');
fMIMEList.Add('.lz','application/x-lzip');
fMIMEList.Add('.lzh','application/x-lzh');
fMIMEList.Add('.lzma','application/x-lzma');
fMIMEList.Add('.lzo','application/x-lzop');
fMIMEList.Add('.lzx','application/x-lzx');
fMIMEList.Add('.m13','application/x-msmediaview');
fMIMEList.Add('.m14','application/x-msmediaview');
fMIMEList.Add('.mpp','application/vnd.ms-project');
fMIMEList.Add('.mvb','application/x-msmediaview');
fMIMEList.Add('.man','application/x-troff-man');
fMIMEList.Add('.mdb','application/x-msaccess');
fMIMEList.Add('.me','application/x-troff-me');
fMIMEList.Add('.ms','application/x-troff-ms');
fMIMEList.Add('.msi','application/x-msi');
fMIMEList.Add('.mpkg','vnd.apple.installer+xml');
fMIMEList.Add('.mny','application/x-msmoney');
fMIMEList.Add('.nix','application/x-mix-transfer');
fMIMEList.Add('.o','application/x-object');
fMIMEList.Add('.oda','application/oda');
fMIMEList.Add('.odb','application/vnd.oasis.opendocument.database');
fMIMEList.Add('.odc','application/vnd.oasis.opendocument.chart');
fMIMEList.Add('.odf','application/vnd.oasis.opendocument.formula');
fMIMEList.Add('.odg','application/vnd.oasis.opendocument.graphics');
fMIMEList.Add('.odi','application/vnd.oasis.opendocument.image');
fMIMEList.Add('.odm','application/vnd.oasis.opendocument.text-master');
fMIMEList.Add('.odp','application/vnd.oasis.opendocument.presentation');
fMIMEList.Add('.ods','application/vnd.oasis.opendocument.spreadsheet');
fMIMEList.Add('.ogg','application/ogg');
fMIMEList.Add('.odt','application/vnd.oasis.opendocument.text');
fMIMEList.Add('.otg','application/vnd.oasis.opendocument.graphics-template');
fMIMEList.Add('.oth','application/vnd.oasis.opendocument.text-web');
fMIMEList.Add('.otp','application/vnd.oasis.opendocument.presentation-template');
fMIMEList.Add('.ots','application/vnd.oasis.opendocument.spreadsheet-template');
fMIMEList.Add('.ott','application/vnd.oasis.opendocument.text-template');
fMIMEList.Add('.p10','application/pkcs10');
fMIMEList.Add('.p12','application/x-pkcs12');
fMIMEList.Add('.p7b','application/x-pkcs7-certificates');
fMIMEList.Add('.p7m','application/pkcs7-mime');
fMIMEList.Add('.p7r','application/x-pkcs7-certreqresp');
fMIMEList.Add('.p7s','application/pkcs7-signature');
fMIMEList.Add('.package','application/vnd.autopackage');
fMIMEList.Add('.pfr','application/font-tdpfr');
fMIMEList.Add('.pkg','vnd.apple.installer+xml');
fMIMEList.Add('.pdf','application/pdf');
fMIMEList.Add('.pko','application/vnd.ms-pki.pko');
fMIMEList.Add('.pl','application/x-perl');
fMIMEList.Add('.pnq','application/x-icq-pnq');
fMIMEList.Add('.pot','application/mspowerpoint');
fMIMEList.Add('.pps','application/mspowerpoint');
fMIMEList.Add('.ppt','application/mspowerpoint');
fMIMEList.Add('.ppz','application/mspowerpoint');
fMIMEList.Add('.ps','application/postscript');
fMIMEList.Add('.pub','application/x-mspublisher');
fMIMEList.Add('.qpw','application/x-quattropro');
fMIMEList.Add('.qtl','application/x-quicktimeplayer');
fMIMEList.Add('.rar','application/rar');
fMIMEList.Add('.rjs','application/vnd.rn-realsystem-rjs');
fMIMEList.Add('.rmf','application/vnd.rmf');
fMIMEList.Add('.rmp','application/vnd.rn-rn_music_package');
fMIMEList.Add('.rmx','application/vnd.rn-realsystem-rmx');
fMIMEList.Add('.rnx','application/vnd.rn-realplayer');
fMIMEList.Add('.rpm','application/x-redhat-package-manager');
fMIMEList.Add('.rsml','application/vnd.rn-rsml');
fMIMEList.Add('.rtsp','application/x-rtsp');
fMIMEList.Add('.scm','application/x-icq-scm');
fMIMEList.Add('.ser','application/java-serialized-object');
fMIMEList.Add('.scd','application/x-msschedule');
fMIMEList.Add('.sda','application/vnd.stardivision.draw');
fMIMEList.Add('.sdc','application/vnd.stardivision.calc');
fMIMEList.Add('.sdd','application/vnd.stardivision.impress');
fMIMEList.Add('.sdp','application/x-sdp');
fMIMEList.Add('.setpay','application/set-payment-initiation');
fMIMEList.Add('.setreg','application/set-registration-initiation');
fMIMEList.Add('.sh','application/x-sh');
fMIMEList.Add('.shar','application/x-shar');
fMIMEList.Add('.shw','application/presentations');
fMIMEList.Add('.sit','application/x-stuffit');
fMIMEList.Add('.sitx','application/x-stuffitx');
fMIMEList.Add('.skd','application/x-koan');
fMIMEList.Add('.skm','application/x-koan');
fMIMEList.Add('.skp','application/x-koan');
fMIMEList.Add('.skt','application/x-koan');
fMIMEList.Add('.smf','application/vnd.stardivision.math');
fMIMEList.Add('.smi','application/smil');
fMIMEList.Add('.smil','application/smil');
fMIMEList.Add('.spl','application/futuresplash');
fMIMEList.Add('.ssm','application/streamingmedia');
fMIMEList.Add('.sst','application/vnd.ms-pki.certstore');
fMIMEList.Add('.stc','application/vnd.sun.xml.calc.template');
fMIMEList.Add('.std','application/vnd.sun.xml.draw.template');
fMIMEList.Add('.sti','application/vnd.sun.xml.impress.template');
fMIMEList.Add('.stl','application/vnd.ms-pki.stl');
fMIMEList.Add('.stw','application/vnd.sun.xml.writer.template');
fMIMEList.Add('.svi','application/softvision');
fMIMEList.Add('.sv4cpio','application/x-sv4cpio');
fMIMEList.Add('.sv4crc','application/x-sv4crc');
fMIMEList.Add('.swf','application/x-shockwave-flash');
fMIMEList.Add('.swf1','application/x-shockwave-flash');
fMIMEList.Add('.sxc','application/vnd.sun.xml.calc');
fMIMEList.Add('.sxi','application/vnd.sun.xml.impress');
fMIMEList.Add('.sxm','application/vnd.sun.xml.math');
fMIMEList.Add('.sxw','application/vnd.sun.xml.writer');
fMIMEList.Add('.sxg','application/vnd.sun.xml.writer.global');
fMIMEList.Add('.t','application/x-troff');
fMIMEList.Add('.tar','application/x-tar');
fMIMEList.Add('.tcl','application/x-tcl');
fMIMEList.Add('.tex','application/x-tex');
fMIMEList.Add('.texi','application/x-texinfo');
fMIMEList.Add('.texinfo','application/x-texinfo');
fMIMEList.Add('.tbz','application/x-bzip-compressed-tar');
fMIMEList.Add('.tbz2','application/x-bzip-compressed-tar');
fMIMEList.Add('.tgz','application/x-compressed-tar');
fMIMEList.Add('.tlz','application/x-lzma-compressed-tar');
fMIMEList.Add('.tr','application/x-troff');
fMIMEList.Add('.trm','application/x-msterminal');
fMIMEList.Add('.troff','application/x-troff');
fMIMEList.Add('.tsp','application/dsptype');
fMIMEList.Add('.torrent','application/x-bittorrent');
fMIMEList.Add('.ttz','application/t-time');
fMIMEList.Add('.txz','application/x-xz-compressed-tar');
fMIMEList.Add('.udeb','application/x-debian-package');
fMIMEList.Add('.uin','application/x-icq');
fMIMEList.Add('.urls','application/x-url-list');
fMIMEList.Add('.ustar','application/x-ustar');
fMIMEList.Add('.vcd','application/x-cdlink');
fMIMEList.Add('.vor','application/vnd.stardivision.writer');
fMIMEList.Add('.vsl','application/x-cnet-vsl');
fMIMEList.Add('.wcm','application/vnd.ms-works');
fMIMEList.Add('.wb1','application/x-quattropro');
fMIMEList.Add('.wb2','application/x-quattropro');
fMIMEList.Add('.wb3','application/x-quattropro');
fMIMEList.Add('.wdb','application/vnd.ms-works');
fMIMEList.Add('.wks','application/vnd.ms-works');
fMIMEList.Add('.wmd','application/x-ms-wmd');
fMIMEList.Add('.wms','application/x-ms-wms');
fMIMEList.Add('.wmz','application/x-ms-wmz');
fMIMEList.Add('.wp5','application/wordperfect5.1');
fMIMEList.Add('.wpd','application/wordperfect');
fMIMEList.Add('.wpl','application/vnd.ms-wpl');
fMIMEList.Add('.wps','application/vnd.ms-works');
fMIMEList.Add('.wri','application/x-mswrite');
fMIMEList.Add('.xfdf','application/vnd.adobe.xfdf');
fMIMEList.Add('.xls','application/x-msexcel');
fMIMEList.Add('.xlb','application/x-msexcel');
fMIMEList.Add('.xpi','application/x-xpinstall');
fMIMEList.Add('.xps','application/vnd.ms-xpsdocument');
fMIMEList.Add('.xsd','application/vnd.sun.xml.draw');
fMIMEList.Add('.xul','application/vnd.mozilla.xul+xml');
fMIMEList.Add('.z','application/x-compress');
fMIMEList.Add('.zoo','application/x-zoo');
fMIMEList.Add('.zip','application/x-zip-compressed');
{ WAP }
fMIMEList.Add('.wbmp','image/vnd.wap.wbmp');
fMIMEList.Add('.wml','text/vnd.wap.wml');
fMIMEList.Add('.wmlc','application/vnd.wap.wmlc');
fMIMEList.Add('.wmls','text/vnd.wap.wmlscript');
fMIMEList.Add('.wmlsc','application/vnd.wap.wmlscriptc');
{ Non-web text}
fMIMEList.Add('.asm','text/x-asm');
fMIMEList.Add('.p','text/x-pascal');
fMIMEList.Add('.pas','text/x-pascal');
fMIMEList.Add('.cs','text/x-csharp');
fMIMEList.Add('.c','text/x-csrc');
fMIMEList.Add('.c++','text/x-c++src');
fMIMEList.Add('.cpp','text/x-c++src');
fMIMEList.Add('.cxx','text/x-c++src');
fMIMEList.Add('.cc','text/x-c++src');
fMIMEList.Add('.h','text/x-chdr');
fMIMEList.Add('.h++','text/x-c++hdr');
fMIMEList.Add('.hpp','text/x-c++hdr');
fMIMEList.Add('.hxx','text/x-c++hdr');
fMIMEList.Add('.hh','text/x-c++hdr');
fMIMEList.Add('.java','text/x-java');
{ WEB }
fMIMEList.Add('.css','text/css');
fMIMEList.Add('.js','text/javascript');
fMIMEList.Add('.htm','text/html');
fMIMEList.Add('.html','text/html');
fMIMEList.Add('.xhtml','application/xhtml+xml');
fMIMEList.Add('.xht','application/xhtml+xml');
fMIMEList.Add('.rdf','application/rdf+xml');
fMIMEList.Add('.rss','application/rss+xml');
fMIMEList.Add('.ls','text/javascript');
fMIMEList.Add('.mocha','text/javascript');
fMIMEList.Add('.shtml','server-parsed-html');
fMIMEList.Add('.sgm','text/sgml');
fMIMEList.Add('.sgml','text/sgml');
{ Message }
fMIMEList.Add('.mht','message/rfc822');
end;
function TMIMETypes.GetExtensionMIMEType(const aExtension: string): string;
begin
if not fMIMEList.TryGetValue(aExtension,Result) then Result := 'text/html';
end;
function TMIMETypes.GetFileMIMEType(const aFilename: string): string;
var
fname : string;
begin
fname := ExtractFileExt(aFilename);
//remove queries
if fname.Contains('?') then fname := Copy(fname,1,fname.IndexOf('?'));
if not fMIMEList.TryGetValue(fname,Result) then Result := 'text/html';
end;
{ EControlledException }
constructor EControlledException.Create(aCaller: TObject; const aMessage: string);
begin
inherited Create(aMessage);
if aCaller <> nil then fCallerClass := aCaller.ClassType;
end;
initialization
MIMETypes := TMIMETypes.Create;
finalization
MIMETypes.Free;
end.
|
unit DelphiUp.View.Components.Button004;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs,
FMX.Controls.Presentation, FMX.StdCtrls, FMX.Layouts,
DelphiUp.View.Components.Buttons.Interfaces, FMX.Objects;
type
TComponentButton004 = class(TForm)
Layout1: TLayout;
Layout2: TLayout;
Label1: TLabel;
Label2: TLabel;
Rectangle1: TRectangle;
SpeedButton1: TSpeedButton;
procedure FormCreate(Sender: TObject);
procedure SpeedButton1MouseEnter(Sender: TObject);
procedure SpeedButton1MouseLeave(Sender: TObject);
procedure SpeedButton1Click(Sender: TObject);
private
{ Private declarations }
FAttributes : iComponentButtonAttributes<TComponentButton004>;
public
{ Public declarations }
function Component : TFMXObject;
function Attributes : iComponentButtonAttributes<TComponentButton004>;
end;
var
ComponentButton004: TComponentButton004;
implementation
uses
DelphiUp.View.Components.Buttons.Attributes;
{$R *.fmx}
function TComponentButton004.Attributes: iComponentButtonAttributes<TComponentButton004>;
begin
Result := FAttributes;
end;
function TComponentButton004.Component: TFMXObject;
begin
Result := Layout1;
Label1.Text := FAttributes.Title;
Label2.Text := FAttributes.SubTitle;
Label1.TextSettings.Font.Size := FAttributes.FontSize;
Label2.TextSettings.Font.Size := FAttributes.FontSizeSubTitle;
Label1.FontColor := FAttributes.FontColor;
Label2.FontColor := FAttributes.FontColor;
Rectangle1.Fill.Color := FAttributes.Background;
end;
procedure TComponentButton004.FormCreate(Sender: TObject);
begin
FAttributes := TButtonAttributes<TComponentButton004>.New(Self);
end;
procedure TComponentButton004.SpeedButton1Click(Sender: TObject);
var
FOnClick : TProc<TObject>;
begin
FOnClick := FAttributes.OnClick;
if Assigned(FOnClick) then
FOnClick(Sender);
end;
procedure TComponentButton004.SpeedButton1MouseEnter(Sender: TObject);
begin
Rectangle1.Fill.Color := FAttributes.DestBackground;
end;
procedure TComponentButton004.SpeedButton1MouseLeave(Sender: TObject);
begin
Rectangle1.Fill.Color := FAttributes.Background;
end;
end.
|
{
Clever Internet Suite
Copyright (C) 2014 Clever Components
All Rights Reserved
www.CleverComponents.com
}
unit clSoapHttpWebNode;
interface
{$I clVer.inc}
uses
{$IFNDEF DELPHIXE2}
Classes, WebNode, WSDLNode, IntfInfo, SOAPAttachIntf, WSDLIntf,
{$ELSE}
System.Classes, Soap.WebNode, Soap.WSDLNode, Soap.IntfInfo, Soap.SOAPAttachIntf, Soap.WSDLIntf,
{$ENDIF}
clWUtils, clHttp, clSoapMessage;
type
EclSoapHttpError = class(EclHttpError);
TclSoapHttpWebNode = class(TComponent, IInterface, IWebNode)
private
FRefCount: Integer;
FOwnerIsComponent: Boolean;
FUDDIBindingKey: WideString;
FWSDLView: TWSDLView;
FUDDIOperator: String;
FSoapAction: string;
FURL: string;
FUserSetURL: Boolean;
FMimeBoundary: TclString;
{$IFDEF DELPHI2010}
FWebNodeOptions: WebNodeOptions;
{$ENDIF}
FBindingType: TWebServiceBindingType;
FHttp: TclHttp;
FSoapMessage: TclSoapMessage;
function GetSOAPAction: string;
procedure SetSOAPAction(const Value: string);
procedure SetWSDLView(const Value: TWSDLView);
procedure SetURL(const Value: string);
function GetSOAPActionHeader: string;
procedure CheckContentType;
procedure SetHttp(const Value: TclHttp);
function GetHttp: TclHttp;
procedure SetSoapMessage(const Value: TclSoapMessage);
function GetSoapMessage: TclSoapMessage;
protected
function _AddRef: Integer; stdcall;
function _Release: Integer; stdcall;
{$IFDEF DELPHIXE2}
{$IFDEF DELPHIX101}
function GetMimeBoundary: string;
procedure SetMimeBoundary(const Value: string);
{$ELSE}
function GetMimeBoundary: TclString;
procedure SetMimeBoundary(const Value: TclString);
{$ENDIF}
{$ELSE}
function GetMimeBoundary: string;
procedure SetMimeBoundary(Value: string);
{$ENDIF}
{$IFDEF DELPHI2010}
function GetWebNodeOptions: WebNodeOptions;
procedure SetWebNodeOptions(Value: WebNodeOptions);
{$ENDIF}
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
public
class function NewInstance: TObject; override;
procedure AfterConstruction; override;
procedure BeforeExecute(const IntfMD: TIntfMetaData; const MethMD: TIntfMethEntry;
MethodIndex: Integer; AttachHandler: IMimeAttachmentHandler);
procedure Execute(const DataMsg: String; Response: TStream); overload;
procedure Execute(const Request: TStream; Response: TStream); overload;
function Execute(const Request: TStream): TStream; overload;
property URL: string read FURL write SetURL;
property SoapAction: string read GetSOAPAction write SetSOAPAction;
published
property WSDLView: TWSDLView read FWSDLView write SetWSDLView;
property UDDIBindingKey: WideString read FUDDIBindingKey write FUDDIBindingKey;
property UDDIOperator: String read FUDDIOperator write FUDDIOperator;
property HttpClient: TclHttp read FHttp write SetHttp;
property SoapMessage: TclSoapMessage read FSoapMessage write SetSoapMessage;
end;
resourcestring
SoapHttpError = 'Error occurred during the SOAP request';
const
CantGetURLCode = -500;
NoWSDLURLCode = -501;
InvalidContentTypeCode = -502;
implementation
uses
{$IFNDEF DELPHIXE2}
SysUtils, SyncObjs, Windows, InvokeRegistry, WSDLItems, SOAPConst, UDDIHelper,
{$ELSE}
System.SysUtils, System.SyncObjs, Soap.InvokeRegistry, Soap.WSDLItems, Soap.SOAPConst, Soap.UDDIHelper,
{$ENDIF}
clUtils, clTranslator;
{ TclSoapHttpWebNode }
procedure TclSoapHttpWebNode.AfterConstruction;
begin
inherited AfterConstruction();
FOwnerIsComponent := Assigned(Owner) and (Owner is TComponent);
{$IFDEF DELPHIXE}
TInterlocked.Decrement(FRefCount);
{$ELSE}
InterlockedDecrement(FRefCount);
{$ENDIF}
end;
procedure TclSoapHttpWebNode.BeforeExecute(const IntfMD: TIntfMetaData;
const MethMD: TIntfMethEntry; MethodIndex: Integer; AttachHandler: IMimeAttachmentHandler);
var
MethName: InvString;
Binding: InvString;
QBinding: IQualifiedName;
{$IFDEF DELPHI2010}
SOAPVersion: TSOAPVersion;
{$ENDIF}
begin
if FUserSetURL then
begin
MethName := InvRegistry.GetMethExternalName(IntfMD.Info, MethMD.Name);
FSoapAction := InvRegistry.GetActionURIOfInfo(IntfMD.Info, MethName, MethodIndex);
end else
begin
if (WSDLView <> nil) then
begin
{$IFDEF DELPHI2010}
if (ioSOAP12 in InvRegistry.GetIntfInvokeOptions(IntfMD.Info)) then
begin
SOAPVersion := svSOAP12
end else
begin
SOAPVersion := svSOAP11;
end;
{$ENDIF}
WSDLView.Activate();
QBinding := WSDLView.WSDL.GetBindingForServicePort(WSDLView.Service, WSDLView.Port);
if (QBinding <> nil) then
begin
Binding := QBinding.Name;
MethName := InvRegistry.GetMethExternalName(WSDLView.IntfInfo, WSDLView.Operation);
FSoapAction := WSDLView.WSDL.GetSoapAction(Binding, MethName, 0{$IFDEF DELPHI2010}, SOAPVersion{$ENDIF});
end;
if (FSoapAction = '') then
begin
InvRegistry.GetActionURIOfInfo(IntfMD.Info, MethName, MethodIndex);
end;
FURL := WSDLView.WSDL.GetSoapAddressForServicePort(WSDLView.Service, WSDLView.Port{$IFDEF DELPHI2010}, SOAPVersion{$ENDIF});
if (FURL = '') then
begin
raise EclSoapHttpError.Create(Format(sCantGetURL, [WSDLView.Service, WSDLView.Port, WSDLView.WSDL.FileName]), CantGetURLCode, '');
end;
end else
begin
raise EclSoapHttpError.Create(sNoWSDLURL, NoWSDLURLCode, '');
end;
end;
if (AttachHandler <> nil) then
begin
FBindingType := btMIME;
FMimeBoundary := TclString(AttachHandler.MIMEBoundary);
if (SameText(GetSoapMessage().Header.CharSet, 'utf-8')) then
begin
AttachHandler.AddSoapHeader(Format(ContentTypeTemplate, [ContentTypeUTF8]));
end else
begin
AttachHandler.AddSoapHeader(Format(ContentTypeTemplate, [ContentTypeNoUTF8]));
end;
AttachHandler.AddSoapHeader(GetSOAPActionHeader);
end else
begin
FBindingType := btSOAP;
end;
end;
procedure TclSoapHttpWebNode.CheckContentType;
begin
if SameText(GetHttp().ResponseHeader.ContentType, ContentTypeTextPlain) or
SameText(GetHttp().ResponseHeader.ContentType, STextHtml) then
begin
raise EclSoapHttpError.Create(Format(SInvalidContentType, [GetHttp().ResponseHeader.ContentType]), InvalidContentTypeCode, '');
end;
end;
function TclSoapHttpWebNode.Execute(const Request: TStream): TStream;
begin
Result := TMemoryStream.Create();
try
Execute(Request, Result);
except
Result.Free();
raise;
end;
end;
procedure TclSoapHttpWebNode.Execute(const Request: TStream; Response: TStream);
var
canRetry: Boolean;
lookUpUDDI: Boolean;
accessPoint: string;
prevError: Integer;
respHdr: TStrings;
oldSilentMode: Boolean;
begin
lookUpUDDI := False;
canRetry := (Length(FUDDIBindingKey) > 0) and (Length(FUDDIOperator) > 0);
prevError := 0;
oldSilentMode := GetHttp().SilentHTTP;
respHdr := TStringList.Create();
try
GetHttp().SilentHTTP := True;
while (True) do
begin
if (lookUpUDDI and canRetry) then
begin
canRetry := False;
accessPoint := GetBindingkeyAccessPoint(FUDDIOperator, FUDDIBindingKey);
if (accessPoint = '') or SameText(accessPoint, FURL) then
begin
raise EclSoapHttpError.Create(SoapHttpError, prevError, '');
end;
SetURL(accessPoint);
end;
if (FBindingType = btMIME) then
begin
GetSoapMessage().Header.Boundary := GetString_(FMimeBoundary);
end else
begin
GetSoapMessage().Header.SoapAction := SOAPAction;
end;
GetHttp().SendRequest('POST', FURL, GetSoapMessage().HeaderSource, Request, respHdr, Response);
FMimeBoundary := GetTclString(GetHttp().ResponseHeader.Boundary);
if canRetry and (GetHttp().StatusCode >= 400) then
begin
lookUpUDDI := True;
PrevError := GetHttp().StatusCode;
end else
begin
CheckContentType();
Break;
end;
end;
finally
GetHttp().SilentHTTP := oldSilentMode;
respHdr.Free();
end;
end;
procedure TclSoapHttpWebNode.Execute(const DataMsg: String; Response: TStream);
var
stream: TStream;
buf: TclByteArray;
begin
Stream := TMemoryStream.Create;
try
buf := TclTranslator.GetUtf8Bytes(WideString(DataMsg));//TODO use GetSoapMessage().Header.CharSet
if (Length(buf) > 0) then
begin
stream.Write(buf[0], Length(buf));
end;
Execute(stream, Response);
finally
stream.Free();
end;
end;
function TclSoapHttpWebNode.GetHttp: TclHttp;
begin
Assert(FHttp <> nil);
Result := FHttp;
end;
function TclSoapHttpWebNode.GetSOAPAction: string;
begin
if (FSoapAction = '') then
begin
Result := '""';
end else
begin
Result := FSoapAction;
end;
end;
function TclSoapHttpWebNode.GetSOAPActionHeader: string;
begin
if (SoapAction = '') then
begin
Result := SHTTPSoapAction + ':'
end else
if (SoapAction = '""') then
begin
Result := SHTTPSoapAction + ': ""'
end else
begin
Result := SHTTPSoapAction + ': ' + '"' + SoapAction + '"';
end;
end;
function TclSoapHttpWebNode.GetSoapMessage: TclSoapMessage;
begin
Assert(FSoapMessage <> nil);
Result := FSoapMessage;
end;
{$IFDEF DELPHI2010}
function TclSoapHttpWebNode.GetWebNodeOptions: WebNodeOptions;
begin
Result := FWebNodeOptions;
end;
procedure TclSoapHttpWebNode.SetWebNodeOptions(Value: WebNodeOptions);
begin
FWebNodeOptions := Value;
end;
{$ENDIF}
class function TclSoapHttpWebNode.NewInstance: TObject;
begin
Result := inherited NewInstance();
TclSoapHttpWebNode(Result).FRefCount := 1;
end;
procedure TclSoapHttpWebNode.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if (AComponent = FHttp) and (Operation = opRemove) then
begin
FHttp := nil;
end else
if (AComponent = FSoapMessage) and (Operation = opRemove) then
begin
FSoapMessage := nil;
end;
end;
procedure TclSoapHttpWebNode.SetHttp(const Value: TclHttp);
begin
if (FHttp <> Value) then
begin
if (FHttp <> nil) then
begin
FHttp.RemoveFreeNotification(Self);
end;
FHttp := Value;
if (FHttp <> nil) then
begin
FHttp.FreeNotification(Self);
end;
end;
end;
{$IFDEF DELPHIXE2}
{$IFDEF DELPHIX101}
function TclSoapHttpWebNode.GetMimeBoundary: string;
begin
Result := string(FMimeBoundary);
end;
procedure TclSoapHttpWebNode.SetMimeBoundary(const Value: string);
begin
FMimeBoundary := TclString(Value);
end;
{$ELSE}
function TclSoapHttpWebNode.GetMimeBoundary: TclString;
begin
Result := FMimeBoundary;
end;
procedure TclSoapHttpWebNode.SetMimeBoundary(const Value: TclString);
begin
FMimeBoundary := Value;
end;
{$ENDIF}
{$ELSE}
function TclSoapHttpWebNode.GetMimeBoundary: string;
begin
Result := string(FMimeBoundary);
end;
procedure TclSoapHttpWebNode.SetMimeBoundary(Value: string);
begin
FMimeBoundary := TclString(Value);
end;
{$ENDIF}
procedure TclSoapHttpWebNode.SetSOAPAction(const Value: string);
begin
FSoapAction := Value;
end;
procedure TclSoapHttpWebNode.SetSoapMessage(const Value: TclSoapMessage);
begin
if (FSoapMessage <> Value) then
begin
if (FSoapMessage <> nil) then
begin
FSoapMessage.RemoveFreeNotification(Self);
end;
FSoapMessage := Value;
if (FSoapMessage <> nil) then
begin
FSoapMessage.FreeNotification(Self);
end;
end;
end;
procedure TclSoapHttpWebNode.SetURL(const Value: string);
begin
FURL := Value;
FUserSetURL := (FURL <> '');
GetHttp().Close();
end;
procedure TclSoapHttpWebNode.SetWSDLView(const Value: TWSDLView);
begin
FWSDLView := Value;
end;
function TclSoapHttpWebNode._AddRef: Integer;
begin
{$IFDEF DELPHIXE}
Result := TInterlocked.Increment(FRefCount)
{$ELSE}
Result := InterlockedIncrement(FRefCount);
{$ENDIF}
end;
function TclSoapHttpWebNode._Release: Integer;
begin
{$IFDEF DELPHIXE}
Result := TInterlocked.Decrement(FRefCount);
{$ELSE}
Result := InterlockedDecrement(FRefCount);
{$ENDIF}
if (Result = 0) and not FOwnerIsComponent then
begin
Destroy();
end;
end;
end.
|
{ *************************************************************************** }
{ }
{ This file is part of the XPde project }
{ }
{ Copyright (c) 2002 Jose Leon Serna <ttm@xpde.com> }
{ }
{ This program is free software; you can redistribute it and/or }
{ modify it under the terms of the GNU General Public }
{ License as published by the Free Software Foundation; either }
{ version 2 of the License, or (at your option) any later version. }
{ }
{ This program is distributed in the hope that it will be useful, }
{ but WITHOUT ANY WARRANTY; without even the implied warranty of }
{ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU }
{ General Public License for more details. }
{ }
{ You should have received a copy of the GNU General Public License }
{ along with this program; see the file COPYING. If not, write to }
{ the Free Software Foundation, Inc., 59 Temple Place - Suite 330, }
{ Boston, MA 02111-1307, USA. }
{ }
{ *************************************************************************** }
unit uXPDirectoryMonitor;
{ TODO : Clean up the code }
interface
uses
Classes, SysUtils, QFileCtrls,
QTypes, QDialogs, Libc,
QForms, QStdCtrls, QExtCtrls;
type
//Dirty class to access the private FFiles field
TDirtyDirectory = class(TPersistent)
private
FAutoUpdate: Boolean;
FIncludeParentDir: Boolean;
FSortMode: TSortMode;
FFileType: TFileType;
FSuspendEvents: Boolean;
FDirChanging: Boolean;
FClient: IDirectoryClient;
FFiles: TList;
end;
//XPDirectory, maintains an updated list of the contents
//of a directory
TXPDirectory=class(TDirectory)
private
FOldLocation: string;
FTimer: TTimer;
doTimer: boolean;
signal: boolean;
function updatefilelist(const newlist:TStringList): boolean;
public
procedure OnTimer(sender: TObject);
procedure ListFiles(Reread: Boolean = True); override;
constructor Create(AClient: IDirectoryClient); override;
destructor Destroy;override;
end;
//Wrapper around a TXPDirectory, this is the one you have to use
//access directory properties through Directory property
TXPDirectoryMonitor=class(TComponent, IDirectoryClient)
private
FDirectory: TXPDirectory;
FOnDirectoryModified: TNotifyEvent;
procedure SetOnDirectoryModified(const Value: TNotifyEvent);
public
function FileFound(const SearchRec: TSearchRec): Boolean;
procedure ListEnd;
function ListStart: Boolean;
procedure DirectoryChanged(const NewDir: WideString);
procedure MaskChange(const NewMask: WideString);
constructor Create(AOwner:TComponent);override;
destructor Destroy;override;
published
property Directory: TXPDirectory read FDirectory;
property OnDirectoryModified: TNotifyEvent read FOnDirectoryModified write SetOnDirectoryModified;
end;
implementation
{ TXPDirectoryMonitor }
constructor TXPDirectoryMonitor.Create(AOwner: TComponent);
begin
inherited;
FOnDirectoryModified:=nil;
//Creates the directory object
FDirectory:=TXPDirectory.create(self);
FDirectory.AutoUpdate:=true;
FDirectory.IncludeParentDir:=false;
end;
destructor TXPDirectoryMonitor.Destroy;
begin
FDirectory.free;
inherited;
end;
procedure TXPDirectoryMonitor.DirectoryChanged(const NewDir: WideString);
begin
//Not used
end;
function TXPDirectoryMonitor.FileFound(const SearchRec: TSearchRec): Boolean;
begin
//Not used
result:=true;
end;
procedure TXPDirectoryMonitor.ListEnd;
begin
//Fires the DirectoryModified event to update the control
if assigned(FOnDirectoryModified) then FOnDirectoryModified(self);
end;
function TXPDirectoryMonitor.ListStart: Boolean;
begin
//Not used
result:=true;
end;
procedure TXPDirectoryMonitor.MaskChange(const NewMask: WideString);
begin
//Not used
end;
procedure TXPDirectoryMonitor.SetOnDirectoryModified(const Value: TNotifyEvent);
begin
FOnDirectoryModified := Value;
end;
{ TXPDirectory }
constructor TXPDirectory.Create(AClient: IDirectoryClient);
begin
inherited;
signal:=false;
dotimer:=false;
//Uses a timer to reduce update operations
{ TODO : Allow configure this by the registry }
FTimer:=TTimer.create(nil);
FTimer.Interval:=500;
FTimer.OnTimer:=OnTimer;
FTimer.Enabled:=false;
FOldLocation:='';
end;
destructor TXPDirectory.Destroy;
begin
FTimer.free;
inherited;
end;
procedure TXPDirectory.ListFiles(Reread: Boolean);
var
SearchRec: TSearchRec;
files: TStringList;
begin
//If there are no files or location changed, reread all the contents
if (Count=0) or (FOldLocation<>Location) then begin
FOldLocation:=Location;
inherited ListFiles(Reread);
end
else begin
if ReRead and dotimer then begin
//Start filling newlist
files:=TStringList.create;
try
if FindFirst(IncludeTrailingPathDelimiter(Location) + '*', faAnyFile, SearchRec) = 0 then begin
repeat
if ((SearchRec.Name <> '..') and (SearchRec.Name <> '.')) then begin
files.addobject(searchrec.Name,TObject(AllocFileInfo(SearchRec)));
end;
application.processmessages;
until FindNext(SearchRec) <> 0;
FindClose(SearchRec);
end;
files.Sorted:=true;
//Update the list with the new contents
if updatefilelist(files) then begin
DoListEnd;
end;
finally
files.free;
end;
end
else begin
if not ftimer.enabled then begin
signal:=false;
ftimer.enabled:=true;
end
else begin
signal:=true;
end;
end;
end;
end;
procedure TXPDirectory.OnTimer(sender: TObject);
begin
FTimer.Enabled:=false;
if signal then begin
signal:=false;
ftimer.Enabled:=true;
end
else begin
dotimer:=true;
try
ListFiles;
finally
dotimer:=false;
end;
end;
end;
function TXPDirectory.updatefilelist(const newlist: TStringList): boolean;
var
foldlist: TList;
old, new: PFileInfo;
fname: string;
k: integer;
i: integer;
begin
result:=false;
foldlist:=TDirtyDirectory(self).FFiles;
//Iterates through the old list
for i:=foldlist.count-1 downto 0 do begin
old:=PFileInfo(foldlist[i]);
fname:=old^.SR.Name;
//Delete items that already exist
if newlist.find(fname,k) then newlist.Delete(k)
else begin
//If the items doesn't exist on the new list, then is because have been removed from disk
Dispose(PFileInfo(FoldList[i]));
foldlist.Delete(i);
result:=true;
end;
application.processmessages;
end;
//Add new items at the end
for k:=0 to newlist.count-1 do begin
new:=PFileInfo(newlist.Objects[k]);
FOldList.Add(AllocFileInfo(new^.sr));
result:=true;
application.processmessages;
end;
end;
end.
|
unit uGnLog;
interface
uses
System.SysUtils, System.IOUtils, uGnGeneral;
type
TLog = class
class procedure Init;
class procedure Log(const AMsg: string); overload;
class procedure Log(const AMsg: string; AArgs: array of const); overload;
end;
implementation
const
cFileName = 'log.txt';
cLogEnabled = True;
{ TLog }
class procedure TLog.Log(const AMsg: string);
begin
if cLogEnabled then
TFile.AppendAllText(gnrProgramUserDataPath + cFileName, AMsg + #13#10);
end;
class procedure TLog.Init;
begin
TFile.Delete(gnrProgramUserDataPath + cFileName);
end;
class procedure TLog.Log(const AMsg: string; AArgs: array of const);
begin
Log(Format(AMsg, AArgs));
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.