text stringlengths 14 6.51M |
|---|
{**************************************************************************************************}
{ }
{ Project JEDI Code Library (JCL) }
{ }
{ 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 JclRegistry.pas. }
{ }
{ The Initial Developer of the Original Code is documented in the accompanying }
{ help file JCL.chm. Portions created by these individuals are Copyright (C) of these individuals. }
{ }
{**************************************************************************************************}
{ }
{ Contains various utility routines to read and write registry values. Using these routines }
{ prevents you from having to instantiate temporary TRegistry objects and since the routines }
{ directly call the registry API they do not suffer from the resource overhead as TRegistry does. }
{ }
{ Unit owner: Eric S.Fisher }
{ Last modified: February 21, 2001 }
{ }
{**************************************************************************************************}
unit JclRegistry;
{$I jcl.inc}
{$WEAKPACKAGEUNIT ON}
interface
uses
Windows, Classes,
JclBase;
//--------------------------------------------------------------------------------------------------
// Registry
//--------------------------------------------------------------------------------------------------
function RegCreateKey(const RootKey: HKEY; const Key, Value: string): Longint;
function RegDeleteEntry(const RootKey: HKEY; const Key, Name: string): Boolean;
function RegDeleteKeyTree(const RootKey: HKEY; const Key: string): Boolean;
function RegReadBool(const RootKey: HKEY; const Key, Name: string): Boolean;
function RegReadBoolDef(const RootKey: HKEY; const Key, Name: string; Def: Boolean): Boolean;
function RegReadInteger(const RootKey: HKEY; const Key, Name: string): Integer;
function RegReadIntegerDef(const RootKey: HKEY; const Key, Name: string; Def: Integer): Integer;
function RegReadString(const RootKey: HKEY; const Key, Name: string): string;
function RegReadStringDef(const RootKey: HKEY; const Key, Name, Def: string): string;
function RegReadBinary(const RootKey: HKEY; const Key, Name: string; var Value; const ValueSize: Cardinal): Cardinal;
function RegReadBinaryDef(const RootKey: HKEY; const Key, Name: string;
var Value; const ValueSize: Cardinal; const Def: Byte): Cardinal;
procedure RegWriteBool(const RootKey: HKEY; const Key, Name: string; Value: Boolean);
procedure RegWriteInteger(const RootKey: HKEY; const Key, Name: string; Value: Integer);
procedure RegWriteString(const RootKey: HKEY; const Key, Name, Value: string);
procedure RegWriteBinary(const RootKey: HKEY; const Key, Name: string; var Value; const ValueSize: Cardinal);
function RegGetValueNames(const RootKey: HKEY; const Key: string; const List: TStrings): Boolean;
function RegGetKeyNames(const RootKey: HKEY; const Key: string; const List: TStrings): Boolean;
function RegHasSubKeys(const RootKey: HKEY; const Key: string): Boolean;
{
TODOC
From: Jean-Fabien Connault [mailto:cycocrew@worldnet.fr]
Descr: Test whether a registry key exists as a subkey of RootKey
Used test cases:
procedure TForm1.Button1Click(Sender: TObject);
var
RegKey: HKEY;
begin
if RegOpenKeyEx(HKEY_CURRENT_USER, 'Software', 0, KEY_READ, RegKey) = ERROR_SUCCESS then
begin
Assert(not RegKeyExists(RegKey, 'Microsoft\_Windows'));
RegCloseKey(RegKey);
end;
if RegOpenKeyEx(HKEY_CURRENT_USER, 'Software', 0, KEY_READ, RegKey) = ERROR_SUCCESS then
begin
Assert(RegKeyExists(RegKey, 'Microsoft\Windows'));;
RegCloseKey(RegKey);
end;
Assert(RegKeyExists(HKEY_CURRENT_USER, ''));
Assert(RegKeyExists(HKEY_CURRENT_USER, 'Software'));
Assert(RegKeyExists(HKEY_CURRENT_USER, 'Software\Microsoft'));
Assert(RegKeyExists(HKEY_CURRENT_USER, 'Software\Microsoft\Windows'));
Assert(RegKeyExists(HKEY_CURRENT_USER, '\Software\Microsoft\Windows'));
Assert(not RegKeyExists(HKEY_CURRENT_USER, '\Software\Microsoft2\Windows'));
end;
}
function RegKeyExists(const RootKey: HKEY; const Key: string): Boolean;
type
TExecKind = (ekMachineRun, ekMachineRunOnce, ekUserRun, ekUserRunOnce,
ekServiceRun, ekServiceRunOnce);
EJclRegistryError = class (EJclError);
function UnregisterAutoExec(ExecKind: TExecKind; const Name: string): Boolean;
function RegisterAutoExec(ExecKind: TExecKind; const Name, Cmdline: string): Boolean;
function RegSaveList(const RootKey: HKEY; const Key: string; const ListName: string;
const Items: TStrings): Boolean;
function RegLoadList(const RootKey: HKEY; const Key: string; const ListName: string;
const SaveTo: TStrings): Boolean;
function RegDelList(const RootKey: HKEY; const Key: string; const ListName: string): Boolean;
implementation
uses
SysUtils,
JclResources;
const
cItems = 'Items';
cRegBinKinds = [REG_BINARY, REG_MULTI_SZ];
//==================================================================================================
// Internal helper routines
//==================================================================================================
procedure ReadError(const Key: string);
begin
raise EJclRegistryError.CreateResRecFmt(@RsUnableToOpenKeyRead, [Key]);
end;
//--------------------------------------------------------------------------------------------------
procedure WriteError(const Key: string);
begin
raise EJclRegistryError.CreateResRecFmt(@RsUnableToOpenKeyWrite, [Key]);
end;
//--------------------------------------------------------------------------------------------------
procedure ValueError(const Key, Name: string);
begin
raise EJclRegistryError.CreateResRecFmt(@RsUnableToAccessValue, [Key, Name]);
end;
//--------------------------------------------------------------------------------------------------
function GetKeyAndPath(ExecKind: TExecKind; var Key: HKEY; var RegPath: string): Boolean;
begin
Result := False;
if (ExecKind in [ekServiceRun, ekServiceRunOnce]) and (Win32Platform = VER_PLATFORM_WIN32_NT) then
Exit;
Key := HKEY_CURRENT_USER;
if ExecKind in [ekMachineRun, ekMachineRunOnce, ekServiceRun, ekServiceRunOnce] then
Key := HKEY_LOCAL_MACHINE;
RegPath := 'Software\Microsoft\Windows\CurrentVersion\';
case ExecKind of
ekMachineRun, ekUserRun:
RegPath := RegPath + 'Run';
ekMachineRunOnce, ekUserRunOnce:
RegPath := RegPath + 'RunOnce';
ekServiceRun:
RegPath := RegPath + 'RunServices';
ekServiceRunOnce:
RegPath := RegPath + 'RunServicesOnce';
end;
Result := True;
end;
//--------------------------------------------------------------------------------------------------
function RelativeKey(const Key: string): PChar;
begin
Result := PChar(Key);
if (Key <> '') and (Key[1] = '\') then
Inc(Result);
end;
//==================================================================================================
// Registry
//==================================================================================================
function RegCreateKey(const RootKey: HKEY; const Key, Value: string): Longint;
begin
Result := RegSetValue(RootKey, RelativeKey(Key), REG_SZ, PChar(Value), Length(Value));
end;
//--------------------------------------------------------------------------------------------------
function RegDeleteEntry(const RootKey: HKEY; const Key, Name: string): Boolean;
var
RegKey: HKEY;
begin
Result := False;
if RegOpenKeyEx(RootKey, RelativeKey(Key), 0, KEY_SET_VALUE, RegKey) = ERROR_SUCCESS then
begin
Result := RegDeleteValue(RegKey, PChar(Name)) = ERROR_SUCCESS;
RegCloseKey(RegKey);
if not Result then
ValueError(Key, Name);
end
else
WriteError(Key);
end;
//--------------------------------------------------------------------------------------------------
function RegDeleteKeyTree(const RootKey: HKEY; const Key: string): Boolean;
var
RegKey: HKEY;
I: DWORD;
Size: DWORD;
NumSubKeys: DWORD;
MaxSubKeyLen: DWORD;
KeyName: string;
begin
Result := RegOpenKeyEx(RootKey, RelativeKey(Key), 0, KEY_ALL_ACCESS, RegKey) = ERROR_SUCCESS;
if Result then
begin
RegQueryInfoKey(RegKey, nil, nil, nil, @NumSubKeys, @MaxSubKeyLen, nil, nil, nil, nil, nil, nil);
if NumSubKeys <> 0 then
for I := NumSubKeys-1 downto 0 do
begin
Size := MaxSubKeyLen+1;
SetLength(KeyName, Size);
RegEnumKeyEx(RegKey, I, PChar(KeyName), Size, nil, nil, nil, nil);
SetLength(KeyName, StrLen(PChar(KeyName)));
Result := RegDeleteKeyTree(RootKey, Key + '\' + KeyName);
if not Result then
Break;
end;
RegCloseKey(RegKey);
if Result then
Result := Windows.RegDeleteKey(RootKey, RelativeKey(Key)) = ERROR_SUCCESS;
end
else
WriteError(Key);
end;
//--------------------------------------------------------------------------------------------------
function RegReadBool(const RootKey: HKEY; const Key, Name: string): Boolean;
begin
Result := RegReadInteger(RootKey, Key, Name) <> 0;
end;
//--------------------------------------------------------------------------------------------------
function RegReadBoolDef(const RootKey: HKEY; const Key, Name: string; Def: Boolean): Boolean;
begin
Result := Boolean(RegReadIntegerDef(RootKey, Key, Name, Ord(Def)));
end;
//--------------------------------------------------------------------------------------------------
function RegReadInteger(const RootKey: HKEY; const Key, Name: string): Integer;
var
RegKey: HKEY;
Size: DWORD;
IntVal: Integer;
RegKind: DWORD;
Ret: Longint;
begin
Result := 0;
if RegOpenKeyEx(RootKey, RelativeKey(Key), 0, KEY_READ, RegKey) = ERROR_SUCCESS then
begin
RegKind := 0;
Size := SizeOf(Integer);
Ret := RegQueryValueEx(RegKey, PChar(Name), nil, @RegKind, @IntVal, @Size);
RegCloseKey(RegKey);
if Ret = ERROR_SUCCESS then
begin
if RegKind = REG_DWORD then
Result := IntVal
else
ValueError(Key, Name);
end
else
ValueError(Key, Name);
end
else
ReadError(Key);
end;
//--------------------------------------------------------------------------------------------------
function RegReadIntegerDef(const RootKey: HKEY; const Key, Name: string; Def: Integer): Integer;
var
RegKey: HKEY;
Size: DWORD;
IntVal: Integer;
RegKind: DWORD;
begin
Result := Def;
if RegOpenKeyEx(RootKey, RelativeKey(Key), 0, KEY_READ, RegKey) = ERROR_SUCCESS then
begin
RegKind := 0;
Size := SizeOf(Integer);
if RegQueryValueEx(RegKey, PChar(Name), nil, @RegKind, @IntVal, @Size) = ERROR_SUCCESS then
if RegKind = REG_DWORD then
Result := IntVal;
RegCloseKey(RegKey);
end;
end;
//--------------------------------------------------------------------------------------------------
function RegReadString(const RootKey: HKEY; const Key, Name: string): string;
var
RegKey: HKEY;
Size: DWORD;
StrVal: string;
RegKind: DWORD;
Ret: Longint;
begin
Result := '';
if RegOpenKeyEx(RootKey, RelativeKey(Key), 0, KEY_READ, RegKey) = ERROR_SUCCESS then
begin
RegKind := 0;
Size := 0;
Ret := RegQueryValueEx(RegKey, PChar(Name), nil, @RegKind, nil, @Size);
if Ret = ERROR_SUCCESS then
if RegKind in [REG_SZ, REG_EXPAND_SZ] then
begin
SetLength(StrVal, Size);
RegQueryValueEx(RegKey, PChar(Name), nil, @RegKind, PByte(StrVal), @Size);
SetLength(StrVal, StrLen(PChar(StrVal)));
Result := StrVal;
end;
RegCloseKey(RegKey);
if not (RegKind in [REG_SZ, REG_EXPAND_SZ]) then
ValueError(Key, Name);
end
else
ReadError(Key);
end;
//--------------------------------------------------------------------------------------------------
function RegReadStringDef(const RootKey: HKEY; const Key, Name, Def: string): string;
var
RegKey: HKEY;
Size: DWORD;
StrVal: string;
RegKind: DWORD;
begin
Result := Def;
if RegOpenKeyEx(RootKey, RelativeKey(Key), 0, KEY_READ, RegKey) = ERROR_SUCCESS then
begin
RegKind := 0;
Size := 0;
if RegQueryValueEx(RegKey, PChar(Name), nil, @RegKind, nil, @Size) = ERROR_SUCCESS then
if RegKind in [REG_SZ, REG_EXPAND_SZ] then
begin
SetLength(StrVal, Size);
if RegQueryValueEx(RegKey, PChar(Name), nil, @RegKind, PByte(StrVal), @Size) = ERROR_SUCCESS then
begin
SetLength(StrVal, StrLen(PChar(StrVal)));
Result := StrVal;
end;
end;
RegCloseKey(RegKey);
end;
end;
//--------------------------------------------------------------------------------------------------
function RegReadBinary(const RootKey: HKEY; const Key, Name: string; var Value; const ValueSize: Cardinal): Cardinal;
var
RegKey: HKEY;
Size: DWORD;
RegKind: DWORD;
Ret: Longint;
begin
Result := 0;
if RegOpenKeyEx(RootKey, RelativeKey(Key), 0, KEY_READ, RegKey) = ERROR_SUCCESS then
begin
RegKind := 0;
Size := 0;
Ret := RegQueryValueEx(RegKey, PChar(Name), nil, @RegKind, nil, @Size);
if Ret = ERROR_SUCCESS then
if RegKind in cRegBinKinds then
begin
if Size > ValueSize then
Size := ValueSize;
RegQueryValueEx(RegKey, PChar(Name), nil, @RegKind, @Value, @Size);
Result := Size;
end;
RegCloseKey(RegKey);
if not (RegKind in cRegBinKinds) then
ValueError(Key, Name);
end
else
ReadError(Key);
end;
//--------------------------------------------------------------------------------------------------
function RegReadBinaryDef(const RootKey: HKEY; const Key, Name: string;
var Value; const ValueSize: Cardinal; const Def: Byte): Cardinal;
var
RegKey: HKEY;
Size: DWORD;
StrVal: string;
RegKind: DWORD;
begin
Result := 0;
FillChar(Value, ValueSize, Def);
if RegOpenKeyEx(RootKey, RelativeKey(Key), 0, KEY_READ, RegKey) = ERROR_SUCCESS then
begin
RegKind := 0;
Size := 0;
if RegQueryValueEx(RegKey, PChar(Name), nil, @RegKind, nil, @Size) = ERROR_SUCCESS then
if RegKind in cRegBinKinds then
begin
if RegQueryValueEx(RegKey, PChar(Name), nil, @RegKind, PByte(StrVal), @Size) = ERROR_SUCCESS then
begin
if Size > ValueSize then
Size := ValueSize;
RegQueryValueEx(RegKey, PChar(Name), nil, @RegKind, @Value, @Size);
Result := Size;
end;
end;
RegCloseKey(RegKey);
end;
end;
//--------------------------------------------------------------------------------------------------
procedure RegWriteBool(const RootKey: HKEY; const Key, Name: string; Value: Boolean);
begin
RegWriteInteger(RootKey, Key, Name, Ord(Value));
end;
//--------------------------------------------------------------------------------------------------
procedure RegWriteInteger(const RootKey: HKEY; const Key, Name: string; Value: Integer);
var
RegKey: HKEY;
Ret: Longint;
begin
if RegOpenKeyEx(RootKey, RelativeKey(Key), 0, KEY_SET_VALUE, RegKey) = ERROR_SUCCESS then
begin
Ret := RegSetValueEx(RegKey, PChar(Name), 0, REG_DWORD, @Value, SizeOf(Integer));
RegCloseKey(RegKey);
if Ret <> ERROR_SUCCESS then
WriteError(Key);
end
else
WriteError(Key);
end;
//--------------------------------------------------------------------------------------------------
procedure RegWriteString(const RootKey: HKEY; const Key, Name, Value: string);
var
RegKey: HKEY;
Ret: Longint;
begin
if RegOpenKeyEx(RootKey, RelativeKey(Key), 0, KEY_SET_VALUE, RegKey) = ERROR_SUCCESS then
begin
Ret := RegSetValueEx(RegKey, PChar(Name), 0, REG_SZ, PChar(Value), Length(Value)+1);
RegCloseKey(RegKey);
if Ret <> ERROR_SUCCESS then
WriteError(Key);
end
else
WriteError(Key);
end;
//--------------------------------------------------------------------------------------------------
procedure RegWriteBinary(const RootKey: HKEY; const Key, Name: string; var Value; const ValueSize: Cardinal);
var
RegKey: HKEY;
Ret: Longint;
begin
if RegOpenKeyEx(RootKey, RelativeKey(Key), 0, KEY_SET_VALUE, RegKey) = ERROR_SUCCESS then
begin
Ret := RegSetValueEx(RegKey, PChar(Name), 0, REG_BINARY, @Value, ValueSize);
RegCloseKey(RegKey);
if Ret <> ERROR_SUCCESS then
WriteError(Key);
end
else
WriteError(Key);
end;
//--------------------------------------------------------------------------------------------------
function UnregisterAutoExec(ExecKind: TExecKind; const Name: string): Boolean;
var
Key: HKEY;
RegPath: string;
begin
Result := GetKeyAndPath(ExecKind, Key, RegPath);
if Result then
Result := RegDeleteEntry(Key, RegPath, Name);
end;
//--------------------------------------------------------------------------------------------------
function RegisterAutoExec(ExecKind: TExecKind; const Name, Cmdline: string): Boolean;
var
Key: HKEY;
RegPath: string;
begin
Result := GetKeyAndPath(ExecKind, Key, RegPath);
if Result then
RegWriteString(Key, RegPath, Name, Cmdline);
end;
//--------------------------------------------------------------------------------------------------
function RegGetValueNames(const RootKey: HKEY; const Key: string; const List: TStrings): Boolean;
var
RegKey: HKEY;
I: DWORD;
Size: DWORD;
NumSubKeys: DWORD;
NumSubValues: DWORD;
MaxSubValueLen: DWORD;
ValueName: string;
begin
Result := False;
List.Clear;
if RegOpenKeyEx(RootKey, RelativeKey(Key), 0, KEY_READ, RegKey) = ERROR_SUCCESS then
begin
if RegQueryInfoKey(RegKey, nil, nil, nil, @NumSubKeys, nil, nil, @NumSubValues, @MaxSubValueLen, nil, nil, nil) = ERROR_SUCCESS then
begin
SetLength(ValueName, MaxSubValueLen + 1);
if NumSubValues <> 0 then
for I := 0 to NumSubValues - 1 do
begin
Size := MaxSubValueLen + 1;
RegEnumValue(RegKey, I, PChar(ValueName), Size, nil, nil, nil, nil);
List.Add(PChar(ValueName));
end;
Result := True;
end;
RegCloseKey(RegKey);
end
else
ReadError(Key);
end;
//--------------------------------------------------------------------------------------------------
function RegGetKeyNames(const RootKey: HKEY; const Key: string; const List: TStrings): Boolean;
var
RegKey: HKEY;
I: DWORD;
Size: DWORD;
NumSubKeys: DWORD;
MaxSubKeyLen: DWORD;
KeyName: string;
begin
Result := False;
List.Clear;
if RegOpenKeyEx(RootKey, RelativeKey(Key), 0, KEY_READ, RegKey) = ERROR_SUCCESS then
begin
if RegQueryInfoKey(RegKey, nil, nil, nil, @NumSubKeys, @MaxSubKeyLen, nil, nil, nil, nil, nil, nil) = ERROR_SUCCESS then
begin
SetLength(KeyName, MaxSubKeyLen+1);
if NumSubKeys <> 0 then
for I := 0 to NumSubKeys-1 do
begin
Size := MaxSubKeyLen+1;
RegEnumKeyEx(RegKey, I, PChar(KeyName), Size, nil, nil, nil, nil);
List.Add(PChar(KeyName));
end;
Result := True;
end;
RegCloseKey(RegKey);
end
else
ReadError(Key);
end;
//--------------------------------------------------------------------------------------------------
function RegHasSubKeys(const RootKey: HKEY; const Key: string): Boolean;
var
RegKey: HKEY;
NumSubKeys: Integer;
begin
Result := False;
if RegOpenKeyEx(RootKey, RelativeKey(Key), 0, KEY_READ, RegKey) = ERROR_SUCCESS then
begin
RegQueryInfoKey(RegKey, nil, nil, nil, @NumSubKeys, nil, nil, nil, nil, nil, nil, nil);
Result := NumSubKeys <> 0;
RegCloseKey(RegKey);
end
else
ReadError(Key);
end;
//--------------------------------------------------------------------------------------------------
function RegKeyExists(const RootKey: HKEY; const Key: string): Boolean;
var
RegKey: HKEY;
begin
Result := (RegOpenKeyEx(RootKey, RelativeKey(Key), 0, KEY_READ, RegKey) = ERROR_SUCCESS);
if Result then RegCloseKey(RegKey);
end;
//--------------------------------------------------------------------------------------------------
function RegSaveList(const RootKey: HKEY; const Key: string;
const ListName: string; const Items: TStrings): Boolean;
var
I: Integer;
Subkey: string;
begin
Result := False;
Subkey := Key + '\' + ListName;
if RegCreateKey(RootKey, Subkey, '') = ERROR_SUCCESS then
begin
// Save Number of strings
RegWriteInteger(RootKey, Subkey, cItems, Items.Count);
for I := 1 to Items.Count do
RegWriteString(RootKey, Subkey, IntToStr(I), Items[I-1]);
Result := True;
end;
end;
//--------------------------------------------------------------------------------------------------
function RegLoadList(const RootKey: HKEY; const Key: string;
const ListName: string; const SaveTo: TStrings): Boolean;
var
I, N: Integer;
Subkey: string;
begin
SaveTo.Clear;
Subkey := Key + '\' + ListName;
N := RegReadInteger(RootKey, Subkey, cItems);
for I := 1 to N do
SaveTo.Add(RegReadString(RootKey, Subkey, IntToStr(I)));
Result := N > 0;
end;
//--------------------------------------------------------------------------------------------------
function RegDelList(const RootKey: HKEY; const Key: string; const ListName: string): Boolean;
var
I, N: Integer;
Subkey: string;
begin
Result := False;
Subkey := Key + '\' + ListName;
N := RegReadIntegerDef(RootKey, Subkey, cItems, -1);
if (N > 0) and RegDeleteEntry(RootKey, Subkey, cItems) then
for I := 1 to N do
begin
Result := RegDeleteEntry(RootKey, Subkey, IntToStr(I));
if not Result then
Break;
end;
end;
end.
|
{*******************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ XDR Translator for XML Schema }
{ }
{ Copyright (c) 2001-2002 Borland Software Corporation }
{ }
{*******************************************************}
unit XDRSchema;
interface
uses SysUtils, Classes, XMLSchema, XMLDOM, XMLDoc, XMLIntf;
type
{ TXDRImportTranslator }
TXDRImportTranslator = class(TXMLSchemaTranslator)
protected
XDRDoc: IXMLDocument;
SchemaPrefix: string;
DataTypePrefix: string;
ns: string;
procedure AddAttribute(XdrAttributedef: IDOMNode; XsdAttributeDefs: IXMLAttributeDefs);
procedure AddChildElement(XdrElement: IDOMNode; XsdElementDefs: IXMLElementDefs; Order: string);
procedure AddExtends(Extends: IDOMNode; XsdElementDefs: IXMLElementDefs; Order: string);
procedure Parse(XdrDom: IDomDocument);
procedure ParseAttributeDefinition(Parent: string; XdrAttributeDef: IDOMNode; XsdAttributeDefs: IXMLAttributeDefs);
procedure ParseElementDefinition(Parent: string; XdrElementDef: IDOMNode; XsdElementDefs: IXMLElementDefs);
procedure ParseGroup(Group: IDOMNode; XsdElementCompositors: IXMLElementCompositors);
procedure Translate(const FileName: WideString; const SchemaDef: IXMLSchemaDef); override;
end;
const
XDRExtension = '.xdr';
XDR_DataTypes = 'urn:w3-org:xmldatatypes';
XDR_Schema = 'urn:w3-org:xmlschema';
MSXDR_DataTypes = 'urn:schemas-microsoft-com:datatypes';
MSXDR_Schema = 'urn:schemas-microsoft-com:xml-data';
xdrElementType='ElementType';
xdrAttributeType='AttributeType';
xdrDescription='Description';
xdrElement='element';
xdrAttribute='attribute';
xdrGroup='group';
xdrExtends='extends';
xdrName='name';
xdrType='type';
xdrContent='content';
xdrContent_default='mixed';
xdrMixed='mixed';
xdrEmpty='empty';
xdrTextOnly='textOnly';
xdrEltOnly='eltOnly';
xdrModel='model';
xdrOpen='open';
xdrClosed='closed';
xdrOrder='order';
xdrSeq='seq';
xdrOne='one';
xdrAll='all';
xdrMany='many';
xdrRequired='required';
xdrRequired_default='no';
xdrYes='yes';
xdrNo='no';
xdrDefault='default';
xdrOccurs='occurs';
xdrMinOccurs='minOccurs';
xdrMaxOccurs='maxOccurs';
xdrOptional='optional';
xdrOneOrMore='oneOrMore';
xdrZeroOrMore='zeroOrMore';
xdrDatatype='datatype'; //only if no dt:type, and content=textonly
xdrMaxLength='maxLength';
xdrValues='values';
xdrMax='max';
xdrMin='min';
xdrMinExclusive='minExclusive';
xdrMaxExclusive='maxExclusive';
xdrString='string';
xdrId='id';
xdrIdref='idref';
xdrIdrefs='idrefs';
xdrEntity='entity';
xdrEntities='entities';
xdrNmtoken='nmtoken';
xdrNmtokens='nmtokens';
xdrNumber='number';
xdrInt='int';
xdrEnumeration='enumeration';
xdrNotation='notation';
xdrFixed='fixed';
xdrBoolean='boolean';
xdrDateTime='dateTime';
xdrDateTimeTz='dateTime.tz';
xdrDate='date';
xdrTime='time';
xdrTimetz='time.tz';
xdrI1='i1';
xdrByte='byte';
xdrI2='i2';
xdrI4='i4';
xdrI8='i8';
xdrUi1='ui1';
xdrUi2='ui2';
xdrUi4='ui4';
xdrUi8='ui8';
xdrR4='r4';
xdrR8='r8';
xdrFloat='float';
xdrChar='char';
xdrUuid='uuid';
xdrBinhex='bin.hex';
xdrBinbase64='bin.base64';
implementation
uses XMLSchemaTags, XMLConst;
{ TXDRImportTranslator }
procedure TXDRImportTranslator.Translate(const FileName: WideString;
const SchemaDef: IXMLSchemaDef);
begin
inherited;
XDRDoc := LoadXMLDocument(FileName);
Parse(XDRDoc.DOMDocument);
end;
function Split(Str: string; SubStr: string): TStringList;
var
I: Integer;
S, Tmp: string;
List: TStringList;
begin
List := TStringList.Create;
S := Str;
while Length(S) > 0 do
begin
I := Pos(SubStr, S);
if I = 0 then
begin
List.Add(S);
S := '';
end
else
begin
if I = 1 then
begin
List.Add('');
Delete(S, 1, Length(SubStr));
end
else
begin
Tmp := S;
Delete(Tmp, I, Length(Tmp));
List.Add(Tmp);
Delete(S, 1, I + Length(SubStr) - 1);
if Length(S) = 0 then
List.Add('');
end;
end;
end;
Result := List;
end;
function Tail(Str: string; SubStr: string): string;
var
I: Integer;
begin
I:= pos(SubStr, Str);
if i = 0 then
Result:= ''
else
begin
delete(Str,1,i+Length(SubStr)-1);
Result:= Str;
end;
end;
function Head(Str: string; SubStr: string; var TailStr: string): string;
var
I: Integer;
begin
i:= pos(SubStr, Str);
if I = 0 then
begin
Result:= Str;
TailStr:= '';
end
else
begin
TailStr:= Str;
delete(TailStr, 1, I+Length(SubStr)-1);
delete(Str, I, Length(Str));
Result:= Str;
end;
end;
function GetAttribute(Node:IDOMNode; Name:string):string;
var
attr:IDOMNode;
begin
Result:= '';
if (Node<>nil) and (Node.attributes <> nil) then
begin
attr:= Node.attributes.GetNamedItem(name);
if attr<>nil then
Result:= attr.nodeValue;
end;
end;
function XdrTypeToXsdType(DtType: string):string;
begin
if DtType = xdrId then Result:= xsdID else
if DtType = xdrIdRef then Result:= xsdIDREF else
if DtType = xdrIdRefs then Result:= xsdIDREFS else
if DtType = xdrEntity then Result:= xsdENTITY else
if DtType = xdrEntities then Result:= xsdENTITIES else
if DtType = xdrNmToken then Result:= xsdNMTOKEN else
if DtType = xdrNmTokens then Result:= xsdNMTOKENS else
if DtType = xdrNotation then Result:= xsdNOTATION else
// if DtType = xdrDateTimeTz then Result:= xsdInt else
// if DtType = xdrTimeTz then Result:= xsdInteger else
if DtType = xdrUuid then Result:= xsdAnyURI else
if DtType = xdrBinHex then Result:= xsdHexBinary else
if DtType = xdrBinBase64 then Result:= xsdBase64Binary else
if DtType = xdrString then Result:= xsdString else
if DtType = xdrChar then Result:= xsdByte else
if DtType = xdrI1 then Result:= xsdByte else
if DtType = xdrByte then Result:= xsdByte else
if DtType = xdrI2 then Result:= xsdShort else
if DtType = xdrI4 then Result:= xsdInteger else
if DtType = xdrInt then Result:= xsdInteger else
if DtType = XdrI8 then Result:= xsdLong else
if DtType = xdrUi1 then Result:= xsdUnsignedByte else
if DtType = xdrUi2 then Result:= xsdUnsignedShort else
if DtType = xdrUi4 then Result:= xsdUnsignedInt else
if DtType = xdrUi8 then Result:= xsdUnsignedLong else
// if DtType = xdrR4 then Result:= xsd else
if DtType = xdrR8 then Result:= xsdDouble else
if DtType = xdrFloat then Result:= xsdFloat else
if DtType = xdrNumber then Result:= xsdFloat else
if DtType = xdrFixed then Result:= xsdDecimal else
if DtType = xdrBoolean then Result:= xsdBoolean else
if DtType = xdrDate then Result:= xsdDate else
if DtType = xdrDateTime then Result:= xdrDateTime else
if DtType = xdrTime then Result:= xsdTime else
// if DtType = dt_options then Result:= Xsd_Enumerations else
// if DtType = dt_Unknown then Result:= xsdString else
Result:= xsdString;
end;
procedure DetermineOccurence(Occurs: string; var MinOccurs: string; var MaxOccurs: string; Order: string);
begin
if (Occurs <> '') then
begin
if (pos(':', Occurs) > 0) then
begin
MinOccurs:= Head(Occurs,':', MaxOccurs);
end
else
if Occurs=xdroneorMore then
begin
MinOccurs:= '1';
MaxOccurs:= SUnbounded;
end
else
if Occurs= xdrZeroOrMore then
begin
MinOccurs:= '0';
MaxOccurs:= SUnbounded;
end
else
if Occurs=xdrOptional then
begin
MinOccurs:= '0';
MaxOccurs:= '1';
end;
end;
if Order=xdrMany then
begin
MinOccurs:= '0';
MaxOccurs:= SUnbounded;
end;
if (MaxOccurs='*') or (MaxOccurs='+') then
MaxOccurs:= SUnbounded;
end;
//parse an expanded xdr-string into a nodeinfo-list
procedure TXDRImportTranslator.Parse(XdrDom: IDomDocument);
var
I: integer;
DtTypes, DtValues: string;
Root, SchemaNode, AttributeNode, ChildNode: IDOMNode;
AttributeName, AttributeValue, ChildName: string;
SchemaName, Prefix, RootName, Ns: string;
begin
try
SchemaPrefix:= '';
DataTypePrefix:= 'dt:';
DtTypes:= 'dt:type';
DtValues:= 'dt:values';
Ns:= '';
Root:= XdrDom.DocumentElement;
if (Root = nil) then exit;
SchemaName:= Root.LocalName;
if pos('Schema', SchemaName) > 0 then
begin
SchemaNode:= Root;
//Get any prefix
if pos(':', SchemaName) > 0 then
SchemaPrefix:= Head(RootName, ':', SchemaName) + ':'
else
SchemaPrefix:= '';
RootName:= GetAttribute(Root, xdrName);
for I:= 0 to Root.attributes.length-1 do
begin
AttributeNode:= Root.Attributes.item[I];
AttributeName:= AttributeNode.NodeName;
if pos('xmlns', AttributeName)> 0 then
begin
if pos(':', AttributeName) > 0 then
begin
Prefix:= Tail(AttributeName, ':') +':';
end
else
Prefix:= '';
AttributeValue:= AttributeNode.NodeValue;
if AttributeValue=MSXDR_Schema then
SchemaPrefix:= Prefix;
if AttributeValue=MSXDR_DataTypes then
DataTypePrefix:= Prefix;
end;
end;
//Process all children
for I:= 0 to SchemaNode.ChildNodes.Length-1 do
begin
ChildNode:= SchemaNode.ChildNodes.item[I];
ChildName:= ChildNode.LocalName;
if ChildName = xdrElementType then
begin
ParseElementDefinition('', ChildNode, SchemaDef.ElementDefs);
end else
if ChildName = xdrAttributeType then
begin
ParseAttributeDefinition('', ChildNode, SchemaDef.AttributeDefs);
end else
if ChildName = xdrNotation then
begin
end else
if ChildName = xdrEntity then
begin
end else
if ChildName = xdrDescription then
begin
end;
end;
end;
finally
end;
end;
procedure TXDRImportTranslator.ParseElementDefinition(Parent:string;
XdrElementDef: IDOMNode; XsdElementDefs: IXMLElementDefs);
var
I, J: Integer;
Name, Content, Order, Model: string;
DtType, DtValues, DtMaxLength, DtMin, DtMax: string;
DtNode, XdrChildNode : IDOMNode;
ChildName: string;
XsdType: string;
ComplexTypeDef: IXMLComplexTypeDef;
SimpleTypeDef: IXMLSimpleTypeDef;
Compositor: IXMLElementCompositor;
begin
Name := GetAttribute(XdrElementDef, xdrname);
if Name = '' then exit;
Content:= GetAttribute(XdrElementDef, xdrcontent);
Order:= GetAttribute(XdrElementDef, xdrorder);
Model:= GetAttribute(XdrElementDef, xdrmodel);
if Content = xdrTextOnly then
begin
DtNode:= nil;
DtType:= GetAttribute(XdrElementDef, DataTypePrefix+'type');
if DtType<>'' then
DtNode:= XdrElementDef
else
if XdrElementDef.ChildNodes.Length>0 then
begin //contains datatype element
for J:= 0 to XdrElementDef.ChildNodes.Length-1 do
begin
XdrChildNode:= XdrElementDef.ChildNodes.item[J];
if XdrChildNode.LocalName = xdrDatatype then
begin
DtNode:= XdrChildNode;
DtType:= GetAttribute(DtNode, DataTypePrefix+'type');
if DtType='' then
DtNode:= nil;
break;
end;
end;
end;
if DtNode <> nil then
begin //defaults
DtValues:= GetAttribute(DtNode, DataTypePrefix+xdrvalues);
DtMaxLength:= GetAttribute(DtNode, DataTypePrefix+xdrMaxLength);
DtMin:= GetAttribute(DtNode, DataTypePrefix+xdrMin);
DtMax:= GetAttribute(DtNode, DataTypePrefix+xdrMax);
XsdType:= XdrTypeToXsdType(DtType); //XdrTypeToCdsType(pInfo, DtType, DtMaxLength, DtValues);
end
else
XsdType:= xsdString; //convert DtType;
XsdElementDefs.Add(Name, Name+'Type');
SimpleTypeDef:= SchemaDef.SimpleTypes.Add(Name+'Type', XsdType);
with SimpleTypeDef do
begin
if DtMaxLength <> '' then
MaxLength:= DtMaxLength;
if DtMin <> '' then
MinInclusive:= DtMin;
if DtMax <> '' then
MaxInclusive:= DtMax;
if DtValues <> '' then
begin
//enumeration ? Value:= DtValues;
end;
end;
end//textOnly
else
begin //Elements-only
XsdElementDefs.Add(Name, Name+'Type');
ComplexTypeDef:= SchemaDef.ComplexTypes.Add(Name+'Type');
if Order = xdrOne then
Compositor:= ComplexTypeDef.ElementCompositors.Add(ctChoice)
else Compositor:= nil;
for I:= 0 to XdrElementdef.ChildNodes.Length-1 do
begin
XdrChildNode:= XdrElementDef.childNodes.item[I];
ChildName:= XdrChildNode.LocalName;
if ChildName = xdrElementType then
begin
if Compositor <> nil then
ParseElementDefinition(Name, XdrChildNode, Compositor.ElementDefs)
else
ParseElementDefinition(Name, XdrChildNode, ComplexTypeDef.ElementDefs);
end
else
if ChildName = xdrAttributeType then
begin
ParseAttributeDefinition(Name, XdrChildNode, ComplexTypeDef.AttributeDefs);
end
else
if ChildName = xdrElement then
begin
if Compositor <> nil then
AddChildElement(XdrChildNode, Compositor.ElementDefs, Order)
else
AddChildElement(XdrChildNode, ComplexTypeDef.ElementDefs, Order)
end
else
if ChildName = xdrAttribute then
begin
AddAttribute(XdrChildNode, ComplexTypeDef.AttributeDefs);
end
else
if ChildName = xdrGroup then
begin
if Compositor <> nil then
ParseGroup(XdrChildNode, Compositor.Compositors)
else
ParseGroup(XdrChildNode, ComplexTypeDef.ElementCompositors);
end
else
if ChildName = xdrExtends then
begin
if Compositor <> nil then
AddExtends(XdrChildNode, Compositor.ElementDefs, Order)
else
AddExtends(XdrChildNode, ComplexTypeDef.ElementDefs, Order)
end;
end;
end;//Elementsonly
end;
procedure TXDRImportTranslator.ParseAttributeDefinition(Parent: string;
XdrAttributeDef: IDOMNode; XsdAttributeDefs: IXMLAttributeDefs);
var
I: Integer;
Name : string;
Required, DefValue, DtType, DtValues, DtMaxLength, DtMin, DtMax: string;
DtNode, ChildNode: IDOMNode;
OList: TStringList;
XdrChildName: string;
XsdType: string;
AttributeDef: IXMLAttributeDef;
begin
Name:= GetAttribute(XdrAttributeDef, xdrName);
Dttype:= GetAttribute(XdrAttributeDef, DataTypePrefix+'type');
DtNode:= nil;
if DtType<> '' then
DtNode:= XdrAttributeDef
else
begin
for I:= 0 to XdrAttributeDef.ChildNodes.Length-1 do
begin
ChildNode:= XdrAttributeDef.Childnodes.Item[I];
XdrChildName:= ChildNode.LocalName;
if XdrChildName = xdrDatatype then
begin
DtNode:= ChildNode;
break;
end
end;
end;
if DtNode<>nil then
begin
DtType:= GetAttribute(DtNode, DataTypePrefix+'type');
DtValues:= GetAttribute(DtNode, DataTypePrefix+xdrvalues);
DtMaxLength:= GetAttribute(DtNode, DataTypePrefix+xdrmaxLength);
DtMin:= GetAttribute(DtNode, DataTypePrefix+xdrMin);
DtMax:= GetAttribute(DtNode, DataTypePrefix+xdrMax);
XsdType:= XdrTypeToXsdType(DtType);
end
else
XsdType:= xsdString;
Required := GetAttribute(XdrAttributeDef, SchemaPrefix+xdrRequired);
DefValue := GetAttribute(XdrAttributeDef, SchemaPrefix+xdrDefault);
if DtValues<> '' then
AttributeDef := xsdAttributeDefs.Add(Name, true, XsdType)
else
AttributeDef := xsdAttributeDefs.Add(Name, XsdType);
with AttributeDef do
begin
if DefValue <> '' then
begin
Default := DefValue;
end;
if Required = 'yes' then //yes ?
begin
Use := SRequired;
end;
//FixedValue
if (DtType = XdrEnumeration) and (DtValues <> '') then
begin
OList:= Split(DtValues, ' ');
try
for I:= 0 to OList.Count-1 do
begin
DataType.Enumerations.Add(OList[I]);
end;
finally
OList.Free;
end;
end;
end;
end;
procedure TXDRImportTranslator.ParseGroup(Group: IDOMNode; XsdElementCompositors: IXMLElementCompositors);
var
I: integer;
ChildNode: IDOMNode;
ChildName, GroupOrder, groupOccurs, GroupMinOccurs, GroupMaxOccurs: string;
CompType: TCompositorType;
Compositor: IXMLElementCompositor;
begin
GroupOrder:= GetAttribute(Group, xdrOrder);
GroupOccurs:= GetAttribute(Group, xdrOccurs);
GroupMinOccurs:= GetAttribute(Group, xdrMinOccurs);
GroupMaxOccurs:= GetAttribute(Group, xdrMaxOccurs);
if GroupOrder = xdrSeq then
CompType:= ctSequence
else
if GroupOrder = xdrOne then
CompType:= ctChoice
else
if GroupOrder = xdrAll then
CompType:= ctAll
else
if GroupOrder = xdrMany then
CompType:= ctSequence
else
CompType:= ctSequence;
Compositor:= XsdElementCompositors.Add(CompType);
DetermineOccurence(GroupOccurs, GroupMinOccurs, GroupMaxOccurs, GroupOrder);
if GroupMinOccurs = '' then GroupMinOccurs:= '1';
if GroupMaxOccurs = '' then GroupMaxOccurs:= '1';
Compositor.MinOccurs:= GroupMinOccurs;
Compositor.MaxOccurs:= GroupMaxOccurs;
for I:= 0 to Group.ChildNodes.Length-1 do
begin
ChildNode:= Group.ChildNodes.item[I];
ChildName:= ChildNode.LocalName;
if ChildName = xdrElement then
begin
AddChildElement(ChildNode, Compositor.ElementDefs, GroupOrder);
end
else
if ChildName = xdrGroup then
begin
ParseGroup(ChildNode, Compositor.Compositors);
end
else
if ChildName = xdrExtends then
begin
AddExtends(ChildNode, Compositor.ElementDefs, GroupOrder);
end;
end;
end;
procedure TXDRImportTranslator.AddChildElement(XdrElement: IDOMNode; XsdElementDefs: IXMLElementDefs; Order: string);
var
Name: string;
MinOccurs, MaxOccurs, Occurs: string;
ChildElement: IXMLElementDef;
begin
Name:= GetAttribute(XdrElement, 'type');
MinOccurs:= GetAttribute(XdrElement, xdrMinOccurs);
MaxOccurs:= GetAttribute(XdrElement, xdrMaxOccurs);
Occurs:= GetAttribute(XdrElement, xdrOccurs);
DetermineOccurence(Occurs, MinOccurs, MaxOccurs, Order);
if MinOccurs = '' then MinOccurs:= '1';
if MaxOccurs = '' then MaxOccurs:= '1';
ChildElement:= XsdElementdefs.Add(Name);
ChildElement.MinOccurs:= MinOccurs;
ChildElement.MaxOccurs:= MaxOccurs;
end;
procedure TXDRImportTranslator.AddAttribute(XdrAttributeDef: IDOMNode; XsdAttributeDefs: IXMLAttributeDefs);
var
Name: string;
DefValue, Required: string;
begin
Name:= GetAttribute(XdrAttributeDef, Stype);
DefValue:= GetAttribute(XdrAttributeDef, xdrDefault);
Required:= GetAttribute(XdrAttributeDef, xdrRequired);
with XsdAttributeDefs.Add(Name) do
begin
if DefValue <> '' then
begin
Default := DefValue;
end;
if Required <> '' then
begin
Use:= SRequired;
end;
//Fixed
end;
end;
procedure TXDRImportTranslator.AddExtends(Extends: IDOMNode; XsdElementDefs: IXMLElementDefs; Order: string);
var
Name: string;
begin
Name:= GetAttribute(Extends, Stype);
XsdElementDefs.Add(Name);
end;
var
TranslatorFactory: IXMLSchemaTranslatorFactory;
initialization
TranslatorFactory:= TXMLSchemaTranslatorFactory.Create(TXDRImportTranslator,
nil, XDRExtension, SXDRTransDesc);
RegisterSchemaTranslator(TranslatorFactory);
finalization
UnRegisterSchemaTranslator(TranslatorFactory);
end.
|
unit ProgressBarForm2;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, RootForm, cxGraphics, cxControls,
cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, dxSkinsCore,
dxSkinBlack, dxSkinBlue, dxSkinBlueprint, dxSkinCaramel, dxSkinCoffee,
dxSkinDarkRoom, dxSkinDarkSide, dxSkinDevExpressDarkStyle,
dxSkinDevExpressStyle, dxSkinFoggy, dxSkinGlassOceans, dxSkinHighContrast,
dxSkiniMaginary, dxSkinLilian, dxSkinLiquidSky, dxSkinLondonLiquidSky,
dxSkinMcSkin, dxSkinMetropolis, dxSkinMetropolisDark, dxSkinMoneyTwins,
dxSkinOffice2007Black, dxSkinOffice2007Blue, dxSkinOffice2007Green,
dxSkinOffice2007Pink, dxSkinOffice2007Silver, dxSkinOffice2010Black,
dxSkinOffice2010Blue, dxSkinOffice2010Silver, dxSkinOffice2013DarkGray,
dxSkinOffice2013LightGray, dxSkinOffice2013White, dxSkinOffice2016Colorful,
dxSkinOffice2016Dark, dxSkinPumpkin, dxSkinSeven, dxSkinSevenClassic,
dxSkinSharp, dxSkinSharpPlus, dxSkinSilver, dxSkinSpringTime, dxSkinStardust,
dxSkinSummer2008, dxSkinTheAsphaltWorld, dxSkinsDefaultPainters,
dxSkinValentine, dxSkinVisualStudio2013Blue, dxSkinVisualStudio2013Dark,
dxSkinVisualStudio2013Light, dxSkinVS2010, dxSkinWhiteprint,
dxSkinXmas2008Blue, cxLabel, cxProgressBar, ProgressInfo, ProcRefUnit,
ExcelDataModule, System.Contnrs;
type
TfrmProgressBar2 = class(TfrmRoot)
pbRead: TcxProgressBar;
lRead: TcxLabel;
lWrite: TcxLabel;
pbWrite: TcxProgressBar;
private
FReadLabel: string;
FWriteLabel: string;
procedure DoAfterLoadSheet(ASender: TObject);
procedure DoBeforeLoadSheet(ASender: TObject);
procedure DoOnTotalProgress(ASender: TObject);
{ Private declarations }
protected
property ReadLabel: string read FReadLabel write FReadLabel;
property WriteLabel: string read FWriteLabel write FWriteLabel;
public
constructor Create(AOwner: TComponent); override;
class procedure Process(AExcelDM: TExcelDM;
const AFileName, ACaption, ARowSubstitute: string); static;
procedure UpdateReadStatistic(AProgressInfo: TProgressInfo);
procedure UpdateWriteStatistic(AProgressInfo: TProgressInfo);
{ Public declarations }
end;
implementation
uses NotifyEvents;
Var AfrmProgressBar: TfrmProgressBar2;
{$R *.dfm}
constructor TfrmProgressBar2.Create(AOwner: TComponent);
begin
inherited;
FReadLabel := 'Прочитано строк';
FWriteLabel := 'Сохранено записей'
end;
procedure TfrmProgressBar2.DoAfterLoadSheet(ASender: TObject);
begin
// Прямем окно с прогрессом
Assert(AfrmProgressBar <> nil);
AfrmProgressBar.Hide;
end;
procedure TfrmProgressBar2.DoBeforeLoadSheet(ASender: TObject);
begin
Assert(AfrmProgressBar <> nil);
AfrmProgressBar.Show; // Показываем окно с прогрессом
end;
procedure TfrmProgressBar2.DoOnTotalProgress(ASender: TObject);
begin
Assert(AfrmProgressBar <> nil);
AfrmProgressBar.UpdateReadStatistic(ASender as TProgressInfo);
end;
class procedure TfrmProgressBar2.Process(AExcelDM: TExcelDM;
const AFileName, ACaption, ARowSubstitute: string);
var
e: TNotifyEventWrap;
L: TObjectList;
begin
AfrmProgressBar := TfrmProgressBar2.Create(nil);
try
if not ACaption.IsEmpty then
AfrmProgressBar.Caption := ACaption;
if not ARowSubstitute.IsEmpty then
AfrmProgressBar.ReadLabel := Format('Прочитано %s', [ARowSubstitute]);
L := TObjectList.Create;
try
TNotifyEventWrap.Create(AExcelDM.BeforeLoadSheet, AfrmProgressBar.DoBeforeLoadSheet, L);
e := TNotifyEventWrap.Create(AExcelDM.AfterLoadSheet, AfrmProgressBar.DoAfterLoadSheet, L);
// Хотим первыми получать извещение об этом событии
e.Index := 0;
TNotifyEventWrap.Create(AExcelDM.OnTotalProgress, AfrmProgressBar.DoOnTotalProgress, L);
AExcelDM.LoadExcelFile2(AFileName);
finally
FreeAndNil(L)
end;
finally
FreeAndNil(AfrmProgressBar);
end;
end;
procedure TfrmProgressBar2.UpdateReadStatistic(AProgressInfo: TProgressInfo);
begin
Assert(AProgressInfo <> nil);
lRead.Caption := Format('%s: %d из %d',
[FReadLabel, AProgressInfo.ProcessRecords,
AProgressInfo.TotalRecords]);
pbRead.Position := AProgressInfo.Position;
Application.ProcessMessages;
end;
procedure TfrmProgressBar2.UpdateWriteStatistic(AProgressInfo: TProgressInfo);
begin
lWrite.Caption := Format('%s: %d из %d',
[FWriteLabel, AProgressInfo.ProcessRecords,
AProgressInfo.TotalRecords]);
pbWrite.Position := AProgressInfo.Position;
Application.ProcessMessages;
end;
end.
|
unit SHL_ProcessStream; // SemVersion: 0.2.0
// Contains TProcessStream class for creating processes and piping data
// Currently only for windows, this is quick&dirty approach...
// Changelog:
// 0.1.0 - test version
// 0.2.0 - priority
// TODO:
// - follow Lazarus's TProcess?
// - more control
// - error codes
interface // SpyroHackingLib is licensed under WTFPL
uses
Windows, SysUtils, Classes, SHL_Types;
type
TProcessStream = class(TStream)
constructor Create(const ExecutableName, CommandLine, WorkDirectory: WideString; ReadPipe, WritePipe: Boolean; ErrPipe: Boolean = False; ToStd: Boolean = True);
destructor Destroy(); override;
private
FName, FComm, FDir: WideString;
OutRead, OutWrite, InRead, InWrite, ErrRead, ErrWrite: THandle;
FProcHand: THandle;
public
StdIn, StdOut, StdErr: THandleStream;
function IsRunning(Timeout: Integer = 0): Boolean;
procedure SetPriority(Prio: Cardinal);
function Write(const Buffer; Count: Longint): Longint; override;
function Read(var Buffer; Count: Longint): Longint; override;
function Seek(Offset: Longint; Origin: Word): Longint; override;
procedure Close(Read: Boolean; Write: Boolean = False; Error: Boolean = False);
end;
implementation
uses
Math;
constructor TProcessStream.Create(const ExecutableName, CommandLine, WorkDirectory: WideString; ReadPipe, WritePipe: Boolean; ErrPipe: Boolean = False; ToStd: Boolean = True);
var
SI: STARTUPINFO;
PI: PROCESS_INFORMATION;
SA: SECURITY_ATTRIBUTES;
Err: Integer;
PDir: PWideChar;
begin
Err := 0;
FName := ExecutableName + #0#0;
FComm := CommandLine + #0#0;
if WorkDirectory = '' then
PDir := nil
else
begin
FDir := WorkDirectory + #0#0;
PDir := PWideChar(FDir);
end;
ZeroMemory(@SI, SizeOf(STARTUPINFO));
ZeroMemory(@PI, SizeOf(PROCESS_INFORMATION));
ZeroMemory(@SA, SizeOf(SECURITY_ATTRIBUTES));
SI.cb := SizeOf(STARTUPINFO);
SA.nLength := SizeOf(SECURITY_ATTRIBUTES);
SA.bInheritHandle := True;
if ReadPipe then
CreatePipe(InRead, InWrite, @SA, 0);
if WritePipe then
CreatePipe(OutRead, OutWrite, @SA, 0);
if ErrPipe then
CreatePipe(ErrRead, ErrWrite, @SA, 0);
if ReadPipe then
SetHandleInformation(InWrite, HANDLE_FLAG_INHERIT, 0);
if WritePipe then
SetHandleInformation(OutRead, HANDLE_FLAG_INHERIT, 0);
if ErrPipe then
SetHandleInformation(ErrRead, HANDLE_FLAG_INHERIT, 0);
if ReadPipe then
SI.hStdInput := InRead
else if ToStd then
SI.hStdInput := GetStdHandle(STD_INPUT_HANDLE);
if WritePipe then
SI.hStdOutput := OutWrite
else if ToStd then
SI.hStdOutput := GetStdHandle(STD_OUTPUT_HANDLE);
if ErrPipe then
SI.hStdError := ErrWrite
else if ToStd then
SI.hStdError := GetStdHandle(STD_ERROR_HANDLE);
SI.dwFlags := STARTF_USESTDHANDLES or STARTF_USESHOWWINDOW;
SI.wShowWindow := SW_HIDE;
if not CreateProcessW(PWideChar(FName), PWideChar(FComm), nil, nil, True, CREATE_NO_WINDOW, nil, PDir, SI, PI) then
Err := GetLastError();
if ReadPipe then
CloseHandle(InRead);
if WritePipe then
CloseHandle(OutWrite);
if ErrPipe then
CloseHandle(ErrWrite);
if PI.dwProcessId = 0 then
raise Exception.Create(IntToStr(Err));
if ReadPipe then
StdIn := THandleStream.Create(InWrite);
if WritePipe then
StdOut := THandleStream.Create(OutRead);
if ErrPipe then
StdErr := THandleStream.Create(ErrRead);
CloseHandle(PI.hThread);
FProcHand := PI.hProcess;
end;
destructor TProcessStream.Destroy();
begin
Close(True, True, True);
if FProcHand <> 0 then
if IsRunning() then
TerminateProcess(FProcHand, 1);
CloseHandle(FProcHand);
end;
function TProcessStream.IsRunning(Timeout: Integer = 0): Boolean;
begin
Result := (WaitForSingleObject(FProcHand, Timeout) = WAIT_TIMEOUT);
end;
procedure TProcessStream.SetPriority(Prio: Cardinal);
begin
SetPriorityClass(FProcHand, Prio);
end;
procedure TProcessStream.Close(Read: Boolean; Write: Boolean = False; Error: Boolean = False);
begin
if Read and (StdIn <> nil) then
begin
StdIn.Free();
CloseHandle(InWrite);
StdIn := nil;
InWrite := 0;
end;
if Write and (StdOut <> nil) then
begin
StdOut.Free();
CloseHandle(OutRead);
StdOut := nil;
OutRead := 0;
end;
if Error and (StdErr <> nil) then
begin
StdErr.Free();
CloseHandle(ErrRead);
StdErr := nil;
ErrRead := 0;
end;
end;
function TProcessStream.Write(const Buffer; Count: Longint): Longint;
begin
if StdIn <> nil then
Result := StdIn.Write(Buffer, Count)
else
Result := 0;
end;
function TProcessStream.Read(var Buffer; Count: Longint): Longint;
begin
if StdOut <> nil then
Result := StdOut.Read(Buffer, Count)
else
Result := 0;
end;
function TProcessStream.Seek(Offset: Longint; Origin: Word): Longint;
begin
Result := 0;
end;
end.
|
unit BLog4D;
interface uses Log4D,Classes, Windows, SysUtils, BDebug;
type TBLog4DInfo = record
FLoggerName: string;
FUnitName : string;
FMethodName: string;
end;
procedure BLog4DConfigure(APropertyFileName: String);
// Main Logging Methods
procedure LogFatal(ALogMessage: string; const ALoggerName : string=''; const Ex: Exception = nil);
procedure LogError(ALogMessage: string; const ALoggerName : string=''; const Ex: Exception = nil);
procedure LogWarn (ALogMessage: string; const ALoggerName : string=''; const Ex: Exception = nil);
procedure LogInfo (ALogMessage: string; const ALoggerName : string=''; const Ex: Exception = nil);
procedure LogDebug(ALogMessage: string; const ALoggerName : string=''; const Ex: Exception = nil); overload;
procedure LogDebug(ALogMessage: string; ALogInfo: TBLog4DInfo; const Ex: Exception = nil); overload;
procedure InitDefaultLogFile;
const
GIT_TEMP_LOG_PATH = 'GiT\realax\Log\';
LOG_SETTINGS_FILENAME = 'logging.properties';
FALLBACK_SETTING = 'FALLBACK_SETTING';
GIT_FALLBACK_LOGGER = 'GIT_CONSOLE_LOGGER';
LOGGER_TOM = 'ToMLogger';
LOGGER_CONSOLE = 'DefaultConsoleLogger';
var
BLog4D_CurrentLogPropertiesFile : string;
BLog4D_CurrentLogger : TLogLogger;
implementation uses Dialogs;
procedure SetCurrentLogger(ALogger: string);
begin
if(Length(ALogger) > 0) then
begin
//LogDebug('@BLog4D.SetCurrentLogger: Setting Logger To [' + ALogger +']');// StackOverFlow
BLog4D_CurrentLogger := LogLog.GetLogger(ALogger);
end;
end;
// Main Logging Methods
procedure LogFatal(ALogMessage: string; const ALoggerName : string=''; const Ex: Exception = nil);
begin
SetCurrentLogger(ALoggerName);
BLog4D_CurrentLogger.Fatal(ALogMessage,Ex);
end;
procedure LogError(ALogMessage: string; const ALoggerName : string=''; const Ex: Exception = nil);
begin
SetCurrentLogger(ALoggerName);
BLog4D_CurrentLogger.Error(ALogMessage,Ex);
end;
procedure LogWarn (ALogMessage: string; const ALoggerName : string=''; const Ex: Exception = nil);
begin
SetCurrentLogger(ALoggerName);
BLog4D_CurrentLogger.Warn(ALogMessage,Ex);
end;
procedure LogInfo (ALogMessage: string; const ALoggerName : string=''; const Ex: Exception = nil);
begin
SetCurrentLogger(ALoggerName);
BLog4D_CurrentLogger.Info(ALogMessage,Ex);
end;
procedure LogDebug(ALogMessage: string; const ALoggerName : string=''; const Ex: Exception = nil);
begin
SetCurrentLogger(ALoggerName);
BLog4D_CurrentLogger.Debug(ALogMessage,Ex);
end;
procedure LogDebug(ALogMessage: string; ALogInfo: TBLog4DInfo; const Ex: Exception = nil);
begin
LogDebug('['+ALogInfo.FUnitName+'] ['+ALogInfo.FMethodName+'] :' + ALogMessage,ALogInfo.FLoggerName,Ex);
end;
procedure BLog4DConfigure(APropertyFileName: String);
begin
TLogPropertyConfigurator.ResetConfiguration;
if ((Assigned(BLog4D_CurrentLogger)) AND (Length(BLog4D_CurrentLogger.Name) > 0)) then
begin
LogDebug('@BLog4DConfigure: Switching from [' + BLog4D_CurrentLogPropertiesFile + '] to ['+APropertyFileName+']');
end;
if ( (not(AnsiCompareStr(APropertyFileName,FALLBACK_SETTING) = 0))
AND (FileExists(APropertyFileName))
) then
begin
TLogPropertyConfigurator.Configure(APropertyFileName);
//LogLog.Hierarchy.EmitNoAppenderWarning(TLogLogger.GetRootLogger);
BLog4D_CurrentLogPropertiesFile := APropertyFileName;
BLog4D_CurrentLogger := TLogLogger.GetLogger(LOGGER_CONSOLE);
end
else
begin
TLogBasicConfigurator.Configure();
BLog4D_CurrentLogPropertiesFile := '';
BLog4D_CurrentLogger := TLogLogger.GetLogger(GIT_FALLBACK_LOGGER);
end;
LogDebug('@BLog4DConfigure: CurrentLogger is ['+BLog4D_CurrentLogger.Name+']');
end;
function CreateDefaultDirStructure(ATempDir: string): Boolean;
begin
Result := ForceDirectories(ATempDir);
end;
procedure InitDefaultLogFile;
var
Stream: TResourceStream;
ADest: string;
FTmpDir: string;
begin
try
Stream := TResourceStream.Create(hInstance,'LOGSETTINGS', RT_RCDATA);
try
FTmpDir := GetTempVerzeichnis;
ADest := FTmpDir + GIT_TEMP_LOG_PATH + LOG_SETTINGS_FILENAME;
if not FileExists(ADest) then
begin
if not DirectoryExists(ExtractFilePath(ADest)) then
begin
if CreateDefaultDirStructure(ExtractFilePath(ADest)) then
begin
Stream.SaveToFile(ADest);
end;
end;
end;
if(FileExists(ADest)) then
begin
BLog4DConfigure(ADest);
end
else
begin
end;
except on E:Exception do
begin
BLog4DConfigure(FALLBACK_SETTING);
LogError(E.Message);
end;
end;
finally
Stream.Free;
end;
end;
// TODO Als Parameter einbindbar machen;
function sDbgFN: string;
var
buffer: array[0..255] of char;
begin
GetModuleFilename(HInstance, addr(buffer), sizeof(buffer));
Result := lowercase(buffer);
end;
initialization
InitDefaultLogFile;
finalization
BLog4D_CurrentLogger.Free;
end.
|
unit Optimizer.SystemRestore;
interface
uses
SysUtils,
OS.EnvironmentVariable, Optimizer.Template, Global.LanguageString,
OS.ProcessOpener, Registry.Helper;
type
TSystemRestoreOptimizer = class(TOptimizationUnit)
public
function IsOptional: Boolean; override;
function IsCompatible: Boolean; override;
function IsApplied: Boolean; override;
function GetName: String; override;
procedure Apply; override;
procedure Undo; override;
end;
implementation
function TSystemRestoreOptimizer.IsOptional: Boolean;
begin
exit(true);
end;
function TSystemRestoreOptimizer.IsCompatible: Boolean;
begin
exit(true);
end;
function TSystemRestoreOptimizer.IsApplied: Boolean;
begin
result :=
((NSTRegistry.GetRegInt(NSTRegistry.LegacyPathToNew('LM',
'SOFTWARE\Microsoft\Windows NT\CurrentVersion\SystemRestore',
'RPSessionInterval')) = 0)) or
((NSTRegistry.GetRegInt(NSTRegistry.LegacyPathToNew('LM',
'SOFTWARE\Microsoft\Windows NT\CurrentVersion\SystemRestore',
'DisableConfig')) = 1) and
(NSTRegistry.GetRegInt(NSTRegistry.LegacyPathToNew('LM',
'SOFTWARE\Microsoft\Windows NT\CurrentVersion\SystemRestore',
'DisableSR')) = 1));
end;
function TSystemRestoreOptimizer.GetName: String;
begin
exit(CapOptRes[CurrLang]);
end;
procedure TSystemRestoreOptimizer.Apply;
var
ProcOutput: String;
begin
ProcOutput :=
string(ProcessOpener.OpenProcWithOutput(
EnvironmentVariable.WinDir + '\System32',
'schtasks /change /TN "Microsoft\Windows\SystemRestore\SR" /disable'));
NSTRegistry.SetRegInt(NSTRegistry.LegacyPathToNew(
'LM', 'SOFTWARE\Microsoft\Windows NT\CurrentVersion\' +
'SystemRestore', 'RPSessionInterval'), 0);
NSTRegistry.SetRegInt(NSTRegistry.LegacyPathToNew(
'LM', 'SOFTWARE\Microsoft\Windows NT\CurrentVersion' +
'\SystemRestore', 'DisableConfig'), 1);
NSTRegistry.SetRegInt(NSTRegistry.LegacyPathToNew(
'LM', 'SOFTWARE\Microsoft\Windows NT\CurrentVersion\' +
'SystemRestore', 'DisableSR'), 1);
end;
procedure TSystemRestoreOptimizer.Undo;
var
ProcOutput: String;
begin
ProcOutput :=
string(ProcessOpener.OpenProcWithOutput(
EnvironmentVariable.WinDir + '\System32',
'schtasks /change /TN "Microsoft\Windows\SystemRestore\SR" /enable'));
NSTRegistry.SetRegInt(NSTRegistry.LegacyPathToNew(
'LM', 'SOFTWARE\Microsoft\Windows NT\CurrentVersion\' +
'SystemRestore', 'RPSessionInterval'), 1);
NSTRegistry.SetRegInt(NSTRegistry.LegacyPathToNew(
'LM', 'SOFTWARE\Microsoft\Windows NT\CurrentVersion' +
'\SystemRestore', 'DisableConfig'), 0);
NSTRegistry.SetRegInt(NSTRegistry.LegacyPathToNew(
'LM', 'SOFTWARE\Microsoft\Windows NT\CurrentVersion\' +
'SystemRestore', 'DisableSR'), 0);
end;
end.
|
{***********************************************************************************************************************
*
* TERRA Game Engine
* ==========================================
*
* Copyright (C) 2003, 2014 by SÚrgio Flores (relfos@gmail.com)
*
***********************************************************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
**********************************************************************************************************************
* TERRA_HTTP
* Implements HTTP protocol
***********************************************************************************************************************
}
Unit TERRA_HTTP;
{$I terra.inc}
Interface
Uses SysUtils, TERRA_Utils, TERRA_Application, TERRA_OS, TERRA_IO, TERRA_Sockets,
TERRA_FileIO, TERRA_FileUtils, TERRA_FileManager;
Const
HTTPProtocol='HTTP';
FILEProtocol='FILE';
HTTPPort = 80;
BufferSize = 1024;
DefaultClientName = 'TERRA Downloader v1.1';
ConnectionTimeOut = 5000;
httpOk = 0;
httpInvalidURL = 1;
httpInvalidProtocol = 2;
httpNotFound = 3;
httpConnectionFailed = 4;
httpConnectionTimeOut = 5;
httpInvalidStream = 6;
Type
HeaderTag = Record
Name:AnsiString;
Value:AnsiString;
End;
HTTPDownloader = Class;
DownloadCallback = Procedure (Download:HTTPDownloader); Cdecl;
HTTPDownloader = Class(TERRAObject)
Protected
_URL:AnsiString;
_FileName:AnsiString;
_ErrorCode:Integer;
_Offset:Integer;
_Stream:Stream;
_Target:Stream;
_TargetName:AnsiString;
_Callback:DownloadCallback;
_Downloading:Boolean;
_TotalSize:Integer;
_Read:Integer;
_Response:AnsiString;
_Buffer:Pointer;
_Protocol:AnsiString;
_HostName:AnsiString;
_Tags:Array Of HeaderTag;
_TagCount:Integer;
_Progress:Integer;
_UpdateTime:Cardinal;
_UserData:Pointer;
_ChunkedTransfer:Boolean;
_ClientName:AnsiString;
_Cookie:AnsiString;
Function ReceiveHeader:Integer;
Procedure Update;
Procedure ContinueTransfer(Count: Integer);
Procedure WriteLeftovers();
Public
Constructor Create(URL:AnsiString; Const Cookie:AnsiString; Dest:Stream; Callback:DownloadCallback = Nil; Port:Integer=HTTPPort; Const ClientName:AnsiString = DefaultClientName); // Returns file size in bytes
Destructor Destroy; Override;
Function GetHeaderProperty(Name:AnsiString):AnsiString;
Function GetTag(Name:AnsiString):AnsiString;
Property TagCount:Integer Read _TagCount;
Property Progress:Integer Read _Progress;
Property HostName:AnsiString Read _HostName;
Property URL:AnsiString Read _URL;
Property FileName:AnsiString Read _FileName;
Property Target:Stream Read _Target;
Property ErrorCode:Integer Read _ErrorCode;
Property UserData:Pointer Read _UserData;
Property Cookie:AnsiString Read _Cookie;
End;
DownloadManager = Class(ApplicationComponent)
Protected
_Downloads:Array Of HTTPDownloader;
_DownloadCount:Integer;
Function GetOverallProgress:Integer;
Public
Constructor Create;
Destructor Destroy; Override;
Class Function Instance:DownloadManager;
Procedure Update; Override;
Procedure Flush;
Function GetDownload(Index:Integer):HTTPDownloader;
Function StartWithCookie(URL:AnsiString; Const Cookie:AnsiString; Dest:Stream = Nil; Callback:DownloadCallback = Nil; UserData:Pointer = Nil; Port:Integer=HTTPPort; AllowCache:Boolean=True; Const ClientName:AnsiString = DefaultClientName):HTTPDownloader;
Function Start(Const URL:AnsiString; Dest:Stream = Nil; Callback:DownloadCallback = Nil; UserData:Pointer = Nil; Port:Integer=HTTPPort; AllowCache:Boolean=True; Const ClientName:AnsiString = DefaultClientName):HTTPDownloader;
Function Post(URL:AnsiString; Port:Integer=HTTPPort; Const ClientName:AnsiString = DefaultClientName):Integer;
Function Put(URL:AnsiString; Source:Stream; Port:Integer=HTTPPort; Const ClientName:AnsiString = DefaultClientName):Integer;
Property Count:Integer Read _DownloadCount;
Property Progress:Integer Read GetOverallProgress;
End;
Var
DownloadTempPath:AnsiString;
Implementation
Uses TERRA_Log, TERRA_ResourceManager;
Function GetTempPath:AnsiString;
Begin
If DownloadTempPath<>'' Then
Result := DownloadTempPath
Else
If Assigned(Application.Instance()) Then
Result := Application.Instance.TempPath
Else
Result := '';
End;
// LHTTPDownloader class
Constructor HTTPDownloader.Create(URL:AnsiString; Const Cookie:AnsiString; Dest:Stream; Callback:DownloadCallback; Port:Integer; Const ClientName:AnsiString);
Var
I:Integer;
Request:AnsiString;
Begin
_Stream := Nil;
_ErrorCode := httpOK;
_URL := URL;
_Offset := Dest.Position;
_Target := Dest;
_Callback := Callback;
GetMem(_Buffer, BufferSize);
If (ClientName <> '') Then
Self._ClientName := ClientName
Else
Self._ClientName := DefaultClientName;
_Downloading := False;
_Read := 0;
_TagCount := 0;
_Progress := 0;
If (URL='') Or (Dest=Nil) Then
Begin
Log(logError, 'HTTP', 'Invalid download arguments.');
_TotalSize := -1;
_ErrorCode := httpInvalidURL;
Exit;
End;
For I:=1 To Length(URL) Do
If URL[I]='\' Then
URL[I]:='/';
// extract http:// from url
I:=Pos('://',URL);
If I>0 Then
Begin
_Protocol:=UpStr(Copy(URL,1,Pred(I)));
URL:=Copy(URL,I+3,Length(URL));
End Else
_Protocol:=HTTPProtocol;
I := PosRev('/', URL);
_FileName := Copy(URL, Succ(I), MaxInt);
_UpdateTime := GetTime;
If (_Protocol = HTTPProtocol) Then
Begin
// Extract hostname from url
If Pos('/', URL)<=0 Then
URL:=URL+'/';
I:=Pos('/',URL);
If I>0 Then
Begin
_HostName:=Copy(URL,1,Pred(I));
URL:=Copy(URL,I,Length(URL));
End Else
Begin
Log(logError, 'HTTP', 'Invalid URL: '+URL);
_TotalSize := -1;
_ErrorCode := httpInvalidURL;
Exit;
End;
_Stream := Socket.Create(_HostName, Port);
If (_Stream.EOF) Then
Begin
Log(logError, 'HTTP', 'Connection failed: '+URL);
_TotalSize := -1;
_ErrorCode := httpConnectionFailed;
Exit;
End;
Log(logDebug, 'HTTP', 'Sending request to '+URL);
Request:= 'GET '+URL+' HTTP/1.1'+#13#10;
Request := Request + 'User-Agent: ' + ClientName + #13#10;
Request := Request + 'Host: '+ _HostName + #13#10;
Request := Request + 'Accept: text/html, text/xml, image/gif, image/x-xbitmap, image/jpeg, */*'#13#10;
If (Cookie<>'') And (Pos('=', Cookie)>0) Then
Request := Request + 'Cookie: ' + Cookie + #13#10;
//Request := Request + 'Connection: keep-alive'+#13#10;
Request := Request + #13#10;
Socket(_Stream).Blocking := True;
_Stream.Write(@Request[1], Length(Request));
_TotalSize := ReceiveHeader;
End Else
If (_Protocol=FILEProtocol) Then
Begin
If Not FileExists(URL) Then
Begin
Log(logError, 'HTTP', 'File not found: '+_URL);
_TotalSize := -1;
_ErrorCode := httpNotFound;
Exit;
End;
_Stream := FileStream.Open(URL);
_TotalSize := _Stream.Size;
End Else
Begin
Log(logError, 'HTTP', 'Unknown protocol: '+_Protocol);
_TotalSize := -1;
_ErrorCode := httpInvalidProtocol;
Exit;
End;
_Downloading := (_Progress<100);
End;
{
HTTP/1.1 200 OK
Date: Thu, 12 Jan 2006 23:25:37 GMT
Server: Apache/1.3.34 (Unix) mod_auth_passthrough/1.8 mod_log_bytes/1.2 mod_bwlimited/1.4 FrontPage/5.0.2.2635 mod_ssl/2.8.25 OpenSSL/0.9.7a PHP-CGI/0.1b
Last-Modified: Mon, 09 Jan 2006 16:37:56 GMT
ETag: "6c4126-f46-43c29164"
Accept-Ranges: bytes
Content-Length: 3910
}
Function HTTPDownloader.ReceiveHeader:Integer;
Var
I,X,Len:Integer;
Tag,Value,S:AnsiString;
Response:AnsiString;
Begin
_TotalSize := -1;
_ChunkedTransfer := False;
_Cookie := '';
Len := _Stream.Read(_Buffer, BufferSize);
If Len>0 Then
Begin
SetLength(Response,Len);
Move(_Buffer^,Response[1],Len);
X:=0;
While Response<>'' Do
Begin
I:=Pos(#10,Response);
If I=0 Then
I:=Length(Response);
Value:=TrimLeft(TrimRight(Copy(Response,1,I)));
If (Value='') Then
Begin
Response := Copy(Response, 3, MaxInt);
If (_TotalSize<0) And (Not _ChunkedTransfer) Then
Begin
_TotalSize := 0;
End;
Break;
End;
Response := Copy(Response, Succ(I), Length(Response));
If Pos('404 Not Found', Value)>0 Then
Break;
I:=Pos(':',Value);
If (I=0)And(X>0) Then Break;
Tag := Copy(Value,1,Pred(I));
Tag := UpStr(Tag);
Value:=Copy(Value,Succ(I),Length(Value));
Value:=TrimLeft(TrimRight(Value));
If (Tag<>'') Then
Begin
Inc(_TagCount);
SetLength(_Tags, _TagCount);
_Tags[Pred(_TagCount)].Name := Tag;
_Tags[Pred(_TagCount)].Value := Value;
If (Tag = 'SET-COOKIE') Then
Begin
Self._Cookie := GetNextWord(Value, ';');
End;
If Tag='CONTENT-LENGTH' Then
Begin
_TotalSize := StringToInt(Value);
End;
If (Tag='TRANSFER-ENCODING') Then
Begin
If (UpStr(Value)='CHUNKED') Then
_ChunkedTransfer := True;
End;
End;
Inc(X);
End;
_Response := Response;
SetLength(Response,0);
End;
If (_ChunkedTransfer) And (_Response<>'') Then
Begin
I := Pos(#13, _Response);
S := Copy(_Response, 1, Pred(I));
_Response := Copy(_Response, (I+2), MaxInt);
Len := HexStrToInt(S) - Length(_Response);
WriteLeftovers();
If Len<=0 Then
_Progress := 100
Else
ContinueTransfer(Len);
End Else
WriteLeftovers();
Result:=_TotalSize;
End;
Procedure HTTPDownloader.WriteLeftovers();
Begin
If _Response<>'' Then
Begin
_Target.Write(@_Response[1], Length(_Response));
Inc(_Read, Length(_Response));
_Response := '';
End;
End;
Procedure HTTPDownloader.ContinueTransfer(Count:Integer);
Var
Len, Count2, Temp:Integer;
Begin
While (Count>0) And (Not _Stream.EOF) Do
Begin
Count2 := Count;
If Count2>BufferSize Then
Count2 := BufferSize;
Log(logDebug, 'HTTP', 'Reading '+IntToString(Count2));
Len := _Stream.Read(_Buffer, Count2);
Log(logDebug, 'HTTP', 'Got '+IntToString(Len));
If Len>0 Then
Begin
_UpdateTime := GetTime;
_Target.Write(_Buffer, Len);
Inc(_Read, Len);
Dec(Count, Len);
If (_ChunkedTransfer) And (Count=0) Then
Begin
Len := _Stream.Read(@Temp, 2);
IntToString(Len);
End;
End;
End;
If (_ChunkedTransfer) Then
Begin
_TotalSize := _Read;
If (_Stream.EOF) Or (Count=0) Then
_Progress := 100
Else
_Progress := 0;
End Else
_Progress := Trunc((_Read/_TotalSize)*100);
If _Progress>=100 Then
Begin
_Progress := 100;
_Downloading := False;
End;
End;
Procedure HTTPDownloader.Update;
Var
I,Len, Count:Integer;
S:AnsiString;
Begin
If (Not _Downloading) Then
Exit;
If (_TotalSize=0) Then
Begin
_Progress := 100;
Exit;
End;
If (_ChunkedTransfer) Then
Begin
Len := _Stream.Read(_Buffer, 20);
If (Len>0) Then
Begin
SetLength(_Response, Len);
Move(_Buffer^, _Response[1],Len);
I := Pos(#13#10, _Response);
S := Copy(_Response, 1, Pred(I));
_Response := Copy(_Response, I + 2, MaxInt);
Count := HexStrToInt(S);
If (Count<>646) And (Count<>6212) And (Count<>0) Then
IntTostring(2);
If (Count>0) Then
Begin
Dec(Count, Length(_Response));
WriteLeftovers();
End;
End Else
Count := 0;
End Else
Begin
Count := _TotalSize - _Read;
End;
ContinueTransfer(Count);
End;
Destructor HTTPDownloader.Destroy;
Begin
If Assigned(_Buffer) Then
FreeMem(_Buffer);
If Assigned(_Stream) Then
_Stream.Destroy;
End;
Function HTTPDownloader.GetHeaderProperty(Name:AnsiString):AnsiString;
Var
I:Integer;
Begin
Result:='';
For I:=0 To Pred(_TagCount) Do
If (_Tags[I].Name = Name) Then
Begin
Result := _Tags[I].Value;
Exit;
End;
End;
{ DownloadManager }
Var
_DownloadManager_Instance:ApplicationObject = Nil;
Class Function DownloadManager.Instance:DownloadManager;
Begin
If Not Assigned(_DownloadManager_Instance) Then
_DownloadManager_Instance := InitializeApplicationComponent(DownloadManager, Nil);
Result := DownloadManager(_DownloadManager_Instance.Instance);
End;
Constructor DownloadManager.Create;
Begin
_DownloadCount := 0;
End;
Destructor DownloadManager.Destroy;
Var
I:Integer;
Begin
For I:=0 To Pred(_DownloadCount) Do
_Downloads[I].Destroy;
_DownloadManager_Instance := Nil;
End;
Procedure DownloadManager.Update;
Var
Remove:Boolean;
I:Integer;
Begin
If (Prefetching) Then
Exit;
//Application.Instance.Yeld();
I:=0;
While (I<_DownloadCount) Do
Begin
Remove := False;
If (_Downloads[I]._Progress<100) And (GetTime - _Downloads[I]._UpdateTime>ConnectionTimeOut) Then
Begin
Log(logWarning, 'HTTP', 'Connection time out :'+_Downloads[i]._URL);
_Downloads[I]._ErrorCode := httpConnectionTimeOut;
End;
If (_Downloads[I]._ErrorCode<>httpOk) Then
Begin
Log(logDebug, 'HTTP', 'Download error :'+_Downloads[i]._URL);
If Assigned(_Downloads[I]._Callback) Then
_Downloads[I]._Callback(_Downloads[I]);
Remove := True;
End Else
Begin
_Downloads[I].Update;
If (_Downloads[I].Progress>=100) Then
Begin
Log(logDebug, 'HTTP', 'Download finished :'+_Downloads[i]._URL);
If (_Downloads[I]._Target Is MemoryStream) Then
Begin
Log(logDebug, 'HTTP', 'Truncating memory stream');
_Downloads[I]._Target.Truncate;
End;
Log(logDebug, 'HTTP', 'Seeking to zero');
_Downloads[I]._Target.Seek(_Downloads[I]._Offset);
Log(logDebug, 'HTTP', 'Invokating callback');
If Assigned(_Downloads[I]._Callback) Then
Begin
{S := _Downloads[I]._URL;
ReplaceAllText('/', PathSeparator, S);
S := GetFileName(S, False);
S := GetTempPath + PathSeparator + S;
If (FileStream.Exists(S)) Then
Begin
_Downloads[I]._Target.Destroy;
_Downloads[I]._Target := MemoryStream.Create(S);
End;}
_Downloads[I]._Callback(_Downloads[I]);
End;
Remove := True;
End;
End;
If (Remove) Then
Begin
_Downloads[I].Destroy;
_Downloads[I] := _Downloads[Pred(_DownloadCount)];
Dec(_DownloadCount);
End Else
Inc(I);
End;
End;
Function DownloadManager.StartWithCookie(URL:AnsiString; Const Cookie:AnsiString; Dest:Stream; Callback:DownloadCallback; UserData:Pointer; Port:Integer; AllowCache:Boolean; Const ClientName:AnsiString):HTTPDownloader;
Var
S, FileName:AnsiString;
NoCache:Boolean;
Begin
FileName := URL;
ReplaceText('/', PathSeparator, FileName);
FileName := GetFileName(FileName, False);
S := FileManager.Instance.SearchResourceFile(FileName);
NoCache := Pos('.PHP', UpStr(URL))>0;
If (Dest = Nil) Then
Begin
If (S<>'') And (Not NoCache) And (AllowCache) Then
Begin
Log(logDebug, 'HTTP', 'Cached: '+URL);
URL := 'file://'+S;
Dest := MemoryStream.Create(1024);
End Else
If (FileName<>'') Then
Begin
If NoCache Then
Begin
FileName := 'temp.php';
//S := FileName;
//FileName := GetNextWord(S, '?');
Dest := MemoryStream.Create(1024*1024);
End Else
Dest := FileStream.Create(GetTempPath + PathSeparator + FileName);
End;
End;
Log(logDebug, 'HTTP', 'Starting download');
Result := HTTPDownloader.Create(URL, Cookie, Dest, Callback, Port, ClientName);
Result._UserData := UserData;
Inc(_DownloadCount);
SetLength(_Downloads, _DownloadCount);
_Downloads[Pred(_DownloadCount)] := Result;
Log(logDebug, 'HTTP', 'Download dispatched.');
End;
Function DownloadManager.Start(Const URL:AnsiString; Dest:Stream; Callback:DownloadCallback; UserData:Pointer; Port:Integer; AllowCache:Boolean; Const ClientName:AnsiString):HTTPDownloader;
Begin
Result := StartWithCookie(URL, '', Dest, Callback, UserData, Port, AllowCache, ClientName);
End;
Function HTTPDownloader.GetTag(Name:AnsiString):AnsiString;
Var
I:Integer;
Begin
Name := UpStr(Name);
For I:=0 To Pred(_TagCount) Do
If (UpStr(_Tags[I].Name) = Name) Then
Begin
Result := _Tags[I].Value;
Exit;
End;
Result := '';
End;
Procedure DownloadManager.Flush;
Begin
Repeat
Self.Update();
Until Self.Count <=0;
End;
Function DownloadManager.GetOverallProgress: Integer;
Var
I:Integer;
Begin
If (Self._DownloadCount<=0) Then
Begin
Result := 100;
Exit;
End;
Result := 0;
For I:=0 To Pred(_DownloadCount) Do
Inc(Result, _Downloads[I].Progress);
Result := Result Div _DownloadCount;
End;
Function DownloadManager.GetDownload(Index: Integer): HTTPDownloader;
Begin
If (Index<0) Or (Index>=_DownloadCount) Then
Result := Nil
Else
Result := _Downloads[Index];
End;
Function DownloadManager.Post(URL:AnsiString; Port: Integer; Const ClientName:AnsiString): Integer;
Var
I:Integer;
Dest:Socket;
Protocol, Request, Data, HostName:AnsiString;
Begin
I:=Pos('://',URL);
If I>0 Then
Begin
Protocol := UpStr(Copy(URL,1,Pred(I)));
URL := Copy(URL, I+3, Length(URL));
End Else
Protocol := HTTPProtocol;
If (Protocol<>HTTPProtocol) Then
Begin
Result := httpInvalidProtocol;
Exit;
End;
I := Pos('/',URL);
If I>0 Then
Begin
HostName := Copy(URL,1,Pred(I));
URL := Copy(URL,I,Length(URL));
End Else
Begin
Log(logError, 'HTTP', 'Invalid URL: '+URL);
Result := httpInvalidURL;
Exit;
End;
I := Pos('?', URL);
If (I>0) Then
Begin
Data := Copy(URL, Succ(I), MaxInt);
URL := Copy(URL, 1, Pred(I));
End Else
Begin
Log(logError, 'HTTP', 'Invalid URL: '+URL);
Result := httpInvalidURL;
Exit;
End;
Request:= 'POST '+URL+' HTTP/1.1'+#13#10+
'Host: '+HostName+#13#10+
'User-Agent: '+ClientName+#13#10+
'Accept: text/html, text/xml, image/gif, */*'#13#10+
'Content-Type: application/x-www-form-urlencoded'#13#10+
'Content-Length: '+IntToString(Length(Data))+#13#10+
#13#10;
Request := Request + Data;
Dest := Socket.Create(HostName, Port);
If (Dest.EOF) Then
Begin
Log(logError, 'HTTP', 'Connection failed: '+URL);
Result := httpConnectionFailed;
Exit;
End;
Log(logDebug, 'HTTP', 'Sending post request to '+URL);
Dest.Write(@Request[1], Length(Request));
Dest.Destroy;
Result := httpOk;
End;
Function DownloadManager.Put(URL:AnsiString; Source: Stream; Port: Integer; Const ClientName:AnsiString): Integer;
Var
I:Integer;
Dest:Socket;
Len:Integer;
Protocol, Request, HostName:AnsiString;
Response:AnsiString;
Begin
If (Source = Nil) Or (Source.Size<=0) Then
Begin
Result := httpInvalidStream;
Exit;
End;
I:=Pos('://',URL);
If I>0 Then
Begin
Protocol := UpStr(Copy(URL,1,Pred(I)));
URL := Copy(URL, I+3, Length(URL));
End Else
Protocol := HTTPProtocol;
If (Protocol<>HTTPProtocol) Then
Begin
Result := httpInvalidProtocol;
Exit;
End;
I := Pos('/',URL);
If I>0 Then
Begin
HostName := Copy(URL,1,Pred(I));
URL := Copy(URL,I,Length(URL));
End Else
Begin
Log(logError, 'HTTP', 'Invalid URL: '+URL);
Result := httpInvalidURL;
Exit;
End;
I := Pos('?', URL);
If (I>0) Then
Begin
Result := httpInvalidURL;
Exit;
End;
Source.Seek(0);
Request:= 'PUT '+URL+' HTTP/1.1'+#13#10+
'Host: '+HostName+#13#10+
'Content-Length: '+IntToString(Source.Size)+#13#10+
#13#10;
Dest := Socket.Create(HostName, Port);
If (Dest.EOF) Then
Begin
Log(logError, 'HTTP', 'Connection failed: '+URL);
Result := httpConnectionFailed;
Exit;
End;
Log(logDebug, 'HTTP', 'Sending post request to '+URL);
Dest.Write(@Request[1], Length(Request));
Source.Copy(Dest);
Response := #13#10;
Dest.Write(@Response[1], Length(Response));
SetLength(Response, 1024);
Len := Dest.Read(@Response[1], Length(Response));
If Len>0 Then
Begin
SetLength(Response,Len);
If (Pos(' ',Response)>0) Then
IntToString(2);
End;
Dest.Destroy;
Result := httpOk;
End;
End.
|
unit ncaWebBotao;
interface
uses
classes, sysutils, dxBar, Windows, idHttp, cxStyles, dxGDIPlusClasses, Graphics, cxPC, ncaFrmWebTab;
type
TncaWebBotoes = class;
TncaDownloadBotaoThread = class ( TThread )
private
FDownOk : Boolean;
FImg : String;
protected
procedure Execute; override;
public
constructor Create(aImg: String);
end;
TncaWebBotaoData = object
Nome : String;
Url : String;
Blank : Boolean;
ShowUrl : Boolean;
Sel : Boolean;
Toolbar : Boolean;
Bold : Boolean;
paramSessao,
paramAdmin,
paramConta : Boolean;
Posicao : Byte;
Gray : Boolean;
Width : Integer;
Color : Integer;
Img : String;
procedure Clear;
function BotaoExiste: Boolean;
function FromString(S: String): Boolean;
procedure AssignFrom(B: TncaWebBotaoData);
function Igual(B: TncaWebBotaoData): Boolean;
function GetStyle(aStylePadrao: TcxStyle): TcxStyle;
end;
TncaWebBotao = class
private
FWebBotoes : TncaWebBotoes;
FData : TncaWebBotaoData;
FDownBtn : TncaDownloadBotaoThread;
FBtn : TdxBarLargeButton;
FTab : TcxTabSheet;
FWebTab : TFrmWebTab;
procedure OnLoadBtn(Sender: TObject);
procedure LoadImgBtn;
public
constructor Create(aWebBotoes: TncaWebBotoes; aData: TncaWebBotaoData);
destructor Destroy; override;
function Visible: Boolean;
property Data: TncaWebBotaoData read FData;
property Tab: TcxTabSheet read FTab;
property WebTab: TFrmWebTab read FWebTab;
property Btn: TdxBarLargeButton read FBtn;
end;
TncaWebBotoes = class
private
FBotoes : TList;
FBar : TdxBar;
FOnClick : TNotifyEvent;
FStyle : TcxStyle;
FWidth : Integer;
FPC : TcxPageControl;
function FindBotao(aNome: String): TncaWebBotao;
procedure UpdateBotao(aData: TncaWebBotaoData);
function GetBotao(I: Integer): TncaWebBotao;
public
constructor Create(aBar: TdxBar; aPC: TcxPageControl; aStyle: TcxStyle; aWidth: Integer);
procedure FromString(S: String);
function Count: Integer;
destructor Destroy; override;
property Botao[I: Integer]: TncaWebBotao
read GetBotao;
property OnClick: TNotifyEvent
read FOnClick write FOnClick;
end;
var
gWebBotoes : TncaWebBotoes = nil;
implementation
uses ncClassesBase;
{ TncaWebBotoes }
function UrlBotao(aImg: String): String;
begin
Result := 'http://botao.nextar.com/'+aImg+'.png';
end;
function PathBotao: String;
begin
Result := ExtractFilePath(ParamStr(0))+'imgs\';
end;
function ArqBotao(aImg: String): String;
begin
Result := PathBotao+aImg+'.png';
end;
function TncaWebBotoes.Count: Integer;
begin
Result := FBotoes.Count;
end;
constructor TncaWebBotoes.Create(aBar: TdxBar; aPC: TcxPageControl; aStyle: TcxStyle; aWidth: Integer);
begin
FBar := aBar;
FPC := aPC;
FStyle := aStyle;
FWidth := aWidth;
FOnClick := nil;
FBotoes := TList.Create;
end;
destructor TncaWebBotoes.Destroy;
begin
while FBotoes.Count>0 do begin
TObject(FBotoes[0]).Free;
FBotoes.Delete(0);
end;
FBotoes.Free;
end;
function SplitBotoes(S: String) : TStrings;
var P : Integer;
function GetPos: Boolean;
begin
P := Pos('[', S);
Result := (P>0);
end;
begin
Result := TStringList.Create;
while GetPos do begin
Delete(S, 1, P);
P := Pos(']', S);
if P>0 then begin
Result.Add(Copy(S, 1, P-1));
Delete(S, 1, P);
end else
S := '';
end;
end;
function TncaWebBotoes.FindBotao(aNome: String): TncaWebBotao;
var i: integer;
begin
for i := 0 to FBotoes.Count - 1 do
if TncaWebBotao(FBotoes[i]).FData.Nome=aNome then begin
Result := TncaWebBotao(FBotoes[i]);
Exit;
end;
Result := nil;
end;
procedure TncaWebBotoes.FromString(S: String);
var
sl: TStrings;
sl2: TStrings;
B : TncaWebBotaoData;
i : Integer;
begin
sl2 := TStringList.Create;
sl := SplitBotoes(S);
try
for i := 0 to sl.Count-1 do
if B.FromString(sl[i]) then begin
sl2.Add(B.Nome);
UpdateBotao(B);
end;
for i := FBotoes.Count -1 downto 0 do
if sl2.IndexOf(TncaWebBotao(FBotoes[i]).FData.Nome)=-1 then begin
TObject(FBotoes[i]).Free;
FBotoes.Delete(i);
end;
finally
sl2.Free;
sl.Free;
end;
end;
function TncaWebBotoes.GetBotao(I: Integer): TncaWebBotao;
begin
REsult := TncaWebBotao(FBotoes[I]);
end;
procedure TncaWebBotoes.UpdateBotao(aData: TncaWebBotaoData);
var B : TncaWebBotao;
begin
B := FindBotao(aData.Nome);
if (B<>nil) and (not B.FData.Igual(aData)) then begin
FBotoes.Remove(B);
B.Free;
B := nil;
end;
if B=nil then begin
B := TncaWebBotao.Create(Self, aData);
FBotoes.Add(B);
end;
end;
{ TncaWebBotaoData }
procedure TncaWebBotaoData.AssignFrom(B: TncaWebBotaoData);
begin
Nome := B.Nome;
Url := B.Url;
Blank := B.Blank;
ShowUrl := B.ShowUrl;
Sel := B.Sel;
Toolbar := B.Toolbar;
Posicao := B.Posicao;
Img := B.Img;
Bold := B.Bold;
Gray := B.Gray;
Width := B.Width;
Color := B.Color;
paramSessao := B.paramSessao;
paramConta := B.paramConta;
paramAdmin := B.paramAdmin;
end;
function TncaWebBotaoData.BotaoExiste: Boolean;
begin
Result := FileExists(ArqBotao(Img));
end;
procedure TncaWebBotaoData.Clear;
begin
Nome := '';
Url := '';
Blank := False;
ShowUrl := False;
Sel := False;
Toolbar := False;
Posicao := 0;
Img := '';
Bold := False;
Gray := False;
Width := 0;
Color := 0;
paramSessao := False;
paramAdmin := False;
paramConta := False;
end;
function TncaWebBotaoData.FromString(S: String): Boolean;
var sl: TStrings;
begin
Clear;
sl := SplitParams(S);
try
Nome := RemoveAspas(sl.Values['nome']);
Posicao := StrToIntDef(sl.Values['pos'], 0);
Img := RemoveAspas(sl.Values['img']);
Url := RemoveAspas(sl.Values['url']);
Blank := (sl.Values['blank']='1');
Gray := (sl.Values['gray']<>'0');
Width := StrToIntDef(sl.Values['width'], 0);
Color := StrToIntDef(sl.Values['color'], 0);
Bold := (sl.Values['bold']='1');
Toolbar := False; //(sl.Values['toolbar']='1');
ShowUrl := False; //(sl.Values['showurl']='1');
Sel := (sl.Values['sel']='1');
paramSessao := (sl.Values['paramSessao']='1');
paramAdmin := (sl.Values['paramAdmin']='1');
paramConta := (sl.Values['paramConta']='1');
Result := (Nome>'') and (Posicao in [0..1]) and (Img > '') and (Url>'');
finally
sl.Free;
end;
end;
function TncaWebBotaoData.GetStyle(aStylePadrao: TcxStyle): TcxStyle;
begin
Result := TcxStyle.Create(nil);
Result.Assign(aStylePadrao);
if Bold or (Color<>0) then begin
Result.TextColor := Color;
if Bold then
Result.Font.Style := [fsBold];
end;
end;
function TncaWebBotaoData.Igual(B: TncaWebBotaoData): Boolean;
begin
Result := False;
if Nome<>B.Nome then Exit;
if Url<>B.Url then Exit;
if Blank<>B.Blank then Exit;
if ShowUrl<>B.ShowUrl then Exit;
if Sel<>B.Sel then Exit;
if Toolbar<>B.Toolbar then Exit;
if Posicao<>B.Posicao then Exit;
if Img<>B.Img then Exit;
if Bold<>B.Bold then Exit;
if Gray<>B.Gray then Exit;
if Color<>B.Color then Exit;
if Width<>B.Width then Exit;
if paramSessao<>B.paramSessao then Exit;
if paramAdmin<>B.paramAdmin then Exit;
if paramConta<>B.paramConta then Exit;
Result := True;
end;
{ TncaWebBotao }
constructor TncaWebBotao.Create(aWebBotoes: TncaWebBotoes; aData: TncaWebBotaoData);
begin
FWebBotoes := aWebBotoes;
FDownBtn := nil;
FData.AssignFrom(aData);
FBtn := TdxBarLargeButton.Create(FWebBotoes.FBar.Owner);
FBtn.Style := FData.GetStyle(FWebBotoes.FStyle);
FBtn.BarManager := FWebBotoes.FBar.BarManager;
FBtn.Caption := aData.Nome;
FBtn.OnClick := FWebBotoes.OnClick;
FBtn.Visible := ivNever;
FBtn.Tag := Integer(Self);
FBtn.AutoGrayScale := FData.Gray;
if FData.Width<FWebBotoes.FWidth then
FBtn.Width := FWebBotoes.FWidth else
FBtn.Width := FData.Width;
if FData.BotaoExiste then
LoadImgBtn
else begin
FDownBtn := TncaDownloadBotaoThread.Create(FData.Img);
FDownBtn.OnTerminate := OnLoadBtn;
FDownBtn.Resume;
end;
with FWebBotoes.FBar.ItemLinks.Add do begin
Item := FBtn;
if FData.Posicao=0 then
Index := 0;
end;
if FData.Blank then begin
FTab := nil;
FWebTab := nil;
end
else begin
FTab := TcxTabSheet.Create(nil);
FTab.PageControl := FWebBotoes.FPC;
FWebTab := TFrmWebTab.Create(nil);
FWebTab.paramSessao := FData.paramSessao;
FWebTab.paramAdmin := FData.paramAdmin;
FWebTab.paramConta := FData.paramConta;
FWebTab.Paginas.Parent := Ftab;
FWebTab.URL := FData.Url;
FWebTab.showToolbar := FData.Toolbar;
if FData.ShowUrl then
FWebTab.showUrl := suBase else
FWebTab.showUrl := suNao;
end;
if not FData.Blank then begin
FBtn.AllowAllUp := False;
FBtn.ButtonStyle := bsChecked;
FBtn.GroupIndex := 1;
end;
end;
destructor TncaWebBotao.Destroy;
begin
if Assigned(FDownBtn) then begin
FDownBtn.OnTerminate := nil;
FDownBtn.Terminate;
end;
FBtn.Style.Free;
FBtn.Free;
if Assigned(FWebTab) then FWebTab.Free;
if Assigned(FTab) then FTab.Free;
inherited;
end;
procedure TncaWebBotao.LoadImgBtn;
var P: TdxPngImage;
begin
try
P := TdxPngImage.Create;
try
P.LoadFromFile(ArqBotao(FData.Img));
FBtn.LargeGlyph := P.GetAsBitmap;
FBtn.Visible := ivAlways;
finally
P.Free;
end;
except
end;
end;
procedure TncaWebBotao.OnLoadBtn(Sender: TObject);
begin
if TncaDownloadBotaoThread(Sender).FDownOk then
LoadImgBtn;
end;
function TncaWebBotao.Visible: Boolean;
begin
Result := (FBtn.Visible=ivAlways);
end;
{ TncaDownloadBotaoThread }
constructor TncaDownloadBotaoThread.Create(aImg: String);
begin
FImg := aImg;
FDownOk := False;
inherited Create(True);
FreeOnTerminate := True;
end;
function DownloadArq(aFrom, aTo: String): Boolean;
var S: TFileStream;
begin
S := TFileStream.Create(aTo, fmCreate);
try
with TidHttp.Create(nil) do
try
try
Get(aFrom, S);
Result := True;
except
end;
finally
Free;
end;
finally
S.Free;
end;
end;
procedure TncaDownloadBotaoThread.Execute;
var
TryMS,
NextTry: Cardinal;
aFrom, aTo: String;
begin
ForceDirectories(PathBotao);
NextTry := GetTickCount;
TryMS := 0;
aFrom := UrlBotao(FImg);
aTo := ArqBotao(FImg);
FDownOk := False;
repeat
if GetTickCount>=NextTry then begin
FDownOk := DownloadArq(aFrom, aTo);
if not FDownOk then begin
if TryMS<(60*1000*30) then
TryMS := TryMS+5000;
NextTry := GetTickCount+TryMS;
end;
end else
Sleep(100);
until (Terminated) or FDownOk;
end;
end.
|
unit ServerMain;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Corba, CosNaming, Bank_I, Bank_C, Bank_S, Bank_Impl;
type
TForm1 = class(TForm)
Label1: TLabel;
Edit1: TEdit;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
AccountServer : Account;
nameArray : COSNaming.Name;
nameComp : COSNaming.NameComponent;
nameContext : COSNaming.NamingContext;
procedure CorbaInit;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.CorbaInit;
begin
{Corba Initialization}
CorbaInitialize;
AccountServer := TAccountSkeleton.Create('Jack B Quick', TAccount.Create);
BOA.ObjIsReady(AccountServer as _Object);
{Set up the CosNaming Registration - unregister when program shuts down}
// create the naming component -- match test server id and kind values
// Note that "Test1" is the Naming Component specified on the cmd line for
// the naming service i.e. NameExtF Test1 mylog.txt
nameComp := TNameComponent.Create('Test1', 'AccountServer');
//set up the Name sequence
SetLength(NameArray, 1);
NameArray[0] := nameComp;
//bind to the naming context
NameContext := TNamingContextHelper.Bind;
NameContext.bind(NameArray, AccountServer as CorbaObject);
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
CorbaInit;
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
//unregister server with CosNaming
NameContext.unbind(NameArray);
end;
end.
|
{*******************************************************}
{ }
{ FMX UI Dialog 通用对话框 }
{ }
{ 版权所有 (C) 2016 YangYxd }
{ }
{*******************************************************}
{
示例:
1. 基本对话框
TDialogBuilder.Create(Self)
.SetTitle('标题')
.SetMessage('消息内容')
.SetNegativeButton('取消')
.Show();
2. 列表框
TDialogBuilder.Create(Self)
.SetItems(['Item1', 'Item2', 'Item3'],
procedure (Dialog: IDialog; Which: Integer) begin
Hint(Dialog.Builder.ItemArray[Which]);
end
)
.Show();
3. 多选框
TDialogBuilder.Create(Self)
.SetMultiChoiceItems(
['Item1', 'Item2', 'Item3'],
[False, True, False],
procedure (Dialog: IDialog; Which: Integer; IsChecked: Boolean) begin
// Hint(Dialog.Builder.ItemArray[Which]);
end
)
.SetNeutralButton('确定',
procedure (Dialog: IDialog; Which: Integer) begin
Hint(Format('您选择了%d项', [Dialog.Builder.CheckedCount]));
end
)
.Show();
}
unit UI.Dialog;
interface
uses
UI.Base, UI.Ani, UI.Utils, UI.Standard, UI.ListView,
{$IFDEF WINDOWS}UI.Debug, {$ENDIF}
System.TypInfo, System.SysUtils, System.Character, System.RTLConsts,
FMX.Graphics, System.Generics.Collections, FMX.TextLayout, FMX.Ani,
System.Classes, System.Types, System.UITypes, System.Math.Vectors, System.Rtti,
FMX.Types, FMX.Controls, FMX.Forms, FMX.StdCtrls, FMX.Utils, FMX.Effects,
FMX.ListView, FMX.ListView.Appearances, FMX.ListView.Types;
const
// 没有点击按钮
BUTTON_NONE = 0;
// The identifier for the positive button.
BUTTON_POSITIVE = -1;
// The identifier for the negative button.
BUTTON_NEGATIVE = -2;
// The identifier for the neutral button.
BUTTON_NEUTRAL = -3;
// The identifier for the cancel button.
BUTTON_CANCEL = -4;
const
// 颜色、字体等默认设置项
COLOR_BodyBackgroundColor = $ffffffff;
COLOR_BackgroundColor = $ffffffff;
COLOR_DialogMaskColor = $9f000000;
COLOR_DialogMaskShadowColor = $7f000000;
COLOR_MessageTextBackground = $00f00000;
COLOR_MessageTextColor = $ff101010;
COLOR_TitleBackGroundColor = $00000000;
{$IFDEF IOS}
//COLOR_TitleTextColor = $ff077dfe;
COLOR_TitleTextColor = $ff7D7e7f;
{$ELSE}
COLOR_TitleTextColor = $ff7D7D7D;
{$ENDIF}
{$IFDEF MSWINDOWS}
COLOR_ProcessBackgroundColor = $7fbababa;
{$ENDIF}
{$IFDEF IOS}
COLOR_ProcessBackgroundColor = $80000000;
{$ELSE}
{$IFDEF MACOS}
COLOR_ProcessBackgroundColor = $80000000;
{$ENDIF}
{$ENDIF}
{$IFDEF ANDROID}
COLOR_ProcessBackgroundColor = $7f000000;
{$ENDIF}
{$IFDEF LINUX}
COLOR_ProcessBackgroundColor = $7f000000;
{$ENDIF}
COLOR_ProcessTextColor = $fff7f7f7;
COLOR_ButtonColor = $ffffffff;
COLOR_ButtonPressColor = $ffd9d9d9;
COLOR_ButtonBorderColor = $ffe0e0e0;
{$IFDEF IOS}
// COLOR_ButtonTextColor = $FF077dfe;
// COLOR_ButtonTextPressColor = $FF0049f5;
COLOR_ButtonTextColor = $FF404040;
COLOR_ButtonTextPressColor = $FF101010;
{$ELSE}
COLOR_ButtonTextColor = $FF404040;
COLOR_ButtonTextPressColor = $FF101010;
{$ENDIF}
COLOR_ListItemPressedColor = $ffd9d9d9;
COLOR_LIstItemDividerColor = $afe3e4e5;
COLOR_TitleSpaceColor = $ffe7e7e7;
SIZE_TitleSpaceHeight = 1;
FONT_TitleTextSize = 18;
FONT_MessageTextSize = 15;
FONT_ButtonTextSize = 15;
Title_Gravity = TLayoutGravity.Center;
{$IFDEF IOS}
SIZE_BackgroundRadius = 15;
SIZE_TitleHeight = 42;
{$ELSE}
SIZE_BackgroundRadius = 13;
SIZE_TitleHeight = 50;
{$ENDIF}
SIZE_ButtonHeight = 42;
SIZE_ICON = 32;
SIZE_ButtonBorder = 0.6;
SIZE_MENU_WIDTH = 0.8;
type
TButtonViewColor = class(TViewColor)
public
constructor Create(const ADefaultColor: TAlphaColor = COLOR_ButtonColor);
published
property Default default COLOR_ButtonColor;
property Pressed default COLOR_ButtonPressColor;
end;
type
/// <summary>
/// 对话框样式管理器
/// </summary>
[ComponentPlatformsAttribute(AllCurrentPlatforms)]
TDialogStyleManager = class(TComponent)
private
FDialogMaskColor: TAlphaColor;
FDialogMaskMargins: TBounds;
FDialogMaskShadowColor: TAlphaColor;
FBackgroundColor: TAlphaColor;
FBackgroundPadding: TBounds;
FTitleBackGroundColor: TAlphaColor;
FTitleTextColor: TAlphaColor;
FBodyBackgroundColor: TAlphaColor;
FProcessBackgroundColor: TAlphaColor;
FProcessTextColor: TAlphaColor;
FMessageTextColor: TAlphaColor;
FMessageTextBackground: TAlphaColor;
FButtonColor: TButtonViewColor;
FButtonTextColor: TTextColor;
FButtonBorder: TViewBorder;
FMessageTextSize: Integer;
FTitleHeight: Integer;
FTitleTextSize: Integer;
FButtonTextSize: Integer;
FIconSize: Integer;
FBackgroundRadius: Single;
FTitleGravity: TLayoutGravity;
FTitleSpaceHeight: Single;
FTitleSpaceColor: TAlphaColor;
FMaxWidth: Integer;
FMessageTextMargins: TBounds;
FMessageTextGravity: TLayoutGravity;
FTitleTextBold: Boolean;
FListItemPressedColor: TAlphaColor;
FListItemDividerColor: TAlphaColor;
FButtonHeight: Integer;
procedure SetButtonColor(const Value: TButtonViewColor);
procedure SetButtonBorder(const Value: TViewBorder);
procedure SetButtonTextColor(const Value: TTextColor);
function IsStoredBackgroundRadius: Boolean;
function IsStoredTitleSpaceHeight: Boolean;
function GetMessageTextMargins: TBounds;
procedure SetMessageTextMargins(const Value: TBounds);
protected
procedure AssignTo(Dest: TPersistent); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Assign(Dest: TPersistent); override;
published
// 遮罩层颜色
property DialogMaskColor: TAlphaColor read FDialogMaskColor write FDialogMaskColor default COLOR_DialogMaskColor;
// 遮罩层外边距
property DialogMaskMargins: TBounds read FDialogMaskMargins write FDialogMaskMargins;
// 遮罩层阴影颜色
property DialogMaskShadowColor: TAlphaColor read FDialogMaskShadowColor write FDialogMaskShadowColor default COLOR_DialogMaskShadowColor;
// 消息框背景颜色
property BackgroundColor: TAlphaColor read FBackgroundColor write FBackgroundColor default COLOR_BackgroundColor;
// 消息框背景内边距
property BackgroundPadding: TBounds read FBackgroundPadding write FBackgroundPadding;
// 标题栏背景色
property TitleBackGroundColor: TAlphaColor read FTitleBackGroundColor write FTitleBackGroundColor default COLOR_TitleBackGroundColor;
// 标题栏文本颜色
property TitleTextColor: TAlphaColor read FTitleTextColor write FTitleTextColor default COLOR_TitleTextColor;
// 主体区背景颜色
property BodyBackgroundColor: TAlphaColor read FBodyBackgroundColor write FBodyBackgroundColor default COLOR_BodyBackgroundColor;
// 消息文本颜色
property MessageTextColor: TAlphaColor read FMessageTextColor write FMessageTextColor default COLOR_MessageTextColor;
// 消息文本背景颜色
property MessageTextBackground: TAlphaColor read FMessageTextBackground write FMessageTextBackground default COLOR_MessageTextBackground;
// 消息文本外边距
property MessageTextMargins: TBounds read GetMessageTextMargins write SetMessageTextMargins;
// 消息文本重力
property MessageTextGravity: TLayoutGravity read FMessageTextGravity write FMessageTextGravity default TLayoutGravity.CenterVertical;
// 等待消息框背景颜色
property ProcessBackgroundColor: TAlphaColor read FProcessBackgroundColor write FProcessBackgroundColor default COLOR_ProcessBackgroundColor;
// 等待消息框消息文字颜色
property ProcessTextColor: TAlphaColor read FProcessTextColor write FProcessTextColor default COLOR_ProcessTextColor;
// 列表框默认列表项按下时背景颜色
property ListItemPressedColor: TAlphaColor read FListItemPressedColor write FListItemPressedColor default COLOR_ListItemPressedColor;
// 列表框默认行列分隔线颜色
property ListItemDividerColor: TAlphaColor read FListItemDividerColor write FListItemDividerColor default COLOR_ListItemDividerColor;
// 标题栏文本重力
property TitleGravity: TLayoutGravity read FTitleGravity write FTitleGravity default Title_Gravity;
// 标题栏高度
property TitleHeight: Integer read FTitleHeight write FTitleHeight default SIZE_TitleHeight;
// 标题栏粗体
property TitleTextBold: Boolean read FTitleTextBold write FTitleTextBold default False;
// 标题文本大小
property TitleTextSize: Integer read FTitleTextSize write FTitleTextSize default FONT_TitleTextSize;
// 消息文本大小
property MessageTextSize: Integer read FMessageTextSize write FMessageTextSize default FONT_MessageTextSize;
// 按钮文本大小
property ButtonTextSize: Integer read FButtonTextSize write FButtonTextSize default FONT_ButtonTextSize;
// 按钮高度
property ButtonHeight: Integer read FButtonHeight write FButtonHeight default SIZE_ButtonHeight;
// 图标大小
property IconSize: Integer read FIconSize write FIconSize default SIZE_ICON;
// 最大宽度
property MaxWidth: Integer read FMaxWidth write FMaxWidth default 0;
property BackgroundRadius: Single read FBackgroundRadius write FBackgroundRadius stored IsStoredBackgroundRadius;
property ButtonColor: TButtonViewColor read FButtonColor write SetButtonColor;
property ButtonTextColor: TTextColor read FButtonTextColor write SetButtonTextColor;
property ButtonBorder: TViewBorder read FButtonBorder write SetButtonBorder;
// 标题与内容区分隔线颜色
property TitleSpaceColor: TAlphaColor read FTitleSpaceColor write FTitleSpaceColor default COLOR_TitleSpaceColor;
// 标题与内容区分隔线高度
property TitleSpaceHeight: Single read FTitleSpaceHeight write FTitleSpaceHeight stored IsStoredTitleSpaceHeight;
end;
type
TDialogBuilder = class;
TCustomAlertDialog = class;
TDialogView = class;
/// <summary>
/// 对话框接口
/// </summary>
IDialog = interface(IInterface)
['{53E2915A-B90C-4C9B-85D8-F4E3B9892D9A}']
function GetBuilder: TDialogBuilder;
function GetView: TControl;
function GetViewRoot: TDialogView;
function GetCancelable: Boolean;
/// <summary>
/// 显示对话框
/// </summary>
procedure Show();
/// <summary>
/// 关闭对话框
/// </summary>
procedure Dismiss();
/// <summary>
/// 异步关闭对话框
/// </summary>
procedure AsyncDismiss();
/// <summary>
/// 关闭对话框
/// </summary>
procedure Close();
/// <summary>
/// 取消对话框
/// </summary>
procedure Cancel();
/// <summary>
/// 隐藏对话框
/// </summary>
procedure Hide();
/// <summary>
/// 构造器
/// </summary>
property Builder: TDialogBuilder read GetBuilder;
/// <summary>
/// 视图组件
/// </summary>
property View: TControl read GetView;
/// <summary>
/// 根视图组件
/// </summary>
property ViewRoot: TDialogView read GetViewRoot;
/// <summary>
/// 是否能取消对话框
/// </summary>
property Cancelable: Boolean read GetCancelable;
end;
TOnDialogKeyListener = procedure (Dialog: IDialog; keyCode: Integer) of object;
TOnDialogKeyListenerA = reference to procedure (Dialog: IDialog; keyCode: Integer);
TOnDialogMultiChoiceClickListener = procedure (Dialog: IDialog; Which: Integer; IsChecked: Boolean) of object;
TOnDialogMultiChoiceClickListenerA = reference to procedure (Dialog: IDialog; Which: Integer; IsChecked: Boolean);
TOnDialogItemSelectedListener = procedure (Dialog: IDialog; Position: Integer; ID: Int64) of object;
TOnDialogItemSelectedListenerA = reference to procedure (Dialog: IDialog; Position: Integer; ID: Int64);
TOnDialogClickListener = procedure (Dialog: IDialog; Which: Integer) of object;
TOnDialogClickListenerA = reference to procedure (Dialog: IDialog; Which: Integer);
TOnDialogListener = procedure (Dialog: IDialog) of object;
TOnDialogListenerA = reference to procedure (Dialog: IDialog);
TOnDialogInitListAdapterA = reference to procedure (Dialog: IDialog; Builder: TDialogBuilder; var Adapter: IListAdapter);
TOnDialogInitA = reference to procedure (Dialog: IDialog; Builder: TDialogBuilder);
/// <summary>
/// 对话框视图 (不要直接使用它)
/// </summary>
TDialogView = class(TRelativeLayout)
private
[Weak] FDialog: IDialog;
protected
FLayBubble: TLinearLayout;
FLayBubbleBottom: TLinearLayout;
FTitleView: TTextView;
FTitleSpace: TView;
FMsgBody: TLinearLayout;
FMsgMessage: TTextView;
FButtonLayout: TLinearLayout;
FButtonPositive: TButtonView;
FButtonNegative: TButtonView;
FButtonNeutral: TButtonView;
FCancelButtonLayout: TLinearLayout;
FButtonCancel: TButtonView;
FListView: TListViewEx;
FAnilndictor: TAniIndicator;
FIsDownPopup: Boolean;
FShadowEffect: TShadowEffect;
protected
procedure AfterDialogKey(var Key: Word; Shift: TShiftState); override;
procedure Resize; override;
procedure DoRealign; override;
function GetTabStopController: ITabStopController; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure InitView(StyleMgr: TDialogStyleManager);
procedure InitShadow(StyleMgr: TDialogStyleManager);
procedure InitProcessView(StyleMgr: TDialogStyleManager);
procedure InitMask(StyleMgr: TDialogStyleManager);
procedure InitMessage(StyleMgr: TDialogStyleManager);
procedure InitList(StyleMgr: TDialogStyleManager);
procedure InitButton(StyleMgr: TDialogStyleManager);
procedure InitOK();
procedure Show; override;
procedure Hide; override;
procedure SetTitle(const AText: string);
property ListView: TListViewEx read FListView;
property TitleView: TTextView read FTitleView;
property MessageView: TTextView read FMsgMessage;
property ButtonLayout: TLinearLayout read FButtonLayout;
property ButtonPositive: TButtonView read FButtonPositive;
property ButtonNegative: TButtonView read FButtonNegative;
property ButtonNeutral: TButtonView read FButtonNeutral;
property CancelButtonLayout: TLinearLayout read FCancelButtonLayout;
property ButtonCancel: TButtonView read FButtonCancel;
property Dialog: IDialog read FDialog write FDialog;
end;
TControlClass = type of TControl;
TDialogViewPosition = (Top, Bottom, LeftBottom, RightBottom, Left, Right, Center, LeftFill, RightFill);
TDialog = class(TComponent, IDialog)
private
FAnimate: TFrameAniType;
FMask: Boolean;
FOnCancelListener: TOnDialogListener;
FOnCancelListenerA: TOnDialogListenerA;
FOnShowListener: TOnDialogListener;
FOnShowListenerA: TOnDialogListenerA;
FOnDismissListener: TOnDialogListener;
FOnDismissListenerA: TOnDialogListenerA;
procedure SetOnCancelListener(const Value: TOnDialogListener);
procedure SetOnCancelListenerA(const Value: TOnDialogListenerA);
function GetView: TControl;
function GetViewRoot: TDialogView;
function GetRootView: TDialogView;
function GetIsDismiss: Boolean;
function GetAniView: TControl;
protected
FViewRoot: TDialogView;
FCancelable: Boolean;
FCanceled: Boolean;
FIsDismiss: Boolean;
FEventing: Boolean; // 事件处理中
FAllowDismiss: Boolean; // 需要释放
FTempValue: Single; // 临时变量
FIsDowPopup: Boolean; // 是否是下拉弹出方式
procedure SetCancelable(const Value: Boolean);
function GetCancelable: Boolean;
procedure InitOK(); virtual;
procedure DoFreeBuilder(); virtual;
procedure DoApplyTitle(); virtual;
function GetBuilder: TDialogBuilder; virtual;
function GetMessage: string; virtual;
procedure SetMessage(const Value: string); virtual;
function GetFirstParent(): TFmxObject;
protected
procedure DoRootClick(Sender: TObject); virtual;
procedure DoAsyncDismiss();
/// <summary>
/// 播放动画
/// <param name="Ani">动画类型</param>
/// <param name="IsIn">是否是正要显示</param>
/// <param name="AEvent">动画播放完成事件</param>
/// </summary>
procedure AnimatePlay(Ani: TFrameAniType; IsIn: Boolean; AEvent: TNotifyEventA);
property AniView: TControl read GetAniView;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
/// <summary>
/// 显示对话框
/// </summary>
procedure Show();
/// <summary>
/// 显示对话框
/// <param name="Target">定位控件</param>
/// <param name="ViewClass">要自动创建的视图类</param>
/// <param name="Position">视图位置(默认位于目标下方)</param>
/// <param name="XOffset">视图偏移横向位置</param>
/// <param name="YOffset">视图偏移垂直位置</param>
/// </summary>
class function ShowView(const AOwner: TComponent; const Target: TControl;
const ViewClass: TControlClass;
XOffset: Single = 0; YOffset: Single = 0;
Position: TDialogViewPosition = TDialogViewPosition.Bottom;
Cancelable: Boolean = True; Ani: TFrameAniType = TFrameAniType.None;
Mask: Boolean = True; Shadow: Boolean = False): TDialog; overload;
/// <summary>
/// 显示对话框
/// <param name="Target">定位控件</param>
/// <param name="View">要显示的视图对象</param>
/// <param name="AViewAutoFree">是否自动释放View对象</param>
/// <param name="Position">视图位置(默认位于目标下方)</param>
/// <param name="XOffset">视图偏移横向位置</param>
/// <param name="YOffset">视图偏移垂直位置</param>
/// </summary>
class function ShowView(const AOwner: TComponent; const Target: TControl;
const View: TControl; AViewAutoFree: Boolean = True;
XOffset: Single = 0; YOffset: Single = 0;
Position: TDialogViewPosition = TDialogViewPosition.Bottom;
Cancelable: Boolean = True; Ani: TFrameAniType = TFrameAniType.None;
Mask: Boolean = True; Shadow: Boolean = False): TDialog; overload;
/// <summary>
/// 在一个目标控件身上查找与其绑定在一起的对象框
/// </summary>
class function GetDialog(const Target: TControl): IDialog;
/// <summary>
/// 在一个目标控件身上查找与其绑定在一起的对话框,如果找到,关闭它
/// </summary>
class procedure CloseDialog(const Target: TControl);
/// <summary>
/// 关闭对话框
/// </summary>
procedure Dismiss();
/// <summary>
/// 关闭对话框
/// </summary>
procedure Close();
/// <summary>
/// 取消对话框
/// </summary>
procedure Cancel();
/// <summary>
/// 隐藏
/// </summary>
procedure Hide();
/// <summary>
/// 异步释放
/// </summary>
procedure AsyncDismiss();
/// <summary>
/// 通知数据已经改变,刷新列表
/// </summary>
procedure NotifyDataSetChanged();
/// <summary>
/// 对话框View
/// </summary>
property View: TControl read GetView;
property RootView: TDialogView read GetRootView;
/// <summary>
/// 是否能取消对话框
/// </summary>
property Cancelable: Boolean read FCancelable write SetCancelable;
property Message: string read GetMessage write SetMessage;
property Canceled: Boolean read FCanceled;
property IsDismiss: Boolean read GetIsDismiss;
property Animate: TFrameAniType read FAnimate write FAnimate default TFrameAniType.FadeInOut;
property OnCancelListener: TOnDialogListener read FOnCancelListener write SetOnCancelListener;
property OnCancelListenerA: TOnDialogListenerA read FOnCancelListenerA write SetOnCancelListenerA;
property OnShowListener: TOnDialogListener read FOnShowListener write FOnShowListener;
property OnShowListenerA: TOnDialogListenerA read FOnShowListenerA write FOnShowListenerA;
property OnDismissListener: TOnDialogListener read FOnDismissListener write FOnDismissListener;
property OnDismissListenerA: TOnDialogListenerA read FOnDismissListenerA write FOnDismissListenerA;
end;
/// <summary>
/// 弹出式对话框基类
/// </summary>
TCustomAlertDialog = class(TDialog)
private
FBuilder: TDialogBuilder;
FOnKeyListener: TOnDialogKeyListener;
FOnKeyListenerA: TOnDialogKeyListenerA;
procedure SetOnKeyListener(const Value: TOnDialogKeyListener);
function GetItems: TStrings;
protected
function GetTitle: string;
procedure SetTitle(const Value: string);
function GetMessage: string; override;
procedure SetMessage(const Value: string); override;
function GetBuilder: TDialogBuilder; override;
procedure InitList(const ListView: TListViewEx; IsMulti: Boolean = False);
procedure InitExtPopView();
procedure InitSinglePopView();
procedure InitMultiPopView();
procedure InitListPopView();
procedure InitDefaultPopView();
procedure InitDownPopupView();
procedure AdjustDownPopupPosition();
protected
procedure DoButtonClick(Sender: TObject);
procedure DoListItemClick(Sender: TObject; ItemIndex: Integer; const ItemView: TControl);
procedure DoApplyTitle(); override;
procedure DoFreeBuilder(); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
/// <summary>
/// 以 Builder 的设置来初始化对话框
/// </summary>
procedure Apply(const ABuilder: TDialogBuilder); virtual;
/// <summary>
/// 对话框构造器
/// </summary>
property Builder: TDialogBuilder read FBuilder;
property Title: string read GetTitle write SetTitle;
property Items: TStrings read GetItems;
property OnKeyListener: TOnDialogKeyListener read FOnKeyListener write SetOnKeyListener;
property OnKeyListenerA: TOnDialogKeyListenerA read FOnKeyListenerA write FOnKeyListenerA;
end;
/// <summary>
/// 对话框构造器
/// </summary>
TDialogBuilder = class(TObject)
private
[Weak] FOwner: TComponent;
[Weak] FIcon: TObject;
[Weak] FItems: TStrings;
[Weak] FStyleManager: TDialogStyleManager;
[Weak] FDataObject: TObject;
FItemArray: TArray<string>;
FData: TValue;
FView: TControl;
FViewAutoFree: Boolean;
FUseRootBackColor: Boolean;
FRootBackColor: TAlphaColor;
FTitle: string;
FMessage: string;
FMessageIsHtml: Boolean;
FCancelable: Boolean;
FIsMaxWidth: Boolean;
FIsSingleChoice: Boolean;
FIsMultiChoice: Boolean;
FItemSingleLine: Boolean;
FClickButtonDismiss: Boolean;
FMaskVisible: Boolean;
FCheckedItem: Integer;
FTag: Integer;
FWidth: Single;
FMaxHeight: Single;
FListItemDefaultHeight: Single;
FPosition: TDialogViewPosition;
[Weak] FTarget: TControl;
FTargetOffsetX, FTargetOffsetY: Single;
FTargetGravity: TLayoutGravity;
FWordWrap: Boolean;
FCheckedItems: TArray<Boolean>;
FPositiveButtonText: string;
FPositiveButtonListener: TOnDialogClickListener;
FPositiveButtonListenerA: TOnDialogClickListenerA;
FPositiveButtonSize: Single;
FPositiveButtonColor: Int64;
FPositiveButtonStyle: TFontStyles;
FNegativeButtonText: string;
FNegativeButtonListener: TOnDialogClickListener;
FNegativeButtonListenerA: TOnDialogClickListenerA;
FNegativeButtonSize: Single;
FNegativeButtonColor: Int64;
FNegativeButtonStyle: TFontStyles;
FNeutralButtonText: string;
FNeutralButtonListener: TOnDialogClickListener;
FNeutralButtonListenerA: TOnDialogClickListenerA;
FNeutralButtonSize: Single;
FNeutralButtonColor: Int64;
FNeutralButtonStyle: TFontStyles;
FCancelButtonText: string;
FCancelButtonListener: TOnDialogClickListener;
FCancelButtonListenerA: TOnDialogClickListenerA;
FCancelButtonSize: Single;
FCancelButtonColor: Int64;
FCancelButtonStyle: TFontStyles;
FOnCancelListener: TOnDialogListener;
FOnCancelListenerA: TOnDialogListenerA;
FOnKeyListener: TOnDialogKeyListener;
FOnKeyListenerA: TOnDialogKeyListenerA;
FOnCheckboxClickListener: TOnDialogMultiChoiceClickListener;
FOnCheckboxClickListenerA: TOnDialogMultiChoiceClickListenerA;
FOnItemSelectedListener: TOnDialogItemSelectedListener;
FOnItemSelectedListenerA: TOnDialogItemSelectedListenerA;
FOnClickListener: TOnDialogClickListener;
FOnClickListenerA: TOnDialogClickListenerA;
FOnInitListAdapterA: TOnDialogInitListAdapterA;
FOnInitA: TOnDialogInitA;
FShadowVisible: Boolean;
function GetCheckedCount: Integer;
public
constructor Create(AOwner: TComponent); virtual;
destructor Destroy; override;
function CreateDialog(): IDialog;
function Show(): IDialog; overload;
function Show(OnDismissListener: TOnDialogListener): IDialog; overload;
function Show(OnDismissListener: TOnDialogListenerA): IDialog; overload;
/// <summary>
/// 设置Dialog初始化事件
/// </summary>
function SetOnInitA(AListener: TOnDialogInitA): TDialogBuilder;
/// <summary>
/// 设置一个对话框样式管理器,不设置则会自动查找,找不到则使用默认样式
/// </summary>
function SetStyleManager(AValue: TDialogStyleManager): TDialogBuilder;
/// <summary>
/// 设置是否最大化宽度
/// </summary>
function SetIsMaxWidth(AIsMaxWidth: Boolean): TDialogBuilder;
/// <summary>
/// 设置标题
/// </summary>
function SetTitle(const ATitle: string): TDialogBuilder;
/// <summary>
/// 设置消息
/// </summary>
function SetMessage(const AMessage: string; IsHtmlText: Boolean = False): TDialogBuilder;
/// <summary>
/// 设置图标
/// </summary>
function SetIcon(AIcon: TBrush): TDialogBuilder; overload;
/// <summary>
/// 设置图标
/// </summary>
function SetIcon(AIcon: TBrushBitmap): TDialogBuilder; overload;
/// <summary>
/// 设置图标
/// </summary>
function SetIcon(AIcon: TDrawableBase): TDialogBuilder; overload;
/// <summary>
/// 设置图标
/// </summary>
function SetIcon(AIcon: TBitmap): TDialogBuilder; overload;
/// <summary>
/// 设置将对话框作为下拉弹出菜单时的标靶和偏移 (Target非空时,对话框以下拉弹出菜单样式显示)
/// </summary>
function SetDownPopup(ATarget: TControl; const XOffset, YOffset: Single;
Gravity: TLayoutGravity = TLayoutGravity.LeftBottom;
MaskVisible: Boolean = False): TDialogBuilder;
/// <summary>
/// 设置位置
/// </summary>
function SetPosition(APosition: TDialogViewPosition): TDialogBuilder;
/// <summary>
/// 设置是否自动换行(列表项)
/// </summary>
function SetWordWrap(V: Boolean): TDialogBuilder;
/// <summary>
/// 设置确认按钮
/// </summary>
function SetPositiveButton(const AText: string; AListener: TOnDialogClickListener = nil): TDialogBuilder; overload;
function SetPositiveButton(const AText: string; AListener: TOnDialogClickListenerA): TDialogBuilder; overload;
function SetPositiveButtonStyle(const AColor: Int64; const AStyle: TFontStyles = []; const ASize: Single = -1): TDialogBuilder; overload;
/// <summary>
/// 设置否定按钮
/// </summary>
function SetNegativeButton(const AText: string; AListener: TOnDialogClickListener = nil): TDialogBuilder; overload;
function SetNegativeButton(const AText: string; AListener: TOnDialogClickListenerA): TDialogBuilder; overload;
function SetNegativeButtonStyle(const AColor: Int64; const AStyle: TFontStyles = []; const ASize: Single = -1): TDialogBuilder; overload;
/// <summary>
/// 设置中间按钮
/// </summary>
function SetNeutralButton(const AText: string; AListener: TOnDialogClickListener = nil): TDialogBuilder; overload;
function SetNeutralButton(const AText: string; AListener: TOnDialogClickListenerA): TDialogBuilder; overload;
function SetNeutralButtonStyle(const AColor: Int64; const AStyle: TFontStyles = []; const ASize: Single = -1): TDialogBuilder; overload;
/// <summary>
/// 设置底部取消按钮
/// </summary>
function SetCancelButton(const AText: string; AListener: TOnDialogClickListener = nil): TDialogBuilder; overload;
function SetCancelButton(const AText: string; AListener: TOnDialogClickListenerA): TDialogBuilder; overload;
function SetCancelButtonStyle(const AColor: Int64; const AStyle: TFontStyles = []; const ASize: Single = -1): TDialogBuilder; overload;
/// <summary>
/// 设置是否可以取消
/// </summary>
function SetCancelable(ACancelable: Boolean): TDialogBuilder;
/// <summary>
/// 设置取消事件
/// </summary>
function SetOnCancelListener(AListener: TOnDialogListener): TDialogBuilder; overload;
function SetOnCancelListener(AListener: TOnDialogListenerA): TDialogBuilder; overload;
/// <summary>
/// 设置按键监听事件
/// </summary>
function SetOnKeyListener(AListener: TOnDialogKeyListener): TDialogBuilder; overload;
function SetOnKeyListener(AListener: TOnDialogKeyListenerA): TDialogBuilder; overload;
/// <summary>
/// 设置列表项
/// </summary>
function SetItems(AItems: TStrings; AListener: TOnDialogClickListener = nil): TDialogBuilder; overload;
function SetItems(AItems: TStrings; AListener: TOnDialogClickListenerA): TDialogBuilder; overload;
function SetItems(const AItems: TArray<string>; AListener: TOnDialogClickListener = nil): TDialogBuilder; overload;
function SetItems(const AItems: TArray<string>; AListener: TOnDialogClickListenerA): TDialogBuilder; overload;
/// <summary>
/// 设置一个子视图
/// </summary>
function SetView(AView: TControl; AViewAutoFree: Boolean = True): TDialogBuilder;
/// <summary>
/// 设置多重选项列表项
/// </summary>
function SetMultiChoiceItems(AItems: TStrings; ACheckedItems: TArray<Boolean>;
AListener: TOnDialogMultiChoiceClickListener = nil): TDialogBuilder; overload;
function SetMultiChoiceItems(AItems: TStrings; ACheckedItems: TArray<Boolean>;
AListener: TOnDialogMultiChoiceClickListenerA): TDialogBuilder; overload;
function SetMultiChoiceItems(const AItems: TArray<string>; ACheckedItems: TArray<Boolean>;
AListener: TOnDialogMultiChoiceClickListener = nil): TDialogBuilder; overload;
function SetMultiChoiceItems(const AItems: TArray<string>; ACheckedItems: TArray<Boolean>;
AListener: TOnDialogMultiChoiceClickListenerA): TDialogBuilder; overload;
/// <summary>
/// 设置单选列表项
/// </summary>
function SetSingleChoiceItems(AItems: TStrings; ACheckedItem: Integer;
AListener: TOnDialogClickListener = nil): TDialogBuilder; overload;
function SetSingleChoiceItems(AItems: TStrings; ACheckedItem: Integer;
AListener: TOnDialogClickListenerA): TDialogBuilder; overload;
function SetSingleChoiceItems(const AItems: TArray<string>; ACheckedItem: Integer;
AListener: TOnDialogClickListener = nil): TDialogBuilder; overload;
function SetSingleChoiceItems(const AItems: TArray<string>; ACheckedItem: Integer;
AListener: TOnDialogClickListenerA): TDialogBuilder; overload;
/// <summary>
/// 设置列表项选择事件
/// </summary>
function SetOnItemSelectedListener(AListener: TOnDialogItemSelectedListener): TDialogBuilder; overload;
function SetOnItemSelectedListener(AListener: TOnDialogItemSelectedListenerA): TDialogBuilder; overload;
/// <summary>
/// 设置列表项是否为单行文本,默认为 True
/// </summary>
function SetItemSingleLine(AItemSingleLine: Boolean): TDialogBuilder;
/// <summary>
/// 设置是否在点击了按钮后释放对话框
/// </summary>
function SetClickButtonDismiss(V: Boolean): TDialogBuilder;
/// <summary>
/// 设置自定义列表数据适配器
/// </summary>
function SetOnInitListAdapterA(AListener: TOnDialogInitListAdapterA): TDialogBuilder;
/// <summary>
/// 设置 Mask 是否可视
/// </summary>
function SetMaskVisible(V: Boolean): TDialogBuilder;
/// <summary>
/// 设置 Shadow 是否可视
/// </summary>
function SetShadowVisible(V: Boolean): TDialogBuilder;
/// <summary>
/// 设置 对话框 Root 层背景颜色
/// </summary>
function SetRootBackColor(const V: TAlphaColor): TDialogBuilder;
/// <summary>
/// 设置宽度
/// </summary>
function SetWidth(const V: Single): TDialogBuilder;
/// <summary>
/// 设置最大高度
/// </summary>
function SetMaxHeight(const V: Single): TDialogBuilder;
/// <summary>
/// 设置列表项对话框默认行高
/// </summary>
function SetListItemDefaultHeight(const V: Single): TDialogBuilder;
/// <summary>
/// 设置附加的数据
/// </summary>
function SetData(const V: TObject): TDialogBuilder; overload;
function SetData(const V: TValue): TDialogBuilder; overload;
function SetTag(const V: Integer): TDialogBuilder;
public
property Owner: TComponent read FOwner;
property View: TControl read FView;
property Icon: TObject read FIcon;
property Items: TStrings read FItems;
property ItemArray: TArray<string> read FItemArray;
property StyleManager: TDialogStyleManager read FStyleManager;
property Title: string read FTitle;
property Message: string read FMessage;
property MessageIsHtml: Boolean read FMessageIsHtml;
property Cancelable: Boolean read FCancelable;
property IsMaxWidth: Boolean read FIsMaxWidth;
property IsSingleChoice: Boolean read FIsSingleChoice;
property IsMultiChoice: Boolean read FIsMultiChoice;
property ItemSingleLine: Boolean read FItemSingleLine;
property MaskVisible: Boolean read FMaskVisible write FMaskVisible;
property ShadowVisible: Boolean read FShadowVisible write FShadowVisible;
property RootBackColor: TAlphaColor read FRootBackColor write FRootBackColor;
property ClickButtonDismiss: Boolean read FClickButtonDismiss write FClickButtonDismiss;
property CheckedItem: Integer read FCheckedItem;
property CheckedItems: TArray<Boolean> read FCheckedItems;
property CheckedCount: Integer read GetCheckedCount;
property Target: TControl read FTarget;
property DataObject: TObject read FDataObject write FDataObject;
property Data: TValue read FData write FData;
property Tag: Integer read FTag write FTag;
property PositiveButtonText: string read FPositiveButtonText;
property PositiveButtonListener: TOnDialogClickListener read FPositiveButtonListener;
property PositiveButtonListenerA: TOnDialogClickListenerA read FPositiveButtonListenerA;
property PositiveButtonSize: Single read FPositiveButtonSize;
property PositiveButtonColor: Int64 read FPositiveButtonColor;
property PositiveButtonStyle: TFontStyles read FPositiveButtonStyle;
property NegativeButtonText: string read FNegativeButtonText;
property NegativeButtonListener: TOnDialogClickListener read FNegativeButtonListener;
property NegativeButtonListenerA: TOnDialogClickListenerA read FNegativeButtonListenerA;
property NegativeButtonSize: Single read FNegativeButtonSize;
property NegativeButtonColor: Int64 read FNegativeButtonColor;
property NegativeButtonStyle: TFontStyles read FNegativeButtonStyle;
property NeutralButtonText: string read FNeutralButtonText;
property NeutralButtonListener: TOnDialogClickListener read FNeutralButtonListener;
property NeutralButtonListenerA: TOnDialogClickListenerA read FNeutralButtonListenerA;
property NeutralButtonSize: Single read FNeutralButtonSize;
property NeutralButtonColor: Int64 read FNeutralButtonColor;
property NeutralButtonStyle: TFontStyles read FNeutralButtonStyle;
property CancelButtonText: string read FCancelButtonText;
property CancelButtonListener: TOnDialogClickListener read FCancelButtonListener;
property CancelButtonListenerA: TOnDialogClickListenerA read FCancelButtonListenerA;
property CancelButtonSize: Single read FCancelButtonSize;
property CancelButtonColor: Int64 read FCancelButtonColor;
property CancelButtonStyle: TFontStyles read FCancelButtonStyle;
property OnCancelListener: TOnDialogListener read FOnCancelListener;
property OnCancelListenerA: TOnDialogListenerA read FOnCancelListenerA;
property OnKeyListener: TOnDialogKeyListener read FOnKeyListener;
property OnKeyListenerA: TOnDialogKeyListenerA read FOnKeyListenerA;
property OnCheckboxClickListener: TOnDialogMultiChoiceClickListener read FOnCheckboxClickListener;
property OnItemSelectedListener: TOnDialogItemSelectedListener read FOnItemSelectedListener;
property OnClickListener: TOnDialogClickListener read FOnClickListener;
property OnClickListenerA: TOnDialogClickListenerA read FOnClickListenerA;
end;
type
/// <summary>
/// 对话框组件
/// </summary>
[ComponentPlatformsAttribute(AllCurrentPlatforms)]
TAlertDialog = class(TCustomAlertDialog)
published
property Cancelable default True;
property Title;
property Message;
property OnCancelListener;
property OnShowListener;
property OnKeyListener;
property OnDismissListener;
end;
type
/// <summary>
/// 等待对话框
/// </summary>
[ComponentPlatformsAttribute(AllCurrentPlatforms)]
TProgressDialog = class(TDialog)
private
[Weak] FStyleManager: TDialogStyleManager;
protected
function GetMessage: string; override;
procedure SetMessage(const Value: string); override;
procedure DoRootClick(Sender: TObject); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure InitView(const AMsg: string; IsHtmlText: Boolean = False);
/// <summary>
/// 显示一个等待对话框
/// </summary>
class function Show(AOwner: TComponent; const AMsg: string; ACancelable: Boolean = True): TProgressDialog;
published
property StyleManager: TDialogStyleManager read FStyleManager write FStyleManager;
end;
// 默认对话框样式
function GetDefaultStyleMgr: TDialogStyleManager;
implementation
uses
UI.Frame;
var
DefaultStyleManager: TDialogStyleManager = nil;
DialogRef: Integer = 0;
type
TFrameViewTmp = class(TFrameView);
function GetDefaultStyleMgr: TDialogStyleManager;
begin
if DefaultStyleManager = nil then
DefaultStyleManager := TDialogStyleManager.Create(nil);
Result := DefaultStyleManager;
end;
{ TDialogBuilder }
constructor TDialogBuilder.Create(AOwner: TComponent);
begin
FOwner := AOwner;
FView := nil;
FCancelable := True;
FItemSingleLine := True;
FClickButtonDismiss := True;
FMaskVisible := True;
FUseRootBackColor := False;
FRootBackColor := TAlphaColorRec.Null;
FIcon := nil;
FWordWrap := True;
FPosition := TDialogViewPosition.Center;
FPositiveButtonColor := -1;
FNegativeButtonColor := -1;
FNeutralButtonColor := -1;
FCancelButtonColor := -1;
end;
function TDialogBuilder.CreateDialog: IDialog;
var
Dlg: TAlertDialog;
begin
Dlg := TAlertDialog.Create(FOwner);
try
Dlg.Apply(Self);
Dlg.SetCancelable(FCancelable);
Dlg.SetOnCancelListener(FOnCancelListener);
Dlg.SetOnCancelListenerA(FOnCancelListenerA);
if Assigned(FOnKeyListener) then
Dlg.SetOnKeyListener(FOnKeyListener);
if Assigned(FOnInitA) then
FOnInitA(Dlg, Self);
Result := Dlg;
except
FreeAndNil(Dlg);
Result := nil;
end;
end;
destructor TDialogBuilder.Destroy;
begin
FIcon := nil;
FIcon := nil;
FItems := nil;
if Assigned(FView) then begin
FView.Parent := nil;
if FViewAutoFree then begin
if not (csDestroying in FView.ComponentState) then
FreeAndNil(FView);
end;
end;
inherited;
end;
function TDialogBuilder.GetCheckedCount: Integer;
var
I: Integer;
begin
Result := 0;
for I := 0 to Length(FCheckedItems) - 1 do
if FCheckedItems[I] then
Inc(Result);
end;
function TDialogBuilder.SetIcon(AIcon: TBrush): TDialogBuilder;
begin
Result := Self;
FIcon := AIcon;
end;
function TDialogBuilder.SetCancelable(ACancelable: Boolean): TDialogBuilder;
begin
Result := Self;
FCancelable := ACancelable;
end;
function TDialogBuilder.SetCancelButton(const AText: string;
AListener: TOnDialogClickListener): TDialogBuilder;
begin
Result := Self;
FCancelButtonText := AText;
FCancelButtonListener := AListener;
end;
function TDialogBuilder.SetCancelButton(const AText: string;
AListener: TOnDialogClickListenerA): TDialogBuilder;
begin
Result := Self;
FCancelButtonText := AText;
FCancelButtonListenerA := AListener;
end;
function TDialogBuilder.SetCancelButtonStyle(const AColor: Int64;
const AStyle: TFontStyles; const ASize: Single): TDialogBuilder;
begin
Result := Self;
FCancelButtonSize := ASize;
FCancelButtonColor := AColor;
FCancelButtonStyle := AStyle;
end;
function TDialogBuilder.SetClickButtonDismiss(V: Boolean): TDialogBuilder;
begin
Result := Self;
FClickButtonDismiss := V;
end;
function TDialogBuilder.SetData(const V: TObject): TDialogBuilder;
begin
Result := Self;
FDataObject := V;
end;
function TDialogBuilder.SetData(const V: TValue): TDialogBuilder;
begin
Result := Self;
FData := V;
end;
function TDialogBuilder.SetDownPopup(ATarget: TControl; const XOffset,
YOffset: Single; Gravity: TLayoutGravity; MaskVisible: Boolean): TDialogBuilder;
begin
Result := Self;
FTarget := ATarget;
FTargetOffsetX := XOffset;
FTargetOffsetY := YOffset;
FTargetGravity := Gravity;
FMaskVisible := MaskVisible;
end;
function TDialogBuilder.SetSingleChoiceItems(AItems: TStrings;
ACheckedItem: Integer; AListener: TOnDialogClickListenerA): TDialogBuilder;
begin
Result := Self;
FItems := AItems;
FOnClickListenerA := AListener;
FCheckedItem := ACheckedItem;
FIsSingleChoice := True;
end;
function TDialogBuilder.SetShadowVisible(V: Boolean): TDialogBuilder;
begin
Result := Self;
FShadowVisible := V;
end;
function TDialogBuilder.SetSingleChoiceItems(const AItems: TArray<string>;
ACheckedItem: Integer; AListener: TOnDialogClickListenerA): TDialogBuilder;
begin
Result := Self;
FItemArray := AItems;
FOnClickListenerA := AListener;
FCheckedItem := ACheckedItem;
FIsSingleChoice := True;
end;
function TDialogBuilder.SetSingleChoiceItems(const AItems: TArray<string>;
ACheckedItem: Integer; AListener: TOnDialogClickListener): TDialogBuilder;
begin
Result := Self;
FItemArray := AItems;
FOnClickListener := AListener;
FCheckedItem := ACheckedItem;
FIsSingleChoice := True;
end;
function TDialogBuilder.SetStyleManager(
AValue: TDialogStyleManager): TDialogBuilder;
begin
Result := Self;
FStyleManager := AValue;
end;
function TDialogBuilder.SetIcon(AIcon: TDrawableBase): TDialogBuilder;
begin
Result := Self;
FIcon := AIcon;
end;
function TDialogBuilder.SetIcon(AIcon: TBrushBitmap): TDialogBuilder;
begin
Result := Self;
FIcon := AIcon;
end;
function TDialogBuilder.SetIcon(AIcon: TBitmap): TDialogBuilder;
begin
Result := Self;
FIcon := AIcon;
end;
function TDialogBuilder.SetIsMaxWidth(AIsMaxWidth: Boolean): TDialogBuilder;
begin
Result := Self;
FIsMaxWidth := AIsMaxWidth;
end;
function TDialogBuilder.SetItems(AItems: TStrings;
AListener: TOnDialogClickListener): TDialogBuilder;
begin
Result := Self;
FItems := AItems;
FIsMultiChoice := False;
FOnClickListener := AListener;
end;
function TDialogBuilder.SetItems(AItems: TStrings;
AListener: TOnDialogClickListenerA): TDialogBuilder;
begin
Result := Self;
FItems := AItems;
FIsMultiChoice := False;
FOnClickListenerA := AListener;
end;
function TDialogBuilder.SetItems(const AItems: TArray<string>;
AListener: TOnDialogClickListener): TDialogBuilder;
begin
Result := Self;
FItemArray := AItems;
FIsMultiChoice := False;
FOnClickListener := AListener;
end;
function TDialogBuilder.SetItems(const AItems: TArray<string>;
AListener: TOnDialogClickListenerA): TDialogBuilder;
begin
Result := Self;
FItemArray := AItems;
FIsMultiChoice := False;
FOnClickListenerA := AListener;
end;
function TDialogBuilder.SetItemSingleLine(
AItemSingleLine: Boolean): TDialogBuilder;
begin
FItemSingleLine := AItemSingleLine;
Result := Self;
end;
function TDialogBuilder.SetListItemDefaultHeight(
const V: Single): TDialogBuilder;
begin
Result := Self;
FListItemDefaultHeight := V;
end;
function TDialogBuilder.SetMaskVisible(V: Boolean): TDialogBuilder;
begin
Result := Self;
FMaskVisible := V;
end;
function TDialogBuilder.SetMaxHeight(const V: Single): TDialogBuilder;
begin
Result := Self;
FMaxHeight := V;
end;
function TDialogBuilder.SetWidth(const V: Single): TDialogBuilder;
begin
Result := Self;
FWidth := V;
end;
function TDialogBuilder.SetWordWrap(V: Boolean): TDialogBuilder;
begin
FWordWrap := V;
Result := Self;
end;
function TDialogBuilder.SetMessage(const AMessage: string; IsHtmlText: Boolean): TDialogBuilder;
begin
Result := Self;
FMessage := AMessage;
FMessageIsHtml := IsHtmlText;
end;
function TDialogBuilder.SetMultiChoiceItems(const AItems: TArray<string>;
ACheckedItems: TArray<Boolean>;
AListener: TOnDialogMultiChoiceClickListenerA): TDialogBuilder;
begin
Result := Self;
FItemArray := AItems;
FOnCheckboxClickListenerA := AListener;
FCheckedItems := ACheckedItems;
FIsMultiChoice := True;
end;
function TDialogBuilder.SetMultiChoiceItems(const AItems: TArray<string>;
ACheckedItems: TArray<Boolean>;
AListener: TOnDialogMultiChoiceClickListener): TDialogBuilder;
begin
Result := Self;
FItemArray := AItems;
FOnCheckboxClickListener := AListener;
FCheckedItems := ACheckedItems;
FIsMultiChoice := True;
end;
function TDialogBuilder.SetMultiChoiceItems(AItems: TStrings;
ACheckedItems: TArray<Boolean>;
AListener: TOnDialogMultiChoiceClickListenerA): TDialogBuilder;
begin
Result := Self;
FItems := AItems;
FOnCheckboxClickListenerA := AListener;
FCheckedItems := ACheckedItems;
FIsMultiChoice := True;
end;
function TDialogBuilder.SetMultiChoiceItems(AItems: TStrings;
ACheckedItems: TArray<Boolean>;
AListener: TOnDialogMultiChoiceClickListener): TDialogBuilder;
begin
result := Self;
FItems := AItems;
FOnCheckboxClickListener := AListener;
FCheckedItems := ACheckedItems;
FIsMultiChoice := True;
end;
function TDialogBuilder.SetNegativeButton(const AText: string;
AListener: TOnDialogClickListener): TDialogBuilder;
begin
Result := Self;
FNegativeButtonText := AText;
FNegativeButtonListener := AListener;
end;
function TDialogBuilder.SetNeutralButton(const AText: string;
AListener: TOnDialogClickListener): TDialogBuilder;
begin
Result := Self;
FNeutralButtonText := AText;
FNeutralButtonListener := AListener;
end;
function TDialogBuilder.SetOnCancelListener(
AListener: TOnDialogListener): TDialogBuilder;
begin
Result := Self;
FOnCancelListener := AListener;
end;
function TDialogBuilder.SetOnCancelListener(
AListener: TOnDialogListenerA): TDialogBuilder;
begin
Result := Self;
FOnCancelListenerA := AListener;
end;
function TDialogBuilder.SetOnInitA(AListener: TOnDialogInitA): TDialogBuilder;
begin
Result := Self;
FOnInitA := AListener;
end;
function TDialogBuilder.SetOnInitListAdapterA(
AListener: TOnDialogInitListAdapterA): TDialogBuilder;
begin
Result := Self;
FOnInitListAdapterA := AListener;
end;
function TDialogBuilder.SetOnItemSelectedListener(
AListener: TOnDialogItemSelectedListenerA): TDialogBuilder;
begin
Result := Self;
FOnItemSelectedListenerA := AListener;
end;
function TDialogBuilder.SetOnItemSelectedListener(
AListener: TOnDialogItemSelectedListener): TDialogBuilder;
begin
Result := Self;
FOnItemSelectedListener := AListener;
end;
function TDialogBuilder.SetOnKeyListener(
AListener: TOnDialogKeyListenerA): TDialogBuilder;
begin
Result := Self;
FOnKeyListenerA := AListener;
end;
function TDialogBuilder.SetOnKeyListener(
AListener: TOnDialogKeyListener): TDialogBuilder;
begin
Result := Self;
FOnKeyListener := AListener;
end;
function TDialogBuilder.SetPosition(
APosition: TDialogViewPosition): TDialogBuilder;
begin
Result := Self;
FPosition := APosition;
end;
function TDialogBuilder.SetPositiveButton(const AText: string;
AListener: TOnDialogClickListenerA): TDialogBuilder;
begin
Result := Self;
FPositiveButtonText := AText;
FPositiveButtonListenerA := AListener;
end;
function TDialogBuilder.SetPositiveButtonStyle(const AColor: Int64;
const AStyle: TFontStyles; const ASize: Single): TDialogBuilder;
begin
Result := Self;
FPositiveButtonSize := ASize;
FPositiveButtonColor := AColor;
FPositiveButtonStyle := AStyle;
end;
function TDialogBuilder.SetRootBackColor(const V: TAlphaColor): TDialogBuilder;
begin
Result := Self;
FRootBackColor := V;
FUseRootBackColor := True;
end;
function TDialogBuilder.SetPositiveButton(const AText: string;
AListener: TOnDialogClickListener): TDialogBuilder;
begin
Result := Self;
FPositiveButtonText := AText;
FPositiveButtonListener := AListener;
end;
function TDialogBuilder.SetSingleChoiceItems(AItems: TStrings;
ACheckedItem: Integer; AListener: TOnDialogClickListener): TDialogBuilder;
begin
Result := Self;
FItems := AItems;
FOnClickListener := AListener;
FCheckedItem := ACheckedItem;
FIsSingleChoice := True;
end;
function TDialogBuilder.SetTag(const V: Integer): TDialogBuilder;
begin
Result := Self;
FTag := V;
end;
function TDialogBuilder.SetTitle(const ATitle: string): TDialogBuilder;
begin
Result := Self;
FTitle := ATitle;
end;
function TDialogBuilder.SetView(AView: TControl; AViewAutoFree: Boolean): TDialogBuilder;
begin
Result := Self;
FView := AView;
FViewAutoFree := AViewAutoFree;
end;
function TDialogBuilder.Show(OnDismissListener: TOnDialogListener): IDialog;
begin
Result := CreateDialog();
if Assigned(Result) then begin
if Assigned(OnDismissListener) then
(Result as TAlertDialog).FOnDismissListener := OnDismissListener;
Result.Show();
end;
end;
function TDialogBuilder.Show(OnDismissListener: TOnDialogListenerA): IDialog;
begin
Result := CreateDialog();
if Assigned(Result) then begin
if Assigned(OnDismissListener) then
(Result as TAlertDialog).FOnDismissListenerA := OnDismissListener;
Result.Show();
end;
end;
function TDialogBuilder.Show: IDialog;
begin
Result := CreateDialog();
if Assigned(Result) then
Result.Show();
end;
function TDialogBuilder.SetNegativeButton(const AText: string;
AListener: TOnDialogClickListenerA): TDialogBuilder;
begin
Result := Self;
FNegativeButtonText := AText;
FNegativeButtonListenerA := AListener;
end;
function TDialogBuilder.SetNegativeButtonStyle(const AColor: Int64;
const AStyle: TFontStyles; const ASize: Single): TDialogBuilder;
begin
Result := Self;
FNegativeButtonSize := ASize;
FNegativeButtonColor := AColor;
FNegativeButtonStyle := AStyle;
end;
function TDialogBuilder.SetNeutralButton(const AText: string;
AListener: TOnDialogClickListenerA): TDialogBuilder;
begin
Result := Self;
FNeutralButtonText := AText;
FNeutralButtonListenerA := AListener;
end;
function TDialogBuilder.SetNeutralButtonStyle(const AColor: Int64;
const AStyle: TFontStyles; const ASize: Single): TDialogBuilder;
begin
Result := Self;
FNeutralButtonSize := ASize;
FNeutralButtonColor := AColor;
FNeutralButtonStyle := AStyle;
end;
{ TDialog }
procedure TDialog.AnimatePlay(Ani: TFrameAniType; IsIn: Boolean;
AEvent: TNotifyEventA);
var
AniView: TControl;
// 背景淡入淡出
procedure DoFadeInOutBackgroyund();
var
NewValue: TAlphaColor;
begin
if not FMask then Exit;
if not Assigned(FViewRoot) then Exit;
if IsIn then begin
if (FViewRoot.Background.ItemDefault.Color and $FF000000 = 0) then
Exit;
NewValue := FViewRoot.Background.ItemDefault.Color;
FViewRoot.Background.ItemDefault.Color := 0;
end else
NewValue := 0;
TFrameAnimator.AnimateColor(FViewRoot, 'Background.ItemDefault.Color', NewValue, nil, 0.3);
end;
// 淡入淡出
procedure DoFadeInOut();
var
NewValue: Single;
begin
// 背景处理
if Assigned(AniView) then begin
if IsIn then begin
AniView.Opacity := 0;
NewValue := 1;
end else begin
NewValue := 0;
end;
TFrameAnimator.AnimateFloat(AniView, 'Opacity', NewValue, AEvent, 0.15);
end;
end;
// 从顶部弹出
procedure DoTopMoveInOut();
var
NewValue: Single;
begin
if Assigned(AniView) and Assigned(FViewRoot) then begin
if IsIn then begin
AniView.Position.Y := - AniView.Height;
NewValue := 0;
TFrameAnimator.AnimateFloat(AniView, 'Position.Y', NewValue, AEvent);
end else begin
NewValue := - FViewRoot.Height - AniView.Height;
TFrameAnimator.AnimateFloat(AniView, 'Position.Y', NewValue, AEvent, 0.05);
end;
end;
end;
// 从底部弹出
procedure DoBottomMoveInOut();
var
NewValue: Single;
begin
if Assigned(AniView) and Assigned(FViewRoot) then begin
if IsIn then begin
AniView.Position.Y := FViewRoot.Height;
NewValue := FViewRoot.Height - AniView.Height;
TFrameAnimator.AnimateFloat(AniView, 'Position.Y', NewValue, AEvent);
end else begin
NewValue := FViewRoot.Height;
TFrameAnimator.AnimateFloat(AniView, 'Position.Y', NewValue, AEvent, 0.05);
end;
end;
end;
// 从左边弹出 弹入菜单
procedure DoLeftSlideMenu();
var
NewValue: Single;
LFrame: TFrame;
begin
if (Owner is TFrame) then LFrame := TFrame(Owner) else LFrame := nil;
if Assigned(AniView) and Assigned(FViewRoot) then begin
if IsIn then begin
NewValue := AniView.Position.X;
AniView.Position.X := -FViewRoot.Width + 1;
TFrameAnimator.AnimateFloat(AniView, 'Position.X', NewValue, AEvent);
if Assigned(LFrame) then begin
FTempValue := LFrame.Position.X;
TFrameAnimator.AnimateFloat(LFrame, 'Position.X', FTempValue + AniView.Width, AEvent);
end;
end else begin
NewValue := -FViewRoot.Width + 1;
TFrameAnimator.AnimateFloat(AniView, 'Position.X', NewValue, AEvent, 0.15);
if Assigned(LFrame) then
TFrameAnimator.AnimateFloat(LFrame, 'Position.X', FTempValue, nil, 0.15);
end;
end;
end;
// 从右边弹出 弹入菜单
procedure DoRightSlideMenu();
var
NewValue: Single;
LFrame: TFrame;
begin
if (Owner is TFrame) then LFrame := TFrame(Owner) else LFrame := nil;
if Assigned(AniView) and Assigned(FViewRoot) then begin
if IsIn then begin
NewValue := FViewRoot.Width - AniView.Width;
AniView.Position.X := FViewRoot.Width + 1;
TFrameAnimator.AnimateFloat(AniView, 'Position.X', NewValue, AEvent);
if Assigned(LFrame) then begin
FTempValue := LFrame.Position.X;
TFrameAnimator.AnimateFloat(LFrame, 'Position.X', FTempValue - AniView.Width, AEvent);
end
end else begin
NewValue := FViewRoot.Width + 1;
TFrameAnimator.AnimateFloat(AniView, 'Position.X', NewValue, AEvent, 0.15);
if Assigned(LFrame) then
TFrameAnimator.AnimateFloat(LFrame, 'Position.X', FTempValue, nil, 0.15);
end;
end;
end;
begin
if not Assigned(FViewRoot) then Exit;
AniView := GetAniView;
// 淡入淡出背景
DoFadeInOutBackgroyund();
// 如果图层完全不可见,设置动画时会出错
if (not Assigned(AniView)) or (not FMask) or
((AniView is TView) and (TView(AniView).Background.ItemDefault.Color and $FF000000 = 0)) then begin
if Assigned(AEvent) then
AEvent(Self);
Exit;
end;
// 处理动画
case Ani of
TFrameAniType.FadeInOut:
DoFadeInOut;
TFrameAniType.TopMoveInOut:
DoTopMoveInOut;
TFrameAniType.BottomMoveInOut:
DoBottomMoveInOut;
TFrameAniType.LeftSlideMenu:
DoLeftSlideMenu;
TFrameAniType.RightSlideMenu:
DoRightSlideMenu;
else
begin
// 无动画效果
if Assigned(AEvent) then
AEvent(Self);
if IsIn then
AniView.Opacity := 1
else
AniView.Opacity := 0;
end;
end;
end;
procedure TDialog.AsyncDismiss;
begin
DoAsyncDismiss();
end;
procedure TDialog.Cancel;
begin
if (not FCanceled) then begin
FCanceled := True;
if Assigned(FOnCancelListenerA) then
FOnCancelListenerA(Self)
else if Assigned(FOnCancelListener) then
FOnCancelListener(Self);
end;
DoAsyncDismiss;
end;
procedure TDialog.Close;
begin
Dismiss;
end;
class procedure TDialog.CloseDialog(const Target: TControl);
var
Dialog: IDialog;
begin
Dialog := GetDialog(Target);
if Assigned(Dialog) then
Dialog.AsyncDismiss;
end;
constructor TDialog.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FCancelable := True;
FCanceled := False;
FAnimate := TFrameAniType.FadeInOut;
FMask := True;
end;
destructor TDialog.Destroy;
begin
{$IFNDEF MSWINDOWS}
AtomicDecrement(DialogRef);// may cause duplicate name
{$ENDIF}
if Assigned(Self) then begin
FIsDismiss := True;
if (FViewRoot <> nil) then begin
FEventing := False;
Dismiss;
FViewRoot := nil;
end;
end;
FViewRoot := nil;
inherited Destroy;
end;
procedure TDialog.Dismiss;
var
LTarget: TControl;
LParent: TFmxObject;
begin
if not Assigned(Self) then
Exit;
if FEventing then begin
FAllowDismiss := True;
Exit;
end;
if FIsDismiss then
Exit;
FIsDismiss := True;
if Assigned(FOnDismissListenerA) then begin
FOnDismissListenerA(Self);
FOnDismissListenerA := nil;
FOnDismissListener := nil;
end else if Assigned(FOnDismissListener) then begin
FOnDismissListener(Self);
FOnDismissListener := nil;
end;
if Assigned(GetBuilder()) then
LTarget := GetBuilder.FTarget
else
LTarget := nil;
DoFreeBuilder();
if (FViewRoot <> nil) and Assigned(FViewRoot.Parent) then begin
{$IFDEF MSWINDOWS}
FViewRoot.ParentForm.ReleaseCapture;
{$ENDIF}
LParent := FViewRoot.Parent;
FViewRoot.Parent.RemoveObject(FViewRoot);
FreeAndNil(FViewRoot);
if LTarget <> nil then
LTarget.SetFocusObject(LTarget)
else if LParent <> nil then begin
if LParent is TControl then
TControl(LParent).SetFocus
else if LParent is TCustomForm then
// 暂不处理
end;
end;
if not (csDestroying in ComponentState) then
DisposeOf;
end;
procedure TDialog.DoApplyTitle;
begin
end;
procedure TDialog.DoAsyncDismiss;
var
AniView: TControl;
begin
if Assigned(Self) and Assigned(Owner) then begin
if FEventing then begin
FAllowDismiss := True;
Exit;
end;
if (FViewRoot <> nil) then begin
if (FViewRoot.FLayBubble <> nil) then
FViewRoot.FLayBubble.Visible := False
// else if FViewRoot.ControlsCount = 1 then // ShowView 时会是这种情况
// FViewRoot.Controls[0].Visible := False;
end;
if FAnimate = TFrameAniType.None then begin
AniView := GetAniView;
if Assigned(AniView) then begin
TFrameAnimator.DelayExecute(AniView,
procedure (Sender: TObject)
begin
Dismiss;
end,
0.05);
end else
Dismiss;
end else
AnimatePlay(FAnimate, False,
procedure (Sendet: TObject)
begin
Dismiss;
end
);
end;
end;
procedure TDialog.DoFreeBuilder;
begin
if (not (csDestroying in ComponentState)) and Assigned(FViewRoot) and
(FViewRoot.ChildrenCount = 1) and (FViewRoot.FLayBubble = nil)
then
{$IF CompilerVersion >= 30}
FViewRoot.Children[0].Parent := nil;
{$ELSE}
FViewRoot.Controls[0].Parent := nil;
{$ENDIF}
end;
procedure TDialog.DoRootClick(Sender: TObject);
begin
if FCancelable then
Cancel;
end;
function TDialog.GetAniView: TControl;
begin
if Assigned(FViewRoot.FLayBubble) then
Result := FViewRoot.FLayBubble
else begin
if FViewRoot.{$IF CompilerVersion >= 30}ControlsCount{$ELSE}ChildrenCount{$ENDIF} = 1 then
Result := FViewRoot.Controls[0]
else
Result := nil;
end;
end;
function TDialog.GetBuilder: TDialogBuilder;
begin
Result := nil;
end;
function TDialog.GetCancelable: Boolean;
begin
Result := FCancelable;
end;
class function TDialog.GetDialog(const Target: TControl): IDialog;
var
V: TControl;
begin
Result := nil;
if (Target = nil) or (Target.Parent = nil) then Exit;
V := Target.ParentControl;
while V <> nil do begin
if V is TDialogView then begin
Result := (V as TDialogView).FDialog;
Break;
end;
V := V.ParentControl;
end;
end;
function TDialog.GetFirstParent: TFmxObject;
var
P: TFmxObject;
begin
if Owner is TFmxObject then begin
P := TFmxObject(Owner);
while P.Parent <> nil do
P := P.Parent;
Result := P;
end else
Result := nil;
end;
function TDialog.GetIsDismiss: Boolean;
begin
Result := (not Assigned(Self)) or FIsDismiss;
end;
function TDialog.GetMessage: string;
begin
Result := '';
end;
function TDialog.GetRootView: TDialogView;
begin
Result := FViewRoot;
end;
function TDialog.GetView: TControl;
begin
if FViewRoot <> nil then begin
Result := FViewRoot.FLayBubble;
if Result = nil then
Result := FViewRoot;
end else
Result := nil;
end;
function TDialog.GetViewRoot: TDialogView;
begin
Result := FViewRoot;
end;
procedure TDialog.Hide;
begin
if FViewRoot <> nil then
FViewRoot.Hide;
end;
procedure TDialog.InitOK;
begin
if FViewRoot <> nil then
FViewRoot.InitOK;
end;
procedure TDialog.NotifyDataSetChanged;
begin
if Assigned(FViewRoot) then
FViewRoot.Repaint;
end;
procedure TDialog.SetCancelable(const Value: Boolean);
begin
FCancelable := Value;
end;
procedure TDialog.SetMessage(const Value: string);
begin
end;
procedure TDialog.SetOnCancelListener(const Value: TOnDialogListener);
begin
FOnCancelListener := Value;
end;
procedure TDialog.SetOnCancelListenerA(const Value: TOnDialogListenerA);
begin
FOnCancelListenerA := Value;
end;
procedure TDialog.Show;
begin
try
if Assigned(FViewRoot) then begin
DoApplyTitle();
if Assigned(FOnShowListenerA) then
FOnShowListenerA(Self)
else if Assigned(FOnCancelListener) then
FOnCancelListener(Self);
FViewRoot.Show;
AnimatePlay(FAnimate, True, nil);
end;
except
{$IFDEF WINDOWS}LogE(Self, 'Show', Exception(ExceptObject)); {$ENDIF}
Dismiss;
end;
end;
class function TDialog.ShowView(const AOwner: TComponent; const Target: TControl;
const ViewClass: TControlClass; XOffset: Single; YOffset: Single;
Position: TDialogViewPosition; Cancelable: Boolean; Ani: TFrameAniType;
Mask: Boolean; Shadow: Boolean): TDialog;
var
AView: TControl;
begin
AView := ViewClass.Create(AOwner);
Result := ShowView(AOwner, Target, AView, True, XOffset, YOffset, Position, Cancelable, Ani, Mask, Shadow);
end;
class function TDialog.ShowView(const AOwner: TComponent; const Target, View: TControl;
AViewAutoFree: Boolean; XOffset: Single; YOffset: Single;
Position: TDialogViewPosition; Cancelable: Boolean; Ani: TFrameAniType;
Mask: Boolean; Shadow: Boolean): TDialog;
var
Dialog: TDialog;
X, Y, PW, PH: Single;
P: TPointF;
begin
Result := nil;
if View = nil then Exit;
AtomicIncrement(DialogRef);
Dialog := TDialog.Create(AOwner);
Dialog.FViewRoot := TDialogView.Create(AOwner);
Dialog.FViewRoot.Dialog := Dialog;
Dialog.FViewRoot.BeginUpdate;
//Dialog.FViewRoot.FDisableAlign := True;
Dialog.FViewRoot.OnClick := Dialog.DoRootClick;
Dialog.FViewRoot.Parent := Dialog.GetFirstParent;
if Dialog.FViewRoot.Parent = nil then begin
Dialog.FViewRoot.EndUpdate;
Dialog.Dismiss;
Exit;
end;
Dialog.FViewRoot.Clickable := True;
Dialog.FViewRoot.Align := TAlignLayout.Contents; //TAlignLayout.Client;
Dialog.FViewRoot.Index := Dialog.FViewRoot.Parent.ChildrenCount - 1;
Dialog.FViewRoot.Background.ItemDefault.Kind := TViewBrushKind.Solid;
Dialog.FViewRoot.CanFocus := False;
View.Name := '';
View.Parent := Dialog.FViewRoot;
X := 0;
Y := 0;
if Assigned(Target) then begin
P := TPointF.Zero;
P := Target.LocalToAbsolute(P);
PW := Target.Width;
PH := Target.Height;
case Position of
Top:
begin
X := (PW - View.Width) / 2 + P.X + XOffset;
Y := P.Y - View.Height - YOffset;
end;
Bottom:
begin
X := (PW - View.Width) / 2 + P.X + XOffset;
Y := P.Y + PH + YOffset;
end;
LeftBottom:
begin
X := P.X + XOffset;
Y := P.Y + PH + YOffset;
end;
RightBottom:
begin
X := PW - P.X + XOffset;
Y := P.Y + PH + YOffset;
end;
Left:
begin
X := P.X - View.Width - XOffset;
Y := (PH - View.Height) / 2 + P.Y + YOffset;
end;
Right:
begin
X := P.X + PW + XOffset;
Y := (PH - View.Height) / 2 + P.Y + YOffset;
end;
Center:
begin
X := (PW - View.Width) / 2 + P.X + XOffset;
Y := (PH - View.Height) / 2 + P.Y + YOffset;
end;
end;
end else begin
PW := Dialog.FViewRoot.Width;
PH := Dialog.FViewRoot.Height;
case Position of
Top:
begin
X := (PW - View.Width) / 2 + XOffset;
Y := 0 + YOffset;
end;
Bottom:
begin
X := (PW - View.Width) / 2 + XOffset;
Y := PH - View.Height - YOffset;
end;
Left:
begin
X := 0 + XOffset;
Y := (PH - View.Height) / 2 + YOffset;
end;
Right:
begin
X := PW - View.Width - XOffset;
Y := (PH - View.Height) / 2 + YOffset;
end;
Center:
begin
X := (PW - View.Width) / 2 + XOffset;
Y := (PH - View.Height) / 2 + YOffset;
end;
end;
end;
case Position of
LeftFill:
begin
X := 0 + XOffset;
Y := 0 + YOffset;
View.Height := Dialog.FViewRoot.Height - YOffset * 2;
View.Width := (Dialog.FViewRoot.Width - XOffset) * SIZE_MENU_WIDTH;
View.Align := TAlignLayout.Left;
end;
RightFill:
begin
PW := Dialog.FViewRoot.Width;
PH := Dialog.FViewRoot.Height;
View.Width := (PW - XOffset) * SIZE_MENU_WIDTH;
X := PW - XOffset - View.Width;
View.Height := PH - YOffset * 2;
Y := 0 + YOffset;
View.Align := TAlignLayout.Right;
end;
end;
{$IFDEF ANDROID}
if Y = 0 then begin
View.Padding.Top := TView.GetStatusHeight;
if View is TFrameView then
with TFrameViewTmp(View) do
if IsUseDefaultBackColor or (BackColor and $FF000000 = 0) then
BackColor := StatusColor;
end;
{$ENDIF}
View.Position.Point := TPointF.Create(X, Y);
if View is TFrameView then
TFrameViewTmp(View).DoShow();
Dialog.FAnimate := Ani;
Dialog.FMask := Mask;
Dialog.Cancelable := Cancelable;
if Mask then
Dialog.FViewRoot.InitMask(GetDefaultStyleMgr);
if Shadow then
Dialog.FViewRoot.InitShadow(GetDefaultStyleMgr);
//Dialog.FViewRoot.FDisableAlign := True;
Dialog.InitOK;
Dialog.AnimatePlay(Dialog.FAnimate, True, nil);
Result := Dialog;
end;
{ TCustomAlertDialog }
procedure TCustomAlertDialog.AdjustDownPopupPosition;
var
P: TPointF;
PW, PH, SW, SH, W, H, X, Y, OX, OY: Single;
begin
P := TPointF.Zero;
P := FBuilder.FTarget.LocalToAbsolute(P);
W := FBuilder.FTarget.Width;
H := FBuilder.FTarget.Height;
PW := FViewRoot.Width;
PH := FViewRoot.Height;
SW := FViewRoot.FLayBubble.Width;
SH := FViewRoot.FLayBubble.Height;
X := P.X;
Y := P.Y;
OX := FBuilder.FTargetOffsetX;
OY := FBuilder.FTargetOffsetY;
case FBuilder.FTargetGravity of
TLayoutGravity.LeftTop:
begin
X := X + OX;
Y := Y - SH - OY;
end;
TLayoutGravity.LeftBottom:
begin
X := X + OX;
Y := Y + H + OY;
end;
TLayoutGravity.RightTop:
begin
X := X + W - SW - OX;
Y := Y - SH - OY;
end;
TLayoutGravity.RightBottom:
begin
X := X + W - SW - OX;
Y := Y + H + OY;
end;
end;
FViewRoot.FLayBubble.Position.Point := PointF(X, Y);
case FBuilder.FTargetGravity of
TLayoutGravity.LeftTop, TLayoutGravity.RightTop:
H := SH + Y - FViewRoot.FLayBubble.Margins.Top - FViewRoot.FLayBubble.Margins.Bottom;
else
H := PH - Y - FViewRoot.FLayBubble.Margins.Top - FViewRoot.FLayBubble.Margins.Bottom;
end;
if (H < FViewRoot.FLayBubble.MaxHeight) or (FViewRoot.FLayBubble.MaxHeight = 0) then
FViewRoot.FLayBubble.MaxHeight := H;
end;
procedure TCustomAlertDialog.Apply(const ABuilder: TDialogBuilder);
begin
AtomicIncrement(DialogRef);
FBuilder := ABuilder;
if ABuilder = nil then Exit;
FIsDowPopup := False;
if Assigned(FBuilder.FTarget) then begin
FIsDowPopup := True;
InitDownPopupView();
end else begin
if ABuilder.View <> nil then
// 附加 View 的对话框
InitExtPopView()
else if ABuilder.FIsSingleChoice then
// 单选对话框
InitSinglePopView()
else if ABuilder.FIsMultiChoice then
// 多选对话框
InitMultiPopView()
else if (Length(ABuilder.FItemArray) > 0) or
(Assigned(ABuilder.Items) and (ABuilder.Items.Count > 0)) then
// 列表框
InitListPopView()
else
// 基本对话框
InitDefaultPopView();
end;
InitOK();
FViewRoot.FIsDownPopup := FIsDowPopup;
end;
procedure TCustomAlertDialog.DoApplyTitle;
begin
SetTitle(FBuilder.FTitle);
end;
constructor TCustomAlertDialog.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
end;
destructor TCustomAlertDialog.Destroy;
begin
FreeAndNil(FBuilder);
inherited Destroy;
end;
procedure TCustomAlertDialog.DoButtonClick(Sender: TObject);
begin
if FViewRoot <> nil then begin
FEventing := True;
FAllowDismiss := False;
try
if Sender = FViewRoot.FButtonPositive then begin
if Assigned(Builder.FPositiveButtonListenerA) then
Builder.FPositiveButtonListenerA(Self, BUTTON_POSITIVE)
else if Assigned(Builder.PositiveButtonListener) then
Builder.PositiveButtonListener(Self, BUTTON_POSITIVE)
else // 没有事件的按钮点击后关闭对话框
FAllowDismiss := True;
end else if Sender = FViewRoot.FButtonNegative then begin
if Assigned(Builder.FNegativeButtonListenerA) then
Builder.FNegativeButtonListenerA(Self, BUTTON_NEGATIVE)
else if Assigned(Builder.NegativeButtonListener) then
Builder.NegativeButtonListener(Self, BUTTON_NEGATIVE)
else
FAllowDismiss := True;
end else if Sender = FViewRoot.FButtonNeutral then begin
if Assigned(Builder.FNeutralButtonListenerA) then
Builder.FNeutralButtonListenerA(Self, BUTTON_NEUTRAL)
else if Assigned(Builder.NeutralButtonListener) then
Builder.NeutralButtonListener(Self, BUTTON_NEUTRAL)
else
FAllowDismiss := True;
end else if Sender = FViewRoot.FButtonCancel then begin
if Assigned(Builder.FCancelButtonListenerA) then
Builder.FCancelButtonListenerA(Self, BUTTON_CANCEL)
else if Assigned(Builder.CancelButtonListener) then
Builder.CancelButtonListener(Self, BUTTON_CANCEL)
else
FAllowDismiss := True;
end;
except
end;
FEventing := False;
if FAllowDismiss or (Assigned(Builder) and Builder.FClickButtonDismiss) then begin
FAllowDismiss := False;
AsyncDismiss;
end;
end;
end;
procedure TCustomAlertDialog.DoFreeBuilder;
begin
if Assigned(FBuilder) then
FreeAndNil(FBuilder);
end;
procedure TCustomAlertDialog.DoListItemClick(Sender: TObject; ItemIndex: Integer;
const ItemView: TControl);
var
B: Boolean;
begin
if (FViewRoot = nil) or (FViewRoot.FListView = nil) then Exit;
FEventing := True;
FAllowDismiss := False;
try
if FBuilder.FIsMultiChoice then begin
B := TStringsListCheckAdapter(TListViewEx(Sender).Adapter).ItemCheck[ItemIndex];
if Length(FBuilder.FCheckedItems) > ItemIndex then
FBuilder.FCheckedItems[ItemIndex] := B;
if Assigned(FBuilder.FOnCheckboxClickListenerA) then
FBuilder.FOnCheckboxClickListenerA(Self, ItemIndex, B)
else if Assigned(FBuilder.FOnCheckboxClickListener) then
FBuilder.FOnCheckboxClickListener(Self, ItemIndex, B);
end else begin
if FBuilder.FIsSingleChoice then
FBuilder.FCheckedItem := ItemIndex;
if Assigned(FBuilder.OnClickListenerA) then
FBuilder.OnClickListenerA(Self, ItemIndex)
else if Assigned(FBuilder.OnClickListener) then
FBuilder.OnClickListener(Self, ItemIndex);
if (not (FBuilder.FIsMultiChoice or FBuilder.FIsSingleChoice)) and (not FAllowDismiss) then
DoAsyncDismiss;
end;
except
end;
FEventing := False;
if FAllowDismiss then begin
FAllowDismiss := False;
DoAsyncDismiss;
end;
end;
function TCustomAlertDialog.GetBuilder: TDialogBuilder;
begin
Result := FBuilder;
end;
function TCustomAlertDialog.GetItems: TStrings;
begin
if Assigned(FBuilder) then
Result := FBuilder.FItems
else
Result := nil;
end;
function TCustomAlertDialog.GetMessage: string;
begin
if Assigned(FBuilder) then
Result := FBuilder.FMessage
else
Result := '';
end;
function TCustomAlertDialog.GetTitle: string;
begin
if Assigned(FBuilder) then
Result := FBuilder.FTitle
else
Result := '';
end;
procedure TCustomAlertDialog.InitDefaultPopView;
var
StyleMgr: TDialogStyleManager;
ButtonLayoutHeight: Single;
BodyMH: Single;
begin
StyleMgr := FBuilder.FStyleManager;
if StyleMgr = nil then
StyleMgr := GetDefaultStyleMgr;
// 初始化基础
FViewRoot := TDialogView.Create(Owner);
FViewRoot.Dialog := Self;
FViewRoot.BeginUpdate;
FViewRoot.OnClick := DoRootClick;
FViewRoot.Parent := GetFirstParent;
if FViewRoot.Parent = nil then begin
Dismiss;
Exit;
end;
FViewRoot.Clickable := True;
FViewRoot.Align := TAlignLayout.Contents; // TAlignLayout.Client;
FViewRoot.Index := FViewRoot.Parent.ChildrenCount - 1;
FViewRoot.Background.ItemDefault.Kind := TViewBrushKind.Solid;
FViewRoot.InitView(StyleMgr);
if Builder.FWidth > 0 then begin
FViewRoot.FLayBubble.WidthSize := TViewSize.CustomSize;
FViewRoot.FLayBubble.Size.Width := Builder.FWidth;
FViewRoot.FLayBubble.MaxWidth := Builder.FWidth;
FViewRoot.FLayBubble.AdjustViewBounds := True;
end;
if FBuilder.FMaxHeight > 0 then
FViewRoot.FLayBubble.MaxHeight := FBuilder.FMaxHeight;
// 初始化消息区
if (Builder.FIcon <> nil) or (Builder.FMessage <> '') then begin
FViewRoot.InitMessage(StyleMgr);
if Builder.MessageIsHtml then
FViewRoot.FMsgMessage.HtmlText := Builder.FMessage
else
FViewRoot.FMsgMessage.Text := Builder.FMessage;
if Assigned(Builder.FIcon) then begin
if Builder.FIcon is TDrawableBase then
FViewRoot.FMsgMessage.Drawable.Assign(TDrawableBase(Builder.FIcon))
else if Builder.FIcon is TBrush then
FViewRoot.FMsgMessage.Drawable.ItemDefault.Assign(TBrush(Builder.FIcon))
else if Builder.FIcon is TBrushBitmap then begin
FViewRoot.FMsgMessage.Drawable.ItemDefault.Bitmap.Assign(TBrushBitmap(Builder.FIcon));
FViewRoot.FMsgMessage.Drawable.ItemDefault.Kind := TBrushKind.Bitmap;
end
else if Builder.FIcon is TBitmap then begin
FViewRoot.FMsgMessage.Drawable.ItemDefault.Bitmap.Bitmap.Assign(TBitmap(Builder.FIcon));
FViewRoot.FMsgMessage.Drawable.ItemDefault.Kind := TBrushKind.Bitmap;
end;
end;
end else
FViewRoot.FMsgBody.Visible := False;
// 初始化列表
if (Length(Builder.FItemArray) > 0) or
((Assigned(Builder.FItems)) and (Builder.FItems.Count > 0)) then begin
FViewRoot.InitList(StyleMgr);
end;
// 初始化按钮
FViewRoot.InitButton(StyleMgr);
if Assigned(FViewRoot.FButtonLayout) then begin
if Assigned(FViewRoot.FButtonPositive) then
FViewRoot.FButtonPositive.OnClick := DoButtonClick;
if Assigned(FViewRoot.FButtonNegative) then
FViewRoot.FButtonNegative.OnClick := DoButtonClick;
if Assigned(FViewRoot.FButtonNeutral) then
FViewRoot.FButtonNeutral.OnClick := DoButtonClick;
ButtonLayoutHeight := FViewRoot.FButtonLayout.Height
end
else
ButtonLayoutHeight := 0;
if Assigned(FViewRoot.FButtonCancel) then
FViewRoot.FButtonCancel.OnClick := DoButtonClick;
if (Builder.Title = '') or (ButtonLayoutHeight = 0) then begin
FViewRoot.FMsgBody.Background.XRadius := StyleMgr.FBackgroundRadius;
FViewRoot.FMsgBody.Background.YRadius := StyleMgr.FBackgroundRadius;
if ButtonLayoutHeight = 0 then begin
if Builder.Title = '' then
FViewRoot.FMsgBody.Background.Corners := [TCorner.TopLeft, TCorner.TopRight, TCorner.BottomLeft, TCorner.BottomRight]
else
FViewRoot.FMsgBody.Background.Corners := [TCorner.BottomLeft, TCorner.BottomRight]
end else
FViewRoot.FMsgBody.Background.Corners := [TCorner.TopLeft, TCorner.TopRight];
end;
// 设置 Body 最大高度
if Assigned(FViewRoot.FMsgBody) then begin
BodyMH := FViewRoot.FLayBubble.MaxHeight;
if ButtonLayoutHeight > 0 then
BodyMH := BodyMH - ButtonLayoutHeight;
if Assigned(FViewRoot.FTitleView) and (FViewRoot.FTitleView.Visible) then
BodyMH := BodyMH - FViewRoot.FTitleView.Height;
FViewRoot.FMsgBody.MaxHeight := BodyMH;
if Assigned(FViewRoot.FListView) then begin
if Assigned(FViewRoot.FMsgMessage) and (FViewRoot.FMsgMessage.Visible) then
FViewRoot.FListView.MaxHeight := BodyMH - FViewRoot.FMsgMessage.Height
else
FViewRoot.FListView.MaxHeight := BodyMH;
if ButtonLayoutHeight = 0 then
FViewRoot.FListView.Margins.Bottom := StyleMgr.FBackgroundRadius;
end;
end;
if Assigned(FViewRoot.FTitleSpace) then begin
if FViewRoot.FTitleView.Visible = False then
FViewRoot.FTitleSpace.Visible := False
else if (ButtonLayoutHeight = 0) and
(FViewRoot.FMsgBody.Visible = False) and
((not Assigned(FViewRoot.FListView)) or (FViewRoot.FListView.Visible = False)) then
FViewRoot.FTitleSpace.Visible := False;
end;
if (Builder.Title = '') then begin
if FBuilder.Message = '' then begin
if Assigned(FViewRoot.FListView) then
FViewRoot.FListView.Margins.Top := StyleMgr.FBackgroundRadius;
end;
end;
// 初始化遮罩背景
if Builder.FMaskVisible then
FViewRoot.InitMask(StyleMgr);
// 初始化阴影
if Builder.FShadowVisible then
FViewRoot.InitShadow(StyleMgr);
end;
procedure TCustomAlertDialog.InitDownPopupView;
var
StyleMgr: TDialogStyleManager;
ButtonLayoutHeight: Single;
BodyMH: Single;
begin
Inc(DialogRef);
StyleMgr := FBuilder.FStyleManager;
if StyleMgr = nil then
StyleMgr := GetDefaultStyleMgr;
// 初始化基础
FViewRoot := TDialogView.Create(Owner);
FViewRoot.Name := '';
FViewRoot.Dialog := Self;
FViewRoot.BeginUpdate;
FViewRoot.OnClick := DoRootClick;
FViewRoot.Parent := GetFirstParent;
if FViewRoot.Parent = nil then begin
Dismiss;
Exit;
end;
FViewRoot.Clickable := True;
FViewRoot.Align := TAlignLayout.Contents; //TAlignLayout.Client;
FViewRoot.Index := FViewRoot.Parent.ChildrenCount - 1;
FViewRoot.Background.ItemDefault.Kind := TViewBrushKind.Solid;
FViewRoot.InitView(StyleMgr);
// FViewRoot.Background.ItemDefault.Kind := TViewBrushKind.Solid;
// FViewRoot.Background.ItemDefault.Color := $7f33cc33;
// FViewRoot.FLayBubble.Background.ItemDefault.Kind := TViewBrushKind.Solid;
// FViewRoot.FLayBubble.Background.ItemDefault.Color := $7f33ccff;
FViewRoot.FLayBubble.Layout.CenterInParent := False;
if Builder.FWidth > 0 then begin
FViewRoot.FLayBubble.WidthSize := TViewSize.CustomSize;
FViewRoot.FLayBubble.Size.Width := Builder.FWidth;
FViewRoot.FLayBubble.MaxWidth := Builder.FWidth;
FViewRoot.FLayBubble.AdjustViewBounds := True;
end else if Assigned(FBuilder.FTarget) then begin
FViewRoot.FLayBubble.WidthSize := TViewSize.CustomSize;
FViewRoot.FLayBubble.Size.Width := FBuilder.FTarget.Width;
FViewRoot.FLayBubble.MaxWidth := FBuilder.FTarget.Width;
FViewRoot.FLayBubble.AdjustViewBounds := True;
end;
FViewRoot.FLayBubble.Paddings := '1';
with TDrawableBorder(FViewRoot.FLayBubble.Background).Border do begin
Style := TViewBorderStyle.RectBorder;
Color.Default := StyleMgr.ListItemPressedColor;
end;
if FBuilder.FMaxHeight > 0 then
FViewRoot.FLayBubble.MaxHeight := FBuilder.FMaxHeight;
AdjustDownPopupPosition();
// 初始化消息区
if (Builder.FIcon <> nil) or (Builder.FMessage <> '') then begin
FViewRoot.InitMessage(StyleMgr);
if Builder.FMessageIsHtml then
FViewRoot.FMsgMessage.HtmlText := Builder.FMessage
else
FViewRoot.FMsgMessage.Text := Builder.FMessage;
if Assigned(Builder.FIcon) then begin
if Builder.FIcon is TDrawableBase then
FViewRoot.FMsgMessage.Drawable.Assign(TDrawableBase(Builder.FIcon))
else if Builder.FIcon is TBrush then
FViewRoot.FMsgMessage.Drawable.ItemDefault.Assign(TBrush(Builder.FIcon))
else if Builder.FIcon is TBrushBitmap then begin
FViewRoot.FMsgMessage.Drawable.ItemDefault.Bitmap.Assign(TBrushBitmap(Builder.FIcon));
FViewRoot.FMsgMessage.Drawable.ItemDefault.Kind := TBrushKind.Bitmap;
end
else if Builder.FIcon is TBitmap then begin
FViewRoot.FMsgMessage.Drawable.ItemDefault.Bitmap.Bitmap.Assign(TBitmap(Builder.FIcon));
FViewRoot.FMsgMessage.Drawable.ItemDefault.Kind := TBrushKind.Bitmap;
end;
end;
end else
FViewRoot.FMsgBody.Visible := False;
// 初始化列表
if (Length(Builder.FItemArray) > 0) or
((Assigned(Builder.FItems)) and (Builder.FItems.Count > 0)) then begin
FViewRoot.InitList(StyleMgr);
end;
// 初始化按钮
FViewRoot.FLayBubble.Background.Corners := [];
FViewRoot.InitButton(StyleMgr);
if Assigned(FViewRoot.FButtonLayout) then begin
if Assigned(FViewRoot.FButtonPositive) then
FViewRoot.FButtonPositive.OnClick := DoButtonClick;
if Assigned(FViewRoot.FButtonNegative) then
FViewRoot.FButtonNegative.OnClick := DoButtonClick;
if Assigned(FViewRoot.FButtonNeutral) then
FViewRoot.FButtonNeutral.OnClick := DoButtonClick;
ButtonLayoutHeight := FViewRoot.FButtonLayout.Height
end
else
ButtonLayoutHeight := 0;
if Assigned(FViewRoot.FButtonCancel) then
FViewRoot.FButtonCancel.OnClick := DoButtonClick;
// 设置 Body 最大高度
if Assigned(FViewRoot.FMsgBody) then begin
BodyMH := FViewRoot.FLayBubble.MaxHeight;
if ButtonLayoutHeight > 0 then
BodyMH := BodyMH - ButtonLayoutHeight;
if Assigned(FViewRoot.FTitleView) and (FViewRoot.FTitleView.Visible) then
BodyMH := BodyMH - FViewRoot.FTitleView.Height;
FViewRoot.FMsgBody.MaxHeight := BodyMH;
if Assigned(FViewRoot.FListView) then begin
if Assigned(FViewRoot.FMsgMessage) and (FViewRoot.FMsgMessage.Visible) then
FViewRoot.FListView.MaxHeight := BodyMH - FViewRoot.FMsgMessage.Height
else
FViewRoot.FListView.MaxHeight := BodyMH;
end;
end;
if Assigned(FViewRoot.FTitleSpace) then begin
if FViewRoot.FTitleView.Visible = False then
FViewRoot.FTitleSpace.Visible := False
else if (ButtonLayoutHeight = 0) and
(FViewRoot.FMsgBody.Visible = False) and
((not Assigned(FViewRoot.FListView)) or (FViewRoot.FListView.Visible = False)) then
FViewRoot.FTitleSpace.Visible := False;
end;
// 初始化遮罩背景
if Builder.FMaskVisible then
FViewRoot.InitMask(StyleMgr);
// 初始化阴影
if Builder.FShadowVisible then
FViewRoot.InitShadow(StyleMgr);
if FBuilder.View <> nil then
// 附加 View 的对话框
InitExtPopView()
else if FBuilder.FIsSingleChoice then
// 单选对话框
InitSinglePopView()
else if FBuilder.FIsMultiChoice then
// 多选对话框
InitMultiPopView()
else if (Length(FBuilder.FItemArray) > 0) or
(Assigned(FBuilder.Items) and (FBuilder.Items.Count > 0)) then
// 列表框
InitListPopView();
end;
procedure TCustomAlertDialog.InitExtPopView;
begin
if not FIsDowPopup then
InitDefaultPopView;
FViewRoot.FMsgBody.Visible := True;
if Assigned(FViewRoot.FMsgMessage) then
FViewRoot.FMsgMessage.Visible := False;
with Builder.View do begin
Name := '';
Parent := FViewRoot.FMsgBody;
if Assigned(FViewRoot.FButtonLayout) then
Index := FViewRoot.FButtonLayout.Index - 1;
Align := TAlignLayout.Client;
end;
FViewRoot.FMsgBody.Height := Builder.View.Height;
if Builder.View is TFrameView then
TFrameViewTmp(Builder.View).DoShow();
end;
procedure TCustomAlertDialog.InitList(const ListView: TListViewEx; IsMulti: Boolean);
var
Adapter: IListAdapter;
begin
Adapter := nil;
if Assigned(FBuilder.FOnInitListAdapterA) then begin
FBuilder.FOnInitListAdapterA(Self, FBuilder, Adapter);
end;
if not Assigned(Adapter) then begin
if Length(FBuilder.FItemArray) > 0 then begin
if IsMulti then begin
Adapter := TStringsListCheckAdapter.Create(Builder.FItemArray);
TStringsListCheckAdapter(Adapter).Checks := FBuilder.FCheckedItems;
end else if FBuilder.IsSingleChoice then begin
Adapter := TStringsListSingleAdapter.Create(Builder.FItemArray);
if (Builder.FCheckedItem >= 0) and (Builder.FCheckedItem < Adapter.Count) then
TStringsListSingleAdapter(Adapter).ItemIndex := Builder.FCheckedItem;
end else begin
Adapter := TStringsListAdapter.Create(Builder.FItemArray);
end;
end else if Assigned(FBuilder.FItems) and (FBuilder.FItems.Count > 0) then begin
if IsMulti then begin
Adapter := TStringsListCheckAdapter.Create(FBuilder.FItems);
TStringsListCheckAdapter(Adapter).Checks := FBuilder.FCheckedItems;
end else if FBuilder.IsSingleChoice then begin
Adapter := TStringsListSingleAdapter.Create(FBuilder.FItems);
if (Builder.FCheckedItem >= 0) and (Builder.FCheckedItem < Adapter.Count) then
TStringsListSingleAdapter(Adapter).ItemIndex := Builder.FCheckedItem;
end else begin
Adapter := TStringsListAdapter.Create(FBuilder.FItems);
end;
end;
if FBuilder.FListItemDefaultHeight > 0 then
TStringsListAdapter(Adapter).DefaultItemHeight := FBuilder.FListItemDefaultHeight;
TStringsListAdapter(Adapter).WordWrap := FBuilder.FWordWrap;
end;
ListView.Adapter := Adapter;
ListView.Height := ListView.ContentBounds.Height;
end;
procedure TCustomAlertDialog.InitListPopView;
var
ListView: TListViewEx;
begin
if not FIsDowPopup then
InitDefaultPopView;
FViewRoot.FMsgBody.Visible := True;
if Assigned(FViewRoot.FMsgMessage) then begin
if FBuilder.Message = '' then
FViewRoot.FMsgMessage.Visible := False;
end;
// 初始化列表
ListView := FViewRoot.FListView;
InitList(ListView);
ListView.OnItemClick := DoListItemClick;
end;
procedure TCustomAlertDialog.InitMultiPopView;
var
ListView: TListViewEx;
begin
if not FIsDowPopup then
InitDefaultPopView;
FViewRoot.FMsgBody.Visible := True;
if Assigned(FViewRoot.FMsgMessage) then begin
if FBuilder.Message = '' then
FViewRoot.FMsgMessage.Visible := False;
end;
// 初始化列表
ListView := FViewRoot.FListView;
InitList(ListView, True);
if Length(Builder.FCheckedItems) < ListView.Count then
SetLength(Builder.FCheckedItems, ListView.Count);
ListView.EndUpdate;
ListView.OnItemClick := DoListItemClick;
end;
procedure TCustomAlertDialog.InitSinglePopView;
var
ListView: TListViewEx;
begin
if not FIsDowPopup then
InitDefaultPopView;
FViewRoot.FMsgBody.Visible := True;
if Assigned(FViewRoot.FMsgMessage) then begin
if FBuilder.Message = '' then
FViewRoot.FMsgMessage.Visible := False;
end;
// 初始化列表
ListView := FViewRoot.FListView;
InitList(ListView);
ListView.OnItemClick := DoListItemClick;
end;
procedure TCustomAlertDialog.SetMessage(const Value: string);
begin
if Assigned(FBuilder) then
FBuilder.FMessage := Value;
end;
procedure TCustomAlertDialog.SetOnKeyListener(const Value: TOnDialogKeyListener);
begin
FOnKeyListener := Value;
end;
procedure TCustomAlertDialog.SetTitle(const Value: string);
begin
if Assigned(FBuilder) then
FBuilder.FTitle := Value;
if Assigned(FViewRoot) then
FViewRoot.SetTitle(Value);
end;
type
TMyControl = class(TControl);
{ TDialogView }
procedure TDialogView.AfterDialogKey(var Key: Word; Shift: TShiftState);
begin
if not Assigned(FDialog) then
Exit;
// TMyControl(xxx).KeyDown
// 入云龙反馈在一些情况下会有问题,
// 所以判断Key < $80时才传递事件
// KngStr: 更改 KeyDown 为 AfterDialogKey,暂时关闭 Key < $80
// 如果按下了返回键,且允许取消对话框,则关闭对话框
if Key in [vkEscape, vkHardwareBack] then begin
if FDialog.Cancelable then
FDialog.Cancel;
Key := 0;
Exit;
end;
if Assigned(FDialog.Builder) and Assigned(FDialog.Builder.View) {and (Key < $80)} then
TMyControl(FDialog.Builder.View).AfterDialogKey(Key, Shift);
if (Key <> 0) and (ControlsCount = 1) and (not Assigned(FAnilndictor)) {and (Key < $80)} then
TMyControl(Controls[0]).AfterDialogKey(Key, Shift);
if Key <> 0 then
Key := 0;
end;
constructor TDialogView.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
end;
destructor TDialogView.Destroy;
begin
FShadowEffect := nil;
FLayBubble := nil;
FTitleView := nil;
FMsgBody := nil;
FMsgMessage := nil;
FButtonLayout := nil;
FButtonPositive := nil;
FButtonNegative := nil;
FButtonNeutral := nil;
FListView := nil;
FAnilndictor := nil;
FTitleSpace := nil;
inherited Destroy;
end;
procedure TDialogView.DoRealign;
begin
inherited DoRealign;
if (not FDisableAlign) and FIsDownPopup then
TAlertDialog(FDialog).AdjustDownPopupPosition;
end;
function TDialogView.GetTabStopController: ITabStopController;
begin
if Parent <> nil then
Result := Self
else
Result := nil;
end;
procedure TDialogView.Hide;
begin
Visible := False;
end;
procedure TDialogView.InitButton(StyleMgr: TDialogStyleManager);
var
FView1, FView2: TButtonView;
procedure SetButton(var B: TButtonView; FText: string;
FSize: Single; FColor: Int64; FStyle: TFontStyles);
begin
B.Text := FText;
//B.OnClick := DoButtonClick;
if FSize > 0 then
B.TextSettings.Font.Size := FSize;
if FColor > -1 then
B.TextSettings.Color.Default := FColor;
if FStyle <> [] then
B.TextSettings.Font.Style := FStyle;
end;
procedure SetButtonColor(Button: TButtonView; State: TViewState);
var
AColor: TAlphaColor;
ABrush: TBrush;
begin
AColor := StyleMgr.FButtonColor.GetColor(State);
ABrush := Button.Background.GetBrush(State, False);
if (AColor = TAlphaColorRec.Null) and (ABrush = nil) then
Exit;
if ABrush = nil then
ABrush := Button.Background.GetBrush(State, True);
ABrush.Color := AColor;
ABrush.Kind := TBrushKind.Solid;
end;
function CreateButton(Parent: TFmxObject): TButtonView;
begin
Result := TButtonView.Create(Owner);
Result.Parent := Parent;
Result.Weight := 1;
Result.MinHeight := StyleMgr.ButtonHeight;
Result.Gravity := TLayoutGravity.Center;
Result.Paddings := '4';
Result.CanFocus := True;
Result.Clickable := True;
Result.TextSettings.Font.Size := StyleMgr.ButtonTextSize;
Result.TextSettings.Color.Assign(StyleMgr.ButtonTextColor);
Result.Background.Corners := [];
Result.Background.XRadius := StyleMgr.FBackgroundRadius;
Result.Background.YRadius := StyleMgr.FBackgroundRadius;
SetButtonColor(Result, TViewState.None);
SetButtonColor(Result, TViewState.Pressed);
SetButtonColor(Result, TViewState.Focused);
SetButtonColor(Result, TViewState.Hovered);
SetButtonColor(Result, TViewState.Selected);
SetButtonColor(Result, TViewState.Checked);
SetButtonColor(Result, TViewState.Enabled);
TDrawableBorder(Result.Background).Border.Assign(StyleMgr.FButtonBorder);
if not Assigned(FView1) then
FView1 := Result;
FView2 := Result;
end;
begin
if (not Assigned(FDialog)) or (not Assigned(FDialog.Builder)) then
Exit;
if (FDialog.Builder.PositiveButtonText <> '')
or (FDialog.Builder.NegativeButtonText <> '')
or (FDialog.Builder.NeutralButtonText <> '') then begin
// 按钮布局层
FButtonLayout := TLinearLayout.Create(Owner);
{$IFDEF MSWINDOWS}
FButtonLayout.Name := 'ButtonLayout' + IntToStr(DialogRef);
{$ENDIF}
FButtonLayout.Parent := FLayBubble;
FButtonLayout.WidthSize := TViewSize.FillParent;
FButtonLayout.Orientation := TOrientation.Horizontal;
FButtonLayout.HeightSize := TViewSize.WrapContent;
// 按钮
FView1 := nil;
FView2 := nil;
if FDialog.Builder.PositiveButtonText <> '' then begin
FButtonPositive := CreateButton(FButtonLayout);
SetButton(FButtonPositive, FDialog.Builder.PositiveButtonText,
FDialog.Builder.PositiveButtonSize, FDialog.Builder.PositiveButtonColor, FDialog.Builder.PositiveButtonStyle);
end;
if FDialog.Builder.NegativeButtonText <> '' then begin
FButtonNegative := CreateButton(FButtonLayout);
SetButton(FButtonNegative, FDialog.Builder.NegativeButtonText,
FDialog.Builder.NegativeButtonSize, FDialog.Builder.NegativeButtonColor, FDialog.Builder.NegativeButtonStyle);
end;
if FDialog.Builder.NeutralButtonText <> '' then begin
FButtonNeutral := CreateButton(FButtonLayout);
SetButton(FButtonNeutral, FDialog.Builder.NeutralButtonText,
FDialog.Builder.NeutralButtonSize, FDialog.Builder.NeutralButtonColor, FDialog.Builder.NeutralButtonStyle);
end;
// 默认焦点
FView1.Default := True;
FView1.SetFocus;
// 按钮圆角
if FLayBubble.Background.Corners <> [] then begin
if FView1 = FView2 then
FView1.Background.Corners := [TCorner.BottomLeft, TCorner.BottomRight]
else begin
FView1.Background.Corners := [TCorner.BottomLeft];
FView2.Background.Corners := [TCorner.BottomRight];
end;
end;
end;
if Assigned(FLayBubbleBottom) and (FDialog.Builder.CancelButtonText <> '') then begin
// 按钮布局层
FCancelButtonLayout := TLinearLayout.Create(Owner);
{$IFDEF MSWINDOWS}
FCancelButtonLayout.Name := 'CancelButtonLayout' + IntToStr(DialogRef);
{$ENDIF}
FCancelButtonLayout.Parent := FLayBubbleBottom;
FCancelButtonLayout.WidthSize := TViewSize.FillParent;
FCancelButtonLayout.Orientation := TOrientation.Horizontal;
FCancelButtonLayout.HeightSize := TViewSize.WrapContent;
// 按钮
FButtonCancel := CreateButton(FCancelButtonLayout);
FButtonCancel.Background.Corners := [TCorner.TopLeft, TCorner.TopRight, TCorner.BottomLeft, TCorner.BottomRight];
SetButton(FButtonCancel, FDialog.Builder.CancelButtonText,
FDialog.Builder.CancelButtonSize, FDialog.Builder.CancelButtonColor, FDialog.Builder.CancelButtonStyle);
FLayBubble.Margins.Bottom := FButtonCancel.MinHeight + 30;
end;
end;
procedure TDialogView.InitList(StyleMgr: TDialogStyleManager);
begin
// 列表
FListView := TListViewEx.Create(Owner);
{$IFDEF MSWINDOWS}
FListView.Name := 'FListView' + IntToStr(DialogRef);
{$ENDIF}
FListView.Parent := FMsgBody;
FListView.HitTest := True;
FListView.CanFocus := True;
//FListView.ControlType := TControlType.Platform;
FListView.WidthSize := TViewSize.FillParent;
FListView.HeightSize := TViewSize.WrapContent;
FListView.Background.ItemPressed.Color := StyleMgr.ListItemPressedColor;
FListView.Divider := StyleMgr.ListItemDividerColor;
FListView.DragScroll := True;
end;
procedure TDialogView.InitMask(StyleMgr: TDialogStyleManager);
begin
if Background.ItemDefault.Color <> StyleMgr.FDialogMaskColor then
Background.ItemDefault.Color := StyleMgr.FDialogMaskColor;
if not Margins.Equals(StyleMgr.FDialogMaskMargins) then
Margins.Assign(StyleMgr.FDialogMaskMargins);
end;
procedure TDialogView.InitMessage(StyleMgr: TDialogStyleManager);
begin
if FMsgMessage <> nil then Exit;
// 内容区
FMsgMessage := TTextView.Create(Owner);
{$IFDEF MSWINDOWS}
FMsgMessage.Name := 'FMsgMessage' + IntToStr(DialogRef);
{$ENDIF}
FMsgMessage.Parent := FMsgBody;
FMsgMessage.Clickable := False;
FMsgMessage.WidthSize := TViewSize.FillParent;
FMsgMessage.HeightSize := TViewSize.WrapContent;
FMsgMessage.Padding.Rect := RectF(8, 8, 8, 12);
FMsgMessage.Gravity := StyleMgr.MessageTextGravity;
FMsgMessage.TextSettings.WordWrap := True;
FMsgMessage.TextSettings.Color.Default := StyleMgr.MessageTextColor;
FMsgMessage.TextSettings.Font.Size := StyleMgr.MessageTextSize;
FMsgMessage.AutoSize := True;
FMsgMessage.ScrollBars := TViewScroll.Vertical;
FMsgMessage.Drawable.SizeWidth := StyleMgr.IconSize;
FMsgMessage.Drawable.SizeHeight := StyleMgr.IconSize;
FMsgMessage.Drawable.Padding := 8;
FMsgMessage.Background.ItemDefault.Color := StyleMgr.MessageTextBackground;
FMsgMessage.Background.ItemDefault.Kind := TViewBrushKind.Solid;
FMsgMessage.Margins.Assign(StyleMgr.MessageTextMargins);
end;
procedure TDialogView.InitOK;
var
AniView: TControl;
begin
EndUpdate;
if Assigned(FAnilndictor) then
FAnilndictor.Enabled := True;
if Assigned(FLayBubble) then
FLayBubble.RecalcSize;
HandleSizeChanged;
if Assigned(FShadowEffect) then begin
AniView := TDialog(Dialog).GetAniView;
if Assigned(AniView) then
TFrameAnimator.DelayExecute(AniView,
procedure (Sender: TObject)
begin
if (not Assigned(Self)) or (Dialog = nil) or TDialog(Dialog).FIsDismiss then
Exit;
if Assigned(FShadowEffect) then
FShadowEffect.Enabled := True;
end,
0.05);
end;
end;
procedure TDialogView.InitProcessView(StyleMgr: TDialogStyleManager);
begin
// 如果对话框不获取焦点,那么焦点会在之前点击的控件上,所以这里要重置下焦点
CanFocus := False;
if Root <> nil then
Root.SetFocused(nil);
FLayBubble := TLinearLayout.Create(Owner);
{$IFDEF MSWINDOWS}
FLayBubble.Name := 'LayBubble' + IntToStr(DialogRef);
{$ENDIF}
// 消息框主体
FLayBubble.Parent := Self;
FLayBubble.Margin := '16';
FLayBubble.Paddings := '16';
{$IFDEF ANDROID}
FLayBubble.Margins.Top := FLayBubble.Margins.Top + TView.GetStatusHeight;
{$ENDIF}
FLayBubble.ClipChildren := True;
FLayBubble.Background.ItemDefault.Color := StyleMgr.ProcessBackgroundColor;
FLayBubble.Background.ItemDefault.Kind := TViewBrushKind.Solid;
FLayBubble.Background.XRadius := StyleMgr.FBackgroundRadius;
FLayBubble.Background.YRadius := StyleMgr.FBackgroundRadius;
FLayBubble.Gravity := TLayoutGravity.Center;
FLayBubble.Layout.CenterInParent := True;
FLayBubble.Clickable := True;
FLayBubble.WidthSize := TViewSize.WrapContent;
FLayBubble.HeightSize := TViewSize.WrapContent;
FLayBubble.Orientation := TOrientation.Vertical;
FLayBubble.CanFocus := False;
FLayBubble.AdjustViewBounds := True;
FLayBubble.MaxWidth := Width - FLayBubble.Margins.Left - FLayBubble.Margins.Right;
FLayBubble.MaxHeight := Height - FLayBubble.Margins.Top - FLayBubble.Margins.Bottom;
// 等待动画
FAnilndictor := TAniIndicator.Create(Owner);
{$IFDEF MSWINDOWS}
FAnilndictor.Name := 'Anilndictor' + IntToStr(DialogRef);
{$ENDIF}
FAnilndictor.Parent := FLayBubble;
FAnilndictor.Align := TAlignLayout.Center;
// 消息内容
FMsgMessage := TTextView.Create(Owner);
{$IFDEF MSWINDOWS}
FMsgMessage.Name := 'FMsgMessage' + IntToStr(DialogRef);
{$ENDIF}
FMsgMessage.Parent := FLayBubble;
FMsgMessage.Clickable := False;
FMsgMessage.Margins.Top := 24;
FMsgMessage.Padding.Left := 16;
FMsgMessage.Padding.Right := 16;
FMsgMessage.WidthSize := TViewSize.WrapContent;
FMsgMessage.HeightSize := TViewSize.WrapContent;
FMsgMessage.Gravity := TLayoutGravity.Center;
FMsgMessage.TextSettings.WordWrap := True;
FMsgMessage.TextSettings.Color.Default := StyleMgr.ProcessTextColor;
FMsgMessage.TextSettings.Font.Size := StyleMgr.MessageTextSize;
FMsgMessage.AutoSize := True;
end;
procedure TDialogView.InitShadow(StyleMgr: TDialogStyleManager);
begin
FShadowEffect := TShadowEffect.Create(Self);
FShadowEffect.Parent := Self;
FShadowEffect.Enabled := False;
FShadowEffect.Direction := 90;
FShadowEffect.Opacity := 1;
FShadowEffect.Softness := 0.75;
FShadowEffect.Distance := 0;
FShadowEffect.ShadowColor := StyleMgr.DialogMaskShadowColor;
end;
procedure TDialogView.InitView(StyleMgr: TDialogStyleManager);
function InitLayBubble(FName: string; FPosition: TDialogViewPosition): TLinearLayout;
begin
Result := TLinearLayout.Create(Owner);
{$IFDEF MSWINDOWS}
Result.Name := FName + IntToStr(DialogRef);
{$ENDIF}
// 消息框主体
Result.Parent := Self;
Result.Margin := '16';
Result.ClipChildren := True;
if FDialog.Builder.FUseRootBackColor then
Result.Background.ItemDefault.Color := FDialog.Builder.FRootBackColor
else begin
Result.Background.ItemDefault.Color := StyleMgr.BackgroundColor;
Result.Background.XRadius := StyleMgr.FBackgroundRadius;
Result.Background.YRadius := StyleMgr.FBackgroundRadius;
end;
Result.Background.ItemDefault.Kind := TViewBrushKind.Solid;
Result.Clickable := True;
Result.WidthSize := TViewSize.FillParent;
case FPosition of
TDialogViewPosition.Top: begin
Result.Layout.CenterHorizontal := True;
Result.Layout.AlignParentTop := True;
end;
TDialogViewPosition.Bottom: begin
Result.Layout.CenterHorizontal := True;
Result.Layout.AlignParentBottom := True;
end;
TDialogViewPosition.LeftBottom: begin
Result.Layout.AlignParentLeft := True;
Result.Layout.AlignParentBottom := True;
end;
TDialogViewPosition.RightBottom: begin
Result.Layout.AlignParentRight := True;
Result.Layout.AlignParentBottom := True;
end;
TDialogViewPosition.Left: begin
Result.Layout.CenterVertical := True;
Result.Layout.AlignParentLeft := True;
end;
TDialogViewPosition.Right: begin
Result.Layout.CenterVertical := True;
Result.Layout.AlignParentRight := True;
end;
TDialogViewPosition.Center: begin
Result.Layout.CenterInParent := True;
end;
TDialogViewPosition.LeftFill: ;
TDialogViewPosition.RightFill: ;
end;
Result.HeightSize := TViewSize.WrapContent;
Result.Orientation := TOrientation.Vertical;
Result.CanFocus := False;
Result.AdjustViewBounds := True;
if StyleMgr.MaxWidth > 0 then begin
Result.WidthSize := TViewSize.CustomSize;
Result.Size.Width := StyleMgr.MaxWidth;
Result.MaxWidth := StyleMgr.MaxWidth;
end;
Result.MaxHeight := Height - Result.Margins.Top - Result.Margins.Bottom;
end;
begin
// 如果对话框不获取焦点,那么焦点会在之前点击的控件上,所以这里要重置下焦点
CanFocus := False;
if Root <> nil then
Root.SetFocused(nil);
FLayBubble := InitLayBubble('LayBubble', FDialog.Builder.FPosition);
FLayBubble.Padding.Assign(StyleMgr.FBackgroundPadding);
{$IFDEF ANDROID}
FLayBubble.Margins.Top := FLayBubble.Margins.Top + TView.GetStatusHeight;
FLayBubble.Margins.Bottom := FLayBubble.Margins.Bottom + TView.GetNavigationBarHeight;
{$ENDIF}
if (FDialog.Builder.FPosition = TDialogViewPosition.Bottom) and (FDialog.Builder.CancelButtonText <> '') then
FLayBubbleBottom := InitLayBubble('LayBubbleBottom', TDialogViewPosition.Bottom);
// 标题栏
FTitleView := TTextView.Create(Owner);
{$IFDEF MSWINDOWS}
FTitleView.Name := 'TitleView' + IntToStr(DialogRef);
{$ENDIF}
FTitleView.Parent := FLayBubble;
FTitleView.ClipChildren := True;
FTitleView.TextSettings.Font.Size := StyleMgr.TitleTextSize;
if StyleMgr.TitleTextBold then
FTitleView.TextSettings.Font.Style := [TFontStyle.fsBold];
FTitleView.TextSettings.Color.Default := StyleMgr.TitleTextColor;
FTitleView.Gravity := StyleMgr.TitleGravity;
FTitleView.Padding.Rect := RectF(8, 4, 8, 4);
FTitleView.MinHeight := StyleMgr.TitleHeight;
FTitleView.WidthSize := TViewSize.FillParent;
FTitleView.Background.ItemDefault.Color := StyleMgr.TitleBackGroundColor;
FTitleView.Background.ItemDefault.Kind := TViewBrushKind.Solid;
FTitleView.Background.XRadius := StyleMgr.FBackgroundRadius;
FTitleView.Background.YRadius := StyleMgr.FBackgroundRadius;
FTitleView.Background.Corners := [TCorner.TopLeft, TCorner.TopRight];
FTitleView.Background.Padding.Rect := RectF(1, 1, 1, 0);
FTitleView.HeightSize := TViewSize.WrapContent;
// 标题与内容区的分隔线
if StyleMgr.FTitleSpaceHeight > 0 then begin
FTitleSpace := TView.Create(Owner);
{$IFDEF MSWINDOWS}
FTitleSpace.Name := 'TitleSpace' + IntToStr(DialogRef);
{$ENDIF}
FTitleSpace.Parent := FLayBubble;
FTitleSpace.ClipChildren := True;
FTitleSpace.Height := StyleMgr.FTitleSpaceHeight;
FTitleSpace.Background.ItemDefault.Color := StyleMgr.FTitleSpaceColor;
FTitleSpace.Background.ItemDefault.Kind := TViewBrushKind.Solid;
FTitleSpace.WidthSize := TViewSize.FillParent;
end;
// 内容区
FMsgBody := TLinearLayout.Create(Owner);
{$IFDEF MSWINDOWS}
FMsgBody.Name := 'MsgBody' + IntToStr(DialogRef);
{$ENDIF}
FMsgBody.Parent := FLayBubble;
FMsgBody.ClipChildren := True;
FMsgBody.Weight := 1;
FMsgBody.MinHeight := 24;
FMsgBody.WidthSize := TViewSize.FillParent;
FMsgBody.HeightSize := TViewSize.WrapContent;
FMsgBody.Orientation := TOrientation.Vertical;
if FDialog.Builder.FUseRootBackColor then
FMsgBody.Background.ItemDefault.Color := FDialog.Builder.FRootBackColor
else
FMsgBody.Background.ItemDefault.Color := StyleMgr.BodyBackGroundColor;
FMsgBody.Background.ItemDefault.Kind := TViewBrushKind.Solid;
end;
procedure TDialogView.Resize;
begin
inherited Resize;
if Assigned(Dialog) and (ControlsCount = 1) then begin
// 左右边栏菜单调整大小
if (TDialog(Dialog).FAnimate in [TFrameAniType.LeftSlideMenu, TFrameAniType.RightSlideMenu]) and
(TDialog(Dialog).Owner is TFrame) then
Controls[0].Width := Width * SIZE_MENU_WIDTH;
end;
end;
procedure TDialogView.SetTitle(const AText: string);
begin
if FTitleView <> nil then begin
FTitleView.Text := AText;
if AText = '' then begin
FTitleView.Visible := False;
if Assigned(FTitleSpace) then
FTitleSpace.Visible := False;
end;
end;
end;
procedure TDialogView.Show;
begin
Visible := True;
BringToFront;
Resize;
if Assigned(FListView) then
Width := Width + 0.01;
end;
{ TDialogStyleManager }
procedure TDialogStyleManager.Assign(Dest: TPersistent);
var
LStyleMgr: TDialogStyleManager;
begin
if not Assigned(Dest) then begin
LStyleMgr := TDialogStyleManager.Create(nil);
try
Assign(LStyleMgr);
finally
FreeAndNil(LStyleMgr);
end;
end
else
inherited;
end;
procedure TDialogStyleManager.AssignTo(Dest: TPersistent);
var
LStyleMgr: TDialogStyleManager;
begin
if not Assigned(Dest) or not (Dest is TDialogStyleManager) then begin
inherited;
Exit;
end;
LStyleMgr := TDialogStyleManager(Dest);
LStyleMgr.FDialogMaskColor := FDialogMaskColor;
LStyleMgr.FDialogMaskMargins.Assign(FDialogMaskMargins);
LStyleMgr.FDialogMaskShadowColor := FDialogMaskShadowColor;
LStyleMgr.FBackgroundColor := FBackgroundColor;
LStyleMgr.FBackgroundPadding.Assign(FBackgroundPadding);
LStyleMgr.FTitleBackGroundColor := FTitleBackGroundColor;
LStyleMgr.FTitleTextColor := FTitleTextColor;
LStyleMgr.FBodyBackgroundColor := FBodyBackgroundColor;
LStyleMgr.FProcessBackgroundColor := FProcessBackgroundColor;
LStyleMgr.FProcessTextColor := FProcessTextColor;
LStyleMgr.FMessageTextColor := FMessageTextColor;
LStyleMgr.FMessageTextBackground := FMessageTextBackground;
LStyleMgr.FButtonColor.Assign(FButtonColor);
LStyleMgr.FButtonTextColor.Assign(FButtonTextColor);
LStyleMgr.FButtonBorder.Assign(FButtonBorder);
LStyleMgr.FMessageTextSize := FMessageTextSize;
LStyleMgr.FTitleHeight := FTitleHeight;
LStyleMgr.FTitleTextSize := FTitleTextSize;
LStyleMgr.FButtonTextSize := FButtonTextSize;
LStyleMgr.FIconSize := FIconSize;
LStyleMgr.FBackgroundRadius := FBackgroundRadius;
LStyleMgr.FTitleGravity := FTitleGravity;
LStyleMgr.FTitleSpaceHeight := FTitleSpaceHeight;
LStyleMgr.FTitleSpaceColor := FTitleSpaceColor;
LStyleMgr.FMaxWidth := FMaxWidth;
LStyleMgr.FMessageTextMargins.Assign(FMessageTextMargins);
LStyleMgr.FMessageTextGravity := FMessageTextGravity;
LStyleMgr.FTitleTextBold := FTitleTextBold;
LStyleMgr.FListItemPressedColor := FListItemPressedColor;
LStyleMgr.FListItemDividerColor := FListItemDividerColor;
LStyleMgr.FButtonHeight := FButtonHeight;
end;
constructor TDialogStyleManager.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FDialogMaskColor := COLOR_DialogMaskColor;
FDialogMaskMargins := TBounds.Create(TRectF.Empty);
FDialogMaskShadowColor := COLOR_DialogMaskShadowColor;
FBackgroundPadding := TBounds.Create(TRectF.Empty);
FTitleBackGroundColor := COLOR_TitleBackGroundColor;
FTitleTextColor := COLOR_TitleTextColor;
FProcessBackgroundColor := COLOR_ProcessBackgroundColor;
FProcessTextColor := COLOR_ProcessTextColor;
FBackgroundColor := COLOR_BackgroundColor;
FBodyBackgroundColor := COLOR_BodyBackgroundColor;
FMessageTextBackground := COLOR_MessageTextBackground;
FMessageTextColor := COLOR_MessageTextColor;
FMessageTextSize := FONT_MessageTextSize;
FMessageTextMargins := TBounds.Create(TRectF.Empty);
FMessageTextGravity := TLayoutGravity.CenterVertical;
FTitleTextSize := FONT_TitleTextSize;
FButtonTextSize := FONT_ButtonTextSize;
FButtonHeight := SIZE_ButtonHeight;
FIconSize := SIZE_ICON;
FTitleHeight := SIZE_TitleHeight;
FTitleGravity := Title_Gravity;
FBackgroundRadius := SIZE_BackgroundRadius;
FTitleTextBold := False;
FButtonColor := TButtonViewColor.Create();
FButtonColor.Default := COLOR_ButtonColor;
FButtonColor.Pressed := COLOR_ButtonPressColor;
FButtonBorder := TViewBorder.Create;
FButtonBorder.Width := SIZE_ButtonBorder;
FButtonBorder.Style := TViewBorderStyle.RectBorder;
FButtonBorder.Color.Default := COLOR_ButtonBorderColor;
FButtonBorder.Color.DefaultChange := False;
FButtonTextColor := TTextColor.Create(COLOR_ButtonTextColor);
FButtonTextColor.Pressed := COLOR_ButtonTextPressColor;
FTitleSpaceHeight := SIZE_TitleSpaceHeight;
FTitleSpaceColor := COLOR_TitleSpaceColor;
FListItemPressedColor := COLOR_ListItemPressedColor;
FListItemDividerColor := COLOR_LIstItemDividerColor;
if Assigned(Owner) and (not (csDesigning in ComponentState)) then begin
if DefaultStyleManager <> nil then begin
DefaultStyleManager.DisposeOf;
DefaultStyleManager := nil;
end;
DefaultStyleManager := Self;
end;
end;
destructor TDialogStyleManager.Destroy;
begin
if (DefaultStyleManager = Self) and (not (csDesigning in ComponentState)) then
DefaultStyleManager := nil;
FreeAndNil(FMessageTextMargins);
FreeAndNil(FButtonColor);
FreeAndNil(FButtonBorder);
FreeAndNil(FButtonTextColor);
FreeAndNil(FBackgroundPadding);
FreeAndNil(FDialogMaskMargins);
inherited;
end;
function TDialogStyleManager.GetMessageTextMargins: TBounds;
begin
Result := FMessageTextMargins;
end;
function TDialogStyleManager.IsStoredBackgroundRadius: Boolean;
begin
Result := FBackgroundRadius <> SIZE_BackgroundRadius;
end;
function TDialogStyleManager.IsStoredTitleSpaceHeight: Boolean;
begin
Result := FTitleSpaceHeight <> SIZE_TitleSpaceHeight;
end;
procedure TDialogStyleManager.SetButtonBorder(const Value: TViewBorder);
begin
FButtonBorder.Assign(Value);
end;
procedure TDialogStyleManager.SetButtonColor(const Value: TButtonViewColor);
begin
FButtonColor.Assign(Value);
end;
procedure TDialogStyleManager.SetButtonTextColor(const Value: TTextColor);
begin
FButtonTextColor.Assign(Value);
end;
procedure TDialogStyleManager.SetMessageTextMargins(const Value: TBounds);
begin
FMessageTextMargins.Assign(Value);
end;
{ TProgressDialog }
constructor TProgressDialog.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
end;
destructor TProgressDialog.Destroy;
begin
inherited Destroy;
end;
procedure TProgressDialog.DoRootClick(Sender: TObject);
begin
end;
function TProgressDialog.GetMessage: string;
begin
if Assigned(FViewRoot) and (Assigned(FViewRoot.FMsgMessage)) then
Result := FViewRoot.FMsgMessage.Text
else
Result := '';
end;
procedure TProgressDialog.InitView(const AMsg: string; IsHtmlText: Boolean);
var
StyleMgr: TDialogStyleManager;
begin
Inc(DialogRef);
StyleMgr := FStyleManager;
if StyleMgr = nil then
StyleMgr := GetDefaultStyleMgr;
// 初始化基础
FViewRoot := TDialogView.Create(Owner);
FViewRoot.Dialog := Self;
FViewRoot.BeginUpdate;
FViewRoot.OnClick := DoRootClick;
FViewRoot.Parent := GetFirstParent;
if FViewRoot.Parent = nil then begin
Dismiss;
Exit;
end;
FViewRoot.Clickable := True;
FViewRoot.Align := TAlignLayout.Contents; //TAlignLayout.Client;
FViewRoot.Background.ItemDefault.Kind := TViewBrushKind.Solid;
FViewRoot.InitProcessView(StyleMgr);
if AMsg = '' then
FViewRoot.FMsgMessage.Visible := False
else begin
if IsHtmlText then
FViewRoot.FMsgMessage.HtmlText := AMsg
else
FViewRoot.FMsgMessage.Text := AMsg;
FViewRoot.FMsgMessage.Visible := True;
FViewRoot.FLayBubble.WidthSize := TViewSize.CustomSize;
FViewRoot.FLayBubble.Width := FViewRoot.FMsgMessage.Width + 32;
FViewRoot.FMsgMessage.WidthSize := TViewSize.FillParent;
end;
// 初始化遮罩背景
FViewRoot.InitMask(StyleMgr);
InitOK();
end;
procedure TProgressDialog.SetMessage(const Value: string);
begin
if Assigned(FViewRoot) and (Assigned(FViewRoot.FMsgMessage)) then begin
FViewRoot.FMsgMessage.Text := Value;
FViewRoot.FMsgMessage.Visible := Value <> '';
FViewRoot.Realign;
end;
end;
class function TProgressDialog.Show(AOwner: TComponent; const AMsg: string;
ACancelable: Boolean): TProgressDialog;
begin
Result := TProgressDialog.Create(AOwner);
Result.Cancelable := ACancelable;
Result.InitView(AMsg);
TDialog(Result).Show();
end;
{ TButtonViewColor }
constructor TButtonViewColor.Create(const ADefaultColor: TAlphaColor);
begin
inherited Create(ADefaultColor);
end;
initialization
finalization
FreeAndNil(DefaultStyleManager);
end.
|
UNIT bigint;
INTERFACE
USES sysutils,
math,
myGenerics,
serializationUtil;
TYPE
DigitType=dword;
CarryType=qword;
DigitTypeArray=array of DigitType;
CONST
BITS_PER_DIGIT=32;
DIGIT_MAX_VALUE:int64=(1 shl BITS_PER_DIGIT)-1;
UPPER_DIGIT_BIT=1 shl (BITS_PER_DIGIT-1);
WORD_BIT:array[0..BITS_PER_DIGIT-1] of DigitType=
( 1, 2, 4, 8, 16, 32, 64, 128,
256, 512, 1024, 2048, 4096, 8192, 16384, 32768,
65536, 131072, 262144, 524288, 1048576, 2097152, 4194304, 8388608,
16777216,33554432,67108864,134217728,268435456,536870912,1073741824,2147483648);
TYPE
T_comparisonResult=(CR_EQUAL,
CR_LESSER,
CR_GREATER,
CR_INVALID_COMPARAND);
T_roundingMode=(RM_DEFAULT,RM_UP,RM_DOWN);
CONST
C_FLIPPED:array[T_comparisonResult] of T_comparisonResult=(CR_EQUAL,CR_GREATER,CR_LESSER,CR_INVALID_COMPARAND);
TYPE
F_rand32Source =FUNCTION:dword;
F_rand32SourceOfObject=FUNCTION:dword of object;
T_arrayOfByte=array of byte;
T_bigInt=object
private
negative:boolean;
digits:DigitTypeArray;
PROCEDURE createFromRawData(CONST negative_:boolean; CONST digits_:DigitTypeArray);
PROCEDURE nullBits(CONST numberOfBitsToKeep:longint);
PROCEDURE shlInc(CONST incFirstBit:boolean);
PROCEDURE setBit(CONST index:longint; CONST value:boolean);
FUNCTION compareAbsValue(CONST big:T_bigInt):T_comparisonResult; inline;
FUNCTION compareAbsValue(CONST int:int64):T_comparisonResult; inline;
PROCEDURE multWith(CONST l:longint);
PROCEDURE multWith(CONST b:T_bigInt);
PROCEDURE divBy(CONST divisor:DigitType; OUT rest:DigitType);
PROCEDURE incAbsValue(CONST positiveIncrement:DigitType);
PROCEDURE shiftRightOneBit;
public
FUNCTION relevantBits:longint;
PROCEDURE shiftRight(CONST rightShift:longint);
PROPERTY isNegative:boolean read negative;
PROCEDURE createZero;
PROCEDURE create(CONST negativeNumber:boolean; CONST digitCount_:longint);
PROCEDURE fromInt(CONST i:int64);
PROCEDURE fromString(CONST s:string);
PROCEDURE fromFloat(CONST f:extended; CONST rounding:T_roundingMode);
PROCEDURE create(CONST toClone:T_bigInt);
PROCEDURE createFromDigits(CONST base:longint; CONST digits_:T_arrayOfLongint);
PROCEDURE clear;
FUNCTION toInt:int64;
FUNCTION toFloat:extended;
{if examineNicheCase is true, the case of -2^63 is considered; otherwise the function is symmetrical}
FUNCTION canBeRepresentedAsInt64(CONST examineNicheCase: boolean=true): boolean;
FUNCTION canBeRepresentedAsInt62:boolean;
FUNCTION canBeRepresentedAsInt32(CONST examineNicheCase: boolean=true): boolean;
FUNCTION getBit(CONST index:longint):boolean;
FUNCTION getDigits(CONST base:longint):T_arrayOfLongint;
PROCEDURE flipSign;
FUNCTION negated:T_bigInt;
FUNCTION compare(CONST big:T_bigInt):T_comparisonResult; inline;
FUNCTION compare(CONST int:int64 ):T_comparisonResult; inline;
FUNCTION compare(CONST f:extended ):T_comparisonResult; inline;
FUNCTION minus(CONST small:DigitType):T_bigInt;
FUNCTION pow (power:dword ):T_bigInt;
FUNCTION powMod(CONST power,modul:T_bigInt):T_bigInt;
FUNCTION isOdd:boolean;
FUNCTION bitAnd(CONST big:T_bigInt):T_bigInt;
FUNCTION bitAnd(CONST small:int64 ):T_bigInt;
FUNCTION bitOr (CONST big:T_bigInt):T_bigInt;
FUNCTION bitOr (CONST small:int64 ):T_bigInt;
FUNCTION bitXor(CONST big:T_bigInt):T_bigInt;
FUNCTION bitXor(CONST small:int64 ):T_bigInt;
FUNCTION bitNegate(CONST consideredBits:longint):T_bigInt;
{returns true on success, false on division by zero}
FUNCTION divMod(CONST divisor:T_bigInt; OUT quotient,rest:T_bigInt):boolean;
FUNCTION divide(CONST divisor:T_bigInt):T_bigInt;
FUNCTION modulus(CONST divisor:T_bigInt):T_bigInt;
FUNCTION toString:string;
FUNCTION toHexString:string;
FUNCTION equals(CONST b:T_bigInt):boolean;
FUNCTION isZero:boolean;
FUNCTION isOne:boolean;
FUNCTION isBetween(CONST lowerBoundInclusive,upperBoundInclusive:longint):boolean;
PROCEDURE writeToStream(CONST stream:P_outputStreamWrapper);
PROCEDURE readFromStream(CONST stream:P_inputStreamWrapper);
PROCEDURE readFromStream(CONST markerByte:byte; CONST stream:P_inputStreamWrapper);
FUNCTION lowDigit:DigitType;
FUNCTION sign:shortint;
FUNCTION greatestCommonDivider(CONST other:T_bigInt):T_bigInt;
FUNCTION greatestCommonDivider(CONST other:int64):int64;
FUNCTION modularInverse(CONST modul:T_bigInt; OUT thereIsAModularInverse:boolean):T_bigInt;
FUNCTION iSqrt(CONST computeEvenIfNotSquare:boolean; CONST roundingMode:T_roundingMode; OUT isSquare:boolean):T_bigInt;
FUNCTION iLog2(OUT isPowerOfTwo:boolean):longint;
FUNCTION hammingWeight:longint;
FUNCTION getRawBytes:T_arrayOfByte;
FUNCTION hash:dword;
end;
T_arrayOfBigint=array of T_bigInt;
T_factorizationResult=record
smallFactors:T_arrayOfLongint;
bigFactors:T_arrayOfBigint;
end;
T_dynamicContinueFlag=FUNCTION:boolean of object;
FUNCTION randomInt(CONST randomSource:F_rand32Source ; CONST maxValExclusive:T_bigInt):T_bigInt;
FUNCTION randomInt(CONST randomSource:F_rand32SourceOfObject; CONST maxValExclusive:T_bigInt):T_bigInt;
{This function works safely for n<=2^45; for larger numbers arithmetic overflows may occur}
FUNCTION factorizeSmall(n:int64):T_factorizationResult;
FUNCTION factorize(CONST B:T_bigInt; CONST continue:T_dynamicContinueFlag):T_factorizationResult;
FUNCTION isPrime(CONST n:int64 ):boolean;
FUNCTION isPrime(CONST B:T_bigInt):boolean;
FUNCTION bigDigits(CONST value,base:T_bigInt):T_arrayOfBigint;
FUNCTION newFromBigDigits(CONST digits:T_arrayOfBigint; CONST base:T_bigInt):T_bigInt;
{For compatibility with constructor T_bigInt.readFromStream}
FUNCTION readLongintFromStream(CONST markerByte:byte; CONST stream:P_inputStreamWrapper):longint;
PROCEDURE writeLongintToStream(CONST value:longint; CONST stream:P_outputStreamWrapper);
OPERATOR +(CONST x:T_bigInt; CONST y:int64):T_bigInt;
OPERATOR +(CONST x,y:T_bigInt):T_bigInt;
OPERATOR -(CONST x:T_bigInt; CONST y:int64):T_bigInt;
OPERATOR -(CONST x:int64; CONST y:T_bigInt):T_bigInt;
OPERATOR -(CONST x,y:T_bigInt):T_bigInt;
OPERATOR *(CONST x:T_bigInt; CONST y:int64):T_bigInt;
OPERATOR *(CONST x,y:T_bigInt):T_bigInt;
FUNCTION divide (CONST x:T_bigInt; CONST y:int64):T_bigInt;
FUNCTION divide (CONST x:int64; CONST y:T_bigInt):T_bigInt;
OPERATOR mod(CONST x:T_bigInt; CONST y:int64):int64;
FUNCTION modulus(CONST x:int64; CONST y:T_bigInt):T_bigInt;
IMPLEMENTATION
FUNCTION randomInt(CONST randomSource:F_rand32Source; CONST maxValExclusive:T_bigInt):T_bigInt;
VAR k:longint;
temp:T_bigInt;
begin
if maxValExclusive.isZero then begin
result.createZero;
exit;
end;
temp.create(false,length(maxValExclusive.digits));
for k:=0 to length(temp.digits)-1 do temp.digits[k]:=randomSource();
result:=temp.modulus(maxValExclusive);
end;
FUNCTION randomInt(CONST randomSource:F_rand32SourceOfObject; CONST maxValExclusive:T_bigInt):T_bigInt;
VAR k:longint;
temp:T_bigInt;
begin
if maxValExclusive.isZero then begin
result.createZero;
exit;
end;
temp.create(false,length(maxValExclusive.digits));
for k:=0 to length(temp.digits)-1 do temp.digits[k]:=randomSource();
result:=temp.modulus(maxValExclusive);
end;
OPERATOR +(CONST x:T_bigInt; CONST y:int64):T_bigInt;
VAR bigY:T_bigInt;
begin
bigY.fromInt(y);
result:=x+bigY;
end;
FUNCTION rawDataPlus(CONST xDigits,yDigits:DigitTypeArray):DigitTypeArray;
VAR carry:CarryType=0;
i :longint;
begin
i:=length(xDigits);
if i< length(yDigits) then
i:=length(yDigits);
initialize(result);
setLength(result,i);
for i:=0 to length(result)-1 do begin
if i<length(xDigits) then carry+=xDigits[i];
if i<length(yDigits) then carry+=yDigits[i];
result[i]:=carry and DIGIT_MAX_VALUE;
carry:=carry shr BITS_PER_DIGIT;
end;
if carry>0 then begin
setLength(result,length(result)+1);
result[length(result)-1]:=carry;
end;
end;
PROCEDURE trimLeadingZeros(VAR digits:DigitTypeArray); inline;
VAR i:longint;
begin
i:=length(digits);
while (i>0) and (digits[i-1]=0) do dec(i);
if i<>length(digits) then setLength(digits,i);
end;
{Precondition: x>y}
FUNCTION rawDataMinus(CONST xDigits,yDigits:DigitTypeArray):DigitTypeArray; inline;
VAR carry:CarryType=0;
i :longint;
begin
initialize(result);
setLength(result,length(xDigits));
for i:=0 to length(yDigits)-1 do begin
carry+=yDigits[i];
if carry>xDigits[i] then begin
result[i]:=((DIGIT_MAX_VALUE+1)-carry+xDigits[i]) and DIGIT_MAX_VALUE;
carry:=1;
end else begin
result[i]:=xDigits[i]-carry;
carry:=0;
end;
end;
for i:=length(yDigits) to length(xDigits)-1 do begin
if carry>xDigits[i] then begin
result[i]:=((DIGIT_MAX_VALUE+1)-carry+xDigits[i]) and DIGIT_MAX_VALUE;
carry:=1;
end else begin
result[i]:=xDigits[i]-carry;
carry:=0;
end;
end;
trimLeadingZeros(result);
end;
OPERATOR +(CONST x,y:T_bigInt):T_bigInt;
begin
if x.negative=y.negative
then result.createFromRawData(x.negative,rawDataPlus(x.digits,y.digits))
else case x.compareAbsValue(y) of
CR_EQUAL : result.createZero;
CR_LESSER : result.createFromRawData(y.negative,rawDataMinus(y.digits,x.digits));
CR_GREATER: result.createFromRawData(x.negative,rawDataMinus(x.digits,y.digits));
end;
end;
OPERATOR -(CONST x:T_bigInt; CONST y:int64):T_bigInt;
VAR bigY:T_bigInt;
begin
bigY.fromInt(y);
result:=x-bigY;
end;
OPERATOR -(CONST x:int64; CONST y:T_bigInt):T_bigInt;
VAR bigX:T_bigInt;
begin
bigX.fromInt(x);
result:=bigX-y;
end;
OPERATOR -(CONST x,y:T_bigInt):T_bigInt;
begin
if x.negative xor y.negative then
//(-x)-y = -(x+y)
//x-(-y) = x+y
result.createFromRawData(x.negative,rawDataPlus(x.digits,y.digits))
else case x.compareAbsValue(y) of
CR_EQUAL : result.createZero;
CR_LESSER : // x-y = -(y-x) //opposed sign as y
result.createFromRawData(not(y.negative),rawDataMinus(y.digits,x.digits));
CR_GREATER: result.createFromRawData(x.negative ,rawDataMinus(x.digits,y.digits));
end;
end;
OPERATOR *(CONST x:T_bigInt; CONST y:int64):T_bigInt;
VAR bigY:T_bigInt;
begin
bigY.fromInt(y);
result:=x*bigY;
end;
OPERATOR *(CONST x,y:T_bigInt):T_bigInt;
VAR i,j,k:longint;
carry:CarryType=0;
begin
{$ifndef debugMode}
if x.canBeRepresentedAsInt32() then begin
if y.canBeRepresentedAsInt32() then begin
result.fromInt(x.toInt*y.toInt);
exit(result);
end else begin
result.create(y);
result.multWith(x);
exit(result);
end;
end else if y.canBeRepresentedAsInt32() then begin
result.create(x);
result.multWith(y.toInt);
exit(result);
end;
{$endif}
result.create(x.negative xor y.negative,length(x.digits)+length(y.digits));
for k:=0 to length(result.digits)-1 do result.digits[k]:=0;
for i:=0 to length(x.digits)-1 do
for j:=0 to length(y.digits)-1 do begin
k:=i+j;
carry:=CarryType(x.digits[i])*CarryType(y.digits[j]);
while carry>0 do begin
//x[i]*y[i]+r[i] <= (2^n-1)*(2^n-1)+2^n-1
// = (2^n)^2 - 2*2^n + 1 + 2^n-1
// = (2^n)^2 - 2*2^n + 1
// < (2^n)^2 - 2 + 1 = (max value of carry type)
carry+=result.digits[k];
result.digits[k]:=carry and DIGIT_MAX_VALUE;
carry:=carry shr BITS_PER_DIGIT;
inc(k);
end;
end;
trimLeadingZeros(result.digits);
end;
FUNCTION divide (CONST x:T_bigInt; CONST y:int64):T_bigInt;
VAR bigY:T_bigInt;
begin
bigY.fromInt(y);
result:=x.divide(bigY);
end;
FUNCTION divide (CONST x:int64; CONST y:T_bigInt):T_bigInt;
VAR bigX:T_bigInt;
begin
bigX.fromInt(x);
result:=bigX.divide(y);
end;
OPERATOR mod(CONST x:T_bigInt; CONST y:int64):int64;
FUNCTION digitValue(CONST index:longint):int64; inline;
VAR f:int64;
i:longint;
begin
result:=x.digits[index] mod y;
i:=index;
f:=(DIGIT_MAX_VALUE+1) mod y;
while i>0 do begin
if odd(i) then begin
result:=(result * f) mod y;
end;
f:=(f*f) mod y;
i:=i shr 1;
end;
end;
VAR bigY,bigResult,bigQuotient:T_bigInt;
k:longint;
begin
if (y>-3025451648) and (y<3025451648) then begin
result:=0;
for k:=0 to length(x.digits)-1 do result:=(result+digitValue(k)) mod y;
end else begin
bigY.fromInt(y);
x.divMod(bigY,bigQuotient,bigResult);
result:=bigResult.toInt;
end;
end;
FUNCTION modulus(CONST x:int64; CONST y:T_bigInt):T_bigInt;
VAR bigX:T_bigInt;
begin
if y.canBeRepresentedAsInt64() then result.fromInt(x) else begin
bigX.fromInt(x);
result:=bigX.modulus(y);
end;
end;
FUNCTION T_bigInt.isOdd:boolean; begin result:=(length(digits)>0) and odd(digits[0]); end;
PROCEDURE T_bigInt.createFromRawData(CONST negative_:boolean; CONST digits_:DigitTypeArray);
begin
negative :=negative_ and (length(digits_)>0); //no such thing as a negative zero
digits :=digits_;
end;
PROCEDURE T_bigInt.nullBits(CONST numberOfBitsToKeep:longint);
VAR i:longint;
begin
for i:=length(digits)*BITS_PER_DIGIT-1 downto numberOfBitsToKeep do setBit(i,false);
end;
PROCEDURE T_bigInt.shlInc(CONST incFirstBit: boolean);
VAR k:longint;
carryBit:boolean;
nextCarry:boolean;
begin
carryBit:=incFirstBit;
nextCarry:=carryBit;
for k:=0 to length(digits)-1 do begin
nextCarry:=(digits[k] and UPPER_DIGIT_BIT)<>0;
{$R-}
digits[k]:=digits[k] shl 1;
{$R+}
if carryBit then inc(digits[k]);
carryBit:=nextCarry;
end;
if nextCarry then begin
k:=length(digits);
setLength(digits,k+1);
digits[k]:=1;
end;
end;
FUNCTION T_bigInt.relevantBits: longint;
VAR upperDigit:DigitType;
k:longint;
begin
if length(digits)=0 then exit(0);
upperDigit:=digits[length(digits)-1];
result:=BITS_PER_DIGIT*length(digits);
for k:=BITS_PER_DIGIT-1 downto 0 do
if upperDigit<WORD_BIT[k]
then dec (result)
else exit(result);
end;
FUNCTION T_bigInt.getBit(CONST index: longint): boolean;
VAR digitIndex:longint;
bitIndex :longint;
begin
digitIndex:=index div BITS_PER_DIGIT;
if digitIndex>=length(digits) then exit(false);
bitIndex :=index mod BITS_PER_DIGIT;
result:=(digits[digitIndex] and WORD_BIT[bitIndex])<>0;
end;
PROCEDURE T_bigInt.setBit(CONST index: longint; CONST value: boolean);
VAR digitIndex:longint;
bitIndex :longint;
oldLength:longint;
k:longint;
begin
digitIndex:=index div BITS_PER_DIGIT;
bitIndex:=index and (BITS_PER_DIGIT-1);
if value then begin
//setting a true bit means, we might have to increase the number of digits
if (digitIndex>=length(digits)) and value then begin
oldLength:=length(digits);
setLength(digits,digitIndex+1);
for k:=length(digits)-1 downto oldLength do digits[k]:=0;
end;
digits[digitIndex]:=digits[digitIndex] or WORD_BIT[bitIndex];
end else begin
//setting a false bit means, we might have to decrease the number of digits
if digitIndex>=length(digits) then exit;
digits[digitIndex]:=digits[digitIndex] and not(WORD_BIT[bitIndex]);
trimLeadingZeros(digits);
end;
end;
PROCEDURE T_bigInt.createZero;
begin
create(false,0);
end;
PROCEDURE T_bigInt.create(CONST negativeNumber: boolean; CONST digitCount_: longint);
begin
negative:=negativeNumber;
setLength(digits,digitCount_);
end;
PROCEDURE T_bigInt.fromInt(CONST i: int64);
VAR unsigned:int64;
d0,d1:DigitType;
begin
negative:=i<0;
if negative
then unsigned:=-i
else unsigned:= i;
d0:=(unsigned ) and DIGIT_MAX_VALUE;
d1:=(unsigned shr (BITS_PER_DIGIT )) and DIGIT_MAX_VALUE;
if d1=0 then begin
if d0=0
then setLength(digits,0)
else setLength(digits,1);
end else setLength(digits,2);
if length(digits)>0 then digits[0]:=d0;
if length(digits)>1 then digits[1]:=d1;
end;
PROCEDURE T_bigInt.fromString(CONST s: string);
CONST MAX_CHUNK_SIZE=9;
CHUNK_FACTOR:array[1..MAX_CHUNK_SIZE] of longint=(10,100,1000,10000,100000,1000000,10000000,100000000,1000000000);
VAR i:longint=1;
chunkSize:longint;
chunkValue:DigitType;
begin
createZero;
if length(s)=0 then raise Exception.create('Cannot parse empty string');
if s[1]='-' then begin
negative:=true;
inc(i);
end;
while i<=length(s) do begin
chunkSize:=length(s)-i+1;
if chunkSize>4 then chunkSize:=4;
chunkValue:=strToInt(copy(s,i,chunkSize));
multWith(CHUNK_FACTOR[chunkSize]);
incAbsValue(chunkValue);
inc(i,chunkSize);
end;
end;
PROCEDURE T_bigInt.fromFloat(CONST f: extended; CONST rounding: T_roundingMode);
VAR r:TDoubleRec;
fraction:double;
begin
r.value:=f;
fromInt(r.Mantissa+4503599627370496);
shiftRight(52-r.exponent);
case rounding of
RM_DEFAULT: begin fraction:=frac(abs(f)); if (fraction>0.5) or (fraction=0.5) and getBit(0) then incAbsValue(1); end;
RM_UP : if not(r.sign) and (frac(f)<>0) then incAbsValue(1);
RM_DOWN : if r.sign and (frac(f)<>0) then incAbsValue(1);
end;
negative:=r.sign;
end;
PROCEDURE T_bigInt.create(CONST toClone: T_bigInt);
VAR k:longint;
begin
create(toClone.negative,length(toClone.digits));
for k:=0 to length(digits)-1 do digits[k]:=toClone.digits[k];
end;
PROCEDURE T_bigInt.createFromDigits(CONST base: longint; CONST digits_:T_arrayOfLongint);
VAR i:longint;
begin
createZero;
for i:=0 to length(digits_)-1 do begin
multWith(base);
incAbsValue(digits_[i]);
end;
end;
PROCEDURE T_bigInt.clear;
begin
setLength(digits,0);
end;
FUNCTION newFromBigDigits(CONST digits:T_arrayOfBigint; CONST base:T_bigInt):T_bigInt;
VAR i:longint;
tmp:T_bigInt;
allSmall:boolean;
baseAsInt:longint;
begin
allSmall:=(base.canBeRepresentedAsInt32()) and not(base.negative);
for i:=0 to length(digits)-1 do allSmall:=allSmall and (length(digits[i].digits)<=1) and not(digits[i].negative);
result.createZero;
if allSmall then begin
baseAsInt:=base.toInt;
for i:=0 to length(digits)-1 do begin
result.multWith(baseAsInt);
if length(digits[i].digits)>0 then result.incAbsValue(digits[i].digits[0]);
end;
end else begin
for i:=0 to length(digits)-1 do begin
tmp:=result*base;
result:=tmp + digits[i];
end;
end;
end;
FUNCTION T_bigInt.toInt: int64;
begin
if length(digits)>0 then begin
result:=digits[0];
if length(digits)>1 then inc(result,int64(digits[1]) shl BITS_PER_DIGIT);
if negative then result:=-result;
end else result:=0;
end;
FUNCTION T_bigInt.toFloat: extended;
VAR k:longint;
begin
result:=0;
for k:=length(digits)-1 downto 0 do result:=result*(DIGIT_MAX_VALUE+1)+digits[k];
if negative then result:=-result;
end;
FUNCTION T_bigInt.canBeRepresentedAsInt64(CONST examineNicheCase: boolean): boolean;
begin
if length(digits)*BITS_PER_DIGIT>64 then exit(false);
if length(digits)*BITS_PER_DIGIT<64 then exit(true);
if not(getBit(63)) then exit(true);
if negative and examineNicheCase then begin
//in this case we can still represent -(2^63), so there is one special case to consider:
result:=(digits[1]=UPPER_DIGIT_BIT) and (digits[0]=0);
end else
result:=false;
end;
FUNCTION T_bigInt.canBeRepresentedAsInt62:boolean;
CONST UPPER_TWO_BITS=3 shl (BITS_PER_DIGIT-2);
begin
if length(digits)*BITS_PER_DIGIT>62 then exit(false);
if length(digits)*BITS_PER_DIGIT<62 then exit(true);
result:=digits[1] and UPPER_TWO_BITS=0;
end;
FUNCTION T_bigInt.canBeRepresentedAsInt32(CONST examineNicheCase: boolean): boolean;
begin
if length(digits)*BITS_PER_DIGIT>32 then exit(false);
if length(digits)*BITS_PER_DIGIT<32 then exit(true);
if not(getBit(31)) then exit(true);
if negative and examineNicheCase then begin
//in this case we can still represent -(2^31), so there is one special case to consider:
result:=(digits[0]=UPPER_DIGIT_BIT);
end else
result:=false;
end;
PROCEDURE T_bigInt.flipSign;
begin
negative:=not(negative);
end;
FUNCTION T_bigInt.negated: T_bigInt;
begin
result.create(self);
result.flipSign;
end;
FUNCTION T_bigInt.compareAbsValue(CONST big: T_bigInt): T_comparisonResult;
VAR i:longint;
begin
if length(digits)<length(big.digits) then exit(CR_LESSER);
if length(digits)>length(big.digits) then exit(CR_GREATER);
//compare highest value digits first
for i:=length(digits)-1 downto 0 do begin
if digits[i]<big.digits[i] then exit(CR_LESSER);
if digits[i]>big.digits[i] then exit(CR_GREATER);
end;
result:=CR_EQUAL;
end;
FUNCTION T_bigInt.compareAbsValue(CONST int: int64): T_comparisonResult;
VAR s,i:int64;
begin
if not(canBeRepresentedAsInt64(false)) then exit(CR_GREATER);
s:=toInt; if s<0 then s:=-s;
i:= int; if i<0 then i:=-i;
if s>i then exit(CR_GREATER);
if s<i then exit(CR_LESSER);
result:=CR_EQUAL;
end;
FUNCTION T_bigInt.compare(CONST big: T_bigInt): T_comparisonResult;
begin
if negative and not(big.negative) then exit(CR_LESSER);
if not(negative) and big.negative then exit(CR_GREATER);
if negative then exit(C_FLIPPED[compareAbsValue(big)])
else exit( compareAbsValue(big) );
end;
FUNCTION T_bigInt.compare(CONST int: int64): T_comparisonResult;
VAR s:int64;
begin
if int=0 then begin
if length(digits)=0 then exit(CR_EQUAL)
else if negative then exit(CR_LESSER)
else exit(CR_GREATER);
end;
if not(canBeRepresentedAsInt64) then begin
if negative then exit(CR_LESSER)
else exit(CR_GREATER);
end;
s:=toInt;
if s>int then exit(CR_GREATER);
if s<int then exit(CR_LESSER);
result:=CR_EQUAL;
end;
FUNCTION T_bigInt.compare(CONST f: extended): T_comparisonResult;
VAR unsigned:extended;
fraction:extended;
d:DigitType;
k:longint;
begin
if isNan(f) then exit(CR_INVALID_COMPARAND);
if isInfinite(f) then begin
if f>0 then exit(CR_LESSER)
else exit(CR_GREATER);
end;
if negative and (f>=0) then exit(CR_LESSER);
if not(negative) and (f< 0) then exit(CR_GREATER);
//both have same sign; none is infinite
if negative then unsigned:=-f else unsigned:=f;
fraction:=frac(unsigned);
k:=0;
while unsigned>=1 do begin
inc(k);
unsigned/=(DIGIT_MAX_VALUE+1);
end;
if k>length(digits) then begin
if negative then exit(CR_GREATER)
else exit(CR_LESSER);
end else if k<length(digits) then begin
if negative then exit(CR_LESSER)
else exit(CR_GREATER);
end;
for k:=length(digits)-1 downto 0 do begin
unsigned*=(DIGIT_MAX_VALUE+1);
d:=trunc(unsigned);
if d<digits[k] then begin
if negative then exit(CR_LESSER)
else exit(CR_GREATER);
end else if d>digits[k] then begin
if negative then exit(CR_GREATER)
else exit(CR_LESSER);
end;
unsigned-=d;
end;
// all integer digits are equal; maybe there is a nonzero fraction...
if fraction>0 then begin
if negative then exit(CR_GREATER)
else exit(CR_LESSER);
end;
result:=CR_EQUAL;
end;
FUNCTION T_bigInt.minus(CONST small:DigitType):T_bigInt;
VAR smallAsArray:DigitTypeArray=();
begin
setLength(smallAsArray,1);
smallAsArray[0]:=small;
if negative then
//(-x)-y = -(x+y)
//x-(-y) = x+y
result.createFromRawData(negative,rawDataPlus(digits,smallAsArray))
else case compareAbsValue(small) of
CR_EQUAL : result.createZero;
CR_LESSER : // x-y = -(y-x) //opposed sign as y
result.createFromRawData(true ,rawDataMinus(smallAsArray,digits));
CR_GREATER: result.createFromRawData(false,rawDataMinus(digits,smallAsArray));
end;
end;
FUNCTION T_bigInt.pow(power: dword): T_bigInt;
CONST BASE_THRESHOLD_FOR_EXPONENT:array[2..62] of longint=(maxLongint,2097151,55108,6208,1448,511,234,127,78,52,38,28,22,18,15,13,11,9,8,7,7,6,6,5,5,5,4,4,4,4,3,3,3,3,3,3,3,3,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2);
VAR multiplicand:T_bigInt;
m:int64;
r:int64;
begin
// x ** 0 = 1
if power=0 then begin
result.create(false,1);
result.digits[0]:=1;
exit(result);
end;
// x^1 = x
if power=1 then begin
result.create(self);
exit(result);
end;
if (power<=62) and (compareAbsValue(BASE_THRESHOLD_FOR_EXPONENT[power]) in [CR_EQUAL,CR_LESSER]) then begin
r:=1;
m:=toInt;
{$R-}{$Q-}
while power>0 do begin
if odd(power) then r*=m;
m*=m;
power:=power shr 1;
end;
{$R+}{$Q+}
result.fromInt(r);
end else begin
result.create(false,1); result.digits[0]:=1;
multiplicand.create(self);
while power>0 do begin
if odd(power) then result.multWith(multiplicand);
multiplicand.multWith(multiplicand);
power:=power shr 1;
end;
end;
end;
FUNCTION T_bigInt.powMod(CONST power,modul:T_bigInt):T_bigInt;
PROCEDURE doModulus(VAR inOut:T_bigInt);
VAR temp:T_bigInt;
begin
if inOut.compareAbsValue(modul)=CR_LESSER then exit;
temp:=inOut.modulus(modul);
inOut:=temp;
end;
VAR p,f:T_bigInt;
begin
if (power.isZero) or (power.negative) or
(modul.negative) or (modul.isZero) then begin
result.fromInt(1);
exit(result);
end;
if (power.compare(1)=CR_EQUAL) or (modul.compare(1)=CR_EQUAL) then begin
result:=modulus(modul);
exit(result);
end;
p.create(power);
f:=modulus(modul);
result.fromInt(1);
while not(p.isZero) do begin
if p.getBit(0) then begin
result.multWith(f); doModulus(result);
end;
f.multWith(f); doModulus(f);
p.shiftRightOneBit;
end;
end;
FUNCTION T_bigInt.bitAnd(CONST big: T_bigInt): T_bigInt;
VAR k,i:longint;
begin
k:=min(length(digits),length(big.digits));
result.create(isNegative and big.isNegative,k);
for i:=0 to length(result.digits)-1 do result.digits[i]:=digits[i] and big.digits[i];
trimLeadingZeros(result.digits);
end;
FUNCTION T_bigInt.bitOr(CONST big: T_bigInt): T_bigInt;
VAR k,i:longint;
begin
k:=max(length(digits),length(big.digits));
result.create(isNegative or big.isNegative,k);
for i:=0 to length(result.digits)-1 do begin
if (i< length(digits)) then result.digits[i]:=digits[i]
else result.digits[i]:=0;
if (i<length(big.digits)) then result.digits[i]:=result.digits[i] or big.digits[i];
end;
trimLeadingZeros(result.digits);
end;
FUNCTION T_bigInt.bitXor(CONST big: T_bigInt): T_bigInt;
VAR k,i:longint;
begin
k:=max(length(digits),length(big.digits));
result.create(isNegative xor big.isNegative,k);
for i:=0 to length(result.digits)-1 do begin
if (i< length(digits)) then result.digits[i]:=digits[i]
else result.digits[i]:=0;
if (i<length(big.digits)) then result.digits[i]:=result.digits[i] xor big.digits[i];
end;
trimLeadingZeros(result.digits);
end;
FUNCTION T_bigInt.bitAnd(CONST small:int64): T_bigInt; VAR big:T_bigInt; begin big.fromInt(small); result:=bitAnd(big); end;
FUNCTION T_bigInt.bitOr (CONST small:int64): T_bigInt; VAR big:T_bigInt; begin big.fromInt(small); result:=bitOr (big); end;
FUNCTION T_bigInt.bitXor(CONST small:int64): T_bigInt; VAR big:T_bigInt; begin big.fromInt(small); result:=bitXor(big); end;
FUNCTION T_bigInt.bitNegate(CONST consideredBits:longint):T_bigInt;
VAR k,i:longint;
begin
if consideredBits<=0 then k:=relevantBits
else k:=consideredBits;
result.create(false,length(digits));
for i:=0 to min(length(digits),length(result.digits))-1 do result.digits[i]:=not(digits[i]);
result.nullBits(k);
end;
FUNCTION isPowerOf2(CONST i:DigitType; OUT log2:longint):boolean; inline;
VAR k:longint;
begin
result:=false;
for k:=0 to length(WORD_BIT)-1 do if i=WORD_BIT[k] then begin
log2:=k;
exit(true);
end;
end;
PROCEDURE T_bigInt.multWith(CONST l: longint);
VAR carry:CarryType=0;
factor:DigitType;
i:longint;
k:longint;
begin
if l=0 then begin
setLength(digits,0);
negative:=false;
exit;
end;
if l<0 then begin
factor:=-l;
negative:=not(negative);
end else factor:=l;
if isPowerOf2(factor,k) then begin
shiftRight(-k);
exit;
end;
for k:=0 to length(digits)-1 do begin
carry+=CarryType(factor)*CarryType(digits[k]);
digits[k]:=carry and DIGIT_MAX_VALUE;
carry:=carry shr BITS_PER_DIGIT;
end;
if carry>0 then begin
k:=length(digits)+1;
//need to grow... but how much ?
if carry shr BITS_PER_DIGIT>0 then begin
inc(k);
if carry shr (2*BITS_PER_DIGIT)>0 then inc(k);
end;
i:=length(digits);
setLength(digits,k);
while i<k do begin
digits[i]:=carry and DIGIT_MAX_VALUE;
carry:=carry shr BITS_PER_DIGIT;
inc(i);
end;
end;
end;
PROCEDURE T_bigInt.multWith(CONST b: T_bigInt);
VAR temp:T_bigInt;
begin
temp :=self*b;
setLength(digits,0);
digits :=temp.digits;
negative :=temp.negative;
end;
PROCEDURE T_bigInt.incAbsValue(CONST positiveIncrement: DigitType);
VAR carry:int64;
k:longint;
begin
carry:=positiveIncrement;
k:=0;
while carry>0 do begin
if k>=length(digits) then begin
setLength(digits,length(digits)+1);
digits[k]:=0;
end;
carry+=digits[k];
digits[k]:=carry and DIGIT_MAX_VALUE;
carry:=carry shr BITS_PER_DIGIT;
end;
end;
FUNCTION T_bigInt.divMod(CONST divisor: T_bigInt; OUT quotient, rest: T_bigInt): boolean;
PROCEDURE rawDec; inline;
VAR carry:CarryType=0;
i :longint;
begin
for i:=0 to length(divisor.digits)-1 do begin
carry+=divisor.digits[i];
if carry>rest.digits[i] then begin
rest.digits[i]:=((DIGIT_MAX_VALUE+1)-carry+rest.digits[i]) and DIGIT_MAX_VALUE;
carry:=1;
end else begin
rest.digits[i]-=carry;
carry:=0;
end;
end;
for i:=length(divisor.digits) to length(rest.digits)-1 do begin
if carry>rest.digits[i] then begin
rest.digits[i]:=((DIGIT_MAX_VALUE+1)-carry+rest.digits[i]) and DIGIT_MAX_VALUE;
carry:=1;
end else begin
rest.digits[i]-=carry;
carry:=0;
end;
end;
end;
FUNCTION restGeqDivisor:boolean; inline;
VAR i:longint;
begin
if length(divisor.digits)>length(rest.digits) then exit(false);
for i:=length(rest.digits)-1 downto length(divisor.digits) do if rest.digits[i]>0 then exit(true);
for i:=length(divisor.digits)-1 downto 0 do
if divisor.digits[i]<rest.digits[i] then exit(true)
else if divisor.digits[i]>rest.digits[i] then exit(false);
result:=true;
end;
VAR bitIdx:longint;
divIsPow2:boolean;
begin
if length(divisor.digits)=0 then exit(false);
bitIdx:=divisor.iLog2(divIsPow2);
if divIsPow2 then begin
rest.create(self);
rest.nullBits(bitIdx);
quotient.create(self);
quotient.shiftRight(bitIdx);
exit(true);
end;
result:=true;
quotient.create(negative xor divisor.negative,0);
rest .create(negative,length(divisor.digits));
//Initialize rest with (probably) enough digits
for bitIdx:=0 to length(rest.digits)-1 do rest.digits[bitIdx]:=0;
for bitIdx:=relevantBits-1 downto 0 do begin
rest.shlInc(getBit(bitIdx));
if restGeqDivisor then begin
rawDec();
quotient.setBit(bitIdx,true);
end;
end;
trimLeadingZeros(rest.digits);
end;
FUNCTION T_bigInt.divide(CONST divisor: T_bigInt): T_bigInt;
VAR temp:T_bigInt;
{$ifndef debugMode} intRest:DigitType; {$endif}
begin
{$ifndef debugMode}
if (canBeRepresentedAsInt64() and divisor.canBeRepresentedAsInt64()) then begin
result.fromInt(toInt div divisor.toInt);
exit(result);
end else if divisor.canBeRepresentedAsInt32(false) and not(divisor.negative) then begin
result.create(self);
result.divBy(divisor.toInt,intRest);
exit(result);
end;
{$endif}
divMod(divisor,result,temp);
end;
FUNCTION T_bigInt.modulus(CONST divisor: T_bigInt): T_bigInt;
VAR temp:T_bigInt;
{$ifndef debugMode} intRest:DigitType; {$endif}
begin
{$ifndef debugMode}
if (canBeRepresentedAsInt64() and divisor.canBeRepresentedAsInt64()) then begin
result.fromInt(toInt mod divisor.toInt);
exit(result);
end else if divisor.canBeRepresentedAsInt32(false) and not(divisor.negative) then begin
temp.create(self);
temp.divBy(divisor.toInt,intRest);
result.fromInt(intRest);
exit(result);
end;
{$endif}
divMod(divisor,temp,result);
end;
PROCEDURE T_bigInt.divBy(CONST divisor: DigitType; OUT rest: DigitType);
VAR bitIdx:longint;
quotient:T_bigInt;
divisorLog2:longint;
tempRest:CarryType=0;
begin
if length(digits)=0 then begin
rest:=0;
exit;
end;
if isPowerOf2(divisor,divisorLog2) then begin
rest:=digits[0] and (divisor-1);
shiftRight(divisorLog2);
exit;
end else begin
quotient.createZero;
for bitIdx:=relevantBits-1 downto 0 do begin
tempRest:=tempRest shl 1;
if getBit(bitIdx) then inc(tempRest);
if tempRest>=divisor then begin
dec(tempRest,divisor);
quotient.setBit(bitIdx,true);
end;
end;
setLength(digits,0);
digits:=quotient.digits;
rest:=tempRest;
end;
end;
FUNCTION T_bigInt.toString: string;
VAR temp:T_bigInt;
chunkVal:DigitType;
chunkTxt:string;
begin
if length(digits)=0 then exit('0');
temp.create(self);
result:='';
while temp.compareAbsValue(10000000) in [CR_EQUAL,CR_GREATER] do begin
temp.divBy(100000000,chunkVal);
chunkTxt:=intToStr(chunkVal);
result:=StringOfChar('0',8-length(chunkTxt))+chunkTxt+result;
end;
while temp.compareAbsValue(1000) in [CR_EQUAL,CR_GREATER] do begin
temp.divBy(10000,chunkVal);
chunkTxt:=intToStr(chunkVal);
result:=StringOfChar('0',4-length(chunkTxt))+chunkTxt+result;
end;
while temp.compareAbsValue(1) in [CR_EQUAL,CR_GREATER] do begin
temp.divBy(10,chunkVal);
chunkTxt:=intToStr(chunkVal);
result:=chunkTxt+result;
end;
if negative then result:='-'+result;
end;
FUNCTION T_bigInt.toHexString:string;
CONST hexChar:array [0..15] of char=('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F');
shifts:array[0..7] of byte=(28,24,20,16,12,8,4,0);
VAR hasADigit:boolean=false;
digit :DigitType;
hexDig:byte;
Shift :byte;
i:longint;
begin
if length(digits)=0 then exit('0');
if negative then result:='-' else result:='';
for i:=length(digits)-1 downto 0 do begin
digit:=digits[i];
for Shift in shifts do begin
hexDig:=(digit shr Shift) and 15;
if (hexDig>0) or hasADigit then begin
hasADigit:=true;
result+=hexChar[hexDig];
end;
end;
end;
end;
FUNCTION T_bigInt.getDigits(CONST base: longint): T_arrayOfLongint;
VAR temp:T_bigInt;
digit:DigitType;
iTemp:int64;
s:string;
resLen:longint=0;
begin
initialize(result);
setLength(result,0);
if isZero then exit(0);
if canBeRepresentedAsInt64(false) then begin
setLength(result,64);
iTemp:=toInt;
if negative then iTemp:=-iTemp;
while (iTemp>0) do begin
digit:=iTemp mod base;
iTemp:=iTemp div base;
result[resLen]:=digit;
inc(resLen);
end;
setLength(result,resLen);
end else if base=10 then begin
s:=toString;
if negative then s:=copy(s,2,length(s)-1);
setLength(result,length(s));
for digit:=1 to length(s) do
result[length(s)-digit]:=ord(s[digit])-ord('0');
end else if base=2 then begin
iTemp:=relevantBits;
setLength(result,iTemp);
for digit:=0 to iTemp-1 do if getBit(digit) then result[digit]:=1 else result[digit]:=0;
end else begin
temp.create(self);
if negative then temp.flipSign;
while temp.compareAbsValue(1) in [CR_EQUAL,CR_GREATER] do begin
temp.divBy(base,digit);
setLength(result,length(result)+1);
result[length(result)-1]:=digit;
end;
end;
end;
FUNCTION bigDigits(CONST value,base:T_bigInt):T_arrayOfBigint;
VAR temp,quotient,rest:T_bigInt;
smallDigits:T_arrayOfLongint;
k:longint;
resSize:longint=0;
begin
initialize(result);
if base.canBeRepresentedAsInt32 then begin
smallDigits:=value.getDigits(base.toInt);
setLength(result,length(smallDigits));
for k:=0 to length(smallDigits)-1 do result[k].fromInt(smallDigits[k]);
setLength(smallDigits,0);
end else begin
setLength(result,round(1+1.01*length(value.digits)));
temp.create(value);
temp.negative:=false;
while temp.compareAbsValue(1) in [CR_EQUAL,CR_GREATER] do begin
temp.divMod(base,quotient,rest);
result[resSize]:=rest; inc(resSize);
temp:=quotient;
end;
setLength(result,resSize);
end;
end;
FUNCTION T_bigInt.equals(CONST b: T_bigInt): boolean;
VAR k:longint;
begin
if (negative <>b.negative) or
(length(digits)<>length(b.digits)) then exit(false);
for k:=0 to length(digits)-1 do if (digits[k]<>b.digits[k]) then exit(false);
result:=true;
end;
FUNCTION T_bigInt.isZero: boolean;
begin
result:=length(digits)=0;
end;
FUNCTION T_bigInt.isOne: boolean;
begin
result:=(length(digits)=1) and not(isNegative) and (digits[0]=1);
end;
FUNCTION T_bigInt.isBetween(CONST lowerBoundInclusive, upperBoundInclusive: longint): boolean;
VAR i:int64;
begin
if not(canBeRepresentedAsInt32()) then exit(false);
i:=toInt;
result:=(i>=lowerBoundInclusive) and (i<=upperBoundInclusive);
end;
PROCEDURE T_bigInt.shiftRightOneBit;
VAR k:longint;
begin
for k:=0 to length(digits)-1 do begin
if (k>0) and odd(digits[k]) then digits[k-1]:=digits[k-1] or UPPER_DIGIT_BIT;
digits[k]:=digits[k] shr 1;
end;
if (length(digits)>0) and (digits[length(digits)-1]=0) then setLength(digits,length(digits)-1);
end;
PROCEDURE T_bigInt.shiftRight(CONST rightShift:longint);
VAR digitsToShift:longint;
bitsToShift :longint;
newBitCount :longint;
newDigitCount:longint;
carry,nextCarry:DigitType;
oldLength:longint;
k:longint;
begin
if rightShift=0 then exit;
bitsToShift :=abs(rightShift);
digitsToShift:=bitsToShift div BITS_PER_DIGIT;
bitsToShift -=digitsToShift * BITS_PER_DIGIT;
if rightShift>0 then begin
if rightShift>=relevantBits then begin
setLength(digits,0);
negative:=false;
exit;
end;
if digitsToShift>0 then begin
for k:=0 to length(digits)-digitsToShift-1 do digits[k]:=digits[k+digitsToShift];
for k:=length(digits)-digitsToShift to length(digits)-1 do digits[k]:=0;
end;
if bitsToShift>0 then begin
carry:=0;
for k:=length(digits)-digitsToShift-1 downto 0 do begin
nextCarry:=digits[k];
digits[k]:=(digits[k] shr bitsToShift) or (carry shl (BITS_PER_DIGIT-bitsToShift));
carry:=nextCarry;
end;
end;
trimLeadingZeros(digits);
end else begin
newBitCount:=relevantBits-rightShift;
newDigitCount:=newBitCount div BITS_PER_DIGIT; if newDigitCount*BITS_PER_DIGIT<newBitCount then inc(newDigitCount);
if newDigitCount>length(digits) then begin
oldLength:=length(digits);
setLength(digits,newDigitCount);
for k:=oldLength to newDigitCount-1 do digits[k]:=0;
end;
if digitsToShift>0 then begin
for k:=length(digits)-1 downto digitsToShift do digits[k]:=digits[k-digitsToShift];
for k:=digitsToShift-1 downto 0 do digits[k]:=0;
end;
if bitsToShift>0 then begin
carry:=0;
for k:=0 to length(digits)-1 do begin
nextCarry:=digits[k] shr (BITS_PER_DIGIT-bitsToShift);
digits[k]:=(digits[k] shl bitsToShift) or carry;
carry:=nextCarry;
end;
end;
end;
end;
PROCEDURE T_bigInt.writeToStream(CONST stream: P_outputStreamWrapper);
VAR value:int64;
k:longint;
begin
if canBeRepresentedAsInt64() then begin
value:=toInt;
if (value>= 0) and (value<= 249) then stream^.writeByte(value)
else if (value>= -128) and (value<= 127) then begin stream^.writeByte(250); stream^.writeShortint(value); end
else if (value>= -32768) and (value<= 32767) then begin stream^.writeByte(251); stream^.writeSmallInt(value); end
else if (value>=-2147483648) and (value<=2147483647) then begin stream^.writeByte(252); stream^.writeLongint (value); end
else begin stream^.writeByte(253); stream^.writeInt64 (value); end;
end else begin
if negative
then stream^.writeByte(255)
else stream^.writeByte(254);
stream^.writeLongint(length(digits)); //number of following Dwords
for k:=0 to length(digits)-1 do stream^.writeDWord(digits[k]);
end;
end;
FUNCTION readLongintFromStream(CONST markerByte:byte; CONST stream:P_inputStreamWrapper):longint;
begin
case markerByte of
253..255: raise Exception.create('Could not read longint from stream; the number is too big.');
252: result:=stream^.readLongint;
251: result:=stream^.readSmallInt;
250: result:=stream^.readShortint;
else result:=markerByte;
end;
end;
PROCEDURE writeLongintToStream(CONST value:longint; CONST stream:P_outputStreamWrapper);
begin
if (value>= 0) and (value<= 249) then stream^.writeByte(value)
else if (value>= -128) and (value<= 127) then begin stream^.writeByte(250); stream^.writeShortint(value); end
else if (value>=-32768) and (value<=32767) then begin stream^.writeByte(251); stream^.writeSmallInt(value); end
else begin stream^.writeByte(252); stream^.writeLongint (value); end;
end;
PROCEDURE T_bigInt.readFromStream(CONST markerByte:byte; CONST stream:P_inputStreamWrapper);
VAR k:longint;
begin
case markerByte of
254,255: begin
negative:=odd(markerByte);
setLength(digits,stream^.readLongint);
for k:=0 to length(digits)-1 do digits[k]:=stream^.readDWord;
end;
253: fromInt(stream^.readInt64);
252: fromInt(stream^.readLongint);
251: fromInt(stream^.readSmallInt);
250: fromInt(stream^.readShortint);
else fromInt(markerByte);
end;
end;
PROCEDURE T_bigInt.readFromStream(CONST stream: P_inputStreamWrapper);
begin
readFromStream(stream^.readByte,stream);
end;
FUNCTION T_bigInt.lowDigit: DigitType;
begin
if length(digits)=0 then exit(0) else exit(digits[0]);
end;
FUNCTION T_bigInt.sign: shortint;
begin
if length(digits)=0 then exit(0) else if negative then exit(-1) else exit(1);
end;
FUNCTION T_bigInt.greatestCommonDivider(CONST other: T_bigInt): T_bigInt;
VAR b,temp:T_bigInt;
x,y,t:int64;
begin
if canBeRepresentedAsInt64(false) and other.canBeRepresentedAsInt64(false) then begin
x:= toInt;
y:=other.toInt;
while (y<>0) do begin
t:=x mod y; x:=y; y:=t;
end;
result.fromInt(x);
end else begin
result.create(self);
b.create(other);
while not(b.isZero) do begin
temp:=result.modulus(b);
result:=b;
b:=temp;
end;
end;
end;
FUNCTION T_bigInt.greatestCommonDivider(CONST other:int64):int64;
VAR y,t:int64;
tempO,tempR:T_bigInt;
begin
if canBeRepresentedAsInt64(false) then begin
result:=toInt;
y:=other;
while (y<>0) do begin
t:=result mod y; result:=y; y:=t;
end;
end else begin
tempO.fromInt(other);
tempR:=greatestCommonDivider(tempO);
result:=tempR.toInt;
end;
end;
FUNCTION T_bigInt.modularInverse(CONST modul:T_bigInt; OUT thereIsAModularInverse:boolean):T_bigInt;
VAR r0,r1,
t0,t1,
quotient,rest:T_bigInt;
{$ifndef debugMode}
iq,ir0,ir1,tmp:int64;
it0:int64=0;
it1:int64=1;
{$endif}
begin
{$ifndef debugMode}
if canBeRepresentedAsInt64(false) and modul.canBeRepresentedAsInt64(false) then begin
ir0:=abs(modul.toInt);
ir1:=abs( toInt);
while(ir1<>0) do begin
iq:=ir0 div ir1;
tmp:=ir1; ir1:=ir0-ir1*iq; ir0:=tmp;
tmp:=it1; it1:=it0-it1*iq; it0:=tmp;
end;
thereIsAModularInverse:=ir0<=1;
if it0<0 then inc(it0,modul.toInt);
result.fromInt(it0);
end else
{$endif}
begin
t0.createZero;
t1.fromInt(1);
r0.create(modul); r0.negative:=false;
r1.create(self); r1.negative:=false;
initialize(quotient);
initialize(rest);
while not(r1.isZero) do begin
setLength(quotient.digits,0);
setLength(rest.digits,0);
r0.divMod(r1,quotient,rest);
r0:=r1;
r1:=rest;
quotient:=t0-quotient*t1;
t0:=t1;
t1:=quotient;
end;
setLength(r0.digits,0);
setLength(r1.digits,0);
setLength(t1.digits,0);
setLength(rest.digits,0);
setLength(quotient.digits,0);
thereIsAModularInverse:=r0.compare(1) in [CR_LESSER,CR_EQUAL];
if (t0.isNegative) then begin
result:=t0 + modul;
end else result:=t0;
end;
end;
FUNCTION T_bigInt.iSqrt(CONST computeEvenIfNotSquare:boolean; CONST roundingMode:T_roundingMode; OUT isSquare:boolean):T_bigInt;
CONST SQUARE_LOW_BYTE_VALUES:set of byte=[0,1,4,9,16,17,25,33,36,41,49,57,64,65,68,73,81,89,97,100,105,113,121,129,132,137,144,145,153,161,164,169,177,185,193,196,201,209,217,225,228,233,241,249];
VAR resDt,temp:T_bigInt;
done:boolean=false;
step:longint=0;
selfShl16:T_bigInt;
{$ifndef debugMode}intRoot:int64;{$endif}
floatSqrt:double;
begin
if negative or isZero then begin
isSquare:=length(digits)=0;
result.createZero;
exit(result);
end;
if not((digits[0] and 255) in SQUARE_LOW_BYTE_VALUES) then begin
isSquare:=false;
if not(computeEvenIfNotSquare) then begin
result.createZero;
exit;
end;
end;
{$ifndef debugMode}
if canBeRepresentedAsInt64 then begin
intRoot:=trunc(sqrt(toFloat));
result.fromInt(intRoot);
isSquare:=toInt=intRoot*intRoot;
exit;
end else if relevantBits<102 then begin
result.fromFloat(sqrt(toFloat),RM_DOWN);
temp:=result*result;
isSquare:=equals(temp);
exit;
end;
{$endif}
//compute the square root of this*2^16, validate by checking lower 8 bits
selfShl16.create(self);
selfShl16.multWith(1 shl 16);
floatSqrt:=sqrt(toFloat)*256;
if isInfinite(floatSqrt) or isNan(floatSqrt) then begin
result.createZero;
result.setBit(selfShl16.relevantBits shr 1+1,true);
end else result.fromFloat(floatSqrt,RM_DOWN);
repeat
selfShl16.divMod(result,resDt,temp); //resDt = y div x@pre; temp = y mod x@pre
isSquare:=temp.isZero;
temp:=resDt + result; //temp = y div x@pre + x@pre
isSquare:=isSquare and not odd(temp.digits[0]);
temp.shiftRightOneBit;
done:=result.equals(temp);
result:=temp;
inc(step);
until done or (step>100);
isSquare:=isSquare and ((result.digits[0] and 255)=0);
case roundingMode of
RM_UP : if (result.digits[0] and 255)=0 then begin
result.shiftRight(8);
end else begin
result.shiftRight(8);
result.incAbsValue(1);
end;
RM_DEFAULT: if (result.digits[0] and 255)<127 then begin
result.shiftRight(8);
end else begin
result.shiftRight(8);
result.incAbsValue(1);
end;
else result.shiftRight(8);
end;
end;
FUNCTION T_bigInt.iLog2(OUT isPowerOfTwo:boolean):longint;
VAR i:longint;
begin
isPowerOfTwo:=false;
if length(digits)=0 then exit(0);
i:=length(digits)-1;
if isPowerOf2(digits[length(digits)-1],result) then begin
inc(result,BITS_PER_DIGIT*(length(digits)-1));
isPowerOfTwo:=true;
for i:=length(digits)-2 downto 0 do isPowerOfTwo:=isPowerOfTwo and (digits[i]=0);
end else result:=0;
end;
FUNCTION T_bigInt.hammingWeight:longint;
VAR i:longint;
begin
result:=0;
for i:=0 to length(digits)*BITS_PER_DIGIT-1 do if getBit(i) then inc(result);
end;
FUNCTION T_bigInt.getRawBytes: T_arrayOfByte;
VAR i:longint;
tmp:dword=0;
begin
i:=relevantBits shr 3;
if i*8<relevantBits then inc(i);
initialize(result);
setLength(result,i);
for i:=0 to length(result)-1 do begin
if i and 3=0 then tmp:=digits[i shr 2]
else tmp:=tmp shr 8;
result[i]:=tmp and 255;
end;
end;
FUNCTION T_bigInt.hash:dword;
VAR i:longint;
begin
{$Q-}{$R-}
if isNegative then result:=1+2*length(digits) else result:=2*length(digits);
for i:=0 to length(digits)-1 do result:=result*dword(127) + ((digits[i]*dword(11)) shr 3);
{$Q+}{$R+}
end;
CONST primes:array[0..144] of word=(3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839);
CONST skip:array[0..47] of byte=(10,2,4,2,4,6,2,6,4,2,4,6,6,2,6,4,2,6,4,6,8,4,2,4,2,4,8,6,4,6,2,4,6,2,6,6,4,2,4,6,2,6,4,2,4,2,10,2);
FUNCTION factorizeSmall(n:int64):T_factorizationResult;
FUNCTION isSquare(CONST y:int64; OUT rootOfY:int64):boolean;
CONST SQUARE_LOW_BYTE_VALUES:set of byte=[0,1,4,9,16,17,25,33,36,41,49,57,64,65,68,73,81,89,97,100,105,113,121,129,132,137,144,145,153,161,164,169,177,185,193,196,201,209,217,225,228,233,241,249];
begin
if (y>=0) and (byte(y and 255) in SQUARE_LOW_BYTE_VALUES) then begin
rootOfY:=round(sqrt(y));
result:=rootOfY*rootOfY=y;
end else result:=false;
end;
FUNCTION gcd(x,y:int64):int64; inline;
begin
result:=x;
while (y<>0) do begin
x:=result mod y; result:=y; y:=x;
end;
end;
FUNCTION floor64(CONST d:double):int64; begin result:=trunc(d); if frac(d)<0 then dec(result); end;
FUNCTION ceil64 (CONST d:double):int64; begin result:=trunc(d); if frac(d)>0 then inc(result); end;
VAR p,k,x:int64;
rootOfY:int64;
skipIdx:longint=0;
sqrt4KN,sixthRootOfN: double;
begin
initialize(result);
setLength(result.smallFactors,0);
if n<0 then begin
n:=-n;
append(result.smallFactors,-1);
if n=1 then exit(result);
end;
if n=1 then begin
append(result.smallFactors,1);
exit(result);
end;
while (n>0) and not(odd(n)) do begin
n:=n shr 1;
append(result.smallFactors,2);
end;
for p in primes do begin
if (int64(p)*p>n) then begin
if n>1 then append(result.smallFactors,n);
exit;
end;
while n mod p=0 do begin
n:=n div p;
append(result.smallFactors,p);
end;
end;
p:=primes[length(primes)-1]+skip[length(skip)-1]; //=841
while int64(p)*p*p<=n do begin
while n mod p=0 do begin
n:=n div p;
append(result.smallFactors,p);
end;
inc(p,skip[skipIdx]);
skipIdx:=(skipIdx+1) mod length(skip);
end;
if n=1 then exit(result);
if isPrime(n) then begin
if n<=maxLongint
then append(result.smallFactors,n)
else begin
setLength(result.bigFactors,1);
result.bigFactors[0].fromInt(n);
end;
exit(result);
end;
//Lehman...
sixthRootOfN:=power(n,1/6)*0.25;
for k:=1 to floor(power(n,1/3)) do begin
sqrt4KN:=2.0*sqrt(k*n);
for x:=ceil64(sqrt4KN) to floor64(sqrt4KN+sixthRootOfN/sqrt(k)) do begin
if isSquare(int64(x)*x-4*n*k,rootOfY) then begin
p:=gcd(x+rootOfY,n);
if p<=maxLongint
then append(result.smallFactors,p)
else begin
setLength(result.bigFactors,1);
result.bigFactors[0].fromInt(p);
end;
p:=n div p;
if p<=maxLongint
then append(result.smallFactors,p)
else begin
setLength(result.bigFactors,length(result.bigFactors)+1);
result.bigFactors[length(result.bigFactors)-1].fromInt(p);
end;
exit(result);
end;
end;
end;
if n>1 then begin
if n<=maxLongint
then append(result.smallFactors,n)
else begin
setLength(result.bigFactors,1);
result.bigFactors[0].fromInt(n);
end;
end;
end;
FUNCTION factorize(CONST B:T_bigInt; CONST continue:T_dynamicContinueFlag):T_factorizationResult;
FUNCTION basicFactorize(VAR inputAndRest:T_bigInt; OUT furtherFactorsPossible:boolean):T_factorizationResult;
VAR workInInt64:boolean=false;
n:int64=9223358842721533952; //to simplify conditions
FUNCTION trySwitchToInt64:boolean; inline;
begin
if workInInt64 then exit(true);
if inputAndRest.relevantBits<63 then begin
n:=inputAndRest.toInt;
workInInt64:=true;
end;
result:=workInInt64;
end;
FUNCTION longDivideIfRestless(CONST divider:T_bigInt):boolean;
VAR quotient,rest:T_bigInt;
begin
inputAndRest.divMod(divider,quotient,rest);
if rest.isZero then begin
result:=true;
inputAndRest:=quotient;
end else begin
result:=false;
end;
end;
VAR p:longint;
bigP:T_bigInt;
skipIdx:longint=0;
thirdRootOfInputAndRest:double;
begin
furtherFactorsPossible:=true;
initialize(result);
setLength(result.smallFactors,0);
setLength(result.bigFactors,0);
//2:
if trySwitchToInt64 then begin
while (n>0) and not(odd(n)) do begin
n:=n shr 1;
append(result.smallFactors,2);
end;
end else begin
while (inputAndRest.relevantBits>0) and not(inputAndRest.isOdd) do begin
inputAndRest.shiftRightOneBit;
append(result.smallFactors,2);
end;
end;
//By list of primes:
for p in primes do begin
if (int64(p)*p>n) then begin
inputAndRest.fromInt(n);
furtherFactorsPossible:=false;
exit;
end;
if trySwitchToInt64 then begin
while n mod p=0 do begin
n:=n div p;
append(result.smallFactors,p);
end;
end else begin
while (inputAndRest mod p)=0 do begin
inputAndRest:=divide(inputAndRest,p);
append(result.smallFactors,p);
end;
end;
end;
if (continue<>nil) and not(continue()) then exit;
//By skipping:
p:=primes[length(primes)-1]+skip[length(skip)-1]; //=841
//2097151.999999 = (2^63-1)^(1/3)
while p<2097151 do begin
if workInInt64 and ((int64(p)*p*p>n)) then begin
inputAndRest.fromInt(n);
furtherFactorsPossible:=int64(p)*p<=n;
exit(result);
end;
if trySwitchToInt64 then begin
while n mod p=0 do begin
n:=n div p;
append(result.smallFactors,p);
end;
end else begin
while (inputAndRest mod p)=0 do begin
inputAndRest:=divide(inputAndRest,p);
append(result.smallFactors,p);
end;
end;
inc(p,skip[skipIdx]);
skipIdx:=(skipIdx+1) mod length(skip);
end;
if workInInt64 and isPrime(n) then begin inputAndRest.fromInt(n); furtherFactorsPossible:=false; exit(result); end;
if not(workInInt64) and isPrime(inputAndRest) then begin furtherFactorsPossible:=false; exit(result); end;
if (continue<>nil) and not(continue()) then exit;
thirdRootOfInputAndRest:=power(inputAndRest.toFloat,1/3);
while (p<maxLongint-10) and (p<thirdRootOfInputAndRest) do begin
if trySwitchToInt64 then begin
while n mod p=0 do begin
n:=n div p;
append(result.smallFactors,p);
thirdRootOfInputAndRest:=power(inputAndRest.toFloat,1/3);
end;
end else begin
while (inputAndRest mod p)=0 do begin
inputAndRest:=divide(inputAndRest,p);
append(result.smallFactors,p);
thirdRootOfInputAndRest:=power(inputAndRest.toFloat,1/3);
end;
end;
inc(p,skip[skipIdx]);
skipIdx:=(skipIdx+1) mod length(skip);
end;
if workInInt64 then begin
inputAndRest.fromInt(n);
workInInt64:=false;
end;
if p<thirdRootOfInputAndRest then begin
bigP.fromInt( p);
while (bigP.compare(thirdRootOfInputAndRest) in [CR_LESSER,CR_EQUAL]) do begin
while longDivideIfRestless(bigP) do begin
setLength(result.bigFactors,length(result.bigFactors)+1);
result.bigFactors[length(result.bigFactors)-1].create(bigP);
thirdRootOfInputAndRest:=power(inputAndRest.toFloat,1/3);
end;
bigP.incAbsValue(skip[skipIdx]);
skipIdx:=(skipIdx+1) mod length(skip);
end;
end;
end;
VAR bigFourKN:T_bigInt;
FUNCTION squareOfMinus4kn(CONST z:int64):T_bigInt;
begin
result.fromInt(z);
result:=result*result-bigFourKN;
end;
FUNCTION floor64(CONST d:double):int64; begin result:=trunc(d); if frac(d)<0 then dec(result); end;
FUNCTION ceil64 (CONST d:double):int64; begin result:=trunc(d); if frac(d)>0 then inc(result); end;
FUNCTION squareIsLesser(CONST toBeSqared:int64; CONST comparand:T_bigInt):boolean; inline;
VAR tmp:T_bigInt;
begin
tmp.fromInt(toBeSqared);
result:=not((tmp*tmp).compare(comparand) in [CR_GREATER,CR_EQUAL]);
end;
FUNCTION bigOfFloat(CONST f:double; CONST rounding:T_roundingMode):T_bigInt;
begin
result.fromFloat(f,rounding);
end;
VAR r:T_bigInt;
sixthRootOfR:double;
furtherFactorsPossible:boolean;
temp:double;
k,kMax:int64;
x,xMax:int64;
bigX,bigXMax:T_bigInt;
bigY:T_bigInt;
bigRootOfY:T_bigInt;
yIsSquare:boolean;
lehmannTestCompleted:boolean=false;
begin
initialize(result);
setLength(result.bigFactors,0);
if B.isZero or (B.compareAbsValue(1)=CR_EQUAL) then begin
setLength(result.smallFactors,1);
result.smallFactors[0]:=B.toInt;
exit;
end;
r.create(B);
if B.isNegative then append(result.smallFactors,-1);
if r.relevantBits<=63 then begin
try
result:=factorizeSmall(r.toInt);
lehmannTestCompleted:=true;
except
lehmannTestCompleted:=false;
setLength(result.smallFactors,0);
for k:=0 to length(result.bigFactors)-1 do result.bigFactors[k].clear;
setLength(result.bigFactors,0);
end;
if lehmannTestCompleted then exit;
end;
//if isPrime(r) then begin
// setLength(result.bigFactors,1);
// result.bigFactors[0]:=r;
// exit(result);
//end;
result:=basicFactorize(r,furtherFactorsPossible);
if not(furtherFactorsPossible) then begin
if not(r.compare(1) in [CR_LESSER,CR_EQUAL]) then begin
setLength(result.bigFactors,length(result.bigFactors)+1);
result.bigFactors[length(result.bigFactors)-1]:=r;
end;
exit;
end;
sixthRootOfR:=power(r.toFloat,1/6);
temp :=power(r.toFloat,1/3);
if temp<9223372036854774000
then kMax:=trunc(temp)
else kMax:=9223372036854774000;
k:=1;
if not(isPrime(r)) then while (k<=kMax) and not(lehmannTestCompleted) and ((continue=nil) or continue()) do begin
bigFourKN:=r*k;
bigFourKN.shlInc(false);
bigFourKN.shlInc(false);
if r.compare(59172824724903) in [CR_LESSER,CR_EQUAL] then begin
temp:=sqrt(bigFourKN.toFloat);
x:=ceil64(temp); //<= 4*r^(4/3) < 2^63 -> r < 2^(61*3/4) = 59172824724903
while squareIsLesser(x,bigFourKN) do inc(x);
xMax:=floor64(temp+sixthRootOfR/(4*sqrt(k))); //<= 4*r^(4/3)+r^(1/6)/(4*sqrt(r^(1/3))) -> r< 59172824724903
while x<=xMax do begin
if (continue<>nil) and not(continue()) then exit;
bigY:=squareOfMinus4kn(x);
bigRootOfY:=bigY.iSqrt(false,RM_DEFAULT,yIsSquare);
if yIsSquare then begin
bigY:=(bigRootOfY + x).greatestCommonDivider(r); //=gcd(sqrt(bigY)+x,r)
bigRootOfY:=r.divide(bigY);
if bigY.isOne
then setLength(result.bigFactors,length(result.bigFactors)+1)
else begin setLength(result.bigFactors,length(result.bigFactors)+2);
result.bigFactors[length(result.bigFactors)-2]:=bigY; end;
result .bigFactors[length(result.bigFactors)-1]:=bigRootOfY;
lehmannTestCompleted:=true;
x:=xMax;
end;
inc(x);
end;
end else begin
bigX :=bigFourKN.iSqrt(true,RM_UP,yIsSquare);
bigXMax:=bigOfFloat(sqrt(bigFourKN.toFloat)+sixthRootOfR/(4*sqrt(k)),RM_DOWN);
while bigX.compare(bigXMax) in [CR_EQUAL,CR_LESSER] do begin
if (continue<>nil) and not(continue()) then exit;
bigY:=bigX*bigX-bigFourKN;
bigRootOfY:=bigY.iSqrt(false,RM_DEFAULT,yIsSquare);
if yIsSquare then begin
bigY:=(bigRootOfY + bigX).greatestCommonDivider(r); //=gcd(sqrt(bigY)+x,r)
bigRootOfY:=r.divide(bigY);
if bigY.isOne
then setLength(result.bigFactors,length(result.bigFactors)+1)
else begin setLength(result.bigFactors,length(result.bigFactors)+2);
result.bigFactors[length(result.bigFactors)-2]:=bigY; end;
result .bigFactors[length(result.bigFactors)-1]:=bigRootOfY;
lehmannTestCompleted:=true;
bigX.create(bigXMax);
end;
bigX.incAbsValue(1);
end;
end;
inc(k);
end;
if not(lehmannTestCompleted) then begin
setLength(result.bigFactors,length(result.bigFactors)+1);
result.bigFactors[length(result.bigFactors)-1]:=r;
end;
end;
FUNCTION isPrime(CONST n:int64):boolean;
FUNCTION millerRabinTest(CONST n,a:int64):boolean;
FUNCTION modularMultiply(x,y:qword):int64;
VAR d:qword;
mp2:qword;
i:longint;
begin
if (x or y) and 9223372034707292160=0
then result:=x*y mod n
else begin
d:=0;
mp2:=n shr 1;
for i:=0 to 62 do begin
if d>mp2
then d:=(d shl 1)-qword(n)
else d:= d shl 1;
if (x and 4611686018427387904)>0 then d+=y;
if d>=qword(n) then d-=qword(n);
x:=x shl 1;
end;
result:=d;
end;
end;
VAR n1,d,t,p:int64;
j:longint=1;
k:longint;
begin
n1:=int64(n)-1;
d :=n shr 1;
while not(odd(d)) do begin
d:=d shr 1;
inc(j);
end;
//1<=j<=63, 1<=d<=2^63-1
t:=a;
p:=a;
while (d>1) do begin
d:=d shr 1;
//p:=p*p mod n;
p:=modularMultiply(p,p);
if odd(d) then t:=modularMultiply(t,p);//t:=t*p mod n;
end;
if (t=1) or (t=n1) then exit(true);
for k:=1 to j-1 do begin
//t:=t*t mod n;
t:=modularMultiply(t,t);
if t=n1 then exit(true);
if t<=1 then break;
end;
result:=false;
end;
FUNCTION isComposite:boolean;
VAR x:int64=1;
y:int64=2*3*5*7*11*13*17*19*23*29*31*37*41*43*47;
z:int64=1;
begin
x:=n mod y;
z:=y;
y:=x;
while (y<>0) do begin x:=z mod y; z:=y; y:=x; end;
result:=z>1;
end;
begin
if (n<=1) then exit(false);
if (n<48) then exit(byte(n) in [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47]);
if isComposite then exit(false)
else if n<2209 then exit(true); //2209=47*47
if n< 9080191
then exit(millerRabinTest(n,31) and
millerRabinTest(n,73)) else
if n<25326001
then exit(millerRabinTest(n,2) and
millerRabinTest(n,3) and
millerRabinTest(n,5)) else
if n < 4759123141
then exit(millerRabinTest(n,2) and
millerRabinTest(n,7) and
millerRabinTest(n,61)) else
if n < 2152302898747 //[41bit] it is enough to test a = array[0..4] of byte=(2,3,5,7,11);
then exit(millerRabinTest(n, 2) and
millerRabinTest(n, 3) and
millerRabinTest(n, 5) and
millerRabinTest(n, 7) and
millerRabinTest(n,11)) else
if n < 3474749660383 //[42bit] it is enough to test a = array[0..5] of byte=(2,3,5,7,11,13);
then exit(millerRabinTest(n, 2) and
millerRabinTest(n, 3) and
millerRabinTest(n, 5) and
millerRabinTest(n, 7) and
millerRabinTest(n,11) and
millerRabinTest(n,13)) else
if n < 341550071728321 //[49bit] it is enough to test a = array[0..6] of byte=(2,3,5,7,11,13,17);
then exit(millerRabinTest(n, 2) and
millerRabinTest(n, 3) and
millerRabinTest(n, 5) and
millerRabinTest(n, 7) and
millerRabinTest(n,11) and
millerRabinTest(n,13) and
millerRabinTest(n,17)) else
//if n < 18446744073709551616 = 2^64, it is enough to test a = 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, and 37.
result:=millerRabinTest(n, 2) and
millerRabinTest(n, 3) and
millerRabinTest(n, 5) and
millerRabinTest(n, 7) and
millerRabinTest(n,11) and
millerRabinTest(n,13) and
millerRabinTest(n,17) and
millerRabinTest(n,19) and
millerRabinTest(n,23) and
millerRabinTest(n,29) and
millerRabinTest(n,31) and
millerRabinTest(n,37);
end;
FUNCTION isPrime(CONST B:T_bigInt):boolean;
FUNCTION isComposite:boolean;
VAR x:int64=1;
y:int64=2*3*5*7*11*13*17*19*23*29*31*37*41*43*47;
z:int64=1;
begin
x:=B mod y;
z:=y;
y:=x;
while (y<>0) do begin x:=z mod y; z:=y; y:=x; end;
result:=z>1;
end;
FUNCTION bigMillerRabinTest(CONST n:T_bigInt; CONST a:int64):boolean;
VAR n1,d,t,tmp:T_bigInt;
j:longint=1;
k:longint;
begin
n1:=n.minus(1);
d.create(n);
d.shiftRightOneBit;
while not(d.isOdd) do begin
d.shiftRightOneBit;
inc(j);
end;
tmp.fromInt(a); t:=tmp.powMod(d,n);
if (t.compare(1)=CR_EQUAL) or (t.compare(n1)=CR_EQUAL) then exit(true);
for k:=1 to j-1 do begin
tmp:=t*t;
t:=tmp.modulus(n);
if (t.compare(n1)=CR_EQUAL) then begin
exit(true);
end;
if (t.compare(1) in [CR_EQUAL,CR_LESSER]) then break;
end;
result:=false;
end;
CONST
pr_79Bit:array[0..12] of byte=(2,3,5,7,11,13,17,19,23,29,31,37,41);
pr:array[0..53] of byte=(2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251);
VAR a:byte;
begin
if B.isNegative then exit(false);
if B.canBeRepresentedAsInt64(false) then exit(isPrime(B.toInt));
if (B.compare(1) in [CR_EQUAL,CR_LESSER]) or isComposite then exit(false);
if B.relevantBits<79 then begin for a in pr_79Bit do if not(bigMillerRabinTest(B,a)) then exit(false) end
else begin for a in pr do if not(bigMillerRabinTest(B,a)) then exit(false) end;
result:=true;
end;
end.
|
Unit APSelectionForm;
Interface
Uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls,
wlanNetwork, wlanBssEntry, wlanAPI, Vcl.ExtCtrls, Vcl.StdCtrls;
type
TForm2 = Class (TForm)
ListView1: TListView;
Panel1: TPanel;
Button1: TButton;
Procedure FormCreate(Sender: TObject);
Procedure Button1Click(Sender: TObject);
Procedure ListView1Deletion(Sender: TObject; Item: TListItem);
Private
FCancelled : Boolean;
FNetwork : TWlanNetwork;
FMACList : TList;
Public
Constructor Create(AOwner:TComponent; ANetwork:TWlanNetwork); Reintroduce;
Property MacList : TList Read FMacList;
Property Cancelled : Boolean Read FCancelled;
end;
Implementation
{$R *.DFM}
Procedure TForm2.Button1Click(Sender: TObject);
Var
L : TListItem;
I : Integer;
Entry : TWlanBssEntry;
begin
FCancelled := False;
FMacList := TList.Create;
For I := 0 To ListView1.Items.Count - 1 Do
begin
L := ListView1.Items[I];
If L.Checked Then
begin
Entry := L.Data;
L.Data := Nil;
FMacList.Add(Entry);
end;
end;
Close;
end;
Constructor TForm2.Create(AOwner:TComponent; ANetwork:TWlanNetwork);
begin
FNetwork := ANetwork;
FCancelled := True;
Inherited Create(AOwner);
end;
Procedure TForm2.FormCreate(Sender: TObject);
Var
I : Integer;
List : TList;
Entry : TWlanBssEntry;
begin
List := TList.Create;
If FNetwork.GetBssList(List) Then
begin
For I := 0 To List.Count - 1 Do
begin
Entry := List[I];
With ListView1.Items.Add Do
begin
Data := Entry;
Caption := TWlanBssEntry.MACToSTr(Entry.MacAddress);
SubItems.Add(Entry.SSID);
SubItems.Add(Format('%d %%', [Entry.LinkQuality]));
SubItems.Add(Format('%d MHz', [Entry.Frequency]));
end;
end;
end;
List.Free;
end;
Procedure TForm2.ListView1Deletion(Sender: TObject; Item: TListItem);
begin
If Assigned(Item.Data) Then
begin
TWlanBssEntry(Item.Data).Free;
Item.Data := Nil;
end;
end;
End.
|
{ *************************************************************************** }
{ }
{ Delphi and Kylix Cross-Platform Visual Component Library }
{ }
{ Copyright (c) 2000, 2001 Borland Software Corporation }
{ }
{ *************************************************************************** }
unit QStyle;
{$R-,T-,H+,X+}
interface
uses
QTypes, Classes, Types, Qt, QGraphics;
type
TScrollBarControl = (sbcAddButton, sbcSubButton, sbcAddPage, sbcSubPage,
sbcSlider, sbcNone);
TScrollBarControls = set of TScrollBarControl;
TBeforeDrawButtonEvent = procedure(Sender, Source: TObject; Canvas: TCanvas;
var DefaultDraw: Boolean) of object;
TAfterDrawButtonEvent = procedure(Sender, Source: TObject; Canvas: TCanvas) of object;
TBeforeDrawMenuItemEvent = procedure(Sender, Source: TObject; Canvas: TCanvas;
Highlighted, Enabled: Boolean; const Rect: TRect; Checkable: Boolean;
CheckMaxWidth, LabelWidth: Integer; var DefaultDraw: Boolean) of object;
TAfterDrawMenuItemEvent = procedure(Sender, Source: TObject; Canvas: TCanvas;
Highlighted, Enabled: Boolean; const Rect: TRect; Checkable: Boolean;
CheckMaxWidth, LabelWidth: Integer) of object;
TDrawButtonFrameEvent = procedure(Sender: TObject; Canvas: TCanvas; const Rect: TRect;
Down: Boolean; var DefaultDraw: Boolean) of object;
TDrawFocusRectEvent = procedure(Sender: TObject; Canvas: TCanvas; const Rect: TRect;
AtBorder: Boolean; var DefaultDraw: Boolean) of object;
TDrawHintEvent = procedure(Sender: TObject; Canvas: TCanvas; const Rect: TRect;
var DefaultDraw: Boolean) of object;
TDrawCheckEvent = procedure(Sender: TObject; Canvas: TCanvas; const Rect: TRect;
Checked, Grayed, Down, Enabled: Boolean; var DefaultDraw: Boolean) of object;
TDrawMenuFrameEvent = procedure(Sender: TObject; Canvas: TCanvas; const R: TRect;
LineWidth: Integer; var DefaultDraw: Boolean) of object;
TDrawRadioEvent = procedure(Sender: TObject; Canvas: TCanvas; const Rect: TRect;
Checked, Down, Enabled: Boolean; var DefaultDraw: Boolean) of object;
//only called when QFrame::FrameStyle = StyledPanel
TDrawFrameEvent = procedure(Sender: TObject; Canvas: TCanvas; const Rect: TRect;
Sunken: Boolean; LineWidth: Integer; var DefaultDraw: Boolean) of object;
TDrawMenuCheckEvent = procedure(Sender: TObject; Canvas: TCanvas; const Rect: TRect;
Checked, Enabled: Boolean) of object;
TBeforeDrawItemEvent = procedure(Sender: TObject; Canvas: TCanvas; const Rect: TRect; Flags: Integer;
Enabled: Boolean; Bitmap: TBitmap; const Text: WideString; Length: Integer; Color: TColor;
var DefaultDraw: Boolean) of object;
TAfterDrawItemEvent = procedure(Sender: TObject; Canvas: TCanvas; const Rect: TRect; Flags: Integer;
Enabled: Boolean; Bitmap: TBitmap; const Text: WideString; Length: Integer; Color: TColor) of object;
TDrawComboButtonEvent = procedure(Sender: TObject; Canvas: TCanvas; const Rect: TRect;
Sunken, ReadOnly, Enabled: Boolean; var DefaultDraw: Boolean) of object;
TDrawMaskEvent = procedure(Sender: TObject; Canvas: TCanvas; const Rect: TRect) of object;
TDrawRadioMaskEvent = procedure(Sender: TObject; Canvas: TCanvas; const Rect: TRect; Checked: Boolean) of object;
TGetItemRectEvent = procedure(Sender: TObject; Canvas: TCanvas; var Rect: TRect; Flags: Integer;
Enabled: Boolean; Bitmap: TBitmap; const Text: WideString) of object;
TPolishEvent = procedure(Sender, Source: TObject) of object;
TDrawHeaderSectionEvent = procedure(Sender: TObject; Canvas: TCanvas; const Rect: TRect;
Down: Boolean; var DefaultDraw: Boolean) of object;
TButtonRectEvent = procedure(Sender: TObject; var Rect: TRect) of object;
TDrawArrowEvent = procedure(Sender: TObject; Canvas: TCanvas; const Rect: TRect; Arrow: ArrowType; Down, Enabled: Boolean) of object;
TDrawCheckMaskEvent = procedure(Sender: TObject; Canvas: TCanvas; const Rect: TRect;
Checked, Grayed: Boolean) of object;
TTabMetricsEvent = procedure(Sender, Source: TObject; var HorizonalPadding, VerticalPadding,
Overlap: Integer) of object;
TDrawTabEvent = procedure(Sender, Source: TObject; Canvas: TCanvas; Index, HorizonalPadding,
VerticalPadding, Overlap: Integer; Selected: Boolean) of object;
TScrollBarMetricsEvent = procedure(Sender: TObject; ScrollBar: QScrollBarH; var SliderLength,
ButtonSize: Integer) of object;
TDrawScrollBarEvent = procedure(Sender: TObject; ScrollBar: QScrollBarH; Canvas: TCanvas;
const Rect: TRect; SliderStart, SliderLength, ButtonSize: Integer; Controls: TScrollBarControls;
DownControl: TScrollBarControl; var DefaultDraw: Boolean) of object;
TDrawTrackBarEvent = procedure(Sender: TObject; Canvas: TCanvas; const Rect: TRect; Horizontal,
TickAbove, TickBelow: Boolean; var DefaultDraw: Boolean) of object;
TDrawTrackBarGrooveEvent = procedure(Sender: TObject; Canvas: TCanvas; const Rect: TRect;
Horizontal: Boolean; var DefaultDraw: Boolean) of object;
TDrawSplitterEvent = procedure(Sender: TObject; Canvas: TCanvas; const Rect: TRect;
Vertical: Boolean; var DefaultDraw: Boolean) of object;
TExtraMenuItemWidthEvent = procedure(Sender, Source: TObject; HasCheckmark: Boolean;
ImageWidth: Integer; FontMetrics: QFontMetricsH; var ExtraWidth: Integer) of object;
TSubmenuIndicatorWidthEvent = procedure(Sender: TObject; FontMetrics: QFontMetricsH;
var Width: Integer) of object;
TMenuItemHeightEvent = procedure(Sender, Source: TObject; Checkable: Boolean;
FontMetrics: QFontMetricsH; var Height: Integer) of object;
TDefaultStyle = (dsWindows,
dsMotif,
dsMotifPlus,
dsCDE,
dsQtSGI,
dsPlatinum,
dsSystemDefault);
{ TStyle }
TStyle = class
private
FHandle: QClxStyleH;
FHooks: QClxStyleHooksH;
FOnChange: TNotifyEvent;
FDrawFocusRect: TDrawFocusRectEvent;
FBeforeDrawMenuItem: TBeforeDrawMenuItemEvent;
FAfterDrawMenuItem: TAfterDrawMenuItemEvent;
FDrawMenuFrame: TDrawMenuFrameEvent;
FBeforeDrawButton: TBeforeDrawButtonEvent;
FAfterDrawButton: TAfterDrawButtonEvent;
FDrawButtonFrame: TDrawButtonFrameEvent;
FDrawButtonLabel: TBeforeDrawButtonEvent;
FDrawCheck: TDrawCheckEvent;
FDrawRadio: TDrawRadioEvent;
FDefaultStyle: TDefaultStyle;
FDrawMenuCheck: TDrawMenuCheckEvent;
FAfterDrawItem: TAfterDrawItemEvent;
FBeforeDrawItem: TBeforeDrawItemEvent;
FDrawComboButton: TDrawComboButtonEvent;
FDrawButtonMask: TDrawMaskEvent;
FGetItemRect: TGetItemRectEvent;
FDrawHeaderSection: TDrawHeaderSectionEvent;
FDrawHint: TDrawHintEvent;
FHeaderSectionRect: TButtonRectEvent;
FButtonRect: TButtonRectEvent;
FDrawArrow: TDrawArrowEvent;
FDrawRadioMask: TDrawRadioMaskEvent;
FDrawCheckMask: TDrawCheckMaskEvent;
FComboButtonRect: TButtonRectEvent;
FComboButtonFocusRect: TButtonRectEvent;
FDrawComboButtonMask: TDrawMaskEvent;
FTabMetrics: TTabMetricsEvent;
FDrawTab: TDrawTabEvent;
FDrawTabMask: TDrawTabEvent;
FScrollBarMetrics: TScrollBarMetricsEvent;
FDrawScrollBar: TDrawScrollBarEvent;
FDrawTrackBar: TDrawTrackBarEvent;
FDrawTrackBarMask: TDrawTrackBarEvent;
FDrawTrackBarGroove: TDrawTrackBarGrooveEvent;
FDrawTrackBarGrooveMask: TDrawTrackBarGrooveEvent;
FDrawSplitter: TDrawSplitterEvent;
FExtraMenuItemWidth: TExtraMenuItemWidthEvent;
FSubmenuIndicatorWidth: TSubmenuIndicatorWidthEvent;
FMenuItemHeight: TMenuItemHeightEvent;
FDrawFrame: TDrawFrameEvent;
procedure BevelButtonRectHook(var x, y, w, h: Integer) cdecl;
procedure ButtonRectHook(var x, y, w, h: Integer) cdecl;
procedure ComboButtonRectHook(var x, y, w, h: Integer) cdecl;
procedure ComboButtonFocusRectHook(var x, y, w, h: Integer) cdecl;
procedure DrawArrowHook(p: QPainterH; _type: ArrowType; down: Boolean; x, y, w, h: Integer; g: QColorGroupH; enabled: Boolean; fill: QBrushH) cdecl;
procedure DrawBevelButtonHook(p: QPainterH; x, y, w, h: Integer; g: QColorGroupH; sunken: Boolean; fill: QBrushH; var Stage: Integer) cdecl;
procedure DrawButtonHook(p: QPainterH; x, y, w, h: Integer; g: QColorGroupH; sunken: Boolean; fill: QBrushH; var Stage: Integer) cdecl;
procedure DrawButtonMaskHook(p: QPainterH; x, y, w, h: Integer) cdecl;
procedure DrawCheckHook(p: QPainterH; x, y, w, h: Integer; g: QColorGroupH; State: Integer; Down, Enabled: Boolean; var Stage: Integer) cdecl;
procedure DrawComboButtonHook(p: QPainterH; x, y, w, h: Integer; g: QColorGroupH; sunken, editable, enabled: Boolean; fill: QBrushH; var Stage: Integer); cdecl;
procedure DrawComboButtonMaskHook(p: QPainterH; x, y, w, h: Integer) cdecl;
procedure DrawFocusRectHook(p1: QPainterH; p2: PRect; p3: QColorGroupH; bg: QColorH; p5: Boolean; var Stage: Integer) cdecl;
procedure DrawIndicatorMaskHook(p: QPainterH; x, y, w, h, state: Integer) cdecl;
procedure DrawItemHook(p: QPainterH; x, y, w, h, flags: Integer; g: QColorGroupH; enabled: Boolean; pixmap: QPixmapH; text: PString; len: Integer; penColor: QColorH; var Stage: Integer) cdecl;
procedure DrawMenuCheckHook(p: QPainterH; x, y, w, h: Integer; g: QColorGroupH; act, dis: Boolean) cdecl;
procedure DrawPopupMenuItemHook(p: QPainterH; checkable: Boolean; maxpmw: Integer;
tab: Integer; mi: QMenuItemH; itemID: Integer; act: Boolean; enabled: Boolean;
x: Integer; y: Integer; w: Integer; h: Integer; var Stage: Integer) cdecl;
procedure DrawPopupPanelHook(p: QPainterH; x: Integer; y: Integer; w: Integer; h: Integer; p6: QColorGroupH; lineWidth: Integer; fill: QBrushH; var Stage: Integer) cdecl;
procedure DrawPushButtonHook(btn: QPushButtonH; p: QPainterH; var Stage: Integer) cdecl;
procedure DrawPushButtonLabelHook(btn: QPushButtonH; p: QPainterH; var Stage: Integer) cdecl;
procedure DrawRadioHook(p: QPainterH; x, y, w, h: Integer; g: QColorGroupH; _on, down, enabled: Boolean; var Stage: Integer) cdecl;
procedure DrawRadioMaskHook(p: QPainterH; x, y, w, h: Integer; _on: Boolean) cdecl;
procedure DrawScrollBarHook(p1: QPainterH; p2: QScrollBarH; sliderStart: Integer; controls, activeControl: Integer; var Stage: Integer) cdecl;
procedure DrawSliderHook(p: QPainterH; x, y, w, h: Integer; g: QColorGroupH; p7: Orientation; tickAbove, tickBelow: Boolean; var Stage: Integer) cdecl;
procedure DrawSliderMaskHook(p: QPainterH; x, y, w, h: Integer; p6: Orientation; tickAbove: Boolean; tickBelow: Boolean) cdecl;
procedure DrawSliderGrooveHook(p: QPainterH; x, y, w, h: Integer; g: QColorGroupH; c: QCOORD; p8: Orientation; var Stage: Integer) cdecl;
procedure DrawSliderGrooveMaskHook(p: QPainterH; x, y, w, h: Integer; c: QCOORD; p8: Orientation) cdecl;
procedure DrawSplitterHook(p: QPainterH; x, y, w, h: Integer; g: QColorGroupH; p7: Orientation; var Stage: Integer) cdecl;
procedure DrawTabHook(p1: QPainterH; p2: QTabBarH; index: Integer; selected: Boolean) cdecl;
procedure DrawTabMaskHook(p1: QPainterH; p2: QTabBarH; index: Integer; selected: Boolean) cdecl;
procedure DrawPanelHook(p: QPainterH; x, y, w, h: Integer; p6: QColorGroupH; sunken: Boolean; lineWidth: Integer; fill: QBrushH; var Stage: Integer) cdecl;
procedure ExtraMenuItemWidthHook(checkable: Boolean; maxpmw: Integer; mi: QMenuItemH; fm: QFontMetricsH; var Retval: Integer) cdecl;
procedure ItemRectHook(p: QPainterH; var x, y, w, h: Integer; flags: Integer; enabled: Boolean; pixmap: QPixmapH; text: PString; len: Integer) cdecl;
procedure MenuItemHeightHook(checkable: Boolean; mi: QMenuItemH; fm: QFontMetricsH; var Height: Integer) cdecl;
procedure ScrollBarMetricsHook(p1: QScrollBarH; var sliderMin, sliderMax, sliderLength, buttonDim: Integer) cdecl;
procedure SubmenuIndicatorWidthHook(fm: QFontMetricsH; var Retval: Integer) cdecl;
procedure TabBarMetricsHook(p1: QTabBarH; var hFrame, vFrame, overlap: Integer) cdecl;
function GetButtonShift: TPoint;
function GetCheckSize: TSize;
function GetDefaultFrameWidth: Integer;
function GetHandle: QClxStyleH;
function GetMaxSliderDragDistance: Integer;
function GetRadioSize: TSize;
function GetSliderLength: Integer;
procedure SetAfterDrawButton(const Value: TAfterDrawButtonEvent);
procedure SetAfterDrawItem(const Value: TAfterDrawItemEvent);
procedure SetAfterDrawMenuItem(const Value: TAfterDrawMenuItemEvent);
procedure SetBeforeDrawButton(const Value: TBeforeDrawButtonEvent);
procedure SetBeforeDrawItem(const Value: TBeforeDrawItemEvent);
procedure SetBeforeDrawMenuItem(const Value: TBeforeDrawMenuItemEvent);
procedure SetButtonRect(const Value: TButtonRectEvent);
procedure SetButtonShift(const Value: TPoint);
procedure SetCheckSize(const Value: TSize);
procedure SetComboButtonRect(const Value: TButtonRectEvent);
procedure SetComboButtonFocusRect(const Value: TButtonRectEvent);
procedure SetDefaultFrameWidth(const Value: Integer);
procedure SetDefaultStyle(const Value: TDefaultStyle); virtual;
procedure SetDrawArrow(const Value: TDrawArrowEvent);
procedure SetDrawButtonMask(const Value: TDrawMaskEvent);
procedure SetDrawButtonFrame(const Value: TDrawButtonFrameEvent);
procedure SetDrawButtonLabel(const Value: TBeforeDrawButtonEvent);
procedure SetDrawCheck(const Value: TDrawCheckEvent);
procedure SetDrawCheckMask(const Value: TDrawCheckMaskEvent);
procedure SetDrawComboButton(const Value: TDrawComboButtonEvent);
procedure SetDrawComboButtonMask(const Value: TDrawMaskEvent);
procedure SetDrawFocusRect(const Value: TDrawFocusRectEvent);
procedure SetDrawHint(const Value: TDrawHintEvent);
procedure SetDrawHeaderSection(const Value: TDrawHeaderSectionEvent);
procedure SetDrawMenuCheck(const Value: TDrawMenuCheckEvent);
procedure SetDrawMenuFrame(const Value: TDrawMenuFrameEvent);
procedure SetDrawRadio(const Value: TDrawRadioEvent);
procedure SetDrawRadioMask(const Value: TDrawRadioMaskEvent);
procedure SetDrawScrollBar(const Value: TDrawScrollBarEvent);
procedure SetDrawTrackBar(const Value: TDrawTrackBarEvent);
procedure SetDrawTrackBarMask(const Value: TDrawTrackBarEvent);
procedure SetDrawTrackBarGroove(const Value: TDrawTrackBarGrooveEvent);
procedure SetDrawTrackBarGrooveMask(const Value: TDrawTrackBarGrooveEvent);
procedure SetDrawSplitter(const Value: TDrawSplitterEvent);
procedure SetDrawTab(const Value: TDrawTabEvent);
procedure SetDrawTabMask(const Value: TDrawTabEvent);
procedure SetExtraMenuItemWidth(const Value: TExtraMenuItemWidthEvent);
procedure SetGetItemRect(const Value: TGetItemRectEvent);
procedure SetHeaderSectionRect(const Value: TButtonRectEvent);
procedure SetMaxSliderDragDistance(const Value: Integer);
procedure SetMenuItemHeight(const Value: TMenuItemHeightEvent);
procedure SetRadioSize(const Value: TSize);
procedure SetScrollBarMetrics(const Value: TScrollBarMetricsEvent);
procedure SetSliderLength(const Value: Integer);
procedure SetSubmenuIndicatorWidth(const Value: TSubmenuIndicatorWidthEvent);
procedure SetTabMetrics(const Value: TTabMetricsEvent);
procedure SetDrawFrame(const Value: TDrawFrameEvent);
protected
procedure Changed(Sender: TObject); dynamic;
procedure CreateHandle; virtual;
procedure DoAfterDrawButton(Source: TObject; Canvas: TCanvas); virtual;
procedure DoAfterDrawItem(Canvas: TCanvas; const Rect: TRect; Flags: Integer; Enabled: Boolean;
Bitmap: TBitmap; const Text: WideString; Length: Integer; Color: TColor); virtual;
function DoBeforeDrawButton(Source: TObject; Canvas: TCanvas): Boolean; virtual;
function DoBeforeDrawItem(Canvas: TCanvas; const Rect: TRect; Flags: Integer; Enabled: Boolean;
Bitmap: TBitmap; const Text: WideString; Length: Integer; Color: TColor): Boolean; virtual;
procedure DoButtonRect(var Rect: TRect); virtual;
procedure DoComboButtonRect(var Rect: TRect); virtual;
procedure DoComboButtonFocusRect(var Rect: TRect); virtual;
procedure DoDrawArrow(Canvas: TCanvas; const Rect: TRect; Arrow: ArrowType; Down, Enabled: Boolean); virtual;
function DoDrawButtonFrame(Canvas: TCanvas; const Rect: TRect; Down: Boolean): Boolean; virtual;
function DoDrawButtonLabel(Source: TObject; Canvas: TCanvas): Boolean; virtual;
procedure DoDrawButtonMask(Canvas: TCanvas; const Rect: TRect); virtual;
function DoDrawCheck(Canvas: TCanvas; const Rect: TRect; Checked, Grayed, Down, Enabled: Boolean): Boolean; virtual;
procedure DoDrawCheckMask(Canvas: TCanvas; const Rect: TRect; Checked, Grayed: Boolean); virtual;
function DoDrawComboButton(Canvas: TCanvas; const Rect: TRect; Sunken, ReadOnly,
Enabled: Boolean): Boolean; virtual;
procedure DoDrawComboButtonMask(Canvas: TCanvas; const Rect: TRect); virtual;
function DoDrawFocusRect(Canvas: TCanvas; const Rect: TRect; AtBorder: Boolean): Boolean; virtual;
function DoDrawHeaderSection(Canvas: TCanvas; const Rect: TRect; Down: Boolean): Boolean; virtual;
function DoDrawMenuFrame(Canvas: TCanvas; const R: TRect; LineWidth: Integer): Boolean; virtual;
procedure DoDrawMenuItem(Source: TObject; Canvas: TCanvas; Highlighted, Enabled: Boolean;
const Rect: TRect; Checkable: Boolean; CheckMaxWidth, LabelWidth: Integer; var Stage: Integer); virtual;
procedure DoDrawMenuCheck(Canvas: TCanvas; const Rect: TRect; Highlighted, Enabled: Boolean); virtual;
procedure DoDrawRadioMask(Canvas: TCanvas; const Rect: TRect; Checked: Boolean); virtual;
function DoDrawRadio(Canvas: TCanvas; const Rect: TRect; Checked, Down, Enabled: Boolean): Boolean; virtual;
function DoDrawScrollBar(ScrollBar: QScrollBarH; Canvas: TCanvas;
const Rect: TRect; SliderStart, SliderLength, ButtonSize: Integer; Controls: TScrollBarControls;
DownControl: TScrollBarControl): Boolean; virtual;
function DoDrawTrackBar(Canvas: TCanvas; const Rect: TRect; Horizontal, TickAbove,
TickBelow: Boolean): Boolean; virtual;
function DoDrawTrackBarMask(Canvas: TCanvas; const Rect: TRect; Horizontal, TickAbove,
TickBelow: Boolean): Boolean; virtual;
function DoDrawTrackBarGroove(Canvas: TCanvas; const Rect: TRect; Horizontal: Boolean): Boolean; virtual;
function DoDrawTrackBarGrooveMask(Canvas: TCanvas; const Rect: TRect; Horizontal: Boolean): Boolean; virtual;
function DoDrawSplitter(Canvas: TCanvas; const Rect: TRect; Vertical: Boolean): Boolean; virtual;
procedure DoDrawTab(Source: TObject; Canvas: TCanvas; Index, HorizontalPadding,
VerticalPadding, Overlap: Integer; Selected: Boolean); virtual;
procedure DoDrawTabMask(Source: TObject; Canvas: TCanvas; Index, HorizontalPadding,
VerticalPadding, Overlap: Integer; Selected: Boolean); virtual;
procedure DoExtraMenuItemWidth(Source: TObject; HasCheckmark: Boolean;
ImageWidth: Integer; FontMetrics: QFontMetricsH; var ExtraWidth: Integer); virtual;
procedure DoGetItemRect(Canvas: TCanvas; var Rect: TRect; Flags: Integer; Enabled: Boolean;
Bitmap: TBitmap; const Text: WideString);
function DoDrawFrame(Canvas: TCanvas; const Rect: TRect; Sunken: Boolean;
LineWidth: Integer): Boolean; virtual;
procedure DoHeaderSectionRect(var Rect: TRect); virtual;
procedure DoMenuItemHeight(Source: TObject; Checkable: Boolean; FontMetrics: QFontMetricsH;
var Height: Integer); virtual;
procedure DoScrollBarMetrics(ScrollBar: QScrollBarH; var SliderMin, SliderMax,
SliderLength, ButtonSize: Integer); virtual;
procedure DoSubmenuIndicatorWidth(FontMetrics: QFontMetricsH; var Width: Integer); virtual;
procedure DoTabMetrics(Source: TObject; var HorizontalPadding, VerticalPadding,
Overlap: Integer); virtual;
procedure StyleDestroyedHook; cdecl;
procedure StyleDestroyed; virtual;
public
constructor Create; virtual;
procedure HandleNeeded;
procedure Refresh;
function GetHooks: QClxStyleHooksH;
property ButtonShift: TPoint read GetButtonShift write SetButtonShift;
property CheckSize: TSize read GetCheckSize write SetCheckSize;
property DefaultStyle: TDefaultStyle read FDefaultStyle write SetDefaultStyle;
property Handle: QClxStyleH read GetHandle;
property Hooks: QClxStyleHooksH read GetHooks;
property MaxSliderDragDistance: Integer read GetMaxSliderDragDistance
write SetMaxSliderDragDistance;
property RadioSize: TSize read GetRadioSize write SetRadioSize;
property SliderLength: Integer read GetSliderLength write SetSliderLength;
//Events
property AfterDrawButton: TAfterDrawButtonEvent read FAfterDrawButton
write SetAfterDrawButton;
property AfterDrawItem: TAfterDrawItemEvent read FAfterDrawItem
write SetAfterDrawItem;
property AfterDrawMenuItem: TAfterDrawMenuItemEvent read FAfterDrawMenuItem
write SetAfterDrawMenuItem;
property BeforeDrawButton: TBeforeDrawButtonEvent read FBeforeDrawButton
write SetBeforeDrawButton;
property BeforeDrawItem: TBeforeDrawItemEvent read FBeforeDrawItem
write SetBeforeDrawItem;
property BeforeDrawMenuItem: TBeforeDrawMenuItemEvent read FBeforeDrawMenuItem
write SetBeforeDrawMenuItem;
property ButtonRect: TButtonRectEvent read FButtonRect write SetButtonRect;
property ComboButtonRect: TButtonRectEvent read FComboButtonRect
write SetComboButtonRect;
property ComboButtonFocusRect: TButtonRectEvent read FComboButtonFocusRect
write SetComboButtonFocusRect;
property DefaultFrameWidth: Integer read GetDefaultFrameWidth write
SetDefaultFrameWidth;
property DrawHint: TDrawHintEvent read FDrawHint write SetDrawHint;
property DrawArrow: TDrawArrowEvent read FDrawArrow write SetDrawArrow;
property DrawButtonLabel: TBeforeDrawButtonEvent read FDrawButtonLabel
write SetDrawButtonLabel;
property DrawButtonFrame: TDrawButtonFrameEvent read FDrawButtonFrame
write SetDrawButtonFrame;
property DrawButtonMask: TDrawMaskEvent read FDrawButtonMask
write SetDrawButtonMask;
property DrawCheck: TDrawCheckEvent read FDrawCheck write SetDrawCheck;
property DrawCheckMask: TDrawCheckMaskEvent read FDrawCheckMask write SetDrawCheckMask;
property DrawComboButton: TDrawComboButtonEvent read FDrawComboButton
write SetDrawComboButton;
property DrawComboButtonMask: TDrawMaskEvent read FDrawComboButtonMask
write SetDrawComboButtonMask;
property DrawFocusRect: TDrawFocusRectEvent read FDrawFocusRect write SetDrawFocusRect;
property DrawHeaderSection: TDrawHeaderSectionEvent read FDrawHeaderSection
write SetDrawHeaderSection;
property DrawMenuCheck: TDrawMenuCheckEvent read FDrawMenuCheck write SetDrawMenuCheck;
property DrawMenuFrame: TDrawMenuFrameEvent read FDrawMenuFrame write SetDrawMenuFrame;
property DrawRadio: TDrawRadioEvent read FDrawRadio write SetDrawRadio;
property DrawRadioMask: TDrawRadioMaskEvent read FDrawRadioMask write SetDrawRadioMask;
property DrawScrollBar: TDrawScrollBarEvent read FDrawScrollBar
write SetDrawScrollBar;
property DrawTrackBar: TDrawTrackBarEvent read FDrawTrackBar write SetDrawTrackBar;
property DrawTrackBarMask: TDrawTrackBarEvent read FDrawTrackBarMask write SetDrawTrackBarMask;
property DrawTrackBarGroove: TDrawTrackBarGrooveEvent read FDrawTrackBarGroove
write SetDrawTrackBarGroove;
property DrawTrackBarGrooveMask: TDrawTrackBarGrooveEvent read FDrawTrackBarGrooveMask
write SetDrawTrackBarGrooveMask;
property DrawSplitter: TDrawSplitterEvent read FDrawSplitter write SetDrawSplitter;
property DrawTab: TDrawTabEvent read FDrawTab write SetDrawTab;
property DrawTabMask: TDrawTabEvent read FDrawTabMask write SetDrawTabMask;
property ExtraMenuItemWidth: TExtraMenuItemWidthEvent
read FExtraMenuItemWidth write SetExtraMenuItemWidth;
property GetItemRect: TGetItemRectEvent read FGetItemRect write SetGetItemRect;
property DrawFrame: TDrawFrameEvent read FDrawFrame write SetDrawFrame;
property HeaderSectionRect: TButtonRectEvent read FHeaderSectionRect
write SetHeaderSectionRect;
property MenuItemHeight: TMenuItemHeightEvent read FMenuItemHeight
write SetMenuItemHeight;
property OnChange: TNotifyEvent read FOnChange write FOnChange;
property ScrollBarMetrics: TScrollBarMetricsEvent read FScrollBarMetrics
write SetScrollBarMetrics;
property SubmenuIndicatorWidth: TSubmenuIndicatorWidthEvent read FSubmenuIndicatorWidth
write SetSubmenuIndicatorWidth;
property TabMetrics: TTabMetricsEvent read FTabMetrics write SetTabMetrics;
end;
TApplicationStyle = class(TStyle)
private
FRecreating: Boolean;
FOnPolish: TPolishEvent;
procedure PolishHook(p1: QApplicationH) cdecl;
procedure SetOnPolish(const Value: TPolishEvent);
protected
procedure DoPolish(Source: TObject); virtual;
procedure CreateHandle; override;
procedure SetDefaultStyle(const Value: TDefaultStyle); override;
procedure StyleDestroyed; override;
public
destructor Destroy; override;
property OnPolish: TPolishEvent read FOnPolish write SetOnPolish;
end;
TWidgetStyle = class(TStyle)
private
FOnPolish: TPolishEvent;
procedure PolishHook(p1: QWidgetH) cdecl;
procedure SetOnPolish(const Value: TPolishEvent);
protected
procedure DoPolish(Source: TObject); virtual;
procedure SetDefaultStyle(const Value: TDefaultStyle); override;
public
property OnPolish: TPolishEvent read FOnPolish write SetOnPolish;
end;
const
cStyles: array [TDefaultStyle] of string = ('Windows 95', { do not localize }
'Motif', { do not localize }
'MotifPlus', { do not localize }
'CDE', { do not localize }
'Qt SGI', { do not localize }
'Platinum', { do not localize }
''); { do not localize }
implementation
{$IFDEF LINUX}
uses
SysUtils, QControls, QForms, IniFiles, Libc;
{$ENDIF}
{$IFDEF MSWINDOWS}
uses
SysUtils, QControls, QForms, IniFiles;
{$ENDIF}
type
QClxStyle_polish_Event = procedure (p1: QWidgetH) of object cdecl;
QClxStyle_unPolish_Event = procedure (p1: QWidgetH) of object cdecl;
QClxStyle_polish2_Event = procedure (p1: QApplicationH) of object cdecl;
QClxStyle_unPolish2_Event = procedure (p1: QApplicationH) of object cdecl;
QClxStyle_polish3_Event = procedure (p1: QPaletteH) of object cdecl;
QClxStyle_itemRect_Event = procedure (p: QPainterH; var x: Integer; var y: Integer; var w: Integer; var h: Integer; flags: Integer; enabled: Boolean; pixmap: QPixmapH; text: PString; len: Integer) of object cdecl;
QClxStyle_drawItem_Event = procedure (p: QPainterH; x: Integer; y: Integer; w: Integer; h: Integer; flags: Integer; g: QColorGroupH; enabled: Boolean; pixmap: QPixmapH; text: PString; len: Integer; penColor: QColorH; var Stage: Integer) of object cdecl;
QClxStyle_drawSeparator_Event = procedure (p: QPainterH; x1: Integer; y1: Integer; x2: Integer; y2: Integer; g: QColorGroupH; sunken: Boolean; lineWidth: Integer; midLineWidth: Integer; var Stage: Integer) of object cdecl;
QClxStyle_drawRect_Event = procedure (p: QPainterH; x: Integer; y: Integer; w: Integer; h: Integer; p6: QColorH; lineWidth: Integer; fill: QBrushH) of object cdecl;
QClxStyle_drawRectStrong_Event = procedure (p: QPainterH; x: Integer; y: Integer; w: Integer; h: Integer; p6: QColorGroupH; sunken: Boolean; lineWidth: Integer; midLineWidth: Integer; fill: QBrushH) of object cdecl;
QClxStyle_drawButton_Event = procedure (p: QPainterH; x: Integer; y: Integer; w: Integer; h: Integer; g: QColorGroupH; sunken: Boolean; fill: QBrushH; var Stage: Integer) of object cdecl;
QClxStyle_buttonRect_Event = procedure(var x: Integer; var y: Integer; var w: Integer; var h: Integer) of object cdecl;
QClxStyle_drawButtonMask_Event = procedure (p: QPainterH; x: Integer; y: Integer; w: Integer; h: Integer) of object cdecl;
QClxStyle_drawBevelButton_Event = procedure (p: QPainterH; x: Integer; y: Integer; w: Integer; h: Integer; g: QColorGroupH; sunken: Boolean; fill: QBrushH; var Stage: Integer) of object cdecl;
QClxStyle_bevelButtonRect_Event = procedure (var x: Integer; var y: Integer; var w: Integer; var h: Integer) of object cdecl;
QClxStyle_drawToolButton_Event = procedure (p: QPainterH; x: Integer; y: Integer; w: Integer; h: Integer; g: QColorGroupH; sunken: Boolean; fill: QBrushH) of object cdecl;
QClxStyle_drawToolButton2_Event = procedure (btn: QToolButtonH; p: QPainterH) of object cdecl;
QClxStyle_toolButtonRect_Event = function (x: Integer; y: Integer; w: Integer; h: Integer): PRect of object cdecl;
QClxStyle_drawPanel_Event = procedure (p: QPainterH; x: Integer; y: Integer; w: Integer; h: Integer; p6: QColorGroupH; sunken: Boolean; lineWidth: Integer; fill: QBrushH; var Stage: Integer) of object cdecl;
QClxStyle_drawPopupPanel_Event = procedure (p: QPainterH; x: Integer; y: Integer; w: Integer; h: Integer; p6: QColorGroupH; lineWidth: Integer; fill: QBrushH; var Stage: Integer) of object cdecl;
QClxStyle_drawArrow_Event = procedure (p: QPainterH; _type: ArrowType; down: Boolean; x: Integer; y: Integer; w: Integer; h: Integer; g: QColorGroupH; enabled: Boolean; fill: QBrushH) of object cdecl;
QClxStyle_exclusiveIndicatorSize_Event = function(): QSizeH of object cdecl;
QClxStyle_drawExclusiveIndicator_Event = procedure (p: QPainterH; x: Integer; y: Integer; w: Integer; h: Integer; g: QColorGroupH; _on, down, enabled: Boolean; var Stage: Integer) of object cdecl;
QClxStyle_drawExclusiveIndicatorMask_Event = procedure (p: QPainterH; x: Integer; y: Integer; w: Integer; h: Integer; on: Boolean) of object cdecl;
QClxStyle_drawIndicatorMask_Event = procedure (p: QPainterH; x, y, w, h, state: Integer) of object cdecl;
QClxStyle_indicatorSize_Event = function (): QSizeH of object cdecl;
QClxStyle_drawIndicator_Event = procedure (p: QPainterH; x: Integer; y: Integer; w: Integer; h: Integer; g: QColorGroupH; state: Integer; down: Boolean; enabled: Boolean; var Stage: Integer) of object cdecl;
QClxStyle_drawFocusRect_Event = procedure (p1: QPainterH; p2: PRect; p3: QColorGroupH; bg: QColorH; p5: Boolean; var Stage: Integer) of object cdecl;
QClxStyle_drawComboButton_Event = procedure (p: QPainterH; x: Integer; y: Integer; w: Integer; h: Integer; g: QColorGroupH; sunken: Boolean; editable: Boolean; enabled: Boolean; fill: QBrushH; var Stage: Integer) of object cdecl;
QClxStyle_comboButtonRect_Event = procedure(var x: Integer; var y: Integer; var w: Integer; var h: Integer) of object cdecl;
QClxStyle_comboButtonFocusRect_Event = procedure(var x: Integer; var y: Integer; var w: Integer; var h: Integer) of object cdecl;
QClxStyle_drawComboButtonMask_Event = procedure (p: QPainterH; x: Integer; y: Integer; w: Integer; h: Integer) of object cdecl;
QClxStyle_drawPushButton_Event = procedure (btn: QPushButtonH; p: QPainterH; var Stage: Integer) of object cdecl;
QClxStyle_drawPushButtonLabel_Event = procedure (btn: QPushButtonH; p: QPainterH; var Stage: Integer) of object cdecl;
QClxStyle_pushButtonContentsRect_Event = function (btn: QPushButtonH): PRect of object cdecl;
QClxStyle_menuButtonIndicatorWidth_Event = function (h: Integer): Integer of object cdecl;
QClxStyle_getButtonShift_Event = procedure (x: PInteger; y: PInteger) of object cdecl;
QClxStyle_defaultFrameWidth_Event = function (): Integer of object cdecl;
QClxStyle_tabbarMetrics_Event = procedure (p1: QTabBarH; var p2, p3, p4: Integer) of object cdecl;
QClxStyle_drawTab_Event = procedure (p1: QPainterH; p2: QTabBarH; index: Integer; selected: Boolean) of object cdecl;
QClxStyle_drawTabMask_Event = procedure (p1: QPainterH; p2: QTabBarH; index: Integer; selected: Boolean) of object cdecl;
QClxStyle_scrollBarMetrics_Event = procedure (p1: QScrollBarH; var sliderMin, sliderMax, sliderLength, buttonDim: Integer) of object cdecl;
QClxStyle_drawScrollBarControls_Event = procedure (p1: QPainterH; p2: QScrollBarH; sliderStart: Integer; controls, activeControl: Integer; var Stage: Integer) of object cdecl;
QClxStyle_sliderLength_Event = function (): Integer of object cdecl;
QClxStyle_drawSlider_Event = procedure (p: QPainterH; x: Integer; y: Integer; w: Integer; h: Integer; g: QColorGroupH; p7: Orientation; tickAbove: Boolean; tickBelow: Boolean; var Stage: Integer) of object cdecl;
QClxStyle_drawSliderMask_Event = procedure (p: QPainterH; x: Integer; y: Integer; w: Integer; h: Integer; p6: Orientation; tickAbove: Boolean; tickBelow: Boolean) of object cdecl;
QClxStyle_drawSliderGroove_Event = procedure (p: QPainterH; x: Integer; y: Integer; w: Integer; h: Integer; g: QColorGroupH; c: QCOORD; p8: Orientation; var Stage: Integer) of object cdecl;
QClxStyle_drawSliderGrooveMask_Event = procedure (p: QPainterH; x: Integer; y: Integer; w: Integer; h: Integer; c: QCOORD; p7: Orientation) of object cdecl;
QClxStyle_maximumSliderDragDistance_Event = function (): Integer of object cdecl;
QClxStyle_splitterWidth_Event = function (): Integer of object cdecl;
QClxStyle_drawSplitter_Event = procedure (p: QPainterH; x: Integer; y: Integer; w: Integer; h: Integer; g: QColorGroupH; p7: Orientation; var Stage: Integer) of object cdecl;
QClxStyle_drawCheckMark_Event = procedure (p: QPainterH; x: Integer; y: Integer; w: Integer; h: Integer; g: QColorGroupH; act: Boolean; dis: Boolean) of object cdecl;
QClxStyle_polishPopupMenu_Event = procedure (p1: QPopupMenuH) of object cdecl;
QClxStyle_extraPopupMenuItemWidth_Event = procedure (checkable: Boolean; maxpmw: Integer; mi: QMenuItemH; fm: QFontMetricsH; var Retval: Integer) of object cdecl;
QClxStyle_popupSubmenuIndicatorWidth_Event = procedure(fm: QFontMetricsH; var Retval: Integer) of object cdecl;
QClxStyle_popupMenuItemHeight_Event = procedure(checkable: Boolean; mi: QMenuItemH; fm: QFontMetricsH; var Height: Integer) of object cdecl;
QClxStyle_drawPopupMenuItem_Event = procedure (p: QPainterH; checkable: Boolean; maxpmw: Integer; tab: Integer; mi: QMenuItemH; itemID: Integer; act: Boolean; enabled: Boolean; x: Integer; y: Integer; w: Integer; h: Integer; var Stage: Integer) of object cdecl;
QClxStyle_scrollBarExtent_Event = function (): QSizeH of object cdecl;
QClxStyle_buttonDefaultIndicatorWidth_Event = function (): Integer of object cdecl;
QClxStyle_toolBarHandleExtend_Event = function (): Integer of object cdecl;
QClxStyle_drawToolBarHandle_Event = procedure (p: QPainterH; r: PRect; orientation: Orientation; highlight: Boolean; cg: QColorGroupH; drawBorder: Boolean) of object cdecl;
QClxStyle_StyleDestroyed_Event = procedure of object cdecl;
{$IFDEF LINUX}
type
TKAppResetStyle = procedure cdecl;
var
AppResetStyle: TKAppResetStyle = nil;
{$ENDIF}
{ TStyle }
function TStyle.GetHandle: QClxStyleH;
begin
HandleNeeded;
Result := FHandle;
end;
function TStyle.GetHooks: QClxStyleHooksH;
begin
HandleNeeded;
Result := FHooks;
end;
procedure TStyle.HandleNeeded;
begin
if FHandle = nil then
CreateHandle;
end;
procedure TStyle.CreateHandle;
var
Temp: WideString;
Method: TMethod;
begin
if FDefaultStyle = dsSystemDefault then
FHandle := Application.Style.Handle
else
begin
Temp := cStyles[FDefaultStyle];
FHooks := QClxStyleHooks_create;
FHandle := QClxStyle_create(@Temp, FHooks);
QClxStyle_StyleDestroyed_Event(Method) := StyleDestroyedHook;
QClxStyleHooks_hook_StyleDestroyed(FHooks, Method);
end;
end;
procedure TStyle.StyleDestroyedHook;
begin
try
StyleDestroyed;
except
Application.HandleException(Self);
end;
end;
procedure TStyle.StyleDestroyed;
begin
if Assigned(FHooks) then
QClxStyleHooks_hook_StyleDestroyed(FHooks, NullHook);
FHandle := nil;
FHooks := nil;
end;
procedure TStyle.DrawFocusRectHook(p1: QPainterH; p2: PRect;
p3: QColorGroupH; bg: QColorH; p5: Boolean; var Stage: Integer);
var
Canvas: TCanvas;
begin
try
Canvas := TCanvas.Create;
try
Canvas.Handle := p1;
Canvas.Start(False);
if DoDrawFocusRect(Canvas, p2^, p5) then
Stage := DrawStage_DefaultDraw;
Canvas.Stop;
finally
Canvas.Free;
end;
except
Application.HandleException(Self);
end;
end;
function TStyle.DoDrawFocusRect(Canvas: TCanvas; const Rect: TRect;
AtBorder: Boolean): Boolean;
begin
Result := True;
if Assigned(FDrawFocusRect) then
FDrawFocusRect(Self, Canvas, Rect, AtBorder, Result);
end;
procedure TStyle.Refresh;
begin
QClxStyle_refresh(Handle);
QPixmapCache_clear;
end;
procedure TStyle.SetDrawFocusRect(const Value: TDrawFocusRectEvent);
var
Method: TMethod;
begin
FDrawFocusRect := Value;
if Assigned(FDrawFocusRect) then
QClxStyle_drawFocusRect_Event(Method) := DrawFocusRectHook
else
Method := NullHook;
QClxStyleHooks_hook_drawFocusRect(Hooks, Method);
Refresh;
end;
procedure TStyle.SetDrawHint(const Value: TDrawHintEvent);
begin
FDrawHint := Value;
Refresh;
end;
procedure TStyle.DoAfterDrawButton(Source: TObject; Canvas: TCanvas);
begin
if Assigned(FAfterDrawButton) then
FAfterDrawButton(Self, Source, Canvas);
end;
function TStyle.DoBeforeDrawButton(Source: TObject; Canvas: TCanvas): Boolean;
begin
Result := True;
if Assigned(FBeforeDrawButton) then
FBeforeDrawButton(Self, Source, Canvas, Result);
end;
procedure TStyle.DoDrawMenuItem(Source: TObject; Canvas: TCanvas;
Highlighted, Enabled: Boolean; const Rect: TRect; Checkable: Boolean;
CheckMaxWidth, LabelWidth: Integer; var Stage: Integer);
var
DefaultDraw: Boolean;
begin
DefaultDraw := True;
case Stage of
DrawStage_Pre:
begin
if Assigned(FBeforeDrawMenuItem) then FBeforeDrawMenuItem(Self, Source, Canvas,
Highlighted, Enabled, Rect, Checkable, CheckMaxWidth, LabelWidth, DefaultDraw);
if DefaultDraw then Stage := DrawStage_DefaultDraw;
end;
DrawStage_Post:
if Assigned(FAfterDrawMenuItem) then FAfterDrawMenuItem(Self, Source, Canvas,
Highlighted, Enabled, Rect, Checkable, CheckMaxWidth, LabelWidth);
end;
end;
function TStyle.DoDrawButtonLabel(Source: TObject; Canvas: TCanvas): Boolean;
begin
Result := True;
if Assigned(FDrawButtonLabel) then
FDrawButtonLabel(Self, Source, Canvas, Result);
end;
procedure TStyle.DrawPopupMenuItemHook(p: QPainterH;
checkable: Boolean; maxpmw, tab: Integer; mi: QMenuItemH; itemID: Integer;
act, enabled: Boolean; x, y, w, h: Integer; var Stage: Integer);
var
Canvas: TCanvas;
R: TRect;
Source: TObject;
begin
try
Canvas := TCanvas.Create;
try
Canvas.Handle := p;
R := Rect(x, y, x+w, y+h);
Canvas.Start(False);
Source := FindObject(QObjectH(mi));
if Source <> nil then
DoDrawMenuItem(Source, Canvas, act, enabled, R, checkable, maxpmw, tab, Stage);
Canvas.Stop;
finally
Canvas.Free;
end;
except
Application.HandleException(Self);
end;
end;
procedure TStyle.DrawPushButtonHook(btn: QPushButtonH; p: QPainterH; var Stage: Integer);
var
Canvas: TCanvas;
Source: TObject;
begin
try
Source := FindControl(btn);
Canvas := TCanvas.Create;
try
Canvas.Handle := p;
Canvas.Start(False);
case Stage of
DrawStage_Pre:
if DoBeforeDrawButton(Source, Canvas) then
Stage := DrawStage_DefaultDraw;
DrawStage_Post:
DoAfterDrawButton(Source, Canvas);
end;
Canvas.Stop;
finally
Canvas.Free;
end;
except
Application.HandleException(Self);
end;
end;
procedure TStyle.DrawPushButtonLabelHook(btn: QPushButtonH;
p: QPainterH; var Stage: Integer);
var
Canvas: TCanvas;
Source: TObject;
begin
try
Source := FindControl(btn);
Canvas := TCanvas.Create;
try
Canvas.Handle := p;
Canvas.Start(False);
if DoDrawButtonLabel(Source, Canvas) then
Stage := DrawStage_DefaultDraw;
Canvas.Stop;
finally
Canvas.Free;
end;
except
Application.HandleException(Self);
end;
end;
procedure TStyle.SetAfterDrawButton(const Value: TAfterDrawButtonEvent);
var
Method: TMethod;
begin
FAfterDrawButton := Value;
if Assigned(FBeforeDrawButton) then
Exit;
if Assigned(FAfterDrawButton) then
QClxStyle_drawPushButton_Event(Method) := DrawPushButtonHook
else
Method := NullHook;
QClxStyleHooks_hook_drawPushButton(Hooks, Method);
Refresh;
end;
procedure TStyle.SetBeforeDrawButton(const Value: TBeforeDrawButtonEvent);
var
Method: TMethod;
begin
FBeforeDrawButton := Value;
if Assigned(FAfterDrawButton) then
Exit;
if Assigned(FBeforeDrawButton) then
QClxStyle_drawPushButton_Event(Method) := DrawPushButtonHook
else
Method := NullHook;
QClxStyleHooks_hook_drawPushButton(Hooks, Method);
Refresh;
end;
procedure TStyle.SetAfterDrawMenuItem(const Value: TAfterDrawMenuItemEvent);
var
Method: TMethod;
begin
FAfterDrawMenuItem := Value;
if Assigned(FBeforeDrawMenuItem) then
Exit;
if Assigned(FAfterDrawMenuItem) then
QClxStyle_drawPopupMenuItem_Event(Method) := DrawPopupMenuItemHook
else
Method := NullHook;
QClxStyleHooks_hook_drawPopupMenuItem(Hooks, Method);
Refresh;
end;
procedure TStyle.SetBeforeDrawMenuItem(const Value: TBeforeDrawMenuItemEvent);
var
Method: TMethod;
begin
FBeforeDrawMenuItem := Value;
if Assigned(FAfterDrawMenuItem) then
Exit;
if Assigned(FBeforeDrawMenuItem) then
QClxStyle_drawPopupMenuItem_Event(Method) := DrawPopupMenuItemHook
else
Method := NullHook;
QClxStyleHooks_hook_drawPopupMenuItem(Hooks, Method);
Refresh;
end;
procedure TStyle.SetDrawButtonLabel(const Value: TBeforeDrawButtonEvent);
var
Method: TMethod;
begin
FDrawButtonLabel := Value;
if Assigned(FDrawButtonLabel) then
QClxStyle_drawPushButtonLabel_Event(Method) := DrawPushButtonLabelHook
else
Method := NullHook;
QClxStyleHooks_hook_drawPushButtonLabel(Hooks, Method);
Refresh;
end;
procedure TStyle.DrawPopupPanelHook(p: QPainterH; x, y, w,
h: Integer; p6: QColorGroupH; lineWidth: Integer; fill: QBrushH; var Stage: Integer);
var
Canvas: TCanvas;
R: TRect;
begin
try
Canvas := TCanvas.Create;
try
R := Rect(x, y, x+w, y+h);
Canvas.Handle := p;
Canvas.Start(False);
if DoDrawMenuFrame(Canvas, R, LineWidth) then
Stage := DrawStage_DefaultDraw;
Canvas.Stop;
finally
Canvas.Free;
end;
except
Application.HandleException(Self);
end;
end;
function TStyle.DoDrawMenuFrame(Canvas: TCanvas; const R: TRect;
LineWidth: Integer): Boolean;
begin
Result := True;
if Assigned(FDrawMenuFrame) then
FDrawMenuFrame(Self, Canvas, R, LineWidth, Result);
end;
procedure TStyle.SetDrawMenuFrame(const Value: TDrawMenuFrameEvent);
var
Method: TMethod;
begin
FDrawMenuFrame := Value;
if Assigned(FDrawMenuFrame) then
QClxStyle_drawPopupPanel_Event(Method) := DrawPopupPanelHook
else
Method := NullHook;
QClxStyleHooks_hook_drawPopupPanel(Hooks, Method);
Refresh;
end;
procedure TStyle.DrawButtonHook(p: QPainterH; x, y, w, h: Integer;
g: QColorGroupH; sunken: Boolean; fill: QBrushH;
var Stage: Integer);
var
Canvas: TCanvas;
begin
try
Canvas := TCanvas.Create;
try
Canvas.Handle := p;
Canvas.Start(False);
if DoDrawButtonFrame(Canvas, Rect(x, y, x+w, y+h), sunken) then
Stage := DrawStage_DefaultDraw;
Canvas.Stop;
finally
Canvas.Free;
end;
except
Application.HandleException(Self);
end;
end;
function TStyle.DoDrawButtonFrame(Canvas: TCanvas; const Rect: TRect;
Down: Boolean): Boolean;
begin
Result := True;
if Assigned(FDrawButtonFrame) then
FDrawButtonFrame(Self, Canvas, Rect, Down, Result);
end;
procedure TStyle.SetDrawButtonFrame(const Value: TDrawButtonFrameEvent);
var
Method: TMethod;
begin
FDrawButtonFrame := Value;
if Assigned(FDrawButtonFrame) then
QClxStyle_drawButton_Event(Method) := DrawButtonHook
else
Method := NullHook;
QClxStyleHooks_hook_drawButton(Hooks, Method);
Refresh;
end;
constructor TStyle.Create;
begin
inherited Create;
FDefaultStyle := dsSystemDefault;
end;
procedure TStyle.DoGetItemRect(Canvas: TCanvas; var Rect: TRect; Flags: Integer;
Enabled: Boolean; Bitmap: TBitmap; const Text: WideString);
begin
if Assigned(FGetItemRect) then
FGetItemRect(Self, Canvas, Rect, Flags, Enabled, Bitmap, Text);
end;
procedure TStyle.ItemRectHook(p: QPainterH; var x, y, w, h: Integer; flags: Integer;
enabled: Boolean; pixmap: QPixmapH; text: PString; len: Integer);
var
Canvas: TCanvas;
R: TRect;
Bitmap: TBitmap;
begin
try
Canvas := TCanvas.Create;
try
Bitmap := TBitmap.Create;
try
R := Rect(x, y, x+w, y+h);
Canvas.Handle := p;
Bitmap.Handle := pixmap;
Canvas.Start(False);
DoGetItemRect(Canvas, R, flags, enabled, Bitmap, text^);
Canvas.Stop;
x := R.Top;
y := R.Left;
w := R.Right - R.Left;
h := R.Bottom - R.Top;
finally
Bitmap.Free;
end;
finally
Canvas.Free;
end;
except
Application.HandleException(Self);
end;
end;
procedure TStyle.SetGetItemRect(const Value: TGetItemRectEvent);
var
Method: TMethod;
begin
FGetItemRect := Value;
if Assigned(FGetItemRect) then
QClxStyle_itemRect_Event(Method) := ItemRectHook
else
Method := NullHook;
QClxStyleHooks_hook_itemRect(Hooks, Method);
end;
function TStyle.DoDrawHeaderSection(Canvas: TCanvas; const Rect: TRect;
Down: Boolean): Boolean;
begin
Result := True;
if Assigned(FDrawHeaderSection) then
FDrawHeaderSection(Self, Canvas, Rect, Down, Result);
end;
procedure TStyle.DrawBevelButtonHook(p: QPainterH; x, y, w, h: Integer;
g: QColorGroupH; sunken: Boolean; fill: QBrushH; var Stage: Integer);
var
Canvas: TCanvas;
R: TRect;
begin
try
Canvas := TCanvas.Create;
try
R := Rect(x, y, x+w, y+h);
Canvas.Handle := p;
Canvas.Start(False);
if DoDrawHeaderSection(Canvas, R, sunken) then
Stage := DrawStage_DefaultDraw;
Canvas.Stop;
finally
Canvas.Free;
end;
except
Application.HandleException(Self);
end;
end;
procedure TStyle.SetDrawHeaderSection(const Value: TDrawHeaderSectionEvent);
var
Method: TMethod;
begin
FDrawHeaderSection := Value;
if Assigned(FDrawHeaderSection) then
QClxStyle_drawBevelButton_Event(Method) := DrawBevelButtonHook
else
Method := NullHook;
QClxStyleHooks_hook_drawBevelButton(Hooks, Method);
Refresh;
end;
procedure TStyle.BevelButtonRectHook(var x, y, w, h: Integer);
var
R: TRect;
begin
try
R := Rect(x, y, x+w, y+h);
DoHeaderSectionRect(R);
x := R.Left;
y := R.Top;
w := R.Right - R.Left;
h := R.Bottom - R.Top;
except
Application.HandleException(Self);
end;
end;
procedure TStyle.DoHeaderSectionRect(var Rect: TRect);
begin
if Assigned(FHeaderSectionRect) then
FHeaderSectionRect(Self, Rect);
end;
procedure TStyle.SetHeaderSectionRect(const Value: TButtonRectEvent);
var
Method: TMethod;
begin
FHeaderSectionRect := Value;
if Assigned(FHeaderSectionRect) then
QClxStyle_bevelButtonRect_Event(Method) := BevelButtonRectHook
else
Method := NullHook;
QClxStyleHooks_hook_bevelButtonRect(Hooks, Method);
Refresh;
end;
procedure TStyle.ButtonRectHook(var x, y, w, h: Integer);
var
R: TRect;
begin
try
R := Rect(x, y, x+w, y+h);
DoButtonRect(R);
x := R.Left;
y := R.Top;
w := R.Right - R.Left;
h := R.Bottom - R.Top;
except
Application.HandleException(Self);
end;
end;
procedure TStyle.DoButtonRect(var Rect: TRect);
begin
if Assigned(FButtonRect) then
FButtonRect(Self, Rect);
end;
procedure TStyle.SetButtonRect(const Value: TButtonRectEvent);
var
Method: TMethod;
begin
FButtonRect := Value;
if Assigned(FButtonRect) then
QClxStyle_buttonRect_Event(Method) := ButtonRectHook
else
Method := NullHook;
QClxStyleHooks_hook_buttonRect(Hooks, Method);
Refresh;
end;
procedure TStyle.DoDrawArrow(Canvas: TCanvas; const Rect: TRect;
Arrow: ArrowType; Down, Enabled: Boolean);
begin
if Assigned(FDrawArrow) then
FDrawArrow(Self, Canvas, Rect, Arrow, Down, Enabled);
end;
procedure TStyle.DrawArrowHook(p: QPainterH; _type: ArrowType;
down: Boolean; x, y, w, h: Integer; g: QColorGroupH; enabled: Boolean;
fill: QBrushH);
var
Canvas: TCanvas;
begin
try
Canvas := TCanvas.Create;
try
Canvas.Handle := p;
Canvas.Start(False);
DoDrawArrow(Canvas, Rect(x, y, x+w, y+h), _type, down, enabled);
Canvas.Stop;
finally
Canvas.Free;
end;
except
Application.HandleException(Self);
end;
end;
procedure TStyle.SetDrawArrow(const Value: TDrawArrowEvent);
var
Method: TMethod;
begin
FDrawArrow := Value;
if Assigned(FDrawArrow) then
QClxStyle_drawArrow_Event(Method) := DrawArrowHook
else
Method := NullHook;
QClxStyleHooks_hook_drawArrow(Hooks, Method);
Refresh;
end;
procedure TStyle.DrawRadioMaskHook(p: QPainterH; x, y, w, h: Integer; _on: Boolean);
var
Canvas: TCanvas;
begin
try
Canvas := TCanvas.Create;
try
Canvas.Handle := p;
Canvas.Start(False);
DoDrawRadioMask(Canvas, Rect(x, y, x+w, y+h), _on);
Canvas.Stop;
finally
Canvas.Free;
end;
except
Application.HandleException(Self);
end;
end;
procedure TStyle.SetDrawRadioMask(const Value: TDrawRadioMaskEvent);
var
Method: TMethod;
begin
FDrawRadioMask := Value;
if Assigned(FDrawRadioMask) then
QClxStyle_drawExclusiveIndicatorMask_event(Method) := DrawRadioMaskHook
else
Method := NullHook;
QClxStyleHooks_hook_drawExclusiveIndicatorMask(Hooks, Method);
Refresh;
end;
procedure TStyle.DoDrawRadioMask(Canvas: TCanvas; const Rect: TRect; Checked: Boolean);
begin
if Assigned(FDrawRadioMask) then
FDrawRadioMask(Self, Canvas, Rect, Checked);
end;
procedure TStyle.DoDrawCheckMask(Canvas: TCanvas; const Rect: TRect; Checked, Grayed: Boolean);
begin
if Assigned(FDrawCheckMask) then
FDrawCheckMask(Self, Canvas, Rect, Checked, Grayed);
end;
procedure TStyle.DrawIndicatorMaskHook(p: QPainterH; x, y, w, h, state: Integer);
var
Canvas: TCanvas;
begin
try
Canvas := TCanvas.Create;
try
Canvas.Handle := p;
Canvas.Start(False);
DoDrawCheckMask(Canvas, Rect(x, y, x+w, y+h), Boolean(state and $02),
Boolean(state and $01));
Canvas.Stop;
finally
Canvas.Free;
end;
except
Application.HandleException(Self);
end;
end;
procedure TStyle.SetDrawCheckMask(const Value: TDrawCheckMaskEvent);
var
Method: TMethod;
begin
FDrawCheckMask := Value;
if Assigned(FDrawCheckMask) then
QClxStyle_drawIndicatorMask_event(Method) := DrawIndicatorMaskHook
else
Method := NullHook;
QClxStyleHooks_hook_drawIndicatorMask(Hooks, Method);
Refresh;
end;
procedure TStyle.ComboButtonRectHook(var x, y, w, h: Integer);
var
R: TRect;
begin
try
R := Rect(x, y, x+w, y+h);
DoComboButtonRect(R);
x := R.Left;
y := R.Top;
w := R.Right - R.Left;
h := R.Bottom - R.Top;
except
Application.HandleException(Self);
end;
end;
procedure TStyle.DoComboButtonRect(var Rect: TRect);
begin
if Assigned(FComboButtonRect) then
FComboButtonRect(Self, Rect);
end;
procedure TStyle.SetComboButtonRect(const Value: TButtonRectEvent);
var
Method: TMethod;
begin
FComboButtonRect := Value;
if Assigned(FComboButtonRect) then
QClxStyle_comboButtonRect_event(Method) := ComboButtonRectHook
else
Method := NullHook;
QClxStyleHooks_hook_comboButtonRect(Hooks, Method);
Refresh;
end;
procedure TStyle.ComboButtonFocusRectHook(var x, y, w, h: Integer);
var
R: TRect;
begin
try
R := Rect(x, y, x+w, y+h);
DoComboButtonFocusRect(R);
x := R.Left;
y := R.Top;
w := R.Right - R.Left;
h := R.Bottom - R.Top;
except
Application.HandleException(Self);
end;
end;
procedure TStyle.DoComboButtonFocusRect(var Rect: TRect);
begin
if Assigned(FComboButtonFocusRect) then
FComboButtonFocusRect(Self, Rect);
end;
procedure TStyle.SetComboButtonFocusRect(const Value: TButtonRectEvent);
var
Method: TMethod;
begin
FComboButtonFocusRect := Value;
if Assigned(FComboButtonFocusRect) then
QClxStyle_comboButtonFocusRect_event(Method) := ComboButtonFocusRectHook
else
Method := NullHook;
QClxStyleHooks_hook_comboButtonFocusRect(Hooks, Method);
Refresh;
end;
procedure TStyle.DoDrawComboButtonMask(Canvas: TCanvas; const Rect: TRect);
begin
if Assigned(FDrawComboButtonMask) then
FDrawComboButtonMask(Self, Canvas, Rect);
end;
procedure TStyle.DrawComboButtonMaskHook(p: QPainterH; x, y, w,
h: Integer);
var
Canvas: TCanvas;
begin
try
Canvas := TCanvas.Create;
try
Canvas.Handle := p;
Canvas.Start(False);
DoDrawButtonMask(Canvas, Rect(x, y, x+w, y+h));
Canvas.Stop;
finally
Canvas.Free;
end;
except
Application.HandleException(Self);
end;
end;
procedure TStyle.SetDrawComboButtonMask(const Value: TDrawMaskEvent);
var
Method: TMethod;
begin
FDrawComboButtonMask := Value;
if Assigned(FDrawComboButtonMask) then
QClxStyle_DrawComboButtonMask_Event(Method) := DrawComboButtonMaskHook
else
Method := NullHook;
QClxStyleHooks_hook_DrawComboButtonMask(Hooks, Method);
Refresh;
end;
function TStyle.GetDefaultFrameWidth: Integer;
begin
Result := QClxStyle_defaultFrameWidth(Handle);
end;
procedure TStyle.SetDefaultFrameWidth(const Value: Integer);
begin
QClxStyle_setDefaultFrameWidth(Handle, Value);
Refresh;
end;
procedure TStyle.DoTabMetrics(Source: TObject; var HorizontalPadding, VerticalPadding,
Overlap: Integer);
begin
if Assigned(FTabMetrics) then
FTabMetrics(Self, Source, HorizontalPadding, VerticalPadding, Overlap);
end;
procedure TStyle.SetTabMetrics(const Value: TTabMetricsEvent);
var
Method: TMethod;
begin
FTabMetrics := Value;
if Assigned(FTabMetrics) then
QClxStyle_tabBarMetrics_Event(Method) := TabBarMetricsHook
else
Method := NullHook;
QClxStyleHooks_hook_tabBarMetrics(Hooks, Method);
Refresh;
end;
procedure TStyle.TabBarMetricsHook(p1: QTabBarH; var hFrame, vFrame, overlap: Integer);
var
Source: TObject;
begin
try
Source := FindControl(p1);
DoTabMetrics(Source, hFrame, vFrame, overlap);
except
Application.HandleException(Self);
end;
end;
procedure TStyle.DoDrawTab(Source: TObject; Canvas: TCanvas; Index, HorizontalPadding,
VerticalPadding, Overlap: Integer; Selected: Boolean);
begin
if Assigned(FDrawTab) then
FDrawTab(Self, Source, Canvas, Index, HorizontalPadding, VerticalPadding,
Overlap, Selected);
end;
procedure TStyle.DrawTabHook(p1: QPainterH; p2: QTabBarH; index: Integer;
selected: Boolean);
var
Canvas: TCanvas;
Source: TObject;
HorizontalPadding,
VerticalPadding,
Overlap: Integer;
begin
try
Canvas := TCanvas.Create;
try
QClxStyle_tabBarMetrics(Handle, P2, @HorizontalPadding, @VerticalPadding,
@Overlap);
Source := FindControl(p2);
Canvas.Handle := p1;
Canvas.Start(False);
DoDrawTab(Source, Canvas, index, HorizontalPadding, VerticalPadding,
Overlap, selected);
Canvas.Stop;
finally
Canvas.Free;
end;
except
Application.HandleException(Self);
end;
end;
procedure TStyle.SetDrawTab(const Value: TDrawTabEvent);
var
Method: TMethod;
begin
FDrawTab := Value;
if Assigned(FDrawTab) then
QClxStyle_drawTab_event(Method) := DrawTabHook
else
Method := NullHook;
QClxStyleHooks_hook_drawTab(Hooks, Method);
Refresh;
end;
procedure TStyle.DoDrawTabMask(Source: TObject; Canvas: TCanvas; Index,
HorizontalPadding, VerticalPadding, Overlap: Integer; Selected: Boolean);
begin
if Assigned(FDrawTabMask) then
FDrawTabMask(Self, Source, Canvas, Index, HorizontalPadding,
VerticalPadding, Overlap, Selected);
end;
procedure TStyle.DrawTabMaskHook(p1: QPainterH; p2: QTabBarH;
index: Integer; selected: Boolean);
var
Canvas: TCanvas;
Source: TObject;
HorizontalPadding,
VerticalPadding,
Overlap: Integer;
begin
try
Canvas := TCanvas.Create;
try
QClxStyle_tabBarMetrics(Handle, P2, @HorizontalPadding, @VerticalPadding,
@Overlap);
Source := FindControl(p2);
Canvas.Handle := p1;
Canvas.Start(False);
DoDrawTabMask(Source, Canvas, index, HorizontalPadding, VerticalPadding,
Overlap, selected);
Canvas.Stop;
finally
Canvas.Free;
end;
except
Application.HandleException(Self);
end;
end;
procedure TStyle.SetDrawTabMask(const Value: TDrawTabEvent);
var
Method: TMethod;
begin
FDrawTabMask := Value;
if Assigned(FDrawTabMask) then
QClxStyle_DrawTabMask_event(Method) := DrawTabMaskHook
else
Method := NullHook;
QClxStyleHooks_hook_DrawTabMask(Hooks, Method);
Refresh;
end;
procedure TStyle.DoScrollBarMetrics(ScrollBar: QScrollBarH; var SliderMin,
SliderMax, SliderLength, ButtonSize: Integer);
var
StockLen, StockSize: Integer;
begin
if Assigned(FScrollBarMetrics) then
begin
StockLen := SliderLength;
StockSize := ButtonSize;
FScrollBarMetrics(Self, ScrollBar, SliderLength, ButtonSize);
SliderMin := SliderMin + (ButtonSize - StockSize);
SliderMax := SliderMax - (ButtonSize - StockSize) - (SliderLength - StockLen);
end;
end;
procedure TStyle.ScrollBarMetricsHook(p1: QScrollBarH; var sliderMin,
sliderMax, sliderLength, buttonDim: Integer);
begin
try
DoScrollBarMetrics(p1, sliderMin, sliderMax, sliderLength, buttonDim);
except
Application.HandleException(Self);
end;
end;
procedure TStyle.SetScrollBarMetrics(const Value: TScrollBarMetricsEvent);
var
Method: TMethod;
begin
FScrollBarMetrics := Value;
if Assigned(FScrollBarMetrics) then
QClxStyle_scrollBarMetrics_event(Method) := ScrollBarMetricsHook
else
Method := NullHook;
QClxStyleHooks_hook_scrollBarMetrics(Hooks, Method);
Refresh;
end;
function TStyle.DoDrawScrollBar(ScrollBar: QScrollBarH; Canvas: TCanvas;
const Rect: TRect; SliderStart, SliderLength, ButtonSize: Integer; Controls: TScrollBarControls;
DownControl: TScrollBarControl): Boolean;
begin
Result := True;
if Assigned(FDrawScrollBar) then
FDrawScrollBar(Self, ScrollBar, Canvas, Rect, SliderStart,
SliderLength, ButtonSize, Controls, DownControl, Result);
end;
procedure TStyle.DrawScrollBarHook(p1: QPainterH; p2: QScrollBarH;
sliderStart: Integer; controls, activeControl: Integer;
var Stage: Integer);
var
Canvas: TCanvas;
Size: TSize;
SliderMin, SliderMax,
SliderLength, ButtonSize: Integer;
ControlSet: TScrollBarControls;
DownControl: TScrollBarControl;
begin
try
Canvas := TCanvas.Create;
try
QClxStyle_scrollBarMetrics(Handle, p2, @SliderMin, @SliderMax, @SliderLength,
@ButtonSize);
ControlSet := [];
if (controls and Integer(QStyleScrollControl_AddLine)) <> 0 then
Include(ControlSet, sbcAddButton);
if (controls and Integer(QStyleScrollControl_SubLine)) <> 0 then
Include(ControlSet, sbcSubButton);
if (controls and Integer(QStyleScrollControl_AddPage)) <> 0 then
Include(ControlSet, sbcAddPage);
if (controls and Integer(QStyleScrollControl_SubPage)) <> 0 then
Include(ControlSet, sbcSubPage);
if (controls and Integer(QStyleScrollControl_Slider)) <> 0 then
Include(ControlSet, sbcSlider);
case QStyleScrollControl(activeControl) of
QStyleScrollControl_AddLine: DownControl := sbcAddButton;
QStyleScrollControl_SubLine: DownControl := sbcSubButton;
QStyleScrollControl_AddPage: DownControl := sbcAddPage;
QStyleScrollControl_SubPage: DownControl := sbcSubPage;
QStyleScrollControl_Slider: DownControl := sbcSlider;
else
DownControl := sbcNone;
end;
QWidget_size(p2, @Size);
Canvas.Handle := p1;
Canvas.Start(False);
if DoDrawScrollBar(p2, Canvas, Rect(0, 0, Size.cx, Size.cy), sliderStart,
SliderLength, ButtonSize, ControlSet, DownControl) then
Stage := DrawStage_DefaultDraw;
Canvas.Stop;
finally
Canvas.Free;
end;
except
Application.HandleException(Self);
end;
end;
procedure TStyle.SetDrawScrollBar(const Value: TDrawScrollBarEvent);
var
Method: TMethod;
begin
FDrawScrollBar := Value;
if Assigned(FDrawScrollBar) then
QClxStyle_drawScrollBarControls_Event(Method) := DrawScrollBarHook
else
Method := NullHook;
QClxStyleHooks_hook_drawScrollBarControls(Hooks, Method);
Refresh;
end;
function TStyle.GetSliderLength: Integer;
begin
Result := QClxStyle_sliderLength(Handle);
end;
procedure TStyle.SetSliderLength(const Value: Integer);
begin
QClxStyle_setSliderLength(Handle, Value);
Refresh;
end;
function TStyle.DoDrawTrackBar(Canvas: TCanvas; const Rect: TRect; Horizontal,
TickAbove, TickBelow: Boolean): Boolean;
begin
Result := True;
if Assigned(FDrawTrackBar) then
FDrawTrackBar(Self, Canvas, Rect, Horizontal,
TickAbove, TickBelow, Result);
end;
procedure TStyle.DrawSliderHook(p: QPainterH; x, y, w, h: Integer;
g: QColorGroupH; p7: Orientation; tickAbove, tickBelow: Boolean;
var Stage: Integer);
var
Canvas: TCanvas;
begin
try
Canvas := TCanvas.Create;
try
Canvas.Handle := p;
Canvas.Start(False);
if DoDrawTrackBar(Canvas, Rect(x, y, x+w, y+h), p7 = Orientation_Horizontal,
tickAbove, tickBelow) then
Stage := DrawStage_DefaultDraw;
Canvas.Stop;
finally
Canvas.Free;
end;
except
Application.HandleException(Self);
end;
end;
procedure TStyle.SetDrawTrackBar(const Value: TDrawTrackBarEvent);
var
Method: TMethod;
begin
FDrawTrackBar := Value;
if Assigned(FDrawTrackBar) then
QClxStyle_drawSlider_Event(Method) := DrawSliderHook
else
Method := NullHook;
QClxStyleHooks_hook_drawSlider(Hooks, Method);
Refresh;
end;
function TStyle.DoDrawTrackBarMask(Canvas: TCanvas; const Rect: TRect; Horizontal,
TickAbove, TickBelow: Boolean): Boolean;
begin
if Assigned(FDrawTrackBarMask) then
FDrawTrackBarMask(Self, Canvas, Rect, Horizontal, TickAbove,
TickBelow, Result);
end;
procedure TStyle.DrawSliderMaskHook(p: QPainterH; x, y, w, h: Integer;
p6: Orientation; tickAbove, tickBelow: Boolean);
var
Canvas: TCanvas;
begin
try
Canvas := TCanvas.Create;
try
Canvas.Handle := p;
Canvas.Start(False);
DoDrawTrackBarMask(Canvas, Rect(x, y, x+w, y+h), p6 = Orientation_Horizontal,
tickAbove, tickBelow);
Canvas.Stop;
finally
Canvas.Free;
end;
except
Application.HandleException(Self);
end;
end;
procedure TStyle.SetDrawTrackBarMask(const Value: TDrawTrackBarEvent);
var
Method: TMethod;
begin
FDrawTrackBarMask := Value;
if Assigned(FDrawTrackBarMask) then
QClxStyle_drawSliderMask_Event(Method) := DrawSliderMaskHook
else
Method := NullHook;
QClxStyleHooks_hook_drawSliderMask(Hooks, Method);
Refresh;
end;
function TStyle.DoDrawTrackBarGroove(Canvas: TCanvas; const Rect: TRect;
Horizontal: Boolean): Boolean;
begin
Result := True;
if Assigned(FDrawTrackBarGroove) then
FDrawTrackBarGroove(Self, Canvas, Rect, Horizontal, Result);
end;
procedure TStyle.DrawSliderGrooveHook(p: QPainterH; x, y, w, h: Integer;
g: QColorGroupH; c: QCOORD; p8: Orientation; var Stage: Integer);
var
Canvas: TCanvas;
begin
try
Canvas := TCanvas.Create;
try
Canvas.Handle := p;
Canvas.Start(False);
if DoDrawTrackBarGroove(Canvas, Rect(x, y, x+w, y+h), p8 = Orientation_Horizontal) then
Stage := DrawStage_DefaultDraw;
Canvas.Stop;
finally
Canvas.Free;
end;
except
Application.HandleException(Self);
end;
end;
procedure TStyle.SetDrawTrackBarGroove(const Value: TDrawTrackBarGrooveEvent);
var
Method: TMethod;
begin
FDrawTrackBarGroove := Value;
if Assigned(FDrawTrackBarGroove) then
QClxStyle_drawSliderGroove_Event(Method) := DrawSliderGrooveHook
else
Method := NullHook;
QClxStyleHooks_hook_drawSliderGroove(Hooks, Method);
Refresh;
end;
function TStyle.DoDrawTrackBarGrooveMask(Canvas: TCanvas; const Rect: TRect;
Horizontal: Boolean): Boolean;
begin
if Assigned(FDrawTrackBarGrooveMask) then
FDrawTrackBarGrooveMask(Self, Canvas, Rect, Horizontal, Result);
end;
procedure TStyle.DrawSliderGrooveMaskHook(p: QPainterH; x, y, w, h: Integer;
c: QCOORD; p8: Orientation);
var
Canvas: TCanvas;
begin
try
Canvas := TCanvas.Create;
try
Canvas.Handle := p;
Canvas.Start(False);
DoDrawTrackBarGrooveMask(Canvas, Rect(x, y, x+w, y+h), p8 = Orientation_Horizontal);
Canvas.Stop;
finally
Canvas.Free;
end;
except
Application.HandleException(Self);
end;
end;
procedure TStyle.SetDrawTrackBarGrooveMask(const Value: TDrawTrackBarGrooveEvent);
var
Method: TMethod;
begin
FDrawTrackBarGrooveMask := Value;
if Assigned(FDrawTrackBarGrooveMask) then
QClxStyle_drawSliderGrooveMask_Event(Method) := DrawSliderGrooveMaskHook
else
Method := NullHook;
QClxStyleHooks_hook_drawSliderGrooveMask(Hooks, Method);
Refresh;
end;
function TStyle.GetMaxSliderDragDistance: Integer;
begin
Result := QClxStyle_maximumSliderDragDistance(Handle);
end;
procedure TStyle.SetMaxSliderDragDistance(const Value: Integer);
begin
QClxStyle_setMaximumSliderDragDistance(Handle, Value);
Refresh;
end;
function TStyle.DoDrawSplitter(Canvas: TCanvas; const Rect: TRect;
Vertical: Boolean): Boolean;
begin
Result := True;
if Assigned(FDrawSplitter) then
FDrawSplitter(Self, Canvas, Rect, Vertical, Result);
end;
procedure TStyle.DrawSplitterHook(p: QPainterH; x, y, w, h: Integer;
g: QColorGroupH; p7: Orientation; var Stage: Integer);
var
Canvas: TCanvas;
begin
try
Canvas := TCanvas.Create;
try
Canvas.Handle := p;
Canvas.Start(False);
if DoDrawSplitter(Canvas, Rect(x, y, x+w, y+h), p7 = Orientation_Vertical) then
Stage := DrawStage_DefaultDraw;
Canvas.Stop;
finally
Canvas.Free;
end;
except
Application.HandleException(Self);
end;
end;
procedure TStyle.SetDrawSplitter(const Value: TDrawSplitterEvent);
var
Method: TMethod;
begin
FDrawSplitter := Value;
if Assigned(FDrawSplitter) then
QClxStyle_drawSplitter_event(Method) := DrawSplitterHook
else
Method := NullHook;
QClxStyleHooks_hook_drawSplitter(Hooks, Method);
Refresh;
end;
procedure TStyle.DoExtraMenuItemWidth(Source: TObject;
HasCheckmark: Boolean; ImageWidth: Integer; FontMetrics: QFontMetricsH;
var ExtraWidth: Integer);
begin
if Assigned(FExtraMenuItemWidth) then
FExtraMenuItemWidth(Self, Source, HasCheckmark, ImageWidth,
FontMetrics, ExtraWidth);
end;
procedure TStyle.ExtraMenuItemWidthHook(checkable: Boolean;
maxpmw: Integer; mi: QMenuItemH; fm: QFontMetricsH; var Retval: Integer);
var
Source: TObject;
begin
try
Source := FindObject(QWidgetH(mi));
if Source <> nil then
DoExtraMenuItemWidth(Source, checkable, maxpmw, fm, Retval);
except
Application.HandleException(Self);
end;
end;
procedure TStyle.SetExtraMenuItemWidth(const Value: TExtraMenuItemWidthEvent);
var
Method: TMethod;
begin
FExtraMenuItemWidth := Value;
if Assigned(FExtraMenuItemWidth) then
QClxStyle_extraPopupMenuItemWidth_Event(Method) := ExtraMenuItemWidthHook
else
Method := NullHook;
QClxStyleHooks_hook_extraPopupMenuItemWidth(Hooks, Method);
Refresh;
end;
procedure TStyle.DoSubmenuIndicatorWidth(FontMetrics: QFontMetricsH; var Width: Integer);
begin
if Assigned(FSubmenuIndicatorWidth) then
FSubmenuIndicatorWidth(Self, FontMetrics, Width);
end;
procedure TStyle.SetSubmenuIndicatorWidth(const Value: TSubmenuIndicatorWidthEvent);
var
Method: TMethod;
begin
FSubmenuIndicatorWidth := Value;
if Assigned(FSubmenuIndicatorWidth) then
QClxStyle_popupSubmenuIndicatorWidth_Event(Method) := SubMenuIndicatorWidthHook
else
Method := NullHook;
QClxStyleHooks_hook_popupSubmenuIndicatorWidth(Hooks, Method);
Refresh;
end;
procedure TStyle.SubmenuIndicatorWidthHook(fm: QFontMetricsH; var Retval: Integer);
begin
try
DoSubmenuIndicatorWidth(fm, Retval);
except
Application.HandleException(Self);
end;
end;
procedure TStyle.DoMenuItemHeight(Source: TObject; Checkable: Boolean;
FontMetrics: QFontMetricsH; var Height: Integer);
begin
if Assigned(FMenuItemHeight) then
FMenuItemHeight(Self, Source, Checkable, FontMetrics, Height);
end;
procedure TStyle.MenuItemHeightHook(checkable: Boolean; mi: QMenuItemH;
fm: QFontMetricsH; var Height: Integer);
var
Source: TObject;
begin
try
Source := FindObject(QWidgetH(mi));
if Source <> nil then
DoMenuItemHeight(Source, checkable, fm, Height);
except
Application.HandleException(Self);
end;
end;
procedure TStyle.SetMenuItemHeight(const Value: TMenuItemHeightEvent);
var
Method: TMethod;
begin
FMenuItemHeight := Value;
if Assigned(FMenuItemHeight) then
QClxStyle_popupMenuItemHeight_Event(Method) := MenuItemHeightHook
else
Method := NullHook;
QClxStyleHooks_hook_popupMenuItemHeight(Hooks, Method);
Refresh;
end;
type
TAppStyleAddr = procedure;
PQStyleH = ^QStyleH;
var
App_Style: TAppStyleAddr = nil;
function ObtainOwnershipofAppStyle: QStyleH;
begin
Result := nil;
{$IFDEF LINUX}
if not Assigned(App_Style) then
App_Style := dlsym(RTLD_DEFAULT, '_12QApplication.app_style');
{$ENDIF}
if Assigned(App_Style) then
begin
Result := PQStyleH(@App_Style)^;
PQStyleH(@App_Style)^ := nil;
end;
end;
procedure TStyle.SetDefaultStyle(const Value: TDefaultStyle);
begin
if FDefaultStyle <> Value then
begin
FDefaultStyle := Value;
Changed(Self);
end;
end;
procedure TStyle.Changed(Sender: TObject);
begin
Refresh;
if Assigned(FOnChange) then
FOnChange(Self);
end;
function TStyle.GetButtonShift: TPoint;
begin
QClxStyle_buttonShift(Handle, @(Result.x), @(Result.y));
end;
procedure TStyle.SetButtonShift(const Value: TPoint);
begin
QClxStyle_setButtonShift(Handle, Value.x, Value.y);
Refresh;
end;
function TStyle.DoDrawCheck(Canvas: TCanvas; const Rect: TRect;
Checked, Grayed, Down, Enabled: Boolean): Boolean;
begin
Result := True;
if Assigned(FDrawCheck) then
FDrawCheck(Self, Canvas, Rect, Checked, Grayed, Down, Enabled, Result);
end;
procedure TStyle.DrawCheckHook(p: QPainterH; x, y, w, h: Integer;
g: QColorGroupH; State: Integer; Down, Enabled: Boolean;
var Stage: Integer);
var
Canvas: TCanvas;
R: TRect;
begin
try
Canvas := TCanvas.Create;
try
R := Rect(x, y, x+w, y+h);
Canvas.Handle := p;
Canvas.Start(False);
if DoDrawCheck(Canvas, R, Boolean(State and $02), Boolean(State and $01),
Down, Enabled) then
Stage := DrawStage_DefaultDraw;
Canvas.Stop;
finally
Canvas.Free;
end;
except
Application.HandleException(Self);
end;
end;
procedure TStyle.SetDrawCheck(const Value: TDrawCheckEvent);
var
Method: TMethod;
begin
FDrawCheck := Value;
if Assigned(FDrawCheck) then
QClxStyle_drawIndicator_Event(Method) := DrawCheckHook
else
Method := NullHook;
QClxStyleHooks_hook_drawIndicator(Hooks, Method);
Refresh;
end;
function TStyle.DoDrawRadio(Canvas: TCanvas; const Rect: TRect; Checked, Down,
Enabled: Boolean): Boolean;
begin
Result := True;
if Assigned(FDrawRadio) then
FDrawRadio(Self, Canvas, Rect, Checked, Down, Enabled, Result);
end;
procedure TStyle.DrawRadioHook(p: QPainterH; x, y, w, h: Integer;
g: QColorGroupH; _on, down, enabled: Boolean; var Stage: Integer);
var
Canvas: TCanvas;
R: TRect;
begin
try
Canvas := TCanvas.Create;
try
R := Rect(x, y, x+w, y+h);
Canvas.Handle := p;
Canvas.Start(False);
if DoDrawRadio(Canvas, R, _on, down, enabled) then
Stage := DrawStage_DefaultDraw;
Canvas.Stop;
finally
Canvas.Free;
end;
except
Application.HandleException(Self);
end;
end;
procedure TStyle.SetDrawRadio(const Value: TDrawRadioEvent);
var
Method: TMethod;
begin
FDrawRadio := Value;
if Assigned(FDrawRadio) then
QClxStyle_drawExclusiveIndicator_Event(Method) := DrawRadioHook
else
Method := NullHook;
QClxStyleHooks_hook_drawExclusiveIndicator(Hooks, Method);
Refresh;
end;
function TStyle.GetCheckSize: TSize;
begin
QClxStyle_indicatorSize(Handle, @Result);
end;
function TStyle.GetRadioSize: TSize;
begin
QClxStyle_exclusiveIndicatorSize(Handle, @Result);
end;
procedure TStyle.SetCheckSize(const Value: TSize);
begin
QClxStyle_setIndicatorSize(Handle, @Value);
Refresh;
end;
procedure TStyle.SetRadioSize(const Value: TSize);
begin
QClxStyle_setExclusiveIndicatorSize(Handle, @Value);
Refresh;
end;
procedure TStyle.DrawPanelHook(p: QPainterH; x, y, w, h: Integer;
p6: QColorGroupH; sunken: Boolean; lineWidth: Integer; fill: QBrushH;
var Stage: Integer);
var
Canvas: TCanvas;
R: TRect;
begin
try
Canvas := TCanvas.Create;
try
R := Rect(x, y, x+w, y+h);
Canvas.Handle := p;
Canvas.Start(False);
if DoDrawFrame(Canvas, R, sunken, lineWidth) then
Stage := DrawStage_DefaultDraw;
Canvas.Stop;
finally
Canvas.Free;
end;
except
Application.HandleException(Self);
end;
end;
function TStyle.DoDrawFrame(Canvas: TCanvas; const Rect: TRect; Sunken: Boolean;
LineWidth: Integer): Boolean;
begin
Result := True;
if Assigned(FDrawFrame) then
FDrawFrame(Self, Canvas, Rect, Sunken, LineWidth, Result);
end;
procedure TStyle.SetDrawFrame(const Value: TDrawFrameEvent);
var
Method: TMethod;
begin
FDrawFrame := Value;
if Assigned(FDrawFrame) then
QClxStyle_drawPanel_Event(Method) := DrawPanelHook
else
Method := NullHook;
QClxStyleHooks_hook_drawPanel(Hooks, Method);
Refresh;
end;
procedure TStyle.DoDrawMenuCheck(Canvas: TCanvas; const Rect: TRect; Highlighted,
Enabled: Boolean);
begin
if Assigned(FDrawMenuCheck) then
FDrawMenuCheck(Self, Canvas, Rect, Highlighted, Enabled);
end;
procedure TStyle.DrawMenuCheckHook(p: QPainterH; x, y, w, h: Integer;
g: QColorGroupH; act, dis: Boolean);
var
Canvas: TCanvas;
R: TRect;
begin
try
Canvas := TCanvas.Create;
try
R := Rect(x, y, x+w, y+h);
Canvas.Handle := p;
Canvas.Start(False);
DoDrawMenuCheck(Canvas, R, act, dis);
Canvas.Stop;
finally
Canvas.Free;
end;
except
Application.HandleException(Self);
end;
end;
procedure TStyle.SetDrawMenuCheck(const Value: TDrawMenuCheckEvent);
var
Method: TMethod;
begin
FDrawMenuCheck := Value;
if Assigned(FDrawMenuCheck) then
QClxStyle_drawCheckMark_Event(Method) := DrawMenuCheckHook
else
Method := NullHook;
QClxStyleHooks_hook_drawCheckMark(Hooks, Method);
Refresh;
end;
procedure TStyle.DrawItemHook(p: QPainterH; x, y, w, h, flags: Integer;
g: QColorGroupH; enabled: Boolean; pixmap: QPixmapH; text: PString;
len: Integer; penColor: QColorH; var Stage: Integer);
var
Canvas: TCanvas;
R: TRect;
Bitmap: TBitmap;
Color: TColor;
begin
try
Canvas := TCanvas.Create;
try
Bitmap := TBitmap.Create;
try
if penColor = nil then
Color := clText
else
Color := QColorColor(penColor);
Bitmap.Handle := pixmap;
Canvas.Handle := p;
Canvas.Start(False);
R := Rect(x, y, x+w, y+h);
case Stage of
DrawStage_Pre:
if DoBeforeDrawItem(Canvas, R, flags, enabled, Bitmap, text^, len, Color) then
Stage := DrawStage_DefaultDraw;
DrawStage_Post:
DoAfterDrawItem(Canvas, R, flags, enabled, Bitmap, text^, len, Color);
end;
Canvas.Stop;
finally
Bitmap.Free;
end;
finally
Canvas.Free;
end;
except
Application.HandleException(Self);
end;
end;
procedure TStyle.DoAfterDrawItem(Canvas: TCanvas; const Rect: TRect;
Flags: Integer; Enabled: Boolean; Bitmap: TBitmap; const Text: WideString;
Length: Integer; Color: TColor);
begin
if Assigned(FAfterDrawItem) then
FAfterDrawItem(Self, Canvas, Rect, Flags, Enabled, Bitmap, Text, Length, Color);
end;
function TStyle.DoBeforeDrawItem(Canvas: TCanvas; const Rect: TRect;
Flags: Integer; Enabled: Boolean; Bitmap: TBitmap; const Text: WideString;
Length: Integer; Color: TColor): Boolean;
begin
Result := True;
if Assigned(FBeforeDrawItem) then
FBeforeDrawItem(Self, Canvas, Rect, Flags, Enabled, Bitmap, Text, Length,
Color, Result);
end;
procedure TStyle.SetAfterDrawItem(const Value: TAfterDrawItemEvent);
var
Method: TMethod;
begin
FAfterDrawItem := Value;
if Assigned(FBeforeDrawItem) then
Exit;
if Assigned(FAfterDrawItem) then
QClxStyle_drawItem_Event(Method) := DrawItemHook
else
Method := NullHook;
QClxStyleHooks_hook_drawItem(Hooks, Method);
Refresh;
end;
procedure TStyle.SetBeforeDrawItem(const Value: TBeforeDrawItemEvent);
var
Method: TMethod;
begin
FBeforeDrawItem := Value;
if Assigned(FAfterDrawItem) then
Exit;
if Assigned(FBeforeDrawItem) then
QClxStyle_drawItem_Event(Method) := DrawItemHook
else
Method := NullHook;
QClxStyleHooks_hook_drawItem(Hooks, Method);
Refresh;
end;
function TStyle.DoDrawComboButton(Canvas: TCanvas; const Rect: TRect; Sunken,
ReadOnly, Enabled: Boolean): Boolean;
begin
Result := True;
if Assigned(FDrawComboButton) then
FDrawComboButton(Self, Canvas, Rect, Sunken, ReadOnly, Enabled, Result);
end;
procedure TStyle.DrawComboButtonHook(p: QPainterH; x, y, w, h: Integer;
g: QColorGroupH; sunken, editable, enabled: Boolean; fill: QBrushH;
var Stage: Integer);
var
Canvas: TCanvas;
R: TRect;
begin
try
Canvas := TCanvas.Create;
try
Canvas.Handle := p;
Canvas.Start(False);
R := Rect(x, y, x+w, y+h);
if DoDrawComboButton(Canvas, R, sunken, not editable, enabled) then
Stage := DrawStage_DefaultDraw;
Canvas.Stop;
finally
Canvas.Free;
end;
except
Application.HandleException(Self);
end;
end;
procedure TStyle.SetDrawComboButton(const Value: TDrawComboButtonEvent);
var
Method: TMethod;
begin
FDrawComboButton := Value;
if Assigned(FDrawComboButton) then
QClxStyle_drawComboButton_Event(Method) := DrawComboButtonHook
else
Method := NullHook;
QClxStyleHooks_hook_drawComboButton(Hooks, Method);
Refresh;
end;
procedure TStyle.DoDrawButtonMask(Canvas: TCanvas; const Rect: TRect);
begin
if Assigned(FDrawButtonMask) then
FDrawButtonMask(Self, Canvas, Rect);
end;
procedure TStyle.DrawButtonMaskHook(p: QPainterH; x, y, w, h: Integer);
var
Canvas: TCanvas;
begin
try
Canvas := TCanvas.Create;
try
Canvas.Handle := p;
Canvas.Start(False);
DoDrawButtonMask(Canvas, Rect(x, y, x+w, y+h));
Canvas.Stop;
finally
Canvas.Free;
end;
except
Application.HandleException(Self);
end;
end;
procedure TStyle.SetDrawButtonMask(const Value: TDrawMaskEvent);
var
Method: TMethod;
begin
FDrawButtonMask := Value;
if Assigned(FDrawButtonMask) then
QClxStyle_DrawButtonMask_Event(Method) := DrawButtonMaskHook
else
Method := NullHook;
QClxStyleHooks_hook_DrawButtonMask(Hooks, Method);
Refresh;
end;
procedure ResetSystemStyle;
begin
{$IFDEF LINUX}
if Assigned(LoadThemeHook) and not Assigned(AppResetStyle) then
AppResetStyle := dlsym(LoadThemeHook(), 'KApplication_resetGUIStyle');
if Assigned(AppResetStyle) then
AppResetStyle
else
{$ENDIF}
QApplication_setStyle(QWindowsStyle_create);
end;
{ TApplicationStyle }
destructor TApplicationStyle.Destroy;
begin
if Assigned(FHooks) then
QClxStyleHooks_hook_StyleDestroyed(FHooks, NullHook);
if Assigned(Application) and not (Application.Terminated) then
ResetSystemStyle;
inherited Destroy;
end;
procedure TApplicationStyle.CreateHandle;
var
Temp: WideString;
Method: TMethod;
TempStyle: QStyleH;
begin
if (FDefaultStyle = dsSystemDefault) then
begin
{$IFDEF LINUX}
if FRecreating then
ResetSystemStyle;
{$ENDIF}
TempStyle := ObtainOwnershipofAppStyle;
FHooks := QClxStyleHooks_create;
FHandle := QClxStyle_create(TempStyle, FHooks);
end
else
begin
FHooks := QClxStyleHooks_create;
Temp := cStyles[FDefaultStyle];
FHandle := QClxStyle_create(@Temp, FHooks);
end;
QClxStyle_StyleDestroyed_Event(Method) := StyleDestroyedHook;
QClxStyleHooks_hook_StyleDestroyed(FHooks, Method);
QApplication_setStyle(FHandle);
end;
procedure TApplicationStyle.StyleDestroyed;
begin
if not FRecreating then
begin
if Assigned(FHooks) then
QClxStyleHooks_hook_StyleDestroyed(FHooks, NullHook);
FHandle := nil;
FHooks := nil;
if Assigned(Application) and not Application.Terminated then
HandleNeeded;
end;
end;
procedure TApplicationStyle.DoPolish(Source: TObject);
begin
if Assigned(FOnPolish) then
FOnPolish(Self, Source);
end;
procedure TApplicationStyle.PolishHook(p1: QApplicationH);
begin
try
DoPolish(Application);
except
Application.HandleException(Self);
end;
end;
procedure TApplicationStyle.SetDefaultStyle(const Value: TDefaultStyle);
begin
if FDefaultStyle <> Value then
begin
FRecreating := True;
try
FHandle := nil;
FHooks := nil;
FDefaultStyle := Value;
HandleNeeded;
finally
FRecreating := False;
end;
Changed(Self);
end;
end;
procedure TApplicationStyle.SetOnPolish(const Value: TPolishEvent);
var
Method: TMethod;
begin
FOnPolish := Value;
if Assigned(FOnPolish) then
QClxStyle_polish2_Event(Method) := PolishHook
else
Method := NullHook;
QClxStyleHooks_hook_polish2(Hooks, Method);
Refresh;
end;
{ TWidgetStyle }
procedure TWidgetStyle.DoPolish(Source: TObject);
begin
if Assigned(FOnPolish) then
FOnPolish(Self, Source);
end;
procedure TWidgetStyle.PolishHook(p1: QWidgetH);
var
Source: TObject;
begin
try
TWidgetControl(Source) := FindControl(p1);
DoPolish(Source);
except
Application.HandleException(Self);
end;
end;
procedure TWidgetStyle.SetDefaultStyle(const Value: TDefaultStyle);
begin
if FDefaultStyle <> Value then
begin
if FDefaultStyle <> dsSystemDefault then
begin
if Assigned(FHandle) then
QClxStyle_destroy(FHandle);
end;
FHandle := nil;
FDefaultStyle := Value;
HandleNeeded;
Changed(Self);
end;
end;
procedure TWidgetStyle.SetOnPolish(const Value: TPolishEvent);
var
Method: TMethod;
begin
FOnPolish := Value;
if Assigned(FOnPolish) then
QClxStyle_polish_Event(Method) := PolishHook
else
Method := NullHook;
QClxStyleHooks_hook_polish(Hooks, Method);
Refresh;
end;
end.
|
unit UnitCennik;
interface
const FIELDS_MAX = 4;
OLD_CENNIK_EXT = '.old';
NEW_CENNIK_EXT = '.new';
type PCennikServer = ^TCennikServer;
PData = ^TData;
TCennikServer = record
Host : string;
Port : integer;
User : string;
Password : string;
Database : string;
end;
TCennikFields = array[0..(FIELDS_MAX-1)] of string;
TData = array of TCennikFields;
TCennik = class
private
FFriendly : string; // User friendly name of table
FName : string; // Real name of table in MySQL database
FFileName : string; // Name of local file containing table data
FData : TData; // Data loaded from local file
procedure LoadFromFile( FileName : string ); // Loads data from file to data
procedure SaveToFile( FileName : string ); // Saves data to file
public
constructor Create( Friendly : string; Name : string; FileName : string );
destructor Destroy; override;
procedure ExportToFile( FileName : string );
procedure AddRow;
procedure DeleteRow( Index : integer );
procedure EditCell( Col : integer; Row : integer; Value : string );
procedure Rename( Name : string );
procedure Assign( Data : PData );
property Data : TData read FData;
property FriendlyName : string read FFriendly;
property Name : string read FName;
property FileName : string read FFileName;
end;
var Cennik : TCennik;
implementation
// Constructor
constructor TCennik.Create( Friendly : string; Name : string; FileName : string );
begin
inherited Create;
FFriendly := Friendly;
FName := Name;
FFileName := FileName;
SetLength( FData , 0 );
LoadFromFile( FFileName );
end;
// Destructor
destructor TCennik.Destroy;
begin
SaveToFile( FFileName );
inherited;
end;
//==============================================================================
// P R I V A T E
//==============================================================================
// Loads data from file to data
procedure TCennik.LoadFromFile( FileName : string );
var F : TextFile;
Count : integer;
I, J : integer;
begin
AssignFile( F , FileName );
{$I-}
Reset( F );
{$I+}
if (IOResult <> 0) then
exit;
Readln( F , FName );
Readln( F , FFriendly );
// Get data
Readln( F , Count );
SetLength( FData , Count );
for I := 0 to Count-1 do
for J := 0 to FIELDS_MAX-1 do
Readln( F , FData[I][J] );
CloseFile( F );
end;
// Saves data to file
procedure TCennik.SaveToFile( FileName : string );
var F : TextFile;
I, J : integer;
begin
AssignFile( F , FileName );
try
Rewrite( F );
Writeln( F , FName );
Writeln( F , FFriendly );
// Save data
Writeln( F , Length( FData ) );
for I := 0 to Length( FData )-1 do
for J := 0 to FIELDS_MAX-1 do
Writeln( F , FData[I][J] );
finally
CloseFile( F );
end;
end;
procedure TCennik.Assign( Data : PData );
var I, J : integer;
begin
SetLength( FData , Length( Data^ ) );
for I := 0 to Length( Data^ )-1 do
for J := 0 to FIELDS_MAX-1 do
FData[I,J] := Data^[I,J];
end;
//==============================================================================
// P U B L I C
//==============================================================================
procedure TCennik.ExportToFile( FileName : string );
begin
SaveToFile( FileName );
end;
procedure TCennik.AddRow;
var I : integer;
begin
SetLength( FData , Length( FData )+1 );
for I := 0 to FIELDS_MAX-1 do
FData[Length( FData )-1][I] := '';
end;
procedure TCennik.DeleteRow( Index : integer );
var I : integer;
begin
if ((Index < 0) or
(Index >= Length( FData ))) then
exit;
for I := Index to Length( FData )-2 do
FData[I] := FData[I+1];
SetLength( FData , Length( FData )-1 );
end;
procedure TCennik.EditCell( Col : integer; Row : integer; Value : string );
begin
if (Row >= Length( FData )) then
SetLength( FData , Row+1 );
FData[Row,Col] := Value;
end;
procedure TCennik.Rename( Name : string );
begin
FFriendly := Name;
end;
end.
|
unit calculate;
interface
type
TCalculate = class
public
function Add( A, B: uint32 ): uint32;
end;
implementation
{ TCalculate }
function TCalculate.Add(A, B: uint32): uint32;
begin
Result := A + B;
end;
end.
|
{(*}
(*------------------------------------------------------------------------------
Delphi Code formatter source code
The Original Code is frCapsSettings.pas, released April 2000.
The Initial Developer of the Original Code is Anthony Steele.
Portions created by Anthony Steele are Copyright (C) 1999-2008 Anthony Steele.
All Rights Reserved.
Contributor(s): Anthony Steele.
The contents of this file are subject to the Mozilla Public License Version 1.1
(the "License"). you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.mozilla.org/NPL/
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied.
See the License for the specific language governing rights and limitations
under the License.
Alternatively, the contents of this file may be used under the terms of
the GNU General Public License Version 2 or later (the "GPL")
See http://www.gnu.org/licenses/gpl.html
------------------------------------------------------------------------------*)
{*)}
unit frReservedCapsSettings;
{$I JcfGlobal.inc}
interface
uses
{ delphi }
Classes, Controls, Forms,
StdCtrls, ExtCtrls,
{ local }
frmBaseSettingsFrame;
type
TfrReservedCapsSettings = class(TfrSettingsFrame)
cbEnable: TCheckBox;
rgReservedWords: TRadioGroup;
rgOperators: TRadioGroup;
rgTypes: TRadioGroup;
rgConstants: TRadioGroup;
rgDirectives: TRadioGroup;
procedure cbEnableClick(Sender: TObject);
private
public
constructor Create(AOwner: TComponent); override;
procedure Read; override;
procedure Write; override;
end;
implementation
{$ifdef FPC}
{$R *.lfm}
{$else}
{$R *.dfm}
{$endif}
uses SettingsTypes, JcfHelp, JcfSettings;
constructor TfrReservedCapsSettings.Create(AOwner: TComponent);
begin
inherited;
fiHelpContext := HELP_CLARIFY_CAPITALISATION;
end;
procedure TfrReservedCapsSettings.cbEnableClick(Sender: TObject);
begin
rgReservedWords.Enabled := cbEnable.Checked;
rgConstants.Enabled := cbEnable.Checked;
rgDirectives.Enabled := cbEnable.Checked;
rgOperators.Enabled := cbEnable.Checked;
rgTypes.Enabled := cbEnable.Checked;
end;
procedure TfrReservedCapsSettings.Read;
begin
cbEnable.Checked := JcfFormatSettings.Caps.Enabled;
with JcfFormatSettings.Caps do
begin
rgReservedWords.ItemIndex := Ord(ReservedWords);
rgConstants.ItemIndex := Ord(Constants);
rgDirectives.ItemIndex := Ord(Directives);
rgOperators.ItemIndex := Ord(Operators);
rgTypes.ItemIndex := Ord(Types);
end;
end;
procedure TfrReservedCapsSettings.Write;
begin
JcfFormatSettings.Caps.Enabled := cbEnable.Checked;
with JcfFormatSettings.Caps do
begin
ReservedWords := TCapitalisationType(rgReservedWords.ItemIndex);
Constants := TCapitalisationType(rgConstants.ItemIndex);
Directives := TCapitalisationType(rgDirectives.ItemIndex);
Operators := TCapitalisationType(rgOperators.ItemIndex);
Types := TCapitalisationType(rgTypes.ItemIndex);
end;
end;
end.
|
unit ReportsDrawer;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BaseForm, Vcl.ComCtrls, cxGraphics,
cxControls, cxLookAndFeels, cxLookAndFeelPainters, dxSkinsCore, dxSkinBlack,
dxSkinBlue, dxSkinBlueprint, dxSkinCaramel, dxSkinCoffee, dxSkinDarkRoom,
dxSkinDarkSide, dxSkinDevExpressDarkStyle, dxSkinDevExpressStyle, dxSkinFoggy,
dxSkinGlassOceans, dxSkinHighContrast, dxSkiniMaginary, dxSkinLilian,
dxSkinLiquidSky, dxSkinLondonLiquidSky, dxSkinMcSkin, dxSkinMoneyTwins,
dxSkinOffice2007Black, dxSkinOffice2007Blue, dxSkinOffice2007Green,
dxSkinOffice2007Pink, dxSkinOffice2007Silver, dxSkinOffice2010Black,
dxSkinOffice2010Blue, dxSkinOffice2010Silver, dxSkinPumpkin, dxSkinSeven,
dxSkinSevenClassic, dxSkinSharp, dxSkinSharpPlus, dxSkinSilver,
dxSkinSpringTime, dxSkinStardust, dxSkinSummer2008, dxSkinTheAsphaltWorld,
dxSkinsDefaultPainters, dxSkinValentine, dxSkinVS2010, dxSkinWhiteprint,
dxSkinXmas2008Blue, cxContainer, cxEdit, cxTreeView, Vcl.ExtCtrls,
JvExExtCtrls, JvExtComponent, JvPanel, JvExComCtrls, JvComCtrls;
type
TfReportsDrawer = class(TfBase)
pDock: TPanel;
pLeft: TPanel;
tvReports: TcxTreeView;
pcMaster: TJvPageControl;
tsMaster: TTabSheet;
pDetails: TJvPanel;
procedure tvReportsChange(Sender: TObject; Node: TTreeNode);
private
{ Private declarations }
public
{ Public declarations }
end;
var
fReportsDrawer: TfReportsDrawer;
implementation
{$R *.dfm}
uses FormUtil, AppConstant, AttendanceReport;
procedure TfReportsDrawer.tvReportsChange(Sender: TObject; Node: TTreeNode);
var
form: TForm;
begin
case Node.SelectedIndex of
TAppConstant.TReport.ATTENDANCE: form := TfAttendanceReport.Create(self);
else form := TForm.Create(self);
end;
DockForm(pDock, form);
end;
end.
|
{*******************************************************}
{ }
{ Delphi DataSnap Framework }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit DSAzDlgPageProps;
interface
uses
System.Classes, Vcl.Controls, Vcl.Dialogs, DSAzDlgBlockProps, Vcl.ExtCtrls, Vcl.Forms, Vcl.Graphics,
Vcl.StdCtrls;
type
TAzPageProps = class(TAzBlockProps)
lbeLength: TLabeledEdit;
lbeNumber: TLabeledEdit;
Label1: TLabel;
cbxAction: TComboBox;
private
{ Private declarations }
function GetLength: String;
procedure SetLength(const Data: string);
function GetNumberAction: String;
procedure SetNumberAction(const Data: string);
function GetSequence: string;
procedure SetSequence(const Data: string);
public
{ Public declarations }
property Length: string read GetLength write SetLength;
property Action: string read GetNumberAction write SetNumberAction;
property Sequence: string read GetSequence write SetSequence;
end;
implementation
{$R *.dfm}
{ TAzPageProps }
function TAzPageProps.GetNumberAction: String;
begin
Result := cbxAction.Text;
end;
function TAzPageProps.GetLength: String;
begin
Result := lbeLength.Text;
end;
function TAzPageProps.GetSequence: string;
begin
Result := '';
if 'increment' <> Action then
Result := lbeNumber.Text;
end;
procedure TAzPageProps.SetNumberAction(const Data: string);
begin
cbxAction.Text := Data;
end;
procedure TAzPageProps.SetLength(const Data: string);
begin
lbeLength.Text := Data;
end;
procedure TAzPageProps.SetSequence(const Data: string);
begin
lbeNumber.Text := Data;
end;
end.
|
{ multiply two matrices, store results in third
matrix, and print results }
program matrix_mul ;
const
SIZE = 9 ; { (size of matrices)-1 }
type
matrix = array[0..SIZE, 0..SIZE] of real;
integer = longint;
var
a : matrix ; { first array }
b : matrix ; { second array }
c : matrix ; { result array }
nprocs: longint; { number of processes }
ret_val: longint; { return value for m_set_procs }
procedure m_lock;
cexternal;
procedure m_unlock;
cexternal;
function m_set_procs(var i : longint) : longint;
cexternal;
procedure m_pfork(procedure a);
cexternal;
function m_get_numprocs : longint;
cexternal;
function m_get_myid : longint;
cexternal;
procedure m_kill_procs;
cexternal;
{ initialize matrix function }
procedure init_matrix ;
var
i, j : integer ;
begin
for i := 0 to SIZE do
begin
for j := 0 to SIZE do
begin
a[i, j] := (i + j) ;
b[i, j] := (i - j) ;
end;
end;
end; { init_matrix }
{ matrix multiply function }
procedure matmul ;
var
i, j, k : integer; { local loop indices }
nprocs : integer; { number of processes }
begin
nprocs := m_get_numprocs; { number of processes }
i := m_get_myid; { start at Nth iteration }
while (i <= SIZE) do
begin
for j := 0 to SIZE do
begin
for k := 0 to SIZE do
c[i, k] := c[i, k] + a[i, j] * b[j, k];
end;
i := i + nprocs;
end;
end; { matmul}
{ print results procedure }
procedure print_mats ;
var
i, j : integer; { local loop indices }
begin
for i := 0 to SIZE do
begin
for j := 0 to SIZE do
begin
writeln('a[',i,',',j,'] = ',a[i,j],
'b[',i,',',j,'] = ',b[i,j],' c[',i,',',
j,'] = ',c[i, j]);
end;
end;
end; {print_mats}
begin { main program starts here}
writeln('Enter number of processes:');
readln(nprocs);
init_matrix; { initialize data arrays }
ret_val := m_set_procs(nprocs); { set number of processes }
m_pfork(matmul); { do matrix multiply }
m_kill_procs; { terminate child processes }
print_mats; { print results }
end. { main program }
|
unit UMinecraftVersionsLoader;
interface
uses SuperObject, Classes, Generics.Collections, VCL.dialogs;
type
TMinecraftVersion = class
public
id, time, releaseTime, mtype:string;
end;
TMinecraftVersionsLoader = class
private
JSON:string;
jso:ISuperObject;
public
Snapshot, Release : string;
Versions:TList<TMinecraftVersion>;
constructor Create(j:string);
end;
implementation
constructor TMinecraftVersionsLoader.Create(j:string);
var vers:ISuperObject;
i: Integer; o:ISuperObject;
v: TMinecraftVersion;
begin
JSON := j;
jso := SO(JSON);
vers := jso['versions'];
Versions := TList<TMinecraftVersion>.Create;
for i := 0 to vers.AsArray.Length - 1 do
begin
v := TMinecraftVersion.Create;
o := vers.AsArray[i];
v.id := o.S['id'];
v.time := o.S['time'];
v.releaseTime := o.S['releaseTime'];
v.mtype := o.S['type'];
Versions.Add(v);
end;
o := jso['latest'];
Snapshot := o.S['snapshot'];
Release := o.S['release'];
end;
end.
|
unit U.Methods;
interface
uses
System.Bindings.EvalProtocol;
procedure PrintFactoryMethodList;
procedure RegisterCapitalizeMethodOnFactory;
function GetPutStarsMethodScope: IScope;
implementation
uses
U.Utilities,
System.Bindings.Methods,
System.Bindings.Helper;
// PrintFactoryMethodList
procedure PrintFactoryMethodList;
var
LFirst: Boolean;
LMethod: TMethodDescription;
begin
LFirst := True;
WriteLn('Registered methods in the global factory:');
Write('[');
for LMethod in TBindingMethodsFactory.GetRegisteredMethods do
begin
if not LFirst then
Write(', ');
Write(LMethod.Name);
LFirst := False;
end;
WriteLn(']');
WriteLn('-----');
end;
// RegisterCustomMethodOnFactory
procedure RegisterCapitalizeMethodOnFactory;
var
LMethodDescription: TMethodDescription;
LInvokable: IInvokable;
begin
// Make IInvokable implementation
LInvokable := MakeInvokable(
function(Args: TArray<IValue>): IValue
var
StrValue: String;
begin
StrValue := Args[0].GetValue.AsString;
Result := TValueWrapper.Create(CapitalizeString(StrValue));
end
);
// Create a TMethodDescription instance
LMethodDescription := TMethodDescription.Create(
LInvokable, // Anonimous method wrapped in a IInvokable implementation instance
'Capitalize', // Method identifier
'Capitalize', // Method name
'U.Utilities', // Unit name where the method is defined
True, // Enabled
'Capitalize the first letter of every word in the string', // Long method description (Hint)
nil // Method's platform (TComponent=VCL; TFMXComponent=FMX; nil=both)
);
// Register in the methods factory
TBindingMethodsFactory.RegisterMethod(LMethodDescription);
// Compressed version
// TBindingMethodsFactory.RegisterMethod(
// TMethodDescription.Create(MakeInvokable(
// function(Args: TArray<IValue>): IValue
// var
// StrValue: String;
// begin
// StrValue := Args[0].GetValue.AsString;
// Result := TValueWrapper.Create(CapitalizeString(StrValue));
// end),
// 'Capitalize', // Method identifier
// 'Capitalize', // Method name
// 'Utilities', // Unit name where the method is defined
// True, // Enabled
// 'Capitalize the first letter of every word in the string', // Long method description (Hint)
// nil // Method's platform (TComponent=VCL; TFMXComponent=FMX; nil=both)
// )
// );
end;
// GetCustomMethodScope
function GetPutStarsMethodScope: IScope;
begin
Result := TBindings.CreateMethodScope('PutStars',
MakeInvokable( // IInvokable
function(Args: TArray<IValue>): IValue
begin
Result := TValueWrapper.Create('*** ' + Args[0].GetValue.AsString + ' ***');
end
)
);
end;
end.
|
{*******************************************************}
{ }
{ Delphi FireMonkey Platform }
{ }
{ Copyright(c) 2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit FMX_OBJ_Importer;
{$IFDEF FPC}
{$mode delphi}
{$ENDIF}
interface
uses
Classes, SysUtils, FMX_Types3D, FMX_Import, FMX_Objects3D;
type
TOBJModelImporter = class(TModelImporter)
public
function GetDescription: WideString; override;
function GetExt: WideString; override;
function LoadFromFile(const AFileName: WideString;
out AMesh: TMeshDynArray; AOwner: TComponent): boolean; override;
end;
implementation
uses
FMX_OBJ_Model;
{ TOBJModelImporter }
function TOBJModelImporter.GetDescription: WideString;
begin
Result := 'Wavefront object';
end;
function TOBJModelImporter.GetExt: WideString;
begin
Result := 'OBJ';
end;
function TOBJModelImporter.LoadFromFile(const AFileName: WideString;
out AMesh: TMeshDynArray; AOwner: TComponent): Boolean;
var
i, j, idx : Integer;
LOBJMesh : TOBJMesh;
LOBJModel : TOBJModel;
begin
LOBJModel := TOBJModel.Create();
LOBJModel.LoadFromFile(AFileName);
LOBJModel.Materials.LoadImages(ExtractFilePath(AFileName));
AMesh := nil;
idx := 0;
for i := 0 to High(LOBJModel.Meshes) do
begin
LOBJMesh := LOBJModel.Meshes[i];
SetLength(AMesh, Length(AMesh) + Length(LOBJMesh.SubMeshes));
for j := 0 to High(LOBJMesh.SubMeshes) do
begin
AMesh[idx] := LOBJMesh.SubMeshes[j].CreateMesh(AOwner, IdentityMatrix3D,
LOBJModel.Materials.Materials);
Inc(idx);
end;
end;
LOBJModel.Free;
Result := True;
end;
var
OBJImporterId: Integer;
initialization
OBJImporterId := TModelImportServices.RegisterImporter(TOBJModelImporter.Create);
finalization
TModelImportServices.UnregisterImporter(OBJImporterId);
end.
|
{*******************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ }
{ Copyright (c) 1997, 1998 Inprise Corporation }
{ }
{*******************************************************}
unit BdeConst;
interface
resourcestring
SAutoSessionExclusive = 'Cannot enable AutoSessionName property with more than one session on a form or data-module';
SAutoSessionExists = 'Cannot add a session to the form or data-module while session ''%s'' has AutoSessionName enabled';
SAutoSessionActive = 'Cannot modify SessionName while AutoSessionName is enabled';
SDuplicateDatabaseName = 'Duplicate database name ''%s''';
SDuplicateSessionName = 'Duplicate session name ''%s''';
SInvalidSessionName = 'Invalid session name %s';
SDatabaseNameMissing = 'Database name missing';
SSessionNameMissing = 'Session name missing';
SDatabaseOpen = 'Cannot perform this operation on an open database';
SDatabaseClosed = 'Cannot perform this operation on a closed database';
SDatabaseHandleSet = 'Database handle owned by a different session';
SSessionActive = 'Cannot perform this operation on an active session';
SHandleError = 'Error creating cursor handle';
SInvalidFloatField = 'Cannot convert field ''%s'' to a floating point value';
SInvalidIntegerField = 'Cannot convert field ''%s'' to an integer value';
STableMismatch = 'Source and destination tables are incompatible';
SFieldAssignError = 'Fields ''%s'' and ''%s'' are not assignment compatible';
SNoReferenceTableName = 'ReferenceTableName not specified for field ''%s''';
SCompositeIndexError = 'Cannot use array of Field values with Expression Indices';
SInvalidBatchMove = 'Invalid batch move parameters';
SEmptySQLStatement = 'No SQL statement available';
SNoParameterValue = 'No value for parameter ''%s''';
SNoParameterType = 'No parameter type for parameter ''%s''';
SLoginError = 'Cannot connect to database ''%s''';
SInitError = 'An error occurred while attempting to initialize the Borland Database Engine (error $%.4x)';
SDatasetDesigner = 'Fields E&ditor...';
SFKInternalCalc = '&InternalCalc';
SFKAggregate = '&Aggregate';
SDatabaseEditor = 'Database &Editor...';
SExplore = 'E&xplore';
SLinkDesigner = 'Field ''%s'', from the Detail Fields list, must be linked';
SLinkDetail = '''%s'' cannot be opened';
SLinkMasterSource = 'The MasterSource property of ''%s'' must be linked to a DataSource';
SLinkMaster = 'Unable to open the MasterSource Table';
SGQEVerb = '&SQL Builder...';
SBindVerb = 'Define &Parameters...';
SIDAPILangID = '0009';
SDisconnectDatabase = 'Database is currently connected. Disconnect and continue?';
SBDEError = 'BDE error $%.4x';
SLookupSourceError = 'Unable to use duplicate DataSource and LookupSource';
SLookupTableError = 'LookupSource must be connected to TTable component';
SLookupIndexError = '%s must be the lookup table''s active index';
SParameterTypes = ';Input;Output;Input/Output;Result';
SInvalidParamFieldType = 'Must have a valid field type selected';
STruncationError = 'Parameter ''%s'' truncated on output';
SDataTypes = ';String;SmallInt;Integer;Word;Boolean;Float;Currency;BCD;Date;Time;DateTime;;;;Blob;Memo;Graphic;;;;;Cursor;';
SResultName = 'Result';
SDBCaption = '%s%s%s Database';
SParamEditor = '%s%s%s Parameters';
SDatasetEditor = '%s%s%s';
SIndexFilesEditor = '%s%s%s Index Files';
SNoIndexFiles = '(None)';
SIndexDoesNotExist = 'Index does not exist. Index: %s';
SNoTableName = 'Missing TableName property';
SNoDataSetField = 'Missing DataSetField property';
SBatchExecute = 'E&xecute';
SNoCachedUpdates = 'Not in cached update mode';
SInvalidAliasName = 'Invalid alias name %s';
SDBGridColEditor = 'Co&lumns Editor...';
SNoFieldAccess = 'Cannot access field ''%s'' in a filter';
SUpdateSQLEditor = '&UpdateSQL Editor...';
SNoDataSet = 'No dataset association';
SUntitled = 'Untitled Application';
SUpdateWrongDB = 'Cannot update, %s is not owned by %s';
SUpdateFailed = 'Update failed';
SSQLGenSelect = 'Must select at least one key field and one update field';
SSQLNotGenerated = 'Update SQL statements not generated, exit anyway?';
SSQLDataSetOpen = 'Unable to determine field names for %s';
SLocalTransDirty = 'The transaction isolation level must be dirty read for local databases';
SPrimary = 'Primary';
SMissingDataSet = 'Missing DataSet property';
SNoProvider = 'No provider available';
SNotAQuery = 'Dataset is not a query';
implementation
end.
|
procedure initLexer();
begin
ch := input^;
get(input);
peek := input^;
end;
procedure getChar();
begin
get(input);
ch := peek;
peek := input^;
end;
procedure getToken();
type tstate = (start, readingid, readingstring, skip, finished, failed);
var
done : boolean;
i : integer;
state : tstate;
begin
done := false;
i := 0;
nextToken.text := '';
state := start;
while not done do
begin
case state of
start:
begin
case ch of
{ identifier }
'a'..'z','A'..'Z':
begin
state := readingid;
done := false;
nextToken.name := identifier;
nextToken.text[i] := ch;
i := i + 1;
end;
'''':
begin
state := readingstring;
done := false;
nextToken.name := characterstring;
end;
'(':
begin
nextToken.name := parenleft;
nextToken.text[0] := ch;
state := finished;
end;
')':
begin
nextToken.name := parenright;
nextToken.text[0] := ch;
state := finished;
end;
' ','!',chr(10),chr(13): state := skip;
';':
begin
nextToken.name := semicolon;
nextToken.text[0] := ch;
state := finished;
end;
',':
begin
nextToken.name := comma;
nextToken.text[0] := ch;
state := finished;
end;
'.':
begin
nextToken.name := period;
nextToken.text[0] := ch;
state := finished;
end;
end; {case ch}
end; {start:}
failed: done := true;
finished: begin
getchar;
done := true;
end;
skip:
begin
getchar;
state := start;
end;
readingid:
begin
state := failed;
getchar;
case ch of
'A'..'Z','a'..'z','0'..'9':
begin
nextToken.name := identifier;
nextToken.text[i] := ch;
i := i + 1;
state := readingid;
end;
end;
end;
readingstring:
begin
getchar;
if ch = '''' then
if peek = '''' then
begin
nextToken.text[i] := '''';
i := i + 1;
getchar;
state:= readingstring;
end
else
state := finished
else
begin
nextToken.text[i] := ch;
i := i + 1;
state := readingstring;
end;
end;
end;
end; {while}
end;
|
{**********************************************************************}
{* Иллюстрация к книге "OpenGL в проектах Delphi" *}
{* Краснов М.В. softgl@chat.ru *}
{**********************************************************************}
unit frmMain;
interface
uses
Windows, Messages, Classes, Graphics, Forms, ExtCtrls, Controls,
SysUtils, Dialogs,
OpenGL;
type
TfrmGL = class(TForm)
procedure FormCreate(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
DC: HDC;
hrc: HGLRC;
procedure SetDCPixelFormat;
protected
procedure WMPaint(var Msg: TWMPaint); message WM_PAINT;
end;
const
vertex : Array [0..5, 0..3, 0..2] of GLFloat = (
((-1.0,-1.0, 1.0),(-1.0, 1.0, 1.0),( 1.0,-1.0, 1.0),( 1.0, 1.0, 1.0)),
((-1.0, 1.0, 1.0),(-1.0, 1.0,-1.0),( 1.0, 1.0, 1.0),( 1.0, 1.0,-1.0)),
(( 1.0,-1.0, 1.0),( 1.0, 1.0, 1.0),( 1.0,-1.0,-1.0),( 1.0, 1.0,-1.0)),
(( 1.0,-1.0,-1.0),( 1.0, 1.0,-1.0),(-1.0,-1.0,-1.0),(-1.0, 1.0,-1.0)),
((-1.0,-1.0,-1.0),(-1.0,-1.0, 1.0),( 1.0,-1.0,-1.0),( 1.0,-1.0, 1.0)),
((-1.0,-1.0,-1.0),(-1.0, 1.0,-1.0),(-1.0,-1.0, 1.0),(-1.0, 1.0, 1.0)));
colors : Array [0..5, 0..2] of GLFloat = (
(1.0, 1.0, 1.0), (1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0),
(1.0, 1.0, 0.0), (0.0, 1.0, 1.0));
var
frmGL: TfrmGL;
implementation
{$R *.DFM}
{=======================================================================
Перерисовка окна}
procedure TfrmGL.WMPaint(var Msg: TWMPaint);
var
ps : TPaintStruct;
i : integer;
begin
BeginPaint(Handle, ps);
glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT);
glPushMatrix;
glTranslatef(0.0, 0.0, -5.0);
glRotatef(-45.0, 1.0, 0.0, 0.0);
glRotatef(45.0, 0.0, 1.0, 0.0);
For i := 0 to 5 do begin
glColor3fv(@colors[i][0]);
glBegin(GL_TRIANGLE_STRIP);
glVertex3fv (@vertex[i][0][0]);
glVertex3fv (@vertex[i][1][0]);
glVertex3fv (@vertex[i][2][0]);
glVertex3fv (@vertex[i][3][0]);
glEnd;
end;
glPopMatrix;
SwapBuffers(DC);
EndPaint(Handle, ps);
end;
{=======================================================================
Создание окна}
procedure TfrmGL.FormCreate(Sender: TObject);
begin
DC := GetDC(Handle);
SetDCPixelFormat;
hrc := wglCreateContext(DC);
wglMakeCurrent(DC, hrc);
glEnable(GL_DEPTH_TEST);// разрешаем тест глубины
glEnable(GL_LIGHTING); // разрешаем работу с освещенностью
glEnable(GL_LIGHT0); // включаем источник света 0
end;
{=======================================================================
Устанавливаем формат пикселей}
procedure TfrmGL.SetDCPixelFormat;
var
nPixelFormat: Integer;
pfd: TPixelFormatDescriptor;
begin
FillChar(pfd, SizeOf(pfd), 0);
pfd.dwFlags := PFD_DRAW_TO_WINDOW or
PFD_SUPPORT_OPENGL or
PFD_DOUBLEBUFFER;
nPixelFormat := ChoosePixelFormat(DC, @pfd);
SetPixelFormat(DC, nPixelFormat, @pfd);
end;
{=======================================================================
Изменение размеров окна}
procedure TfrmGL.FormResize(Sender: TObject);
begin
glViewport (0, 0, ClientWidth, ClientHeight);
glMatrixMode(GL_PROJECTION);
glLoadIdentity;
gluPerspective (45.0, ClientWidth / ClientHeight, 1.0, 100.0);
gluLookAt(0.0, 0.0, 0.0, 0.0, 0.0, -1.0, 0.0, 1.0, 0.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity;
glEnable(GL_DEPTH_TEST);
glEnable(GL_COLOR_MATERIAL);
InvalidateRect(Handle, nil, False);
end;
{=======================================================================
Конец работы программы}
procedure TfrmGL.FormDestroy(Sender: TObject);
begin
wglMakeCurrent(0, 0);
wglDeleteContext(hrc);
ReleaseDC(Handle, DC);
DeleteDC (DC);
end;
procedure TfrmGL.FormMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
var
Viewport : Array [0..3] of GLInt;
mvMatrix, ProjMatrix : Array [0..15] of GLDouble;
RealY : GLint ; // позиция OpenGL y - координаты
wx, wy, wz : GLdouble ; // возвращаемые мировые x, y, z координаты
Zval : GLfloat;
begin
glGetIntegerv (GL_VIEWPORT, @Viewport);
glGetDoublev (GL_MODELVIEW_MATRIX, @mvMatrix);
glGetDoublev (GL_PROJECTION_MATRIX, @ProjMatrix);
// viewport[3] - высота окна в пикселях
RealY := viewport[3] - Y - 1;
Caption := 'Координаты курсора ' + IntToStr (x) + ' ' +
FloatToStr (RealY);
glReadPixels(X, RealY, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, @Zval);
gluUnProject (X, RealY, Zval,
@mvMatrix, @ProjMatrix, @Viewport, wx, wy, wz);
ShowMessage ('Мировые координаты для z=' + FloatToStr(Zval)
+ ' : ' + chr (13) + '(' + FloatToStr(wx)
+ '; ' + FloatToStr(wy)
+ '; ' + FloatToStr(wz) + ')');
end;
procedure TfrmGL.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
If Key = VK_ESCAPE then Close;
end;
end.
|
unit ObjectMappingTests;
interface
uses
TestFramework,
DataBindingResultXML,
XMLDataBindingGenerator;
type
TTestXMLDataBindingGenerator = class(TXMLDataBindingGenerator)
protected
procedure GenerateDataBinding(); override;
end;
TObjectMappingTests = class(TAbstractTest, ITest)
private
FFileName: String;
protected
procedure RunTest(testResult: TTestResult); override;
procedure CompareSchemas(ATestResult: TTestResult; AGenerator: TTestXMLDataBindingGenerator; AResult: IXMLDataBindingResult);
procedure CompareItems(ATestResult: TTestResult; AGeneratorSchema: TXMLDataBindingSchema; AResultSchema: IXMLSchema);
// procedure CompareCollection(ATestResult: TTestResult; AGeneratorSchema: TXMLDataBindingSchema; AGeneratorItem: TXMLDataBindingCollection; AResultItem: IXMLItem);
property FileName: String read FFileName;
public
constructor Create(const AFileName: String);
class function Suite(): ITestSuite;
end;
implementation
uses
Contnrs,
SysUtils,
X2UtApp;
const
ExpectedExtension = '_expected.xml';
{ TObjectMappingTests }
class function TObjectMappingTests.Suite(): ITestSuite;
var
basePath: String;
fileInfo: TSearchRec;
begin
Result := TTestSuite.Create(Self.ClassName);
{ Add tests for all .xsd files which have a corresponding .expected file }
basePath := App.Path + 'Tests\Data\';
if FindFirst(basePath + '*.xsd', faAnyFile, fileInfo) = 0 then
begin
repeat
if FileExists(basePath + ChangeFileExt(fileInfo.Name, ExpectedExtension)) then
begin
Result.AddTest(Self.Create(basePath + fileInfo.Name));
end;
until FindNext(fileInfo) <> 0;
SysUtils.FindClose(fileInfo);
end;
end;
constructor TObjectMappingTests.Create(const AFileName: String);
begin
inherited Create(ChangeFileExt(ExtractFileName(AFileName), ''));
FFileName := AFileName;
end;
procedure TObjectMappingTests.RunTest(testResult: TTestResult);
var
generator: TTestXMLDataBindingGenerator;
expectedResult: IXMLDataBindingResult;
begin
generator := TTestXMLDataBindingGenerator.Create();
try
generator.Execute(FileName);
expectedResult := LoadDataBindingResult(ChangeFileExt(FileName, ExpectedExtension));
CompareSchemas(testResult, generator, expectedResult);
finally
FreeAndNil(generator);
end;
end;
procedure TObjectMappingTests.CompareSchemas(ATestResult: TTestResult; AGenerator: TTestXMLDataBindingGenerator; AResult: IXMLDataBindingResult);
var
handled: TObjectList;
schemaIndex: Integer;
resultSchema: IXMLSchema;
bindingSchema: TXMLDataBindingSchema;
begin
handled := TObjectList.Create(False);
try
{ Iterate expected schemas }
for schemaIndex := 0 to Pred(AResult.Schemas.Count) do
begin
resultSchema := AResult.Schemas[schemaIndex];
bindingSchema := AGenerator.FindSchema(resultSchema.Name);
if Assigned(bindingSchema) then
begin
handled.Add(bindingSchema);
CompareItems(ATestResult, bindingSchema, resultSchema);
end else
ATestResult.AddFailure(Self, nil, Format('Schema "%s" expected', [resultSchema.Name]));
end;
{ Find unexpected schemas }
for schemaIndex := 0 to Pred(AGenerator.SchemaCount) do
if handled.IndexOf(AGenerator.Schemas[schemaIndex]) = -1 then
begin
ATestResult.AddFailure(Self, nil, Format('Schema "%s" not expected', [AGenerator.Schemas[schemaIndex].SchemaName]));
end;
finally
FreeAndNil(handled);
end;
end;
procedure TObjectMappingTests.CompareItems(ATestResult: TTestResult; AGeneratorSchema: TXMLDataBindingSchema; AResultSchema: IXMLSchema);
function FindItem(const AResultItem: IXMLItem): TXMLDataBindingItem;
var
itemType: TXMLDataBindingItemType;
itemIndex: Integer;
item: TXMLDataBindingItem;
begin
Result := nil;
itemType := itInterface;
{if AResultItem.ItemType = 'Collection' then
itemType := itInterface
else }if AResultItem.ItemType = 'Enumeration' then
itemType := itEnumeration;
for itemIndex := 0 to Pred(AGeneratorSchema.ItemCount) do
begin
item := AGeneratorSchema.Items[itemIndex];
if (item.ItemType = itemType) and
(item.Name = AResultItem.Name) then
begin
Result := item;
break;
end;
end;
end;
var
handled: TObjectList;
itemIndex: Integer;
resultItem: IXMLItem;
bindingItem: TXMLDataBindingItem;
begin
handled := TObjectList.Create(False);
try
{ Iterate expected items }
for itemIndex := 0 to Pred(AResultSchema.Items.Count) do
begin
resultItem := AResultSchema.Items[itemIndex];
bindingItem := FindItem(resultItem);
if Assigned(bindingItem) then
begin
handled.Add(bindingItem);
// case bindingItem.ItemType of
// itInterface: CompareProperties;
// itCollection: CompareCollection(ATestResult, AGeneratorSchema, TXMLDataBindingCollection(bindingItem), resultItem);
// end;
end else
ATestResult.AddFailure(Self, nil, Format('Item "%s.%s" expected',
[AGeneratorSchema.SchemaName, resultItem.Name]));
end;
{ Find unexpected items }
for itemIndex := 0 to Pred(AGeneratorSchema.ItemCount) do
begin
// bindingItem := AGeneratorSchema.Items[itemIndex];
// if bindingItem.ItemType <> itForward then
// begin
// if handled.IndexOf(bindingItem) = -1 then
// begin
// ATestResult.AddFailure(Self, nil, Format('Item "%s.%s" not expected',
// [AGeneratorSchema.SchemaName,
// AGeneratorSchema.Items[itemIndex].Name]));
// end;
// end;
end;
finally
FreeAndNil(handled);
end;
end;
{
procedure TObjectMappingTests.CompareCollection(ATestResult: TTestResult; AGeneratorSchema: TXMLDataBindingSchema; AGeneratorItem: TXMLDataBindingCollection; AResultItem: IXMLItem);
begin
if Assigned(AGeneratorItem.CollectionItem) then
begin
if AGeneratorItem.CollectionItem.Name <> AResultItem.Collection.ItemName then
ATestResult.AddFailure(Self, nil, Format('Item "%s.%s": collection item "%s" expected but "%s" found',
[AGeneratorSchema.SchemaName,
AGeneratorItem.Name,
AResultItem.Collection.ItemName,
AGeneratorItem.CollectionItem.Name]));
end else
ATestResult.AddFailure(Self, nil, Format('Item "%s.%s": collection item not Assigned',
[AGeneratorSchema.SchemaName,
AGeneratorItem.Name]));
end;
}
{ TTestXMLDataBindingGenerator }
procedure TTestXMLDataBindingGenerator.GenerateDataBinding();
begin
end;
initialization
// RegisterTest(TObjectMappingTests.Suite);
end.
|
{*******************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ IBM XML DOM Implementation Wrapper }
{ }
{ Copyright (c) 2000 Borland Software Corporation }
{ }
{*******************************************************}
unit ibmxmldom;
interface
uses
{$IFDEF MSWINDOWS}
Windows,
{$ELSE}
Libc,
{$ENDIF}
SysUtils, xmldom;
type
{ TIBMDOMImplementationFactory }
TIBMDOMImplementationFactory = class(TDOMVendor)
private
FLibHandle: Integer;
public
destructor Destroy; override;
function DOMImplementation: IDOMImplementation; override;
function Description: String; override;
end;
var
IBMXML_DOM: TIBMDOMImplementationFactory;
implementation
const
{$IFDEF MSWINDOWS}
ModName = 'ibmxmldom.dll'; //!!!!!
{$ELSE}
ModName = 'libibmxmldom.so'; //!!!!!
function LoadLibrary(LibraryName: PChar): Integer;
begin
Result := Integer (dlopen(PChar(LibraryName), 0));
end;
function FreeLibrary(LibHandle: Integer): Integer;
begin
Result := dlclose(Pointer(LibHandle));
end;
function GetProcAddress(Handle: THandle; ProcName: PChar): Pointer;
begin
Result := dlsym(Pointer(Handle), ProcName);
end;
procedure RaiseLastWin32Error;
begin
Writeln(dlerror);
Assert(False);
end;
procedure SetEnvironmentVariable(Vname: PChar; Value: PChar);
begin
SetEnv(Vname, Value, 1);
end;
//TODO
procedure GetModuleFileName(LibHandle: Integer; NameBuf: PChar; len: Integer);
begin
NameBuf := '../../bin';
end;
{$ENDIF}
{ TIBMDOMImplementationFactory }
destructor TIBMDOMImplementationFactory.Destroy;
begin
if FLibHandle > 0 then
FreeLibrary(FLibHandle);
FLibHandle := 0;
end;
function TIBMDOMImplementationFactory.Description: String;
begin
Result := 'IBMXML';
end;
function TIBMDOMImplementationFactory.DOMImplementation: IDOMImplementation;
type
TGetDOMProc = procedure(var DOMImplementation: IDOMImplementation); stdcall;
var
GetDOMProc: TGetDOMProc;
NameBuf: string;
begin
if FLibHandle = 0 then
FLibHandle := LoadLibrary(ModName);
if FLibHandle = 0 then
RaiseLastWin32Error;
GetDOMProc := GetProcAddress(FLibHandle, 'GetDOMImplementation'); { Do not localize }
SetLength(NameBuf, MAX_PATH);
GetModuleFileName(FLibHandle, PChar(NameBuf), MAX_PATH);
Assert(Assigned(GetDOMProc));
SetEnvironmentVariable('ICU_DATA', PChar(ExtractFilePath(NameBuf))); // do not localize
GetDOMProc(Result);
end;
initialization
IBMXML_DOM := TIBMDOMImplementationFactory.Create;
RegisterDOMVendor(IBMXML_DOM);
finalization
UnRegisterDOMVendor(IBMXML_DOM);
IBMXML_DOM.Free;
end.
|
{$A+,B-,D+,E-,F-,G+,I+,L+,N+,O-,P-,Q-,R-,S-,T-,V+,X+,Y+}
{$M 16384,0,0}
{
by Behdad Esfahbod
Algorithmic Problems Book
April '2000
Problem 166 Backtrack Method
}
program
MapFold;
uses
FoldUnit;
type
TMove = record
L : Byte;
D : string[2];
end;
TMoves = array [1 .. 10] of TMove;
var
M, N : Integer;
M1, M2 : TMap;
Move : TMoves;
MNum : Integer;
I, J : Integer;
procedure ReadInput;
begin
Assign(Input, 'input.txt');
Reset(Input);
Readln(M);
Readln(N);
Readln(M2[1,1]);
M2[1,1,0] := Chr(M * N);
for I := 1 to M do
for J := 1 to N do
M1[I, J] := Chr((I - 1) * N + J - 1 + Ord('A'));
Close(Input);
end;
procedure NoSolution;
begin
Assign(Output, 'output');
ReWrite(Output);
Writeln('No Solution');
Close(Output);
end;
procedure Found;
begin
Assign(Output, 'output.txt');
ReWrite(Output);
for I := 1 to MNum do
with Move[I] do
Write(D[1], L, D[2], ' ');
Close(Output);
Halt;
end;
function Inverse (S : string) : string;
var I, J : Integer;
T : string;
begin
T[0] := S[0];
J := Length(S);
for I := 1 to J do
T[I] := S[J + 1 - I];
Inverse := T;
end;
{proc Fold(M1:TMap;var M2:TMap;B1,A1:Int;var B2,A2:Int;L:Int;D,W:Char);}
procedure BackTrack (var M : TMap; A, B : Integer);
var I, C, D : Integer;
Mp : TMap;
procedure Check;
begin
if Mp[1, 1] = M2[1, 1] then
Found;
end;
begin
for I := 1 to A do
for J := 1 to B do
if (Pos(M[I, J], M2[1, 1]) = 0) and
(Pos(Inverse(M[I, J]), M2[1, 1]) = 0) then
Exit;
Inc(MNum);
for I := 1 to B - 1 do
begin
Move[MNum].L := I;
Fold(M, Mp, A, B, C, D, I, 'V', 'L'); Move[MNum].D := 'VL';
if (C = 1) and (D = 1) then Check else BackTrack(Mp, C, D);
Fold(M, Mp, A, B, C, D, I, 'V', 'R'); Move[MNum].D := 'VR';
if (C = 1) and (D = 1) then Check else BackTrack(Mp, C, D);
end;
for I := 1 to A - 1 do
begin
Move[MNum].L := I;
Fold(M, Mp, A, B, C, D, I, 'H', 'L'); Move[MNum].D := 'HL';
if (C = 1) and (D = 1) then Check else BackTrack(Mp, C, D);
Fold(M, Mp, A, B, C, D, I, 'H', 'U'); Move[MNum].D := 'HU';
if (C = 1) and (D = 1) then Check else BackTrack(Mp, C, D);
end;
Dec(MNum);
end;
begin
ReadInput;
BackTrack(M1, M, N);
NoSolution;
end. |
unit uMain;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
Vcl.StdCtrls, uServer, Vcl.ComCtrls;
type
TServerForm = class(TForm)
labelUniqueName: TLabel;
editUniqueName: TEdit;
gbServer: TGroupBox;
labelDirName: TLabel;
editDirName: TEdit;
pbProgress: TProgressBar;
mLog: TMemo;
btnClose: TButton;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btnCloseClick(Sender: TObject);
private
{ Private declarations }
Server: TSharedMemoryServer;
procedure ServerCallback(const Msg: String; Percents: Integer;
IsError: Boolean);
public
{ Public declarations }
destructor Destroy(); override;
end;
var
ServerForm: TServerForm;
implementation
{$R *.dfm}
uses System.UITypes;
destructor TServerForm.Destroy();
begin
if Assigned(Server) then
FreeAndNil(Server);
inherited Destroy();
end;
procedure TServerForm.FormCreate(Sender: TObject);
begin
try
Server := TSharedMemoryServer.Create(ServerCallback);
editUniqueName.Text := Server.SharedMemoryName;
editDirName.Text := Server.DirName;
except
on E: Exception do
begin
MessageDlg(E.Message, mtError, [mbOk], 0);
Application.Terminate()
end;
end;
end;
procedure TServerForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Server.Terminated();
end;
procedure TServerForm.btnCloseClick(Sender: TObject);
begin
Close();
end;
procedure TServerForm.ServerCallback(const Msg: String; Percents: Integer;
IsError: Boolean);
begin
if IsError then
begin
MessageDlg(Format('Приложение будет завершено,' +
' так как произошла критическая ошибка: "%s"',
[Msg]), mtError, [mbOk], 0);
Close();
end else
begin
pbProgress.Position := Percents;
if Msg <> '' then
mLog.Lines.Add(Msg);
end;
Application.ProcessMessages();
end;
end.
|
(*************************************************************************
Cephes Math Library Release 2.8: June, 2000
Copyright by Stephen L. Moshier
Contributors:
* Sergey Bochkanov (ALGLIB project). Translation from C to
pseudocode.
See subroutines comments for additional copyrights.
>>> SOURCE LICENSE >>>
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 (www.fsf.org); either version 2 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
A copy of the GNU General Public License is available at
http://www.fsf.org/licensing/licenses
>>> END OF LICENSE >>>
*************************************************************************)
unit trigintegrals;
interface
uses Math, Sysutils, Ap;
procedure SineCosineIntegrals(X : AlglibFloat; var SI : AlglibFloat; var CI : AlglibFloat);
procedure HyperbolicSineCosineIntegrals(X : AlglibFloat;
var Shi : AlglibFloat;
var Chi : AlglibFloat);
implementation
procedure ChebIterationShiChi(x : AlglibFloat;
c : AlglibFloat;
var b0 : AlglibFloat;
var b1 : AlglibFloat;
var b2 : AlglibFloat);forward;
(*************************************************************************
Sine and cosine integrals
Evaluates the integrals
x
-
| cos t - 1
Ci(x) = eul + ln x + | --------- dt,
| t
-
0
x
-
| sin t
Si(x) = | ----- dt
| t
-
0
where eul = 0.57721566490153286061 is Euler's constant.
The integrals are approximated by rational functions.
For x > 8 auxiliary functions f(x) and g(x) are employed
such that
Ci(x) = f(x) sin(x) - g(x) cos(x)
Si(x) = pi/2 - f(x) cos(x) - g(x) sin(x)
ACCURACY:
Test interval = [0,50].
Absolute error, except relative when > 1:
arithmetic function # trials peak rms
IEEE Si 30000 4.4e-16 7.3e-17
IEEE Ci 30000 6.9e-16 5.1e-17
Cephes Math Library Release 2.1: January, 1989
Copyright 1984, 1987, 1989 by Stephen L. Moshier
*************************************************************************)
procedure SineCosineIntegrals(X : AlglibFloat; var SI : AlglibFloat; var CI : AlglibFloat);
var
Z : AlglibFloat;
C : AlglibFloat;
S : AlglibFloat;
F : AlglibFloat;
G : AlglibFloat;
Sg : AlglibInteger;
SN : AlglibFloat;
SD : AlglibFloat;
CN : AlglibFloat;
CD : AlglibFloat;
FN : AlglibFloat;
FD : AlglibFloat;
GN : AlglibFloat;
GD : AlglibFloat;
begin
if AP_FP_Less(x,0) then
begin
Sg := -1;
x := -x;
end
else
begin
Sg := 0;
end;
if AP_FP_Eq(x,0) then
begin
Si := 0;
Ci := -MaxRealNumber;
Exit;
end;
if AP_FP_Greater(x,1.0E9) then
begin
Si := 1.570796326794896619-cos(x)/x;
Ci := sin(x)/x;
Exit;
end;
if AP_FP_Less_Eq(X,4) then
begin
z := x*x;
SN := -8.39167827910303881427E-11;
SN := SN*z+4.62591714427012837309E-8;
SN := SN*z-9.75759303843632795789E-6;
SN := SN*z+9.76945438170435310816E-4;
SN := SN*z-4.13470316229406538752E-2;
SN := SN*z+1.00000000000000000302E0;
SD := 2.03269266195951942049E-12;
SD := SD*z+1.27997891179943299903E-9;
SD := SD*z+4.41827842801218905784E-7;
SD := SD*z+9.96412122043875552487E-5;
SD := SD*z+1.42085239326149893930E-2;
SD := SD*z+9.99999999999999996984E-1;
s := x*SN/SD;
CN := 2.02524002389102268789E-11;
CN := CN*z-1.35249504915790756375E-8;
CN := CN*z+3.59325051419993077021E-6;
CN := CN*z-4.74007206873407909465E-4;
CN := CN*z+2.89159652607555242092E-2;
CN := CN*z-1.00000000000000000080E0;
CD := 4.07746040061880559506E-12;
CD := CD*z+3.06780997581887812692E-9;
CD := CD*z+1.23210355685883423679E-6;
CD := CD*z+3.17442024775032769882E-4;
CD := CD*z+5.10028056236446052392E-2;
CD := CD*z+4.00000000000000000080E0;
c := z*CN/CD;
if Sg<>0 then
begin
s := -s;
end;
si := s;
ci := 0.57721566490153286061+Ln(x)+c;
Exit;
end;
s := sin(x);
c := cos(x);
z := 1.0/(x*x);
if AP_FP_Less(x,8) then
begin
FN := 4.23612862892216586994E0;
FN := FN*z+5.45937717161812843388E0;
FN := FN*z+1.62083287701538329132E0;
FN := FN*z+1.67006611831323023771E-1;
FN := FN*z+6.81020132472518137426E-3;
FN := FN*z+1.08936580650328664411E-4;
FN := FN*z+5.48900223421373614008E-7;
FD := 1.00000000000000000000E0;
FD := FD*z+8.16496634205391016773E0;
FD := FD*z+7.30828822505564552187E0;
FD := FD*z+1.86792257950184183883E0;
FD := FD*z+1.78792052963149907262E-1;
FD := FD*z+7.01710668322789753610E-3;
FD := FD*z+1.10034357153915731354E-4;
FD := FD*z+5.48900252756255700982E-7;
f := FN/(x*FD);
GN := 8.71001698973114191777E-2;
GN := GN*z+6.11379109952219284151E-1;
GN := GN*z+3.97180296392337498885E-1;
GN := GN*z+7.48527737628469092119E-2;
GN := GN*z+5.38868681462177273157E-3;
GN := GN*z+1.61999794598934024525E-4;
GN := GN*z+1.97963874140963632189E-6;
GN := GN*z+7.82579040744090311069E-9;
GD := 1.00000000000000000000E0;
GD := GD*z+1.64402202413355338886E0;
GD := GD*z+6.66296701268987968381E-1;
GD := GD*z+9.88771761277688796203E-2;
GD := GD*z+6.22396345441768420760E-3;
GD := GD*z+1.73221081474177119497E-4;
GD := GD*z+2.02659182086343991969E-6;
GD := GD*z+7.82579218933534490868E-9;
g := z*GN/GD;
end
else
begin
FN := 4.55880873470465315206E-1;
FN := FN*z+7.13715274100146711374E-1;
FN := FN*z+1.60300158222319456320E-1;
FN := FN*z+1.16064229408124407915E-2;
FN := FN*z+3.49556442447859055605E-4;
FN := FN*z+4.86215430826454749482E-6;
FN := FN*z+3.20092790091004902806E-8;
FN := FN*z+9.41779576128512936592E-11;
FN := FN*z+9.70507110881952024631E-14;
FD := 1.00000000000000000000E0;
FD := FD*z+9.17463611873684053703E-1;
FD := FD*z+1.78685545332074536321E-1;
FD := FD*z+1.22253594771971293032E-2;
FD := FD*z+3.58696481881851580297E-4;
FD := FD*z+4.92435064317881464393E-6;
FD := FD*z+3.21956939101046018377E-8;
FD := FD*z+9.43720590350276732376E-11;
FD := FD*z+9.70507110881952025725E-14;
f := FN/(x*FD);
GN := 6.97359953443276214934E-1;
GN := GN*z+3.30410979305632063225E-1;
GN := GN*z+3.84878767649974295920E-2;
GN := GN*z+1.71718239052347903558E-3;
GN := GN*z+3.48941165502279436777E-5;
GN := GN*z+3.47131167084116673800E-7;
GN := GN*z+1.70404452782044526189E-9;
GN := GN*z+3.85945925430276600453E-12;
GN := GN*z+3.14040098946363334640E-15;
GD := 1.00000000000000000000E0;
GD := GD*z+1.68548898811011640017E0;
GD := GD*z+4.87852258695304967486E-1;
GD := GD*z+4.67913194259625806320E-2;
GD := GD*z+1.90284426674399523638E-3;
GD := GD*z+3.68475504442561108162E-5;
GD := GD*z+3.57043223443740838771E-7;
GD := GD*z+1.72693748966316146736E-9;
GD := GD*z+3.87830166023954706752E-12;
GD := GD*z+3.14040098946363335242E-15;
g := z*GN/GD;
end;
si := 1.570796326794896619-f*c-g*s;
if sg<>0 then
begin
si := -si;
end;
ci := f*s-g*c;
end;
(*************************************************************************
Hyperbolic sine and cosine integrals
Approximates the integrals
x
-
| | cosh t - 1
Chi(x) = eul + ln x + | ----------- dt,
| | t
-
0
x
-
| | sinh t
Shi(x) = | ------ dt
| | t
-
0
where eul = 0.57721566490153286061 is Euler's constant.
The integrals are evaluated by power series for x < 8
and by Chebyshev expansions for x between 8 and 88.
For large x, both functions approach exp(x)/2x.
Arguments greater than 88 in magnitude return MAXNUM.
ACCURACY:
Test interval 0 to 88.
Relative error:
arithmetic function # trials peak rms
IEEE Shi 30000 6.9e-16 1.6e-16
Absolute error, except relative when |Chi| > 1:
IEEE Chi 30000 8.4e-16 1.4e-16
Cephes Math Library Release 2.8: June, 2000
Copyright 1984, 1987, 2000 by Stephen L. Moshier
*************************************************************************)
procedure HyperbolicSineCosineIntegrals(X : AlglibFloat;
var Shi : AlglibFloat;
var Chi : AlglibFloat);
var
k : AlglibFloat;
z : AlglibFloat;
c : AlglibFloat;
s : AlglibFloat;
a : AlglibFloat;
sg : AlglibInteger;
b0 : AlglibFloat;
b1 : AlglibFloat;
b2 : AlglibFloat;
begin
if AP_FP_Less(x,0) then
begin
sg := -1;
x := -x;
end
else
begin
sg := 0;
end;
if AP_FP_Eq(x,0) then
begin
Shi := 0;
Chi := -MaxRealNumber;
Exit;
end;
if AP_FP_Less(x,8.0) then
begin
z := x*x;
a := 1.0;
s := 1.0;
c := 0.0;
k := 2.0;
repeat
a := a*z/k;
c := c+a/k;
k := k+1.0;
a := a/k;
s := s+a/k;
k := k+1.0;
until AP_FP_Less(AbsReal(a/s),MachineEpsilon);
s := s*x;
end
else
begin
if AP_FP_Less(x,18.0) then
begin
a := (576.0/x-52.0)/10.0;
k := exp(x)/x;
b0 := 1.83889230173399459482E-17;
b1 := 0.0;
ChebIterationShiChi(a, -9.55485532279655569575E-17, b0, b1, b2);
ChebIterationShiChi(a, 2.04326105980879882648E-16, b0, b1, b2);
ChebIterationShiChi(a, 1.09896949074905343022E-15, b0, b1, b2);
ChebIterationShiChi(a, -1.31313534344092599234E-14, b0, b1, b2);
ChebIterationShiChi(a, 5.93976226264314278932E-14, b0, b1, b2);
ChebIterationShiChi(a, -3.47197010497749154755E-14, b0, b1, b2);
ChebIterationShiChi(a, -1.40059764613117131000E-12, b0, b1, b2);
ChebIterationShiChi(a, 9.49044626224223543299E-12, b0, b1, b2);
ChebIterationShiChi(a, -1.61596181145435454033E-11, b0, b1, b2);
ChebIterationShiChi(a, -1.77899784436430310321E-10, b0, b1, b2);
ChebIterationShiChi(a, 1.35455469767246947469E-9, b0, b1, b2);
ChebIterationShiChi(a, -1.03257121792819495123E-9, b0, b1, b2);
ChebIterationShiChi(a, -3.56699611114982536845E-8, b0, b1, b2);
ChebIterationShiChi(a, 1.44818877384267342057E-7, b0, b1, b2);
ChebIterationShiChi(a, 7.82018215184051295296E-7, b0, b1, b2);
ChebIterationShiChi(a, -5.39919118403805073710E-6, b0, b1, b2);
ChebIterationShiChi(a, -3.12458202168959833422E-5, b0, b1, b2);
ChebIterationShiChi(a, 8.90136741950727517826E-5, b0, b1, b2);
ChebIterationShiChi(a, 2.02558474743846862168E-3, b0, b1, b2);
ChebIterationShiChi(a, 2.96064440855633256972E-2, b0, b1, b2);
ChebIterationShiChi(a, 1.11847751047257036625E0, b0, b1, b2);
s := k*0.5*(b0-b2);
b0 := -8.12435385225864036372E-18;
b1 := 0.0;
ChebIterationShiChi(a, 2.17586413290339214377E-17, b0, b1, b2);
ChebIterationShiChi(a, 5.22624394924072204667E-17, b0, b1, b2);
ChebIterationShiChi(a, -9.48812110591690559363E-16, b0, b1, b2);
ChebIterationShiChi(a, 5.35546311647465209166E-15, b0, b1, b2);
ChebIterationShiChi(a, -1.21009970113732918701E-14, b0, b1, b2);
ChebIterationShiChi(a, -6.00865178553447437951E-14, b0, b1, b2);
ChebIterationShiChi(a, 7.16339649156028587775E-13, b0, b1, b2);
ChebIterationShiChi(a, -2.93496072607599856104E-12, b0, b1, b2);
ChebIterationShiChi(a, -1.40359438136491256904E-12, b0, b1, b2);
ChebIterationShiChi(a, 8.76302288609054966081E-11, b0, b1, b2);
ChebIterationShiChi(a, -4.40092476213282340617E-10, b0, b1, b2);
ChebIterationShiChi(a, -1.87992075640569295479E-10, b0, b1, b2);
ChebIterationShiChi(a, 1.31458150989474594064E-8, b0, b1, b2);
ChebIterationShiChi(a, -4.75513930924765465590E-8, b0, b1, b2);
ChebIterationShiChi(a, -2.21775018801848880741E-7, b0, b1, b2);
ChebIterationShiChi(a, 1.94635531373272490962E-6, b0, b1, b2);
ChebIterationShiChi(a, 4.33505889257316408893E-6, b0, b1, b2);
ChebIterationShiChi(a, -6.13387001076494349496E-5, b0, b1, b2);
ChebIterationShiChi(a, -3.13085477492997465138E-4, b0, b1, b2);
ChebIterationShiChi(a, 4.97164789823116062801E-4, b0, b1, b2);
ChebIterationShiChi(a, 2.64347496031374526641E-2, b0, b1, b2);
ChebIterationShiChi(a, 1.11446150876699213025E0, b0, b1, b2);
c := k*0.5*(b0-b2);
end
else
begin
if AP_FP_Less_Eq(x,88.0) then
begin
a := (6336.0/x-212.0)/70.0;
k := exp(x)/x;
b0 := -1.05311574154850938805E-17;
b1 := 0.0;
ChebIterationShiChi(a, 2.62446095596355225821E-17, b0, b1, b2);
ChebIterationShiChi(a, 8.82090135625368160657E-17, b0, b1, b2);
ChebIterationShiChi(a, -3.38459811878103047136E-16, b0, b1, b2);
ChebIterationShiChi(a, -8.30608026366935789136E-16, b0, b1, b2);
ChebIterationShiChi(a, 3.93397875437050071776E-15, b0, b1, b2);
ChebIterationShiChi(a, 1.01765565969729044505E-14, b0, b1, b2);
ChebIterationShiChi(a, -4.21128170307640802703E-14, b0, b1, b2);
ChebIterationShiChi(a, -1.60818204519802480035E-13, b0, b1, b2);
ChebIterationShiChi(a, 3.34714954175994481761E-13, b0, b1, b2);
ChebIterationShiChi(a, 2.72600352129153073807E-12, b0, b1, b2);
ChebIterationShiChi(a, 1.66894954752839083608E-12, b0, b1, b2);
ChebIterationShiChi(a, -3.49278141024730899554E-11, b0, b1, b2);
ChebIterationShiChi(a, -1.58580661666482709598E-10, b0, b1, b2);
ChebIterationShiChi(a, -1.79289437183355633342E-10, b0, b1, b2);
ChebIterationShiChi(a, 1.76281629144264523277E-9, b0, b1, b2);
ChebIterationShiChi(a, 1.69050228879421288846E-8, b0, b1, b2);
ChebIterationShiChi(a, 1.25391771228487041649E-7, b0, b1, b2);
ChebIterationShiChi(a, 1.16229947068677338732E-6, b0, b1, b2);
ChebIterationShiChi(a, 1.61038260117376323993E-5, b0, b1, b2);
ChebIterationShiChi(a, 3.49810375601053973070E-4, b0, b1, b2);
ChebIterationShiChi(a, 1.28478065259647610779E-2, b0, b1, b2);
ChebIterationShiChi(a, 1.03665722588798326712E0, b0, b1, b2);
s := k*0.5*(b0-b2);
b0 := 8.06913408255155572081E-18;
b1 := 0.0;
ChebIterationShiChi(a, -2.08074168180148170312E-17, b0, b1, b2);
ChebIterationShiChi(a, -5.98111329658272336816E-17, b0, b1, b2);
ChebIterationShiChi(a, 2.68533951085945765591E-16, b0, b1, b2);
ChebIterationShiChi(a, 4.52313941698904694774E-16, b0, b1, b2);
ChebIterationShiChi(a, -3.10734917335299464535E-15, b0, b1, b2);
ChebIterationShiChi(a, -4.42823207332531972288E-15, b0, b1, b2);
ChebIterationShiChi(a, 3.49639695410806959872E-14, b0, b1, b2);
ChebIterationShiChi(a, 6.63406731718911586609E-14, b0, b1, b2);
ChebIterationShiChi(a, -3.71902448093119218395E-13, b0, b1, b2);
ChebIterationShiChi(a, -1.27135418132338309016E-12, b0, b1, b2);
ChebIterationShiChi(a, 2.74851141935315395333E-12, b0, b1, b2);
ChebIterationShiChi(a, 2.33781843985453438400E-11, b0, b1, b2);
ChebIterationShiChi(a, 2.71436006377612442764E-11, b0, b1, b2);
ChebIterationShiChi(a, -2.56600180000355990529E-10, b0, b1, b2);
ChebIterationShiChi(a, -1.61021375163803438552E-9, b0, b1, b2);
ChebIterationShiChi(a, -4.72543064876271773512E-9, b0, b1, b2);
ChebIterationShiChi(a, -3.00095178028681682282E-9, b0, b1, b2);
ChebIterationShiChi(a, 7.79387474390914922337E-8, b0, b1, b2);
ChebIterationShiChi(a, 1.06942765566401507066E-6, b0, b1, b2);
ChebIterationShiChi(a, 1.59503164802313196374E-5, b0, b1, b2);
ChebIterationShiChi(a, 3.49592575153777996871E-4, b0, b1, b2);
ChebIterationShiChi(a, 1.28475387530065247392E-2, b0, b1, b2);
ChebIterationShiChi(a, 1.03665693917934275131E0, b0, b1, b2);
c := k*0.5*(b0-b2);
end
else
begin
if sg<>0 then
begin
shi := -MaxRealNumber;
end
else
begin
shi := MaxRealNumber;
end;
chi := MaxRealNumber;
Exit;
end;
end;
end;
if sg<>0 then
begin
s := -s;
end;
shi := s;
chi := 0.57721566490153286061+Ln(x)+c;
end;
procedure ChebIterationShiChi(x : AlglibFloat;
c : AlglibFloat;
var b0 : AlglibFloat;
var b1 : AlglibFloat;
var b2 : AlglibFloat);
begin
b2 := b1;
b1 := b0;
b0 := x*b1-b2+c;
end;
end. |
unit WinTestColors;
{$mode objfpc}{$H+}
interface
uses
SysUtils, Forms, Graphics, ColorBox, StdCtrls, ExtCtrls, FpcUnit, TestRegistry;
type
TTest_Colors = class(TTestCase)
published
procedure TestColors;
end;
{ TWndTestColors }
TWndTestColors = class(TForm)
BlendTestButton: TButton;
BlendColor1: TColorBox;
BlendColor2: TColorBox;
BlendValue: TEdit;
GroupBox1: TGroupBox;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
LabelBlended: TLabel;
LabelColor2: TLabel;
LabelColor1: TLabel;
PanelBlend: TPanel;
procedure BlendTestButtonClick(Sender: TObject);
end;
implementation
{$R *.lfm}
uses
OriGraphics;
procedure TTest_Colors.TestColors;
begin
with TWndTestColors.Create(nil) do
try
ShowModal;
finally
Free;
end;
end;
procedure TWndTestColors.BlendTestButtonClick(Sender: TObject);
var
Blended: TColor;
Color1: TColor;
Color2: TColor;
Value: Integer;
begin
Color1 := BlendColor1.Selected;
Color2 := BlendColor2.Selected;
Value := StrToInt(BlendValue.Text);
Blended := Blend(Color1, Color2, Value);
PanelBlend.Color := Blended;
LabelColor1.Caption := IntToHex(Color1, 8) + #13 + IntToStr(Color1);
LabelColor2.Caption := IntToHex(Color2, 8) + #13 + IntToStr(Color2);
LabelBlended.Caption := IntToHex(Blended, 8) + #13 + IntToStr(Blended);
end;
initialization
RegisterTest(TTest_Colors);
end.
|
{
"RTC Gate Streamer Link"
- Copyright 2004-2017 (c) RealThinClient.com (http://www.realthinclient.com)
@exclude
}
unit rtcXGateStream;
interface
{$include rtcDefs.inc}
uses
Classes,
SysUtils,
rtcTypes,
rtcConn,
rtcGateConst,
rtcGateCli,
rtcXGateCIDs;
type
TRtcGMLinkUserStatusChange = procedure(Sender:TObject; UserID:TGateUID) of object;
TRtcGMLinkUserStatus = (scu_Unknown, scu_OffLine, scu_Passive, scu_Invited, scu_Active);
{ @Abstract(RTC Gate Streamer Link)
Link this component to a TRtcHttpGateClient to handle Group Streaming events. }
{$IFDEF IDE_XE2up}
[ComponentPlatformsAttribute(pidAll)]
{$ENDIF}
TRtcGateStreamerLink = class(TRtcAbsGateClientLink)
private
FOnSendingStart: TNotifyEvent;
FOnSendingPause: TNotifyEvent;
FOnSendingIdle: TNotifyEvent;
FOnUserStatusChange: TRtcGMLinkUserStatusChange;
protected
InviteKey: RtcByteArray;
StreamWasReset:boolean;
LastPackRecv,
LastPackSent:word;
SendingFirst,
SendingPaused,
SendingStream:boolean;
// @exclude
procedure Call_AfterLogOut(Sender:TRtcConnection); override;
// @exclude
procedure Call_OnDataReceived(Sender:TRtcConnection); override;
// @exclude
procedure Call_OnInfoReceived(Sender:TRtcConnection); override;
// @exclude
procedure Call_OnReadyToSend(Sender:TRtcConnection); override;
// @exclude
procedure Call_OnStreamReset(Sender:TRtcConnection); override;
// @exclude
procedure SetClient(const Value: TRtcHttpGateClient); override;
procedure DoDataFilter(Client:TRtcHttpGateClient; Data:TRtcGateClientData; var Wanted:boolean);
procedure DoDataReceived(Client:TRtcHttpGateClient; Data:TRtcGateClientData; var WantGUI, WantBackThread:boolean);
procedure DoDataReceivedGUI(Client:TRtcHttpGateClient; Data:TRtcGateClientData);
procedure DoInfoFilter(Client:TRtcHttpGateClient; Data:TRtcGateClientData; var Wanted:boolean);
procedure DoInfoReceivedGUI(Client:TRtcHttpGateClient; Data:TRtcGateClientData);
procedure ConfirmPackSent;
procedure UpdateLastPackRecv;
function LastPackDiff:word;
procedure AddAllDisabledUsers;
procedure InviteAllDisabledUsers;
function MakeRandomKey(GID:TGateUID; len:integer):RtcByteArray;
function CompareKeys(const OrigKey,RecvKey:RtcByteArray):boolean;
function IsMyPackage(Data:TRtcGateClientData):boolean;
function IsControlPackage(Data:TRtcGateClientData):boolean;
protected
cid_GroupInvite:word; // needs to be assigned the Group Invitation ID !!!
procedure DoSendStart; virtual; // initialize the sending process
procedure DoSendNext; virtual; // ready to send the next package
procedure DoSendStop; virtual; // stop the sending process
public
constructor Create(AOwner:TComponent); override;
destructor Destroy; override;
function UserInviteToGroup(UserID:TGateUID):boolean;
function UserKickFromGroup(UserID:TGateUID):boolean;
function UserEnableControl(UserID:TGateUID):boolean;
function UserDisableControl(UserID:TGateUID):boolean;
function IsUserInControl(UserID:TGateUID):boolean;
function CheckUserStatus(UserID:TGateUID):TRtcGMLinkUserStatus;
procedure UpdateUserStatus(UserID: TGateUID);
function ConnectedUsers:integer;
procedure StartMyGroup;
procedure PauseSending;
procedure ResumeSending;
property NowSending:boolean read SendingStream;
property NowPaused:boolean read SendingPaused;
property InviteCallID:word read cid_GroupInvite write cid_GroupInvite;
published
property OnSendingPaused:TNotifyEvent read FOnSendingPause write FOnSendingPause;
property OnSendingIdle:TNotifyEvent read FOnSendingIdle write FOnSendingIdle;
property OnSendingActive:TNotifyEvent read FOnSendingStart write FOnSendingStart;
property OnUserStatusChange:TRtcGMLinkUserStatusChange read FOnUserStatusChange write FOnUserStatusChange;
end;
implementation
{ TRtcGateStreamerLink }
constructor TRtcGateStreamerLink.Create(AOwner: TComponent);
begin
inherited;
SetLength(InviteKey,0);
LastPackSent:=0;
LastPackRecv:=0;
SendingFirst:=True;
SendingStream:=True;
SendingPaused:=True;
end;
destructor TRtcGateStreamerLink.Destroy;
begin
Client:=nil;
inherited;
end;
function TRtcGateStreamerLink.MakeRandomKey(GID:TGateUID; len:integer):RtcByteArray;
var
a:integer;
b:byte;
begin
SetLength(Result,len+1);
Result[0]:=GID;
for a:=1 to length(Result)-1 do
begin
b:=random(255);
Result[a]:=b;
end;
end;
function TRtcGateStreamerLink.CompareKeys(const OrigKey,RecvKey:RtcByteArray):boolean;
var
a:integer;
begin
if length(OrigKey)>length(RecvKey) then
Result:=False
else
begin
Result:=True;
for a:=0 to length(OrigKey)-1 do
if OrigKey[a]<>RecvKey[a] then
begin
Result:=False;
Break;
end;
end;
end;
procedure TRtcGateStreamerLink.Call_AfterLogOut(Sender: TRtcConnection);
begin
if Client=nil then Exit;
if not Sender.inMainThread then
begin
Sender.Sync(Call_AfterLogOut);
Exit;
end;
LastPackSent:=0;
LastPackRecv:=0;
SendingFirst:=True;
Groups.ClearAllStates;
if SendingStream then
begin
SendingStream:=False;
SendingPaused:=True;
if assigned(FOnSendingPause) then
FOnSendingPause(self);
end;
end;
procedure TRtcGateStreamerLink.DoDataFilter(Client: TRtcHttpGateClient; Data: TRtcGateClientData; var Wanted: boolean);
begin
case Data.CallID of
cid_GroupAccept:
if Data.Footer then
Wanted:=(Data.ToGroupID=MyGroupID) and (Groups.GetStatus(Data.UserID,0)=4)
else if Data.Header then
Data.ToBuffer:=(Data.ToGroupID=MyGroupID) and (Groups.GetStatus(Data.UserID,0)=4);
cid_GroupConfirmRecv:
if Data.Footer then
Wanted:=IsMyPackage(Data) and (length(Data.Content)=2)
else if Data.Header then
Data.ToBuffer:=IsMyPackage(Data);
end;
end;
procedure TRtcGateStreamerLink.DoDataReceived(Client: TRtcHttpGateClient; Data: TRtcGateClientData; var WantGUI, WantBackThread: boolean);
procedure ProcessPackOK;
var
lr:word;
begin
if LastPackSent>0 then
begin
lr:=Bytes2Word(Data.Content);
Groups.SetStatus(Data.UserID,2,lr);
UpdateLastPackRecv;
end;
end;
begin
case Data.CallID of
cid_GroupAccept: WantGUI:=True;
cid_GroupConfirmRecv: ProcessPackOK;
end;
end;
procedure TRtcGateStreamerLink.DoDataReceivedGUI(Client: TRtcHttpGateClient; Data: TRtcGateClientData);
procedure ProcessAccept;
begin
// Invitation Key is correct?
if CompareKeys(InviteKey, Data.Content) then
begin
SendingPaused:=True;
Groups.SetStatus(Data.UserID,0,5);
if Groups.GetStatus(Data.UserID,1)>0 then
Groups.SetStatus(Data.UserID,1,5);
Groups.ClearStatus(Data.UserID,2);
UpdateLastPackRecv;
UpdateUserStatus(Data.UserID);
AddUserToGroup(Data.UserID);
if SendingStream then
if assigned(FOnSendingStart) then
FOnSendingStart(self);
SendingPaused:=False;
if (Client<>nil) and
(SendingPaused=False) and
(SendingStream=True) then
begin
SendingFirst:=True;
DoSendNext;
end;
end;
end;
begin
case Data.CallID of
cid_GroupAccept: ProcessAccept;
end;
end;
procedure TRtcGateStreamerLink.Call_OnDataReceived(Sender: TRtcConnection);
begin
if Filter(DoDataFilter,Sender) then
Call(DoDataReceived,DoDataReceivedGUI,Sender);
inherited;
end;
procedure TRtcGateStreamerLink.DoInfoFilter(Client: TRtcHttpGateClient; Data: TRtcGateClientData; var Wanted: boolean);
begin
case Data.Command of
gc_UserOffline:
Wanted:=Groups.GetMinStatus(Data.UserID)>0;
gc_UserLeft:
Wanted:=(Data.GroupID=MyGroupID) and (Groups.GetStatus(Data.UserID,0)>0);
gc_UserJoined:
Wanted:=(Data.GroupID=MyGroupID) and (Groups.GetStatus(Data.UserID,0)=5);
end;
end;
procedure TRtcGateStreamerLink.DoInfoReceivedGUI(Client: TRtcHttpGateClient; Data: TRtcGateClientData);
begin
case Data.Command of
gc_UserOffline:
begin
if Groups.GetStatus(Data.UserID,0)>=4 then
begin
Groups.SetStatus(Data.UserID,0,4);
if Groups.GetStatus(Data.UserID,1)>1 then
Groups.SetStatus(Data.UserID,1,4);
Groups.ClearStatus(Data.UserID,2);
end
else
begin
Groups.SetStatus(Data.UserID,0,1);
if Groups.GetStatus(Data.UserID,1)>1 then
Groups.SetStatus(Data.UserID,1,1);
Groups.ClearStatus(Data.UserID,2);
end;
Groups.ClearStatus(Data.UserID,3); // offline
UpdateLastPackRecv;
UpdateUserStatus(Data.UserID);
end;
gc_UserLeft:
begin
if Groups.GetStatus(Data.UserID,0)>=4 then
begin
Groups.SetStatus(Data.UserID,0,4);
if Groups.GetStatus(Data.UserID,1)>0 then
Groups.SetStatus(Data.UserID,1,4);
Groups.ClearStatus(Data.UserID,2);
end
else
begin
Groups.SetStatus(Data.UserID,0,1);
if Groups.GetStatus(Data.UserID,1)>0 then
Groups.SetStatus(Data.UserID,1,1);
Groups.ClearStatus(Data.UserID,2);
end;
UpdateLastPackRecv;
UpdateUserStatus(Data.UserID);
if ConnectedUsers=0 then
begin
if SendingStream then
begin
SendingPaused:=True;
if assigned(FOnSendingIdle) then
FOnSendingIdle(self);
end;
end;
end;
gc_UserJoined:
begin
Groups.SetStatus(Data.UserID,0,10);
Groups.ClearStatus(Data.UserID,2);
Groups.SetStatus(Data.UserID,3,2); // online, active
if Groups.GetStatus(Data.UserID,1)>0 then
begin
Groups.SetStatus(Data.UserID,1,10);
SendBytes(Data.UserID,MyGroupID,cid_GroupAllowControl);
end;
UpdateLastPackRecv;
UpdateUserStatus(Data.UserID);
end;
end;
end;
procedure TRtcGateStreamerLink.Call_OnInfoReceived(Sender: TRtcConnection);
begin
if Filter(DoInfoFilter,Sender) then
CallGUI(DoInfoReceivedGUI,Sender);
inherited;
end;
procedure TRtcGateStreamerLink.Call_OnReadyToSend(Sender: TRtcConnection);
begin
if (Client=nil) or (MyGroupID=0) then Exit;
if StreamWasReset then
begin
StreamWasReset:=False;
InviteAllDisabledUsers;
end;
if (Client<>nil) and
(SendingPaused=False) and
(SendingStream=True) then
DoSendNext;
end;
procedure TRtcGateStreamerLink.Call_OnStreamReset(Sender: TRtcConnection);
var
UID,GID,GST:TGateUID;
begin
if (Client=nil) or (MyGroupID=0) then Exit;
if not Sender.inMainThread then
begin
Sender.Sync(Call_OnStreamReset);
Exit;
end;
if SendingStream then
begin
SendingPaused:=True;
if assigned(FOnSendingIdle) then
FOnSendingIdle(self);
end;
StreamWasReset:=True;
UID:=0; GID:=0;
repeat
GST:=Groups.GetNextStatus(UID,GID);
if (GID=0) and (GST>=4) then
begin
Groups.SetStatus(UID,0,4);
if Groups.GetStatus(UID,1)>4 then
Groups.SetStatus(UID,1,4);
Groups.ClearStatus(UID,2);
UpdateUserStatus(UID);
end;
until GST=0;
UpdateLastPackRecv;
end;
procedure TRtcGateStreamerLink.SetClient(const Value: TRtcHttpGateClient);
begin
if Value=Client then Exit;
if assigned(Client) then
begin
SendingStream:=False;
SendingPaused:=True;
DoSendStop;
if MyGroupID>0 then
if assigned(Client) then
begin
if Client.Ready then
begin
AddAllDisabledUsers;
SendToGroup(cid_GroupClosed);
end;
end;
end;
inherited;
end;
procedure TRtcGateStreamerLink.StartMyGroup;
begin
if length(InviteKey)=0 then
begin
InviteKey:=MakeRandomKey(MyGroupID, 16);
SendingStream:=True;
SendingPaused:=True;
DoSendStart;
end;
end;
procedure TRtcGateStreamerLink.UpdateLastPackRecv;
var
UID,GID,GST,Result:TGateUID;
overflow:boolean;
begin
overflow:=LastPackSent<LastPackRecv;
Result:=0;
UID:=0; GID:=0;
repeat
GST:=Groups.GetNextStatus(UID,GID);
if (GST>0) and (GID=2) then
begin
if Result=0 then
Result:=GST
else if overflow then
begin
if (GST>=LastPackSent) and (GST>Result) then
Result:=GST;
end
else
begin
if (GST<=LastPackSent) and (GST<Result) then
Result:=GST;
end;
end;
until GST=0;
if Result>0 then
LastPackRecv:=Result;
end;
procedure TRtcGateStreamerLink.UpdateUserStatus(UserID: TGateUID);
begin
if assigned(FOnUserStatusChange) then
FOnUserStatusChange(self,UserID);
end;
function TRtcGateStreamerLink.ConnectedUsers: integer;
var
UID,GID,GST:TGateUID;
begin
Result:=0;
UID:=0; GID:=0;
repeat
GST:=Groups.GetNextStatus(UID,GID);
if (GID=0) and (GST=10) then
Inc(Result);
until GST=0;
end;
procedure TRtcGateStreamerLink.InviteAllDisabledUsers;
var
UID,GID,GST:TGateUID;
begin
if MyGroupID=0 then Exit;
UID:=0; GID:=0;
repeat
GST:=Groups.GetNextStatus(UID,GID);
if (GID=0) and (GST>=3) then
UserInviteToGroup(UID);
until GST=0;
end;
procedure TRtcGateStreamerLink.AddAllDisabledUsers;
var
UID,GID,GST:TGateUID;
begin
if MyGroupID=0 then Exit;
UID:=0; GID:=0;
repeat
GST:=Groups.GetNextStatus(UID,GID);
if (GID=0) and (GST>0) and (GST<10) then
AddUserToGroup(UID);
until GST=0;
end;
function TRtcGateStreamerLink.LastPackDiff:word;
begin
if LastPackSent>0 then
begin
if LastPackRecv<=LastPackSent then
Result:=LastPackSent-LastPackRecv
else // full synchronize on overflow
Result:=65535;
end
else
Result:=0;
end;
function TRtcGateStreamerLink.UserInviteToGroup(UserID: TGateUID):boolean;
begin
Result:=False;
if (Client=nil) or (UserID<MinUserID) or (UserID>MaxUserID) then Exit;
if not Client.Ready then Exit;
if Groups.GetStatus(UserID,0)<10 then
begin
StartMyGroup;
Groups.SetStatus(UserID,0,4);
if Groups.GetStatus(UserID,1)>0 then
Groups.SetStatus(UserID,1,4);
Groups.ClearStatus(UserID,2);
Groups.SetStatus(UserID,3,1); // invited
UpdateLastPackRecv;
UpdateUserStatus(UserID);
SendBytes(UserID,MyGroupID,cid_GroupInvite,InviteKey);
PingUser(UserID);
Result:=True;
end;
end;
function TRtcGateStreamerLink.UserKickFromGroup(UserID: TGateUID): boolean;
begin
Result:=False;
if (Client=nil) or (MyGroupID=0) then Exit;
if Groups.GetStatus(UserID,0)>=4 then
begin
Groups.SetStatus(UserID,0,1);
if Groups.GetStatus(UserID,1)>=4 then
Groups.SetStatus(UserID,1,1);
Groups.ClearStatus(UserID,2);
UpdateLastPackRecv;
UpdateUserStatus(UserID);
RemoveUserFromGroup(UserID);
PingUser(UserID);
Result:=True;
end;
end;
function TRtcGateStreamerLink.UserDisableControl(UserID: TGateUID): boolean;
begin
Result:=False;
if (Client=nil) or (MyGroupID=0) then Exit;
if Groups.GetStatus(UserID,1)>0 then
begin
Groups.ClearStatus(UserID,1);
UpdateUserStatus(UserID);
if Groups.GetStatus(UserID,0)>=5 then
begin
SendBytes(UserID,MyGroupID,cid_GroupDisallowControl);
PingUser(UserID);
end;
Result:=True;
end;
end;
function TRtcGateStreamerLink.UserEnableControl(UserID: TGateUID): boolean;
begin
Result:=False;
if (Client=nil) or (MyGroupID=0) then Exit;
if (Groups.GetStatus(UserID,0)>0) and
(Groups.GetStatus(UserID,1)=0) then
begin
Groups.SetStatus(UserID,1,Groups.GetStatus(UserID,0));
UpdateLastPackRecv;
UpdateUserStatus(UserID);
if Groups.GetStatus(UserID,0)>=5 then
begin
SendBytes(UserID,MyGroupID,cid_GroupAllowControl);
PingUser(UserID);
end;
Result:=True;
end;
end;
procedure TRtcGateStreamerLink.PauseSending;
begin
SendingStream:=False;
SendingPaused:=False;
end;
procedure TRtcGateStreamerLink.ResumeSending;
begin
SendingStream:=True;
SendingPaused:=ConnectedUsers=0;
if SendingPaused=False then
if MyGroupID>0 then
if assigned(Client) then
DoSendNext;
end;
function TRtcGateStreamerLink.IsUserInControl(UserID: TGateUID): boolean;
begin
Result := Groups.GetStatus(UserID,1)>0;
end;
function TRtcGateStreamerLink.CheckUserStatus(UserID: TGateUID): TRtcGMLinkUserStatus;
begin
if Groups.GetStatus(UserID,3)=0 then
begin
if Groups.GetStatus(UserID,0)>0 then
Result:=scu_OffLine
else
Result:=scu_Unknown;
end
else
case Groups.GetStatus(UserID,0) of
1..3: Result:=scu_Passive;
4..9: Result:=scu_Invited;
10: Result:=scu_Active;
else Result:=scu_Unknown;
end;
end;
procedure TRtcGateStreamerLink.ConfirmPackSent;
begin
if Client=nil then Exit;
if Client.Ready then
begin
if LastPackSent<64000 then
Inc(LastPackSent)
else
LastPackSent:=1;
SendToGroup(cid_GroupConfirmSend,Word2Bytes(LastPackSent));
end;
end;
function TRtcGateStreamerLink.IsControlPackage(Data:TRtcGateClientData): boolean;
begin
Result:=(Data.ToGroupID=MyGroupID) and
(Groups.GetStatus(Data.UserID,1)>=5);
end;
function TRtcGateStreamerLink.IsMyPackage(Data:TRtcGateClientData): boolean;
begin
Result:=(Data.ToGroupID=MyGroupID) and
(Groups.GetStatus(Data.UserID,0)>=5);
end;
procedure TRtcGateStreamerLink.DoSendStart;
begin
// Initialize Streaming components
end;
procedure TRtcGateStreamerLink.DoSendNext;
begin
// Ready to Stream the Next Package
end;
procedure TRtcGateStreamerLink.DoSendStop;
begin
// Deinitialize Streaming components
end;
end.
|
{*****************************************}
{ TeeChart Pro }
{ Copyright (c) 1996-2004 David Berneda }
{ }
{ TPyramid Series }
{*****************************************}
unit TeePyramid;
{$I TeeDefs.inc}
interface
Uses Classes, TeEngine;
type
TPyramidSeries=class(TChartSeries)
private
FSize : Integer;
Function AcumUpTo(UpToIndex:Integer):Double;
procedure SetSize(const Value: Integer);
protected
Procedure CalcHorizMargins(Var LeftMargin,RightMargin:Integer); override;
class Function GetEditorClass:String; override;
Procedure DrawMark( ValueIndex:Integer; Const St:String;
APosition:TSeriesMarkPosition); override;
Procedure DrawValue(ValueIndex:Integer); override;
public
Constructor Create(AOwner:TComponent); override;
Function DrawValuesForward:Boolean; override;
Function MaxXValue:Double; override;
Function MinXValue:Double; override;
Function MaxYValue:Double; override;
Function MinYValue:Double; override;
published
property Active;
property Brush;
property ColorEachPoint default True;
property ColorSource;
property Cursor;
property Depth;
property HorizAxis;
property Marks;
property ParentChart;
property DataSource;
property Pen;
property PercentFormat;
property SeriesColor;
property ShowInLegend;
property SizePercent:Integer read FSize write SetSize default 50;
property Title;
property ValueFormat;
property VertAxis;
property XLabelsSource;
property XValues;
property YValues;
{ events }
property AfterDrawValues;
property BeforeDrawValues;
property OnAfterAdd;
property OnBeforeAdd;
property OnClearValues;
property OnClick;
property OnDblClick;
property OnGetMarkText;
property OnMouseEnter;
property OnMouseLeave;
end;
implementation
Uses {$IFNDEF LINUX}
Windows,
{$ENDIF}
Chart, TeeConst, TeeProCo, TeCanvas
{$IFDEF CLX}
, QGraphics, Types
{$ELSE}
, Graphics
{$ENDIF};
{ TPyramidSeries }
constructor TPyramidSeries.Create(AOwner: TComponent);
begin
inherited;
CalcVisiblePoints:=False;
ColorEachPoint:=True;
FSize:=50;
end;
procedure TPyramidSeries.CalcHorizMargins(var LeftMargin,
RightMargin: Integer);
begin
LeftMargin:=20;
RightMargin:=20;
end;
Function TPyramidSeries.AcumUpTo(UpToIndex:Integer):Double;
var t : Integer;
begin
result:=0;
for t:=0 to UpToIndex do result:=result+MandatoryValueList.Value[t];
end;
procedure TPyramidSeries.DrawValue(ValueIndex: Integer);
var tmp : Double;
tmpTrunc : Double;
tmpTruncZ : Double;
tmpZ2 : Integer;
tmpZ : Integer;
tmpX : Integer;
R : TRect;
tmpSize : Integer;
begin
if not IsNull(ValueIndex) then
begin
ParentChart.SetBrushCanvas(ValueColor[ValueIndex],Brush,Brush.Color);
ParentChart.Canvas.AssignVisiblePen(Pen);
tmp:=AcumUpTo(ValueIndex-1);
tmpTrunc:=100.0-(tmp*100.0/MandatoryValueList.Total);
tmpSize:=Round(SizePercent*GetHorizAxis.IAxisSize*0.005);
tmpX:=Round(tmpTrunc*tmpSize*0.01);
R.Left:=GetHorizAxis.CalcPosValue(MinXValue)-tmpX;
R.Right:=R.Left+2*tmpX;
tmpTruncZ:=100.0-tmpTrunc;
if tmpTruncZ>0 then tmpZ:=Round(tmpTruncZ*(EndZ-StartZ)*0.005)
else tmpZ:=0;
R.Bottom:=GetVertAxis.CalcPosValue(tmp);
tmp:=tmp+MandatoryValueList.Value[ValueIndex];
R.Top:=GetVertAxis.CalcPosValue(tmp);
tmpTrunc:=100.0-(tmp*100.0/MandatoryValueList.Total);
if tmpTrunc<100 then tmpZ2:=Round(tmpTrunc*(EndZ-StartZ)*0.005)
else tmpZ2:=0;
ParentChart.Canvas.PyramidTrunc(R,StartZ+tmpZ,EndZ-tmpZ,
Round(tmpTrunc*tmpSize*0.01),
tmpZ2);
end;
end;
function TPyramidSeries.MaxXValue: Double;
begin
result:=MinXValue;
end;
function TPyramidSeries.MaxYValue: Double;
begin
result:=MandatoryValueList.TotalABS
end;
function TPyramidSeries.MinXValue: Double;
begin
result:=ParentChart.SeriesList.IndexOf(Self);
end;
function TPyramidSeries.MinYValue: Double;
begin
result:=0;
end;
procedure TPyramidSeries.SetSize(const Value: Integer);
begin
SetIntegerProperty(FSize,Value);
end;
class function TPyramidSeries.GetEditorClass: String;
begin
result:='TPyramidSeriesEditor';
end;
procedure TPyramidSeries.DrawMark(ValueIndex: Integer; const St: String;
APosition: TSeriesMarkPosition);
begin
APosition.LeftTop.Y:=GetVertAxis.CalcPosValue(AcumUpTo(ValueIndex));
inherited;
end;
function TPyramidSeries.DrawValuesForward: Boolean;
begin
result:=not GetVertAxis.Inverted;
end;
initialization
RegisterTeeSeries(TPyramidSeries,
{$IFNDEF CLR}@{$ENDIF}TeeMsg_GalleryPyramid,
{$IFNDEF CLR}@{$ENDIF}TeeMsg_GalleryExtended,2);
finalization
UnRegisterTeeSeries([TPyramidSeries]);
end.
|
{
Union-Find Data Structure
Operations:
Init(N): Initialize list for use with N records
Union(X, Y): Merge groups of X and Y
Find(X): Return the group of a X
Reference:
Creative, p80-83
By Ali
}
program
UnionFind;
const
MaxN = 10000 + 2;
var
List: array[1 .. MaxN] of record
P: Integer; {Parent (= 0 for roots)}
S: Integer; {Size of group (= 0 for non-roots)}
end;
procedure Init(N: Integer);
var
i: Integer;
begin
FillChar(List, SizeOf(List), 0);
for i := 1 to N do
List[i].S := 1;
end;
function Find(a: Integer): Integer;
var
i, j: Integer;
begin
i := a;
while List[i].P <> 0 do
i := List[i].p;
while (a <> i) do
begin
j := List[a].P;
List[a].P := i;
a := j;
end;
Find := i;
end;
procedure Union(a, b: Integer);
var
i, j: Integer;
begin
a := Find(a);
b := Find(b);
if (a = b) then
Exit;
if List[b].S > List[a].S then
begin
i := a; a := b; b := i;
end;
Inc(List[a].S, List[b].S);
List[b].S := 0;
List[b].P := a;
end;
begin
Init(2);
Union(1, 2);
Writeln(Find(2));
end.
|
{*******************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ }
{ Copyright (c) 1995,2002 Borland Software Corporation }
{ }
{*******************************************************}
unit GraphUtil;
interface
{$IFDEF MSWINDOWS}
uses Windows, Graphics;
{$ENDIF}
{$IFDEF LINUX}
uses Types, QGraphics;
{$ENDIF}
type
TScrollDirection = (sdLeft, sdRight, sdUp, sdDown);
TArrowType = (atSolid, atArrows);
{ GetHighLightColor and GetShadowColor take a Color and calculate an
"appropriate" highlight/shadow color for that value. If the color's
saturation is beyond 220 then it's lumination is decreased rather than
increased. Since these routines may be called repeatedly for (potentially)
the same color value they cache the results of the previous call. }
function GetHighLightColor(const Color: TColor; Luminance: Integer = 19): TColor;
function GetShadowColor(const Color: TColor; Luminance: Integer = -50): TColor;
{ Draws checkmarks of any Size at Location with/out a shadow. }
procedure DrawCheck(ACanvas: TCanvas; Location: TPoint; Size: Integer;
Shadow: Boolean = True);
{ Draws arrows that look like ">" which can point in any TScrollDirection }
procedure DrawChevron(ACanvas: TCanvas; Direction: TScrollDirection;
Location: TPoint; Size: Integer);
{ Draws a solid triangular arrow that can point in any TScrollDirection }
procedure DrawArrow(ACanvas: TCanvas; Direction: TScrollDirection;
Location: TPoint; Size: Integer);
{ The following routines mimic the like named routines from Shlwapi.dll except
these routines do not rely on any specific version of IE being installed. }
{ Calculates Hue, Luminance and Saturation for the clrRGB value }
procedure ColorRGBToHLS(clrRGB: COLORREF; var Hue, Luminance, Saturation: Word);
{ Calculates a color given Hue, Luminance and Saturation values }
function ColorHLSToRGB(Hue, Luminance, Saturation: Word): TColorRef;
{ Given a color and a luminance change "n" this routine returns a color whose
luminace has been changed accordingly. }
function ColorAdjustLuma(clrRGB: TColor; n: Integer; fScale: BOOL): TColor;
implementation
uses Classes, Math;
const
ArrowPts: array[TScrollDirection, 0..2] of TPoint =
(((X:1; Y:0), (X:0; Y:1), (X:1; Y:2)),
((X:0; Y:0), (X:1; Y:1), (X:0; Y:2)),
((X:0; Y:1), (X:1; Y:0), (X:2; Y:1)),
((X:0; Y:0), (X:1; Y:1), (X:2; Y:0)));
threadvar
CachedRGBToHLSclrRGB: COLORREF;
CachedRGBToHLSHue: WORD;
CachedRGBToHLSLum: WORD;
CachedRGBToHLSSat: WORD;
{-----------------------------------------------------------------------
References:
1) J. Foley and a.van Dam, "Fundamentals of Interactive Computer Graphics",
Addison-Wesley (IBM Systems Programming Series), Reading, MA, 664 pp., 1982.
2) MSDN online HOWTO: Converting Colors Between RGB and HLS (HBS)
http://support.microsoft.com/support/kb/articles/Q29/2/40.ASP
SUMMARY
The code fragment below converts colors between RGB (Red, Green, Blue) and
HLS/HBS (Hue, Lightness, Saturation/Hue, Brightness, Saturation).
http://lists.w3.org/Archives/Public/www-style/1997Dec/0182.html
http://www.math.clemson.edu/~rsimms/neat/math/hlsrgb.pas
-----------------------------------------------------------------------}
const
HLSMAX = 240; // H,L, and S vary over 0-HLSMAX
RGBMAX = 255; // R,G, and B vary over 0-RGBMAX
// HLSMAX BEST IF DIVISIBLE BY 6
// RGBMAX, HLSMAX must each fit in a byte.
{ Hue is undefined if Saturation is 0 (grey-scale)
This value determines where the Hue scrollbar is
initially set for achromatic colors }
HLSUndefined = (HLSMAX*2/3);
procedure ColorRGBToHLS(clrRGB: COLORREF; var Hue, Luminance, Saturation: Word);
var
H, L, S: Double;
R, G, B: Word;
cMax, cMin: Double;
Rdelta, Gdelta, Bdelta: Extended; { intermediate value: % of spread from max }
begin
if clrRGB = CachedRGBToHLSclrRGB then
begin
Hue := CachedRGBToHLSHue;
Luminance := CachedRGBToHLSLum;
Saturation := CachedRGBToHLSSat;
exit;
end;
R := GetRValue(clrRGB);
G := GetGValue(clrRGB);
B := GetBValue(clrRGB);
{ calculate lightness }
cMax := Math.Max(Math.Max(R, G), B);
cMin := Math.Min(Math.Min(R, G), B);
L := ( ((cMax + cMin) * HLSMAX) + RGBMAX ) / ( 2 * RGBMAX);
if cMax = cMin then { r=g=b --> achromatic case }
begin { saturation }
Hue := Round(HLSUndefined);
// pwHue := 160; { MS's ColorRGBToHLS always defaults to 160 in this case }
Luminance := Round(L);
Saturation := 0;
end
else { chromatic case }
begin
{ saturation }
if L <= HLSMAX/2 then
S := ( ((cMax-cMin)*HLSMAX) + ((cMax+cMin)/2) ) / (cMax+cMin)
else
S := ( ((cMax-cMin)*HLSMAX) + ((2*RGBMAX-cMax-cMin)/2) ) / (2*RGBMAX-cMax-cMin);
{ hue }
Rdelta := ( ((cMax-R)*(HLSMAX/6)) + ((cMax-cMin)/2) ) / (cMax-cMin);
Gdelta := ( ((cMax-G)*(HLSMAX/6)) + ((cMax-cMin)/2) ) / (cMax-cMin);
Bdelta := ( ((cMax-B)*(HLSMAX/6)) + ((cMax-cMin)/2) ) / (cMax-cMin);
if (R = cMax) then
H := Bdelta - Gdelta
else if (G = cMax) then
H := (HLSMAX/3) + Rdelta - Bdelta
else // B == cMax
H := ((2 * HLSMAX) / 3) + Gdelta - Rdelta;
if (H < 0) then
H := H + HLSMAX;
if (H > HLSMAX) then
H := H - HLSMAX;
Hue := Round(H);
Luminance := Round(L);
Saturation := Round(S);
end;
CachedRGBToHLSclrRGB := clrRGB;
CachedRGBToHLSHue := Hue;
CachedRGBToHLSLum := Luminance;
CachedRGBToHLSSat := Saturation;
end;
function HueToRGB(Lum, Sat, Hue: Double): Integer;
var
ResultEx: Double;
begin
{ range check: note values passed add/subtract thirds of range }
if (hue < 0) then
hue := hue + HLSMAX;
if (hue > HLSMAX) then
hue := hue - HLSMAX;
{ return r,g, or b value from this tridrant }
if (hue < (HLSMAX/6)) then
ResultEx := Lum + (((Sat-Lum)*hue+(HLSMAX/12))/(HLSMAX/6))
else if (hue < (HLSMAX/2)) then
ResultEx := Sat
else if (hue < ((HLSMAX*2)/3)) then
ResultEx := Lum + (((Sat-Lum)*(((HLSMAX*2)/3)-hue)+(HLSMAX/12))/(HLSMAX/6))
else
ResultEx := Lum;
Result := Round(ResultEx);
end;
function ColorHLSToRGB(Hue, Luminance, Saturation: Word): TColorRef;
function RoundColor(Value: Double): Integer;
begin
if Value > 255 then
Result := 255
else
Result := Round(Value);
end;
var
R,G,B: Double; { RGB component values }
Magic1,Magic2: Double; { calculated magic numbers (really!) }
begin
if (Saturation = 0) then
begin { achromatic case }
R := (Luminance * RGBMAX)/HLSMAX;
G := R;
B := R;
if (Hue <> HLSUndefined) then
;{ ERROR }
end
else
begin { chromatic case }
{ set up magic numbers }
if (Luminance <= (HLSMAX/2)) then
Magic2 := (Luminance * (HLSMAX + Saturation) + (HLSMAX/2)) / HLSMAX
else
Magic2 := Luminance + Saturation - ((Luminance * Saturation) + (HLSMAX/2)) / HLSMAX;
Magic1 := 2 * Luminance - Magic2;
{ get RGB, change units from HLSMAX to RGBMAX }
R := (HueToRGB(Magic1,Magic2,Hue+(HLSMAX/3))*RGBMAX + (HLSMAX/2))/HLSMAX;
G := (HueToRGB(Magic1,Magic2,Hue)*RGBMAX + (HLSMAX/2)) / HLSMAX;
B := (HueToRGB(Magic1,Magic2,Hue-(HLSMAX/3))*RGBMAX + (HLSMAX/2))/HLSMAX;
end;
Result := RGB(RoundColor(R), RoundColor(G), RoundColor(B));
end;
threadvar
CachedHighlightLum: Integer;
CachedHighlightColor,
CachedHighlight: TColor;
CachedShadowLum: Integer;
CachedShadowColor,
CachedShadow: TColor;
CachedColorValue: Integer;
CachedLumValue: Integer;
CachedColorAdjustLuma: TColor;
function ColorAdjustLuma(clrRGB: TColor; n: Integer; fScale: BOOL): TColor;
var
H, L, S: Word;
begin
if (clrRGB = CachedColorValue) and (n = CachedLumValue) then
Result := CachedColorAdjustLuma
else
begin
ColorRGBToHLS(ColorToRGB(clrRGB), H, L, S);
Result := TColor(ColorHLSToRGB(H, L + n, S));
CachedColorValue := clrRGB;
CachedLumValue := n;
CachedColorAdjustLuma := Result;
end;
end;
function GetHighLightColor(const Color: TColor; Luminance: Integer): TColor;
var
H, L, S: Word;
Clr: Cardinal;
begin
if (Color = CachedHighlightColor) and (Luminance = CachedHighlightLum) then
Result := CachedHighlight
else
begin
// Case for default luminance
if (Color = clBtnFace) and (Luminance = 19) then
Result := clBtnHighlight
else
begin
Clr := ColorToRGB(Color);
ColorRGBToHLS(Clr, H, L, S);
if S > 220 then
Result := ColorHLSToRGB(H, L - Luminance, S)
else
Result := TColor(ColorAdjustLuma(Clr, Luminance, False));
CachedHighlightLum := Luminance;
CachedHighlightColor := Color;
CachedHighlight := Result;
end;
end;
end;
function GetShadowColor(const Color: TColor; Luminance: Integer): TColor;
var
H, L, S: Word;
Clr: Cardinal;
begin
if (Color = CachedShadowColor) and (Luminance = CachedShadowLum) then
Result := CachedShadow
else
begin
// Case for default luminance
if (Color = clBtnFace) and (Luminance = -50) then
Result := clBtnShadow
else
begin
Clr := ColorToRGB(Color);
ColorRGBToHLS(Clr, H, L, S);
if S >= 160 then
Result := ColorHLSToRGB(H, L + Luminance, S)
else
Result := TColor(ColorAdjustLuma(Clr, Luminance, False));
end;
CachedShadowLum := Luminance;
CachedShadowColor := Color;
CachedShadow := Result;
end;
end;
{ Utility Drawing Routines }
procedure DrawArrow(ACanvas: TCanvas; Direction: TScrollDirection;
Location: TPoint; Size: Integer);
var
I: Integer;
Pts: array[0..2] of TPoint;
OldWidth: Integer;
OldColor: TColor;
begin
if ACanvas = nil then exit;
OldColor := ACanvas.Brush.Color;
ACanvas.Brush.Color := ACanvas.Pen.Color;
Move(ArrowPts[Direction], Pts, SizeOf(Pts));
for I := 0 to 2 do
Pts[I] := Point(Pts[I].x * Size + Location.X, Pts[I].y * Size + Location.Y);
with ACanvas do
begin
OldWidth := Pen.Width;
Pen.Width := 1;
Polygon(Pts);
Pen.Width := OldWidth;
Brush.Color := OldColor;
end;
end;
procedure DrawChevron(ACanvas: TCanvas; Direction: TScrollDirection;
Location: TPoint; Size: Integer);
procedure DrawLine;
var
I: Integer;
Pts: array[0..2] of TPoint;
begin
Move(ArrowPts[Direction], Pts, SizeOf(Pts));
// Scale to the correct size
for I := 0 to 2 do
Pts[I] := Point(Pts[I].X * Size + Location.X, Pts[I].Y * Size + Location.Y);
case Direction of
sdDown : Pts[2] := Point(Pts[2].X + 1, Pts[2].Y - 1);
sdRight: Pts[2] := Point(Pts[2].X - 1, Pts[2].Y + 1);
sdUp,
sdLeft : Pts[2] := Point(Pts[2].X + 1, Pts[2].Y + 1);
end;
ACanvas.PolyLine(Pts);
end;
var
OldWidth: Integer;
begin
if ACanvas = nil then exit;
OldWidth := ACanvas.Pen.Width;
ACanvas.Pen.Width := 1;
case Direction of
sdLeft, sdRight:
begin
Dec(Location.x, Size);
DrawLine;
Inc(Location.x);
DrawLine;
Inc(Location.x, 3);
DrawLine;
Inc(Location.x);
DrawLine;
end;
sdUp, sdDown:
begin
Dec(Location.y, Size);
DrawLine;
Inc(Location.y);
DrawLine;
Inc(Location.y, 3);
DrawLine;
Inc(Location.y);
DrawLine;
end;
end;
ACanvas.Pen.Width := OldWidth;
end;
procedure DrawCheck(ACanvas: TCanvas; Location: TPoint; Size: Integer;
Shadow: Boolean = True);
var
PR: TPenRecall;
begin
if ACanvas = nil then exit;
PR := TPenRecall.Create(ACanvas.Pen);
try
ACanvas.Pen.Width := 1;
ACanvas.PolyLine([
Point(Location.X, Location.Y),
Point(Location.X + Size, Location.Y + Size),
Point(Location.X + Size * 2 + Size, Location.Y - Size),
Point(Location.X + Size * 2 + Size, Location.Y - Size - 1),
Point(Location.X + Size, Location.Y + Size - 1),
Point(Location.X - 1, Location.Y - 2)]);
if Shadow then
begin
ACanvas.Pen.Color := clWhite;
ACanvas.PolyLine([
Point(Location.X - 1, Location.Y - 1),
Point(Location.X - 1, Location.Y),
Point(Location.X, Location.Y + 1),
Point(Location.X + Size, Location.Y + Size + 1),
Point(Location.X + Size * 2 + Size + 1, Location.Y - Size),
Point(Location.X + Size * 2 + Size + 1, Location.Y - Size - 1),
Point(Location.X + Size * 2 + Size + 1, Location.Y - Size - 2)]);
end;
finally
PR.Free;
end;
end;
initialization
CachedHighlightLum := 0;
CachedHighlightColor := 0;
CachedHighlight := 0;
CachedShadowLum := 0;
CachedShadowColor := 0;
CachedShadow := 0;
CachedColorValue := 0;
CachedLumValue := 0;
CachedColorAdjustLuma := 0;
end.
|
{**********************************************************************}
{* Иллюстрация к книге "OpenGL в проектах Delphi" *}
{* Краснов М.В. softgl@chat.ru *}
{**********************************************************************}
{/*
* decal.c
* Brad Grantham, 1997
*
* Demonstrates how to use the stencil buffer to produce decals on
* co-planar surfaces.
*/}
unit frmMain;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, Menus, OpenGL;
type
TfrmGL = class(TForm)
PopupMenu1: TPopupMenu;
turnonstencildecal1: TMenuItem;
visiblebuffer1: TMenuItem;
Colorbuffer1: TMenuItem;
Stencilbuffer1: TMenuItem;
Depthbuffre1: TMenuItem;
Finishframeafter1: TMenuItem;
Clearingscreen1: TMenuItem;
Drawingairplane1: TMenuItem;
Drawingground1: TMenuItem;
Drawingasphalt1: TMenuItem;
Drawingpaint1: TMenuItem;
Drawingshadow1: TMenuItem;
procedure FormCreate(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure FormMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure FormMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure FormMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure turnonstencildecal1Click(Sender: TObject);
procedure Colorbuffer1Click(Sender: TObject);
procedure Stencilbuffer1Click(Sender: TObject);
procedure Depthbuffre1Click(Sender: TObject);
procedure Clearingscreen1Click(Sender: TObject);
private
DC: HDC;
hrc: HGLRC;
procedure SetDCPixelFormat;
procedure Init;
procedure pushOrthoView(left, right, bottom, top, znear, zfar : GLfloat);
procedure popView;
procedure copyDepthToColor(whichColorBuffer : GLenum);
procedure copyStencilToColor(whichColorBuffer : GLenum);
procedure setupLight;
procedure setupNormalDrawingState;
procedure setupDecalState(decalNum : GLint);
procedure setupBasePolygonState(maxDecal : GLint);
procedure drawStripes;
procedure drawAsphalt;
procedure drawGround;
procedure drawAirplane;
protected
procedure WMPaint(var Msg: TWMPaint); message WM_PAINT;
end;
const
winWidth = 400;
winHeight = 400;
var
depthSave : Array [0..winWidth * winHeight-1] of GLfloat;
colorSave : Array [0..3*winWidth * winHeight-1] of GLUbyte;
stencilSave : Array [0..winWidth * winHeight-1] of GLUbyte;
quadric : GLUquadricObj;
Down : Boolean = False;
ox : GLint;
oy : GLint;
ang : GLfloat = 0;
sheight : GLfloat = 10;
useStencil : Boolean = True;
stage : GLint = 6;
dataChoice : (DCOLOR, DEPTH, STENCIL) = DCOLOR;
numStripes : GLint = 5;
stripeGap : GLfloat = 0.66;
var
frmGL: TfrmGL;
implementation
{$R *.DFM}
procedure TfrmGL.pushOrthoView(left, right, bottom, top, znear, zfar : GLfloat);
begin
glPushMatrix;
glLoadIdentity;
glMatrixMode(GL_PROJECTION);
glPushMatrix;
glLoadIdentity;
glOrtho(left, right, bottom, top, znear, zfar);
end;
procedure TfrmGL.popView;
begin
glPopMatrix;
glMatrixMode(GL_MODELVIEW);
glPopMatrix;
end;
procedure TfrmGL.copyDepthToColor(whichColorBuffer : GLenum);
var
x, y : GLint;
max, min : GLfloat;
previousColorBuffer : GLint;
begin
glReadPixels(0, 0, winWidth, winHeight, GL_DEPTH_COMPONENT, GL_FLOAT,
@depthSave);
//* I'm sure this could be done much better with OpenGL */
max := 0;
min := 1;
For y := 0 to winHeight - 1 do
For x := 0 to winWidth - 1 do begin
If (depthSave[winWidth * y + x] < min)
then min := depthSave[winWidth * y + x];
If (depthSave[winWidth * y + x] > max) and (depthSave[winWidth * y + x] < 0.999)
then max := depthSave[winWidth * y + x];
end;
For y := 0 to winHeight - 1 do
For x := 0 to winWidth - 1 do
If (depthSave[winWidth * y + x] <= max)
then depthSave[winWidth * y + x] := 1 - (depthSave[winWidth * y + x] - min) / (max - min)
else depthSave[winWidth * y + x] := 0;
pushOrthoView(0, 1, 0, 1, 0, 1);
glRasterPos3f(0, 0, -0.5);
glDisable(GL_DEPTH_TEST);
glDisable(GL_STENCIL_TEST);
glColorMask(TRUE, TRUE, TRUE, TRUE);
glGetIntegerv(GL_DRAW_BUFFER, @previousColorBuffer);
glDrawBuffer(whichColorBuffer);
glDrawPixels(winWidth, winHeight, GL_LUMINANCE , GL_FLOAT, @depthSave);
glDrawBuffer(previousColorBuffer);
glEnable(GL_DEPTH_TEST);
popView;
end;
const
colors : Array [0..6, 0..2] of Byte =
(
(255, 0, 0), //* red *//
(255, 218, 0), //* yellow *//
(72, 255, 0), //* yellowish green *//
(0, 255, 145), //* bluish cyan *//
(0, 145, 255), //* cyanish blue *//
(72, 0, 255), //* purplish blue *//
(255, 0, 218) //* reddish purple *//
);
procedure TfrmGL.copyStencilToColor(whichColorBuffer : GLenum);
var
x, y : GLint;
previousColorBuffer : GLint;
stencilValue : GLint;
begin
glReadPixels(0, 0, winWidth, winHeight, GL_STENCIL_INDEX, GL_UNSIGNED_BYTE,
@stencilSave);
//* I'm sure this could be done much better with OpenGL */
For y := 0 to winHeight - 1 do
For x := 0 to winWidth - 1 do begin
stencilValue := stencilSave [winWidth * y + x];
colorSave[(winWidth * y + x) * 3 + 0] := colors[stencilValue mod 7][0];
colorSave[(winWidth * y + x) * 3 + 1] := colors[stencilValue mod 7][1];
colorSave[(winWidth * y + x) * 3 + 2] := colors[stencilValue mod 7][2];
end;
pushOrthoView(0, 1, 0, 1, 0, 1);
glRasterPos3f(0, 0, -0.5);
glDisable(GL_DEPTH_TEST);
glDisable(GL_STENCIL_TEST);
glColorMask(TRUE, TRUE, TRUE, TRUE);
glGetIntegerv(GL_DRAW_BUFFER, @previousColorBuffer);
glDrawBuffer(whichColorBuffer);
glDrawPixels(winWidth, winHeight, GL_RGB, GL_UNSIGNED_BYTE, @colorSave);
glDrawBuffer(previousColorBuffer);
glEnable(GL_DEPTH_TEST);
popView;
end;
procedure TfrmGL.Init;
begin
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
quadric := gluNewQuadric;
glMatrixMode(GL_PROJECTION);
glFrustum(-0.33, 0.33, -0.33, 0.33, 0.5, 40);
glMatrixMode(GL_MODELVIEW);
gluLookAt(-4, 10, 6, 0, 0, 0, 0, 1, 0);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_NORMALIZE);
{ /*
* only need this to clear stencil and only need to clear stencil
* when you're looking at it; the algorithm works without it.
*/}
glClearStencil(5);
end;
procedure TfrmGL.setupLight;
const
lightpos : Array [0..3] of GLfloat = (0, 1, 0, 0);
begin
glLightfv(GL_LIGHT0, GL_POSITION, @lightpos);
end;
procedure TfrmGL.setupNormalDrawingState;
begin
glDisable(GL_STENCIL_TEST);
glEnable(GL_DEPTH_TEST);
glDepthMask(TRUE);
end;
procedure TfrmGL.setupBasePolygonState(maxDecal : GLint);
begin
glEnable(GL_DEPTH_TEST);
If useStencil then begin
glEnable(GL_STENCIL_TEST);
glStencilFunc(GL_ALWAYS, maxDecal + 1, $ff);
glStencilOp(GL_KEEP, GL_REPLACE, GL_ZERO);
end
end;
procedure TfrmGL.setupDecalState(decalNum : GLint);
begin
If useStencil then begin
glDisable(GL_DEPTH_TEST);
glDepthMask(FALSE);
glEnable(GL_STENCIL_TEST);
glStencilFunc(GL_GREATER, decalNum, $ff);
glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
end
end;
procedure TfrmGL.drawAirplane;
const
airplaneColor : Array [0..3] of GLfloat = (0.75, 0.75, 0.75, 1);
begin
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, @airplaneColor);
glDisable(GL_CULL_FACE);
glPushMatrix;
glTranslatef(0, 0, -2.5);
gluCylinder(quadric, 0.5, 0.5, 5, 10, 10);
glPushMatrix;
glTranslatef(0, 0, 5);
gluCylinder(quadric, 0.5, 0, 1, 10, 10);
glPopMatrix;
glPushMatrix;
glTranslatef(0, 0, 3);
glScalef(3, 0.1, 1);
gluSphere(quadric, 1, 10, 10);
glPopMatrix;
glPushMatrix;
glTranslatef(0, 0, 0.5);
glScalef(2, 0.1, 0.5);
gluSphere(quadric, 1, 10, 10);
glPopMatrix;
glEnable(GL_CULL_FACE);
glBegin(GL_TRIANGLES);
glNormal3f(1, 0, 0);
glVertex3f(0, 1.5, 0);
glVertex3f(0, 0.5, 1);
glVertex3f(0, 0.5, 0);
glNormal3f(-1, 0, 0);
glVertex3f(0, 1.5, 0);
glVertex3f(0, 0.5, 0);
glVertex3f(0, 0.5, 1);
glEnd;
glDisable(GL_CULL_FACE);
glRotatef(180, 0, 1, 0);
gluDisk(quadric, 0, 0.5, 10, 10);
glPopMatrix;
glEnable(GL_CULL_FACE);
end;
procedure TfrmGL.drawGround;
const
groundColor : Array [0..3] of GLfloat = (0.647, 0.165, 0.165, 1);
begin
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, @groundColor);
glBegin(GL_QUADS);
glNormal3i(0, 1, 0);
glVertex3f(10, 0, 10);
glVertex3f(10, 0, -10);
glVertex3f(-10, 0, -10);
glVertex3f(-10, 0, 10);
glEnd;
end;
procedure TfrmGL.drawAsphalt;
const
asphaltColor : Array [0..3] of GLfloat = (0.25, 0.25, 0.25, 1);
begin
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, @asphaltColor);
glBegin(GL_QUADS);
glNormal3i(0, 1, 0);
glVertex3f(5, 0, 9.5);
glVertex3f(5, 0, -9.5);
glVertex3f(-5, 0, -9.5);
glVertex3f(-5, 0, 9.5);
glEnd;
end;
procedure TfrmGL.drawStripes;
const
stripeColor : Array [0..3] of GLfloat = (1, 1, 0, 1);
var
i : GLint;
stripeLength : GLfloat;
begin
stripeLength := (16 - stripeGap * (numStripes - 1)) / numStripes;
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, @stripeColor);
glBegin(GL_QUADS);
glNormal3i(0, 1, 0);
glVertex3f(4.5, 0, 8.5);
glVertex3f(4.5, 0, -8.5);
glVertex3f(3.5, 0, -8.5);
glVertex3f(3.5, 0, 8.5);
glVertex3f(-3.5, 0, 8.5);
glVertex3f(-3.5, 0, -8.5);
glVertex3f(-4.5, 0, -8.5);
glVertex3f(-4.5, 0, 8.5);
For i := 0 to numStripes - 1 do begin
glVertex3f(0.5, 0, 8 - i * (stripeLength + stripeGap));
glVertex3f(0.5, 0, 8 - i * (stripeLength + stripeGap) - stripeLength);
glVertex3f(-0.5, 0, 8 - i * (stripeLength + stripeGap) - stripeLength);
glVertex3f(-0.5, 0, 8 - i * (stripeLength + stripeGap));
end;
glEnd;
end;
procedure TfrmGL.WMPaint(var Msg: TWMPaint);
var
ps : TPaintStruct;
label
doneWithFrame;
begin
BeginPaint(Handle, ps);
glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT);
//* Only need this If you care to look at the stencil buffer */
If dataChoice = STENCIL
then glClear(GL_STENCIL_BUFFER_BIT);
glPushMatrix;
glScalef(0.5, 0.5, 0.5);
If stage = 1
then goto doneWithFrame;
setupLight;
setupNormalDrawingState;
glPushMatrix;
glTranslatef(0, 1, 4);
glRotatef(135, 0, 1, 0);
drawAirplane;
glPopMatrix;
If stage = 2
then goto doneWithFrame;
setupBasePolygonState(3); //* 2 decals */
drawGround;
If stage = 3
then goto doneWithFrame;
setupDecalState(1); //* decal # 1 = the runway asphalt */
drawAsphalt;
If stage = 4
then goto doneWithFrame;
setupDecalState(2); //* decal # 2 = yellow paint on the runway */
drawStripes;
If stage = 5
then goto doneWithFrame;
setupDecalState(3); //* decal # 3 = the plane's shadow */
glDisable(GL_LIGHTING);
glEnable(GL_BLEND);
glPushMatrix;
glColor4f(0, 0, 0, 0.5);
glTranslatef(0, 0, 4);
glRotatef(135, 0, 1, 0);
glScalef(1, 0, 1);
drawAirplane;
glPopMatrix;
glDisable(GL_BLEND);
glEnable(GL_LIGHTING);
{label} doneWithFrame:
setupNormalDrawingState;
glPopMatrix;
// If dataChoice = DCOLOR then Exit;
If dataChoice = STENCIL
then copyStencilToColor(GL_BACK);
If dataChoice = DEPTH
then copyDepthToColor(GL_BACK);
SwapBuffers(DC);
EndPaint(Handle, ps);
end;
procedure TfrmGL.FormCreate(Sender: TObject);
begin
DC := GetDC(Handle);
SetDCPixelFormat;
hrc := wglCreateContext(DC);
wglMakeCurrent(DC, hrc);
Init;
end;
procedure TfrmGL.FormResize(Sender: TObject);
begin
glViewport(0, 0, ClientWidth, ClientHeight);
InvalidateRect(Handle, nil, False);
end;
procedure TfrmGL.FormDestroy(Sender: TObject);
begin
gluDeleteQuadric (quadric);
wglMakeCurrent(0, 0);
wglDeleteContext(hrc);
ReleaseDC(Handle, DC);
DeleteDC (DC);
end;
procedure TfrmGL.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
If Key = VK_ESCAPE then Close;
If (Key >= 49) and (Key<=54) then begin
stage := Key - 48;
InvalidateRect(Handle, nil, False);
end;
end;
procedure TfrmGL.SetDCPixelFormat;
var
nPixelFormat: Integer;
pfd: TPixelFormatDescriptor;
begin
FillChar(pfd, SizeOf(pfd), 0);
pfd.dwFlags := PFD_DRAW_TO_WINDOW or PFD_SUPPORT_OPENGL or
PFD_DOUBLEBUFFER;
nPixelFormat := ChoosePixelFormat(DC, @pfd);
SetPixelFormat(DC, nPixelFormat, @pfd);
end;
procedure TfrmGL.FormMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
var
eyex, eyez : GLfloat;
begin
If Down then begin
ang := ang + (x - ox) / 512.0 * PI;
sheight := sheight + (y - oy) / 512.0 * 10;
eyex := cos(ang) * 7;
eyez := sin(ang) * 7;
glLoadIdentity;
gluLookAt(eyex, sheight, eyez, 0, 0, 0, 0, 1, 0);
InvalidateRect(Handle, nil, False);
ox := x;
oy := y;
end;
end;
procedure TfrmGL.FormMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
Down := True;
ox := x;
oy := y;
end;
procedure TfrmGL.FormMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
Down := False;
end;
procedure TfrmGL.turnonstencildecal1Click(Sender: TObject);
begin
useStencil := not useStencil;
InvalidateRect(Handle, nil, False);
end;
procedure TfrmGL.Colorbuffer1Click(Sender: TObject);
begin
dataChoice := DCOLOR;
InvalidateRect(Handle, nil, False);
end;
procedure TfrmGL.Stencilbuffer1Click(Sender: TObject);
begin
dataChoice := STENCIL;
InvalidateRect(Handle, nil, False);
end;
procedure TfrmGL.Depthbuffre1Click(Sender: TObject);
begin
dataChoice := DEPTH;
InvalidateRect(Handle, nil, False);
end;
procedure TfrmGL.Clearingscreen1Click(Sender: TObject);
begin
stage := (Sender as TMenuItem).Tag;
InvalidateRect(Handle, nil, False);
end;
end.
|
unit PascalCoin.FMX.Frame.Wallet;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes,
System.Variants,
FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls,
FMX.Controls.Presentation, FMX.Layouts, System.Rtti, FMX.Grid.Style, FMX.Grid,
FMX.ScrollBox, PascalCoin.FMX.Frame.Base, Data.Bind.EngExt, FMX.Bind.DBEngExt,
FMX.Bind.Grid, System.Bindings.Outputs, FMX.Bind.Editors,
Data.Bind.Components, Data.Bind.Grid, Data.Bind.DBScope, System.Actions,
FMX.ActnList, FMX.Menus;
type
TWalletFrame = class(TBaseFrame)
MainLayout: TLayout;
MyBalanceLabel: TLabel;
BalanceLabel: TLabel;
WalletPanel: TPanel;
ToolBar2: TToolBar;
AccountShow: TCheckBox;
BindSourceDB1: TBindSourceDB;
BindingsList1: TBindingsList;
AccountGrid: TGrid;
Layout1: TLayout;
LinkGridToDataSourceBindSourceDB1: TLinkGridToDataSource;
PopupMenu1: TPopupMenu;
AccountInfoItem: TMenuItem;
ActionList1: TActionList;
AccountInfoAction: TAction;
PasaCount: TLabel;
procedure AccountInfoActionExecute(Sender: TObject);
private
{ Private declarations }
procedure OnBalanceChange(const Value: Currency);
procedure OnInitComplete(Sender: TObject);
procedure OnAccountsUpdated(Sender: TObject);
procedure OnAdvancedOptionsChanged(const AValue: Boolean);
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure InitialiseFrame; override;
procedure Showing; override;
procedure Hiding; override;
end;
implementation
{$R *.fmx}
uses PascalCoin.FMX.DataModule, PascalCoin.RPC.Interfaces;
{ TWalletFrame }
constructor TWalletFrame.Create(AOwner: TComponent);
begin
inherited;
BalanceLabel.Text := 'loading from safebox';
MainDataModule.Settings.OnAdvancedOptionsChange.Add(OnAdvancedOptionsChanged);
OnAdvancedOptionsChanged(MainDataModule.Settings.AdvancedOptions);
MainDataModule.OnBalanceChangeEvent.Add(OnBalanceChange);
MainDataModule.OnInitComplete.Add(OnInitComplete);
MainDataModule.OnAccountsUpdated.Add(OnAccountsUpdated);
end;
destructor TWalletFrame.Destroy;
begin
MainDataModule.Settings.OnAdvancedOptionsChange.Remove
(OnAdvancedOptionsChanged);
MainDataModule.OnBalanceChangeEvent.Remove(OnBalanceChange);
MainDataModule.OnInitComplete.Remove(OnInitComplete);
MainDataModule.OnAccountsUpdated.Remove(OnAccountsUpdated);
inherited;
end;
procedure TWalletFrame.AccountInfoActionExecute(Sender: TObject);
var
lAccount: IPascalCoinAccount;
begin
// Need a proper popup frame to do all this
lAccount := MainDataModule.API.getaccount
(MainDataModule.AccountsDataAccountNumber.Value);
ShowMessage(lAccount.enc_pubkey);
end;
procedure TWalletFrame.Hiding;
begin
inherited;
end;
procedure TWalletFrame.InitialiseFrame;
begin
inherited;
end;
procedure TWalletFrame.OnAccountsUpdated(Sender: TObject);
begin
PasaCount.Text := 'Number of PASA shown: ' +
FormatFloat('', BindSourceDB1.DataSet.RecordCount);
end;
procedure TWalletFrame.OnAdvancedOptionsChanged(const AValue: Boolean);
begin
LinkGridToDataSourceBindSourceDB1.Columns[4].Visible := AValue;
end;
procedure TWalletFrame.OnBalanceChange(const Value: Currency);
begin
BalanceLabel.Text := CurrToStrF(Value, ffCurrency, 4);
end;
procedure TWalletFrame.OnInitComplete(Sender: TObject);
begin
end;
procedure TWalletFrame.Showing;
begin
inherited;
end;
end.
|
{
Copyright (c) 2010, Loginov Dmitry Sergeevich
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
}
unit EditHTMLFrm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, ActnList;
type
TEditHTMLForm = class(TForm)
Panel1: TPanel;
Panel2: TPanel;
btnOk: TButton;
btnCancel: TButton;
ActionList1: TActionList;
acClose: TAction;
acCancel: TAction;
procedure acCloseExecute(Sender: TObject);
procedure acCancelExecute(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
EditHTMLForm: TEditHTMLForm;
function ShowEditHTMLForm(var HTMLText: string; CanEdit: Boolean): Boolean;
implementation
{$R *.dfm}
function ShowEditHTMLForm(var HTMLText: string; CanEdit: Boolean): Boolean;
begin
{ with TEditHTMLForm.Create(nil) do
try
//memHTML.Text := HTMLText;
SynEdit1.Text := HTMLText;
if not CanEdit then
begin
Caption := 'Просмотр HTML-текста';
btnOk.ModalResult := mrNone;
btnOk.Visible := False;
btnCancel.Caption := 'Закрыть';
end;
Result := ShowModal = mrOk;
if Result then
//HTMLText := memHTML.Text;
HTMLText := SynEdit1.Text;
finally
Free;
end; }
end;
procedure TEditHTMLForm.acCancelExecute(Sender: TObject);
begin
btnCancel.Click;
end;
procedure TEditHTMLForm.acCloseExecute(Sender: TObject);
begin
btnOk.Click;
end;
end.
|
unit MediaStream.Writer.AVI;
interface
uses Windows,Classes,SysUtils,VFW,MMSystem,MediaProcessing.Definitions;
type
//Записывает видеопоток в формате AVI напрямую складывая данные из потока
TMediaStreamWriter_AVI = class
private
FFileName: string;
FHeaderWritten: boolean;
FVideoEnabled: boolean;
FVideoFCC: cardinal;
FVideoFormat: TBitmapInfoHeader ;
FVideoFrameRate: double;
FAudioEnabled: boolean;
FAudioFCC: cardinal;
FAudioFormat: TPCMWaveFormat;
FVideoFramesWrittenCount: cardinal;
FAudioFramesWrittenCount :cardinal;
FWrittenDataSize: int64;
FVideoStream,FAudioStream: IAVIStream;
FAviFile: IAVIFile;
procedure WriteHeader;
procedure CheckOpened;
public
constructor Create; overload;
destructor Destroy; override;
//Открыть файл для записи
procedure EnableVideo(aFCC: cardinal; const aVideoFormat: TBitmapInfoHeader; const aFrameRate: double);
procedure EnableAudio(aFCC: cardinal; const aAudioFormat: TPCMWaveFormat);
procedure Open(const aFileName: string);
procedure OpenFileOnly(const aFileName: string);
procedure BeginWriting;
//Закрыть файл
procedure Close;
function Opened: boolean;
property FileName: string read FFileName;
property WrittenDataSize: int64 read FWrittenDataSize;
procedure WriteData(const aFormat: TMediaStreamDataHeader;aData: pointer; aDataSize: cardinal);
property AviStream: IAVIStream read FVideoStream;
property AudioEnabled: boolean read FAudioEnabled;
property AudioType: TStreamType read FAudioFCC;
property VideoEnabled: boolean read FVideoEnabled;
property VideoType: TStreamType read FVideoFCC;
property VideoFramesWrittenCount: cardinal read FVideoFramesWrittenCount;
property AudioFramesWrittenCount :cardinal read FAudioFramesWrittenCount;
end;
implementation
uses BitPlane;
{ TMediaStreamWriter_AVI }
constructor TMediaStreamWriter_AVI.Create;
begin
inherited Create;
end;
destructor TMediaStreamWriter_AVI.Destroy;
begin
Close;
inherited;
end;
procedure TMediaStreamWriter_AVI.EnableAudio(aFCC: cardinal; const aAudioFormat: TPCMWaveFormat);
begin
FAudioEnabled:=true;
FAudioFCC:=aFCC;
if aFCC=stPCM then
FAudioFCC:=0;
FAudioFormat:=aAudioFormat;
end;
procedure TMediaStreamWriter_AVI.EnableVideo(aFCC: cardinal; const aVideoFormat: TBitmapInfoHeader; const aFrameRate: double);
begin
FVideoEnabled:=true;
FVideoFCC:=aFCC;
FVideoFrameRate:=aFrameRate;
if FVideoFCC=stRGB then
FVideoFCC:=0; //!!!
FVideoFormat:=aVideoFormat;
end;
procedure TMediaStreamWriter_AVI.BeginWriting;
begin
if FHeaderWritten then
exit;
WriteHeader;
FHeaderWritten:=true;
end;
procedure TMediaStreamWriter_AVI.CheckOpened;
begin
if not Opened then
raise Exception.Create('Файл еще не открыт');
end;
procedure TMediaStreamWriter_AVI.Close;
begin
inherited;
//AVIStreamRelease(FVideoStream);
FVideoStream:=nil;
FAudioStream:=nil;
FAviFile:=nil;
FHeaderWritten:=false;
//AVIStreamRelease(FCompressedStream);
FVideoFramesWrittenCount:=0;
FAudioFramesWrittenCount:=0;
end;
procedure TMediaStreamWriter_AVI.WriteHeader;
var
aStreamInfo: TAVIStreamInfoW;
begin
if FVideoEnabled or FAudioEnabled = false then
raise Exception. Create('Не активизирован ни один из потоков (Audio, Video)');
//VIDEO
if FVideoEnabled then
begin
ZeroMemory(@aStreamInfo, SizeOf(aStreamInfo));
aStreamInfo.fccType := streamtypeVIDEO;
aStreamInfo.fccHandler := FVideoFCC;
aStreamInfo.dwScale := 10; //Умножаем на 10, чтобы считать кол-во кадров с точностью до десятых
aStreamInfo.dwRate := Round(FVideoFrameRate*10);
aStreamInfo.dwSuggestedBufferSize := FVideoFormat.biWidth*FVideoFormat.biHeight*4; //aBih.biSizeImage; // size of 1 frame
SetRect(aStreamInfo.rcFrame, 0, 0, FVideoFormat.biWidth, FVideoFormat.biHeight);
if FAviFile.CreateStream(FVideoStream, aStreamInfo) <> 0 then
RaiseLastOSError;
if FVideoStream.SetFormat(0, @FVideoFormat, sizeof(FVideoFormat)) <> 0 then
RaiseLastOSError;
end;
if FAudioEnabled then
begin
// AUDIO
ZeroMemory(@aStreamInfo, SizeOf(aStreamInfo));
aStreamInfo.fccType := streamtypeAUDIO;
aStreamInfo.fccHandler := FAudioFCC;
aStreamInfo.dwScale := FAudioFormat.wf.nBlockAlign; //кол-во байт за один квант на всех каналах.;
aStreamInfo.dwRate := FAudioFormat.wf.nSamplesPerSec * aStreamInfo.dwScale; // байт в сек.
//aStreamInfo.dwInitialFrames := 1; //номер первого кадра.
aStreamInfo.dwSampleSize := aStreamInfo.dwScale; //кол-во байт за квант на всех каналах.
aStreamInfo.dwSuggestedBufferSize := aStreamInfo.dwScale*FAudioFormat.wf.nSamplesPerSec;
//aStreamInfo.dwQuality := cardinal(-1); //качество, -1 - по умолчанию.
if FAviFile.CreateStream(FAudioStream, aStreamInfo) <> 0 then
RaiseLastOSError;
if FAudioStream.SetFormat(0,@FAudioFormat,sizeof(FAudioFormat))<>0 then
RaiseLastOSError;
end;
end;
procedure TMediaStreamWriter_AVI.WriteData(const aFormat: TMediaStreamDataHeader; aData: pointer; aDataSize: cardinal);
var
x,i,j:integer;
aFlags : cardinal;
aBitPlane: TBitPlaneDesc;
begin
if aDataSize=0 then
exit;
CheckOpened;
aFlags:=0;
if ffKeyFrame in aFormat.biFrameFlags then
aFlags:=aFlags or AVIIF_KEYFRAME;
if aFormat.biMediaType=mtVideo then
begin
if FVideoStream=nil then
exit;
if aFormat.biStreamType=stRGB then
if not aFormat.VideoReversedVertical then
begin
aBitPlane.Init(aData,aDataSize,aFormat.VideoWidth,aFormat.VideoHeight,aFormat.VideoBitCount);
aBitPlane.Upturn;
end;
if FVideoStream.Write(FVideoFramesWrittenCount, 1, aData, aDataSize, aFlags, i, j) <> 0 then
RaiseLastOSError;
Assert(i=1);
Assert(j=integer(aDataSize));
inc(FVideoFramesWrittenCount);
end
else if aFormat.biMediaType=mtAudio then
begin
if FAudioStream=nil then
exit;
x:=aDataSize div FAudioFormat.wf.nChannels div (FAudioFormat.wBitsPerSample div 8);
if FAudioStream.Write(FAudioFramesWrittenCount, x, aData, aDataSize, aFlags, i, j) <> 0 then
RaiseLastOSError;
Assert(i=x);
Assert(j=integer(aDataSize));
inc(FAudioFramesWrittenCount,x);
end;
inc(FWrittenDataSize,aDataSize);
end;
procedure TMediaStreamWriter_AVI.Open(const aFileName: string);
begin
OpenFileOnly(aFileName);
BeginWriting;
end;
procedure TMediaStreamWriter_AVI.OpenFileOnly(const aFileName: string);
var
aDirectory: string;
begin
Close;
FFileName:=aFileName;
AviFileInit;
aDirectory:=ExtractFileDir(aFileName);
if not DirectoryExists(aDirectory) then
raise Exception.CreateFmt('Не удается найти путь "%s"',[aDirectory]);
DeleteFile(PChar(FFileName));
if AviFileOpen(FAviFile, PChar(FFileName), OF_WRITE or OF_CREATE, nil) <> 0 then
RaiseLastOSError;
end;
function TMediaStreamWriter_AVI.Opened: boolean;
begin
result:=FAviFile<>nil;
end;
end.
|
unit uImagesScrollBox;
interface
uses
Windows, SysUtils, ExtCtrls, classes, controls, StdCtrls, graphics, forms,
uImagem, uPrintManBaseClasses, Messages, Int64List, SyncObjs;
type
TPageEvent = procedure(Sender: TObject; aPageNum:integer) of object;
TBitmapEvent = procedure(Sender: TObject; idx:integer; aBmp:TBitmap) of object;
TPopulateEvent = procedure(Sender: TObject; aInicio, aFim:integer) of object;
TIniReadEvent = procedure(Sender: TObject; aTotalPages, aThumbWidth, aThumbHeight, aBmpWidth, aBmpHeight:integer; aMD5:string) of object;
TProgressEvent = procedure(Sender: TObject; aPos, aTotal:integer) of object;
TLoadImagesThread = class;
TImagesScrollBox = class(TScrollBox)
private
fOnImageClick : TPageEvent;
fOnImageDblClick : TPageEvent;
fAfterPrintRunning : boolean;
fLastAfterPrintPage : integer;
procedure CMMouseWheel(var Message: TCMMouseWheel); message CM_MOUSEWHEEL;
procedure WMVScroll(var Message: TWMVScroll); message WM_VSCROLL;
protected
fImageCount : integer;
fImageWidth : integer;
fImageHeight : integer;
fPageHeight : integer;
fLastVPos : integer;
fScrollDown : boolean;
fLastSelected : integer;
fVisibleCols : integer;
fVisibleRows : integer;
fFirstVisiblePage : integer;
fLastVisiblePage : integer;
fRequisitarLastInicio : integer;
fRequisitarLastFim : integer;
fLoadingBmp : TBitmap;
frepagLastInicio : integer;
frepagLastFim : integer;
frepagLastPanelHeight : integer;
fScrollW : integer;
procedure doAfterVScroll; virtual; abstract;
procedure doImageClick ( aPageNum:integer );
procedure doImageDblClick ( aPageNum:integer );
procedure ClearPanels;
public
property ScrollW : integer read fScrollW;
property ImageCount : integer read fImageCount write fImageCount;
property ImageWidth : integer read fImageWidth write fImageWidth;
property ImageHeight : integer read fImageHeight write fImageHeight;
property OnImageClick : TPageEvent read fOnImageClick write fOnImageClick;
property OnImageDblClick : TPageEvent read fOnImageDblClick write fOnImageDblClick;
property LoadingBmp : TBitmap read fLoadingBmp;
procedure NotifyStartPrintMessage;
procedure NotifyProgressPrintMessage(aPage:integer); virtual;
procedure Clear;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
end;
TImageManagerThread = class(TThread)
private
fOnFirstBmp : TBitmapEvent;
fOnBmpReady : TBitmapEvent;
fOnUnload : TPageEvent;
protected
fLoadImagesThread : TLoadImagesThread;
fIdx : integer;
fRunning : boolean;
fbmpSchedulados : TInt64List;
fbmpFailed : TInt64List;
fbmpRequisitados : TInt64List;
fbmpCarregados : TInt64List;
fbmpGrantNoUnload : TInt64List;
fBmp : TBitmap;
fIsFirstBmp : boolean;
fMaxLoadedPages : integer;
procedure FinalizeImageManagerThread;
procedure ScheduleLoadBitmap;
procedure SyncOnBmpReady;
procedure doOnBmpReady(aIdx:integer; aBmp:TBitmap);
procedure ImageManagerThreadOnBmpLoaded(Sender: TObject; idx:integer; aBmp:TBitmap);
procedure ImageManagerThreadOnBmpLoadFail(Sender: TObject; idx:integer);
procedure SyncOnFirstBmp;
procedure doOnFirstBmp(aIdx:integer; aBmp:TBitmap); virtual;
public
property Running : boolean read fRunning;
property OnBmpReady : TBitmapEvent read fOnBmpReady write fOnBmpReady;
property OnUnload : TPageEvent read fOnUnload write fOnUnload;
property OnFirstBmp : TBitmapEvent read fOnFirstBmp write fOnFirstBmp;
constructor Create;
destructor Destroy; override;
end;
TLoadImagesThread = class(TThread)
private
fIdx : integer;
fBmp : TBitmap;
fBusy : boolean;
fOnBmpLoaded : TBitmapEvent;
fOnBmpLoadFail : TPageEvent;
fImagesManagerThread : TImageManagerThread;
fPageCount : integer;
procedure SyncBmpLoaded;
procedure SyncBmpLoadFail;
protected
fFilesPath : string;
function loadBitmap(i:integer):boolean; virtual; abstract;
procedure doBmpLoaded(idx:integer; aBmp:TBitmap);
procedure doBmpLoadedFail(idx:integer);
procedure Execute; override;
public
property Busy : boolean read fBusy;
property FilesPath : string read fFilesPath write fFilesPath;
property PageCount : integer read fPageCount write fPageCount;
property OnBmpLoaded : TBitmapEvent read fOnBmpLoaded write fOnBmpLoaded;
property OnBmpLoadFail : TPageEvent read fOnBmpLoadFail write fOnBmpLoadFail;
constructor Create(aImagesManagerThread : TImageManagerThread);
end;
implementation
{$IFNDEF NOLOG}
uses
uLogs;
{$ENDIF}
{ TImagesScrollBox }
constructor TImagesScrollBox.Create(AOwner: TComponent);
begin
inherited;
fLoadingBmp := TBitmap.Create;
fLoadingBmp.PixelFormat := pf24bit;
//AutoScroll := false;
//VertScrollBar.Visible := true;
//HorzScrollBar.Visible := false;
end;
destructor TImagesScrollBox.Destroy;
begin
fLoadingBmp.Free;
inherited;
end;
procedure TImagesScrollBox.Clear;
begin
fImageCount :=0;
fImageWidth :=0;
fImageHeight :=0;
fLastVPos :=0;
fLastSelected :=0;
fVisibleCols :=1;
fVisibleRows :=1;
fFirstVisiblePage :=0;
fLastVisiblePage :=0;
fRequisitarLastInicio :=0;
fRequisitarLastFim :=0;
frepagLastInicio :=-1;
frepagLastFim :=-1;
frepagLastPanelHeight :=-1;
fAfterPrintRunning := false;
if fLoadingBmp <> nil then
fLoadingBmp.Empty;
ClearPanels;
end;
procedure TImagesScrollBox.ClearPanels;
var
i : integer;
begin
{$IFNDEF NOLOG}GLog.Log(self,[lcTrace],'ClearPanels ');{$ENDIF}
for i:=ControlCount-1 downto 0 do
Controls[i].Parent := nil;
end;
procedure TImagesScrollBox.CMMouseWheel(var Message: TCMMouseWheel);
begin
VertScrollBar.position := VertScrollBar.position - Message.WheelDelta;
if fLastVPos <> VertScrollBar.position then begin
fScrollDown := VertScrollBar.position - fLastVPos > 0;
{//$IFNDEF NOLOG}//GLog.Log(self,[lcMsgs],'CMMouseWheel '+inttostr(Message.WheelDelta)+ ' dwn '+inttostr(VertScrollBar.position)+' up '+booltostr(fScrollDown, true));{$ENDIF}
fLastVPos := VertScrollBar.position;
doAfterVScroll;
end;
Message.Result := 1;
{//$IFNDEF NOLOG}//GLog.ForceLogWrite;{$ENDIF}
end;
procedure TImagesScrollBox.WMVScroll(var Message: TWMVScroll);
begin
inherited;
if fLastVPos <> VertScrollBar.position then begin
fScrollDown := VertScrollBar.position - fLastVPos > 0;
{//$IFNDEF NOLOG}//GLog.Log(self,[lcMsgs],'WMVScroll pos '+inttostr(VertScrollBar.position)+' dwn '+booltostr(fScrollDown, true));{$ENDIF}
fLastVPos := VertScrollBar.position;
doAfterVScroll;
end;
Message.Result := 1;
{$IFNDEF NOLOG}GLog.ForceLogWrite;{$ENDIF}
end;
procedure TImagesScrollBox.doImageClick(aPageNum: integer);
begin
if assigned(fOnImageClick) then
fOnImageClick(Self, aPageNum);
end;
procedure TImagesScrollBox.doImageDblClick(aPageNum: integer);
begin
if assigned(fOnImageDblClick) then
fOnImageDblClick(Self, aPageNum);
end;
procedure TImagesScrollBox.NotifyProgressPrintMessage(aPage:integer);
begin
fLastAfterPrintPage := aPage;
end;
procedure TImagesScrollBox.NotifyStartPrintMessage;
begin
fAfterPrintRunning := true;
end;
{ TImageManagerThread }
constructor TImageManagerThread.Create;
begin
{$IFNDEF NOLOG}GLog.Log(self,[lcTrace],'Create');{$ENDIF}
inherited Create(true);
fbmpRequisitados := TInt64List.create;
fbmpRequisitados.SortType := Int64SortNoneNoDup;
fbmpSchedulados := TInt64List.create;
fbmpSchedulados.SortType := Int64SortNoneNoDup;
fbmpCarregados := TInt64List.create;
fbmpCarregados.SortType := Int64SortNoneNoDup;
fbmpGrantNoUnload := TInt64List.create;
fbmpFailed := TInt64List.create;
fbmpFailed.SortType := Int64SortNoneNoDup;
{$IFNDEF NOLOG}GLog.Log(self,[lcTrace], classname + 'created');{$ENDIF}
end;
destructor TImageManagerThread.Destroy;
begin
{$IFNDEF NOLOG}GLog.Log(self,[lcTrace], 'destroying '+classname);{$ENDIF}
fbmpRequisitados.free;
fbmpCarregados.free;
fbmpSchedulados.free;
fbmpGrantNoUnload.free;
fbmpFailed.free;
inherited;
{$IFNDEF NOLOG}GLog.Log(self,[lcTrace], 'Destroyed');{$ENDIF}
end;
procedure TImageManagerThread.doOnBmpReady(aIdx: integer; aBmp: TBitmap);
var
i : integer;
begin
{$IFNDEF NOLOG}GLog.Log(self,[lcTrace],'doOnBmpReady '+inttostr(aIdx));{$ENDIF}
fIdx := aIdx;
fBmp := aBmp;
fbmpCarregados.add(aIdx);
i := fbmpRequisitados.IndexOf(aIdx);
if i>-1 then
fbmpRequisitados.Delete(i);
i := fbmpSchedulados.IndexOf(aIdx);
if i>-1 then
fbmpSchedulados.Delete(i);
{$IFNDEF NOLOG}GLog.Log(self,[lcTrace],'fbmpRequisitados: '+fbmpRequisitados.asStringSeries);{$ENDIF}
{//$IFNDEF NOLOG}//GLog.Log(self,[lcTrace],'fbmpCarregados: '+fbmpCarregados.asStringSeries);{$ENDIF}
{$IFNDEF NOLOG}GLog.Log(self,[lcTrace],'doOnBmpReady go Sync');{$ENDIF}
Synchronize(SyncOnBmpReady);
{$IFNDEF NOLOG}GLog.Log(self,[lcTrace],'doOnBmpReady SyncEvt done');{$ENDIF}
{$IFNDEF NOLOG}GLog.ForceLogWrite;{$ENDIF}
end;
procedure TImageManagerThread.doOnFirstBmp(aIdx: integer; aBmp: TBitmap);
var
i : integer;
begin
{$IFNDEF NOLOG}GLog.Log(self,[lcTrace],'doOnFirstBmp '+inttostr(aIdx));{$ENDIF}
fIdx := aIdx;
fBmp := aBmp;
fbmpCarregados.add(aIdx);
i := fbmpRequisitados.IndexOf(aIdx);
if i>-1 then
fbmpRequisitados.Delete(i);
i := fbmpSchedulados.IndexOf(aIdx);
if i>-1 then
fbmpSchedulados.Delete(i);
{$IFNDEF NOLOG}GLog.Log(self,[lcTrace],'fbmpRequisitados: '+fbmpRequisitados.asStringSeries);{$ENDIF}
{//$IFNDEF NOLOG}//GLog.Log(self,[lcTrace],'fbmpCarregados: '+fbmpCarregados.asStringSeries);{$ENDIF}
{$IFNDEF NOLOG}GLog.Log(self,[lcTrace],'doOnFirstBmp go Sync');{$ENDIF}
Synchronize(SyncOnFirstBmp);
{$IFNDEF NOLOG}GLog.Log(self,[lcTrace],'doOnFirstBmp SyncEvt done');{$ENDIF}
{$IFNDEF NOLOG}GLog.ForceLogWrite;{$ENDIF}
end;
procedure TImageManagerThread.FinalizeImageManagerThread;
var
i,idx: integer;
begin
if fLoadImagesThread <> nil then begin
fLoadImagesThread.Terminate;
fLoadImagesThread.WaitFor;
fLoadImagesThread.free;
fLoadImagesThread := nil;
end;
if (assigned(fOnUnload)) and
(fbmpCarregados.count>0) then begin
{$IFNDEF NOLOG}GLog.Log(self,[lcTrace],'FinalizeImageManagerThread fbmpCarregados: '+fbmpCarregados.asStringSeries);{$ENDIF}
{$IFNDEF NOLOG}GLog.Log(self,[lcTrace],'FinalizeImageManagerThread fbmpRequisitados: '+fbmpRequisitados.asStringSeries);{$ENDIF}
{$IFNDEF NOLOG}GLog.Log(self,[lcTrace],'FinalizeImageManagerThread fbmpSchedulados: '+fbmpSchedulados.asStringSeries);{$ENDIF}
{$IFNDEF NOLOG}GLog.Log(self,[lcTrace],'FinalizeImageManagerThread fbmpGrantNoUnload: '+fbmpGrantNoUnload.asStringSeries);{$ENDIF}
for i:=fbmpCarregados.count-1 downto 0 do begin
idx := fbmpCarregados[i];
fOnUnload(self, idx+1);
fbmpCarregados.delete(i);
{$IFNDEF NOLOG}GLog.Log(self,[lcTrace],'FinalizeImageManagerThread UNLOADED : '+inttostr(idx));{$ENDIF}
end;
end;
end;
procedure TImageManagerThread.ScheduleLoadBitmap;
var
i,k,idx: integer;
bres : boolean;
retry : Integer;
begin
try
if fbmpRequisitados.count>0 then begin
{//$IFNDEF NOLOG}//GLog.Log(self,[lcTrace],'ScheduleLoadBitmap');{$ENDIF}
try
idx := fbmpRequisitados[0];
except
exit;
end;
if fbmpSchedulados.indexof(idx)=-1 then begin
fbmpSchedulados.Add(idx);
{$IFNDEF NOLOG}GLog.Log(self,[lcTrace],'ScheduleLoadBitmap goPost THMSG_LoadBMP');{$ENDIF}
retry := 0;
repeat
GLog.Log(self,[lcMsgs],'PostThreadMessage THMSG_LoadBMP '+inttostr(idx)+' 0');
bres := PostThreadMessage (fLoadImagesThread.ThreadID, THMSG_LoadBMP, idx, 0);
if not bres then begin
inc(retry);
sleep(kMsgRetrySleep);
end;
until terminated or (retry=kMaxMsgRetry) or bres;
{$IFNDEF NOLOG}
if not bres then
GLog.Log(self,[lcExcept],'ScheduleLoadBitmap PostThreadMessage THMSG_LoadBMP FAILED '+inttostr(idx));
{$ENDIF}
end;
end;
if (assigned(fOnUnload)) and
(fbmpCarregados.count>fMaxLoadedPages) then begin
{$IFNDEF NOLOG}GLog.Log(self,[lcTrace],'ScheduleLoadBitmap fbmpCarregados: '+fbmpCarregados.asStringSeries);{$ENDIF}
{$IFNDEF NOLOG}GLog.Log(self,[lcTrace],'ScheduleLoadBitmap fbmpRequisitados: '+fbmpRequisitados.asStringSeries);{$ENDIF}
{$IFNDEF NOLOG}GLog.Log(self,[lcTrace],'ScheduleLoadBitmap fbmpSchedulados: '+fbmpSchedulados.asStringSeries);{$ENDIF}
{$IFNDEF NOLOG}GLog.Log(self,[lcTrace],'ScheduleLoadBitmap fbmpGrantNoUnload: '+fbmpGrantNoUnload.asStringSeries);{$ENDIF}
i:=0; k:=fbmpCarregados.count-1;
while i<k do begin
idx := fbmpCarregados[i];
if (fbmpGrantNoUnload.indexof(idx)=-1) then begin
fOnUnload(self, idx+1);
fbmpCarregados.delete(i);
dec(k);
{$IFNDEF NOLOG}GLog.Log(self,[lcTrace],'ScheduleLoadBitmap UNLOADED : '+inttostr(idx));{$ENDIF}
end else
inc(i);
if fbmpCarregados.count<=fMaxLoadedPages then break;
end;
end;
except
on e: exception do begin
{$IFNDEF NOLOG}GLog.Log(self,[lcExcept], e.message); {$ENDIF}
end;
end;
end;
procedure TImageManagerThread.SyncOnBmpReady;
begin
if assigned(fOnBmpReady) then
fOnBmpReady(self, fIdx+1, fBmp);
end;
procedure TImageManagerThread.SyncOnFirstBmp;
begin
if assigned(fOnFirstBmp) then
fOnFirstBmp(self, fIdx+1, fBmp);
end;
procedure TImageManagerThread.ImageManagerThreadOnBmpLoaded(Sender: TObject;
idx: integer; aBmp: TBitmap);
var
i : integer;
begin
{$IFNDEF NOLOG}GLog.Log(self,[lcTrace],'pagesManagerThreadOnBmpLoaded '+inttostr(idx));{$ENDIF}
if (fIsFirstBmp) then begin
fIsFirstBmp := false;
try
doOnFirstBmp(idx, aBmp);
except
on e:Exception do
{$IFNDEF NOLOG}GLog.Log(self,[lcExcept],'pagesManagerThreadOnBmpLoaded doOnFirstBmp e:'+e.message);{$ENDIF}
end;
end;
if not terminated then begin
doOnBmpReady(idx, aBmp);
end;
i := fbmpFailed.IndexOf(Idx);
if i>-1 then
fbmpFailed.Delete(i);
{$IFNDEF NOLOG}GLog.Log(self,[lcTrace],'pagesManagerThreadOnBmpLoaded end');{$ENDIF}
end;
procedure TImageManagerThread.ImageManagerThreadOnBmpLoadFail(Sender: TObject;
idx: integer);
var
i : integer;
begin
{$IFNDEF NOLOG}GLog.Log(self,[lcTrace],'pagesManagerThreadOnBmpLoadFail '+inttostr(Idx));{$ENDIF}
i := fbmpRequisitados.IndexOf(Idx);
if i>-1 then
fbmpRequisitados.Delete(i);
i := fbmpSchedulados.IndexOf(Idx);
if i>-1 then
fbmpSchedulados.Delete(i);
fbmpFailed.add(idx);
{$IFNDEF NOLOG}GLog.ForceLogWrite;{$ENDIF}
end;
{ TLoadImagesThread }
constructor TLoadImagesThread.Create(aImagesManagerThread : TImageManagerThread);
begin
inherited Create(true);
fImagesManagerThread := aImagesManagerThread;
end;
procedure TLoadImagesThread.Execute;
var
Msg : TMsg;
pmRes : integer;
sMSG : string;
begin
{$IFNDEF NOLOG} GLog.Log(self,[lcTrace],'Execute start');{$ENDIF}
while not Terminated do begin
pmRes := Integer(PeekMessage(Msg, hwnd(0), 0, 0, PM_REMOVE));
if pmRes <> 0 then begin
TranslateMessage(Msg);
DispatchMessage(Msg);
case Msg.message of
THMSG_LoadBMP : sMSG := 'THMSG_LoadBMP';
end;
GLog.Log(self,[lcMsgs], 'Mensagem recebida: ' + sMSG + ' w:' +inttostr(Msg.wParam)+ ' l:'+inttostr(Msg.lParam));
case Msg.message of
THMSG_LoadBMP : begin
{$IFNDEF NOLOG}GLog.Log(self,[lcTrace],'THMSG_LoadBMP '+inttostr(msg.wParam));{$ENDIF}
fBusy := true;
try
loadBitmap(msg.wParam);
finally
fBusy := false;
end;
end;
end;
end else
sleep(50);
end;
{$IFNDEF NOLOG} GLog.Log(self,[lcTrace],'Execute end');{$ENDIF}
{$IFNDEF NOLOG}GLog.ForceLogWrite;{$ENDIF}
end;
procedure TLoadImagesThread.doBmpLoaded(idx:integer; aBmp:TBitmap);
begin
fIdx := idx;
fBmp := aBmp;
try
Synchronize(fImagesManagerThread, SyncBmpLoaded);
except
on e:exception do begin
{$IFNDEF NOLOG} GLog.Log(self,[lcExcept],'doBmpLoaded '+inttostr(idx)+ ' e:'+e.message );{$ENDIF}
end
end;
end;
procedure TLoadImagesThread.doBmpLoadedFail(idx: integer);
begin
fIdx := idx;
try
Synchronize(fImagesManagerThread, SyncBmpLoadFail);
except
on e:exception do begin
{$IFNDEF NOLOG} GLog.Log(self,[lcExcept],'doBmpLoadedFail '+inttostr(idx)+ 'e:'+e.message );{$ENDIF}
end
end;
end;
procedure TLoadImagesThread.SyncBmpLoaded;
begin
if (assigned(fOnBmpLoaded)) then
try
fOnBmpLoaded(self, fIdx, fBmp);
except
on e:exception do begin
{$IFNDEF NOLOG} GLog.Log(self,[lcExcept],'SyncBmpLoaded '+inttostr(fIdx)+ ' e:'+e.message );{$ENDIF}
end
end;
end;
procedure TLoadImagesThread.SyncBmpLoadFail;
begin
if (assigned(fOnBmpLoadFail)) then
try
fOnBmpLoadFail(self, fIdx);
except
on e:exception do begin
{$IFNDEF NOLOG} GLog.Log(self,[lcExcept],'SyncBmpLoadFail '+inttostr(fIdx)+ 'e:'+e.message );{$ENDIF}
end
end;
end;
end.
|
unit Getter.VolumeLabel;
interface
uses
Classes, Windows, SysUtils,
MeasureUnit.DataSize, OSFile.ForInternal;
type
TVolumeLabelGetter = class(TOSFileForInternal)
private
type
TNTBSVolumeName = Array[0..MAX_PATH] of Char;
private
VolumeLabelInNTBS: TNTBSVolumeName;
procedure SetVolumeLabelInNTBS;
procedure IfVolumeLabelIsNullUseAlternative(const AlternativeName: String);
function GetSizeOfDiskInMB: Double;
function AppendSizeOfDiskInMB(const AlternativeName: String): String;
function GetByteToMega: TDatasizeUnitChangeSetting;
public
function GetVolumeLabel(const AlternativeName: String): String;
end;
procedure PathListToVolumeLabel(const PathList: TStrings;
const AlternativeName: String);
implementation
function TVolumeLabelGetter.GetByteToMega: TDatasizeUnitChangeSetting;
begin
result.FNumeralSystem := Denary;
result.FFromUnit := ByteUnit;
result.FToUnit := MegaUnit;
end;
function TVolumeLabelGetter.GetSizeOfDiskInMB: Double;
const
VolumeNames = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var
SizeOfDiskInByte: Int64;
begin
SizeOfDiskInByte := DiskSize(Pos(GetPathOfFileAccessing[1], VolumeNames));
exit(ChangeDatasizeUnit(SizeOfDiskInByte, GetByteToMega));
end;
procedure TVolumeLabelGetter.SetVolumeLabelInNTBS;
var
MaximumComponentLength: DWORD;
VolumeFlags: DWORD;
VolumeSerialNumber: DWORD;
begin
ZeroMemory(@VolumeLabelInNTBS, SizeOf(VolumeLabelInNTBS));
GetVolumeInformation(PChar(GetPathOfFileAccessing), VolumeLabelInNTBS,
SizeOf(VolumeLabelInNTBS), @VolumeSerialNumber, MaximumComponentLength,
VolumeFlags, nil, 0);
end;
procedure TVolumeLabelGetter.IfVolumeLabelIsNullUseAlternative(
const AlternativeName: String);
begin
if VolumeLabelInNTBS[0] = #0 then
CopyMemory(@VolumeLabelInNTBS, @AlternativeName[1],
Length(AlternativeName) * SizeOf(Char));
end;
function TVolumeLabelGetter.AppendSizeOfDiskInMB(
const AlternativeName: String): String;
const
DenaryInteger: TFormatSizeSetting =
(FNumeralSystem: Denary; FPrecision: 0);
var
SizeOfDiskInMB: Double;
begin
SizeOfDiskInMB := GetSizeOfDiskInMB;
result :=
GetPathOfFileAccessing + ' (' + VolumeLabelInNTBS + ' - ' +
FormatSizeInMB(SizeOfDiskInMB, DenaryInteger) + ')';
end;
function TVolumeLabelGetter.GetVolumeLabel(const AlternativeName: String):
String;
begin
SetVolumeLabelInNTBS;
IfVolumeLabelIsNullUseAlternative(AlternativeName);
exit(AppendSizeOfDiskInMB(AlternativeName));
end;
procedure PathListToVolumeLabel(const PathList: TStrings;
const AlternativeName: String);
var
VolumeLabelGetter: TVolumeLabelGetter;
CurrentPath: Integer;
begin
for CurrentPath := 0 to PathList.Count - 1 do
begin
VolumeLabelGetter := TVolumeLabelGetter.Create(PathList[CurrentPath]);
PathList[CurrentPath] := VolumeLabelGetter.GetVolumeLabel(AlternativeName);
FreeAndNil(VolumeLabelGetter);
end;
end;
end.
|
unit Extern.SevenZip;
interface
uses
SysUtils,
OS.ProcessOpener, Getter.CodesignVerifier;
type
TSevenZip = class
private
function BuildCommand
(const SzipPath, SrcFile, DestFolder, Password: String): String;
function VerifySevenZip(const SzipPath: String): Boolean;
public
function Extract
(const SzipPath, SrcFile, DestFolder: String;
const Password: String = ''): AnsiString;
class function Create: TSevenZip;
end;
var
SevenZip: TSevenZip;
implementation
{ TSevenZip }
function TSevenZip.BuildCommand(const SzipPath, SrcFile, DestFolder,
Password: String): String;
begin
result :=
'"' + SzipPath + '" e -y ' +
'-o"' + DestFolder + '\" ' +
'"' + SrcFile + '"';
if Length(Password) = 0 then
exit;
result :=
result + ' -p"' + Password + '"';
end;
function TSevenZip.VerifySevenZip(const SzipPath: String): Boolean;
var
CodesignVerifier: TCodesignVerifier;
begin
CodesignVerifier := TCodesignVerifier.Create;
result := CodesignVerifier.VerifySignByPublisher(SzipPath, 'Minkyu Kim');
FreeAndNil(CodesignVerifier);
end;
class function TSevenZip.Create: TSevenZip;
begin
if SevenZip = nil then
result := inherited Create as self
else
result := SevenZip;
end;
function TSevenZip.Extract
(const SzipPath, SrcFile, DestFolder, Password: String): AnsiString;
begin
result := '';
if VerifySevenZip(SzipPath) then
result :=
ProcessOpener.OpenProcWithOutput('C:\',
BuildCommand(SzipPath, SrcFile, DestFolder, Password));
end;
initialization
SevenZip := TSevenZip.Create;
finalization
SevenZip.Free;
end.
|
namespace Documents;
interface
uses
AppKit;
type
[IBObject]
FooDocument = public class(NSDocument)
method loadDocumentFromURL(url: NSURL): Boolean;
method saveDocumentToURL(url: NSURL): Boolean;
public
property data: FooDocumentData read private write ;
// NSDocument implementation
constructor withType(&type: NSString) error(error: ^NSError); override; // workaround for invalid NSError pointer being passed in, sometimes
method readFromURL(url: not nullable NSURL) ofType(typeName: not nullable NSString) error(var error: NSError): Boolean; override;
method writeToURL(url: not nullable NSURL) ofType(typeName: not nullable NSString) forSaveOperation(aveOperation: NSSaveOperationType) originalContentsURL(absoluteOriginalContentsURL: nullable NSURL) error(var error: NSError): Boolean; override;
method makeWindowControllers; override;
class property autosavesInPlace: Boolean read true; override;
end;
FooDocumentData = public class
public
property text: NSString read write ;
constructor;
constructor withURL(url: NSURL);
method save(url: NSURL);
end;
implementation
constructor FooDocument withType(&type: NSString) error(error: ^NSError);
begin
data := new FooDocumentData();
end;
method FooDocument.readFromURL(url: not nullable NSURL) ofType(typeName: not nullable NSString) error(var error: NSError): Boolean;
begin
result := loadDocumentFromURL(url);
end;
method FooDocument.writeToURL(url: not nullable NSURL) ofType(typeName: not nullable NSString) forSaveOperation(aveOperation: NSSaveOperationType) originalContentsURL(absoluteOriginalContentsURL: nullable NSURL) error(var error: NSError): Boolean;
begin
result := saveDocumentToURL(url);
end;
method FooDocument.makeWindowControllers;
begin
addWindowController(new FooDocumentWindowController withDocument(self));
end;
method FooDocument.loadDocumentFromURL(url: NSURL): Boolean;
begin
data := new FooDocumentData withURL(url);
exit assigned(data);
end;
method FooDocument.saveDocumentToURL(url: NSURL): Boolean;
begin
if data = nil then
exit false;
data.save(url);
result := true;
end;
constructor FooDocumentData;
begin
text := 'New Foo!';
end;
constructor FooDocumentData withURL(url: NSURL);
begin
if File.Exists(url.path) then
text := File.ReadText(url.path)
else
exit nil;
end;
method FooDocumentData.save(url: NSURL);
begin
File.WriteText(url.path, text);
end;
end. |
unit Unit2;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.ComCtrls, Data.FMTBcd,
Data.DB, Data.SqlExpr, Data.DbxSqlite, Vcl.Grids, Vcl.DBGrids, Vcl.Themes;
type
TForm1 = class(TForm)
Panel1: TPanel;
Edit1: TEdit;
btnConnection: TButton;
btnExecute: TButton;
Memo1: TMemo;
StatusBar1: TStatusBar;
SQLConnection: TSQLConnection;
SQLQuery: TSQLQuery;
DBGrid1: TDBGrid;
LinkLabel1: TLinkLabel;
ComboBox1: TComboBox;
procedure FormCreate(Sender: TObject);
procedure btnConnectionClick(Sender: TObject);
procedure btnExecuteClick(Sender: TObject);
procedure ComboBox1Change(Sender: TObject);
private
{ Déclarations privées }
procedure ShowSelectResults();
public
{ Déclarations publiques }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.btnConnectionClick(Sender: TObject);
begin
SQLConnection.Params.Add(Edit1.Text);
try
SQLConnection.Connected := True;
btnExecute.Enabled := True;
Memo1.Lines.Add('Connection established!');
except
on E: EDatabaseError do
ShowMessage('Exception raised with message' + E.Message);
on E: Exception do
ShowMessage('Exception raised with message' + E.Message);
end;
end;
procedure TForm1.btnExecuteClick(Sender: TObject);
var
query: string;
begin
Memo1.ClearSelection;
query := 'SELECT * FROM Operations;';
try
SQLQuery.SQL.Clear;
SQLQuery.SQL.Add(query);
SQLQuery.Active := True;
except
on E: Exception do
Memo1.Lines.Add('raised with message: ' + E.Message);
end;
ShowSelectResults();
end;
procedure TForm1.ComboBox1Change(Sender: TObject);
begin
TStyleManager.SetStyle(ComboBox1.Items[ComboBox1.ItemIndex]);
end;
procedure TForm1.ShowSelectResults();
var
names: TStringList;
currentLine: string;
i: Integer;
currentField: TField;
begin
if not SQLQuery.IsEmpty then
begin
SQLQuery.First;
names := TStringList.Create;
try
SQLQuery.GetFieldNames(names);
while not SQLQuery.Eof do
begin
currentLine := '';
for i := 0 to names.Count - 1 do
begin
currentField := SQLQuery.FieldByName(names[i]);
currentLine := currentLine + ' ' + currentField.AsString;
end;
Memo1.Lines.Add(currentLine);
SQLQuery.Next;
end;
finally
names.Free;
end;
end;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
SQLConnection.DriverName := 'SQLite';
btnConnection.Enabled := True;
btnExecute.Enabled := False;
Edit1.Text := 'C:\Opensource\SQLiteDatabaseBrowserPortable\Data\test1.db';
Memo1.Lines.Clear;
// Chargement du combobox des styles (
ComboBox1.Items.Clear;
ComboBox1.Items.AddStrings(TStyleManager.StyleNames);
ComboBox1.ItemIndex := ComboBox1.Items.IndexOf(TStyleManager.ActiveStyle.Name);
end;
end.
|
Unit SDS_Det;
{
Sound Deluxe System 5
a Maple Leaf production, 1996-1997
(Maple Leaf is a.k.a. Gruian Radu Bogdan)
---------------------------------------------------------------------
Souncards detection and initialization routines
---------------------------------------------------------------------
This program is part of the Sound Deluxe System 5, and it cannot
be modified or sold without the written permission of the author. The
author does not assume any responsability for the incidental loss or
hardware/software damages produced while using this program or any other
part of the Sound Deluxe System. The author also does not assume any
responsability for the damages produced by using modified parts of this
package. Blah, blah...
---------------------------------------------------------------------
Detection order:
GUS-SB16-WSS-PAS-Aria-SBPro-SB2/SB
}
Interface
var
Base, Irq, Dma : WORD; { Set up by the routines below }
Card : WORD; { Same for this shit }
function DetectSoundCard(var Base:WORD; var Irq:WORD; var Dma:WORD):word;far;
function InitSoundCard(Card, Base, Irq, Dma:WORD):boolean;
function InitSB(Base, Irq, Dma:WORD):Boolean;far;
function DetectSB(var Base:WORD; var Irq:WORD; var Dma:WORD):Boolean;far;
function InitSBPro(Base, Irq, Dma:WORD):Boolean;far;
function DetectSBPro(var Base:WORD; var Irq:WORD; var Dma:WORD):Boolean;far;
function InitSB16(Base, Irq, Dma:WORD):Boolean;far;
function DetectSB16(var Base:WORD; var Irq:WORD; var Dma:WORD):Boolean;far;
function InitGUS(Base, Irq, Dma:WORD):Boolean;far;
function DetectGUS(var Base:WORD; var Irq:WORD; var Dma:WORD):Boolean;far;
function InitPAS(Base, Irq, Dma:WORD):Boolean;far;
function DetectPAS(var Base:WORD; var Irq:WORD; var Dma:WORD):Boolean;far;
function InitWSS(Base, Irq, Dma:WORD):Boolean;far;
function DetectWSS(var Base:WORD; var Irq:WORD; var Dma:WORD):Boolean;far;
function InitARIA(Base, Irq, Dma:WORD):Boolean;far;
function DetectARIA(var Base:WORD; var Irq:WORD; var Dma:WORD):Boolean;far;
Implementation
{$L sds_det.obj}
function InitSB;external;
function DetectSB;external;
function InitSBPro;external;
function DetectSBPro;external;
function InitSB16;external;
function DetectSB16;external;
function InitGUS;external;
function DetectGUS;external;
function InitPAS;external;
function DetectPAS;external;
function InitWSS;external;
function DetectWSS;external;
function InitARIA;external;
function DetectARIA;external;
function DetectSoundCard(var Base:WORD; var Irq:WORD; var Dma:WORD):word;
begin
if DetectGUS (Base,Irq,Dma) then card:=4 else
if DetectSB16 (Base,Irq,Dma) then card:=3 else
if DetectWSS (Base,Irq,Dma) then card:=6 else
if DetectPAS (Base,Irq,Dma) then card:=5 else
if DetectARIA (Base,Irq,Dma) then card:=7 else
if DetectSBPro (Base,Irq,Dma) then card:=2 else
if DetectSB (Base,Irq,Dma) then card:=1 else
begin
card:=8; base:=$378; dma:=0; Irq:=0; {not used}
end;
DetectSoundCard:=card; {useless, just for compatibility with a previous SDS version}
end;
function InitSoundCard(Card, Base, Irq, Dma:WORD):boolean;
var yes:boolean;
begin
case Card of
1: yes:=InitSB(Base,Irq,Dma);
2: yes:=InitSBPro(Base,Irq,Dma);
3: yes:=InitSB16(Base,Irq,Dma);
4: yes:=InitGUS(Base,Irq,Dma);
5: yes:=InitPAS(Base,Irq,Dma);
6: yes:=InitWSS(Base,Irq,Dma);
7: yes:=InitAria(Base,Irq,Dma);
8: yes:=true;
else yes:=false;
end;
InitSoundCard:=yes;
end;
begin
end. |
unit uDynArray;
interface
uses
Winapi.Windows, Winapi.Messages,
System.SysUtils, System.Classes, System.Character, System.Variants,
Generics.Collections, Generics.Defaults,
VCL.Forms;
type
TDynArrayObjectDestroyEvent = procedure( Sender: TObject );
TDynArrayObject< T > = class
private
FItems: TArray< T >;
FCapacity: Cardinal;
FCount: Cardinal;
FIndex: Integer;
FOnDestroy: TDynArrayObjectDestroyEvent;
function GetItem( Index: Integer ): T;
procedure SetItem( Index: Integer; Value: T );
public
constructor Create( Capacity: Cardinal; OnDestroy: TDynArrayObjectDestroyEvent );
destructor Destroy; override;
procedure Append( Value: T );
procedure Trim;
procedure Purge;
property Count: Cardinal read FCount;
property Items[ Index: Integer ]: T read GetItem write SetItem; default;
end;
type
TDynArray< T > = record
private
FCapacity: Integer;
FCount: Integer;
procedure Expand;
procedure SetCapacity( Capacity: Integer );
public
Items: TArray< T >;
type
P = ^T;
procedure Init( Capacity: Integer );
procedure Purge;
procedure Trim;
procedure Push( Item: T );
procedure Pop; overload;
procedure Pop( var Item: T ); overload;
function GetItem( Index: Integer ): Pointer;
function NewItem: Pointer;
function FirstItem: Pointer;
function LastItem: Pointer;
procedure LastItemFrom( Source: P { P = ^T } ); overload;
procedure LastItemFrom( Source: TArray< T >; SourceIndex: Integer ); overload;
procedure CopyFrom( Source: TArray< T >; SourceIndex: Integer; DestIndex: Integer; Count: Integer = 1 );
property Count: Integer read FCount;
end;
implementation
{ TDynArrayObject<T> }
procedure TDynArrayObject< T >.Append( Value: T );
var
i: Cardinal;
Delta: Cardinal;
begin
if FCount < FCapacity then
Delta := 0
else if FCapacity > 64 then
Delta := FCapacity div 4
else if FCapacity > 8 then
Delta := 16
else
Delta := 4;
FCapacity := FCapacity + Delta;
if Delta > 0 then
SetLength( FItems, FCapacity );
FItems[ FCount ] := Value;
FCount := FCount + 1;
end;
procedure TDynArrayObject< T >.Purge;
begin
FItems := nil;
end;
constructor TDynArrayObject< T >.Create( Capacity: Cardinal; OnDestroy: TDynArrayObjectDestroyEvent );
begin
inherited Create;
FCount := 0;
FOnDestroy := OnDestroy;
FCapacity := Capacity;
SetLength( FItems, Capacity ); // Purge memory after GetMem()
end;
destructor TDynArrayObject< T >.Destroy;
begin
if Assigned( FOnDestroy ) then
FOnDestroy( Self );
FItems := nil; // Free everything
inherited;
end;
function TDynArrayObject< T >.GetItem( Index: Integer ): T;
begin
Result := FItems[ Index ];
end;
procedure TDynArrayObject< T >.SetItem( Index: Integer; Value: T );
begin
FItems[ Index ] := Value;
end;
procedure TDynArrayObject< T >.Trim;
begin
FCapacity := FCount;
SetLength( FItems, FCapacity );
end;
{ TDynArray<T> }
procedure TDynArray< T >.Pop( var Item: T );
begin
Dec( FCount );
Item := Items[ FCount ];
Items[ FCount ] := Default ( T );
end;
procedure TDynArray< T >.Pop;
begin
Dec( FCount );
Items[ FCount ] := Default ( T );
end;
procedure TDynArray< T >.CopyFrom( Source: TArray< T >; SourceIndex: Integer; DestIndex: Integer; Count: Integer );
begin
CopyArray( Addr( Items[ DestIndex ] ), Addr( Source[ SourceIndex ] ), TypeInfo( T ), Count );
end;
procedure TDynArray< T >.Expand;
var
i: Cardinal;
Delta: Cardinal;
begin
if FCount < FCapacity then
Exit;
if FCapacity > 64 then
Delta := FCapacity div 4
else if FCapacity > 8 then
Delta := 16
else
Delta := 4;
FCapacity := FCapacity + Delta;
SetLength( Items, FCapacity );
end;
procedure TDynArray< T >.Push( Item: T );
begin
Expand( );
Items[ FCount ] := Item;
FCount := FCount + 1;
end;
function TDynArray< T >.GetItem( Index: Integer ): Pointer;
begin
Result := Addr( Items[ Index ] );
end;
function TDynArray< T >.NewItem: Pointer;
begin
Expand( );
Result := Addr( Items[ FCount ] );
FCount := FCount + 1;
end;
procedure TDynArray< T >.Purge;
begin
FCount := 0;
SetCapacity( 0 ); // Free everything
end;
function TDynArray< T >.FirstItem: Pointer;
begin
Result := Addr( Items[ 0 ] );
end;
procedure TDynArray< T >.Init( Capacity: Integer );
begin
Purge;
SetCapacity( Capacity );
end;
function TDynArray< T >.LastItem: Pointer;
begin
Result := Addr( Items[ FCount - 1 ] );
end;
procedure TDynArray< T >.LastItemFrom( Source: P );
begin
CopyArray( Addr( Items[ Self.FCount - 1 ] ), Source, TypeInfo( T ), 1 );
end;
procedure TDynArray< T >.LastItemFrom( Source: TArray< T >; SourceIndex: Integer );
begin
CopyArray( Addr( Items[ FCount - 1 ] ), Addr( Source[ SourceIndex ] ), TypeInfo( T ), 1 );
end;
procedure TDynArray< T >.SetCapacity( Capacity: Integer );
begin
FCapacity := Capacity;
SetLength( Items, Capacity ); // Clear memory after GetMem()
end;
procedure TDynArray< T >.Trim;
begin
FCapacity := FCount;
SetLength( Items, FCapacity );
end;
end.
|
{$i deltics.interfacedobjects.inc}
unit Deltics.InterfacedObjects.ComInterfacedObject;
interface
uses
Deltics.InterfacedObjects.InterfacedObject,
Deltics.InterfacedObjects.ObjectLifecycle;
type
TComInterfacedObject = class(TInterfacedObject)
private
fReferenceCount: Integer;
protected
procedure DoDestroy; virtual;
public
class function NewInstance: TObject; override;
procedure AfterConstruction; override;
procedure BeforeDestruction; override;
// IUnknown
protected
function _AddRef: Integer; override;
function _Release: Integer; override;
// IInterfacedObject overrides
protected
function get_IsReferenceCounted: Boolean; override;
function get_Lifecycle: TObjectLifecycle; override;
function get_ReferenceCount: Integer; override;
public
procedure Free; reintroduce;
end;
implementation
uses
Windows,
SysUtils;
{ TComInterfacedObject --------------------------------------------------------------------------- }
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
function TComInterfacedObject._AddRef: Integer;
begin
if NOT (IsBeingDestroyed) then
result := InterlockedIncrement(fReferenceCount)
else
result := 1;
end;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
function TComInterfacedObject._Release: Integer;
begin
if NOT (IsBeingDestroyed) then
begin
result := InterlockedDecrement(fReferenceCount);
if (result = 0) then
DoDestroy;
end
else
result := 1;
end;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
procedure TComInterfacedObject.AfterConstruction;
begin
inherited;
// Now that the constructors are done, remove the reference count we added
// in NewInstance - the reference count will typically be zero at this
// point as a result, but will then get bumped back to 1 (one) by the
// assignment of the constructed instance to some interface reference var
InterlockedDecrement(fReferenceCount);
end;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
procedure TComInterfacedObject.BeforeDestruction;
begin
if (fReferenceCount <> 0) then
System.Error(reInvalidPtr);
inherited;
end;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
procedure TComInterfacedObject.DoDestroy;
begin
Destroy;
end;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
procedure TComInterfacedObject.Free;
begin
if (fReferenceCount > 0) then
raise EInvalidPointer.Create('You must not explicitly free a COM interfaced object (or class '
+ 'derived from it) where interface references have been '
+ 'obtained. The lifecycle of these objects is determined by '
+ 'reference counting.');
Destroy;
end;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
function TComInterfacedObject.get_IsReferenceCounted: Boolean;
begin
result := TRUE;
end;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
function TComInterfacedObject.get_Lifecycle: TObjectLifecycle;
begin
result := olReferenceCOunted;
end;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
function TComInterfacedObject.get_ReferenceCount: Integer;
begin
result := fReferenceCount;
end;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
class function TComInterfacedObject.NewInstance: TObject;
begin
result := inherited NewInstance;
// Ensure a minimum reference count of 1 during execution of the constructors
// to protect against _Release destroying ourselves as a result of interface
// references being passed around
InterlockedIncrement(TComInterfacedObject(result).fReferenceCount);
end;
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{: GLEParticleMasksManager<p>
A pretty particle mask effect manager.<p>
<b>History : </b><font size=-1><ul>
<li>16/03/11 - Yar - Fixes after emergence of GLMaterialEx
<li>24/03/07 - Improved Cross-Platform compatibility (BugTracker ID = 1684432)
Got rid of Types dependancy
<li>29/01/07 - DaStr - Initial version (donated to GLScene by Kenneth Poulter)
Original Header:
GLEParticleMasksManager.pas
This unit is part of GLE - GLScene Game Utilities Engine set by Kenneth Poulter difacane@telkomsa.net
Module Number: 37
Description: This is merely an addon to GLScene, since i don't want to edit GLScene's source code directly
and make changes (since GLScene's source code constantly changes). What the manager does
is to provide a basic tool for newly created particles to be modified (their position currently).
Their position is set from 3 different masks, which create a "virtual" 3d object... meaning,
an actual 3d object is not created, but an outline for particles or any other objects are positioned.
ActualUsage: Create the component, create a new ParticleMask, set the material library, set the materials,
and use the procedures provided in the managers root. positioning and scaling applicable aswell.
The images should be
Licenses: Removed. Donated to GLScene's Code Base as long as the author (Kenneth Poulter) is not altered in this file.
Theft of code also is not allowed, although alterations are allowed.
History:
28/12/2005 - Added - LX,LY,LZ for correct positioning;
Rotating;
GenerateParticleMaskFromProjection;
Targeting Objects (scales, positions and rotation of object applies)
27/12/2005 - Added - Scale and Positioning
27/12/2005 - Improved code speed significantly (could do better)
26/12/2005 - Creation of base code from experimentation
}
unit GLEParticleMasksManager;
interface
{$I GLScene.inc}
uses
System.SysUtils, System.Classes, System.Math,
VCL.Graphics,
// GLS
GLTexture, GLMaterial, GLScene, GLVectorGeometry, GLVectorTypes,
GLParticleFX, GLCrossPlatform, GLCoordinates;
type
TGLEProjectedParticleMask = (pptXMask, pptYMask, pptZMask);
TGLEParticleMask = class;
TGLEParticleMasks = class;
TGLEParticleMask = class(TCollectionItem, IGLMaterialLibrarySupported)
private
{ Private Declarations }
FName: string;
FScale: TGLCoordinates;
FPosition: TGLCoordinates;
FYMask: TGLLibMaterialName;
FZMask: TGLLibMaterialName;
FXMask: TGLLibMaterialName;
FMaterialLibrary: TGLMaterialLibrary;
FBackgroundColor: TDelphiColor;
FMaskColor: TDelphiColor;
FMaxX, FMaxY, FMaxZ, FMinX, FMinY, FMinZ: Integer;
IXW, IXH, IYW, IYH, IZW, IZH: Integer;
LX, LY, LZ: Integer;
MX, MY: Integer;
BogusMask, BogusMaskX, BogusMaskY, BogusMaskZ: Boolean;
// we might have a pitch mask
FRollAngle: Single;
FPitchAngle: Single;
FTurnAngle: Single;
procedure SetName(const Value: string);
procedure SetXMask(const Value: TGLLibMaterialName);
procedure SetYMask(const Value: TGLLibMaterialName);
procedure SetZMask(const Value: TGLLibMaterialName);
procedure SetMaterialLibrary(const Value: TGLMaterialLibrary);
function XCan: TGLBitmap;
function YCan: TGLBitmap;
function ZCan: TGLBitmap;
//implementing IGLMaterialLibrarySupported
function GetMaterialLibrary: TGLAbstractMaterialLibrary;
//implementing IInterface
function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall;
function _AddRef: Integer; stdcall;
function _Release: Integer; stdcall;
protected
{ Protected Declarations }
function GetDisplayName: string; override;
public
{ Public Declarations }
constructor Create(Collection: TCollection); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
procedure UpdateExtents;
procedure Roll(Angle: Single);
procedure Turn(Angle: Single);
procedure Pitch(Angle: Single);
// this generates a xmask from another mask just to fill gaps,
// depth is dependant on frommask width and height
procedure GenerateMaskFromProjection(FromMask, ToMask:
TGLEProjectedParticleMask; Depth: Integer);
published
{ Published Declarations }
// scales and positions
property Scale: TGLCoordinates read FScale write FScale;
property Position: TGLCoordinates read FPosition write FPosition;
// the reference name of the particle mask
property Name: string read FName write SetName;
property MaterialLibrary: TGLMaterialLibrary read FMaterialLibrary write
SetMaterialLibrary;
// mask images, make sure materiallibrary is assigned
property XMask: TGLLibMaterialName read FXMask write SetXMask;
property YMask: TGLLibMaterialName read FYMask write SetYMask;
property ZMask: TGLLibMaterialName read FZMask write SetZMask;
// background color is the color that prevents particles from being positioned there
property BackgroundColor: TDelphiColor read FBackgroundColor write
FBackgroundColor;
// maskcolor is where particles are allowed to be positioned
property MaskColor: TDelphiColor read FMaskColor write FMaskColor;
// just the average angles for orientation
property RollAngle: Single read FRollAngle write FRollAngle;
property PitchAngle: Single read FPitchAngle write FPitchAngle;
property TurnAngle: Single read FTurnAngle write FTurnAngle;
end;
TGLEParticleMasks = class(TCollection)
protected
{ Protected Declarations }
Owner: TComponent;
function GetOwner: TPersistent; override;
procedure SetItems(Index: Integer; const Val: TGLEParticleMask);
function GetItems(Index: Integer): TGLEParticleMask;
public
{ Public Declarations }
function Add: TGLEParticleMask;
constructor Create(AOwner: TComponent);
property Items[Index: Integer]: TGLEParticleMask read GetItems write
SetItems; default;
end;
TGLEParticleMasksManager = class(TComponent)
private
FParticleMasks: TGLEParticleMasks;
{ Private declarations }
protected
{ Protected declarations }
procedure ApplyOrthoGraphic(var Vec: TVector3f; Mask: TGLEParticleMask);
procedure ApplyRotation(var Vec: TVector3f; Mask: TGLEParticleMask);
procedure ApplyRotationTarget(var Vec: TVector3f; Mask: TGLEParticleMask;
TargetObject: TGLBaseSceneObject);
procedure ApplyScaleAndPosition(var Vec: TVector3f; Mask: TGLEParticleMask);
procedure ApplyScaleAndPositionTarget(var Vec: TVector3f; Mask:
TGLEParticleMask; TargetObject: TGLBaseSceneObject);
procedure FindParticlePosition(var Vec: TVector3f; Mask: TGLEParticleMask);
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function CreateParticlePositionFromMask(MaskName: string): TVector3f;
function TargetParticlePositionFromMask(TargetObject: TGLBaseSceneObject;
MaskName: string): TVector3f;
procedure SetParticlePositionFromMask(Particle: TGLParticle; MaskName:
string);
procedure SetParticlePositionFromMaskTarget(Particle: TGLParticle; MaskName:
string; TargetObject: TGLBaseSceneObject);
function ParticleMaskByName(MaskName: string): TGLEParticleMask;
published
{ Published declarations }
property ParticleMasks: TGLEParticleMasks read FParticleMasks write
FParticleMasks;
end;
implementation
{ TGLEParticleMasks }
function TGLEParticleMasks.Add: TGLEParticleMask;
begin
Result := (inherited Add) as TGLEParticleMask;
end;
constructor TGLEParticleMasks.Create(AOwner: TComponent);
begin
inherited Create(TGLEParticleMask);
Owner := AOwner;
end;
function TGLEParticleMasks.GetItems(Index: Integer): TGLEParticleMask;
begin
Result := TGLEParticleMask(inherited Items[Index]);
end;
function TGLEParticleMasks.GetOwner: TPersistent;
begin
Result := Owner;
end;
procedure TGLEParticleMasks.SetItems(Index: Integer; const Val:
TGLEParticleMask);
begin
inherited Items[Index] := Val;
end;
{ TGLEParticleMask }
procedure TGLEParticleMask.Assign(Source: TPersistent);
begin
if Source is TGLEParticleMask then
begin
FScale.Assign(TGLEParticleMask(Source).FScale);
FPosition.Assign(TGLEParticleMask(Source).FPosition);
FMaterialLibrary := TGLEParticleMask(Source).FMaterialLibrary;
FXMask := TGLEParticleMask(Source).FXMask;
FYMask := TGLEParticleMask(Source).FYMask;
FZMask := TGLEParticleMask(Source).FZMask;
end
else
inherited Assign(Source);
end;
constructor TGLEParticleMask.Create(Collection: TCollection);
begin
inherited Create(Collection);
FName := 'ParticleMask' + IntToStr(ID);
FScale := TGLCoordinates.CreateInitialized(Self, XYZHMGVector, csPoint);
FPosition := TGLCoordinates.CreateInitialized(Self, NullHmgPoint, csPoint);
FMaterialLibrary := nil;
FMaskColor := clWhite;
FBackGroundColor := clBlack;
FTurnAngle := 0;
FRollAngle := 0;
FPitchAngle := 0;
FXMask := '';
FYMask := '';
FZMask := '';
UpdateExtents;
end;
destructor TGLEParticleMask.Destroy;
begin
FScale.Free;
FPosition.Free;
FMaterialLibrary := nil;
FBackgroundColor := clBlack;
FMaskColor := clWhite;
FXMask := '';
FYMask := '';
FZMask := '';
inherited Destroy;
end;
procedure TGLEParticleMask.GenerateMaskFromProjection(FromMask,
ToMask: TGLEProjectedParticleMask; Depth: Integer);
var
FromBitMap: TGLBitmap;
ToBitMap: TGLBitmap;
X, Y: Integer;
Rect: TGLRect;
begin
FromBitMap := nil;
ToBitMap := nil;
if not assigned(FMaterialLibrary) then
Exit;
if FromMask = ToMask then
Exit; // we can't project to the same mask
if Depth < 0 then
Exit;
case FromMask of
pptXMask: FromBitMap := XCan;
pptYMask: FromBitMap := YCan;
pptZMask: FromBitMap := ZCan;
end;
if (FromBitMap.Width = 0) and (FromBitMap.Height = 0) then
Exit; // we can't use something that has no image
case ToMask of
pptXMask: ToBitMap := XCan;
pptYMask: ToBitMap := YCan;
pptZMask: ToBitMap := ZCan;
end;
ToBitMap.Width := FromBitMap.Width;
ToBitMap.Height := FromBitMap.Height;
ToBitMap.Canvas.Pen.Color := FBackgroundColor;
ToBitMap.Canvas.Pen.Style := psSolid;
ToBitMap.Canvas.Brush.Color := FBackgroundColor;
ToBitMap.Canvas.Brush.Style := bsSolid;
Rect.Left := 0;
Rect.Top := 0;
Rect.Right := ToBitMap.Width;
Rect.Bottom := ToBitMap.Height;
ToBitMap.Canvas.FillRect(Rect);
ToBitMap.Canvas.Pen.Color := FMaskColor;
ToBitMap.Canvas.Brush.Color := FMaskColor;
for X := 0 to ToBitMap.Width do
for Y := 0 to ToBitMap.Height do
begin
// from x mask
if (FromMask = pptXMask) and (ToMask = pptYMask) then
if FromBitMap.Canvas.Pixels[X, Y] = FMaskColor then
begin
ToBitMap.Canvas.MoveTo(((FromBitmap.Width - Depth) div 2), X);
ToBitMap.Canvas.LineTo(((FromBitmap.Width + Depth) div 2), X);
end;
if (FromMask = pptXMask) and (ToMask = pptZMask) then
if FromBitMap.Canvas.Pixels[X, Y] = FMaskColor then
begin
ToBitMap.Canvas.MoveTo(((FromBitmap.Width - Depth) div 2), Y);
ToBitMap.Canvas.LineTo(((FromBitmap.Width + Depth) div 2), Y);
end;
// from y mask
if (FromMask = pptYMask) and (ToMask = pptXMask) then
if FromBitMap.Canvas.Pixels[X, Y] = FMaskColor then
begin
ToBitMap.Canvas.MoveTo(Y, ((FromBitmap.Height - Depth) div 2));
ToBitMap.Canvas.LineTo(Y, ((FromBitmap.Height + Depth) div 2));
end;
if (FromMask = pptYMask) and (ToMask = pptZMask) then
if FromBitMap.Canvas.Pixels[X, Y] = FMaskColor then
begin
ToBitMap.Canvas.MoveTo(X, ((FromBitmap.Height - Depth) div 2));
ToBitMap.Canvas.LineTo(X, ((FromBitmap.Height + Depth) div 2));
end;
// from z mask
if (FromMask = pptZMask) and (ToMask = pptXMask) then
if FromBitMap.Canvas.Pixels[X, Y] = FMaskColor then
begin
ToBitMap.Canvas.MoveTo(((FromBitmap.Width - Depth) div 2), Y);
ToBitMap.Canvas.LineTo(((FromBitmap.Width + Depth) div 2), Y);
end;
if (FromMask = pptZMask) and (ToMask = pptYMask) then
if FromBitMap.Canvas.Pixels[X, Y] = FMaskColor then
begin
ToBitMap.Canvas.MoveTo(X, ((FromBitmap.Height - Depth) div 2));
ToBitMap.Canvas.LineTo(X, ((FromBitmap.Height + Depth) div 2));
end;
end;
UpdateExtents;
end;
function TGLEParticleMask.GetDisplayName: string;
begin
Result := '';
if FName <> '' then
Result := FName
else
Result := 'TGLEParticleMask';
end;
function TGLEParticleMask.GetMaterialLibrary: TGLAbstractMaterialLibrary;
begin
Result := FMaterialLibrary;
end;
procedure TGLEParticleMask.Pitch(Angle: Single);
begin
FPitchAngle := FPitchAngle + Angle;
end;
procedure TGLEParticleMask.Roll(Angle: Single);
begin
FRollAngle := FRollAngle + Angle;
end;
procedure TGLEParticleMask.SetMaterialLibrary(const Value: TGLMaterialLibrary);
begin
FMaterialLibrary := Value;
UpdateExtents;
end;
procedure TGLEParticleMask.SetName(const Value: string);
var
I: Integer;
begin
for I := 1 to Length(Value) do
if Value[I] = ' ' then
begin
raise Exception.Create('Cannot contain spaces or special characters.');
Exit;
end;
FName := Value;
end;
procedure TGLEParticleMask.SetXMask(const Value: TGLLibMaterialName);
begin
FXMask := Value;
if assigned(FMaterialLibrary) then
if not assigned(FMaterialLibrary.LibMaterialByName(FXMask)) then
begin
XCan.Width := 0;
XCan.Height := 0;
end;
UpdateExtents;
end;
procedure TGLEParticleMask.SetYMask(const Value: TGLLibMaterialName);
begin
FYMask := Value;
if assigned(FMaterialLibrary) then
if not assigned(FMaterialLibrary.LibMaterialByName(FYMask)) then
begin
YCan.Width := 0;
YCan.Height := 0;
end;
UpdateExtents;
end;
procedure TGLEParticleMask.SetZMask(const Value: TGLLibMaterialName);
begin
FZMask := Value;
if assigned(FMaterialLibrary) then
if not assigned(FMaterialLibrary.LibMaterialByName(FZMask)) then
begin
ZCan.Width := 0;
ZCan.Height := 0;
end;
UpdateExtents;
end;
procedure TGLEParticleMask.Turn(Angle: Single);
begin
FTurnAngle := FTurnAngle + Angle;
end;
procedure TGLEParticleMask.UpdateExtents;
var
MinXX, MinXY, MinYX, MinYY, MinZX, MinZY: Integer;
MaxXX, MaxXY, MaxYX, MaxYY, MaxZX, MaxZY: Integer;
X, Y: Integer;
begin
FMinX := 0; // min extents
FMinY := 0;
FMinZ := 0;
FMaxX := 0; // max extents
FMaxY := 0;
FMaxZ := 0;
IXW := 0; // widths
IYW := 0;
IZW := 0;
IXH := 0; // heights
IYH := 0;
IZH := 0;
MinXX := 0; // min plane mask extents
MinXY := 0;
MinYX := 0;
MinYY := 0;
MinZX := 0;
MinZY := 0;
MaxXX := 0; // max plane mask extents
MaxXY := 0;
MaxYX := 0;
MaxYY := 0;
MaxZX := 0;
MaxZY := 0;
BogusMask := True; // prevents system locks
BogusMaskX := True;
BogusMaskY := True;
BogusMaskZ := True;
// we don't find it? no point in continuing
if not assigned(FMaterialLibrary) then
Exit;
// it is recommended to have 3 different masks
// if there is only 2, the 3rd image will just take the largest extents and use them...
// creating not a very good effect
if XCan <> nil then
begin
IXW := XCan.Width;
IXH := XCan.Height;
end;
if YCan <> nil then
begin
IYW := YCan.Width;
IYH := YCan.Height;
end;
if ZCan <> nil then
begin
IZW := ZCan.Width;
IZH := ZCan.Height;
end;
// we find the largest dimensions of each image and give them to min mask extents so we work backwards
MX := MaxInteger(MaxInteger(IXW, IYW), IZW);
MY := MaxInteger(MaxInteger(IXH, IYH), IZH);
if XCan <> nil then
begin
MinXX := MX;
MinXY := MY;
end;
if YCan <> nil then
begin
MinYX := MX;
MinYY := MY;
end;
if ZCan <> nil then
begin
MinZX := MX;
MinZY := MY;
end;
// this is where we work backwards from to find the max size of the dimensions...
// in a sense, this provides information for the randomizing, and speeds up the code
for X := 0 to MX do
for Y := 0 to MY do
begin
if XCan <> nil then
if (X <= XCan.Width) and (Y <= XCan.Height) then
if (XCan.Canvas.Pixels[X, Y] = FMaskColor) then
begin
if X > MaxXX then
MaxXX := X;
if Y > MaxXY then
MaxXY := Y;
if X < MinXX then
MinXX := X;
if X < MinXY then
MinXY := Y;
BogusMaskX := False;
end;
if YCan <> nil then
if (X <= YCan.Width) and (Y <= YCan.Height) then
if (YCan.Canvas.Pixels[X, Y] = FMaskColor) then
begin
if X > MaxYX then
MaxYX := X;
if Y > MaxYY then
MaxYY := Y;
if X < MinYX then
MinYX := X;
if X < MinYY then
MinYY := Y;
BogusMaskY := False;
end;
if ZCan <> nil then
if (X <= ZCan.Width) and (Y <= ZCan.Height) then
if (ZCan.Canvas.Pixels[X, Y] = FMaskColor) then
begin
if X > MaxZX then
MaxZX := X;
if Y > MaxZY then
MaxZY := Y;
if X < MinZX then
MinZX := X;
if X < MinZY then
MinZY := Y;
BogusMaskZ := False;
end;
end;
BogusMask := (BogusMaskX or BogusMaskY or BogusMaskZ);
// here we find our 3d extents from a 1st angle orthographic shape
FMinX := MinInteger(MinZX, MinYX);
FMinY := MinInteger(MinXY, MinZY);
FMinZ := MinInteger(MinXX, MinYY);
FMaxX := MaxInteger(MaxZX, MaxYX);
FMaxY := MaxInteger(MaxXY, MaxZY);
FMaxZ := MaxInteger(MaxXX, MaxYY);
// this is the largest mask image sizes converted to orthographic and extents... used later on
LX := MaxInteger(IZW, IYW);
LY := MaxInteger(IXH, IZH);
LZ := MaxInteger(IXW, IYH);
end;
function TGLEParticleMask.XCan: TGLBitmap;
begin
Result := nil;
if not assigned(FMaterialLibrary) then
Exit;
if not assigned(FMaterialLibrary.LibMaterialByName(FXMask)) then
Exit;
if FMaterialLibrary.LibMaterialByName(FXMask).Material.Texture.ImageClassName
<> TGLPersistentImage.ClassName then
Exit;
Result :=
TGLBitmap((FMaterialLibrary.LibMaterialByName(FXMask).Material.Texture.Image as
TGLPersistentImage).Picture.Bitmap);
end;
function TGLEParticleMask.YCan: TGLBitmap;
begin
Result := nil;
if not assigned(FMaterialLibrary) then
Exit;
if not assigned(FMaterialLibrary.LibMaterialByName(FYMask)) then
Exit;
if FMaterialLibrary.LibMaterialByName(FYMask).Material.Texture.ImageClassName
<> TGLPersistentImage.ClassName then
Exit;
Result :=
TGLBitmap((FMaterialLibrary.LibMaterialByName(FYMask).Material.Texture.Image as
TGLPersistentImage).Picture.Bitmap);
end;
function TGLEParticleMask.ZCan: TGLBitmap;
begin
Result := nil;
if not assigned(FMaterialLibrary) then
Exit;
if not assigned(FMaterialLibrary.LibMaterialByName(FZMask)) then
Exit;
if FMaterialLibrary.LibMaterialByName(FZMask).Material.Texture.ImageClassName
<> TGLPersistentImage.ClassName then
Exit;
Result :=
TGLBitmap((FMaterialLibrary.LibMaterialByName(FZMask).Material.Texture.Image as
TGLPersistentImage).Picture.Bitmap);
end;
function TGLEParticleMask.QueryInterface(const IID: TGUID; out Obj): HResult; stdcall;
begin
if GetInterface(IID, Obj) then
Result := S_OK
else
Result := E_NOINTERFACE;
end;
function TGLEParticleMask._AddRef: Integer; stdcall;
begin
Result := -1; //ignore
end;
function TGLEParticleMask._Release: Integer; stdcall;
begin
Result := -1; //ignore
end;
{ TGLEParticleMasksManager }
procedure TGLEParticleMasksManager.ApplyOrthoGraphic(var Vec: TVector3f; Mask:
TGLEParticleMask);
begin
Vec.V[0] := (Mask.LX / 2 - Vec.V[0]) / Mask.LX;
Vec.V[1] := (Mask.LY / 2 - Vec.V[1]) / Mask.LY;
Vec.V[2] := (Mask.LZ / 2 - Vec.V[2]) / Mask.LZ;
end;
procedure TGLEParticleMasksManager.ApplyRotation(var Vec: TVector3f; Mask:
TGLEParticleMask);
begin
Vec := VectorRotateAroundX(Vec, DegToRad(Mask.FPitchAngle));
Vec := VectorRotateAroundY(Vec, DegToRad(Mask.FTurnAngle));
Vec := VectorRotateAroundZ(Vec, DegToRad(Mask.FRollAngle));
end;
procedure TGLEParticleMasksManager.ApplyRotationTarget(var Vec: TVector3f; Mask:
TGLEParticleMask; TargetObject: TGLBaseSceneObject);
begin
Vec := VectorRotateAroundX(Vec, DegToRad(Mask.FPitchAngle +
TargetObject.Rotation.X));
Vec := VectorRotateAroundY(Vec, DegToRad(Mask.FTurnAngle +
TargetObject.Rotation.Y));
Vec := VectorRotateAroundZ(Vec, DegToRad(Mask.FRollAngle +
TargetObject.Rotation.Z));
end;
procedure TGLEParticleMasksManager.ApplyScaleAndPosition(var Vec: TVector3f;
Mask: TGLEParticleMask);
begin
Vec.V[0] := Vec.V[0] * Mask.FScale.DirectX + Mask.FPosition.DirectX;
Vec.V[1] := Vec.V[1] * Mask.FScale.DirectY + Mask.FPosition.DirectY;
Vec.V[2] := Vec.V[2] * Mask.FScale.DirectZ + Mask.FPosition.DirectZ;
end;
procedure TGLEParticleMasksManager.ApplyScaleAndPositionTarget(var Vec:
TVector3f; Mask: TGLEParticleMask; TargetObject: TGLBaseSceneObject);
begin
Vec.V[0] := Vec.V[0] * Mask.FScale.DirectX * TargetObject.Scale.DirectX +
Mask.FPosition.DirectX + TargetObject.AbsolutePosition.V[0];
Vec.V[1] := Vec.V[1] * Mask.FScale.DirectY * TargetObject.Scale.DirectY +
Mask.FPosition.DirectY + TargetObject.AbsolutePosition.V[1];
Vec.V[2] := Vec.V[2] * Mask.FScale.DirectZ * TargetObject.Scale.DirectZ +
Mask.FPosition.DirectZ + TargetObject.AbsolutePosition.V[2];
end;
constructor TGLEParticleMasksManager.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FParticleMasks := TGLEParticleMasks.Create(Self);
end;
function TGLEParticleMasksManager.CreateParticlePositionFromMask(MaskName:
string): TVector3f;
var
Mask: TGLEParticleMask;
begin
Result := NullVector;
Mask := ParticleMaskByName(MaskName);
if not assigned(Mask) then
Exit;
if Mask.BogusMask then
Exit;
// finds the particle position on the masks
FindParticlePosition(Result, Mask);
// this converts 1st angle orthographic to 3rd angle orthograhic
ApplyOrthoGraphic(Result, Mask);
// this just turns it accordingly
ApplyRotation(Result, Mask);
// this applies the scales and positioning
ApplyScaleAndPosition(Result, Mask);
end;
destructor TGLEParticleMasksManager.Destroy;
begin
FParticleMasks.Destroy;
inherited Destroy;
end;
procedure TGLEParticleMasksManager.FindParticlePosition(var Vec: TVector3f;
Mask: TGLEParticleMask);
var
X, Y, Z: Integer;
begin
repeat
X := Random(Mask.FMaxX - Mask.FMinX) + Mask.FMinX;
Y := Random(Mask.FMaxY - Mask.FMinY) + Mask.FMinY;
Z := Random(Mask.FMaxZ - Mask.FMinZ) + Mask.FMinZ;
until (Mask.XCan.Canvas.Pixels[Z, Y] = Mask.FMaskColor) and
(Mask.YCan.Canvas.Pixels[X, Z] = Mask.FMaskColor) and
(Mask.ZCan.Canvas.Pixels[X, Y] = Mask.FMaskColor);
MakeVector(Vec, X, Y, Z);
end;
function TGLEParticleMasksManager.ParticleMaskByName(MaskName: string):
TGLEParticleMask;
var
I: Integer;
begin
Result := nil;
if FParticleMasks.Count > 0 then
for I := 0 to FParticleMasks.Count - 1 do
if FParticleMasks.Items[I].FName = MaskName then
Result := FParticleMasks.Items[I];
end;
procedure TGLEParticleMasksManager.SetParticlePositionFromMask(
Particle: TGLParticle; MaskName: string);
begin
if not assigned(Particle) then
Exit;
Particle.Position := CreateParticlePositionFromMask(MaskName);
end;
procedure TGLEParticleMasksManager.SetParticlePositionFromMaskTarget(
Particle: TGLParticle; MaskName: string; TargetObject: TGLBaseSceneObject);
begin
if not assigned(Particle) then
Exit;
Particle.Position := TargetParticlePositionFromMask(TargetObject, MaskName);
end;
function TGLEParticleMasksManager.TargetParticlePositionFromMask(
TargetObject: TGLBaseSceneObject; MaskName: string): TVector3f;
var
Mask: TGLEParticleMask;
begin
Result := NullVector;
if not assigned(TargetObject) then
Exit;
Mask := ParticleMaskByName(MaskName);
if not assigned(Mask) then
Exit;
if Mask.BogusMask then
Exit;
// finds the particle position on the masks
FindParticlePosition(Result, Mask);
// this converts 1st angle orthographic to 3rd angle orthograhic
ApplyOrthoGraphic(Result, Mask);
// this just turns it accordingly
ApplyRotationTarget(Result, Mask, TargetObject);
// this applies the scales and positioning
ApplyScaleAndPositionTarget(Result, Mask, TargetObject);
end;
end.
|
{ This simple TreeView component is inherited from TCustomControl }
{ it does not uses Windows TreeView control from comctl32.dll }
{ (c) L_G, last modification: Jan 2014 }
// To use your custom-modified TUserDumbTreeNode in separate UserDumbTreeNode.pas,
// uncomment define in the next line
//{$DEFINE USES_USERDUMBTREENODE_PAS}
unit DumbTreeView;
interface
uses Windows, Messages, Classes, Forms, Controls, Graphics
{$IFDEF USES_USERDUMBTREENODE_PAS}
, UserDumbTreeNode; // better to define your class in separate .pas file!
{$ELSE}; // but it can be defined just here:
type
TUserDumbTreeNode = class // in the lightest case, the class is totally empty
// for example, here you may insert:
//Id, ParentId: integer; // for database-stored trees
//Bmp: TBitmap; // 'icon' bitmap
//Obj: TObject; // anything else you need
end;
TDumbTreeNodeFlag = (nfFocused, nfSelected, nfCollapsed, // these 3 is used in TDumbTreeView
nfChecked, nfIndeterminate, // these 2 - in TDumbCheckBoxTreeView
nfDisabled, nfExpandabilityUnknown); // these are not used
//nfGrayed, nfDefault, nfHot, nfMarked); // ???
{$ENDIF}
const DefSelectedNodeColor = clHighlight;
DefSelectedNodeTextColor = clHighlightText;
FDefRootIndent = 4;
FVertOffset = 2;
FCaptionSpace = 2;
type
TDumbFlag = nfFocused..nfExpandabilityUnknown; // these are not used
//nfGrayed, nfDefault, nfHot, nfMarked); // ???
TDumbTreeNodeFlags = set of TDumbTreeNodeFlag;
TDumbTreeNode = class(TUserDumbTreeNode) // inherits FROM class with USER-DEFINED fields/properties!
private
FParent,
FChild, // _1st_ of node's child nodes
FSibling: TDumbTreeNode; // _NEXT_ sibling
////PrevSibling: TDumbTreeNode; // thinked it may be useful, but it is not!
FName: string;
FFlags: TDumbTreeNodeFlags;
// Wonder how many bytes each tree node takes?
// This record size is 5 fields * 4 bytes = 16 bytes + 4 for TObject = 20 bytes
// Plus even the shortest 1-3 characrer string for Name takes 8+4=12 bytes (but 0 for empty)
// 8..11 character Name takes 8+12=20 bytes, so total = 16+4+20 = 40 bytes
function GetLevel: integer;
protected
property Parent: TDumbTreeNode read FParent write FParent;
//property {1st}Child: TDumbTreeNode read FChild write FChild;
property {Next}Sibling: TDumbTreeNode read FSibling write FSibling;
property Flags: TDumbTreeNodeFlags read FFlags write FFlags;
public
property {1st}Child: TDumbTreeNode read FChild write FChild;
property Name: string read FName write FName;
property Level: integer read GetLevel;
constructor Create(AName: string);
function AddSibling(AName: string): TDumbTreeNode;
function AddChild(AName: string): TDumbTreeNode;
end;
TDumbTreeView = class;
TDumbTreeCustomDrawRowEvent = procedure
(Sender: TDumbTreeView; ANode: TDumbTreeNode; const ARect: TRect;
var DefaultDraw: Boolean) of object;
TDumbTreeCustomDrawCaptionEvent = procedure
(Sender: TDumbTreeView; ANode: TDumbTreeNode; const ARect: TRect;
var DefaultDraw: Boolean) of object;
TDumbTreeMeasureCaptionWidthEvent = procedure
(Sender: TDumbTreeView; ANode: TDumbTreeNode; var Width: integer) of object;
TDumbTreeNodeEvent = procedure
(Sender: TDumbTreeView; ANode: TDumbTreeNode) of object;
TDumbTreeNodeClickEvent = procedure
(Sender: TDumbTreeView; ANode: TDumbTreeNode; AButton: TMouseButton;
Shift: TShiftState; X, Y: integer) of object;
TDumbTreeNodeAllowEvent = procedure
(Sender: TDumbTreeView; ANode: TDumbTreeNode; var Allow: Boolean) of object;
TDumbTreeCompareNodes = function
(Sender: TDumbTreeView; N1, N2: TDumbTreeNode): integer of object;
TDumbTreeView = class(TCustomControl)
private
//FNodeCount: integer;
FRootNode: TDumbTreeNode; // root can have siblings, not only children!
FBorderStyle: TBorderStyle;
FRowHeight: integer; // pixels
FIndent: integer; // child node offset to right from parent; pixels
FExpandButtonHalfSize: integer;
FCaptionOffset: Integer; //pixels between
FWindowRows: integer; // count of rows that fits in ClientHeight
FFirstRow: integer;
FHorzPos: integer; // scrollbar positions
FVertPos: integer;
FHorzRange: integer; // scrollbar ranges
FVertRange: integer;
FVisibleNodes: integer; // = total node count minus hidden (by collapsing) childs
FUpdateCount: integer;
FScrollInfo: TScrollInfo;
FSelectedNodeColor, FSelectedNodeTextColor: TColor;
FActiveNode: TDumbTreeNode; // active means focused
FMultiSelect: boolean;
FShowExpandButtons: boolean;
FShowLines: boolean;
FShowRootLines: boolean;
FFullRowSelect: boolean;
FRootIndent: integer; // = FShowRootLines ? FDefRootIndent : FIndent
FLevel, FRow: integer; // 'outer' variables for recursive iterations: current level and row
FMaxRowWidth: integer; // updated on each Paint; TODO: needs to be resetted somewhere!!!
//FExpandBmp, FCollapseBmp, FCheckedBmp, FUncheckedBmp: TBitmap;
FDefExpandBmp, FDefCollapseBmp: TBitmap;
FExpandBmp, FCollapseBmp: TBitmap;
FUseButtonBitmaps: boolean;
FOnCustomDrawRow: TDumbTreeCustomDrawRowEvent;
FOnCustomDrawCaption: TDumbTreeCustomDrawCaptionEvent;
FOnMeasureCaptionWidth: TDumbTreeMeasureCaptionWidthEvent;
FOnNodeClick: TDumbTreeNodeClickEvent;
FOnNodeDblClick: TDumbTreeNodeEvent;
FOnCompareNodes: TDumbTreeCompareNodes;
FBeforeNodeExpandCollapse: TDumbTreeNodeAllowEvent;
FBeforeNodeSelect: TDumbTreeNodeAllowEvent;
procedure WMHScroll(var Msg: TWMHScroll); message WM_HSCROLL;
procedure WMVScroll(var Msg: TWMVScroll); message WM_VSCROLL;
procedure CNKeyDown(var Message: TWMKeyDown); message CN_KEYDOWN;
procedure WMMouseWheel(var Message: TWMMouseWheel); message WM_MOUSEWHEEL;
procedure WMLButtonDblClk(var Message: TWMLButtonDblClk); message WM_LBUTTONDBLCLK;
procedure SetBorderStyle(Value: TBorderStyle);
procedure SetHorzPos(Value: integer);
procedure SetVertPos(Value: integer);
procedure SetIndent(Value: integer);
procedure SetExpandButtonSize(Value: integer);
function GetExpandButtonSize: integer;
procedure SetShowExpandButtons(Value: boolean);
procedure SetShowLines(Value: boolean);
procedure SetShowRootLines(Value: boolean);
procedure SetFullRowSelect(Value: boolean);
procedure SetSelectedNodeColor(Value: TColor);
procedure SetSelectedNodeTextColor(Value: TColor);
procedure SetCollapseBmp(const Value: TBitmap);
procedure SetExpandBmp(const Value: TBitmap);
procedure SetUseButtonBitmaps(const Value: boolean);
function InternalSortSiblings(const ANode: TDumbTreeNode): TDumbTreeNode;
protected
procedure WndProc(var Message: TMessage); override;
procedure DeleteSiblingNodes(ANode: TDumbTreeNode);
procedure DeleteNodeChilds(ANode: TDumbTreeNode);
procedure DrawSiblingNodes(ANode: TDumbTreeNode);
function GetCaptionOffset: integer; virtual;
procedure SetCaptionOffset(Value: integer); virtual;
procedure SetRowHeight(Value: integer); virtual;
procedure CreateParams(var Params: TCreateParams); override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
procedure Paint; override;
procedure SetEnabled(Value: Boolean); override;
procedure AdjustScrollBars; virtual;
procedure SetActiveNode(ANode: TDumbTreeNode); virtual;
procedure DrawNodeRow(ANode: TDumbTreeNode; ALevel, ARow: integer); virtual;
procedure DrawNodeCaption(ANode: TDumbTreeNode; ALevel, ARow: integer); virtual;
procedure AdjustCaptionWidth(ANode: TDumbTreeNode; var AWidth: integer); virtual;
procedure DoNodeClick(ANode: TDumbTreeNode; AButton: TMouseButton;
Shift: TShiftState; X, Y: Integer); virtual;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Refresh; virtual;
procedure RefreshNode(ANode: TDumbTreeNode); virtual;
function GetNodeAtXY(X, Y: integer): TDumbTreeNode;
function GetNodeAtRow(ARow: integer): TDumbTreeNode;
function GetNodeRow(ANode: TDumbTreeNode): integer;
function GetPrevNode(ANode: TDumbTreeNode; IncludeHidden: boolean = False): TDumbTreeNode;
function GetNextNode(ANode: TDumbTreeNode; IncludeHidden: boolean = False): TDumbTreeNode;
function AddSibling(ANode: TDumbTreeNode; AName: string): TDumbTreeNode;
function AddChild(ANode: TDumbTreeNode; AName: string): TDumbTreeNode;
procedure ExpandOrCollapseNode(ANode: TDumbTreeNode); virtual;
procedure ExpandNode(ANode: TDumbTreeNode); virtual;
procedure CollapseNode(ANode: TDumbTreeNode); virtual;
procedure ToggleNodeSelection(ANode: TDumbTreeNode);
procedure ClearSelectionInSiblings(ANode: TDumbTreeNode);
procedure ClearSelection; virtual;
procedure BeginUpdate;
procedure EndUpdate;
procedure DeleteNodeWithChilds(ANode: TDumbTreeNode);
procedure Clear; virtual;
function CompareNodes(n1, n2: TDumbTreeNode): integer;
procedure SortChilds(const ANode: TDumbTreeNode);
procedure SortSiblings(const ANode: TDumbTreeNode);
property RootNode: TDumbTreeNode read FRootNode write FRootNode;
property ActiveNode: TDumbTreeNode read FActiveNode write SetActiveNode;
property HorzPos: integer read FHorzPos write SetHorzPos;
property VertPos: integer read FVertPos write SetVertPos;
//property NodeCount: integer read FNodeCount write FNodeCount; ////// not used
property Canvas; ///?!?!
property UpdateCount: integer read FUpdateCount write FUpdateCount;
published
property BorderStyle: TBorderStyle
read FBorderStyle write SetBorderStyle default bsSingle;
property RowHeight: integer read FRowHeight write SetRowHeight default 16;
property Indent: integer read FIndent write SetIndent default 18;
property CaptionOffset: integer read GetCaptionOffset write SetCaptionOffset default 0;
property ExpandButtonSize: integer
read GetExpandButtonSize write SetExpandButtonSize default 8;
property OnCustomDrawItem: TDumbTreeCustomDrawRowEvent
read FOnCustomDrawRow write FOnCustomDrawRow;
property OnCustomDrawCaption: TDumbTreeCustomDrawCaptionEvent
read FOnCustomDrawCaption write FOnCustomDrawCaption;
property OnNodeClick: TDumbTreeNodeClickEvent read FOnNodeClick write FOnNodeClick;
property OnNodeDblClick: TDumbTreeNodeEvent
read FOnNodeDblClick write FOnNodeDblClick;
// OnCompareNodes event can be used to change default sorting criterium (Name, alphabetically, ascending)
// should return -1 when then first node parameter is LESS then the second, 0 if they are equal, and 1 in other case
property OnCompareNodes: TDumbTreeCompareNodes read FOnCompareNodes write FOnCompareNodes;
property BeforeNodeExpandCollapse: TDumbTreeNodeAllowEvent
read FBeforeNodeExpandCollapse write FBeforeNodeExpandCollapse;
property BeforeNodeSelect: TDumbTreeNodeAllowEvent
read FBeforeNodeSelect write FBeforeNodeSelect;
property SelectedNodeColor: TColor read FSelectedNodeColor
write SetSelectedNodeColor default DefSelectedNodeColor;
property SelectedNodeTextColor: TColor read FSelectedNodeTextColor
write SetSelectedNodeTextColor default DefSelectedNodeTextColor;
property MultiSelect: boolean read FMultiSelect write FMultiSelect default False;
property ShowButtons: boolean read FShowExpandButtons write SetShowExpandButtons default True;
property ShowLines: boolean read FShowLines write SetShowLines default True;
property ShowRoot{Lines}: boolean read FShowRootLines write SetShowRootLines default True;
property FullRowSelect: boolean read FFullRowSelect write SetFullRowSelect default False;
property UseButtonBitmaps: boolean read FUseButtonBitmaps write SetUseButtonBitmaps default True;
property ExpandBmp: TBitmap read FExpandBmp write SetExpandBmp;
property CollapseBmp: TBitmap read FCollapseBmp write SetCollapseBmp;
property Anchors;
property Align;
property BevelInner;
property BevelEdges;
property BevelKind;
property BevelOuter;
property BevelWidth;
property Color default clWindow;
property Font;
property ParentColor default False;
property Hint;
property ShowHint;
property ParentShowHint;
property Enabled;
property PopupMenu;
property Ctl3D;
property ParentCtl3D;
property TabOrder;
property TabStop default True;
property Visible;
property OnClick;
property OnDblClick;
property OnEnter;
property OnExit;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnCanResize;
property OnConstrainedResize;
property OnResize;
end;
/// TODO: maybe, turn this constants into fields/properties?
const FMouseWheelScrollRows = 3;
FLineColor = $989898;
FExpandButtonFaceColor = clWhite;
FExpandButtonBorderColor = FLineColor;
FExpandButtonSignColor = clBlack;
type
TDumbCheckboxTreeView = class(TDumbTreeView)
private
FCheckBoxes: Boolean;
FUserCaptionOffset: Integer;
FDefCheckedBmp, FDefUncheckedBmp: TBitmap;
FUncheckedBmp, FCheckedBmp: TBitmap;
procedure SetCheckBoxes(Value: boolean);
procedure SetCheckedBmp(const Value: TBitmap);
procedure SetUncheckedBmp(const Value: TBitmap);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function GetCaptionOffset: integer; override;
procedure SetCaptionOffset(Value: integer); override;
procedure SetRowHeight(Value: integer); override;
procedure DrawNodeCaption(ANode: TDumbTreeNode; ALevel, ARow: integer); override;
//procedure AdjustCaptionWidth(ANode: TDumbTreeNode; var AWidth: integer); override;
procedure DoNodeClick(ANode: TDumbTreeNode; AButton: TMouseButton;
Shift: TShiftState; X, Y: Integer); override;
published
property CheckBoxes: Boolean read FCheckBoxes write SetCheckBoxes default False;
property CheckedBmp: TBitmap read FCheckedBmp write SetCheckedBmp;
property UncheckedBmp: TBitmap read FUncheckedBmp write SetUncheckedBmp;
end;
procedure Register;
implementation
{$R *.res}
uses SysUtils;
procedure TDumbTreeView.WndProc(var Message: TMessage);
var p: ^TComponentState;
begin
if (csDesigning in ComponentState) then
begin
p := @ComponentState;
p^ := p^ - [csDesigning];
inherited;
p^ := p^ + [csDesigning];
end
else
inherited;
end;
procedure Register;
begin
RegisterComponents('Samples', [TDumbTreeView, TDumbCheckBoxTreeView]);
end;
{ TDumbTreeNode }
constructor TDumbTreeNode.Create(AName: string);
begin
inherited Create;
FName := AName;
end;
function TDumbTreeNode.AddSibling(AName: string): TDumbTreeNode;
begin
Result := TDumbTreeNode.Create(AName);
Result.FParent := Self.FParent;
//if FSibling <> nil then
Result.FSibling := FSibling;
FSibling := Result;
end;
function TDumbTreeNode.AddChild(AName: string): TDumbTreeNode;
begin
Result := TDumbTreeNode.Create(AName);
Result.FParent := Self;
//if FChild <> nil then
Result.FSibling := FChild;
FChild := Result;
end;
function TDumbTreeNode.GetLevel: integer;
var node: TDumbTreeNode;
begin
Result := 0;
node := Self.FParent;
while node <> nil do
begin
node := node.FParent;
inc(Result);
end;
end;
{ TDumbTreeView }
constructor TDumbTreeView.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Height := 150; Width := 150;
TabStop := True;
FScrollInfo.cbSize := SizeOf(FScrollInfo);
ControlStyle := ControlStyle + [csDesignInteractive, csOpaque{, csFramed}];
FBorderStyle := bsSingle;
FSelectedNodeColor := DefSelectedNodeColor;
FSelectedNodeTextColor := DefSelectedNodeTextColor;
FRowHeight := 16;
FIndent := 18;
FRootIndent := FIndent;
FShowLines := True;
FShowRootLines := True;
FShowExpandButtons := True;
FExpandButtonHalfSize := 4;
ParentColor := False;
Color := clWindow;
//FNodeCount := 1;
FDefExpandBmp := TBitmap.Create;
FDefExpandBmp.LoadFromResourceName(HInstance, 'EXPAND');
FDefCollapseBmp := TBitmap.Create;
FDefCollapseBmp.LoadFromResourceName(HInstance, 'COLLAPSE');
FExpandBmp := TBitmap.Create;
FCollapseBmp := TBitmap.Create;
FUseButtonBitmaps := True;
if csDesigning in ComponentState then
begin
FRootNode := TDumbTreeNode.Create('RootNode');
FRootNode.AddSibling('RootSibling1').AddSibling('RootSibling2');
FRootNode.AddChild('RootChild').AddChild('RootChildChild');
FActiveNode := FRootNode;
end;
end;
destructor TDumbTreeView.Destroy;
begin
if csDesigning in ComponentState then
Clear;
FRootNode.Free;
FDefExpandBmp.Free; FDefCollapseBmp.Free;
FExpandBmp.Free; FCollapseBmp.Free;
inherited;
end;
procedure TDumbTreeView.CreateParams(var Params: TCreateParams);
Const
BorderStyles: array[TBorderStyle] of cardinal = (0, WS_BORDER);
begin
inherited CreateParams(Params);
Params.Style := Params.Style or WS_HSCROLL or WS_VSCROLL or BorderStyles[FBorderStyle]; //or WS_VISIBLE -??
Params.ExStyle := Params.ExStyle or WS_EX_COMPOSITED; // suppress blinking on form resizing
if Ctl3D and NewStyleControls and (FBorderStyle = bsSingle) then
begin
Params.Style := Params.Style and not WS_BORDER;
Params.ExStyle := Params.ExStyle or WS_EX_CLIENTEDGE;
end;
//Params.WindowClass.Style := Params.WindowClass.style and not (CS_HREDRAW or CS_VREDRAW); // saw no effect
end;
procedure TDumbTreeView.WMHScroll(var Msg: TWMHScroll);
begin
case Msg.ScrollCode of
sb_LineUp : HorzPos := HorzPos - 1;
sb_LineDown : HorzPos := HorzPos + 1;
sb_PageUp : HorzPos := HorzPos - ClientWidth;
sb_PageDown : HorzPos := HorzPos + ClientWidth;
sb_Top : HorzPos := 0;
sb_Bottom : HorzPos := FHorzRange;
sb_ThumbTrack,
sb_ThumbPosition : HorzPos := word(Msg.Pos);
end;
end;
procedure TDumbTreeView.WMVScroll(var Msg: TWMVScroll);
begin
case Msg.ScrollCode of
sb_LineUp : VertPos := VertPos - 1;
sb_LineDown : VertPos := VertPos + 1;
sb_PageUp : VertPos := VertPos - FWindowRows;
sb_PageDown : VertPos := VertPos + FWindowRows;
sb_Top : VertPos := 0;
sb_Bottom : VertPos := FVertRange;
sb_ThumbTrack,
sb_ThumbPosition :
begin // Msg.Pos gives only 16 low bits, so -
FScrollInfo.fMask := SIF_TRACKPOS;
GetScrollInfo(Handle, SB_VERT, FScrollInfo);
VertPos := FScrollInfo.nTrackPos; // = nPos, so works for sb_ThumbPosition too
////Application.MainForm.Caption:=Format('%d %d', [FScrollInfo.nPos, FScrollInfo.nTrackPos]);
end;
end;
end;
procedure TDumbTreeView.WMMouseWheel(var Message: TWMMouseWheel);
begin
inherited;
if Message.WheelDelta < 0 then
VertPos := VertPos + FMouseWheelScrollRows
else if Message.WheelDelta > 0 then
VertPos := VertPos - FMouseWheelScrollRows;
end;
procedure TDumbTreeView.DoNodeClick(ANode: TDumbTreeNode; AButton: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
if Assigned(FOnNodeClick) then
FOnNodeClick(Self, ANode, AButton, Shift, X, Y);
end;
procedure TDumbTreeView.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var node: TDumbTreeNode;
cx, cy: integer;
begin
inherited;
Self.SetFocus;
node := GetNodeAtXY(X, Y);
if node <> nil then
begin
cx := FIndent * node.Level + FRootIndent - FIndent div 2 - FHorzPos;
cy := (Y - FVertOffset) div FRowHeight * FRowHeight + FRowHeight div 2 + FVertOffset - 1;
if (X >= cx - FExpandButtonHalfSize) and (X <= cx + FExpandButtonHalfSize)
and (Y >= cy - FExpandButtonHalfSize) and (Y <= cy + FExpandButtonHalfSize)
then
ExpandOrCollapseNode(node);
ActiveNode := node;
if ActiveNode = node then
if FMultiSelect then
begin
if not (ssCtrl in Shift) then
ClearSelection;
node.FFlags := node.FFlags + [nfFocused];
ToggleNodeSelection(node);
end;
DoNodeClick(node, Button, Shift, X - cx - FIndent + FIndent div 2, Y - cy + FRowHeight div 2);
end;
end;
procedure TDumbTreeView.CNKeyDown(var Message: TWMKeyDown);
var node: TDumbTreeNode; //i: integer;
begin
node := nil;
case Message.CharCode of
VK_UP:
node := GetPrevNode(ActiveNode);
//TODO: scroll when active node gets out of sight
VK_DOWN:
node := GetNextNode(ActiveNode);
VK_PRIOR:
begin //TODO: move focus (active node) on pair with scrolling
{node := ActiveNode;
for i:= 2 to FWindowRows do
node := GetPrevNode(node);
ActiveNode := node;}
VertPos := VertPos - FWindowRows;
//Refresh;
end;
VK_NEXT:
begin
{node := ActiveNode;
for i:= 2 to FWindowRows do
node := GetNextNode(node);
ActiveNode := node;}
VertPos := VertPos + FWindowRows;
//Refresh;
end;
VK_SPACE:
ExpandOrCollapseNode(ActiveNode);
VK_RETURN:
ToggleNodeSelection(ActiveNode);
else
inherited;
end;
if node <> nil then
ActiveNode := node;
end;
procedure TDumbTreeView.WMLButtonDblClk(var Message: TWMLButtonDblClk);
begin
inherited;
if ActiveNode = nil then Exit;
if Assigned (FOnNodeDblClick) then
FOnNodeDblClick(Self, ActiveNode);
ExpandOrCollapseNode(ActiveNode); ////???
end;
procedure TDumbTreeView.SetHorzPos(Value: integer);
begin
if Value < 0 then
Value := 0
else if Value > FHorzRange - ClientWidth+4 then
Value := FHorzRange - ClientWidth+4;
if (FHorzPos <> Value) then
begin
FHorzPos := Value;
FScrollInfo.fMask := SIF_POS;
FScrollInfo.nPos := FHorzPos;
SetScrollInfo(Handle, SB_HORZ, FScrollInfo, True);
Refresh;
end;
end;
procedure TDumbTreeView.SetVertPos(Value: integer);
begin
if Value < 0 then
Value:=0
else if Value > FVertRange - FWindowRows + 1 then
Value := FVertRange - FWindowRows + 1;
if (FVertPos <> Value) then
begin
FVertPos := Value;
FScrollInfo.fMask := SIF_POS;
FScrollInfo.nPos := FVertPos;
SetScrollInfo(Handle, SB_VERT, FScrollInfo, True);
FFirstRow := FVertPos;
Refresh;
end;
end;
function TDumbTreeView.GetNodeAtXY(X, Y: integer): TDumbTreeNode;
begin
Result := GetNodeAtRow((Y - FVertOffset) div FRowHeight + FFirstRow);
end;
function TDumbTreeView.GetNodeAtRow(ARow: integer): TDumbTreeNode;
var row: integer;
function CheckSiblingNodes(node: TDumbTreeNode): TDumbTreeNode;
var n: TDumbTreeNode;
begin
//Result := nil;
repeat
if row = ARow then Break;
inc(row);
n := node;
if not (nfCollapsed in node.FFlags) and (node.FChild <> nil) then
begin
node := CheckSiblingNodes(node.FChild);
if node <> nil then Break;
end;
node := n.FSibling;
until node = nil;
Result := node;
end;
begin
row := 0;
if RootNode <> nil then
Result := CheckSiblingNodes(RootNode)
else
Result := nil;
end;
function TDumbTreeView.GetNodeRow(ANode: TDumbTreeNode): integer;
var row: integer;
function CheckSiblingNodesRow(node: TDumbTreeNode): integer;
var r: integer;
begin
repeat
if node = ANode then Break;
inc(row);
if not (nfCollapsed in node.FFlags) and (node.FChild <> nil) then
begin
r := CheckSiblingNodesRow(node.FChild);
if r <> -1 then begin row := r; Break; end;
end;
node := node.FSibling;
until node = nil;
if node = nil then
Result := -1
else
Result := row;
end;
begin
row := 0;
Result := CheckSiblingNodesRow(RootNode);
end;
function TDumbTreeView.GetPrevNode(ANode: TDumbTreeNode; IncludeHidden: boolean = False): TDumbTreeNode;
var node: TDumbTreeNode;
begin
Assert(Assigned(ANode));
//Result := GetNodeAtRow(GetNodeRow(ANode)-1); //simple but slow 1-line version
//Exit;
if ANode = FRootNode then
Result := nil
else if (ANode.FParent <> nil) and (ANode.FParent.FChild = ANode) then
Result := ANode.FParent
else begin // find previous sibling
if ANode.FParent = nil then
node := FRootNode
else
node := ANode.FParent.FChild;
while node.FSibling <> ANode do
begin
node := node.FSibling;
Assert(Assigned(node));
end;
while (node.FChild <> nil) and (IncludeHidden or not (nfCollapsed in node.FFlags)) do
begin // find last child of last child etc...
node:= node.FChild;
while node.FSibling <> nil do
node := node.FSibling;
end;
Result:= node;
end;
end;
function TDumbTreeView.GetNextNode(ANode: TDumbTreeNode; IncludeHidden: boolean = False): TDumbTreeNode;
var node: TDumbTreeNode;
begin
Assert(Assigned(ANode));
//Result := GetNodeAtRow(GetNodeRow(ANode)+1); //simple but slow 1-line version
//Exit;
if IncludeHidden or not (nfCollapsed in ANode.FFlags) then
begin
Result := ANode.FChild;
if Result <> nil then Exit; // first child is candidate #1 for NextNode
end;
Result := ANode.FSibling;
if Result <> nil then Exit; // when there's no children, NextNode is {Next}Sibling
Result := ANode;
node := nil;
repeat
if node = nil then
Result := Result.FParent; // otherwise, it will be our Parent's {Next}Sibling
if Result = nil then Exit; // or Sibling of first node in ancestors' line that have Sibling
node := Result.FSibling;
until node <> nil;
Result := node;
{
//Result := ANode.Parent;
//if Result = nil then Exit;
repeat
node := Result.Sibling;
if node = nil then
Result := Result.Parent;
if Result = nil then Exit;
until node <> nil;
}
end;
procedure TDumbTreeView.DeleteSiblingNodes(ANode: TDumbTreeNode);
var n: TDumbTreeNode;
begin
repeat
if ANode.FChild <> nil then
DeleteSiblingNodes(ANode.FChild);
n := ANode;
ANode := ANode.FSibling;
n.Free;
//dec(FNodeCount);
until ANode = nil;
end;
procedure TDumbTreeView.Clear;
begin
if FRootNode = nil then Exit;
DeleteSiblingNodes(FRootNode);
FRootNode := nil;
FActiveNode := nil;
Refresh;
end;
procedure TDumbTreeView.DeleteNodeChilds(ANode: TDumbTreeNode);
begin
Assert(Assigned(ANode));
if ANode.FChild <> nil then
DeleteSiblingNodes(ANode.FChild);
ANode.FChild := nil;
FActiveNode := nil;
end;
procedure TDumbTreeView.DeleteNodeWithChilds(ANode: TDumbTreeNode);
var node: TDumbTreeNode;
begin
if ANode = nil then Exit;
DeleteNodeChilds(ANode);
if ANode = FRootNode then
FRootNode := ANode.FSibling
else if (ANode.FParent <> nil) and (ANode.FParent.FChild = ANode) then
ANode.FParent.FChild := ANode.FSibling // clear reference to our node
else begin // find previous sibling
if ANode.FParent = nil then
node := FRootNode
else
node := ANode.FParent.FChild;
while node.FSibling <> ANode do
begin
node := node.FSibling;
Assert(Assigned(node));
end;
node.FSibling := ANode.FSibling; // clear reference to our node
end;
ANode.Free;
//dec(FNodeCount);
FActiveNode := nil;
end;
procedure DottedLineTo(ACanvas: TCanvas; X, Y: Integer);
var i: Integer;
begin
if ACanvas.PenPos.X = X then
begin
for i := ACanvas.PenPos.Y+1 to Y do
if i and 1 <> 0 then
ACanvas.MoveTo(X, i)
else
ACanvas.LineTo(X, i)
end
else if ACanvas.PenPos.Y = Y then
begin
for i := ACanvas.PenPos.X+1 to X do
if i and 1 <> 0 then
ACanvas.MoveTo(i, Y)
else
ACanvas.LineTo(i, Y);
end
else
ACanvas.MoveTo(X, Y);
end;
procedure TDumbTreeView.DrawNodeRow(ANode: TDumbTreeNode; ALevel, ARow: integer);
var cx, cy, i: integer; node: TDumbTreeNode;
begin
if (ARow < FFirstRow) or (ARow > FFirstRow + FWindowRows) then
Exit;
Assert(Assigned(ANode));
if FFullRowSelect and (nfSelected in ANode.FFlags) and Enabled then
begin
Canvas.Brush.Color := FSelectedNodeColor;
cy := FRowHeight*(ARow-FFirstRow)+FVertOffset;
Canvas.FillRect(Rect(0, cy, ClientWidth, cy + FRowHeight));
end;
if FShowRootLines or (Alevel > 0) then
begin
cx := FIndent*ALevel+FRootIndent-(FIndent div 2)-FHorzPos;
cy := FRowHeight*(ARow-FFirstRow)+(FRowHeight div 2)+FVertOffset-1;
if FShowLines then
// Lines
begin
Canvas.Pen.Color := FLineColor;
// draw straight vert. lines from overlying nodes down to their chidlren
// (only their fragments, bounded by current row)
node := ANode;
for i := 1 to ALevel+Ord(FShowRootLines) do
begin
if node.FParent <> nil then
begin
if node.FParent.FSibling <> nil then
begin
Canvas.MoveTo(cx-i*FIndent, FRowHeight*(ARow-FFirstRow)+FVertOffset-1);
DottedLineTo(Canvas, cx-i*FIndent, FRowHeight*(ARow-FFirstRow+1)+FVertOffset-1);
end;
node := node.FParent;
end;
end;
// draw L-shaped line fragment to current node from its parent
if ANode = FRootNode then
Canvas.MoveTo(cx, cy)
else begin
Canvas.MoveTo(cx, FRowHeight*(ARow-FFirstRow)+FVertOffset-1);
DottedLineTo(Canvas, cx, cy);
end;
DottedLineTo(Canvas, FIndent*ALevel+FRootIndent-FHorzPos, cy);
if (ANode.FSibling <> nil) then
begin
// continue L-shape downward to next sibling (so shape is T, rotated 90 deg. CCW)
Canvas.MoveTo(cx, cy);
DottedLineTo(Canvas, cx, FRowHeight*(ARow-FFirstRow+1)+FVertOffset-1);
end;
end;
// Expand/Collapse Buttons
if FShowExpandButtons and (ANode.FChild <> nil) then
begin
if FUseButtonBitmaps then
begin
if nfCollapsed in ANode.FFlags then
if FExpandBmp.HandleAllocated then
Canvas.Draw(cx-4, cy-4, FExpandBmp)
else
Canvas.Draw(cx-4, cy-4, FDefExpandBmp)
else
if FCollapseBmp.HandleAllocated then
Canvas.Draw(cx-4, cy-4, FCollapseBmp)
else
Canvas.Draw(cx-4, cy-4, FDefCollapseBmp);
end
else begin
Canvas.Brush.Color := FExpandButtonFaceColor;
Canvas.Pen.Color := FExpandButtonBorderColor;
Canvas.Rectangle(cx-FExpandButtonHalfSize, cy-FExpandButtonHalfSize,
cx+FExpandButtonHalfSize+1, cy+FExpandButtonHalfSize+1);
Canvas.Pen.Color := FExpandButtonSignColor;
Canvas.MoveTo(cx-FExpandButtonHalfSize+2, cy);
Canvas.LineTo(cx+FExpandButtonHalfSize-1, cy);
if nfCollapsed in ANode.FFlags then
begin
Canvas.MoveTo(cx, cy-FExpandButtonHalfSize+2);
Canvas.LineTo(cx, cy+FExpandButtonHalfSize-1);
end;
end;
end;
end;
// Caption (text)
DrawNodeCaption(ANode, ALevel, ARow);
end;
procedure TDumbTreeView.AdjustCaptionWidth(ANode: TDumbTreeNode; var AWidth: integer);
begin
if Assigned(FOnMeasureCaptionWidth) then
FOnMeasureCaptionWidth(Self, ANode, AWidth);
end;
procedure TDumbTreeView.DrawNodeCaption(ANode: TDumbTreeNode; ALevel, ARow: integer);
var x, y, wdt: integer;
rct: TRect;
def: boolean;
begin
Assert(Assigned(ANode));
x := FCaptionOffset + FRootIndent + FIndent * ALevel - FHorzPos;
y := FRowHeight * (ARow - FFirstRow) + FVertOffset;
wdt := Canvas.TextWidth(ANode.FName) + FCaptionSpace*2;
rct := Rect(x, y, x + wdt, y + FRowHeight);
if Assigned(FOnCustomDrawCaption) then
begin
def := false;
FOnCustomDrawCaption(Self, ANode, rct, def);
if not def then Exit;
end;
Canvas.Font.Assign(Font);
if not Enabled then
Canvas.Font.Color := clGrayText
else if nfSelected in ANode.FFlags then
begin
Canvas.Brush.Color := FSelectedNodeColor;
Canvas.Font.Color := FSelectedNodeTextColor;
end
else
Canvas.Brush.Color := Color;
Canvas.FillRect(rct);
Canvas.TextRect(rct, x+FCaptionSpace, y, ANode.FName);// + Format(' %p %p %p', [Pointer(ANode.Parent), Pointer(ANode.Sibling), Pointer(ANode.Child)]));
if nfFocused in ANode.FFlags then
Canvas.DrawFocusRect(rct);
AdjustCaptionWidth(ANode, wdt);
wdt := wdt + FRootIndent + FCaptionOffset + Alevel*FIndent;
if wdt > FMaxRowWidth then
FMaxRowWidth := wdt;
end;
procedure TDumbTreeView.RefreshNode(ANode: TDumbTreeNode);
begin
Assert(Assigned(ANode));
//DrawNodeCaption(ANode, ANode.Level, GetNodeRow(ANode));
DrawNodeRow(ANode, ANode.Level, GetNodeRow(ANode));
end;
procedure TDumbTreeView.DrawSiblingNodes(ANode: TDumbTreeNode);
var node: TDumbTreeNode;
begin
Assert(Assigned(ANode));
//if (FUpdateCount > 0) or not HandleAllocated then Exit;
inc(FLevel);
node := ANode;
repeat
if (FRow >= FFirstRow) and (FRow <= FFirstRow + FWindowRows) then
DrawNodeRow(node, FLevel, FRow);
inc(FRow);
if not (nfCollapsed in node.FFlags) and (node.FChild <> nil) then
DrawSiblingNodes(node.FChild);
node := node.FSibling;
until node = nil;
dec(FLevel);
end;
procedure TDumbTreeView.ClearSelection;
begin
ClearSelectionInSiblings(RootNode); // Stack Overflow error is possible here!
Refresh; // (in case of too many nested levels)
end;
procedure TDumbTreeView.ClearSelectionInSiblings(ANode: TDumbTreeNode);
var node: TDumbTreeNode;
begin
Assert(Assigned(ANode));
node := ANode;
repeat
node.FFlags := node.FFlags - [nfFocused, nfSelected];
if node.FChild <> nil then
ClearSelectionInSiblings(node.FChild);
node := node.FSibling;
until node = nil;
end;
procedure TDumbTreeView.AdjustScrollbars;
begin
FVertRange := FVisibleNodes;
FHorzRange := FMaxRowWidth;
FScrollInfo.fMask := SIF_PAGE or SIF_POS or SIF_RANGE;
FScrollInfo.nMin := 0;
FScrollInfo.nMax := FHorzRange;
FScrollInfo.nPos := FHorzPos;
FScrollInfo.nPage := ClientWidth;
SetScrollInfo(Handle, SB_HORZ, FScrollInfo, True);
FScrollInfo.nMax := FVertRange;
FScrollInfo.nPos := FVertPos;
FScrollInfo.nPage := FWindowRows;
SetScrollInfo(Handle, SB_VERT, FScrollInfo, True);
end;
procedure TDumbTreeView.Paint;
var s1, s2: cardinal;
begin
if (FUpdateCount > 0) or not HandleAllocated then Exit;
FWindowRows := ClientHeight div FRowHeight;
Canvas.Brush.Color := Color;
Canvas.FillRect(ClientRect);
////FMaxRowWidth := 0; // TODO: commented-out here, so need to be resetted to 0 somewhere!!!
FLevel := -1;
FRow := 0;
if RootNode <> nil then
DrawSiblingNodes(RootNode);
FVisibleNodes := FRow - 1;
AdjustScrollBars;
if (FHorzRange > ClientWidth) and (FHorzPos > FHorzRange - ClientWidth) then
FHorzPos := FHorzRange - ClientWidth;
end;
procedure TDumbTreeView.Refresh;
begin
if FUpdateCount > 0 then Exit;
Repaint;
end;
procedure TDumbTreeView.SetEnabled(Value: Boolean);
begin
inherited;
Refresh;
end;
procedure TDumbTreeView.BeginUpdate;
begin
inc(FUpdateCount);
end;
procedure TDumbTreeView.EndUpdate;
begin
dec(FUpdateCount);
end;
procedure TDumbTreeView.SetActiveNode(ANode: TDumbTreeNode);
var allow: boolean;
begin
if Assigned(FBeforeNodeSelect) then
begin
allow := true;
FBeforeNodeSelect(Self, ANode, allow);
if not allow then Exit;
end;
if ANode <> FActiveNode then
begin
if FActiveNode <> nil then
begin
if FMultiSelect then
FActiveNode.FFlags := FActiveNode.FFlags - [nfFocused]
else
FActiveNode.FFlags := FActiveNode.FFlags - [nfFocused, nfSelected];
RefreshNode(FActiveNode);
end;
FActiveNode := ANode;
if FActiveNode <> nil then
begin
if FMultiSelect then
FActiveNode.FFlags := FActiveNode.FFlags + [nfFocused]
else
FActiveNode.FFlags := FActiveNode.FFlags + [nfFocused, nfSelected];
RefreshNode(FActiveNode);
end;
end;
end;
procedure TDumbTreeView.ToggleNodeSelection(ANode: TDumbTreeNode);
begin
Assert(Assigned(ANode));
if nfSelected in ANode.FFlags then
ANode.FFlags := ANode.FFlags - [nfSelected]
else
ANode.FFlags := ANode.FFlags + [nfSelected];
// one-liner for 4-line operation above, but looks like ugly sort of hack:
//ANode.FFlags := TDumbTreeNodeFlags(byte(ANode.FFlags) xor byte(nfsetSelected));
// and needs definition of const nfsetSelected: TDumbTreeNodeFlags = [nfSelected];
RefreshNode(ANode);
end;
procedure TDumbTreeView.ExpandOrCollapseNode(ANode: TDumbTreeNode);
var allow: boolean;
begin
Assert(Assigned(ANode));
if Assigned(FBeforeNodeExpandCollapse) then
begin
allow := true;
FBeforeNodeExpandCollapse(Self, ANode, allow);
if not allow then Exit;
end;
if nfCollapsed in ANode.FFlags then
ANode.FFlags := ANode.FFlags - [nfCollapsed]
else
ANode.FFlags := ANode.FFlags + [nfCollapsed];
Refresh;
end;
function TDumbTreeView.AddSibling(ANode: TDumbTreeNode; AName: string): TDumbTreeNode;
begin
if ANode = nil then
if FRootNode = nil then
begin
Result:= TDumbTreeNode.Create(AName);
FRootNode := Result;
end
else
Result:= FRootNode.AddSibling(AName)
else
Result := ANode.AddSibling(AName);
//inc(FNodeCount);
Refresh;
end;
function TDumbTreeView.AddChild(ANode: TDumbTreeNode; AName: string): TDumbTreeNode;
begin
if ANode = nil then
if FRootNode = nil then
begin
Result:= TDumbTreeNode.Create(AName);
FRootNode := Result;
end
else
Result:= FRootNode.AddChild(AName)
else
Result := ANode.AddChild(AName);
//inc(FNodeCount);
Refresh;
end;
function TDumbTreeView.CompareNodes(N1, N2: TDumbTreeNode): integer;
begin
if Assigned(FOnCompareNodes) then
Result := FOnCompareNodes(Self, N1, N2)
else
if n1.Name = n2.Name then Result := 0 else
if n1.Name < n2.Name then Result := -1 else
Result := 1;
end;
procedure TDumbTreeView.SortChilds(const ANode: TDumbTreeNode);
begin
if ANode.Child <> nil then
ANode.Child := InternalSortSiblings(ANode.Child);
end;
procedure TDumbTreeView.SortSiblings(const ANode: TDumbTreeNode);
begin
if ANode = RootNode then
RootNode := InternalSortSiblings(ANode)
else if ANode.Parent.Child = ANode then
ANode.Parent.Child := InternalSortSiblings(ANode)
else raise Exception.Create('TDumbTreeView.SortSiblings called with not the first sibling of its chain in ANode parameter!');
end;
function TDumbTreeView.InternalSortSiblings(const ANode: TDumbTreeNode): TDumbTreeNode;
// slightly adapted code from http://ru.wikipedia.org/wiki/Сортировка_связного_списка
function IntersectSorted(const ANode1, ANode2: TDumbTreeNode): TDumbTreeNode;
var node, n1, n2: TDumbTreeNode;
begin
n1 := ANode1;
n2 := ANode2;
if CompareNodes(n1, n2) <= 0 then
begin
node := n1;
n1 := n1.Sibling;
end
else begin
node := n2;
n2 := n2.Sibling;
end;
Result := node;
while (n1 <> nil) and (n2 <> nil) do
begin
if CompareNodes(n1, n2) <= 0 then
begin
node.Sibling := n1;
node := n1;
n1 := n1.Sibling;
end
else begin
node.Sibling := n2;
node := n2;
n2 := n2.Sibling;
end;
end;
if n1 <> nil then
node.Sibling := n1
else
node.Sibling := n2;
end;
type
TSortStackItem = record
Level: Integer;
Node: TDumbTreeNode;
end;
var
Stack: Array[0..31] of TSortStackItem; // enough to sort 2^32 nodes
StackPos: Integer;
node: TDumbTreeNode;
begin
StackPos := 0;
node := ANode;
Result := node;
while node <> nil do
begin
Stack[StackPos].Level := 1;
Stack[StackPos].Node := node;
node := node.Sibling;
Stack[StackPos].Node.Sibling := nil;
Inc(StackPos);
while (StackPos > 1) and (Stack[StackPos - 1].Level = Stack[StackPos - 2].Level) do
begin
Stack[StackPos - 2].Node := IntersectSorted(Stack[StackPos - 2].Node, Stack[StackPos - 1].Node);
Inc(Stack[StackPos - 2].Level);
Dec(StackPos);
end;
end;
while StackPos > 1 do
begin
Stack[StackPos - 2].Node := IntersectSorted(Stack[StackPos - 2].Node, Stack[StackPos - 1].Node);
Inc(Stack[StackPos - 2].Level);
Dec(StackPos);
end;
if StackPos > 0 then
Result := Stack[0].Node;
end;
procedure TDumbTreeView.ExpandNode(ANode: TDumbTreeNode);
begin
Assert(Assigned(ANode));
ANode.FFlags := ANode.FFlags - [nfCollapsed];
Refresh;
end;
procedure TDumbTreeView.CollapseNode(ANode: TDumbTreeNode);
begin
Assert(Assigned(ANode));
ANode.FFlags := ANode.FFlags + [nfCollapsed];
Refresh;
end;
procedure TDumbTreeView.SetBorderStyle(Value: TBorderStyle);
begin
if Value <> FBorderStyle then
begin
FBorderStyle := Value;
RecreateWnd;
end;
end;
procedure TDumbTreeView.SetRowHeight(Value: integer);
begin
if Value <> FRowHeight then
begin
FRowHeight := Value;
Refresh;
end;
end;
procedure TDumbTreeView.SetIndent(Value: integer);
begin
if Value <> FIndent then
begin
FIndent := Value;
if FShowRootLines then
FRootIndent := FIndent;
Refresh;
end;
end;
function TDumbTreeView.GetCaptionOffset: integer;
begin
Result := FCaptionOffset;
end;
procedure TDumbTreeView.SetCaptionOffset(Value: integer);
begin
if Value <> FCaptionOffset then
begin
FCaptionOffset := Value;
Refresh;
end;
end;
procedure TDumbTreeView.SetExpandButtonSize(Value: integer);
begin
if Value div 2 <> FExpandButtonHalfSize then
begin
FExpandButtonHalfSize := Value div 2;
Refresh;
end;
end;
function TDumbTreeView.GetExpandButtonSize: integer;
begin
Result:= FExpandButtonHalfSize * 2;
end;
procedure TDumbTreeView.SetSelectedNodeColor(Value: TColor);
begin
if Value <> FSelectedNodeColor then
begin
FSelectedNodeColor := Value;
Refresh;
end;
end;
procedure TDumbTreeView.SetSelectedNodeTextColor(Value: TColor);
begin
if Value <> FSelectedNodeTextColor then
begin
FSelectedNodeTextColor := Value;
Refresh;
end;
end;
procedure TDumbTreeView.SetShowExpandButtons(Value: boolean);
begin
if Value <> FShowExpandButtons then
begin
FShowExpandButtons := Value;
Refresh;
end;
end;
procedure TDumbTreeView.SetShowLines(Value: boolean);
begin
if Value <> FShowLines then
begin
FShowLines := Value;
Refresh;
end;
end;
procedure TDumbTreeView.SetShowRootLines(Value: boolean);
begin
if Value <> FShowRootLines then
begin
FShowRootLines := Value;
if FShowRootLines then
FRootIndent := FIndent
else
FRootIndent := FDefRootIndent;
Refresh;
end;
end;
procedure TDumbTreeView.SetFullRowSelect(Value: boolean);
begin
if Value <> FFullRowSelect then
begin
FFullRowSelect := Value;
Refresh;
end;
end;
procedure TDumbTreeView.SetCollapseBmp(const Value: TBitmap);
begin
FCollapseBmp.Assign(Value);
Refresh;
end;
procedure TDumbTreeView.SetExpandBmp(const Value: TBitmap);
begin
FExpandBmp.Assign(Value);
Refresh;
end;
procedure TDumbTreeView.SetUseButtonBitmaps(const Value: boolean);
begin
if Value <> FUseButtonBitmaps then
begin
FUseButtonBitmaps := Value;
Refresh;
end;
end;
{ TDumbCheckBoxTreeView }
const FCheckMarkColor = clGreen; //$707070;
constructor TDumbCheckBoxTreeView.Create(AOwner: TComponent);
begin
inherited;
FUserCaptionOffset := FCaptionOffset;
//Inc(FCaptionOffset, FRowHeight);
FDefCheckedBmp := TBitmap.Create;
FDefCheckedBmp.LoadFromResourceName(HInstance, 'CHECKED');
FDefUncheckedBmp := TBitmap.Create;
FDefUncheckedBmp.LoadFromResourceName(HInstance, 'UNCHECKED');
FCheckedBmp := TBitmap.Create;
FUncheckedBmp := TBitmap.Create;
end;
destructor TDumbCheckBoxTreeView.Destroy;
begin
FDefCheckedBmp.Free; FDefUncheckedBmp.Free;
FCheckedBmp.Free; FUncheckedBmp.Free;
inherited;
end;
procedure TDumbCheckBoxTreeView.SetCheckBoxes(Value: boolean);
begin
if Value <> FCheckBoxes then
begin
FCheckBoxes := Value;
FCaptionOffset := FUserCaptionOffset;
if FCheckBoxes then inc(FCaptionOffset, FRowHeight);
Refresh;
end;
end;
function TDumbCheckBoxTreeView.GetCaptionOffset: integer;
begin
Result := FUserCaptionOffset;
end;
procedure TDumbCheckBoxTreeView.SetCaptionOffset(Value: integer);
begin
FUserCaptionOffset := Value;
if FCheckBoxes then Inc(Value, FRowHeight);
inherited SetCaptionOffset(Value);
end;
procedure TDumbCheckBoxTreeView.SetRowHeight(Value: integer);
begin
if FCheckBoxes then
FCaptionOffset := FUserCaptionOffset + Value;
inherited;
end;
procedure TDumbCheckBoxTreeView.DrawNodeCaption(ANode: TDumbTreeNode; ALevel, ARow: integer);
var rct: TRect;
d: Integer;
begin
inherited;
if not FCheckBoxes then Exit;
if (FRowHeight >= 15) and (FRowHeight <= 19) then
begin
rct.Left := FRootIndent + FIndent * ALevel - FHorzPos + 1;
rct.Top := FRowHeight * (ARow - FFirstRow) + FVertOffset + FRowHeight div 18 + 1;
rct.Right := rct.Left + 13;
rct.Bottom := rct.Top + 13;
end
else begin
rct.Left := FRootIndent + FIndent * ALevel - FHorzPos + 2;
rct.Top := FRowHeight * (ARow - FFirstRow) + FVertOffset + 2;
rct.Right := rct.Left + FRowHeight - 4;
rct.Bottom := rct.Top + FRowHeight - 4;
end;
if FUseButtonBitmaps then
begin
if nfChecked in ANode.Flags then
if FCheckedBmp.HandleAllocated then
Canvas.StretchDraw(rct, FCheckedBmp)
else
Canvas.StretchDraw(rct, FDefCheckedBmp)
else
if FUncheckedBmp.HandleAllocated then
Canvas.StretchDraw(rct, FUncheckedBmp)
else
Canvas.StretchDraw(rct, FDefUncheckedBmp);
end
else begin
{} // version with windows-drawn checkmark
Canvas.Brush.Color := Color;
if nfChecked in ANode.Flags then
begin
{
inc(rct.Right); Dec(rct.Top);
DrawFrameControl(Canvas.Handle, rct, DFC_MENU, DFCS_MENUCHECK);
dec(rct.Right); inc(rct.Top);
Canvas.Brush.Style := bsClear;
}
d:= FRowHeight div 5;
Canvas.Brush.Color := FCheckMarkColor;
Canvas.Pen.Style := psClear;
//Canvas.Pen.Color := clGreen;
Canvas.Polygon([Point(rct.Left+d, rct.Bottom-d*3),
Point(rct.Left+d, rct.Bottom-d*2),
Point(rct.Left+d*2-1, rct.Bottom-d),
Point(rct.Right-d, rct.Top+d*2-2),
Point(rct.Right-d, rct.Top+d-2),
Point(rct.Left+d*2-1, rct.Bottom-d*2)
]);
Canvas.Brush.Style := bsClear;
Canvas.Pen.Style := psSolid;
end else
Canvas.Brush.Style := bsSolid;
if FRowHeight > 18 then Canvas.Pen.Width := 2;
Canvas.Pen.Color := clBlack;
Canvas.Rectangle(rct);
Canvas.Pen.Width := 1;
{ // fully-drawn-by-lines version
Canvas.Brush.Color := clWhite;
Canvas.Pen.Color := clBlack;
Canvas.Pen.Width := FRowHeight div 11;
Canvas.Rectangle(rct);
if nfChecked in ANode.Flags then
begin
d:= FRowHeight div 6 + 1;
Canvas.Pen.Color := FCheckMarkColor;
Canvas.Pen.Width := FRowHeight div 6;
Canvas.MoveTo(rct.Left+d, (rct.Top+Rct.Bottom) div 2);
Canvas.LineTo((rct.Left+rct.Right) div 2, rct.Bottom-d);
Canvas.LineTo(rct.Right-d, rct.Top+d);
end;
Canvas.Pen.Width := 1;
}
end;
end;
procedure TDumbCheckBoxTreeView.DoNodeClick(ANode: TDumbTreeNode; AButton: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
inherited;
////Application.MainForm.Caption:=Format('%d %d', [X, Y]);
if (x > 0) and (x < FRowHeight) then
begin
if nfChecked in ANode.Flags then
ANode.Flags := ANode.Flags - [nfChecked]
else
ANode.Flags := ANode.Flags + [nfChecked];
RefreshNode(ANode);
end;
end;
procedure TDumbCheckboxTreeView.SetCheckedBmp(const Value: TBitmap);
begin
FCheckedBmp.Assign(Value);
Refresh;
end;
procedure TDumbCheckboxTreeView.SetUncheckedBmp(const Value: TBitmap);
begin
FUncheckedBmp.Assign(Value);
Refresh;
end;
end.
|
unit IdMessageCollection;
{*
TIdMessageCollection: Contains a collection of IdMessages.
2000-APR-14 Peter Mee: Converted to Indy.
2001-MAY-03 Idan Cohen: Added Create and Destroy of TIdMessage.
Originally by Peter Mee.
*}
interface
uses
Classes,
IdMessage;
type
TIdMessageItems = class of TIdMessageItem;
TIdMessageItem = class(TCollectionItem)
protected
FAttempt: Integer;
FQueued: Boolean;
public
IdMessage: TIdMessage;
property Attempt: Integer read FAttempt write FAttempt;
property Queued: Boolean read FQueued write FQueued;
constructor Create(Collection: TCollection); override;
destructor Destroy; override;
end;
TIdMessageCollection = class(TCollection)
private
function GetMessage(index: Integer): TIdMessage;
procedure SetMessage(index: Integer; const Value: TIdMessage);
public
function Add: TIdMessageItem;
property Messages[index: Integer]: TIdMessage read GetMessage write SetMessage; Default;
end;
implementation
function TIdMessageCollection.Add;
begin
Result := TIdMessageItem(inherited Add);
end;
{ TIdMessageItem }
constructor TIdMessageItem.Create;
begin
inherited;
IdMessage := TIdMessage.Create(nil);
end;
destructor TIdMessageItem.Destroy;
begin
IdMessage.Free;
inherited;
end;
function TIdMessageCollection.GetMessage(index: Integer): TIdMessage;
begin
Result := TIdMessageItem(Items[index]).IdMessage;
end;
procedure TIdMessageCollection.SetMessage(index: Integer;
const Value: TIdMessage);
begin
//I think it should be freed before the new value is assigned or else the
//pointer will be lost.
TIdMessageItem(Items[index]).IdMessage.Free;
TIdMessageItem(Items[index]).IdMessage := Value;
end;
end.
|
{Pascal function that tests if a number is prime
The function tests if a number is prime by looking for possible divisors between 2 and the square root of the number
There is no need to look for divisors bigger than the square root of the number, since if they exist,
then there should also exist another divisor, which is smaller than the square root,
and with which if multiplied it would give the original number.}
function is_prime(number:longint):boolean;
var i:longint;
return_value: boolean;
begin
return_value := true;
for i:=2 to trunc(sqrt(number)) do
begin
if (number mod i = 0) then
begin
return_value := false;
break;
end;
end;
if (return_value = true) then
if (number = 0) or (number = 1) then return_value := false;
is_prime := return_value;
end;
|
unit JD.Weather.NWS;
interface
uses
System.Classes, System.SysUtils, System.Generics.Collections,
Vcl.Graphics, Vcl.Imaging.Jpeg, Vcl.Imaging.PngImage, Vcl.Imaging.GifImg,
JD.Weather, JD.Weather.Intf, SuperObject;
type
TNWSWeatherThread = class(TJDWeatherThread)
public
public
function GetUrl: String; override;
function DoAll(Conditions: TWeatherConditions; Forecast: TWeatherForecast;
ForecastDaily: TWeatherForecast; ForecastHourly: TWeatherForecast;
Alerts: TWeatherAlerts; Maps: TWeatherMaps): Boolean; override;
function DoConditions(Conditions: TWeatherConditions): Boolean; override;
function DoForecast(Forecast: TWeatherForecast): Boolean; override;
function DoForecastHourly(Forecast: TWeatherForecast): Boolean; override;
function DoForecastDaily(Forecast: TWeatherForecast): Boolean; override;
function DoAlerts(Alerts: TWeatherAlerts): Boolean; override;
function DoMaps(Maps: TWeatherMaps): Boolean; override;
end;
implementation
uses
DateUtils, StrUtils, Math;
{ TNWSWeatherThread }
function TNWSWeatherThread.GetUrl: String;
begin
Result:= ''; //TODO
end;
function TNWSWeatherThread.DoAlerts(Alerts: TWeatherAlerts): Boolean;
begin
Result:= False;
end;
function TNWSWeatherThread.DoAll(Conditions: TWeatherConditions; Forecast,
ForecastDaily, ForecastHourly: TWeatherForecast; Alerts: TWeatherAlerts;
Maps: TWeatherMaps): Boolean;
begin
Result:= False;
end;
function TNWSWeatherThread.DoConditions(
Conditions: TWeatherConditions): Boolean;
begin
Result:= False;
end;
function TNWSWeatherThread.DoForecast(Forecast: TWeatherForecast): Boolean;
begin
Result:= False;
end;
function TNWSWeatherThread.DoForecastDaily(Forecast: TWeatherForecast): Boolean;
begin
Result:= False;
end;
function TNWSWeatherThread.DoForecastHourly(
Forecast: TWeatherForecast): Boolean;
begin
Result:= False;
end;
function TNWSWeatherThread.DoMaps(Maps: TWeatherMaps): Boolean;
begin
Result:= False;
end;
end.
|
unit TestClass;
{$mode delphi}
interface
uses
Classes, SysUtils;
type
{ TRect }
TRect = class
private
FHeight: Integer;
FWidth: Integer;
procedure SetHeight(AValue: Integer);
procedure SetWidth(AValue: Integer);
public
property Width: Integer read FWidth write SetWidth;
property Height: Integer read FHeight write SetHeight;
function CalcArea: Integer;
end;
implementation
{ TRect }
procedure TRect.SetHeight(AValue: Integer);
begin
if AValue > 0 then
Self.FHeight := AValue
else
Self.FHeight := 0;
end;
procedure TRect.SetWidth(AValue: Integer);
begin
if AValue > 0 then
Self.FWidth := AValue
else
Self.FWidth := 0;
end;
function TRect.CalcArea: Integer;
begin
Result := Self.Width * Self.Height;
end;
end.
|
unit LoanType;
interface
type
TLoanType = class(TObject)
private
FId: integer;
FName: string;
public
property Id: integer read FId write FId;
property Name: string read FName write FName;
constructor Create; overload;
constructor Create(const id: integer; const name: string); overload;
end;
var
ltype: TLoanType;
implementation
constructor TLoanType.Create;
begin
if ltype <> nil then
Exit
else
ltype := self;
end;
constructor TLoanType.Create(const id: integer; const name: string);
begin
FId := id;
FName := name;
end;
end.
|
unit Antlr.Runtime.Collections.Tests;
{
Delphi DUnit Test Case
----------------------
This unit contains a skeleton test case class generated by the Test Case Wizard.
Modify the generated code to correctly setup and call the methods from the unit
being tested.
}
interface
uses
TestFramework,
Antlr.Runtime.Collections,
Generics.Collections,
Antlr.Runtime.Tools;
type
// Test methods for class IHashList
TestIHashList = class(TTestCase)
strict private
FIHashList: IHashList<Integer, String>;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestInsertionOrder;
procedure TestRemove;
end;
// Test methods for class IStackList
TestIStackList = class(TTestCase)
strict private
FIStackList: IStackList<String>;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestPushPop;
procedure TestPeek;
end;
implementation
uses
SysUtils;
const
Values: array [0..9] of Integer = (50, 1, 33, 76, -22, 22, 34, 2, 88, 12);
procedure TestIHashList.SetUp;
var
I: Integer;
begin
FIHashList := THashList<Integer, String>.Create;
for I in Values do
FIHashList.Add(I,'Value' + IntToStr(I));
end;
procedure TestIHashList.TearDown;
begin
FIHashList := nil;
end;
procedure TestIHashList.TestInsertionOrder;
var
I: Integer;
P: TPair<Integer, String>;
begin
I := 0;
for P in FIHashList do
begin
CheckEquals(P.Key, Values[I]);
CheckEquals(P.Value, 'Value' + IntToStr(Values[I]));
Inc(I);
end;
end;
procedure TestIHashList.TestRemove;
var
I: Integer;
P: TPair<Integer, String>;
begin
FIHashList.Remove(34);
I := 0;
for P in FIHashList do
begin
if (Values[I] = 34) then
Inc(I);
CheckEquals(P.Key, Values[I]);
CheckEquals(P.Value, 'Value' + IntToStr(Values[I]));
Inc(I);
end;
end;
procedure TestIStackList.SetUp;
begin
FIStackList := TStackList<String>.Create;
end;
procedure TestIStackList.TearDown;
begin
FIStackList := nil;
end;
procedure TestIStackList.TestPushPop;
var
Item: String;
begin
Item := 'Item 1';
FIStackList.Push(Item);
Item := 'Item 2';
FIStackList.Push(Item);
CheckEquals(FIStackList.Pop,'Item 2');
CheckEquals(FIStackList.Pop,'Item 1');
end;
procedure TestIStackList.TestPeek;
begin
FIStackList.Push('Item 1');
FIStackList.Push('Item 2');
FIStackList.Push('Item 3');
FIStackList.Pop;
CheckEquals(FIStackList.Peek, 'Item 2');
CheckEquals(FIStackList.Pop, 'Item 2');
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestIHashList.Suite);
RegisterTest(TestIStackList.Suite);
end.
|
////////////////////////////////////////////////////////////////////////////////
//
//
// FileName : SUIComboBox.pas
// Creator : Shen Min
// Date : 2002-09-29 V1-V3
// 2003-06-24 V4
// Comment :
//
// Copyright (c) 2002-2003 Sunisoft
// http://www.sunisoft.com
// Email: support@sunisoft.com
//
////////////////////////////////////////////////////////////////////////////////
unit SUIComboBox;
interface
{$I SUIPack.inc}
uses SysUtils, Classes, Controls, StdCtrls, Graphics, Messages, Forms, Windows,
filectrl, ComCtrls,
SUIThemes, SUIMgr;
type
TsuiCustomComboBox = class(TCustomComboBox)
private
m_BorderColor : TColor;
m_ButtonColor : TColor;
m_ArrowColor : TColor;
m_UIStyle : TsuiUIStyle;
m_FileTheme : TsuiFileTheme;
procedure SetBorderColor(const Value: TColor);
procedure WMPAINT(var Msg : TMessage); message WM_PAINT;
procedure WMEARSEBKGND(var Msg : TMessage); message WM_ERASEBKGND;
{$IFDEF SUIPACK_D5}
procedure CBNCloseUp(var Msg : TWMCommand); message CN_COMMAND;
{$ENDIF}
procedure DrawButton();
procedure DrawArrow(const ACanvas : TCanvas;X, Y : Integer);
procedure SetArrowColor(const Value: TColor);
procedure SetButtonColor(const Value: TColor);
procedure SetUIStyle(const Value: TsuiUIStyle);
procedure SetFileTheme(const Value: TsuiFileTheme);
protected
procedure SetEnabled(Value: Boolean); override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
{$IFDEF SUIPACK_D5}
procedure CloseUp(); virtual;
{$ENDIF}
{$IFDEF SUIPACK_D6UP}
procedure CloseUp(); override;
{$ENDIF}
public
constructor Create(AOwner : TComponent); override;
published
property FileTheme : TsuiFileTheme read m_FileTheme write SetFileTheme;
property UIStyle : TsuiUIStyle read m_UIStyle write SetUIStyle;
property BorderColor : TColor read m_BorderColor write SetBorderColor;
property ArrowColor : TColor read m_ArrowColor write SetArrowColor;
property ButtonColor : TColor read m_ButtonColor write SetButtonColor;
end;
TsuiComboBox = class(TsuiCustomComboBox)
published
{$IFDEF SUIPACK_D6UP}
property AutoComplete default True;
property AutoDropDown default False;
{$ENDIF}
property Style; {Must be published before Items}
property Anchors;
property BiDiMode;
property CharCase;
property Color;
property Constraints;
property Ctl3D;
property DragCursor;
property DragKind;
property DragMode;
property DropDownCount;
property Enabled;
property Font;
property ImeMode;
property ImeName;
property ItemHeight;
property ItemIndex default -1;
property MaxLength;
property ParentBiDiMode;
property ParentColor;
property ParentCtl3D;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property Sorted;
property TabOrder;
property TabStop;
property Text;
property Visible;
property OnChange;
property OnClick;
property OnContextPopup;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnDrawItem;
property OnDropDown;
property OnEndDock;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnMeasureItem;
property OnStartDock;
property OnStartDrag;
{$IFDEF SUIPACK_D6UP}
property OnSelect;
{$ENDIF}
property Items; { Must be published after OnMeasureItem }
end;
TsuiDriveComboBox = class(TDriveComboBox)
private
m_BorderColor : TColor;
m_ButtonColor : TColor;
m_ArrowColor : TColor;
m_UIStyle : TsuiUIStyle;
m_FileTheme : TsuiFileTheme;
procedure SetBorderColor(const Value: TColor);
procedure WMPAINT(var Msg : TMessage); message WM_PAINT;
procedure WMEARSEBKGND(var Msg : TMessage); message WM_ERASEBKGND;
{$IFDEF SUIPACK_D5}
procedure CBNCloseUp(var Msg : TWMCommand); message CN_COMMAND;
{$ENDIF}
procedure DrawButton();
procedure DrawArrow(const ACanvas : TCanvas;X, Y : Integer);
procedure SetArrowColor(const Value: TColor);
procedure SetButtonColor(const Value: TColor);
procedure SetUIStyle(const Value: TsuiUIStyle);
procedure SetFileTheme(const Value: TsuiFileTheme);
function GetDroppedDown: Boolean;
procedure SetDroppedDown(const Value: Boolean);
protected
procedure SetEnabled(Value: Boolean); override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
{$IFDEF SUIPACK_D5}
procedure CloseUp(); virtual;
{$ENDIF}
{$IFDEF SUIPACK_D6UP}
procedure CloseUp(); override;
{$ENDIF}
public
constructor Create(AOwner : TComponent); override;
published
property FileTheme : TsuiFileTheme read m_FileTheme write SetFileTheme;
property UIStyle : TsuiUIStyle read m_UIStyle write SetUIStyle;
property BorderColor : TColor read m_BorderColor write SetBorderColor;
property ArrowColor : TColor read m_ArrowColor write SetArrowColor;
property ButtonColor : TColor read m_ButtonColor write SetButtonColor;
property DroppedDown: Boolean read GetDroppedDown write SetDroppedDown;
end;
TsuiFilterComboBox = class(TFilterComboBox)
private
m_BorderColor : TColor;
m_ButtonColor : TColor;
m_ArrowColor : TColor;
m_UIStyle : TsuiUIStyle;
m_FileTheme : TsuiFileTheme;
procedure SetBorderColor(const Value: TColor);
procedure WMPAINT(var Msg : TMessage); message WM_PAINT;
procedure WMEARSEBKGND(var Msg : TMessage); message WM_ERASEBKGND;
{$IFDEF SUIPACK_D5}
procedure CBNCloseUp(var Msg : TWMCommand); message CN_COMMAND;
{$ENDIF}
procedure DrawButton();
procedure DrawArrow(const ACanvas : TCanvas;X, Y : Integer);
procedure SetArrowColor(const Value: TColor);
procedure SetButtonColor(const Value: TColor);
procedure SetUIStyle(const Value: TsuiUIStyle);
procedure SetFileTheme(const Value: TsuiFileTheme);
function GetDroppedDown: Boolean;
procedure SetDroppedDown(const Value: Boolean);
protected
procedure SetEnabled(Value: Boolean); override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
{$IFDEF SUIPACK_D5}
procedure CloseUp(); virtual;
{$ENDIF}
{$IFDEF SUIPACK_D6UP}
procedure CloseUp(); override;
{$ENDIF}
public
constructor Create(AOwner : TComponent); override;
published
property FileTheme : TsuiFileTheme read m_FileTheme write SetFileTheme;
property UIStyle : TsuiUIStyle read m_UIStyle write SetUIStyle;
property BorderColor : TColor read m_BorderColor write SetBorderColor;
property ArrowColor : TColor read m_ArrowColor write SetArrowColor;
property ButtonColor : TColor read m_ButtonColor write SetButtonColor;
property DroppedDown: Boolean read GetDroppedDown write SetDroppedDown;
end;
implementation
uses SUIPublic, SUIResDef;
{ TsuiCustomComboBox }
{$IFDEF SUIPACK_D5}
procedure TsuiCustomComboBox.CBNCloseUp(var Msg: TWMCommand);
begin
if Msg.NotifyCode = CBN_CLOSEUP then
CloseUp()
else
inherited;
end;
{$ENDIF}
procedure TsuiCustomComboBox.CloseUp;
begin
inherited;
if Parent <> nil then
Parent.Repaint();
end;
constructor TsuiCustomComboBox.Create(AOwner: TComponent);
begin
inherited;
ControlStyle := ControlStyle + [csOpaque];
BorderWidth := 0;
UIStyle := GetSUIFormStyle(AOwner);
end;
procedure TsuiCustomComboBox.DrawArrow(const ACanvas : TCanvas; X, Y: Integer);
begin
if not Enabled then
begin
ACanvas.Brush.Color := clWhite;
ACanvas.Pen.Color := clWhite;
ACanvas.Polygon([Point(X + 1, Y + 1), Point(X + 7, Y + 1), Point(X + 4, Y + 4)]);
ACanvas.Brush.Color := clGray;
ACanvas.Pen.Color := clGray;
end
else
begin
ACanvas.Brush.Color := m_ArrowColor;
ACanvas.Pen.Color := m_ArrowColor;
end;
ACanvas.Polygon([Point(X, Y), Point(X + 6, Y), Point(X + 3, Y + 3)]);
end;
procedure TsuiCustomComboBox.DrawButton;
var
R, ListRect : TRect;
X, Y : Integer;
Btn : graphics.TBitmap;
pcbi : tagCOMBOBOXINFO;
C: TControlCanvas;
DesktopCanvas : TCanvas;
begin
pcbi.cbSize := SizeOf(pcbi);
if not SUIGetComboBoxInfo(Handle, pcbi) then
Exit;
// draw border
if Style <> csSimple then
begin
C := TControlCanvas.Create;
C.Control := Self;
with C do
begin
C.Brush.Color := m_BorderColor;
R := ClientRect;
FrameRect(R);
C.Brush.Color := Color;
InflateRect(R, -1, -1);
FrameRect(R);
GetWindowRect(pcbi.hwndList, ListRect);
if DroppedDown then
begin
DesktopCanvas := TCanvas.Create();
DesktopCanvas.Handle := GetWindowDC(0);
DesktopCanvas.Brush.Color := m_BorderColor;
DesktopCanvas.FrameRect(ListRect);
ReleaseDC(0, DesktopCanvas.Handle);
DesktopCanvas.Free();
end
end;
// Draw button
R := pcbi.rcButton;
if {$IFDEF RES_MACOS} (m_UIStyle = MacOS) {$ELSE} false {$ENDIF} or
{$IFDEF RES_WINXP} (m_UIStyle = WinXP) {$ELSE} false {$ENDIF} then
begin
Btn := graphics.TBitmap.Create();
{$IFDEF RES_MACOS}
if m_UIStyle = MacOS then
Btn.LoadFromResourceName(hInstance, 'MACOS_COMBOBOX_BUTTON')
else
{$ENDIF}
Btn.LoadFromResourceName(hInstance, 'WINXP_COMBOBOX_BUTTON');
C.StretchDraw(R, Btn);
Btn.Free();
end
else
begin
C.Brush.Color := m_ButtonColor;
C.FillRect(R);
C.Pen.Color := m_BorderColor;
if (BidiMode = bdRightToLeft) and SysLocale.MiddleEast then
begin
C.MoveTo(R.Right, R.Top - 1);
C.LineTo(R.Right, R.Bottom + 1);
end
else
begin
C.MoveTo(R.Left, R.Top - 1);
C.LineTo(R.Left, R.Bottom + 1);
end;
end;
X := (R.Right - R.Left) div 2 + R.Left - 3;
Y := (R.Bottom - R.Top) div 2;
if {$IFDEF RES_WINXP} m_UIStyle <> WinXP {$ELSE} True {$ENDIF} then
DrawArrow(C, X, Y);
C.Free;
end;
end;
procedure TsuiCustomComboBox.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited;
if (
(Operation = opRemove) and
(AComponent = m_FileTheme)
)then
begin
m_FileTheme := nil;
SetUIStyle(SUI_THEME_DEFAULT);
end;
end;
procedure TsuiCustomComboBox.SetArrowColor(const Value: TColor);
begin
m_ArrowColor := Value;
Repaint();
end;
procedure TsuiCustomComboBox.SetBorderColor(const Value: TColor);
begin
m_BorderColor := Value;
Repaint();
end;
procedure TsuiCustomComboBox.SetButtonColor(const Value: TColor);
begin
m_ButtonColor := Value;
Repaint();
end;
procedure TsuiCustomComboBox.SetEnabled(Value: Boolean);
begin
inherited;
Repaint();
end;
procedure TsuiCustomComboBox.SetFileTheme(const Value: TsuiFileTheme);
begin
m_FileTheme := Value;
SetUIStyle(m_UIStyle);
end;
procedure TsuiCustomComboBox.SetUIStyle(const Value: TsuiUIStyle);
var
OutUIStyle : TsuiUIStyle;
begin
m_UIStyle := Value;
m_ArrowColor := clBlack;
if UsingFileTheme(m_FileTheme, m_UIStyle, OutUIStyle) then
begin
m_BorderColor := m_FileTheme.GetColor(SUI_THEME_CONTROL_BORDER_COLOR);
m_ButtonColor := m_FileTheme.GetColor(SUI_THEME_FORM_BACKGROUND_COLOR);
end
else
begin
m_BorderColor := GetInsideThemeColor(OutUIStyle, SUI_THEME_CONTROL_BORDER_COLOR);
m_ButtonColor := GetInsideThemeColor(OutUIStyle, SUI_THEME_FORM_BACKGROUND_COLOR);
end;
Repaint();
end;
procedure TsuiCustomComboBox.WMEARSEBKGND(var Msg: TMessage);
begin
inherited;
DrawButton();
end;
procedure TsuiCustomComboBox.WMPAINT(var Msg: TMessage);
begin
inherited;
DrawButton();
end;
{ TsuiDriveComboBox }
{$IFDEF SUIPACK_D5}
procedure TsuiDriveComboBox.CBNCloseUp(var Msg: TWMCommand);
begin
if Msg.NotifyCode = CBN_CLOSEUP then
CloseUp()
else
inherited;
end;
{$ENDIF}
procedure TsuiDriveComboBox.CloseUp;
begin
if Parent <> nil then
Parent.Repaint();
end;
constructor TsuiDriveComboBox.Create(AOwner: TComponent);
begin
inherited;
ControlStyle := ControlStyle + [csOpaque];
BorderWidth := 0;
ItemHeight := 15;
UIStyle := GetSUIFormStyle(AOwner);
end;
procedure TsuiDriveComboBox.DrawArrow(const ACanvas: TCanvas; X,
Y: Integer);
begin
if not Enabled then
begin
ACanvas.Brush.Color := clWhite;
ACanvas.Pen.Color := clWhite;
ACanvas.Polygon([Point(X + 1, Y + 1), Point(X + 7, Y + 1), Point(X + 4, Y + 4)]);
ACanvas.Brush.Color := clGray;
ACanvas.Pen.Color := clGray;
end
else
begin
ACanvas.Brush.Color := m_ArrowColor;
ACanvas.Pen.Color := m_ArrowColor;
end;
ACanvas.Polygon([Point(X, Y), Point(X + 6, Y), Point(X + 3, Y + 3)]);
end;
procedure TsuiDriveComboBox.DrawButton;
var
R, ListRect : TRect;
X, Y : Integer;
Btn : graphics.TBitmap;
pcbi : tagCOMBOBOXINFO;
C: TControlCanvas;
DesktopCanvas : TCanvas;
begin
pcbi.cbSize := SizeOf(pcbi);
if not SUIGetComboBoxInfo(Handle, pcbi) then
Exit;
// draw border
C := TControlCanvas.Create;
C.Control := Self;
with C do
begin
C.Brush.Color := m_BorderColor;
R := ClientRect;
FrameRect(R);
C.Brush.Color := Color;
InflateRect(R, -1, -1);
FrameRect(R);
GetWindowRect(pcbi.hwndList, ListRect);
if DroppedDown then
begin
DesktopCanvas := TCanvas.Create();
DesktopCanvas.Handle := GetWindowDC(0);
DesktopCanvas.Brush.Color := m_BorderColor;
DesktopCanvas.FrameRect(ListRect);
ReleaseDC(0, DesktopCanvas.Handle);
DesktopCanvas.Free();
end
end;
// Draw button
R := pcbi.rcButton;
if {$IFDEF RES_MACOS} (m_UIStyle = MacOS) {$ELSE} false {$ENDIF} or
{$IFDEF RES_WINXP} (m_UIStyle = WinXP) {$ELSE} false {$ENDIF} then
begin
Btn := graphics.TBitmap.Create();
{$IFDEF RES_MACOS}
if m_UIStyle = MacOS then
Btn.LoadFromResourceName(hInstance, 'MACOS_COMBOBOX_BUTTON')
else
{$ENDIF}
Btn.LoadFromResourceName(hInstance, 'WINXP_COMBOBOX_BUTTON');
C.StretchDraw(R, Btn);
Btn.Free();
end
else
begin
C.Brush.Color := m_ButtonColor;
C.FillRect(R);
C.Pen.Color := m_BorderColor;
if (BidiMode = bdRightToLeft) and SysLocale.MiddleEast then
begin
C.MoveTo(R.Right, R.Top - 1);
C.LineTo(R.Right, R.Bottom + 1);
end
else
begin
C.MoveTo(R.Left, R.Top - 1);
C.LineTo(R.Left, R.Bottom + 1);
end;
end;
X := (R.Right - R.Left) div 2 + R.Left - 3;
Y := (R.Bottom - R.Top) div 2;
if {$IFDEF RES_WINXP} m_UIStyle <> WinXP {$ELSE} True {$ENDIF} then
DrawArrow(C, X, Y);
C.Free;
end;
function TsuiDriveComboBox.GetDroppedDown: Boolean;
begin
Result := LongBool(SendMessage(Handle, CB_GETDROPPEDSTATE, 0, 0));
end;
procedure TsuiDriveComboBox.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited;
if (
(Operation = opRemove) and
(AComponent = m_FileTheme)
)then
begin
m_FileTheme := nil;
SetUIStyle(SUI_THEME_DEFAULT);
end;
end;
procedure TsuiDriveComboBox.SetArrowColor(const Value: TColor);
begin
m_ArrowColor := Value;
Repaint();
end;
procedure TsuiDriveComboBox.SetBorderColor(const Value: TColor);
begin
m_BorderColor := Value;
Repaint();
end;
procedure TsuiDriveComboBox.SetButtonColor(const Value: TColor);
begin
m_ButtonColor := Value;
Repaint();
end;
procedure TsuiDriveComboBox.SetDroppedDown(const Value: Boolean);
var
R: TRect;
begin
SendMessage(Handle, CB_SHOWDROPDOWN, Longint(Value), 0);
R := ClientRect;
InvalidateRect(Handle, @R, True);
end;
procedure TsuiDriveComboBox.SetEnabled(Value: Boolean);
begin
inherited;
Repaint();
end;
procedure TsuiDriveComboBox.SetFileTheme(const Value: TsuiFileTheme);
begin
m_FileTheme := Value;
SetUIStyle(m_UIStyle);
end;
procedure TsuiDriveComboBox.SetUIStyle(const Value: TsuiUIStyle);
var
OutUIStyle : TsuiUIStyle;
begin
m_UIStyle := Value;
m_ArrowColor := clBlack;
if UsingFileTheme(m_FileTheme, m_UIStyle, OutUIStyle) then
begin
m_BorderColor := m_FileTheme.GetColor(SUI_THEME_CONTROL_BORDER_COLOR);
m_ButtonColor := m_FileTheme.GetColor(SUI_THEME_FORM_BACKGROUND_COLOR);
end
else
begin
m_BorderColor := GetInsideThemeColor(OutUIStyle, SUI_THEME_CONTROL_BORDER_COLOR);
m_ButtonColor := GetInsideThemeColor(OutUIStyle, SUI_THEME_FORM_BACKGROUND_COLOR);
end;
Repaint();
end;
procedure TsuiDriveComboBox.WMEARSEBKGND(var Msg: TMessage);
begin
inherited;
DrawButton();
end;
procedure TsuiDriveComboBox.WMPAINT(var Msg: TMessage);
begin
inherited;
DrawButton();
end;
{ TsuiFilterComboBox }
{$IFDEF SUIPACK_D5}
procedure TsuiFilterComboBox.CBNCloseUp(var Msg: TWMCommand);
begin
if Msg.NotifyCode = CBN_CLOSEUP then
CloseUp()
else
inherited;
end;
{$ENDIF}
procedure TsuiFilterComboBox.CloseUp;
begin
if Parent <> nil then
Parent.Repaint();
end;
constructor TsuiFilterComboBox.Create(AOwner: TComponent);
begin
inherited;
ControlStyle := ControlStyle + [csOpaque];
BorderWidth := 0;
ItemHeight := 15;
UIStyle := GetSUIFormStyle(AOwner);
end;
procedure TsuiFilterComboBox.DrawArrow(const ACanvas: TCanvas; X,
Y: Integer);
begin
if not Enabled then
begin
ACanvas.Brush.Color := clWhite;
ACanvas.Pen.Color := clWhite;
ACanvas.Polygon([Point(X + 1, Y + 1), Point(X + 7, Y + 1), Point(X + 4, Y + 4)]);
ACanvas.Brush.Color := clGray;
ACanvas.Pen.Color := clGray;
end
else
begin
ACanvas.Brush.Color := m_ArrowColor;
ACanvas.Pen.Color := m_ArrowColor;
end;
ACanvas.Polygon([Point(X, Y), Point(X + 6, Y), Point(X + 3, Y + 3)]);
end;
procedure TsuiFilterComboBox.DrawButton;
var
R, ListRect : TRect;
X, Y : Integer;
Btn : graphics.TBitmap;
pcbi : tagCOMBOBOXINFO;
C: TControlCanvas;
DesktopCanvas : TCanvas;
begin
pcbi.cbSize := SizeOf(pcbi);
if not SUIGetComboBoxInfo(Handle, pcbi) then
Exit;
// draw border
C := TControlCanvas.Create;
C.Control := Self;
with C do
begin
C.Brush.Color := m_BorderColor;
R := ClientRect;
FrameRect(R);
C.Brush.Color := Color;
InflateRect(R, -1, -1);
FrameRect(R);
GetWindowRect(pcbi.hwndList, ListRect);
if DroppedDown then
begin
DesktopCanvas := TCanvas.Create();
DesktopCanvas.Handle := GetWindowDC(0);
DesktopCanvas.Brush.Color := m_BorderColor;
DesktopCanvas.FrameRect(ListRect);
ReleaseDC(0, DesktopCanvas.Handle);
DesktopCanvas.Free();
end
end;
// Draw button
R := pcbi.rcButton;
if {$IFDEF RES_MACOS} (m_UIStyle = MacOS) {$ELSE} false {$ENDIF} or
{$IFDEF RES_WINXP} (m_UIStyle = WinXP) {$ELSE} false {$ENDIF} then
begin
Btn := graphics.TBitmap.Create();
{$IFDEF RES_MACOS}
if m_UIStyle = MacOS then
Btn.LoadFromResourceName(hInstance, 'MACOS_COMBOBOX_BUTTON')
else
{$ENDIF}
Btn.LoadFromResourceName(hInstance, 'WINXP_COMBOBOX_BUTTON');
C.StretchDraw(R, Btn);
Btn.Free();
end
else
begin
C.Brush.Color := m_ButtonColor;
C.FillRect(R);
C.Pen.Color := m_BorderColor;
if (BidiMode = bdRightToLeft) and SysLocale.MiddleEast then
begin
C.MoveTo(R.Right, R.Top - 1);
C.LineTo(R.Right, R.Bottom + 1);
end
else
begin
C.MoveTo(R.Left, R.Top - 1);
C.LineTo(R.Left, R.Bottom + 1);
end;
end;
X := (R.Right - R.Left) div 2 + R.Left - 3;
Y := (R.Bottom - R.Top) div 2;
if {$IFDEF RES_WINXP} m_UIStyle <> WinXP {$ELSE} True {$ENDIF} then
DrawArrow(C, X, Y);
C.Free;
end;
function TsuiFilterComboBox.GetDroppedDown: Boolean;
begin
Result := LongBool(SendMessage(Handle, CB_GETDROPPEDSTATE, 0, 0));
end;
procedure TsuiFilterComboBox.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited;
if (
(Operation = opRemove) and
(AComponent = m_FileTheme)
)then
begin
m_FileTheme := nil;
SetUIStyle(SUI_THEME_DEFAULT);
end;
end;
procedure TsuiFilterComboBox.SetArrowColor(const Value: TColor);
begin
m_ArrowColor := Value;
Repaint();
end;
procedure TsuiFilterComboBox.SetBorderColor(const Value: TColor);
begin
m_BorderColor := Value;
Repaint();
end;
procedure TsuiFilterComboBox.SetButtonColor(const Value: TColor);
begin
m_ButtonColor := Value;
Repaint();
end;
procedure TsuiFilterComboBox.SetDroppedDown(const Value: Boolean);
var
R: TRect;
begin
SendMessage(Handle, CB_SHOWDROPDOWN, Longint(Value), 0);
R := ClientRect;
InvalidateRect(Handle, @R, True);
end;
procedure TsuiFilterComboBox.SetEnabled(Value: Boolean);
begin
inherited;
Repaint();
end;
procedure TsuiFilterComboBox.SetFileTheme(const Value: TsuiFileTheme);
begin
m_FileTheme := Value;
SetUIStyle(m_UIStyle);
end;
procedure TsuiFilterComboBox.SetUIStyle(const Value: TsuiUIStyle);
var
OutUIStyle : TsuiUIStyle;
begin
m_UIStyle := Value;
m_ArrowColor := clBlack;
if UsingFileTheme(m_FileTheme, m_UIStyle, OutUIStyle) then
begin
m_BorderColor := m_FileTheme.GetColor(SUI_THEME_CONTROL_BORDER_COLOR);
m_ButtonColor := m_FileTheme.GetColor(SUI_THEME_FORM_BACKGROUND_COLOR);
end
else
begin
m_BorderColor := GetInsideThemeColor(OutUIStyle, SUI_THEME_CONTROL_BORDER_COLOR);
m_ButtonColor := GetInsideThemeColor(OutUIStyle, SUI_THEME_FORM_BACKGROUND_COLOR);
end;
Repaint();
end;
procedure TsuiFilterComboBox.WMEARSEBKGND(var Msg: TMessage);
begin
inherited;
DrawButton();
end;
procedure TsuiFilterComboBox.WMPAINT(var Msg: TMessage);
begin
inherited;
DrawButton();
end;
end.
|
unit SearchProductDescriptionQuery;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, HandlingQueryUnit, FireDAC.Stan.Intf,
FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS,
FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt,
Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Vcl.StdCtrls, DSWrap;
type
TSearchProductDescriptionW = class(TDSWrap)
private
FDescrID: TFieldWrap;
FID: TFieldWrap;
FDescriptionID: TFieldWrap;
public
constructor Create(AOwner: TComponent); override;
property DescrID: TFieldWrap read FDescrID;
property ID: TFieldWrap read FID;
property DescriptionID: TFieldWrap read FDescriptionID;
end;
TQuerySearchProductDescription = class(THandlingQuery)
FDUpdateSQL: TFDUpdateSQL;
private
FW: TSearchProductDescriptionW;
{ Private declarations }
protected
property W: TSearchProductDescriptionW read FW;
public
constructor Create(AOwner: TComponent); override;
procedure UpdateProductDescriptions(ASender: TObject);
{ Public declarations }
end;
implementation
{$R *.dfm}
uses RepositoryDataModule;
constructor TQuerySearchProductDescription.Create(AOwner: TComponent);
begin
inherited;
FW := TSearchProductDescriptionW.Create(FDQuery);
end;
procedure TQuerySearchProductDescription.UpdateProductDescriptions(ASender:
TObject);
var
i: Integer;
begin
Assert(FDQuery.Active);
// начинаем транзакцию, если она ещё не началась
if (not FDQuery.Connection.InTransaction) then
FDQuery.Connection.StartTransaction;
FDQuery.Last;
FDQuery.First;
i := 0;
CallOnProcessEvent;
while not FDQuery.Eof do
begin
// Связываем компоненты со своими описаниями
if W.DescriptionID.F.AsInteger <> W.DescrID.F.AsInteger then
begin
W.TryEdit;
W.DescriptionID.F.AsInteger := W.DescrID.F.AsInteger;
W.TryPost;
Inc(i);
// Уже много записей обновили в рамках одной транзакции
if i >= 1000 then
begin
i := 0;
FDQuery.Connection.Commit;
FDQuery.Connection.StartTransaction;
end;
end;
FDQuery.Next;
CallOnProcessEvent;
end;
FDQuery.Connection.Commit;
end;
constructor TSearchProductDescriptionW.Create(AOwner: TComponent);
begin
inherited;
FID := TFieldWrap.Create(Self, 'ID', '', True);
FDescrID := TFieldWrap.Create(Self, 'DescrID');
FDescriptionID := TFieldWrap.Create(Self, 'DescriptionID');
end;
end.
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2019 The Bitcoin Core developers
// Copyright (c) 2020-2020 Skybuck Flying
// Copyright (c) 2020-2020 The Delphicoin Developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
// Bitcoin file: src/coins.h
// Bitcoin file: src/coins.cpp
// Bitcoin commit hash: f656165e9c0d09e654efabd56e6581638e35c26c
unit Unit_Coins_Utilities;
interface
{
#include <compressor.h>
#include <core_memusage.h>
#include <crypto/siphash.h>
#include <memusage.h>
#include <primitives/transaction.h>
#include <serialize.h>
#include <uint256.h>
#include <assert.h>
#include <stdint.h>
#include <functional>
#include <unordered_map>
}
//! Utility function to add all of a transaction's outputs to a cache.
//! When check is false, this assumes that overwrites are only possible for coinbase transactions.
//! When check is true, the underlying view may be queried to determine whether an addition is
//! an overwrite.
// TODO: pass in a boolean to limit these possible overwrites to known
// (pre-BIP34) cases.
void AddCoins(CCoinsViewCache& cache, const CTransaction& tx, int nHeight, bool check = false);
//! Utility function to find any unspent output with a given txid.
//! This function can be quite expensive because in the event of a transaction
//! which is not found in the cache, it can cause up to MAX_OUTPUTS_PER_BLOCK
//! lookups to database, so it should be used with care.
const Coin& AccessByTxid(const CCoinsViewCache& cache, const uint256& txid);
implementation
#include <coins.h>
#include <consensus/consensus.h>
#include <logging.h>
#include <random.h>
#include <version.h>
void AddCoins(CCoinsViewCache& cache, const CTransaction &tx, int nHeight, bool check_for_overwrite) {
bool fCoinbase = tx.IsCoinBase();
const uint256& txid = tx.GetHash();
for (size_t i = 0; i < tx.vout.size(); ++i) {
bool overwrite = check_for_overwrite ? cache.HaveCoin(COutPoint(txid, i)) : fCoinbase;
// Coinbase transactions can always be overwritten, in order to correctly
// deal with the pre-BIP30 occurrences of duplicate coinbase transactions.
cache.AddCoin(COutPoint(txid, i), Coin(tx.vout[i], nHeight, fCoinbase), overwrite);
}
}
static const Coin coinEmpty;
static const size_t MIN_TRANSACTION_OUTPUT_WEIGHT = WITNESS_SCALE_FACTOR * ::GetSerializeSize(CTxOut(), PROTOCOL_VERSION);
static const size_t MAX_OUTPUTS_PER_BLOCK = MAX_BLOCK_WEIGHT / MIN_TRANSACTION_OUTPUT_WEIGHT;
const Coin& AccessByTxid(const CCoinsViewCache& view, const uint256& txid)
{
COutPoint iter(txid, 0);
while (iter.n < MAX_OUTPUTS_PER_BLOCK) {
const Coin& alternate = view.AccessCoin(iter);
if (!alternate.IsSpent()) return alternate;
++iter.n;
}
return coinEmpty;
}
end.
|
unit ufmFormSizedFonts;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ufmFormBase, dxPSGlbl, dxPSUtl, dxPSEngn, dxPrnPg, dxBkgnd, dxWrap,
dxPrnDev, dxPSCompsProvider, dxPSFillPatterns, dxPSEdgePatterns,
dxPSPDFExportCore, dxPSPDFExport, cxDrawTextUtils, dxPSPrVwStd, dxPSPrVwAdv,
dxPSPrVwRibbon, dxPScxPageControlProducer, dxPScxEditorProducers,
dxPScxExtEditorProducers, dxBar, dxPSCore, cxGridCustomPopupMenu,
cxGridPopupMenu, cxClasses, ExtCtrls, uParentedPanel, LMDSimplePanel;
type
TSizeInfo = class
name : string;
size : integer;
end;
{TOnChangeInfo = class
name : string;
mthd : TMethod;
end;}
TOnResizeComponentEvent = procedure(Sender: TObject; aComponent:TComponent; var newWidth, newHeight:integer) of object;
TSizeInfoList = class(TList)
protected
function Get(Index: Integer): TSizeInfo;
procedure Put(Index: Integer; Item: TSizeInfo);
public
procedure Clear; override;
function byName(aName:string):TSizeInfo;
function exists(aName:string):boolean;
function Add(aName:string; aSize:integer): Integer;
end;
{TOnChangeInfoList = class(TList)
protected
function Get(Index: Integer): TOnChangeInfo;
procedure Put(Index: Integer; Item: TOnChangeInfo);
public
procedure Clear; override;
function byName(aName:string):TOnChangeInfo;
function exists(aName:string):boolean;
function Add(aName:string; aMthd:TMethod): Integer;
end;}
TFrmSizedFonts = class(TFrmBase)
private
fOnParentModified : TOnParentModifiedEvent;
fOnResizeSimplePanel : TOnResizeComponentEvent;
fOnResizeComponent : TOnResizeComponentEvent;
fLastParent : TWinControl;
fIsFullScreen : boolean;
fZoomFactor : double;
fNormailFormFontSize : integer;
fSizeInfoList : TSizeInfoList;
//fOnChangeInfoList : TOnChangeInfoList;
//fCustomEditPropertiesInfoList : TOnChangeInfoList;
fSimplePanelList :TStringList;
procedure panPriOnParentModified(Sender:TObject; aParent:TWinControl);
procedure resizeControl(aComponent: TComponent);
procedure InternalSetParent(AParent: TWinControl);
procedure calcZoomFactor(aComponent:TControl; var f1, f2: TFont; var aZoomFactorX, aZoomFactorY: double);
//procedure ControlChange(Sender:TObject);
protected
procedure resizeControls; dynamic;
procedure doParentModified(AParent: TWinControl); virtual;
procedure SetParent(AParent: TWinControl); override;
procedure SetZoomFactor(value:double);
procedure doResizeSimplePanel(aComponent:TComponent; var newWidth, newHeight:integer); virtual;
procedure doResizeComponent(aComponent:TComponent; var newWidth, newHeight:integer); virtual;
public
property isFullScreen : boolean read fIsFullScreen write fIsFullScreen;
property onResizeSimplePanel : TOnResizeComponentEvent read fOnResizeSimplePanel write fOnResizeSimplePanel;
property onResizeComponent : TOnResizeComponentEvent read fOnResizeComponent write fOnResizeComponent;
property ZoomFactor : double read fZoomFactor write SetZoomFactor;
procedure ParentChanged; override;
procedure setNormalScreen;
procedure setFullScreen;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property OnParentModified : TOnParentModifiedEvent read FOnParentModified write FOnParentModified;
end;
var
FrmSizedFonts: TFrmSizedFonts;
implementation
{$R *.dfm}
{ TfbFormSizedFonts }
uses
TypInfo, dxDockControl, ncaFrmPri, StdCtrls, uLogs,
math, cxContainer, cxDBLookupComboBox{, cxEdit{, cxLookupEdit};
constructor TFrmSizedFonts.Create(AOwner: TComponent);
begin
inherited;
panPri.OnParentModified := panPriOnParentModified;
fSizeInfoList := TSizeInfoList.create;
//fOnChangeInfoList := TOnChangeInfoList.create;
//fCustomEditPropertiesInfoList := TOnChangeInfoList.create;
fSimplePanelList := TStringList.create;
end;
destructor TFrmSizedFonts.Destroy;
begin
fSizeInfoList.free;
//fOnChangeInfoList.free;
//fCustomEditPropertiesInfoList.free;
fSimplePanelList.free;
inherited;
end;
procedure TFrmSizedFonts.ParentChanged;
begin
inherited;
end;
procedure TFrmSizedFonts.doParentModified(AParent: TWinControl);
begin
if assigned(FOnParentModified) then
fOnParentModified(Self, AParent);
ParentChanged;
end;
procedure TFrmSizedFonts.doResizeComponent(aComponent: TComponent; var newWidth,
newHeight: integer);
begin
if assigned(fOnResizeComponent) then
fOnResizeComponent(Self, aComponent, newWidth, newHeight);
end;
procedure TFrmSizedFonts.doResizeSimplePanel(aComponent:TComponent; var newWidth, newHeight: integer);
begin
if assigned(fOnResizeSimplePanel) then
fOnResizeSimplePanel(Self, aComponent, newWidth, newHeight);
end;
procedure TFrmSizedFonts.InternalSetParent(AParent: TWinControl);
begin
resizeControls;
end;
procedure TFrmSizedFonts.panPriOnParentModified(Sender: TObject; aParent:TWinControl);
begin
if fNormailFormFontSize=0 then begin
fNormailFormFontSize := self.Font.Size;
end;
if parent<>aParent then
doParentModified(aParent);
end;
procedure TFrmSizedFonts.calcZoomFactor(aComponent:TControl; var f1, f2: TFont; var aZoomFactorX, aZoomFactorY: double);
var
PropInfo: PPropInfo;
bmp : TBitmap;
x1,x2,y1,y2 : integer;
txt : string;
begin
aZoomFactorX := fZoomFactor;
aZoomFactorY := fZoomFactor;
txt := '';
PropInfo := GetPropInfo(aComponent, 'caption');
if Assigned(PropInfo) then
txt := GetStrProp(aComponent, 'caption')
else begin
PropInfo := GetPropInfo(aComponent, 'text');
if Assigned(PropInfo) then
txt := GetStrProp(aComponent, 'text')
end;
if txt<>'' then begin
bmp := TBitmap.create;
try
bmp.PixelFormat := pf24bit;
bmp.Width := trunc(TControl(aComponent).Width * fZoomFactor * 1.3);
bmp.Height := trunc(TControl(aComponent).Height * fZoomFactor * 1.3);
with bmp.canvas do begin
Font.Assign(f1);
x1 := TextWidth(txt);
y1 := TextHeight(txt);
Font.Assign(f2);
x2 := TextWidth(txt);
y2 := TextHeight(txt);
end;
aZoomFactorX := x2 / x1;
aZoomFactorY := y2 / y1;
finally
bmp.free;
end;
end;
end;
procedure TFrmSizedFonts.resizeControl(aComponent: TComponent);
var
f1, f2 : TFont;
b : boolean;
PropInfo: PPropInfo;
//mthd : TMethod;
//PEvent: ^TNotifyEvent;
cProp : TcxLookupComboBoxProperties; //TcxCustomEditProperties;
cStyle : TcxContainerStyle;
clss : TClass;
x, y, newWidth, newHeight : integer;
aZoomFactorX, aZoomFactorY : double;
begin
if (fSizeInfoList.exists(aComponent.name)) {or
(fOnChangeInfoList.exists(aComponent.name)) or
(fCustomEditPropertiesInfoList.exists(aComponent.name))} then exit;
//if (fSizeInfoList.exists(aComponent.name)) and
// (fSizeInfoList.byName(aComponent.name).size = trunc(valorqueseja)) then exit;
glog.log(self,[lcTrace],'resizeControl: '+aComponent.ClassName+' '+aComponent.Name);
{PropInfo := GetPropInfo(aComponent, 'font', [tkClass]);
if Assigned(PropInfo) then begin
glog.log(self,[lcTrace],'resizeControl font: '+aComponent.ClassName+' '+aComponent.Name);
mthd.Code := nil;
mthd.Data := nil;
PropInfo := GetPropInfo(aComponent, 'OnChange');
if Assigned(PropInfo) and (PropInfo^.PropType^^.Kind = tkMethod) then begin
mthd := GetMethodProp(aComponent, PropInfo);
fOnChangeInfoList.Add(aComponent.name, mthd);
glog.log(self,[lcTrace],'resizeControl OnChange: '+aComponent.ClassName+' '+aComponent.Name);
PEvent := @mthd.Code;
PEvent^ := ControlChange;
mthd.Data := Self;
SetMethodProp(aComponent, 'OnChange', mthd);
end else
glog.log(self,[lcTrace],'resizeControl OnChange not found: '+aComponent.ClassName+' '+aComponent.Name);
end;
PropInfo := GetPropInfo(aComponent, 'Properties');
if Assigned(PropInfo) then begin
clss := GetObjectPropClass(aComponent, 'Properties');
if Assigned(clss) then begin
cep := TcxCustomEditProperties(GetObjectProp(aComponent, 'Properties', clss));
if Assigned(cep) then begin
glog.log(self,[lcTrace],'resizeControl Properties: '+aComponent.ClassName+' '+aComponent.Name);
if Assigned(cep.OnChange) then begin
PEvent := @mthd.Code;
PEvent^ := cep.OnChange
end else
glog.log(self,[lcTrace],'resizeControl Properties.OnChange unassigned: '+aComponent.ClassName+' '+aComponent.Name);
mthd.Data := Self;
fCustomEditPropertiesInfoList.Add(aComponent.name, mthd);
cep.OnChange := ControlChange;
SetObjectProp(aComponent, 'Properties', cep);
end else
glog.log(self,[lcTrace],'resizeControl Properties unassigned: '+aComponent.ClassName+' '+aComponent.Name)
end else
glog.log(self,[lcTrace],'resizeControl Properties cass unassigned: '+aComponent.ClassName+' '+aComponent.Name)
end else
glog.log(self,[lcTrace],'resizeControl Properties not found: '+aComponent.ClassName+' '+aComponent.Name);
}
PropInfo := GetPropInfo(aComponent, 'ParentFont');
if Assigned(PropInfo) then begin
b := GetOrdProp(aComponent, 'ParentFont')=1;
if b then begin;
glog.log(self,[lcTrace],'resizeControl: '+aComponent.ClassName+' '+aComponent.Name+' has Parent Font');
exit;
end;
end else
glog.log(self,[lcTrace],'resizeControl: no parent font prop: '+aComponent.ClassName+' '+aComponent.Name);
PropInfo := GetPropInfo(aComponent, 'font', [tkClass]);
if Assigned(PropInfo) then begin
f2 := TFont(GetObjectProp(aComponent, 'font', TFont));
if Assigned(f2) then begin;
glog.log(self,[lcTrace],'resizeControl: '+aComponent.ClassName+' '+aComponent.Name+' has '+ inttostr(f2.Height)+'->'+inttostr(trunc(f2.Height * fZoomFactor))+' font Height');
f1 := TFont.Create;
try
f1.assign(f2);
f2.Height := trunc(f2.Height * fZoomFactor);
SetObjectProp(aComponent, 'font', f2);
fSizeInfoList.add(aComponent.Name, f2.Height);
if aComponent is TControl then begin
calcZoomFactor(TControl(aComponent), f1, f2, aZoomFactorX, aZoomFactorY);
newWidth := trunc( TControl(aComponent).Width * fZoomFactor);
newHeight := trunc( TControl(aComponent).Height * fZoomFactor);
doResizeComponent(aComponent, newWidth, newHeight);
TControl(aComponent).Width := newWidth;
TControl(aComponent).Height := newHeight;
end;
finally
f1.free;
end;
end;
end else begin
glog.log(self,[lcTrace],'resizeControl: no font prop: '+aComponent.ClassName+' '+aComponent.Name);
PropInfo := GetPropInfo(aComponent, 'Style');
if Assigned(PropInfo) then begin
clss := GetObjectPropClass(aComponent, 'Style');
if Assigned(clss) then begin
cStyle := TcxContainerStyle(GetObjectProp(aComponent, 'Style', clss));
if Assigned(cStyle) then begin
glog.log(self,[lcTrace],'resizeControl Style: '+aComponent.ClassName+' '+aComponent.Name);
if Assigned(cStyle.Font) then begin
end else
glog.log(self,[lcTrace],'resizeControl Style.Font unassigned: '+aComponent.ClassName+' '+aComponent.Name);
f2 := cStyle.Font;
f1 := TFont.Create;
try
f1.assign(f2);
f2.Height := trunc(f2.Height * fZoomFactor);
fSizeInfoList.add(aComponent.Name, f2.Height);
if aComponent is TControl then begin
calcZoomFactor(TControl(aComponent), f1, f2, aZoomFactorX, aZoomFactorY);
newWidth := trunc( TControl(aComponent).Width * fZoomFactor);
newHeight := trunc( TControl(aComponent).Height * fZoomFactor);
doResizeComponent(aComponent, newWidth, newHeight);
TControl(aComponent).Width := newWidth;
TControl(aComponent).Height := newHeight;
end;
finally
f1.free;
end;
cStyle.Font.assign(f2);
SetObjectProp(aComponent, 'Style', cStyle);
end else
glog.log(self,[lcTrace],'resizeControl Style unassigned: '+aComponent.ClassName+' '+aComponent.Name);
{
PropInfo := GetPropInfo(aComponent, 'Properties');
if Assigned(PropInfo) then begin
glog.log(self,[lcTrace],'resizeControl Properties: '+aComponent.ClassName+' '+aComponent.Name);
clss := GetObjectPropClass(aComponent, 'Properties');
if Assigned(clss) then begin
if clss = TcxLookupComboBoxProperties then begin
cProp := TcxLookupComboBoxProperties(GetObjectProp(aComponent, 'Properties', clss));
x := trunc(cProp.DropDownWidth * aZoomFactorX);
cProp.DropDownWidth := min(x, self.width - TControl(aComponent).left - 10);
y := trunc(cProp.DropDownHeight * aZoomFactorY);
cProp.DropDownHeight := min(y, self.height - TControl(aComponent).Top - 10);
//SetObjectProp(aComponent, 'Properties', cProp);
end;
end else
glog.log(self,[lcTrace],'resizeControl Properties class unassigned: '+aComponent.ClassName+' '+aComponent.Name)
end else
glog.log(self,[lcTrace],'resizeControl Properties not found: '+aComponent.ClassName+' '+aComponent.Name);
}
end else
glog.log(self,[lcTrace],'resizeControl Style class unassigned: '+aComponent.ClassName+' '+aComponent.Name)
end else
glog.log(self,[lcTrace],'resizeControl Style not found: '+aComponent.ClassName+' '+aComponent.Name);
end;
end;
{procedure TFrmSizedFonts.ControlChange(Sender:TObject);
begin
glog.log(self,[lcTrace],'ControlChange: '+Sender.ClassName+' '+TComponent(Sender).Name);
end;}
procedure TFrmSizedFonts.resizeControls;
var
i, newWidth, newHeight : integer;
sp : TLMDSimplePanel;
begin
for i:=0 to ComponentCount-1 do begin
if (Components[i] is TLMDSimplePanel) and
(fSimplePanelList.indexof(Components[i].name)=-1)
then begin
sp := TLMDSimplePanel(Components[i]);
sp.AutoSize := false;
sp.AllowSizing := true;
if sp.align<>alClient then begin
newWidth := trunc( sp.Width * fZoomFactor);
newHeight := trunc( sp.Height * fZoomFactor);
doResizeSimplePanel(sp, newWidth, newHeight);
sp.Width := newWidth;
sp.Height := newHeight;
end;
fSimplePanelList.add(sp.name);
end;
resizeControl(Components[i]);
end;
//for i:=0 to ComponentCount-1 do
// if Components[i] is TLMDSimplePanel then
// TLMDSimplePanel(Components[i]).AutoSize := true;
end;
procedure TFrmSizedFonts.setFullScreen;
begin
fLastParent := panPri.Parent;
panPri.Parent := FrmPri;
fIsFullScreen := true;
resizeControls;
end;
procedure TFrmSizedFonts.setNormalScreen;
begin
panPri.Parent := fLastParent;
fIsFullScreen := false;
resizeControls;
end;
procedure TFrmSizedFonts.SetParent(AParent: TWinControl);
begin
inherited;
InternalSetParent(aParent)
end;
procedure TFrmSizedFonts.SetZoomFactor(value: double);
begin
if value<>fZoomFactor then begin
fZoomFactor := value;
resizeControls;
end;
end;
{ TSizeInfoList }
function TSizeInfoList.Add(aName:string; aSize:integer): Integer;
var
Item: TSizeInfo;
begin
Item := TSizeInfo.create;
Item.name := aName;
Item.size := aSize;
result := inherited add(Item);
end;
function TSizeInfoList.byName(aName: string): TSizeInfo;
var
i : integer;
begin
result := nil;
for i:=0 to count-1 do
if sametext(get(i).name,aName) then begin
result := get(i);
exit;
end;
end;
procedure TSizeInfoList.Clear;
var
i : integer;
begin
for i:=0 to count-1 do
get(i).free;
inherited;
end;
function TSizeInfoList.exists(aName: string): boolean;
var
i : integer;
begin
result := false;
for i:=0 to count-1 do
if sametext(get(i).name,aName) then begin
result := true;
exit;
end;
end;
function TSizeInfoList.Get(Index: Integer): TSizeInfo;
begin
result := TSizeInfo(inherited get(Index));
end;
procedure TSizeInfoList.Put(Index: Integer; Item: TSizeInfo);
begin
if not exists(Item.name) then
inherited Put(Index, Item);
end;
{ TOnChangeInfoList }
{
function TOnChangeInfoList.Add(aName: string; aMthd: TMethod): Integer;
var
Item: TOnChangeInfo;
begin
Item := TOnChangeInfo.create;
Item.name := aName;
Item.mthd := aMthd;
result := inherited add(Item);
end;
function TOnChangeInfoList.byName(aName: string): TOnChangeInfo;
var
i : integer;
begin
result := nil;
for i:=0 to count-1 do
if sametext(get(i).name,aName) then begin
result := get(i);
exit;
end;
end;
procedure TOnChangeInfoList.Clear;
var
i : integer;
begin
for i:=0 to count-1 do
get(i).free;
inherited;
end;
function TOnChangeInfoList.exists(aName: string): boolean;
var
i : integer;
begin
result := false;
for i:=0 to count-1 do
if sametext(get(i).name,aName) then begin
result := true;
exit;
end;
end;
function TOnChangeInfoList.Get(Index: Integer): TOnChangeInfo;
begin
result := TOnChangeInfo(inherited get(Index));
end;
procedure TOnChangeInfoList.Put(Index: Integer; Item: TOnChangeInfo);
begin
if not exists(Item.name) then
inherited Put(Index, Item);
end;
}
end.
|
unit uLog;
interface
uses windows,sysutils,uConfig;
procedure init();
procedure Log(txt:string);
var
tf:TextFile;
implementation
procedure init();
begin
if not uConfig.isInit then uConfig.init();
AssignFile(tf,uconfig.logfile);
if(not fileexists(uconfig.logfile))then
Rewrite(tF) //会覆盖已存在的文件
else
Append(tF); //打开准备追加
end;
procedure Log(txt:string);
var
t:string;
begin
t:=FormatDateTime('yyyy-mm-dd hh:nn:ss:zzz', Now);
WriteLn(tf,t);
WriteLn(tf,txt);
flush(tf);
end;
initialization
{初始化部分}
{程序启动时先执行,并顺序执行}
{一个单元的初始化代码运行之前,就运行了它使用的每一个单元的初始化部分}
init();
finalization
{结束化部分,程序结束时执行}
CloseFile(tF);
end.
|
unit LoginDetails;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Registry;
type
TfrmLoginSetup = class(TForm)
GroupBox1: TGroupBox;
edUserName: TEdit;
edPassword: TEdit;
Label1: TLabel;
Label2: TLabel;
Button1: TButton;
Database: TGroupBox;
Label3: TLabel;
edServerName: TEdit;
edDatabase: TEdit;
Label4: TLabel;
Label5: TLabel;
edPort: TEdit;
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
frmLoginSetup: TfrmLoginSetup;
implementation
uses SaveDoc;
{$R *.dfm}
procedure TfrmLoginSetup.Button1Click(Sender: TObject);
var
regAxiom: TRegistry;
sRegistryRoot: string;
bSuccess: boolean;
begin
bSuccess := False;
sRegistryRoot := 'Software\Colateral\Axiom';
regAxiom := TRegistry.Create;
try
regAxiom.RootKey := HKEY_CURRENT_USER;
if regAxiom.OpenKey(sRegistryRoot+'\InsightDocSave', True) then
begin
regAxiom.WriteString('Net','Y');
regAxiom.WriteString('Server Name',edServerName.Text+':'+edPort.Text+':'+edDatabase.Text);
regAxiom.WriteString('User Name',edUserName.Text);
regAxiom.WriteString('Password',edPassword.Text);
regAxiom.CloseKey;
dmSaveDoc.uniInsight.Server := edServerName.Text+':'+edPort.Text+':'+edDatabase.Text;
dmSaveDoc.uniInsight.Username := edUserName.Text;
dmSaveDoc.uniInsight.Password := edPassword.Text;
try
dmSaveDoc.uniInsight.Connect;
dmSaveDoc.uniInsight.Disconnect;
bSuccess := True;
// MessageBox(Self.Handle,'Connection Test Succesfull.','DragON',MB_OK+MB_ICONINFORMATION);
except
bSuccess := False;
end;
end;
finally
regAxiom.Free;
end;
if bSuccess then
Close;
end;
procedure TfrmLoginSetup.FormCreate(Sender: TObject);
var
LRegAxiom: TRegistry;
LoginStr, s: string;
begin
LregAxiom := TRegistry.Create;
try
LregAxiom.RootKey := HKEY_CURRENT_USER;
LregAxiom.OpenKey('Software\Colateral\Axiom\InsightDocSave', False);
s := Copy(LregAxiom.ReadString('Server Name'),1,Pos(':',LregAxiom.ReadString('Server Name'))-1);
LoginStr := Copy(LregAxiom.ReadString('Server Name'),Pos(':',LregAxiom.ReadString('Server Name'))+1, Length(LregAxiom.ReadString('Server Name')) - Pos(':',LregAxiom.ReadString('Server Name')) );
if s <> '' then
edServerName.Text := s;
s := Copy(LoginStr,1,Pos(':',LoginStr)-1);
LoginStr := Copy(LoginStr,Pos(':',LoginStr)+1, Length(LoginStr));
if s <> '' then
edPort.Text := s;
s := LoginStr;
if s <> '' then
edDatabase.Text := s;
edUserName.Text := LregAxiom.ReadString('User Name');
edPassword.Text := LregAxiom.ReadString('Password');
finally
LregAxiom.Free;
end;
end;
end.
|
unit InfoSourceList;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BaseGridDetail, Data.DB, RzButton,
Vcl.StdCtrls, Vcl.Mask, RzEdit, Vcl.Grids, Vcl.DBGrids, RzDBGrid, RzLabel,
Vcl.ExtCtrls, RzPanel, RzDBEdit;
type
TfrmInfoSourceList = class(TfrmBaseGridDetail)
edSource: TRzDBEdit;
Label2: TLabel;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
public
{ Public declarations }
protected
function EntryIsValid: boolean; override;
function NewIsAllowed: boolean; override;
function EditIsAllowed: boolean; override;
procedure SearchList; override;
procedure BindToObject; override;
end;
implementation
{$R *.dfm}
uses
AuxData, IFinanceDialogs;
{ TfrmInfoSourceList }
procedure TfrmInfoSourceList.BindToObject;
begin
inherited;
end;
function TfrmInfoSourceList.EditIsAllowed: boolean;
begin
Result := true;
end;
function TfrmInfoSourceList.EntryIsValid: boolean;
var
error: string;
begin
if Trim(edSource.Text) = '' then error := 'Please enter source.';
if error <> '' then ShowErrorBox(error);
Result := error = '';
end;
procedure TfrmInfoSourceList.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
dmAux.Free;
inherited;
end;
procedure TfrmInfoSourceList.FormCreate(Sender: TObject);
begin
dmAux := TdmAux.Create(self);
inherited;
end;
function TfrmInfoSourceList.NewIsAllowed: boolean;
begin
Result := true;
end;
procedure TfrmInfoSourceList.SearchList;
begin
grList.DataSource.DataSet.Locate('source_name',edSearchKey.Text,
[loPartialKey,loCaseInsensitive]);
end;
end.
|
unit uTiposDeImpressao;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, cxGraphics, cxControls, cxLookAndFeels,
cxLookAndFeelPainters, dxSkinsCore, dxSkinBlack, dxSkinBlue, dxSkinCaramel,
dxSkinCoffee, dxSkinDarkRoom, dxSkinDarkSide, dxSkinFoggy, dxSkinGlassOceans,
dxSkiniMaginary, dxSkinLilian, dxSkinLiquidSky, dxSkinLondonLiquidSky,
dxSkinMcSkin, dxSkinMoneyTwins, dxSkinOffice2007Black, dxSkinOffice2007Blue,
dxSkinOffice2007Green, dxSkinOffice2007Pink, dxSkinOffice2007Silver,
dxSkinOffice2010Black, dxSkinOffice2010Blue, dxSkinOffice2010Silver,
dxSkinPumpkin, dxSkinSeven, dxSkinSharp, dxSkinSilver, dxSkinSpringTime,
dxSkinStardust, dxSkinSummer2008, dxSkinsDefaultPainters, dxSkinValentine,
dxSkinXmas2008Blue, cxContainer, cxEdit, cxListBox, cxDBEdit, Menus, cxButtons,
cxTextEdit, cxMemo, ncPrinters, udmTipodeImpressao, cxStyles,
dxSkinscxPCPainter, cxCustomData, cxFilter, cxData, cxDataStorage, DB,
cxDBData, cxGridCustomTableView, cxGridTableView, cxGridDBTableView,
cxGridLevel, cxClasses, cxGridCustomView, cxGrid, uPrinterConstsAndTypes,
cxDBLookupComboBox, cxDropDownEdit, cxLookupEdit, cxDBLookupEdit, cxMaskEdit,
uJson, printers, uPrinterInfo8, uPrintException;
Const
kTipoDeImpressao = 'tipo de impressão';
kCriarTipoDeImpressaoTittle = 'Criar novo '+kTipoDeImpressao;
kModificarTipoDeImpressaoTittle = 'Modificar '+kTipoDeImpressao;
kCriarTipoDeImpressaoQuestion = 'Realmente quer terminar a criação do novo '+kTipoDeImpressao+'?';
kCriarTipoDeImpressaoTittle2 = 'Finalizando a criação de novo '+kTipoDeImpressao;
kModificarTipoDeImpressaoQuestion = 'Realmente quer terminar a modificação de '+kTipoDeImpressao+'?';
kModificarTipoDeImpressaoTittle2 = 'Finalizando a modificação de '+kTipoDeImpressao;
kPrintersJsonFile = 'C:\nexcafe\printers.json';
type
TFormTipoDeImpressao = class(TForm)
Label2: TLabel;
cxButtonCriar: TcxButton;
cxQUITESCROTO: TcxButton;
cxGrid1DBTableView1: TcxGridDBTableView;
cxGrid1Level1: TcxGridLevel;
cxGrid1: TcxGrid;
cxGrid1DBTableView1Nome: TcxGridDBColumn;
cxGrid1DBTableView1Impressora: TcxGridDBColumn;
cxGrid1DBTableView1Valor: TcxGridDBColumn;
cxGrid1DBTableView1ID: TcxGridDBColumn;
cxButtonAgapar: TcxButton;
cxButtonModificar: TcxButton;
cxButtonJson: TcxButton;
Memo1: TMemo;
cxLookupComboBox1: TcxLookupComboBox;
Label1: TLabel;
procedure FormCreate(Sender: TObject);
procedure cxButtonCriarClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure cxQUITESCROTOClick(Sender: TObject);
procedure cxGrid1DBTableView1CellClick(Sender: TcxCustomGridTableView;
ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton;
AShift: TShiftState; var AHandled: Boolean);
procedure cxButtonAgaparClick(Sender: TObject);
procedure cxButtonModificarClick(Sender: TObject);
procedure cxButtonJsonClick(Sender: TObject);
private
{ Private declarations }
jPrinters : TJSONObject;
fPrinters : TStringList;
fdefPrinterId : integer;
procedure SelecionarImpresora;
procedure PedirNomeDoTipoDeImpressao;
procedure ConfigPrinter;
procedure SalvarTipoDeImpressao;
function CalcProxCod:integer;
procedure RefreshPMValorMinMax(aFileName:string);
procedure PedirPreco;
function GetPrinterAsJson(getStreamFromDB:boolean):string;
function GetPrintersAsJson:string;
function CheckName(Sender: TObject; aNomeTipo:string):boolean;
function jPrintersGetDefaultPrinter(aJsonText:string):integer;
public
IdTipoImpressao : integer;
printerName :string;
info8AsJson :string;
tipoImpressaoName :string;
preco :double;
PrinterInfo8Stream : TMemoryStream;
function CapturePrinter(Sender: TForm; update:boolean):boolean;
{ Public declarations }
end;
var
FormTipoDeImpressao: TFormTipoDeImpressao;
implementation
uses
ncgPrintInstall, WinSpool, uFormPasso1, uFormBackG1, uFormPasso2,
strutils, uFormPassoQuerSair, uFormPasso3, uFormPasso4;
{$R *.dfm}
function SimNaoH(S: String; H : HWND): Boolean;
begin
Result := (MessageBox(H, PChar(S), 'Atenção',
MB_YESNO + MB_ICONQUESTION + MB_APPLMODAL) = IDYES)
end;
function TFormTipoDeImpressao.jPrintersGetDefaultPrinter(aJsonText:string):integer;
begin
result := 0;
jPrinters.free;
try
jPrinters := TJSONObject.create( aJsonText );
if jPrinters.has('defaultPrinter') then begin
result := jPrinters.getInt('defaultPrinter');
end;
except
end;
end;
procedure TFormTipoDeImpressao.FormCreate(Sender: TObject);
function StrinListAsAsql(sl:TStrings):string;
var
i : integer;
begin
result := '';
for i:=0 to sl.Count-1 do
result := result + ', ''' + trim(sl.Text) + '''';
result := copy(result, 3, maxint);
end;
begin
top := 0;
left := 0;
height := screen.WorkAreaHeight;
width := screen.WorkAreaWidth;
PrinterInfo8Stream := TMemoryStream.create;
fPrinters := TStringList.create;
fPrinters.assign(GetPrinterList(true));
cxButtonAgapar.Enabled := false;
cxButtonModificar.Enabled := false;
with dmTipodeImpressao do begin
if nxTablePrinters.RecordCount=0 then begin
nxTablePrinters.Append;
nxTablePrintersasJson.AsString := '{}';
nxTablePrinters.post;
nxTablePrinters.first;
end;
if nxTablePrintersasJson.AsString='' then begin
nxTablePrinters.edit;
nxTablePrintersasJson.AsString := '{}';
nxTablePrinters.post;
end;
jPrinters := TJSONObject.create('{}');
fdefPrinterId := jPrintersGetDefaultPrinter(nxTablePrintersasJson.AsString );
cxLookupComboBox1.EditValue := fdefPrinterId;
end;
// desactivar printers q foram desintaladas
with dmTipodeImpressao do begin
nxQuery1.SQL.Text := 'update TipoImp set active=false';
if fPrinters.count>0 then
nxQuery1.SQL.Text := nxQuery1.SQL.Text + ' where Impressora not in ('+ StrinListAsAsql(fPrinters) + ')';
nxQuery1.ExecSQL;
nxTableTipoImp.close;
nxTableTipoImp.Open;
RefreshPMValorMinMax(kPrintersJsonFile);
end;
end;
procedure TFormTipoDeImpressao.FormDestroy(Sender: TObject);
begin
fPrinters.Free;
PrinterInfo8Stream.Free;
jPrinters.free;
end;
procedure TFormTipoDeImpressao.FormShow(Sender: TObject);
begin
FormBackG1.Left := self.Left;
FormBackG1.Top := self.Top;
FormBackG1.Height := self.Height;
FormBackG1.Width := self.Width;
end;
function TFormTipoDeImpressao.GetPrintersAsJson: string;
var
defaultPrinter : integer;
jsonPrinterText : string;
jPrinters1 : TJSONObject;
jPrintersA : TJSONArray;
begin
result := '';
defaultPrinter := cxLookupComboBox1.EditValue;
jsonPrinterText := '{' + '"defaultPrinter":'+inttostr(defaultPrinter)+',"printers": []}' ;
jPrinters1 := TJSONObject.create(jsonPrinterText);
with dmTipodeImpressao do
try
dsTableTipoImp.DataSet := nil;
nxTableTipoImp.First;
while not nxTableTipoImp.Eof do begin
if nxTableTipoImpActive.asboolean then begin
jsonPrinterText := GetPrinterAsJson(true);
nxTableTipoImp.edit;
nxTableTipoImpasJson.AsString := jsonPrinterText;
nxTableTipoImp.post;
jPrintersA := jPrinters1.getJSONArray('printers');
jPrintersA.put(TJSONObject.create(jsonPrinterText));
end;
nxTableTipoImp.Next;
end;
dsTableTipoImp.DataSet := nxTableTipoImp;
result := jPrinters1.toString(4);
finally
jPrinters1.Free;
end;
end;
function TFormTipoDeImpressao.CapturePrinter(Sender: TForm; update:boolean):boolean;
begin
PrinterInfo8Stream.seek(0,0);
if update then begin
RestorePrinterInfo8(pchar(printerName), PrinterInfo8Stream);
PrinterInfo8Stream.seek(0,0);
end;
try
info8AsJson := CapturePrinterInfo8(Sender, pchar(printerName), PrinterInfo8Stream, true);
except
on e:eNexPrinterNotFound do begin
ShowMessage(e.Message)
end;
end;
result := info8AsJson<>'';
end;
procedure TFormTipoDeImpressao.cxGrid1DBTableView1CellClick(
Sender: TcxCustomGridTableView; ACellViewInfo: TcxGridTableDataCellViewInfo;
AButton: TMouseButton; AShift: TShiftState; var AHandled: Boolean);
begin
cxButtonAgapar.Enabled := cxGrid1DBTableView1.Controller.SelectedRecordCount > 0;
cxButtonModificar.Enabled := cxGrid1DBTableView1.Controller.SelectedRecordCount > 0;
end;
procedure TFormTipoDeImpressao.cxQUITESCROTOClick(Sender: TObject);
begin
close
end;
procedure TFormTipoDeImpressao.cxButtonModificarClick(Sender: TObject);
begin
//if fPrinters.Count>0 then
with dmTipodeImpressao do begin
if nxTableTipoImpActive.asboolean then begin
IdTipoImpressao := nxTableTipoImpID.Value;
printerName := nxTableTipoImpImpressora.Value;
tipoImpressaoName := nxTableTipoImpNome.Value;
preco := nxTableTipoImpValor.Value;
info8AsJson := nxTableTipoImpAsJson.Value;
PrinterInfo8Stream.Clear;
nxTableTipoImpPrinterDevMode.SaveToStream(PrinterInfo8Stream);
PrinterInfo8Stream.seek(0,0);
SelecionarImpresora;
end else
Raise exception.Create(
'Tipo de impressão não pode ser modificada'+#13#10+
'porque "'+nxTableTipoImpImpressora.Value+'" foi desintalada.');
end;
end;
procedure TFormTipoDeImpressao.cxButtonCriarClick(Sender: TObject);
begin
if dmTipodeImpressao.nxTableTipoImp.RecordCount>9 then
Raise exception.Create('O NexCafé não aceita mais que 10 tipos de impressões diferentes');
IdTipoImpressao := -1;
SelecionarImpresora;
end;
procedure TFormTipoDeImpressao.SelecionarImpresora;
var
loop : boolean;
mr : TModalResult;
begin
FormBackG1.Show;
with FormPasso1 do begin
loop := true;
while loop do begin
mr := FormPasso1.ShowModal;
if mr=mrOk then begin
PedirNomeDoTipoDeImpressao;
loop := false;
end;
if mr=mrAbort then begin
if FormPassoQuerSair.ShowModal=mrOk then begin
FormBackG1.hide;
exit;
end;
end;
end;
end;
end;
procedure TFormTipoDeImpressao.PedirNomeDoTipoDeImpressao;
var
loop : boolean;
mr : TModalResult;
begin
FormBackG1.Show;
with FormPasso2 do begin
loop := true;
while loop do begin
FormPasso2.onCheckName := CheckName;
mr := FormPasso2.ShowModal;
if mr=mrOk then begin
ConfigPrinter;
loop := false;
end;
if mr=mrIgnore then begin
SelecionarImpresora;
loop := false;
end;
if mr=mrAbort then begin
if FormPassoQuerSair.ShowModal=mrOk then begin
FormBackG1.hide;
exit;
end;
end;
end;
end;
end;
procedure TFormTipoDeImpressao.ConfigPrinter;
var
loop : boolean;
mr : TModalResult;
begin
FormBackG1.Show;
with FormPasso3 do begin
loop := true;
while loop do begin
mr := FormPasso3.ShowModal;
if mr=mrOk then begin
PedirPreco;
loop := false;
end;
if mr=mrIgnore then begin
PedirNomeDoTipoDeImpressao;
loop := false;
end;
if mr=mrAbort then begin
if FormPassoQuerSair.ShowModal=mrOk then begin
FormBackG1.hide;
exit;
end;
end;
end;
end;
end;
procedure TFormTipoDeImpressao.PedirPreco;
var
loop : boolean;
mr : TModalResult;
begin
FormBackG1.Show;
with FormPasso4 do begin
loop := true;
while loop do begin
mr := FormPasso4.ShowModal;
if mr=mrOk then begin
FormBackG1.hide;
SalvarTipoDeImpressao;
loop := false;
end;
if mr=mrIgnore then begin
ConfigPrinter;
loop := false;
end;
if mr=mrAbort then begin
if FormPassoQuerSair.ShowModal=mrOk then begin
FormBackG1.hide;
exit;
end;
end;
end;
end;
end;
function TFormTipoDeImpressao.CheckName(Sender: TObject;
aNomeTipo: string): boolean;
begin
result := false;
with dmTipodeImpressao do begin
dsTableTipoImp.DataSet := nil;
try
nxTableTipoImp.First;
while (not nxTableTipoImp.Eof) do begin
if sametext(nxTableTipoImpNome.Value, aNomeTipo) then begin
result := true;
break
end;
nxTableTipoImp.Next;
end;
finally
dsTableTipoImp.DataSet := nxTableTipoImp;
end;
end;
end;
function TFormTipoDeImpressao.CalcProxCod:integer;
var
Ant: Integer;
begin
with dmTipodeImpressao do begin
dsTableTipoImp.DataSet := nil;
try
nxTableTipoImp.IndexName := 'IID'; //@dario atencao! se nao a coisa embaixo nao vai.
nxTableTipoImp.First;
Ant := 0;
while (not nxTableTipoImp.Eof) and ((nxTableTipoImpID.Value-Ant)=1) do begin
Ant := nxTableTipoImpID.Value;
nxTableTipoImp.Next;
end;
result := Ant + 1;
finally
dsTableTipoImp.DataSet := nxTableTipoImp;
end;
end;
end;
procedure TFormTipoDeImpressao.SalvarTipoDeImpressao;
var
id : integer;
begin
with dmTipodeImpressao do begin
if IdTipoImpressao = -1 then begin
id := CalcProxCod;
nxTableTipoImp.Append;
nxTableTipoImpID.Value := id;
end else begin
if nxTableTipoImp.Locate('ID',IdTipoImpressao,[]) then
nxTableTipoImp.Edit
else
raise eNexIdTipoImpressaoNotFound.Create(IdTipoImpressao);
end;
nxTableTipoImpNome.Value := tipoImpressaoName;
nxTableTipoImpImpressora.Value := printerName;
nxTableTipoImpValor.Value := preco;
nxTableTipoImpContador.Value := 0;
PrinterInfo8Stream.seek(0,0);
nxTableTipoImpPrinterDevMode.LoadFromStream(PrinterInfo8Stream);
// em ultima posição para GetPrinterAsJson já ter assignados os valores acima
nxTableTipoImpActive.Value := printer.Printers.IndexOf(printerName)>-1;
if nxTableTipoImpActive.asBoolean then
nxTableTipoImpAsJson.Value := GetPrinterAsJson(false); //info8AsJson
nxTableTipoImp.Post;
RefreshPMValorMinMax(kPrintersJsonFile);
end;
end;
procedure TFormTipoDeImpressao.RefreshPMValorMinMax(aFileName:string);
var
jsonPrintersText : string;
ss : TStringStream;
ms : TMemoryStream;
begin
jsonPrintersText := GetPrintersAsJson;
memo1.Lines.text := jsonPrintersText ;
ss := TStringStream.create(jsonPrintersText);
ms := TMemoryStream.create;
try
ms.CopyFrom(ss,0);
ms.SaveToFile(aFileName);
finally
ms.free;
ss.free;
end;
with dmTipodeImpressao do begin
nxTablePrinters.edit;
nxTablePrintersasJson.AsString := jsonPrintersText;
nxTablePrinters.post;
fdefPrinterId := jPrintersGetDefaultPrinter( jsonPrintersText );
end;
{
procedure TfbTiposImp.RefreshPMValorMinMax;
var aMin, aMax: Currency;
begin
DM.ObtemValorMinMaxImp(aMin, aMax);
if (gConfig.PMValorMin<>aMin) or (gConfig.PMValorMax<>aMax) then begin
gConfig.AtualizaCache;
gConfig.PMValorMin := aMin;
gConfig.PMValorMax := aMax;
Dados.CM.SalvaAlteracoesObj(gConfig, False);
end;
end;
}
end;
procedure TFormTipoDeImpressao.cxButtonAgaparClick(Sender: TObject);
begin
with dmTipodeImpressao do begin
if not nxTableTipoImp.IsEmpty then
if SimNaoH('Deseja realmente apagar o Tipo de Impressão ' + nxTableTipoImpNome.Value + '?', Handle) then begin
nxTableTipoImp.Delete;
RefreshPMValorMinMax(kPrintersJsonFile);
end;
end;
end;
function TFormTipoDeImpressao.GetPrinterAsJson(getStreamFromDB:boolean): string;
var
aPrinter : TPrinter;
jPrinter : TJSONObject;
dchar : char;
begin
aPrinter := Printer;
dchar := decimalseparator;
decimalseparator := '.';
with dmTipodeImpressao do
try
result := '{';
try
result := result + GetPrinterInfoasJson(nxTableTipoImpImpressora.asstring, aPrinter) +',';
if getStreamFromDB then begin
PrinterInfo8Stream.Clear;
nxTableTipoImpPrinterDevMode.SaveToStream(PrinterInfo8Stream);
end;
PrinterInfo8Stream.seek(0,0);
printerName := nxTableTipoImpImpressora.AsString;
result := result + GetPrinterInfo8asJson(pchar(printerName), PrinterInfo8Stream) +',';
result := result + '"NexcafeID": ' + nxTableTipoImpID.AsString +',';
result := result + '"NexcafeNome": "' + nxTableTipoImpNome.AsString +'",';
result := result + '"NexcafePrecoPP": '+ nxTableTipoImpValor.AsString+'}';
except
on e:exception do
showmessage( nxTableTipoImpImpressora.AsString +' error: '+ e.message);
end;
jPrinter := TJSONObject.create(result);
result := jPrinter.toString(4);
jPrinter.free;
finally;
decimalseparator := dchar;
end;
end;
procedure TFormTipoDeImpressao.cxButtonJsonClick(Sender: TObject);
begin
RefreshPMValorMinMax(kPrintersJsonFile);
end;
end.
|
{*********************************************************************
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Autor: Brovin Y.D.
* E-mail: y.brovin@gmail.com
*
********************************************************************}
unit FGX.ToolBar;
interface
uses
System.Classes, System.Types, System.UITypes, System.Generics.Collections, System.ImageList,
FMX.Controls, FMX.Objects, FMX.StdCtrls, FMX.Types, FMX.Menus, FMX.Dialogs, FMX.ImgList, FMX.ActnList, FMX.ListBox,
FMX.Layouts, FGX.BitBtn;
type
{ TfgToolBar }
TfgCustomToolBar = class;
TfgToolBarDisplayOption = (Text, Image);
TfgToolBarDisplayOptions = set of TfgToolBarDisplayOption;
IfgToolbarButton = interface
['{8EDF7D8B-0839-4C21-9302-D191B6F6C2C9}']
procedure SetToolbar(const AToolbar: TfgCustomToolBar);
procedure UpdateToPreferSize;
procedure UpdateDisplayOptions(const ADisplayOptions: TfgToolBarDisplayOptions);
end;
TfgCustomToolBar = class(TStyledControl, IItemsContainer)
public const
DefaultAutoSize = True;
DefaultHorizontalGap = 3;
DefaultDisplayOptions = [TfgToolBarDisplayOption.Text, TfgToolBarDisplayOption.Image];
strict private
FButtons: TList<TControl>;
FAutoSize: Boolean;
FHorizontalGap: Single;
FDisplayOptions: TfgToolBarDisplayOptions;
private
procedure SetAutoSize(const Value: Boolean);
procedure SetHorizontalGap(const Value: Single);
procedure SetDisplayOptions(const Value: TfgToolBarDisplayOptions);
protected
function GetDefaultSize: TSizeF; override;
procedure Resize; override;
procedure RefreshButtonsSize;
procedure RefreshDisplayOptions;
{ Tree objects structure }
procedure DoAddObject(const AObject: TFmxObject); override;
procedure DoInsertObject(Index: Integer; const AObject: TFmxObject); override;
procedure DoRemoveObject(const AObject: TFmxObject); override;
{ IItemsContainer }
function GetItemsCount: Integer;
function GetItem(const AIndex: Integer): TFmxObject;
function GetObject: TFmxObject;
{ IFreeNotification }
procedure FreeNotification(AObject: TObject); override;
{ Style }
function GetDefaultStyleLookupName: string; override;
procedure DoRealign; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
public
property AutoSize: Boolean read FAutoSize write SetAutoSize;
property Buttons: TList<TControl> read FButtons;
property HorizontalGap: Single read FHorizontalGap write SetHorizontalGap;
property DisplayOptions: TfgToolBarDisplayOptions read FDisplayOptions write SetDisplayOptions;
end;
TfgToolBar = class(TfgCustomToolBar)
published
property AutoSize default TfgCustomToolBar.DefaultAutoSize;
property HorizontalGap;
property DisplayOptions default TfgCustomToolBar.DefaultDisplayOptions;
{ TStyledControl }
property Action;
property Align default TAlignLayout.Top;
property Anchors;
property ClipChildren default False;
property ClipParent default False;
property Cursor default crDefault;
property DragMode default TDragMode.dmManual;
property EnableDragHighlight default True;
property Enabled default True;
property Locked default False;
property Height;
property HelpContext;
property HelpKeyword;
property HelpType;
property HitTest default True;
property Padding;
property Opacity;
property Margins;
property PopupMenu;
property Position;
property RotationAngle;
property RotationCenter;
property Scale;
property Size;
property StyleLookup;
property TabOrder;
property TouchTargetExpansion;
property Visible default True;
property Width;
property OnApplyStyleLookup;
property OnDragEnter;
property OnDragLeave;
property OnDragOver;
property OnDragDrop;
property OnDragEnd;
property OnKeyDown;
property OnKeyUp;
property OnCanFocus;
property OnClick;
property OnDblClick;
property OnEnter;
property OnExit;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnMouseWheel;
property OnMouseEnter;
property OnMouseLeave;
property OnPainting;
property OnPaint;
property OnResize;
end;
{ TfgToolBarButton }
TfgToolBarButton = class(TSpeedButton, IfgToolbarButton, IGlyph)
private
FDisplayOptions: TfgToolBarDisplayOptions;
[Weak] FToolBar: TfgCustomToolBar;
protected
{ Size }
function GetDefaultSize: TSizeF; override;
{ Visibility }
procedure Hide; override;
procedure Show; override;
{ Style }
procedure ApplyStyle; override;
function GetStyleObject: TFmxObject; override;
function GetAdjustType: TAdjustType; override;
function GetAdjustSizeValue: TSizeF; override;
public
{ IToolbarButton }
procedure SetToolbar(const AToolbar: TfgCustomToolBar);
procedure UpdateToPreferSize; virtual;
procedure UpdateDisplayOptions(const ADisplayOptions: TfgToolBarDisplayOptions); virtual;
end;
{ TToolBarPopupButton}
TfgToolBarPopupButton = class(TfgToolBarButton)
strict private
FDropDownButton: TControl;
FPopupMenu: TPopupMenu;
FIsDropDown: Boolean;
protected
{ Style }
procedure ApplyStyle; override;
procedure FreeStyle; override;
{ Location }
function GetDefaultSize: TSizeF; override;
{ Mouse Events }
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X: Single; Y: Single); override;
{ Drop Down Menu }
procedure DoDropDown; virtual;
public
{ IToolbarButton }
procedure UpdateToPreferSize; override;
function HasPopupMenu: Boolean;
published
property IsDropDown: Boolean read FIsDropDown;
property PopupMenu: TPopupMenu read FPopupMenu write FPopupMenu;
end;
{ TToolBarSeparator }
TfgToolBarSeparator = class(TStyledControl, IfgToolbarButton)
protected
function GetDefaultSize: TSizeF; override;
{ IfgToolbarButton }
procedure SetToolbar(const AToolbar: TfgCustomToolBar);
procedure UpdateToPreferSize;
procedure UpdateDisplayOptions(const ADisplayOptions: TfgToolBarDisplayOptions); virtual;
{ Visibility }
procedure Hide; override;
procedure Show; override;
{ Styles }
function GetStyleObject: TFmxObject; override;
function GetAdjustType: TAdjustType; override;
function GetAdjustSizeValue: TSizeF; override;
published
property Action;
property Anchors;
property AutoTranslate default True;
property CanFocus default True;
property CanParentFocus;
property ClipChildren default False;
property ClipParent default False;
property Cursor default crDefault;
property DisableFocusEffect;
property DragMode default TDragMode.dmManual;
property EnableDragHighlight default True;
property Enabled default True;
property Height;
property HelpContext;
property HelpKeyword;
property HelpType;
property HitTest default True;
property Locked default False;
property Padding;
property Opacity;
property Margins;
property PopupMenu;
property Position;
property RotationAngle;
property RotationCenter;
property Scale;
property StyleLookup;
property TabOrder;
property TouchTargetExpansion;
property Visible default True;
property Width;
end;
{ TfgToolBarComboBox }
TfgToolBarComboBox = class(TComboBox, IfgToolbarButton)
private
{ IfgToolbarButton }
procedure SetToolbar(const AToolbar: TfgCustomToolBar);
procedure UpdateToPreferSize;
procedure UpdateDisplayOptions(const ADisplayOptions: TfgToolBarDisplayOptions); virtual;
protected
{ Visibility }
procedure Hide; override;
procedure Show; override;
end;
{ TfgToolBarDivider }
TfgToolBarDivider = class(TLayout, IfgToolbarButton)
private
{ IfgToolbarButton }
procedure SetToolbar(const AToolbar: TfgCustomToolBar);
procedure UpdateToPreferSize;
procedure UpdateDisplayOptions(const ADisplayOptions: TfgToolBarDisplayOptions);
protected
function GetDefaultSize: TSizeF; override;
end;
implementation
uses
System.SysUtils, System.Math, FMX.Utils, FGX.Asserts, FMX.Styles;
{ TfgCustomToolBar }
constructor TfgCustomToolBar.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FButtons := TList<TControl>.Create;
FAutoSize := DefaultAutoSize;
FHorizontalGap := DefaultHorizontalGap;
FDisplayOptions := DefaultDisplayOptions;
Align := TAlignLayout.Top;
end;
destructor TfgCustomToolBar.Destroy;
var
Button: TControl;
begin
for Button in FButtons do
Button.RemoveFreeNotify(Self);
FButtons.Free;
inherited Destroy;
end;
procedure TfgCustomToolBar.DoAddObject(const AObject: TFmxObject);
var
ToolBarButton: IfgToolbarButton;
begin
inherited DoAddObject(AObject);
if (AObject is TControl) and AObject.GetInterface(IfgToolbarButton, ToolBarButton) then
begin
ToolBarButton.SetToolbar(Self);
ToolBarButton.UpdateToPreferSize;
ToolBarButton.UpdateDisplayOptions(DisplayOptions);
FButtons.Add(TControl(AObject));
AObject.AddFreeNotify(Self);
Realign;
end;
end;
procedure TfgCustomToolBar.DoInsertObject(Index: Integer; const AObject: TFmxObject);
var
ToolBarButton: IfgToolbarButton;
begin
inherited DoInsertObject(Index, AObject);
if (AObject is TfgToolBarButton) and AObject.GetInterface(IfgToolbarButton, ToolBarButton) then
begin
ToolBarButton.SetToolbar(Self);
ToolBarButton.UpdateToPreferSize;
ToolBarButton.UpdateDisplayOptions(DisplayOptions);
FButtons.Insert(Index, AObject as TfgToolBarButton);
AObject.AddFreeNotify(Self);
Realign;
end;
end;
procedure TfgCustomToolBar.DoRealign;
var
ControlTmp: TControl;
LastX: Single;
begin
inherited DoRealign;
LastX := Padding.Left;
for ControlTmp in Controls do
begin
{$IFDEF MSWINDOWS}
if (csDesigning in ComponentState) and Supports(ControlTmp, IDesignerControl) then
Continue;
{$ENDIF}
if (ResourceControl <> ControlTmp) and ControlTmp.Visible then
begin
LastX := LastX + Floor(HorizontalGap / 2) + ControlTmp.Margins.Left;
ControlTmp.Position.Point := TPointF.Create(LastX, 0);
LastX := LastX + ControlTmp.Size.Width + ControlTmp.Margins.Right + + HorizontalGap / 2;
end;
end;
end;
procedure TfgCustomToolBar.DoRemoveObject(const AObject: TFmxObject);
begin
inherited DoRemoveObject(AObject);
if AObject is TfgToolBarButton then
begin
FButtons.Remove(AObject as TfgToolBarButton);
AObject.RemoveFreeNotify(Self);
end;
end;
procedure TfgCustomToolBar.FreeNotification(AObject: TObject);
begin
AssertIsNotNil(AObject);
inherited FreeNotification(AObject);
if AObject is TfgToolBarButton then
FButtons.Remove(AObject as TfgToolBarButton);
end;
function TfgCustomToolBar.GetDefaultSize: TSizeF;
begin
Result := TSizeF.Create(100, 40);
end;
function TfgCustomToolBar.GetDefaultStyleLookupName: string;
begin
Result := 'ToolbarStyle';
end;
function TfgCustomToolBar.GetItem(const AIndex: Integer): TFmxObject;
begin
AssertIsNotNil(FButtons);
AssertInRange(AIndex, 0, FButtons.Count - 1);
Result := FButtons[AIndex];
end;
function TfgCustomToolBar.GetItemsCount: Integer;
begin
AssertIsNotNil(FButtons);
Result := FButtons.Count;
end;
function TfgCustomToolBar.GetObject: TFmxObject;
begin
Result := Self;
end;
procedure TfgCustomToolBar.RefreshButtonsSize;
var
ControlTmp: TControl;
ToolBarButton: IfgToolbarButton;
begin
inherited Resize;
if AutoSize then
for ControlTmp in Controls do
if ControlTmp.GetInterface(IfgToolbarButton, ToolBarButton) then
ToolBarButton.UpdateToPreferSize;
end;
procedure TfgCustomToolBar.RefreshDisplayOptions;
var
ControlTmp: TControl;
ToolBarButton: IfgToolbarButton;
begin
for ControlTmp in Controls do
if ControlTmp.GetInterface(IfgToolbarButton, ToolBarButton) then
ToolBarButton.UpdateDisplayOptions(FDisplayOptions);
end;
procedure TfgCustomToolBar.Resize;
begin
inherited;
if AutoSize then
RefreshButtonsSize;
end;
procedure TfgCustomToolBar.SetAutoSize(const Value: Boolean);
begin
if AutoSize <> Value then
begin
FAutoSize := Value;
if AutoSize then
RefreshButtonsSize;
end;
end;
procedure TfgCustomToolBar.SetDisplayOptions(const Value: TfgToolBarDisplayOptions);
begin
FDisplayOptions := Value;
RefreshDisplayOptions;
end;
procedure TfgCustomToolBar.SetHorizontalGap(const Value: Single);
begin
FHorizontalGap := Value;
Realign;
end;
{ TfgToolbarButton }
procedure TfgToolBarButton.ApplyStyle;
begin
inherited;
if FToolBar <> nil then
UpdateDisplayOptions(FToolBar.DisplayOptions);
end;
function TfgToolBarButton.GetAdjustSizeValue: TSizeF;
begin
Result := inherited;
if ParentControl <> nil then
Result.Height := ParentControl.Height;
end;
function TfgToolBarButton.GetAdjustType: TAdjustType;
begin
Result := inherited;
if Result = TAdjustType.FixedWidth then
Result := TAdjustType.FixedSize;
if Result = TAdjustType.None then
Result := TAdjustType.FixedHeight;
end;
function TfgToolBarButton.GetDefaultSize: TSizeF;
begin
Result := TSizeF.Create(22, 24);
end;
function TfgToolBarButton.GetStyleObject: TFmxObject;
const
ResourceName = 'TfgToolbarStyle';
var
StyleContainer: TFmxObject;
begin
Result := nil;
if StyleLookup.IsEmpty and (FindResource(HInstance, PChar(ResourceName), RT_RCDATA) <> 0) then
begin
StyleContainer := TStyleStreaming.LoadFromResource(HInstance, ResourceName, RT_RCDATA);
Result := StyleContainer.FindStyleResource(GetDefaultStyleLookupName, True);
if Result <> nil then
Result.Parent := nil;
StyleContainer.Free;
end;
if Result = nil then
Result := inherited GetStyleObject;
end;
procedure TfgToolBarButton.Hide;
var
AlignRoot: IAlignRoot;
begin
inherited;
if Supports(ParentControl.ParentControl, IAlignRoot, AlignRoot) then
AlignRoot.Realign;
end;
procedure TfgToolBarButton.SetToolbar(const AToolbar: TfgCustomToolBar);
begin
FToolBar := AToolbar;
end;
procedure TfgToolBarButton.Show;
var
AlignRoot: IAlignRoot;
begin
inherited;
if Supports(ParentControl.ParentControl, IAlignRoot, AlignRoot) then
AlignRoot.Realign;
end;
procedure TfgToolBarButton.UpdateDisplayOptions(const ADisplayOptions: TfgToolBarDisplayOptions);
var
GlyphObject: TGlyph;
StyleObject: TControl;
begin
FDisplayOptions := ADisplayOptions;
GlyphObject := nil;
if FindStyleResource<TGlyph>('glyphstyle', GlyphObject) then
begin
GlyphObject.AutoHide := False;
GlyphObject.Stretch := False;
GlyphObject.Visible := TfgToolBarDisplayOption.Image in ADisplayOptions;
end;
if FindStyleResource<TControl>('icon', StyleObject) then
StyleObject.Visible := TfgToolBarDisplayOption.Image in ADisplayOptions;
if TextObject <> nil then
TextObject.Visible := TfgToolBarDisplayOption.Text in ADisplayOptions;
end;
procedure TfgToolBarButton.UpdateToPreferSize;
begin
if ParentControl <> nil then
Height := ParentControl.Height;
Width := Height;
end;
{ TfgToolBarSeparator }
function TfgToolBarSeparator.GetAdjustSizeValue: TSizeF;
begin
Result := inherited;
if ParentControl <> nil then
Result.Height := ParentControl.Height;
end;
function TfgToolBarSeparator.GetAdjustType: TAdjustType;
begin
Result := inherited;
if Result = TAdjustType.FixedWidth then
Result := TAdjustType.FixedSize;
if Result = TAdjustType.None then
Result := TAdjustType.FixedHeight;
end;
function TfgToolBarSeparator.GetDefaultSize: TSizeF;
begin
Result := TSizeF.Create(8, 22);
end;
function TfgToolBarSeparator.GetStyleObject: TFmxObject;
const
ResourceName = 'TfgToolbarStyle';
var
StyleContainer: TFmxObject;
begin
Result := nil;
if StyleLookup.IsEmpty and (FindResource(HInstance, PChar(ResourceName), RT_RCDATA) <> 0) then
begin
StyleContainer := TStyleStreaming.LoadFromResource(HInstance, ResourceName, RT_RCDATA);
Result := StyleContainer.FindStyleResource(GetDefaultStyleLookupName, True);
if Result <> nil then
Result.Parent := nil;
StyleContainer.Free;
end;
if Result = nil then
Result := inherited GetStyleObject;
end;
procedure TfgToolBarSeparator.Hide;
var
AlignRoot: IAlignRoot;
begin
inherited;
if Supports(ParentControl.ParentControl, IAlignRoot, AlignRoot) then
AlignRoot.Realign;
end;
procedure TfgToolBarSeparator.SetToolbar(const AToolbar: TfgCustomToolBar);
begin
end;
procedure TfgToolBarSeparator.Show;
var
AlignRoot: IAlignRoot;
begin
inherited;
if Supports(ParentControl.ParentControl, IAlignRoot, AlignRoot) then
AlignRoot.Realign;
end;
procedure TfgToolBarSeparator.UpdateDisplayOptions(const ADisplayOptions: TfgToolBarDisplayOptions);
begin
end;
procedure TfgToolBarSeparator.UpdateToPreferSize;
begin
if ParentControl <> nil then
Height := ParentControl.Height;
end;
{ TfgToolBaropupButton }
procedure TfgToolBarPopupButton.ApplyStyle;
var
Obj: TFmxObject;
begin
inherited ApplyStyle;
Obj := FindStyleResource('drop_down_btn');
if Obj is TControl then
FDropDownButton := TControl(Obj);
end;
procedure TfgToolBarPopupButton.DoDropDown;
var
PopupPos: TPointF;
begin
if HasPopupMenu and not FIsDropDown then
begin
PopupPos := LocalToScreen(TPointF.Create(0, Height));
FIsDropDown := True;
StartTriggerAnimation(Self, 'IsDropDown');
FPopupMenu.Popup(PopupPos.X, PopupPos.Y);
FIsDropDown := False;
StartTriggerAnimation(Self, 'IsDropDown');
end
else
FPopupMenu.CloseMenu;
end;
procedure TfgToolBarPopupButton.FreeStyle;
begin
FDropDownButton := nil;
inherited;
end;
function TfgToolBarPopupButton.GetDefaultSize: TSizeF;
begin
Result := TSizeF.Create(34, 22);
end;
function TfgToolBarPopupButton.HasPopupMenu: Boolean;
begin
Result := Assigned(FPopupMenu);
end;
procedure TfgToolBarPopupButton.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single);
var
P: TPointF;
begin
inherited MouseDown(Button, Shift, X, Y);
P := LocalToAbsolute(TPointF.Create(X, Y));
if FDropDownButton.PointInObject(P.X, P.Y) then
DoDropDown;
end;
procedure TfgToolBarPopupButton.UpdateToPreferSize;
begin
if csLoading in ComponentState then
begin
NeedStyleLookup;
ApplyStyleLookup;
end;
if ParentControl <> nil then
Height := ParentControl.Height;
if Assigned(FDropDownButton) then
Width := Height + FDropDownButton.Width
else
inherited UpdateToPreferSize;
end;
{ TfgToolBarComboBox }
procedure TfgToolBarComboBox.Hide;
var
AlignRoot: IAlignRoot;
begin
inherited;
if Supports(ParentControl, IAlignRoot, AlignRoot) then
AlignRoot.Realign;
end;
procedure TfgToolBarComboBox.SetToolbar(const AToolbar: TfgCustomToolBar);
begin
end;
procedure TfgToolBarComboBox.Show;
var
AlignRoot: IAlignRoot;
begin
inherited;
if Supports(ParentControl, IAlignRoot, AlignRoot) then
AlignRoot.Realign;
end;
procedure TfgToolBarComboBox.UpdateDisplayOptions(const ADisplayOptions: TfgToolBarDisplayOptions);
begin
end;
procedure TfgToolBarComboBox.UpdateToPreferSize;
begin
end;
{ TfgToolBarDivider }
function TfgToolBarDivider.GetDefaultSize: TSizeF;
begin
Result := TSizeF.Create(50, 22);
end;
procedure TfgToolBarDivider.SetToolbar(const AToolbar: TfgCustomToolBar);
begin
end;
procedure TfgToolBarDivider.UpdateDisplayOptions(const ADisplayOptions: TfgToolBarDisplayOptions);
begin
end;
procedure TfgToolBarDivider.UpdateToPreferSize;
begin
if ParentControl <> nil then
Height := ParentControl.Height;
end;
initialization
RegisterFmxClasses([TfgCustomToolBar, TfgToolBar, TfgToolBarButton, TfgToolBarSeparator, TfgToolBarPopupButton,
TfgToolBarComboBox, TfgToolBarDivider]);
end.
|
{-----------------------------------------------------------------------------
Author: Roman Fadeyev
Purpose: Специальный для экспорта котировок
History:
-----------------------------------------------------------------------------}
unit FC.StockData.Export.MT4Exporter;
{$I Compiler.inc}
interface
uses Windows,Forms,BaseUtils,SysUtils, Classes, Controls, Serialization,
StockChart.Definitions,FC.Definitions, StockChart.Obj;
type
TStockDataFileExporterMT4 = class(TStockInterfacedObjectVirtual,IStockDataFileExporter)
private
FCopyright : AnsiString;
public
function Filter: string;
function DefaultExt: string;
function Description: string;
procedure Run(const aDS: IStockDataSource; aStream: TStream);
constructor Create; override;
property Copyright : AnsiString read FCopyright write FCopyright;
end;
implementation
uses DateUtils, SystemService,
Application.Definitions,
FC.Factory,
FC.DataUtils,
MetaTrader.HistoryFileStruct,
FC.StockData.MT.StockDataSource;
{ TStockDataFileExporterMT4 }
constructor TStockDataFileExporterMT4.Create;
begin
inherited;
//FCopyright:=AnsiString('(C) '+Workspace.CompanyName);
FCopyright:='(C)opyright 2003, MetaQuotes Software Corp.';
end;
function TStockDataFileExporterMT4.DefaultExt: string;
begin
result:='.hst';
end;
function TStockDataFileExporterMT4.Description: string;
begin
result:='MT4 files (*.hst)';
end;
function TStockDataFileExporterMT4.Filter: string;
begin
result:='*.hst';
end;
procedure TStockDataFileExporterMT4.Run(const aDS: IStockDataSource; aStream: TStream);
var
i: integer;
aHeader: TMT4Header;
s: AnsiString;
aDate: time_t;
aV: TStockRealNumber;
aWriter: TWriter;
begin
TWaitCursor.SetUntilIdle;
//4 байта - версия
i:=400;
aStream.WriteBuffer(i,sizeof(i));
//Дальше заголовок
ZeroMemory(@aHeader,sizeof(aHeader));
s:=FCopyright;
StrLCopy(@aHeader.copyright[0],PAnsiChar(s),sizeof(aHeader.copyright));
s:=AnsiString(aDS.StockSymbol.Name);
StrLCopy(@aHeader.symbol[0],PAnsiChar(s),sizeof(aHeader.symbol));
aHeader.period:=aDS.StockSymbol.GetTimeIntervalValue;
aHeader.digits:=aDS.GetPricePrecision;
aStream.WriteBuffer(aHeader,sizeof(aHeader));
//данные
aWriter:=TWriter.Create(aStream,1024*1024); //использование врайтера дает оптимизацию за счет использования буфера
try
//данные
for I := 0 to aDS.RecordCount - 1 do
begin
aDate:=DateTimeToUnix(aDS.GetDataDateTime(i));
aWriter.Write(aDate,sizeof(aDate));
//Open
aV:=aDS.GetDataOpen(i);
aWriter.Write(aV,sizeof(aV));
//Low
aV:=aDS.GetDataLow(i);
aWriter.Write(aV,sizeof(aV));
//High
aV:=aDS.GetDataHigh(i);
aWriter.Write(aV,sizeof(aV));
//Close
aV:=aDS.GetDataClose(i);
aWriter.Write(aV,sizeof(aV));
//Volume
aV:=aDS.GetDataVolume(i);
aWriter.Write(aV,sizeof(aV));
end;
aWriter.FlushBuffer;
finally
aWriter.Free;
end;
end;
initialization
Factory.RegisterCreator(TObjectCreator_Coexistent.Create(TStockDataFileExporterMT4));
end.
|
unit testlinminunit;
interface
uses Math, Sysutils, Ap, linmin;
function TestLinMin(Silent : Boolean):Boolean;
function testlinminunit_test_silent():Boolean;
function testlinminunit_test():Boolean;
implementation
function TestLinMin(Silent : Boolean):Boolean;
var
WasErrors : Boolean;
begin
WasErrors := False;
if not Silent then
begin
Write(Format('TESTING LINMIN'#13#10'',[]));
if WasErrors then
begin
Write(Format('TEST FAILED'#13#10'',[]));
end
else
begin
Write(Format('TEST PASSED'#13#10'',[]));
end;
Write(Format(''#13#10''#13#10'',[]));
end;
Result := not WasErrors;
end;
(*************************************************************************
Silent unit test
*************************************************************************)
function testlinminunit_test_silent():Boolean;
begin
Result := TestLinMin(True);
end;
(*************************************************************************
Unit test
*************************************************************************)
function testlinminunit_test():Boolean;
begin
Result := TestLinMin(False);
end;
end. |
unit uBase;
interface
uses WinApi.ActiveX, SysUtils, uExceptions, uExceptionCodes;
type
TBaseObject = class(TInterfacedObject)
strict private
FGuid: TGuid;
function GetGuid: TGuid;
function GetGuidAsStr: string;
public
constructor Create;
property ID: TGuid read GetGuid;
property IDAsStr: string read GetGuidAsStr;
end;
implementation
{ TBaseObject }
var
NullGuid: TGuid;
constructor TBaseObject.Create;
begin
inherited Create;
FGuid := NullGuid;
end;
function TBaseObject.GetGuid: TGuid;
begin
if IsEqualGuid(FGuid, NullGuid) then
begin
if CreateGuid(FGuid) <> 0 then
RaiseFatalException(SYS_EXCEPT);
end;
Result := FGuid;
end;
function TBaseObject.GetGuidAsStr: string;
begin
Result := GUIDToString(ID)
end;
initialization
NullGuid := StringToGuid('{00000000-0000-0000-0000-000000000000}');
end.
|
unit uNexSignAC;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
spdCFeSatType, ActiveX,
spdCFeSat, IdContext, IdCustomHTTPServer, IdBaseComponent, IdComponent,
IdCustomTCPServer, IdHTTPServer, Vcl.StdCtrls, SyncObjs, Vcl.ExtCtrls;
type
TFrmPri = class(TForm)
H: TIdHTTPServer;
Panel1: TPanel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
edLoja: TEdit;
edCNPJ: TEdit;
edChave: TEdit;
Memo1: TMemo;
procedure FormCreate(Sender: TObject);
procedure HCommandGet(AContext: TIdContext;
ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);
procedure edLojaChange(Sender: TObject);
procedure edCNPJChange(Sender: TObject);
private
{ Private declarations }
procedure GerarChave;
public
function Sign(aCNPJ: String): String;
{ Public declarations }
end;
var
FrmPri: TFrmPri;
CS : TCriticalSection;
implementation
{$R *.dfm}
uses ncDebug, md5;
{ TForm7 }
function SoDig(S: String): String;
var I: Integer;
begin
Result := '';
for I := 1 to Length(S) do
if S[I] in ['0'..'9'] then Result := Result + S[I];
end;
function Chave(aLoja, aCNPJ: string): string;
begin
aLoja := Trim(aLoja);
aCNPJ := SoDig(aCNPJ);
Result := getmd5str('piLKHerASD17IUywefd7kdsfTkjhasfdkxzxxx778213zxcnbv'+LowerCase(aLoja)+aCNPJ); // do not localize
end;
procedure TFrmPri.edCNPJChange(Sender: TObject);
begin
GerarChave;
end;
procedure TFrmPri.edLojaChange(Sender: TObject);
begin
GerarChave;
end;
procedure TFrmPri.FormCreate(Sender: TObject);
begin
H.Active := True;
end;
procedure TFrmPri.GerarChave;
begin
if (Trim(edLoja.Text)='') or (Trim(edCNPJ.Text)='') then begin
edChave.Text := '';
Exit;
end;
edChave.Text := Chave(edLoja.Text, edCNPJ.Text);
if Length(SoDig(edCNPJ.Text))=14 then
Memo1.Lines.Text := Sign(SoDig(edCNPJ.Text)) else
Memo1.Lines.Text := '';
end;
procedure TFrmPri.HCommandGet(AContext: TIdContext;
ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);
var
S, sCNPJ, sChave, sDebug, sLoja : String;
I: Integer;
sl : TStrings;
Erro : Integer;
begin
if ARequestInfo.Params.Count=0 then Exit;
try
sCNPJ := SoDig(ARequestInfo.Params.Values['cnpj']);
sChave := Trim(ARequestInfo.Params.Values['chave']);
sLoja := Trim(ARequestInfo.Params.Values['loja']);
if sChave <> Chave(sLoja, sCNPJ) then begin
AResponseInfo.ContentText := 'erro=chave inválida';
Exit;
end;
S := Sign(sCNPJ);
AResponseInfo.ContentText := S;
sDebug := '';
with aRequestInfo do
for I := 0 to Params.Count - 1 do begin
sDebug := sDebug + ', ';
sDebug := sDebug + Params.Names[I] + '=' + Params.ValueFromIndex[I];
end;
DebugMsgEsp('IP: '+ARequestInfo.RemoteIP+sDebug+', Resposta='+S, False, True);
except
on E: Exception do DebugMsgEsp('Exception: ' + E.Message, False, True);
end;
end;
function TFrmPri.Sign(aCNPJ: String): String;
var sat: TspdCFeSat;
begin
CS.Enter;
try
Result := '';
CoInitialize(nil);
try
sat := TspdCFeSat.Create(nil);
try
// sat.NomeCertificado.Text := 'CN=NEXTAR TECNOLOGIA DE SOFTWARE LTDA ME, OU=ID - 8256664, O=ICP-Brasil, C=BR, S=, L=, E=joao@nextar.com.br';
sat.NomeCertificado.Text := 'CN=NEXTAR TECNOLOGIA DE SOFTWARE LTDA ME:04580911000196, OU=Autenticado por AR Fecomercio SC, O=ICP-Brasil, C=BR, S=SC, L=Florianopolis, E=';
Result := sat.GerarSignAC(aCNPJ, '04580911000196');
finally
sat.Free;
end;
except
on E: Exception do begin
DebugMsgEsp('Erro: '+E.Message, False, True);
Result := 'erro='+E.Message;
end;
end;
CoUninitialize;
finally
CS.Leave;
end;
end;
initialization
CS := TCriticalSection.Create;
finalization
CS.Free;
end.
|
unit u_ReaderThread;
{$MODE objfpc}{$H+}
interface
uses
Windows,Classes, FileUtil, LCLIntf, u_DevAPI, u_Func, SysUtils,SyncObjs;
type
TReaderCMD=(RC_None=0,RC_1D_Car=1,RC_UL_Car=2,RC_IC_Driver=3,RC_1D_DriverTargetPlace=4);
{ TReaderThread }
TReaderThread=Class(TThread)
private
FReaderCMD:TReaderCMD;
FSEvent:TSimpleEvent;
procedure CheckSvrConn;
procedure ClearDriver;
procedure ClearDriverTargetPlace;
procedure QueryDriver;
procedure ClearCar;
procedure QueryCar;
function ReaderBarcode1D(var B1DValue:String):Boolean;
function ReaderRF(Const TagTypeFlag:TTagType;var RFValue:String):Boolean;
procedure SetDriverTargetPlace;
procedure SleepEv(Const Timeout : Cardinal);
public
constructor Create(CreateSuspended: Boolean);
destructor Destroy; override;
procedure Execute; override;
procedure SetEvent();
property ReaderCMD: TReaderCMD read FReaderCMD write FReaderCMD default RC_None;
end;
implementation
{ TReaderThread }
constructor TReaderThread.Create(CreateSuspended: Boolean);
begin
FreeOnTerminate := False;
inherited Create(CreateSuspended);
FSEvent:=TSimpleEvent.Create;
end;
destructor TReaderThread.Destroy;
begin
FSEvent.Free;
inherited Destroy;
end;
procedure TReaderThread.SleepEv(Const Timeout : Cardinal);
begin
//Sleep(Timeout);
FSEvent.WaitFor(Timeout);
FSEvent.ResetEvent;
end;
procedure TReaderThread.SetEvent();
begin
FSEvent.SetEvent();
end;
procedure TReaderThread.Execute;
var
Value:String;
T1:DWord;
FullCardNum:Cardinal;
begin
T1:=GetTickCount();
while (not Terminated) do
begin
if FReaderCMD<>RC_None then
begin
Value:='';
case FReaderCMD of
RC_1D_Car: begin
if ReaderBarcode1D(Value) then
begin
U_Car.VIN:=Value;
Synchronize(@QueryCar);
end
else
begin
Synchronize(@ClearCar);
end;
end;
RC_UL_Car: begin
if ReaderRF(ultra_light,Value) then
begin
U_Car.RFID:=Value;
Synchronize(@QueryCar);
end
else
begin
Synchronize(@ClearCar);
end;
end;
RC_IC_Driver :begin
if ReaderRF(Mifare_One_S50,Value) then
begin
if GetFullCardNum(Value,FullCardNum) then
begin
U_Driver.FullCardNum:=InttoStr(FullCardNum);
Synchronize(@QueryDriver);
end
else
begin
Synchronize(@ClearDriver);
end;
end
else
begin
Synchronize(@ClearDriver);
end;
end;
RC_1D_DriverTargetPlace:begin
if ReaderBarcode1D(Value) then
begin
U_Driver.TargetPlace:=Value;
Synchronize(@SetDriverTargetPlace);
end
else
begin
Synchronize(@ClearDriverTargetPlace);
end;
end;
end;
FReaderCMD:=RC_None;
T1:=GetTickCount();
end;
//空闲检测网络连接
if DWord(GetTickCount()-T1)>(HBI*1000) then
begin
//防止休眠 VK_NONAME =$FC
SystemIdleTimerReset();
//SHIdleTimerReset();
keybd_event($FC , 0, KEYEVENTF_SILENT, 0);
keybd_event($FC , 0, KEYEVENTF_KEYUP or KEYEVENTF_SILENT, 0);
//心跳
Synchronize(@CheckSvrConn);
T1:=GetTickCount();
end;
SleepEv(300);
end;
end;
function TReaderThread.ReaderRF(Const TagTypeFlag:TTagType;var RFValue:String):Boolean;
var
TagType:TTagType;
UIDStr: string;
K: Integer;
Pre_ReaderCMD:TReaderCMD;
begin
Result:=False;
//保存最新命令,如果有新命令插入就中止
Pre_ReaderCMD:=FReaderCMD;
K := 0;
while ((not Terminated) and (FReaderCMD=Pre_ReaderCMD)) do
begin
if not Init_RF_ISO14443A_Mode() then
begin
Exit;
end;
try
UIDStr:='';
TagType:=None;
if getRFID(TagType, UIDStr) then
if TagType = TagTypeFlag then
begin
RFValue:= UIDStr;
PlayWav(WT_OK);
Result:=True;
break;
end;
inc(k);
finally
Free_RF_ISO14443A_Mode();
end;
if k > 50 then break;
end;
end;
function TReaderThread.ReaderBarcode1D(var B1DValue:String):Boolean;
Const
BufLen=255;
var
Buf: PByte;
rt, K: Integer;
Pre_ReaderCMD:TReaderCMD;
begin
Result:=False;
//保存最新命令,如果有新命令插入就中止
Pre_ReaderCMD:=FReaderCMD;
Buf := GetMem(BufLen);
try
Barcode1D_init();
K := 0;
while ((not Terminated) and (FReaderCMD=Pre_ReaderCMD)) do
begin
FillChar(Buf^, BufLen, 0);
rt := Barcode1D_scan(Buf);
if rt > 0 then
begin
B1DValue:= StrPas(PChar(Buf));
PlayWav(WT_OK);
Result:=True;
break;
end;
inc(k);
if k > 30 then break;
end;
finally
FreeMem(Buf, BufLen);
Barcode1D_free();
end;
end;
procedure TReaderThread.CheckSvrConn();
begin
_CheckSvrConn();
end;
procedure TReaderThread.ClearDriver;
begin
_ClearDriver();
end;
procedure TReaderThread.QueryDriver;
begin
_QueryDriver();
end;
procedure TReaderThread.ClearCar;
begin
_ClearCar();
end;
procedure TReaderThread.QueryCar;
begin
_QueryCar();
end;
procedure TReaderThread.SetDriverTargetPlace();
begin
_SetDriverTargetPlace();
end;
procedure TReaderThread.ClearDriverTargetPlace();
begin
_ClearDriverTargetPlace();
end;
end.
|
UNIT RandUnit;
INTERFACE
FUNCTION IntRand: integer;
PROCEDURE InitRandSeed(s: integer);
FUNCTION RangeRand(n: integer): integer;
FUNCTION RealRand: real;
IMPLEMENTATION
const
M = 32768; (* 2^x *)
var
x: longint;
FUNCTION RangeRand(n: INTEGER): INTEGER;
VAR
z, k: INTEGER;
BEGIN //RangeRand2
k := m - (m mod n);
REPEAT
z := IntRand;
UNTIL z < k;
RangeRand := z MOD n;
END; //RangeRand2
FUNCTION RealRand: real;
BEGIN (* RealRand *)
RealRand := IntRand / M;
END; (* RealRand *)
PROCEDURE InitRandSeed(s: integer);
BEGIN (* InitRandSeed *)
x := s;
END; (* InitRandSeed *)
FUNCTION IntRand: integer;
const
A = 3421; (* numb + 21, < m *)
C = 1; (* 0 <= c < m *)
BEGIN (* IntRand *)
x := (A * x + C) MOD M;
IntRand := x;
END; (* IntRand *)
BEGIN (* RandUnit *)
x := 0;
END. (* RandUnit *) |
unit HamUtils;
interface
uses
Windows, Messages, SysUtils, Math, DateUtils;
function DateTimeToMJD(DT: TDateTime): double;
function Kepler(U0, E: double): Double;
function UtToSiderealTime(Ut: TDateTime; Lon: double): TDateTime;
//procedure Wait(t: integer);
const
Pi2: double = 2 * pi; // 2 × PI
implementation
{$R *.dfm}
/////////////////////////////////////////////////////////////////////////////////////////////
//
// Delphi の TDateTime 値を準(修正)ユリウス日(Modeified Julian Day;MJD))に変換する。
//
// Delphi の TDateTime 値の整数部は西暦 1899 年 12 月 30 日からの経過日数を示します。
// 小数部はその日の経過時間(24 時間制)です。
//
// 準ユリアス日は、1858年11月17日0時を起算開始日とした通算日
// 準ユリアス日 = ユリアス日 − 2400000.5 の関係がある
//
// 通常 1899年12月30日 以前を計算対象としなければ、特にMJDに変換する必要ない
// 1899年12月30日以前は、TDateTimeを調べなければ分からない (多分 大丈夫)
//
/////////////////////////////////////////////////////////////////////////////////////////////
function DateTimeToMJD(DT: TDateTime): double;
var
Y, M, D: word;
MJD: double;
begin
DecodeDate(DT, Y, M, D);
if M <= 2 then
begin
M := M + 12;
Y := Y - 1;
end;
MJD := int(365.25 * Y) + int(y / 400) - int(y / 100) + int(30.59 * (m - 2)) + d - 678912
+ Frac(DT);
result := MJD;
end;
/////////////////////////////////////////////////////////////////////////////////////////////
//
// ケプラーの方程式で離心近点角(U)を求める
//
/////////////////////////////////////////////////////////////////////////////////////////////
function Kepler(U0, E: double): Double;
var
U, UD: double;
begin
U := U0;
Repeat
UD := (U0 - U + E * sin(U)) / (1- E * cos(U));
U := U + UD
Until IsZero(UD);
result := U;
end;
/////////////////////////////////////////////////////////////////////////////////////////////
//
// Utからグリニッジ平均恒星時に変換する。 (P27,151)
//
/////////////////////////////////////////////////////////////////////////////////////////////
function UtToSiderealTime(Ut: TDateTime; Lon: double): TDateTime;
var
Y,M,D: Integer;
Lt, K, TU, Tg0: Double;
begin
// 1899/12/31 12:00 殻の経過日数(K)を求める
// この式を適用できるのは、1900/3/1〜2100/2/28の期間のみ
Y := YearOf(Ut) - 1900;
M := MonthOf(Ut);
D := DayOf(Ut);
if M < 3 then
begin
Y := Y - 1;
M := M + 2;
end;
K := 365 * Y + 30 * M + D - 33.5 + Int(0.6 * (M + 1)) + Int(Y / 4);
// 1899/12/31 12:00 殻の経過日数(K)を,36525日を1とした単位(TU)を求める
TU := K / 36525;
// UT 00:00のグリニッジ恒星時を求める(24時間以上は、最後に切り捨てている)
Tg0 := (23925.836 + 8640184.542 * TU + 0.0929 * TU * TU) / 86400;
// 求める時刻のグリニッジ恒星時を求める
// 結果は、日付形式であるので、少数以下の桁のみ有効
Lon := Lon / Pi2;
Lt := Frac(Ut);
result := frac(Tg0 + Lon + Lt + 0.00273791 * Lt);
end;
{
procedure Wait(t: integer);
var
endtime : TDateTime; //終了時間
begin
endtime := Now + t / 86400 / 1000;
// while (Now < endtime) do ;
while (Now < endtime) do
Application.ProcessMessages;
end;
}
end.
|
unit g_game_objects;
interface
uses
g_class_gameobject, u_math, g_bonuses;
type
TObjectsEngine = class (TGameObject)
Objects : Array of TGameObject;
Rendered : Integer;
procedure Move; override;
procedure Render; override;
procedure AddObject(Obj : TGameObject);
procedure DeleteObject(Index : Integer);
procedure CollisionObjects;
function GetNearest(Pos : TGamePos; Index : Integer; Collision : Boolean = true) : TGameObject;
function GetNearestCoin : TGamePos;
procedure Clear;
private
end;
var
ObjectsEngine : TObjectsEngine;
implementation
uses Math, g_rockets, g_player;
{ TObjectsEngine }
procedure TObjectsEngine.AddObject(Obj: TGameObject);
begin
SetLength(Objects, Length(Objects)+1);
Obj.Index := High(Objects);
Obj.Parent := Self;
Objects[High(Objects)] := Obj;
end;
procedure TObjectsEngine.Clear;
var
i:Integer;
begin
for i := 0 to High(Objects) do
begin
Objects[i].Free;
end;
SetLength(Objects, 0);
end;
procedure TObjectsEngine.CollisionObjects;
var
i,j:Integer;
begin
for i := 0 to High(Objects) do
begin
for j := i+1 to High(Objects)-1 do
begin
if Objects[i].Collision and Objects[j].Collision then
begin
if Distance(Objects[i].Pos, Objects[j].Pos) <= (Objects[i].Radius + Objects[j].Radius) then
begin
Objects[i].DoCollision(MakeNormalVector(Objects[i].Pos.x - Objects[j].Pos.x, 0, Objects[i].Pos.z - Objects[j].Pos.z), Objects[j]);
Objects[j].DoCollision(MakeNormalVector(Objects[j].Pos.x - Objects[i].Pos.x, 0, Objects[j].Pos.z - Objects[i].Pos.z), Objects[i]);
end;
end;
end;
end;
end;
procedure TObjectsEngine.DeleteObject(Index: Integer);
begin
Objects[Index] := Objects[High(Objects)];
SetLength(Objects, Length(Objects)-1);
end;
function TObjectsEngine.GetNearest(Pos: TGamePos; Index: Integer;
Collision: Boolean): TGameObject;
var
i : Integer;
mind : Single;
begin
Result := nil;
mind := 1000000;
for i := 0 to High(Objects) do
begin
if i <> Index then
begin
if (Objects[i].Collision) and not (Objects[i] is TSimpleRocket) then
begin
if Distance(Pos, Objects[i].Pos) < mind then
Result := Objects[i];
end;
end;
end;
end;
function TObjectsEngine.GetNearestCoin: TGamePos;
var
i:Integer;
mindis, dis : Single;
begin
mindis := 10000000;
for i := 0 to High(Objects) do
begin
if Objects[i] is TCoin then
begin
dis := Distance(Player.Pos, Objects[i].Pos);
if dis < mindis then
begin
Result := Objects[i].Pos;
mindis := dis;
end;
end;
end;
end;
procedure TObjectsEngine.Move;
var
i:Integer;
begin
inherited;
for i := 0 to High(Objects) do
if not Objects[i].Freeze then
Objects[i].Move;
for i := High(Objects) downto 0 do
begin
if (Objects[i].Health <= 0) and not (Objects[i].Unkill) then
begin
Objects[i].Death;
Objects[i].Free;
DeleteObject(i);
end;
end;
end;
procedure TObjectsEngine.Render;
var
i:Integer;
begin
inherited;
Rendered := 0;
for i := 0 to High(Objects) do
begin
//if Distance(Player.Pos, Objects[i].Pos) < 30 then
//begin
if not Objects[i].Hide then
begin
Objects[i].Render;
inc(Rendered);
end;
//end;
end;
end;
initialization
ObjectsEngine := TObjectsEngine.Create;
end.
|
program Sample;
function Func(i :Integer) :Integer;
begin
WriteLn(i);
Func := 'abc';
end;
var res : Integer;
begin
res := Func(1);
WriteLn('res: ', res);
end.
|
unit TimeAndDate;
interface
uses
System.SysUtils,
WebSite,
HtmlDoc;
type
ETimeAndDateWebSite = class(Exception);
ITimeAndDateWebSite = interface
['{F32284C8-1B95-40D8-AEA0-76057587E0CD}']
function IsDaylightSaving(const Area: string; Year: Word): Boolean;
function GetDaylightStart(const Area: string; Year: Word): TDateTime;
function GetDaylightEnd(const Area: string; Year: Word): TDateTime;
end;
TTimeAndDate = class(TInterfacedObject, ITimeAndDateWebSite)
private
fs: TFormatSettings;
WebSite: IWebSite; // CtorDI
function GetUrl(Area: string; Year: Word): string;
function HasDaylightSaving(const Text: string): Boolean;
function ExtractDateTime(const Text, FindText: string): TDateTime;
procedure RaiseInvalidStructure;
function MonthToInt(const MonthStr: string): Integer;
public
constructor Create(AWebSite: IWebSite);
function IsDaylightSaving(const Area: string; Year: Word): Boolean;
function GetDaylightStart(const Area: string; Year: Word): TDateTime;
function GetDaylightEnd(const Area: string; Year: Word): TDateTime;
end;
function BuildTimeAndDateWebSite: ITimeAndDateWebSite;
implementation
uses
System.Types, System.StrUtils,
Utils;
constructor TTimeAndDate.Create(AWebSite: IWebSite);
begin
inherited Create;
fs := TFormatSettings.Create('en');
WebSite := AWebSite;
end;
function TTimeAndDate.IsDaylightSaving(const Area: string; Year: Word): Boolean;
const
SDateAndTimeElemID = 'qfacts';
var
Doc: IHTMLDoc;
Elem: IHTMLElem;
begin
Result := False;
Doc := BuildHTMLDoc(WebSite.GetContent(GetUrl(Area, Year)));
Elem := Doc.getElemById(SDateAndTimeElemID);
if Assigned(Elem) then
Result := HasDaylightSaving(Elem.InnerText)
else
RaiseInvalidStructure;
end;
function TTimeAndDate.GetDaylightStart(const Area: string; Year: Word): TDateTime;
var
Doc: IHTMLDoc;
begin
Doc := BuildHTMLDoc(WebSite.GetContent(GetUrl(Area, Year)));
Result := ExtractDateTime(Doc.Body.InnerText, 'Daylight Saving Time Start')
end;
function TTimeAndDate.GetDaylightEnd(const Area: string; Year: Word): TDateTime;
var
Doc: IHTMLDoc;
begin
Doc := BuildHTMLDoc(WebSite.GetContent(GetUrl(Area, Year)));
Result := ExtractDateTime(Doc.Body.InnerText, 'Daylight Saving Time End')
end;
function TTimeAndDate.GetUrl(Area: string; Year: Word): string;
const
SHost = 'https://www.timeanddate.com';
SDoc = 'time/change';
begin
Result := Format('%s/%s/%s?year=%d', [SHost, SDoc, Area, Year]);
end;
function TTimeAndDate.HasDaylightSaving(const Text: string): Boolean;
begin
Result := ContainsText(Text, 'Start DST:');
end;
function TTimeAndDate.ExtractDateTime(const Text, FindText: string): TDateTime;
function Convert(const Text: string): TDateTime;
var
Tok: TStringDynArray;
Day, Month, Year: Integer;
Time: string;
begin
Tok := SplitString(ReplaceStr(Text, ',', ''), ' ');
if Length(Tok) < 5 then
RaiseInvalidStructure;
Day := StrToInt(Tok[1]);
Month := MonthToInt(Tok[2]);
Year := StrToInt(Tok[3]);
Time := Tok[4];
Result := EncodeDate(Year, Month, Day);
Result := StrToDateTime(DateToStr(Result) + ' ' + Time);
end;
var
ArrIter: IStrArrayIterator;
Line: string;
begin
Result := 0;
ArrIter := BuildStrArrayIteratorNonEmptyLines(SplitString(Text, sLineBreak));
while ArrIter.Next(Line) do begin
if ContainsText(Line, FindText) then begin
ArrIter.Next(Line); // skip 'When local standard/daylight time was about to reach'
ArrIter.Next(Line); // fetch line with date time
Exit(Convert(Line));
end;
end;
end;
function TTimeAndDate.MonthToInt(const MonthStr: string): Integer;
var
Month: Integer;
begin
Result := -1;
for Month := low(fs.LongMonthNames) to high(fs.LongMonthNames) do begin
if SameText(fs.LongMonthNames[Month], MonthStr) then
Exit(Month);
end;
RaiseInvalidStructure;
end;
procedure TTimeAndDate.RaiseInvalidStructure;
begin
raise ETimeAndDateWebSite.Create('Invalid HTML Page structure');
end;
function BuildTimeAndDateWebSite: ITimeAndDateWebSite;
begin
Result := TTimeAndDate.Create(BuildWebSiteWithCache);
end;
end.
|
unit UControlExcepciones;
interface
Uses
SysUtils, Forms, Windows, Classes, DB, {ZAbstractConnection,} ZDataset,
ZConnection, Variants;
Type
TmyProcedure = procedure of object;
ITCException = class(Exception)
protected
procedure CargarMensajes(LMensajes: TStringList);
public
Codigo: Integer;
constructor CreateByCode(Code: Integer; Valores: Array of Variant);
end;
EInteliException = class(ITCException);
EInteliWarning = class(ITCException);
EInteliAbort = class(ITCException);
const
ccCatalog = 'CATALOGO';
ccSelect = 'SELECT';
ccUpdate = 'UPDATE';
var
CEConnection: TZConnection;
CECancelarNativo: Boolean;
CECancelarProceso: Boolean;
procedure AsignarConexion(var BaseDatos: TZConnection);
procedure LevantarExcepcion(Excepcion: Exception; const ProcedimientoAntes: TmyProcedure = nil; const ProcedimientoDespues: TmyProcedure = nil);
function AsignarSentencia(var DataSet: TZQuery; NombreSentencia: string; TipoSentencia: string): Boolean; overload;
function AsignarSentencia(var DataSet: TZReadOnlyQuery; NombreSentencia: string; TipoSentencia: string): Boolean; overload;
function GetSentence(NombreSentencia: string; TipoSentencia: string): string;
function CargarDatosFiltrados(var DataSet: TZQuery; Variables: string; Valores: array of Variant): Boolean; overload;
function CargarDatosFiltrados(var DataSet: TZReadOnlyQuery; Variables: string; Valores: array of Variant): Boolean; overload;
implementation
Uses
Dialogs, Messages, ZAbstractRODataset, Controls;
type
TObjetoError = class
Codigo: Integer;
Titulo: string;
Mensaje: string;
Tipo: TMsgDlgType;
end;
TTipoErr = class
Titulo: string;
end;
const
TipoError: array[0..26, 0..1] of string = (('EAbort', 'Error catastrófico'), {: Finaliza la secuencia de eventos sin mostrar el mensaje de error.}
('EAccessViolation', 'Error de acceso a memoria iválido'), {: Comprueba errores de acceso a memoria inválidos.}
('EBitsError', 'No se puede acceder a elementos de arreglos boleanos'), {: Previene intentos para acceder a arrays de elementos booleanos.}
('EComponentError', 'No se puede registrar o renombrar el componente'), {: Nos informa de un intento inválido de registrar o renombrar un componente.}
('EConvertError', 'No es posible converte la cadena'), {: Muestra un error al convertir objetos o cadenas de texto string.}
('EDatabaseError', 'Error de acceso a base de datos'), {: Especifica un error de acceso a bases de datos.}
('EDBEditError', 'Error al introducir datos incompatibles con una máscara de texto'), {: Error al introducir datos incompatibles con una máscara de texto.}
('EDivByZero', 'Error de división por cero'), {: Errores de división por cero.}
('EExternalException', 'No se reconoce el tipo de excepción'), {: Significa que no reconoce el tipo de excepción (viene de fuera).}
('EIntOutError', 'Error de entrada/salida a archivo'), {: Representa un error de entrada/salida a archivos.}
('EIntOverflow', 'El valor ha desbordado el el máximo para este tipo de dato'), {: Especifica que se ha provocado un desbordamiento de un tipo de dato.}
('EInvalidCast', 'Error de conversión de tipos'), {: Comprueba un error de conversión de tipos.}
('EInvalidGraphic', 'Tipo de gráfico no es reconocido'), {: Indica un intento de trabajar con gráficos que tienen un formato desconocido.}
('EInvalidOp', 'El componente no permite esa operación '), {: Ocurre cuando se ha intentado realizar una operación inválida sobre un componente.}
('EInvalidOperation', 'El componente no permite esa operación'), {: Ocurre cuando se ha intentado realizar una operación inválida sobre un componente.}
('EInvalidPointer', 'Los apuntadores de memoria no permiten esa operación'), {: Se produce en operaciones con punteros inválidos.}
('EMenuError', 'Error en opción del menú'), {: Controla todos los errores relacionados con componentes de menú.}
('EOleCtrlError', 'Error en control Activex'), {: Detecta problemas con controles ActiveX.}
('EOleError', 'Error de automatización de objetos OLE'), {: Especifica errores de automatización de objetos OLE.}
('EPrinterError', 'Error de impresión'), {: Errores al imprimir.}
('ERangeError', 'Número entero demasiado grande para la propieda del objeto'), {: Indica si se intenta asignar un número entero demasiado grande a una propiedad.}
('ERegistryExcepcion', 'Error de registro de windows'), {: Controla los errores en el registro.}
('EZeroDivide', 'División entre cero'), {: Controla los errores de división para valores reales.}
('EInteliException', 'Excepción de Inteli-Code'), {: Excepcion generica propia de nuestros sistemas }
('EInteliWarning', 'Aviso de Inteli-Code'), {: Mensajes de aviso propios de nuestros sistemas }
('EInteliAbort', 'Error catastrófico'), {: Error catastrófico propio de nuestros sistemas }
('EZSQLException', 'Error en sentencia SQL')); {: Error en sentencia SQL }
ListaTiposMensaje = 'mtWarning, mtError, mtInformation, mtConfirmation, mtCustom';
var
ArregloTipoExcepcion: TStringList;
ListaMensajes: TStringList;
UValores: Array of Variant;
procedure ITCException.CargarMensajes(LMensajes: TStringList);
var
Query: TZReadOnlyQuery;
ObjetoError: TObjetoError;
Lista: TStringList;
begin
// Verificar si existe la conexión a la base de datos
if not Assigned(CEConnection) then
// Si no se ha establecido la conexión, informar al usuario y terminar este proceso
raise EInteliWarning.Create('No se pueden generar los mensajes de error de la base de datos debido a que esta no ha sido especificada.' + #10 + #10 + 'Informe de esto al administrador del sistema.');
// Si la conexion se ha realizado, verificar que esté activa
if Not CEConnection.Connected then
// Si no se ha conectado, tratar de conectarla
CEConnection.Connect;
Try
try
Query := TZReadOnlyQuery.Create(Nil);
Query.Connection := CEConnection;
Query.SQL.Text := 'select * from nuc_errores';
Query.Open;
Try
Lista := TStringList.Create;
Lista.CommaText := ListaTiposMensaje;
ListaMensajes := TStringList.Create;
ListaMensajes.Clear;
while Not Query.Eof do
begin
ObjetoError := TObjetoError.Create;
ObjetoError.Codigo := Query.FieldByName('iCodigo').AsInteger;
ObjetoError.Titulo := Query.FieldByName('sDescUsuario').AsString;
ObjetoError.Mensaje := Query.FieldByName('sDescTecnico').AsString;
case Lista.IndexOf(Query.FieldByName('MsgType').AsString) of
0: ObjetoError.Tipo := mtWarning;
1: ObjetoError.Tipo := mtError;
2: ObjetoError.Tipo := mtInformation;
3: ObjetoError.Tipo := mtConfirmation
else
ObjetoError.Tipo := mtCustom;
end;
ListaMensajes.AddObject(Query.FieldByName('iCodigo').AsString, ObjetoError);
Query.Next;
end;
Finally
Query.Close;
End;
except
on e:Exception do
LevantarExcepcion(e);
end;
Finally
Query.Free;
Query := nil;
End;
end;
constructor ITCException.CreateByCode(Code: Integer; Valores: Array of Variant);
var
i: Integer;
begin
Codigo := Code;
SetLength(UValores, High(Valores) +1);
for i := 0 to High(Valores) do
UValores[i] := Valores[i];
Try
// Verificar si ya existen los datos de los mensaje en memoria
if Not Assigned(ListaMensajes) then
CargarMensajes(ListaMensajes);
except
on e:Exception do
LevantarExcepcion(e);
End;
end;
procedure AsignarConexion(var BaseDatos: TZConnection);
begin
// Asignar la conexión y verificar si está activa
try
CEConnection := BaseDatos;
CEConnection.Connect;
except
on e:Exception do
LevantarExcepcion(EInteliAbort.Create('La base de datos no está asignada.'));
end;
end;
procedure CargaListaTiposExcepcion(var ListaT: TStringList);
var
i: Integer;
oTipoErr: TTipoErr;
begin
ListaT := TStringList.Create;
ListaT.Clear;
for i := low(TipoError) to high(TipoError) do
begin
oTipoErr := TTipoErr.Create;
oTipoErr.Titulo := TipoError[i,1];
ListaT.AddObject(TipoError[i,0], oTipoErr);
end;
end;
procedure LevantarExcepcion(Excepcion: Exception; const ProcedimientoAntes: TmyProcedure = nil; const ProcedimientoDespues: TmyProcedure = nil);
var
i,
iFin,
iNumero,
Indice,
IdxError,
NumValores: Integer;
Titulo,
SubTitulo,
Cadena,
NewCadena: string;
TipoMensaje: TMsgDlgType;
begin
//ShowMessage(Excepcion.ClassName);
Titulo := '';
IdxError := -1;
SubTitulo := 'Se ha alcanzado el siguiente error:' + #10 + #10;
if (Excepcion.Message = '') and (Assigned(ListaMensajes)) then
begin
SubTitulo := '';
IdxError := ListaMensajes.IndexOf(IntToStr(ITCException(Excepcion).Codigo));
if IdxError >= 0 then
begin
Titulo := TObjetoError(ListaMensajes.Objects[IdxError]).Titulo;
TipoMensaje := TObjetoError(ListaMensajes.Objects[IdxError]).Tipo;
Cadena := TObjetoError(ListaMensajes.Objects[IdxError]).Mensaje;
NewCadena := '';
// Recorrer el mensaje para intercambiar los parametros
i := 1;
while i <= Length(Cadena) do
begin
if Copy(Cadena, i, 2) = '<%' then
if (Cadena[i +3] = '>') or (Cadena[i +4] = '>') then
begin
iNumero := -1;
if Cadena[i +3] = '>' then
begin
iFin := i +4;
Try
iNumero := StrToInt(Copy(Cadena, i +2, 1));
Except
iNumero := -1;
End;
end
else
begin
iFin := i + 5;
Try
iNumero := StrToInt(Copy(Cadena, i +2, 2));
Except
iNumero := -1;
End;
end;
Dec(iNumero);
if (iNumero >= 0) and (iNumero <= High(UValores)) then
begin
//IndiceMensaje := ;
NewCadena := NewCadena + UValores[iNumero];
end;
i := iFin;
end;
NewCadena := NewCadena + Copy(Cadena, i, 1);
Inc(i);
end;
Excepcion.Message := NewCadena;
end
else
begin
Titulo := 'Error de acceso a los mensajes del sistema';
TipoMensaje := mtError;
Excepcion.Message := 'No se ha podido encontrar el mensaje de error No. ' + IntToStr(ITCException(Excepcion).Codigo);
end;
end;
{ // Localizar el error que se está buscando
Indice := ListaMensajes.IndexOf(IntToStr(Code));
if Indice < 0 then
raise Exception.Create('Eduardo Rangel Vallejo');
}
// Establecer a false las variables de cancelación de proceso, si el programador
// descide modificar este valor por true dentro del procedimiento antes del
// comportamiento nativo la unidad cancelará la continuación
CECancelarNativo := False; // No cancelar el proceso nativo de la excepcion
CECancelarProceso := False; // No cancelar el proceso completo de la excepción
Try
// Verificar si existe un procedimiento anterior que deba ser ejecutado
if Assigned(ProcedimientoAntes) then
ProcedimientoAntes;
if (Not CECancelarNativo) and (Not CECancelarProceso) then
begin
if Not Assigned(ArregloTipoExcepcion) then
CargaListaTiposExcepcion(ArregloTipoExcepcion);
Indice := ArregloTipoExcepcion.IndexOf(Excepcion.ClassName);
if Indice in [0, 25] then
begin
if Titulo = '' then
begin
Titulo := TTipoErr(ArregloTipoExcepcion.Objects[Indice]).Titulo;
SubTitulo := 'El sistema se cerrará debido a un error catastrófico, informe de lo siguiente al administrador del sistema:' + #10 + #10;
TipoMensaje := mtError;
end;
TaskMessageDlg(Titulo, SubTitulo + Excepcion.Message, TipoMensaje, [mbOK], 0);
// Localizar la ventana que se está ejecutando
PostMessage(Application.ActiveFormHandle, WM_CLOSE, 0, 0);
end
else
begin
if Indice = -1 then
Titulo := 'Error inesperado'
else
Titulo := TTipoErr(ArregloTipoExcepcion.Objects[Indice]).Titulo;
if IdxError = -1 then
case Indice of
-1: TipoMensaje := mtError;
1: TipoMensaje := mtError;
13: TipoMensaje := mtWarning;
24: TipoMensaje := mtInformation;
26: TipoMensaje := mtError;
end;
TaskMessageDlg(Titulo, SubTitulo + Excepcion.Message, TipoMensaje, [mbOK], 0);
end;
end;
if not CECancelarProceso then
begin
// Verificar si existe un procedimiento anterior que deba ser ejecutado
if Assigned(ProcedimientoDespues) then
ProcedimientoDespues;
end;
Finally
CECancelarProceso := False;
CECancelarNativo := False;
ITCException(Excepcion).Codigo := -1;
End;
end;
function AsignarSentencia(var DataSet: TZQuery; NombreSentencia: string; TipoSentencia: string): Boolean;
begin
Result := AsignarSentencia(TZReadOnlyQuery(DataSet), NombreSentencia, TipoSentencia);
end;
function AsignarSentencia(var DataSet: TZReadOnlyQuery; NombreSentencia: string; TipoSentencia: string): Boolean;
var
i: Integer;
Cadena: string;
begin
Result := True;
try
if Not Assigned(DataSet) then
DataSet := TZReadOnlyQuery.Create(Nil);
if DataSet.Connection = Nil then
DataSet.Connection := CEConnection;
if DataSet.Connection.Connected and Not DataSet.Connection.Ping then
DataSet.Connection.Reconnect;
if Copy(NombreSentencia, 1, 3) = 'SP_' then
DataSet.SQL.Text := 'CALL ' + Copy(NombreSentencia, 4, Length(NombreSentencia))
else
begin
DataSet.SQL.Text := GetSentence(NombreSentencia, TipoSentencia);
// Poner todos los parámetros a -1 para acceder a todo el catálogo por default
for i := 0 to DataSet.Params.Count -1 do
begin
Cadena := DataSet.Params.Items[i].Name;
DataSet.ParamByName(Cadena).asString := '-1';
end;
{if TipoSentencia = stUpdate then
begin
end;}
end;
Result := True;
finally
//LocQuery.Free;
end;
end;
function GetSentence(NombreSentencia: string; TipoSentencia: string): string;
var
Query: TZReadOnlyQuery;
CadPaso, Negritas, Resultado: string;
LocCursor: TCursor;
begin
Resultado := '';
// Localizar la sentencia en base a los parámetros indicados
try
try
LocCursor := Screen.Cursor;
try
Screen.Cursor := crSQLWait;
Query := TZReadOnlyQuery.Create(Nil);
Query.Connection := CEConnection;
if Query.Connection.Connected and Not Query.Connection.Ping then
Query.Connection.Reconnect;
Query.SQL.Text := 'Select sSentencia from nuc_sentencias where sTablaPrimaria = :Tabla and sTipo = :Tipo';
Query.ParamByName('Tabla').AsString := NombreSentencia;
Query.ParamByName('Tipo').AsString := TipoSentencia;
Query.Open;
if Query.RecordCount = 0 then
Resultado := 'SELECT * FROM ' + NombreSentencia
else
Resultado := Query.FieldByName('sSentencia').AsString;
Query.Close;
finally
Screen.Cursor := LocCursor;
Query.Free;
end;
Except
Resultado := 'SELECT * FROM ' + NombreSentencia;
end;
finally
Result := Resultado;
end;
end;
function CargarDatosFiltrados(var DataSet: TZQuery; Variables: string; Valores: array of Variant): Boolean; overload;
begin
CargarDatosFiltrados(TZReadOnlyQuery(DataSet), Variables, Valores);
end;
function CargarDatosFiltrados(var DataSet: TZReadOnlyQuery; Variables: string; Valores: array of Variant): Boolean; overload;
var
Lista: TStringList;
i: Integer;
Cadena: string;
pValor: string;
begin
Try
// Obtener un conjunto de elementos de los nombres de las variables
Lista := TStringList.Create;
Lista.CommaText := Variables;
if Lista.Count <> High(Valores) +1 then
raise Exception.Create('Hay un error');
// Verificar si algunos de los valores pasados tienen separados ","
for i := low(Valores) to high(Valores) do
begin
Cadena := Valores[i];
if Pos(',', Cadena) <> 0 then
begin
Cadena := StringReplace(Cadena, ',', '|', [rfReplaceAll, rfIgnoreCase]);
Valores[i] := Cadena;
end;
end;
Cadena := '';
for i := 0 to High(Valores) do
DataSet.ParamByName(Lista[i]).Value := Valores[i];
Finally
Lista.Free;
End;
end;
end.
|
unit mGMV_DateRange;
interface
type
TMDateTime = class(TObject)
private
FDateTime: TDateTime;
function getWDate: TDateTime;
function getWTime: TDateTime;
procedure setWDate(aDateTime:TDateTime);
procedure setWTime(aDateTime:TDateTime);
procedure setWDateTime(aDateTime:TDateTime);
public
DateTimeFormat: String;
DateFormat: String;
TimeFormat: String;
constructor Create;
function getMDate: Double;
function getMTime: Double;
function getMDateTime: Double;
procedure setMDate(aDateTime:Double);
procedure setMTime(aDateTime:Double);
procedure setMDateTime(aDateTime:Double);
function getSWDate: String;
function getSWTime: String;
function getSWDateTime: String;
function getSMDate: String;
function getSMTime: String;
function getSMDateTime: String;
procedure setSMDateTime(aDateTime:String);
procedure setsWDateTime(aDateTime:String);
published
property WDate:TDateTime read getWDate write setWDate;
property WTime:TDateTime read getWTime write setWTime;
property WDateTime:TDateTime read FDateTime write setWDateTime;
end;
implementation
uses u_Common, Sysutils;
// function FMDateTimeToWindowsDateTime( FMDateTime: Double ): TDateTime;
// function WindowsDateTimeToFMDateTime( WinDate: TDateTime ): Double;
constructor TMDateTime.Create;
begin
inherited;
DateTimeFormat := 'mm/dd/yy hh:mm:ss';
DateFormat := 'mm/dd/yy';
TimeFormat := 'hh:mm:ss';
end;
function TMDateTime.getWDate:TDateTime;
begin
Result := trunc(FDateTime);
end;
function TMDateTIme.getWTime:TDateTime;
begin
Result := frac(FDateTime);
end;
procedure TMDateTime.setWDate(aDateTime:TDateTime);
begin
FDateTime := trunc(aDateTime) + frac(FDateTime);
end;
procedure TMDateTime.setWTime(aDateTime:TDateTime);
begin
FDateTime := trunc(FDateTime) + frac(aDateTime);
end;
procedure TMDateTime.setWDateTime(aDateTime:TDateTime);
begin
FDateTime := aDateTime;
end;
///////////////////////////////////////////////////////////
function TMDateTime.getMDateTime:Double;
begin
Result := WindowsDateTimeToFMDateTime(FDateTime);
end;
function TMDateTime.getMDate:Double;
begin
Result := trunc(WindowsDateTimeToFMDateTime(FDateTime));
end;
function TMDateTIme.getMTime:Double;
begin
Result := frac(WindowsDateTimeToFMDateTime(FDateTime));
end;
procedure TMDateTime.setMDate(aDateTime:Double);
begin
FDateTime := trunc(FMDateTimeToWindowsDateTime(aDateTime)) + frac(FDateTime);
end;
procedure TMDateTime.setMTime(aDateTime:Double);
begin
FDateTime := trunc(FDateTime) + frac(FMDateTimeToWindowsDateTime(aDateTime));
end;
procedure TMDateTime.setMDateTime(aDateTime:Double);
begin
FDateTime := FMDateTimeToWindowsDateTime(aDateTime);
end;
//////////////////////////////////////////////////////////////////
function TMDateTime.getSWDate:String;
begin
Result := formatDateTime(DateFormat,FDateTime);
end;
function TMDateTIme.getSWTime:String;
begin
Result := formatDateTime(TimeFormat,FDateTime);
end;
function TMDateTime.getSWDateTime:String;
begin
Result := formatDateTime(DateTimeFOrmat,FDateTime);
end;
////////////////////////////////////////////////////////////////////
function TMDateTime.getSMDate:String;
var
d: Double;
begin
try
d :=WindowsDateTimeToFMDateTime(FDateTime);
result := FloatToStr(trunc(d));
except
Result := '';
end;
end;
function TMDateTIme.getSMTime:String;
var
d: Double;
begin
try
d :=WindowsDateTimeToFMDateTime(FDateTime);
result := FloatToStr(frac(d));
except
Result := '';
end;
end;
function TMDateTime.getSMDateTime:String;
begin
try
result := FloatToStr(WindowsDateTimeToFMDateTime(FDateTime));
except
Result := '';
end;
end;
procedure TMDateTime.setSMDateTime(aDateTime:String);
begin
try
FDateTime := FMDateTimeToWindowsDateTime(StrToFloat(aDateTime));
except
end;
end;
procedure TMDateTime.setSWDateTime(aDateTime:String);
begin
try
FDateTime := StrToDateTime(aDateTime);
except
end;
end;
end.
|
unit account_s;
{This file was generated on 11 Aug 2000 20:15:27 GMT by version 03.03.03.C1.06}
{of the Inprise VisiBroker idl2pas CORBA IDL compiler. }
{Please do not edit the contents of this file. You should instead edit and }
{recompile the original IDL which was located in the file account.idl. }
{Delphi Pascal unit : account_s }
{derived from IDL module : default }
interface
uses
CORBA,
account_i,
account_c;
type
TAccountSkeleton = class;
TAccountSkeleton = class(CORBA.TCorbaObject, account_i.Account)
private
FImplementation : Account;
public
constructor Create(const InstanceName: string; const Impl: Account);
destructor Destroy; override;
function GetImplementation : Account;
function balance ( const mySeq : account_i.IntSeq): Single;
published
procedure _balance(const _Input: CORBA.InputStream; _Cookie: Pointer);
end;
implementation
constructor TAccountSkeleton.Create(const InstanceName : string; const Impl : account_i.Account);
begin
inherited;
inherited CreateSkeleton(InstanceName, 'Account', 'IDL:Account:1.0');
FImplementation := Impl;
end;
destructor TAccountSkeleton.Destroy;
begin
FImplementation := nil;
inherited;
end;
function TAccountSkeleton.GetImplementation : account_i.Account;
begin
result := FImplementation as account_i.Account;
end;
function TAccountSkeleton.balance ( const mySeq : account_i.IntSeq): Single;
begin
Result := FImplementation.balance( mySeq);
end;
procedure TAccountSkeleton._balance(const _Input: CORBA.InputStream; _Cookie: Pointer);
var
_Output : CORBA.OutputStream;
_mySeq : account_i.IntSeq;
_Result : Single;
begin
_mySeq := account_c.TIntSeqHelper.Read(_Input);
_Result := balance( _mySeq);
GetReplyBuffer(_Cookie, _Output);
_Output.WriteFloat(_Result);
end;
initialization
end. |
{-----------------------------------------------------------------------------
Unit Name: uThreads
Author: n0mad
Version: 1.1.6.63
Creation: 12.10.2002
Purpose: Working with threads
History:
-----------------------------------------------------------------------------}
unit uThreads;
interface
{$I bugger.inc}
uses
Classes, Comctrls, Bugger;
type
TGenericThreadProc = procedure(PointerToData: Pointer; var Terminated:
boolean);
TGenericThread = class(TThread)
private
FProcToInit: TGenericThreadProc;
FProcToCall: TGenericThreadProc;
FProcToFinal: TGenericThreadProc;
FPointerToData: Pointer;
FForceTerminated: boolean;
FRunning: boolean;
function GetRuning: Boolean;
protected
procedure Execute; override; // Main thread execution
procedure ProcInit;
procedure ProcExecute;
procedure ProcFinal;
public
constructor Create(PriorityLevel: TThreadPriority; ProcToInit, ProcToCall,
ProcToFinal: TGenericThreadProc; PointerToData: Pointer);
destructor Destroy; override;
property Runing: Boolean read GetRuning;
end;
implementation
uses
Windows;
const
UnitName: string = 'uThreads';
constructor TGenericThread.Create(PriorityLevel: TThreadPriority; ProcToInit,
ProcToCall, ProcToFinal: TGenericThreadProc; PointerToData: Pointer);
begin
inherited Create(true); // Create thread suspended
FRunning := true;
Priority := TThreadPriority(PriorityLevel); // Set Priority Level
FreeOnTerminate := true; // Thread Free Itself when terminated
FProcToInit := ProcToInit; // Set reference
FProcToCall := ProcToCall; // Set reference
FProcToFinal := ProcToFinal; // Set reference
FForceTerminated := false;
FPointerToData := PointerToData;
if @ProcToCall <> nil then
Suspended := false // Continue the thread
else
FRunning := false;
end;
destructor TGenericThread.Destroy;
begin
inherited Destroy;
end;
procedure TGenericThread.Execute; // Main execution for thread
begin
FRunning := true;
try
if @FProcToInit <> nil then
Synchronize(ProcInit);
while not (Terminated or FForceTerminated) do
begin
if @FProcToCall <> nil then
Synchronize(ProcExecute);
// if Terminated is true, this loop exits prematurely so the thread will terminate
end;
if @FProcToFinal <> nil then
Synchronize(ProcFinal);
finally
// Bad-bad-bad code
while FRunning do
begin
FRunning := false;
SleepEx(0, false);
end;
end;
end;
procedure TGenericThread.ProcInit;
begin
if @FProcToInit <> nil then
FProcToInit(FPointerToData, FForceTerminated);
end;
procedure TGenericThread.ProcExecute;
begin
if @FProcToCall <> nil then
FProcToCall(FPointerToData, FForceTerminated);
end;
procedure TGenericThread.ProcFinal;
begin
if @FProcToFinal <> nil then
FProcToFinal(FPointerToData, FForceTerminated);
end;
function TGenericThread.GetRuning: Boolean;
begin
Result := FRunning{ or FForceTerminated};
end;
{$IFDEF DEBUG_Module_Start_Finish}
initialization
DEBUGMess(0, UnitName + '.Init');
{$ENDIF}
{$IFDEF DEBUG_Module_Start_Finish}
finalization
DEBUGMess(0, UnitName + '.Final');
{$ENDIF}
end.
|
{******************************************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{ Header conversion of pcre.h }
{ }
{ Translator: Embarcadero Technologies, Inc. }
{ }
{ Based on original translations by: }
{ }
{ Florent Ouchet }
{ Mario R. Carro }
{ Robert Rossmair }
{ Peter Thornqvist }
{ Jan Goyvaerts }
{ }
{******************************************************************************}
{******************************************************************************}
{ }
{ PCRE LICENCE }
{ ------------ }
{ }
{ PCRE is a library of functions to support regular expressions whose syntax }
{ and semantics are as close as possible to those of the Perl 5 language. }
{ }
{ Release 8 of PCRE is distributed under the terms of the "BSD" licence, as }
{ specified below. The documentation for PCRE, supplied in the "doc" }
{ directory, is distributed under the same terms as the software itself. }
{ }
{ The basic library functions are written in C and are freestanding. Also }
{ included in the distribution is a set of C++ wrapper functions, and a }
{ just-in-time compiler that can be used to optimize pattern matching. These }
{ are both optional features that can be omitted when the library is built. }
{ }
{ }
{ THE BASIC LIBRARY FUNCTIONS }
{ --------------------------- }
{ }
{ Written by: Philip Hazel }
{ Email local part: ph10 }
{ Email domain: cam.ac.uk }
{ }
{ University of Cambridge Computing Service, }
{ Cambridge, England. }
{ }
{ Copyright (c) 1997-2014 University of Cambridge }
{ All rights reserved. }
{ }
{ }
{ PCRE JUST-IN-TIME COMPILATION SUPPORT }
{ ------------------------------------- }
{ }
{ Written by: Zoltan Herczeg }
{ Email local part: hzmester }
{ Emain domain: freemail.hu }
{ }
{ Copyright(c) 2010-2014 Zoltan Herczeg }
{ All rights reserved. }
{ }
{ }
{ STACK-LESS JUST-IN-TIME COMPILER }
{ -------------------------------- }
{ }
{ Written by: Zoltan Herczeg }
{ Email local part: hzmester }
{ Emain domain: freemail.hu }
{ }
{ Copyright(c) 2009-2014 Zoltan Herczeg }
{ All rights reserved. }
{ }
{ }
{ THE C++ WRAPPER FUNCTIONS }
{ ------------------------- }
{ }
{ Contributed by: Google Inc. }
{ }
{ Copyright (c) 2007-2012, Google Inc. }
{ All rights reserved. }
{ }
{ }
{ THE "BSD" LICENCE }
{ ----------------- }
{ }
{ Redistribution and use in source and binary forms, with or without }
{ modification, are permitted provided that the following conditions are met: }
{ }
{ * Redistributions of source code must retain the above copyright notice, }
{ this list of conditions and the following disclaimer. }
{ }
{ * Redistributions in binary form must reproduce the above copyright }
{ notice, this list of conditions and the following disclaimer in the }
{ documentation and/or other materials provided with the distribution. }
{ }
{ * Neither the name of the University of Cambridge nor the name of Google }
{ Inc. nor the names of their contributors may be used to endorse or }
{ promote products derived from this software without specific prior }
{ written permission. }
{ }
{ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" }
{ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE }
{ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE }
{ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE }
{ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR }
{ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF }
{ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS }
{ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN }
{ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) }
{ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE }
{ POSSIBILITY OF SUCH DAMAGE. }
{ }
{ End }
{ }
{******************************************************************************}
unit System.RegularExpressionsAPI;
interface
(*************************************************
* Perl-Compatible Regular Expressions *
*************************************************)
{$IFDEF MSWINDOWS}{$DEFINE PCRE16}{$ENDIF}
{$WEAKPACKAGEUNIT ON}
const
MAX_PATTERN_LENGTH = $10003;
MAX_QUANTIFY_REPEAT = $10000;
MAX_CAPTURE_COUNT = $FFFF;
MAX_NESTING_DEPTH = 200;
const
(* Options *)
PCRE_CASELESS = $00000001;
PCRE_MULTILINE = $00000002;
PCRE_DOTALL = $00000004;
PCRE_EXTENDED = $00000008;
PCRE_ANCHORED = $00000010;
PCRE_DOLLAR_ENDONLY = $00000020;
PCRE_EXTRA = $00000040;
PCRE_NOTBOL = $00000080;
PCRE_NOTEOL = $00000100;
PCRE_UNGREEDY = $00000200;
PCRE_NOTEMPTY = $00000400;
PCRE_UTF8 = $00000800;
PCRE_UTF16 = $00000800;
PCRE_UTF32 = $00000800;
PCRE_NO_AUTO_CAPTURE = $00001000;
PCRE_NO_UTF8_CHECK = $00002000;
PCRE_NO_UTF16_CHECK = $00002000;
PCRE_NO_UTF32_CHECK = $00002000;
PCRE_AUTO_CALLOUT = $00004000;
PCRE_PARTIAL = $00008000;
PCRE_NEVER_UTF = $00010000;
PCRE_DFA_SHORTEST = $00010000;
PCRE_NO_AUTO_POSSESS = $00020000;
PCRE_DFA_RESTART = $00020000;
PCRE_FIRSTLINE = $00040000;
PCRE_DUPNAMES = $00080000;
PCRE_NEWLINE_CR = $00100000;
PCRE_NEWLINE_LF = $00200000;
PCRE_NEWLINE_CRLF = $00300000;
PCRE_NEWLINE_ANY = $00400000;
PCRE_NEWLINE_ANYCRLF = $00500000;
PCRE_BSR_ANYCRLF = $00800000;
PCRE_BSR_UNICODE = $01000000;
PCRE_JAVASCRIPT_COMPAT = $02000000;
PCRE_NO_START_OPTIMIZE = $04000000;
PCRE_NO_START_OPTIMISE = $04000000;
PCRE_PARTIAL_HARD = $08000000;
PCRE_NOTEMPTY_ATSTART = $10000000;
PCRE_UCP = $20000000;
(* Exec-time and get-time error codes *)
PCRE_ERROR_NOMATCH = -1;
PCRE_ERROR_NULL = -2;
PCRE_ERROR_BADOPTION = -3;
PCRE_ERROR_BADMAGIC = -4;
PCRE_ERROR_UNKNOWN_NODE = -5;
PCRE_ERROR_NOMEMORY = -6;
PCRE_ERROR_NOSUBSTRING = -7;
PCRE_ERROR_MATCHLIMIT = -8;
PCRE_ERROR_CALLOUT = -9; (* Never used by PCRE itself *)
PCRE_ERROR_BADUTF8 = -10;
PCRE_ERROR_BADUTF16 = -10;
PCRE_ERROR_BADUTF32 = -10;
PCRE_ERROR_BADUTF8_OFFSET = -11;
PCRE_ERROR_BADUTF16_OFFSET = -11;
PCRE_ERROR_PARTIAL = -12;
PCRE_ERROR_BADPARTIAL = -13;
PCRE_ERROR_INTERNAL = -14;
PCRE_ERROR_BADCOUNT = -15;
PCRE_ERROR_DFA_UITEM = -16;
PCRE_ERROR_DFA_UCOND = -17;
PCRE_ERROR_DFA_UMLIMIT = -18;
PCRE_ERROR_DFA_WSSIZE = -19;
PCRE_ERROR_DFA_RECURSE = -20;
PCRE_ERROR_RECURSIONLIMIT = -21;
PCRE_ERROR_NULLWSLIMIT = -22; (* No longer actually used *)
PCRE_ERROR_BADNEWLINE = -23;
PCRE_ERROR_BADOFFSET = -24;
PCRE_ERROR_SHORTUTF8 = -25;
PCRE_ERROR_SHORTUTF16 = -25; (*Same for 8/16 *)
PCRE_ERROR_RECURSELOOP = -26;
PCRE_ERROR_JIT_STACKLIMIT = -27;
PCRE_ERROR_BADMODE = -28;
PCRE_ERROR_BADENDIANNESS = -29;
PCRE_ERROR_DFA_BADRESTART = -30;
PCRE_ERROR_JIT_BADOPTION = -31;
PCRE_ERROR_BADLENGTH = -32;
PCRE_ERROR_UNSET = -33;
(* Specific error codes for UTF-8 validity checks *)
PCRE_UTF8_ERR0 = 0;
PCRE_UTF8_ERR1 = 1;
PCRE_UTF8_ERR2 = 2;
PCRE_UTF8_ERR3 = 3;
PCRE_UTF8_ERR4 = 4;
PCRE_UTF8_ERR5 = 5;
PCRE_UTF8_ERR6 = 6;
PCRE_UTF8_ERR7 = 7;
PCRE_UTF8_ERR8 = 8;
PCRE_UTF8_ERR9 = 9;
PCRE_UTF8_ERR10 = 10;
PCRE_UTF8_ERR11 = 11;
PCRE_UTF8_ERR12 = 12;
PCRE_UTF8_ERR13 = 13;
PCRE_UTF8_ERR14 = 14;
PCRE_UTF8_ERR15 = 15;
PCRE_UTF8_ERR16 = 16;
PCRE_UTF8_ERR17 = 17;
PCRE_UTF8_ERR18 = 18;
PCRE_UTF8_ERR19 = 19;
PCRE_UTF8_ERR20 = 20;
PCRE_UTF8_ERR21 = 21;
PCRE_UTF8_ERR22 = 22; (* Unused (was non-character) *)
(* Specific error codes for UTF-16 validity checks *)
PCRE_UTF16_ERR0 = 0;
PCRE_UTF16_ERR1 = 1;
PCRE_UTF16_ERR2 = 2;
PCRE_UTF16_ERR3 = 3;
PCRE_UTF16_ERR4 = 4; (* Unused (was non-character) *)
(* Specific error codes for UTF-32 validity checks *)
PCRE_UTF32_ERR0 = 0;
PCRE_UTF32_ERR1 = 1;
PCRE_UTF32_ERR2 = 2; (* Unused (was non-character) *)
PCRE_UTF32_ERR3 = 3;
(* Request types for pcre_fullinfo() *)
PCRE_INFO_OPTIONS = 0;
PCRE_INFO_SIZE = 1;
PCRE_INFO_CAPTURECOUNT = 2;
PCRE_INFO_BACKREFMAX = 3;
PCRE_INFO_FIRSTCHAR = 4;
PCRE_INFO_FIRSTTABLE = 5;
PCRE_INFO_LASTLITERAL = 6;
PCRE_INFO_NAMEENTRYSIZE = 7;
PCRE_INFO_NAMECOUNT = 8;
PCRE_INFO_NAMETABLE = 9;
PCRE_INFO_STUDYSIZE = 10;
PCRE_INFO_DEFAULT_TABLES = 11;
PCRE_INFO_OKPARTIAL = 12;
PCRE_INFO_JCHANGED = 13;
PCRE_INFO_HASCRORLF = 14;
PCRE_INFO_MINLENGTH = 15;
PCRE_INFO_JIT = 16;
PCRE_INFO_JITSIZE = 17;
PCRE_INFO_MAXLOOKBEHIND = 18;
PCRE_INFO_FIRSTCHARACTER = 19;
PCRE_INFO_FIRSTCHARACTERFLAGS = 20;
PCRE_INFO_REQUIREDCHAR = 21;
PCRE_INFO_REQUIREDCHARFLAGS = 22;
PCRE_INFO_MATCHLIMIT = 23;
PCRE_INFO_RECURSIONLIMIT = 24;
PCRE_INFO_MATCH_EMPTY = 25;
(* Request types for pcre_config(). Do not re-arrange, in order to remain
compatible. *)
PCRE_CONFIG_UTF8 = 0;
PCRE_CONFIG_NEWLINE = 1;
PCRE_CONFIG_LINK_SIZE = 2;
PCRE_CONFIG_POSIX_MALLOC_THRESHOLD = 3;
PCRE_CONFIG_MATCH_LIMIT = 4;
PCRE_CONFIG_STACKRECURSE = 5;
PCRE_CONFIG_UNICODE_PROPERTIES = 6;
PCRE_CONFIG_MATCH_LIMIT_RECURSION = 7;
PCRE_CONFIG_BSR = 8;
PCRE_CONFIG_JIT = 9;
PCRE_CONFIG_UTF16 = 10;
PCRE_CONFIG_JITTARGET = 11;
PCRE_CONFIG_UTF32 = 12;
PCRE_CONFIG_PARENS_LIMIT = 13;
(* Request types for pcre_study(). Do not re-arrange, in order to remain
compatible. *)
PCRE_STUDY_JIT_COMPILE = $0001;
PCRE_STUDY_JIT_PARTIAL_SOFT_COMPILE = $0002;
PCRE_STUDY_JIT_PARTIAL_HARD_COMPILE = $0004;
PCRE_STUDY_EXTRA_NEEDED = $0008;
(* Bit flags for the pcre[16|32]_extra structure. Do not re-arrange or redefine
these bits, just add new ones on the end, in order to remain compatible. *)
PCRE_EXTRA_STUDY_DATA = $0001;
PCRE_EXTRA_MATCH_LIMIT = $0002;
PCRE_EXTRA_CALLOUT_DATA = $0004;
PCRE_EXTRA_TABLES = $0008;
PCRE_EXTRA_MATCH_LIMIT_RECURSION = $0010;
PCRE_EXTRA_MARK = $0020;
PCRE_EXTRA_EXECUTABLE_JIT = $0040;
type
(* Types *)
PInteger = ^Integer;
{$EXTERNALSYM PInteger} // NOTE: Should use Sysytem's PInteger
PPMarshaledAString = ^PMarshaledAString;
{$NODEFINE PPMarshaledAString}
{$IFDEF PCRE16}
PCRE_STR = MarshaledString;
{$ELSE}
PCRE_STR = MarshaledAString;
{$ENDIF}
PCRE_SPTR = ^PCRE_STR;
PCRE_SPTR_PTR = ^PCRE_SPTR;
real_pcre = packed record
{magic_number: Longword;
size: Integer;}
end;
TPCRE = real_pcre;
PPCRE = ^TPCRE;
real_pcre_jit_stack = packed record
end; (* declaration; the definition is private *)
TRealPCREJitStack = real_pcre_jit_stack;
PRealPCREJitStack = ^TRealPCREJitStack;
pcre_jit_stack = real_pcre_jit_stack;
TPCREJitStack = pcre_jit_stack;
PPCREJitStack = ^TPCREJitStack;
real_pcre_extra = packed record
{options: MarshaledAString;
start_bits: array [0..31] of AnsiChar;}
flags: Cardinal; (* Bits for which fields are set *)
study_data: Pointer; (* Opaque data from pcre_study() *)
match_limit: Cardinal; (* Maximum number of calls to match() *)
callout_data: Pointer; (* Data passed back in callouts *)
tables: PCRE_STR; (* Pointer to character tables *)
match_limit_recursion: Cardinal; (* Max recursive calls to match() *)
mark: PCRE_STR; (* For passing back a mark pointer *)
executable_jit: Pointer; (* Contains a pointer to a compiled jit code *)
end;
TPCREExtra = real_pcre_extra;
PPCREExtra = ^TPCREExtra;
pcre_callout_block = packed record
version: Integer; (* Identifies version of block *)
(* ------------------------ Version 0 ------------------------------- *)
callout_number: Integer; (* Number compiled into pattern *)
offset_vector: PInteger; (* The offset vector *)
subject: PCRE_STR; (* The subject being matched *)
subject_length: Integer; (* The length of the subject *)
start_match: Integer; (* Offset to start of this match attempt *)
current_position: Integer; (* Where we currently are in the subject *)
capture_top: Integer; (* Max current capture *)
capture_last: Integer; (* Most recently closed capture *)
callout_data: Pointer; (* Data passed in with the call *)
(* ------------------- Added for Version 1 -------------------------- *)
pattern_position: Integer; (* Offset to next item in the pattern *)
next_item_length: Integer; (* Length of next item in the pattern *)
(* ------------------- Added for Version 2 -------------------------- *)
mark: PCRE_STR; (* Pointer to current mark or NULL *)
(* ------------------------------------------------------------------ *)
end;
pcre_malloc_callback = function(Size: NativeUInt): Pointer; cdecl;
pcre_free_callback = procedure(P: Pointer); cdecl;
pcre_stack_malloc_callback = function(Size: NativeUInt): Pointer; cdecl;
pcre_stack_free_callback = procedure(P: Pointer); cdecl;
pcre_callout_callback = function(var callout_block: pcre_callout_block): Integer; cdecl;
pcre_stack_guard_callback = function : Integer; cdecl;
procedure SetPCREMallocCallback(const Value: pcre_malloc_callback);
function GetPCREMallocCallback: pcre_malloc_callback;
function CallPCREMalloc(Size: NativeUInt): Pointer;
procedure SetPCREFreeCallback(const Value: pcre_free_callback);
function GetPCREFreeCallback: pcre_free_callback;
procedure CallPCREFree(P: Pointer);
procedure SetPCREStackMallocCallback(const Value: pcre_stack_malloc_callback);
function GetPCREStackMallocCallback: pcre_stack_malloc_callback;
function CallPCREStackMalloc(Size: NativeUInt): Pointer;
procedure SetPCREStackFreeCallback(const Value: pcre_stack_free_callback);
function GetPCREStackFreeCallback: pcre_stack_free_callback;
procedure CallPCREStackFree(P: Pointer);
procedure SetPCRECalloutCallback(const Value: pcre_callout_callback);
function GetPCRECalloutCallback: pcre_callout_callback;
function CallPCRECallout(var callout_block: pcre_callout_block): Integer;
const
{$IFDEF MACOS}
{$IF defined(CPUARM)} //IOS devices
PU = '';
LIBPCRE = 'libpcre.a';
{$DEFINE STATIC_LIB}
{$ELSE}
{$IFDEF IOS} //IOS Simulator
PCRELib = 'libpcre.dylib';
{$ELSE} //OSX
PCRELib = '/usr/lib/libpcre.dylib';
{$ENDIF}
{$DEFINE DYNAMIC_LIB}
{$ENDIF}
{$ENDIF MACOS}
{$IFDEF LINUX}
PU = '';
{$IFDEF PIC}
LIBPCRE = 'libpcre_PIC.a';
{$ELSE PIC}
LIBPCRE = 'libpcre.a';
{$ENDIF PIC}
{$DEFINE STATIC_LIB}
{$ENDIF LINUX}
{$IFDEF MSWINDOWS}
{$IFDEF CPUX86}
PU = '_';
{$ELSE}
PU = '';
{$ENDIF}
{$ENDIF}
{$IFDEF ANDROID}
PU = '';
LIBPCRE = 'libpcre.a';
{$DEFINE STATIC_LIB}
{$ENDIF ANDROID}
{$IFDEF PCRE16}
PCREname = 'pcre16_';
{$ELSE}
PCREname = 'pcre_';
{$ENDIF}
{$EXTERNALSYM PCREname}
(* Functions *)
{$IF Defined(MSWINDOWS) or Defined(STATIC_LIB)}
function pcre_compile(const pattern: PCRE_STR; options: Integer;
const errptr: PMarshaledAString; erroffset: PInteger; const tableptr: MarshaledAString): PPCRE;
cdecl; external {$IFDEF STATIC_LIB}LIBPCRE{$ENDIF} name PU + PCREname + 'compile';
function pcre_compile2(const pattern: PCRE_STR; options: Integer;
const errorcodeptr: PInteger; const errorptr: PMarshaledAString; erroroffset: PInteger;
const tables: MarshaledAString): PPCRE;
cdecl; external {$IFDEF STATIC_LIB}LIBPCRE{$ENDIF} name PU + PCREname + 'compile2';
function pcre_config(what: Integer; where: Pointer): Integer;
cdecl; external {$IFDEF STATIC_LIB}LIBPCRE{$ENDIF} name PU + PCREname + 'config';
function pcre_copy_named_substring(const code: PPCRE; const subject: PCRE_STR;
ovector: PInteger; stringcount: Integer; const stringname: PCRE_STR;
buffer: PCRE_STR; size: Integer): Integer;
cdecl; external {$IFDEF STATIC_LIB}LIBPCRE{$ENDIF} name PU + PCREname + 'copy_named_substring';
function pcre_copy_substring(const subject: PCRE_STR; ovector: PInteger;
stringcount, stringnumber: Integer; buffer: PCRE_STR; buffersize: Integer): Integer;
cdecl; external {$IFDEF STATIC_LIB}LIBPCRE{$ENDIF} name PU + PCREname + 'copy_substring';
function pcre_dfa_exec(const argument_re: PPCRE; const extra_data: PPCREExtra;
const subject: PCRE_STR; length: Integer; start_offset: Integer;
options: Integer; offsets: PInteger; offsetcount: Integer; workspace: PInteger;
wscount: Integer): Integer;
cdecl; external {$IFDEF STATIC_LIB}LIBPCRE{$ENDIF} name PU + PCREname + 'dfa_exec';
function pcre_exec(const code: PPCRE; const extra: PPCREExtra; const subject: PCRE_STR;
length, startoffset, options: Integer; ovector: PInteger; ovecsize: Integer): Integer;
cdecl; external {$IFDEF STATIC_LIB}LIBPCRE{$ENDIF} name PU + PCREname + 'exec';
procedure pcre_free_substring(stringptr: PCRE_STR);
cdecl; external {$IFDEF STATIC_LIB}LIBPCRE{$ENDIF} name PU + PCREname + 'free_substring';
procedure pcre_free_substring_list(stringlistptr: PCRE_SPTR);
cdecl; external {$IFDEF STATIC_LIB}LIBPCRE{$ENDIF} name PU + PCREname + 'free_substring_list';
function pcre_fullinfo(const code: PPCRE; const extra: PPCREExtra;
what: Integer; where: Pointer): Integer;
cdecl; external {$IFDEF STATIC_LIB}LIBPCRE{$ENDIF} name PU + PCREname + 'fullinfo';
function pcre_get_named_substring(const code: PPCRE; const subject: PCRE_STR;
ovector: PInteger; stringcount: Integer; const stringname: PCRE_STR;
const stringptr: PCRE_SPTR): Integer;
cdecl; external {$IFDEF STATIC_LIB}LIBPCRE{$ENDIF} name PU + PCREname + 'get_named_substring';
function pcre_get_stringnumber(const code: PPCRE; const stringname: PCRE_STR): Integer;
cdecl; external {$IFDEF STATIC_LIB}LIBPCRE{$ENDIF} name PU + PCREname + 'get_stringnumber';
function pcre_get_stringtable_entries(const code: PPCRE; const stringname: PCRE_STR;
firstptr: PCRE_SPTR; lastptr: PCRE_SPTR): Integer;
cdecl; external {$IFDEF STATIC_LIB}LIBPCRE{$ENDIF} name PU + PCREname + 'get_stringtable_entries';
function pcre_get_substring(const subject: PCRE_STR; ovector: PInteger;
stringcount, stringnumber: Integer; const stringptr: PCRE_SPTR): Integer;
cdecl; external {$IFDEF STATIC_LIB}LIBPCRE{$ENDIF} name PU + PCREname + 'get_substring';
function pcre_get_substring_list(const subject: PCRE_STR; ovector: PInteger;
stringcount: Integer; listptr: PCRE_SPTR_PTR): Integer;
cdecl; external {$IFDEF STATIC_LIB}LIBPCRE{$ENDIF} name PU + PCREname + 'get_substring_list';
function pcre_maketables: MarshaledAString;
cdecl; external {$IFDEF STATIC_LIB}LIBPCRE{$ENDIF} name PU + PCREname + 'maketables';
function pcre_refcount(argument_re: PPCRE; adjust: Integer): Integer;
cdecl; external {$IFDEF STATIC_LIB}LIBPCRE{$ENDIF} name PU + PCREname + 'refcount';
function pcre_study(const code: PPCRE; options: Integer; const errptr: PMarshaledAString): PPCREExtra;
cdecl; external {$IFDEF STATIC_LIB}LIBPCRE{$ENDIF} name PU + PCREname + 'study';
procedure pcre_free_study(extra: PPCREExtra);
cdecl; external {$IFDEF STATIC_LIB}LIBPCRE{$ENDIF} name PU + PCREname + 'free_study';
function pcre_version: MarshaledAString;
cdecl; external {$IFDEF STATIC_LIB}LIBPCRE{$ENDIF} name PU + PCREname + 'version';
{$IFDEF NEXTGEN}
{$NODEFINE pcre_study}
{$NODEFINE pcre_compile}
{$NODEFINE pcre_compile2}
{$ENDIF}
{$IFDEF STATIC_LIB}
// Functions added by Embarcadero in libpcre (pcre_embt_addon.c)
procedure set_pcre_malloc(addr: Pointer);
cdecl; external {$IFDEF STATIC_LIB}LIBPCRE{$ENDIF} name PU + 'set_pcre_malloc';
procedure set_pcre_free(addr: Pointer);
cdecl; external {$IFDEF STATIC_LIB}LIBPCRE{$ENDIF} name PU + 'set_pcre_free';
procedure set_pcre_stack_malloc(addr: Pointer);
cdecl; external {$IFDEF STATIC_LIB}LIBPCRE{$ENDIF} name PU + 'set_pcre_stack_malloc';
procedure set_pcre_stack_free(addr: Pointer);
cdecl; external {$IFDEF STATIC_LIB}LIBPCRE{$ENDIF} name PU + 'set_pcre_stack_free';
procedure set_pcre_callout(addr: Pointer);
cdecl; external {$IFDEF STATIC_LIB}LIBPCRE{$ENDIF} name PU + 'set_pcre_callout';
procedure set_pcre_stack_guard(addr: Pointer);
cdecl; external {$IFDEF STATIC_LIB}LIBPCRE{$ENDIF} name PU + 'set_pcre_stack_guard';
{$ENDIF}
{$ENDIF Defined(MSWINDOWS) or Defined(STATIC_LIB)}
{$IFDEF DYNAMIC_LIB}
var
pcre_compile: function(const pattern: MarshaledAString; options: Integer;
const errptr: PMarshaledAString; erroffset: PInteger; const tableptr: MarshaledAString): PPCRE; cdecl = nil;
pcre_compile2: function(const pattern: MarshaledAString; options: Integer;
const errorcodeptr: PInteger; const errorptr: PMarshaledAString; erroroffset: PInteger;
const tables: MarshaledAString): PPCRE; cdecl = nil;
pcre_config: function(what: Integer; where: Pointer): Integer; cdecl = nil;
pcre_copy_named_substring: function(const code: PPCRE; const subject: MarshaledAString;
ovector: PInteger; stringcount: Integer; const stringname: MarshaledAString;
buffer: MarshaledAString; size: Integer): Integer; cdecl = nil;
pcre_copy_substring: function(const subject: MarshaledAString; ovector: PInteger;
stringcount, stringnumber: Integer; buffer: MarshaledAString; buffersize: Integer): Integer; cdecl = nil;
pcre_dfa_exec: function(const argument_re: PPCRE; const extra_data: PPCREExtra;
const subject: MarshaledAString; length: Integer; start_offset: Integer;
options: Integer; offsets: PInteger; offsetcount: Integer; workspace: PInteger;
wscount: Integer): Integer; cdecl = nil;
pcre_exec: function(const code: PPCRE; const extra: PPCREExtra; const subject: MarshaledAString;
length, startoffset, options: Integer; ovector: PInteger; ovecsize: Integer): Integer; cdecl = nil;
pcre_free_substring: procedure(stringptr: MarshaledAString); cdecl = nil;
pcre_free_substring_list: procedure(stringptr: PMarshaledAString); cdecl = nil;
pcre_fullinfo: function(const code: PPCRE; const extra: PPCREExtra;
what: Integer; where: Pointer): Integer; cdecl = nil;
pcre_get_named_substring: function(const code: PPCRE; const subject: MarshaledAString;
ovector: PInteger; stringcount: Integer; const stringname: MarshaledAString;
const stringptr: PMarshaledAString): Integer; cdecl = nil;
pcre_get_stringnumber: function(const code: PPCRE;
const stringname: MarshaledAString): Integer; cdecl = nil;
pcre_get_stringtable_entries: function(const code: PPCRE; const stringname: MarshaledAString;
firstptr: PMarshaledAString; lastptr: PMarshaledAString): Integer; cdecl = nil;
pcre_get_substring: function(const subject: MarshaledAString; ovector: PInteger;
stringcount, stringnumber: Integer; const stringptr: PMarshaledAString): Integer; cdecl = nil;
pcre_get_substring_list: function(const subject: MarshaledAString; ovector: PInteger;
stringcount: Integer; listptr: PPMarshaledAString): Integer; cdecl = nil;
pcre_info: function(const code: PPCRE; optptr, firstcharptr: PInteger): Integer; cdecl = nil;
pcre_maketables: function: MarshaledAString; cdecl = nil;
pcre_refcount: function(argument_re: PPCRE; adjust: Integer): Integer; cdecl = nil;
pcre_study: function(const code: PPCRE; options: Integer; const errptr: PMarshaledAString): PPCREExtra; cdecl = nil;
pcre_version: function: MarshaledAString; cdecl = nil;
{$NODEFINE pcre_get_substring_list}
function LoadPCRELib: Boolean;
procedure UnloadPCRELib;
{$ENDIF}
// Calling pcre_free in the DLL causes an access violation error; use pcre_dispose instead
procedure pcre_dispose(pattern, hints, chartable: Pointer);
implementation
{$IFDEF MSWINDOWS}
uses
System.Win.Crtl; {$NOINCLUDE System.Win.Crtl}
{$ENDIF MSWINDOWS}
{$IF defined(DYNAMIC_LIB) and defined(POSIX)}
uses
Posix.Dlfcn, Posix.Stdlib;
{$ENDIF}
{$IF Declared(PCRELib)}
var
_PCRELib: THandle;
{$ENDIF}
{$IFDEF MSWINDOWS}
{$IFDEF PCRE16}
{$IF Defined(Win32)}
{$L pcre16_study.obj}
{$L pcre16_compile.obj}
{$L pcre16_config.obj}
{$L pcre16_dfa_exec.obj}
{$L pcre16_exec.obj}
{$L pcre16_fullinfo.obj}
{$L pcre16_get.obj}
{$L pcre16_maketables.obj}
{$L pcre16_newline.obj}
{$L pcre16_ord2utf16.obj}
{$L pcre16_refcount.obj}
{$L pcre16_tables.obj}
{$L pcre16_string_utils.obj}
{$L pcre16_ucd.obj}
{$L pcre16_valid_utf16.obj}
{$L pcre16_version.obj}
{$L pcre16_xclass.obj}
{$L pcre16_default_tables.obj}
{$ELSEIF Defined(Win64)}
{$L pcre16_study.o}
{$L pcre16_compile.o}
{$L pcre16_config.o}
{$L pcre16_dfa_exec.o}
{$L pcre16_exec.o}
{$L pcre16_fullinfo.o}
{$L pcre16_get.o}
{$L pcre16_maketables.o}
{$L pcre16_newline.o}
{$L pcre16_ord2utf16.o}
{$L pcre16_refcount.o}
{$L pcre16_string_utils.o}
{$L pcre16_tables.o}
{$L pcre16_ucd.o}
{$L pcre16_valid_utf16.o}
{$L pcre16_version.o}
{$L pcre16_xclass.o}
{$L pcre16_default_tables.o}
{$ENDIF}
{$ELSE}
{$IF Defined(Win32)}
{$L pcre_study.obj}
{$L pcre_compile.obj}
{$L pcre_config.obj}
{$L pcre_dfa_exec.obj}
{$L pcre_exec.obj}
{$L pcre_fullinfo.obj}
{$L pcre_get.obj}
{$L pcre_maketables.obj}
{$L pcre_newline.obj}
{$L pcre_ord2utf8.obj}
{$L pcre_refcount.obj}
{$L pcre_tables.obj}
{$L pcre_ucd.obj}
{$L pcre_valid_utf8.obj}
{$L pcre_version.obj}
{$L pcre_xclass.obj}
{$L pcre_default_tables.obj}
{$ELSEIF Defined(Win64)}
{$L pcre_study.o}
{$L pcre_compile.o}
{$L pcre_config.o}
{$L pcre_dfa_exec.o}
{$L pcre_exec.o}
{$L pcre_fullinfo.o}
{$L pcre_get.o}
{$L pcre_maketables.o}
{$L pcre_newline.o}
{$L pcre_ord2utf8.o}
{$L pcre_refcount.o}
{$L pcre_tables.o}
{$L pcre_ucd.o}
{$L pcre_valid_utf8.o}
{$L pcre_version.o}
{$L pcre_xclass.o}
{$L pcre_default_tables.o}
{$ENDIF}
{$ENDIF}
{$ENDIF MSWINDOWS}
// user's defined callbacks
var
pcre_malloc_user: pcre_malloc_callback;
pcre_free_user: pcre_free_callback;
pcre_stack_malloc_user: pcre_stack_malloc_callback;
pcre_stack_free_user: pcre_stack_free_callback;
pcre_callout_user: pcre_callout_callback;
pcre_stack_guard_user: pcre_stack_guard_callback;
function __pcre_malloc(Size: NativeUInt): Pointer; cdecl;
begin
if Assigned(pcre_malloc_user) then
Result := pcre_malloc_user(Size)
else
Result := AllocMem(Size);
end;
function __pcre_stack_malloc(Size: NativeUInt): Pointer; cdecl;
begin
if Assigned(pcre_stack_malloc_user) then
Result := pcre_stack_malloc_user(Size)
else
Result := AllocMem(Size);
end;
procedure __pcre_free(P: Pointer); cdecl;
begin
if Assigned(pcre_free_user) then
pcre_free_user(P)
else
FreeMem(P);
end;
procedure __pcre_stack_free(P: Pointer); cdecl;
begin
if Assigned(pcre_stack_free_user) then
pcre_stack_free_user(P)
else
FreeMem(P);
end;
function __pcre_callout(var callout_block: pcre_callout_block): Integer; cdecl;
begin
if Assigned(pcre_callout_user) then
Result := pcre_callout_user(callout_block)
else
Result := 0;
end;
function __pcre_stack_guard: Integer; cdecl;
begin
if Assigned(pcre_stack_guard_user) then
Result := pcre_stack_guard_user
else
Result := 0;
end;
{$IFDEF PCRE16}
{$IFDEF WIN32}
const
_pcre16_malloc: ^pcre_malloc_callback = @__pcre_malloc;
_pcre16_free: ^pcre_free_callback = @__pcre_free;
_pcre16_stack_malloc: ^pcre_stack_malloc_callback = @__pcre_stack_malloc;
_pcre16_stack_free: ^pcre_stack_free_callback = @__pcre_stack_free;
_pcre16_callout: ^pcre_callout_callback = @__pcre_callout;
_pcre16_stack_guard: ^pcre_stack_guard_callback = @__pcre_stack_guard;
{$ENDIF}
{$IFDEF WIN64}
const
pcre16_malloc: ^pcre_malloc_callback = @__pcre_malloc;
pcre16_free: ^pcre_free_callback = @__pcre_free;
pcre16_stack_malloc: ^pcre_stack_malloc_callback = @__pcre_stack_malloc;
pcre16_stack_free: ^pcre_stack_free_callback = @__pcre_stack_free;
pcre16_callout: ^pcre_callout_callback = @__pcre_callout;
pcre16_stack_guard: ^pcre_stack_guard_callback = @__pcre_stack_guard;
{$ENDIF}
{$ELSE}
{$IFDEF WIN32}
const
_pcre_malloc: ^pcre_malloc_callback = @__pcre_malloc;
_pcre_free: ^pcre_free_callback = @__pcre_free;
_pcre_stack_malloc: ^pcre_stack_malloc_callback = @__pcre_stack_malloc;
_pcre_stack_free: ^pcre_stack_free_callback = @__pcre_stack_free;
_pcre_callout: ^pcre_callout_callback = @__pcre_callout;
_pcre_stack_guard: ^pcre_stack_guard_callback = @__pcre_stack_guard;
{$ENDIF}
{$IFDEF WIN64}
const
pcre_malloc: ^pcre_malloc_callback = @__pcre_malloc;
pcre_free: ^pcre_free_callback = @__pcre_free;
pcre_stack_malloc: ^pcre_stack_malloc_callback = @__pcre_stack_malloc;
pcre_stack_free: ^pcre_stack_free_callback = @__pcre_stack_free;
pcre_callout: ^pcre_callout_callback = @__pcre_callout;
pcre_stack_guard: ^pcre_stack_guard_callback = @__pcre_stack_guard;
{$ENDIF}
{$ENDIF}
procedure SetPCREMallocCallback(const Value: pcre_malloc_callback);
begin
pcre_malloc_user := Value;
end;
function GetPCREMallocCallback: pcre_malloc_callback;
begin
Result := pcre_malloc_user;
end;
function CallPCREMalloc(Size: NativeUInt): Pointer;
begin
Result := __pcre_malloc(Size);
end;
procedure SetPCREFreeCallback(const Value: pcre_free_callback);
begin
pcre_free_user := Value;
end;
function GetPCREFreeCallback: pcre_free_callback;
begin
Result := pcre_free_user;
end;
procedure CallPCREFree(P: Pointer);
begin
__pcre_free(P);
end;
procedure SetPCREStackMallocCallback(const Value: pcre_stack_malloc_callback);
begin
pcre_stack_malloc_user := Value;
end;
function GetPCREStackMallocCallback: pcre_stack_malloc_callback;
begin
Result := pcre_stack_malloc_user;
end;
function CallPCREStackMalloc(Size: NativeUInt): Pointer;
begin
Result := __pcre_stack_malloc(Size);
end;
procedure SetPCREStackFreeCallback(const Value: pcre_stack_free_callback);
begin
pcre_stack_free_user := Value;
end;
function GetPCREStackFreeCallback: pcre_stack_free_callback;
begin
Result := pcre_stack_free_user;
end;
procedure CallPCREStackFree(P: Pointer);
begin
__pcre_stack_free(P);
end;
procedure SetPCRECalloutCallback(const Value: pcre_callout_callback);
begin
pcre_callout_user := Value;
end;
function GetPCRECalloutCallback: pcre_callout_callback;
begin
Result := pcre_callout_user;
end;
function CallPCRECallout(var callout_block: pcre_callout_block): Integer;
begin
Result := __pcre_callout(callout_block);
end;
procedure pcre_dispose(pattern, hints, chartable: Pointer);
begin
if pattern <> nil then
__pcre_free(pattern);
if hints <> nil then
__pcre_free(hints);
if chartable <> nil then
__pcre_free(chartable);
end;
{$IFDEF WIN64}
procedure __chkstk;
asm
end;
{$ENDIF WIN64}
{$IFDEF WIN32}
procedure __chkstk_noalloc;
asm
end;
{$ENDIF WIN64}
{$IFDEF DYNAMIC_LIB}
function LoadPCRELib: Boolean;
function GetProcAddr(const ProcName: MarshaledAString): Pointer;
begin
dlerror;
Result := dlsym(_PCRELib, ProcName);
end;
procedure SetCallback(const cbName: MarshaledAString; ProcPointer: Pointer);
begin
Pointer(GetProcAddr(cbName)^) := ProcPointer;
end;
begin
Result := True;
if _PCRELib = 0 then
begin
Result := False;
_PCRELib := HMODULE(dlopen(PCRELib, RTLD_LAZY));
if _PCRELib <> 0 then
begin
// Setup the function pointers
@pcre_compile := GetProcAddr('pcre_compile');
@pcre_compile2 := GetProcAddr('pcre_compile2');
@pcre_config := GetProcAddr('pcre_config');
@pcre_copy_named_substring := GetProcAddr('pcre_copy_named_substring');
@pcre_copy_substring := GetProcAddr('pcre_copy_substring');
@pcre_dfa_exec := GetProcAddr('pcre_dfa_exec');
@pcre_exec := GetProcAddr('pcre_exec');
@pcre_free_substring := GetProcAddr('pcre_free_substring');
@pcre_free_substring_list := GetProcAddr('pcre_free_substring_list');
@pcre_fullinfo := GetProcAddr('pcre_fullinfo');
@pcre_get_named_substring := GetProcAddr('pcre_get_named_substring');
@pcre_get_stringnumber := GetProcAddr('pcre_get_stringnumber');
@pcre_get_stringtable_entries := GetProcAddr('pcre_get_stringtable_entries');
@pcre_get_substring := GetProcAddr('pcre_get_substring');
@pcre_get_substring_list := GetProcAddr('pcre_get_substring_list');
@pcre_info := GetProcAddr('pcre_info');
@pcre_maketables := GetProcAddr('pcre_maketables');
@pcre_refcount := GetProcAddr('pcre_refcount');
@pcre_study := GetProcAddr('pcre_study');
@pcre_version := GetProcAddr('pcre_version');
// Hook the global variables exported from the library for memory allocation
SetCallback('pcre_malloc', @__pcre_malloc);
SetCallback('pcre_stack_malloc', @__pcre_stack_malloc);
SetCallback('pcre_free', @__pcre_free);
SetCallback('pcre_stack_free', @__pcre_stack_free);
SetCallback('pcre_callout', @__pcre_callout);
Result := True;
end;
end;
end;
procedure UnloadPCRELib;
begin
if _PCRELib <> 0 then
dlclose(_PCRELib);
_PCRELib := 0;
end;
{$ENDIF}
{$IFDEF STATIC_LIB}
initialization
set_pcre_malloc(@__pcre_malloc);
set_pcre_stack_malloc(@__pcre_stack_malloc);
set_pcre_free(@__pcre_free);
set_pcre_stack_free(@__pcre_stack_free);
set_pcre_callout(@__pcre_callout);
set_pcre_stack_guard(@__pcre_stack_guard);
{$ENDIF STATIC_LIB}
end.
|
////////////////////////////////////////////////////////////////////////////////
// IPADRESS98 //
////////////////////////////////////////////////////////////////////////////////
// An implementation of IE4's IPADDRESS Control //
////////////////////////////////////////////////////////////////////////////////
// Version 1.00 Beta //
// Date de création : 20/10/1997 //
// Date dernière modification : 21/10/1997 //
////////////////////////////////////////////////////////////////////////////////
// Jean-Luc Mattei //
// jlucm@club-internet.fr / jlucm@mygale.org //
////////////////////////////////////////////////////////////////////////////////
// IMPORTANT NOTICE : //
// //
// //
// This program is FreeWare //
// //
// Please do not release modified versions of this source code. //
// If you've made any changes that you think should have been there, //
// feel free to submit them to me at jlucm@club-internet.fr //
////////////////////////////////////////////////////////////////////////////////
// REVISIONS : //
// //
////////////////////////////////////////////////////////////////////////////////
unit IpAdress;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ComCtrls, CommCtrl {, Comctl98};
type
{from comctl98}
TCustomIPAdress98 = class;
TIPAdressFieldChangeEvent = procedure (Sender: TCustomIPAdress98; OldField, Value: Byte) of object;
TIPAdressChangeEvent = procedure (Sender: TCustomIPAdress98; IPAdress: String) of object;
TCustomIPAdress98 = class(TWinControl)
private
FOnIPChange: TIPAdressChangeEvent;
FOnIPFieldChange: TIPAdressFieldChangeEvent;
FMinIPAddress: Longint;
FMaxIPAddress: Longint;
FActiveField: Byte;
FAutoSize: Boolean;
procedure CNNotify(var Message: TWMNotify); message CN_NOTIFY;
procedure CNCommand(var Message: TWMCommand); message CN_COMMAND;
protected
procedure CreateParams(var Params: TCreateParams); override;
function GetMinIPAdress: String;
function GetMaxIPAdress: String;
function GetIPAdress: String;
procedure SetMinIPAdress(Value: String);
procedure SetMaxIPAdress(Value: String);
procedure SetIPAdress(Value: String);
function GetEmpty: Boolean;
procedure SetActiveField(Value: Byte);
public
constructor Create(AOwner: TComponent); override;
function IPToString(Ip: Longint): String;
function StringToIP(Value: String): Longint;
procedure Clear;
property ActiveField: Byte read FActiveField write SetActiveField;
property Empty: Boolean read GetEmpty;
property MinIPAdress: String read GetMinIPAdress write SetMinIPAdress;
property MaxIPAdress: String read GetMaxIPAdress write SetMaxIPAdress;
property IPAdress: String read GetIPAdress write SetIPAdress;
property OnIPChange: TIPAdressChangeEvent read FOnIPChange write FOnIPChange;
property OnIPFieldChange: TIPAdressFieldChangeEvent read FOnIPFieldChange write FOnIPFieldChange;
end;
TIPAdress98 = class(TCustomIPAdress98)
published
property ActiveField;
property Empty;
property MinIPAdress;
property MaxIPAdress;
property IPAdress;
property OnIPChange;
property OnIPFieldChange;
property Font;
property ParentColor;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property TabOrder;
property TabStop;
property Tag;
property DragCursor;
property DragMode;
property HelpContext;
end;
function MakeIPRange(Low, High : Byte): Longint;
//#define MAKEIPRANGE(low, high) ((LPARAM)(WORD)(((BYTE)(high) << 8) + (BYTE)(low)))
// And this is a useful macro for making the IP Address to be passed
// as a LPARAM.
(*function MakeIPAdress(b1, b2, b3, b4 : Byte): Longint;
//#define MAKEIPADDRESS(b1,b2,b3,b4) ((LPARAM)(((DWORD)(b1)<<24)+((DWORD)(b2)<<16)+((DWORD)(b3)<<8)+((DWORD)(b4))))
function First_IPAdress(x : Longint): Byte;
//#define FIRST_IPADDRESS(x) ((x>>24) & 0xff)
function Second_IPAdress(x : Longint): Byte;
//#define SECOND_IPADDRESS(x) ((x>>16) & 0xff)
function Third_IPAdress(x : Longint): Byte;
//#define THIRD_IPADDRESS(x) ((x>>8) & 0xff)
function Fourth_IPAdress(x : Longint): Byte;
//#define FOURTH_IPADDRESS(x) (x & 0xff)
*)
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('Samples', [TIPAdress98]);
end;
constructor TCustomIPAdress98.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
if NewStyleControls then
ControlStyle := [csClickEvents, csSetCaption, csDoubleClicks, csFixedHeight]
else
ControlStyle := [csClickEvents, csSetCaption, csDoubleClicks, csFixedHeight, csFramed];
ParentColor := False;
FAutoSize := True;
Width:= 100;
Height:= 25;
TabStop:= True;
FMinIPAddress:= 0;
FMaxIPAddress:= $0FFFFFFFF;
FActiveField:= 0;
FOnIPChange:= nil;
FOnIPFieldChange:= nil;
end;
procedure TCustomIPAdress98.CreateParams(var Params: TCreateParams);
begin
InitCommonControl(ICC_INTERNET_CLASSES);
inherited CreateParams(Params);
CreateSubClass(Params, WC_IPADDRESS);
with Params do
begin
Style := WS_VISIBLE or WS_BORDER or WS_CHILD;
if NewStyleControls and Ctl3D then
begin
Style := Style and not WS_BORDER;
ExStyle := ExStyle or WS_EX_CLIENTEDGE;
end;
end;
end;
procedure TCustomIPAdress98.CNNotify(var Message: TWMNotify);
begin
with Message.NMHdr^ do begin
case Code of
IPN_FIELDCHANGED :
begin
FActiveField:= PNMIPAddress(Message.NMHdr)^.iField;
if Assigned(OnIpFieldChange) then
with PNMIPAddress(Message.NMHdr)^ do begin
OnIPFieldChange(Self, iField, iValue);
end;
end;
end;
end;
end;
function TCustomIPAdress98.GetIPAdress: String;
var Ip: Longint;
begin
SendMessage(Handle, IPM_GETADDRESS, 0, Longint(@Ip));
Result:= IPToString(Ip);
end;
function TCustomIPAdress98.GetMinIPAdress: String;
begin
Result:= IPToString(FMinIPAddress);
end;
procedure TCustomIPAdress98.SetMinIPAdress(Value: String);
begin
FMinIPAddress:= StringToIp(Value);
SendMessage(Handle, IPM_SETRANGE, 0, MakeIpRange(First_IPAddress(FMinIPAddress), First_IPAddress(FMaxIPAddress)));
SendMessage(Handle, IPM_SETRANGE, 1, MakeIpRange(Second_IPAddress(FMinIPAddress), Second_IPAddress(FMaxIPAddress)));
SendMessage(Handle, IPM_SETRANGE, 2, MakeIpRange(Third_IPAddress(FMinIPAddress), Third_IPAddress(FMaxIPAddress)));
SendMessage(Handle, IPM_SETRANGE, 3, MakeIpRange(Fourth_IPAddress(FMinIPAddress), Fourth_IPAddress(FMaxIPAddress)));
end;
function TCustomIPAdress98.GetMaxIPAdress: String;
begin
Result:= IPToString(FMaxIPAddress);
end;
procedure TCustomIPAdress98.SetMaxIPAdress(Value: String);
begin
FMaxIPAddress:= StringToIp(Value);
SendMessage(Handle, IPM_SETRANGE, 0, MakeIpRange(First_IPAddress(FMinIPAddress), First_IPAddress(FMaxIPAddress)));
SendMessage(Handle, IPM_SETRANGE, 1, MakeIpRange(Second_IPAddress(FMinIPAddress), Second_IPAddress(FMaxIPAddress)));
SendMessage(Handle, IPM_SETRANGE, 2, MakeIpRange(Third_IPAddress(FMinIPAddress), Third_IPAddress(FMaxIPAddress)));
SendMessage(Handle, IPM_SETRANGE, 3, MakeIpRange(Fourth_IPAddress(FMinIPAddress), Fourth_IPAddress(FMaxIPAddress)));
end;
procedure TCustomIPAdress98.SetIPAdress(Value: String);
begin
SendMessage(Handle, IPM_SETADDRESS, 0, StringToIp(Value));
end;
function TCustomIPAdress98.GetEmpty: Boolean;
begin
Result:= Boolean(SendMessage(Handle, IPM_ISBLANK, 0, 0));
end;
procedure TCustomIPAdress98.Clear;
begin
SendMessage(Handle, IPM_CLEARADDRESS, 0, 0);
end;
procedure TCustomIPAdress98.SetActiveField(Value: Byte);
begin
if ( Value < 4 ) then begin
SendMessage(Handle, IPM_SETFOCUS, wParam(Value), 0);
FActiveField:= Value;
end;
end;
function TCustomIPAdress98.StringToIp(Value: String): Longint;
var B: Array[0..3] of Byte;
Str: String;
i, Cnt : Integer;
begin
B[0]:= 0;
B[1]:= 0;
B[2]:= 0;
B[3]:= 0;
Cnt:= 0;
i:= Pos('.', Value);
while (Length(Value) > 0) and ( Cnt < 4 ) do begin
if ( i = 0 ) then i:= Length(Value)+1;
Str:= Copy(Value, 0, i-1);
B[Cnt]:= StrToInt(Str);
Value:= Copy(Value, i+1, Length(Value));
i:= Pos('.', Value);
Inc(Cnt);
end;
Result:= MakeIPAddress(b[0], b[1], b[2], b[3]);
end;
function TCustomIPAdress98.IPToString(Ip: Longint): String;
begin
Result:= IntToStr(First_IPAddress(Ip))+'.'+IntToStr(Second_IPAddress(Ip))+'.'+
IntToStr(Third_IPAddress(Ip))+'.'+IntToStr(Fourth_IPAddress(Ip));
end;
procedure TCustomIPAdress98.CNCommand(var Message: TWMCommand);
begin
if (Message.NotifyCode = EN_CHANGE) and Assigned(OnIpChange) then
OnIPChange(Self, IPAdress);
end;
function MakeIPRange(Low, High : Byte): Longint;
begin
Result:= Longint((Longint(high) SHL 8) + Longint(low));
end;
{function First_IPAdress(x : Longint): Byte;
begin
Result:= Byte((x Shr 24) and $0FF);
end;
function Second_IPAdress(x : Longint): Byte;
begin
Result:= Byte((x Shr 16) and $0FF);
end;
function Third_IPAdress(x : Longint): Byte;
begin
Result:= Byte((x Shr 8) and $0FF);
end;
function Fourth_IPAdress(x : Longint): Byte;
begin
Result:= Byte(x and $0FF);
end;}
end.
|
{ **************************************************************
Package: XWB - Kernel RPCBroker
Date Created: Sept 18, 1997 (Version 1.1)
Site Name: Oakland, OI Field Office, Dept of Veteran Affairs
Developers: Danila Manapsal, Don Craven, Joel Ivey, Herlan Westra
Description: Contains TRPCBroker and related components.
Unit: VCEdit Verify Code edit dialog.
Current Release: Version 1.1 Patch 65
*************************************************************** }
{ **************************************************
Changes in v1.1.65 (HGW 08/05/2015) XWB*1.1*65
1. Changed TVCEdit.ChangeVCKnowOldVC so that if old verify code was less
than eight digits, box would not be greyed out (manually enter old VC).
This is because using SSO, old VC is not entered in login form.
2. Added procedure btnCancelClick to continue with login if user chooses
to cancel changing verify code.
Changes in v1.1.60 (HGW 11/20/2013) XWB*1.1*60
1. Fixed process to change VC. VC change did not work if lowercase chars
were used in the new verify code. GUI was case-sensitive, but VistA is not.
Changes in v1.1.50 (JLI 09/01/2011) XWB*1.1*50
1. None.
************************************************** }
unit VCEdit;
interface
uses
{System}
SysUtils, Classes,
{WinApi}
Windows, Messages,
{VA}
Trpcb, XWBHash,
{Vcl}
Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons;
type
TVCEdit = class(TComponent)
private
FRPCBroker : TRPCBroker;
FOldVC : string;
FConfirmFailCnt : integer; //counts failed confirms.
FHelp : string;
FOldVCSet: Boolean; // Shows whether old code was passed in, even if NULL
procedure NoChange(reason : string);
protected
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function ChangeVCKnowOldVC(strOldVC : string) : Boolean;
function ChangeVC : Boolean;
published
property RPCBroker : TRPCBroker read FRPCBroker write FRPCBroker;
end;
TfrmVCEdit = class(TForm)
lblOldVC: TLabel;
lblNewVC: TLabel;
lblConfirmVC: TLabel;
edtOldVC: TEdit;
edtNewVC: TEdit;
edtConfirmVC: TEdit;
btnOK: TBitBtn;
btnCancel: TBitBtn;
btnHelp: TBitBtn;
procedure btnOKClick(Sender: TObject);
procedure btnHelpClick(Sender: TObject);
procedure edtNewVCExit(Sender: TObject);
procedure edtOldVCChange(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
protected
{ Private declarations }
FVCEdit : TVCEdit; //Links form to instance of VCEdit.
public
{ Public declarations }
end;
function ChangeVerify(RPCBroker: TRPCBroker): Boolean;
function SilentChangeVerify(RPCBroker: TRPCBroker; OldVerify, NewVerify1, NewVerify2: String; var Reason: String): Boolean;
var
frmVCEdit: TfrmVCEdit;
const
MAX_CONFIRM_FAIL : integer = 3;
U = '^';
{procedure Register;}
implementation
{$R *.DFM}
function ChangeVerify(RPCBroker: TRPCBroker): Boolean;
var
VCEdit1: TVCEdit;
begin
// Str := '';
VCEdit1 := TVCEdit.Create(Application);
try
VCEdit1.RPCBroker := RPCBroker;
if VCEdit1.ChangeVC then //invoke VCEdit form. //VC changed.
Result := True
else
Result := False;
finally
VCEdit1.Free;
end;
end;
function SilentChangeVerify(RPCBroker: TRPCBroker; OldVerify, NewVerify1, NewVerify2: String; var Reason: String): Boolean;
var
OrigContext: String;
begin
Result := False;
Reason := '';
if OldVerify = NewVerify1 then
Reason := 'The new code is the same as the current one.'
else
if NewVerify1 <> NewVerify2 then
Reason := 'The confirmation code does not match.';
if Reason = '' then
try
with RPCBroker do
begin
OrigContext := CurrentContext;
CreateContext('XUS SIGNON');
RemoteProcedure := 'XUS CVC';
Param[0].PType := literal;
Param[0].Value := Encrypt(OldVerify)
+ U + Encrypt(NewVerify1)
+ U + Encrypt(NewVerify2) ;
Call;
Reason := '';
if Results[0] = '0' then
Result := True
else if Results.Count > 1 then
Reason := Results[1];
CreateContext(OrigContext);
end;
except
on E: Exception do
begin
RPCBroker.RPCBError := E.Message;
if Assigned(RPCBroker.OnRPCBFailure) then
RPCBroker.OnRPCBFailure(RPCBroker)
else if RPCBroker.ShowErrorMsgs = semRaise then
Raise;
end;
end;
end;
{------------------TVCEdit component------------------------------------}
constructor TVCEDit.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FOldVCSet := False;
end;
destructor TVCEDit.Destroy;
begin
inherited Destroy;
end;
function TVCEdit.ChangeVCKnowOldVC(strOldVC : string) : Boolean;
begin
FOldVC := strOldVC;
FOldVCSet := True;
if Length(FOldVC) < 8 then
FOldVCSet := False;
Result := ChangeVC;
FOldVCSet := False; // set it back to false in case we come in again
end;
{--------------------------ChangeVC function---------------------------}
function TVCEdit.ChangeVC : Boolean;
var
OldHandle: THandle;
begin
Result := False;
try
frmVCEDit := TfrmVCEDit.Create(application);
with frmVCEDit do
begin
FVCEdit := Self; //To link form to VCEdit instance.
if FOldVCSet then //If old VC known, stuff it & disable editing.
begin
edtOldVC.Color := clBtnFace;
edtOldVC.Enabled := False;
edtOldVC.Text := FOldVC;
end{if};
// ShowApplicationAndFocusOK(Application);
OldHandle := GetForegroundWindow;
SetForegroundWindow(frmVCEdit.Handle);
if ShowModal = mrOK then //outcome of form.
Result := True;
SetForegroundWindow(OldHandle);
end{with};
frmVCEDit.Free;
except
on E: Exception do
begin
FRPCBroker.RPCBError := E.Message;
if Assigned(FRPCBroker.OnRPCBFailure) then
FRPCBroker.OnRPCBFailure(FRPCBroker)
else if FRPCBroker.ShowErrorMsgs = semRaise then
Raise;
end;
end{except};
end;
{------------------TVCEdit.NoChange-------------------------------------
-----------Displays error messages when change fails.-------------------}
procedure TVCEdit.NoChange(reason : string);
begin
ShowMessage('Your VERIFY code was not changed.' + #13 +
reason + #13 );
end;
{-------------------------TfrmVCEdit methods-------------------------------}
procedure TfrmVCEdit.btnOKClick(Sender: TObject);
begin
with FVCEdit do
begin
edtOldVC.Text := AnsiUpperCase(edtOldVC.Text); //p60
edtNewVC.Text := AnsiUpperCase(edtNewVC.Text); //p60
edtConfirmVC.Text := AnsiUpperCase(edtConfirmVC.Text); //p60
if edtOldVC.Text = edtNewVC.Text then
begin
NoChange('The new code is the same as the current one.');
edtNewVC.Text := '';
edtConfirmVC.Text := '';
edtNewVC.SetFocus;
end
else
if edtNewVC.Text <> edtConfirmVC.Text then
begin
inc(FConfirmFailCnt);
if FConfirmFailCnt > MAX_CONFIRM_FAIL then
begin
edtNewVC.Text := '';
edtConfirmVC.Text := '';
NoChange('The confirmation code does not match.');
edtNewVC.SetFocus;
end
else
begin
edtConfirmVC.text := '';
NoChange('The confirmation code does not match. Try again.');
edtConfirmVC.SetFocus;
end;
end
else
with FRPCBroker do
begin
RemoteProcedure := 'XUS CVC';
Param[0].PType := literal;
Param[0].Value := Encrypt(edtOldVC.Text)
+ U + Encrypt(edtNewVC.Text)
+ U + Encrypt(edtConfirmVC.Text) ;
Call;
if Results[0] = '0' then
begin
ShowMessage('Your VERIFY CODE has been changed');
ModalResult := mrOK; //Close form.
end
else
begin
if Results.Count > 1 then
NoChange(Results[1])
else
NoChange('');
edtNewVC.Text := '';
edtConfirmVC.Text := '';
edtNewVC.SetFocus;
end;
end;
end{with};
end;
procedure TfrmVCEdit.btnCancelClick(Sender: TObject);
begin
with FVCEdit do
begin
edtOldVC.Text := AnsiUpperCase(edtOldVC.Text); //p65
NoChange('You chose to cancel the change.');
ModalResult := mrOK; //result
end{with};
end;
procedure TfrmVCEdit.btnHelpClick(Sender: TObject);
begin
with FVCEdit do
begin
if FHelp = '' then
begin
with FRPCBroker do
begin
RemoteProcedure := 'XUS AV HELP';
Call;
if Results.Count > 0 then
FHelp := Results[0];
FHelp := 'Enter a new verify code and then confirm it.'
+ #13#13 + FHelp;
if FOldVC = '' then
FHelp := 'Enter your current verify code first.' + #13#10 + FHelp;
end{with};
end{if};
ShowMessage(FHelp);
end{with};
end;
procedure TfrmVCEdit.edtNewVCExit(Sender: TObject);
begin
if edtNewVC.Modified then
begin
FVCEdit.FConfirmFailCnt := 0; //Reset counter.
edtNewVC.Modified := False;
end;
end;
procedure TfrmVCEdit.edtOldVCChange(Sender: TObject); //Also NewVC and ConfirmVC
begin
btnOk.Default := ((edtNewVC.Text <> '') and //Update status of OK btn.
(edtOldVC.Text <> '') and
(edtConfirmVC.Text <> '') );
end;
end.
|
unit Game;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ImgList, ExtCtrls, StdCtrls, dglOpenGL, ShellAPI;
type
RGun = record
ClipTime, ClipSize,
sX, sY,
pX, pY, Dmg, Interval: Integer;
Tip: String[16];
TT, ET: String[8];
end;
RmyGun = record
Clip, Index: Integer;
end;
RCreature = record
eX, eY, X, Y: Real;
sX, sY, g,
PicN, Pic, Pic2, PicInt, PicIndex,
Index, TgIndex,
OrgSpd, Spd,
OrgPwr, Pwr, GunY,
HitBy, AiL, Kills, Deaths: Integer;
Dir: -1..1;
AITip, Name,
Act, ActM, exAct: String[16];
myGun: RmyGun;
myGunsI: Array of RmyGun;
ClipTimer,
PicT, ShootI: Int64;
PicShowStyle: 0..1; //animate when walking (0), or repetitive animation (1)
MainPic: 0..20; //pic shown, when standing still
JumpPic:Boolean; //does creature have pics to jump
Dead, Air: Boolean; //is it dead, is it in the air
end;
RBullet = record
X, Y, Dmg: Integer;
Dir: -1..1;
DirY: -3..3;
Owner: record
Name:String[16];
Index: Integer;
HisGun: RMyGun;
end;
Typ, TT, ET: String[8];
end;
TGame = class(TForm)
procedure DrawTex(X, Y: Real; sX, sY: Integer; Rotate: Real; Flip: Boolean; Index: Integer);
procedure DrawCRTex(X, Y: Real; sX, sY: Integer; Rotate: Real; Flip: Boolean; Index1, Index2: Integer);
//TODO: bitmap font.. its just letter by letter right now (see data/font folder)
procedure Text(X, Y: Integer; S: String; Size: Real);
//Particle effects... some effects are used only once and dont have their own functions
procedure P_Blood(X, Y: Real; Int, Size, Dir: Integer);
procedure P_Dissolve(L: Integer);
procedure P_Explode(X, Y: Real; Tip: ShortString);
procedure Draw;
procedure CreatureAI(var C: RCreature; Tg: RCreature);
function OwnedAlready(I, L: Integer): Boolean;
procedure Calculate;
procedure LoadMap;
procedure Loop(Sender: Tobject; var Done: Boolean);
procedure EndItAll;
procedure FormCreate(Sender: TObject);
procedure FormMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure FormMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure FormKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure FormKeyPress(Sender: TObject; var Key: Char);
procedure FormMouseWheelDown(Sender: TObject; Shift: TShiftState;
MousePos: TPoint; var Handled: Boolean);
procedure FormMouseWheelUp(Sender: TObject; Shift: TShiftState;
MousePos: TPoint; var Handled: Boolean);
procedure FormDestroy(Sender: TObject);
end;
var
DjukNjuk: TGame;
implementation
uses Menu;
{$R *.dfm}
const
StuffCount = 300;//Number of trees, bushes and the stuff, that hangs form the ceiling
FontSize = 64;
RespawnPointCount = 150;
TransColor = $10000000;
FPSLimit = 29; //didn't figure out the fps independancy
//Particles
Blood = 0;
Bullet = 1;
Explosion = 2;
Dissolve = 3;//when creature dies
//Quality setting
Lowest = 0;
Low = 1;
Medium = 2;
High = 3;//when creature dies
//Terrain
Dirt = False;
Sky = True;
var
//Poly1 is for the light polygons, poly2 for the dark
//TODO: concave polygon support(then there will be no need for poly2..]
Poly1, Poly2: Array of TPoint;
PolyList: Integer=-1; //The display list for polygons
//A temporary array, used to readback the polygons to array T, screen by screen
TmB: array of Cardinal;
//The array, that stores the terrain (dirt:=false, sky:=true)
T: Array of Array of Boolean;
//Creatures
Cre: Array[ 0..20, 0..20 ] of record//Pics
Pic: array[0..64*64] of Integer;
Index: Cardinal;
end;
CR: Array of RCreature;
//some variables only to enable Djuk to run
//TODO: make all creatures able to run
OrgSpd, OrgPicInt: Integer;
Running: Boolean = False;
//Stuff that lies around on the terrain
ST: Array [0..StuffCount] of record
sX, sY, X, Y,
pIndex: Integer;
Tip: Char;
end;
Stv: Array of record
Pic: array[0..256*256] of Integer;
sX, sY: Integer;
Index: GluInt;
end;
//Bullets
BL: Array of RBullet;
//Particles
PT: Array of record
X: Integer;
Y, g: Single;
Dir: SmallInt;
Tip: 0..3;
Clr: Integer;
end;
//Weather particles
Weather: Array of record
X, Y: Word;
Dir: 0..5;
end;
WeatherInTheSky: Integer = 400;
MaxWeather: Integer = 30000;
WeatherType: Integer;
Wind: 0..2;
//Guns
GN: Array of RGun;
LGN: array of record //guns that lie on the ground
X, Y, g: Integer;
Dir: 0..1;
Air: Boolean;
Index: Integer;
end;
GB: Array of record
Pic: Array [0..64*16] of Integer;
Index: Cardinal;
end;
//Stores letters for the Text function
TextFont: Array of record
Pic: Array[ 0..FontSize, 0..FontSize ] of Cardinal;
Chr: Char;
Index: Cardinal;
end;
//Respawn points
RP: Array [0..RespawnPointCount-1] of TPoint;
Keys: Array of Word;
LoopT: Real;
FPS, RunT: Int64;
Theme: String;
MapCnt: Integer = 0;
//Needed?
//RR: Integer;
XdZ: Integer;
YdZ: Integer;
Pause: Boolean = False;
KP: Boolean = False;
MP: Boolean = False;
Gameover: Boolean = True;
Excape: Boolean = False;
Loading: Boolean = True;
//Quality settings
Part, Back, Smooth, BloodEnabled: Boolean;
stOrgStvari,
tpX, tpY,
tX, tY: Integer;
Rs, Gs, Bs,
Rt, Gt, Bt: Real; //terrain color
// FPSCnt,
FpsTim: Integer;
DeadT: Int64;
Maps: Array of String;
//Loading
Lindex: Cardinal;
Lpic: Array[0..512*128] of Cardinal;
CFl: File of Cardinal;
// QStr: String;
Quality: 0..5;
// bol: boolean=True;
SRec: TSearchRec; //just a search record for finding some files :)
var //GDI/OpenGL stuff
RC: HGLRC;
PF: Integer;
PFD: TPixelFormatDescriptor;
DC: HDC;
var//Timer
StartTime: Int64;
freq: Int64;
function dotTime: Int64;
begin
// Return the current performance counter value.
QueryPerformanceCounter(Result);
end;
function dotTimeSince(start: Int64): Single;
var
x: Int64;
begin
// Return the time elapsed since start (get start with dotTime()).
QueryPerformanceCounter(x);
Result := (x - start) * 1000 / freq;
end;
procedure dotStartTiming;
begin
// Call this to start measuring elapsed time.
StartTime := dotTime;
end;
function dotTimeElapsed: Single;
begin
// Call this to measure the time elapsed since the last StartTiming call.
Result := dotTimeSince(StartTime);
end;
procedure TGame.DrawTex(X, Y: Real; sX, sY: Integer; Rotate: Real; Flip: Boolean; Index: Integer);
var
FlipI: Integer;
begin
glBindTexture(GL_TEXTURE_2D,Index);
if (rotate <> 0) then
begin
glTranslatef(X+sx/2, Y+sy/2, 0);
glRotatef(Rotate, 0, 0, 1);
glTranslatef(-(X+sx/2), -(Y+sy/2), 0);
end;
if Flip then
FlipI := 1
else
FlipI := 0;
glBegin(GL_QUADS);
glColor3f(1, 1, 1);
glTexCoord2f(Abs(1-FlipI), 0);
glVertex2f (X, Y);
glTexCoord2f(Abs(1-FlipI), 1);
glVertex2f (X, Y+Sy);
glTexCoord2f(FlipI, 1);
glVertex2f (X+Sx, Y+Sy);
glTexCoord2f(FlipI, 0);
glVertex2f (X+Sx, Y);
glend;
glLoadIdentity;
end;
procedure TGame.DrawCRTex(X, Y: Real; sX, sY: Integer; Rotate: Real; Flip: Boolean; Index1, Index2: Integer);
var
FlipI, K: Integer;
begin
if (rotate <> 0) then
begin
glTranslatef(X+sx/2, Y+sy/2, 0);
glRotatef(Rotate, 0, 0, 1);
glTranslatef(-(X+sx/2), -(Y+sy/2), 0);
end;
if Flip then
FlipI := 1
else
FlipI := 0;
K := 44;
glBindTexture(GL_TEXTURE_2D,Index1);
glBegin(GL_QUADS);
glColor3f(1, 1, 1);
glTexCoord2f(Abs(1-FlipI), 0);
glVertex2f (X, Y);
glTexCoord2f(Abs(1-FlipI), K/sy);
glVertex2f (X, Y+(Sy*K)/sy);
glTexCoord2f(FlipI, K/sy);
glVertex2f (X+Sx, Y+(Sy*K)/sy);
glTexCoord2f(FlipI, 0);
glVertex2f (X+Sx, Y);
glend;
glBindTexture(GL_TEXTURE_2D,Index2);
glBegin(GL_QUADS);
glColor3f(1, 1, 1);
glTexCoord2f(Abs(1-FlipI), K/sy);
glVertex2f (X, Y+(Sy*K)/sy);
glTexCoord2f(Abs(1-FlipI), 1);
glVertex2f (X, Y+Sy);
glTexCoord2f(FlipI, 1);
glVertex2f (X+Sx, Y+Sy);
glTexCoord2f(FlipI, K/sy);
glVertex2f (X+Sx, Y+(Sy*K)/sy);
glend;
glLoadIdentity;
end;
procedure TGame.Text(X, Y: Integer; S: String; Size: Real);
var
I, J: Integer;
begin
S := UpperCase(S);
for I := 1 to Length(S) do
begin
for J := 0 to Length(TextFont)-1 do
if TextFont[J].Chr = S[I] then
begin
glBindTexture(GL_TEXTURE_2D,TextFont[J].Index);
glLoadIdentity;
glTranslatef(X+(I-1)*Size, Y, 0);
glBegin(GL_QUADS);
glColor3f(0, 0, 0);
glTexCoord2f(0, 0);
glVertex2f (0, 0);
glTexCoord2f(1, 0);
glVertex2f (0, Size);
glTexCoord2f(1, 1);
glVertex2f (Size, Size);
glTexCoord2f(0, 1);
glVertex2f (Size, 0);
glend;
end;
end;
end;
procedure TGame.P_Blood(X, Y: Real; Int, Size, Dir: Integer);
var
I: Integer;
begin
if ((X < tpx-100)
or (X > tpx+(XdZ*2)+100))
and((Y < tpy-100)
or (Y > tpy+(YdZ*2)+100))
or (Part = False)
or (BloodEnabled = False)
then
Exit;
Setlength(PT, Length(PT)+Int);
for I := 1 to Int-1 do
begin
PT[Length(PT)-I].X := Round(X)+Random(Size+2)-Random(Size+2);
PT[Length(PT)-I].Y := Y+Random(Size+2)-Random(Size+2);
PT[Length(PT)-I].g := (Random(Size*7)*0.1)-(Random(Size*7)*0.1);
PT[Length(PT)-I].Tip := Blood;
if Dir = 0 then
begin
if Random(2) = 0 then
PT[Length(PT)-I].Dir := +1+Random(Size) else
PT[Length(PT)-I].Dir := -1-Random(Size);
end else
begin
if Random(3) = 0 then
begin
if Random(2) = 0 then
PT[Length(PT)-I].Dir := +1+Random(Size) else
PT[Length(PT)-I].Dir := -1-Random(Size);
end else
PT[Length(PT)-I].Dir := Dir*(4+Random(3))+Random(3)-Random(3);
end;
end;
end;
procedure TGame.P_Dissolve(L: Integer);
var
I, J, C: Integer;
begin
if (CR[L].X > tpx-CR[L].sX-3)
and (CR[L].X < tpx+(XdZ*2)+3)
and (CR[L].Y > tpy-CR[L].sY-3)
and (CR[L].Y < tpy+(YdZ*2)+3)
and (Part) and (Quality > 1)
then
for C := 1 to Quality-1 do
with CR[L] do
for I := 1+((64-sX) div 2) + ((64-sX) mod 2)
to 64-((64-sX) div 2) do
for J := 1+((64-sY) div 2) + ((64-sY) mod 2)
to 64-((64-sY) div 2) do
try
if (Cre[ Pic, PicIndex ].Pic[I+(J*64)] <> TransColor) then
begin
Setlength(PT, Length(PT)+1);
if Dir = 1 then
PT[Length(PT)-1].X := Round(X)+I-((64-sX) div 2)
else
PT[Length(PT)-1].X := Round(X)+((64-((64-sX) div 2)) div 2)-I+((64-sX) div 2);
PT[Length(PT)-1].Y := Y+J-((64-sY) div 2);
PT[Length(PT)-1].g := 1.5+Random(200)*0.01;
PT[Length(PT)-1].Tip := Dissolve;
PT[Length(PT)-1].Clr := Cre[ Pic, PicIndex ].Pic[I+(J*64)]
end;
except
Continue;
end;
end;
procedure TGame.P_Explode(X, Y: Real; Tip: ShortString);
var
I, Int, Size: Integer;
label
ven;
begin
if(((X < tpx-200)
or (X > tpx+(XdZ*2)+200))
and((Y < tpy-200)
or (Y > tpy+(YdZ*2)+200)))
or (Part = False) then
Exit;
if Tip = 'Tiny' then
begin
Int := 25;
Size := 6+Random(3)-Random(3);
end else
if Tip = 'Small' then
begin
Int := 75;
Size := 7+Random(5)-Random(5);
end else
if Tip = 'Medium' then
begin
Int := 300;
Size := 10+Random(5)-Random(5);
end else
if Tip = 'Large' then
begin
Int := 800;
Size := 15+Random(10)-Random(10);
end else
if Tip = 'Huge' then
begin
Int := 1300;
Size := 25+Random(15)-Random(15);
end else
goto Ven;
Setlength(PT, Length(PT)+Int);
for I := 1 to Int-1 do
begin
PT[Length(PT)-I].X := Round(X)+Random(Size div 2)-Random(Size div 2);
PT[Length(PT)-I].Y := Y+Random(Size div 2)-Random(Size div 2);
PT[Length(PT)-I].g := (Random(Size*5)*0.1)-(Random(Size*5)*0.1);
PT[Length(PT)-I].Tip := Explosion;
if Random(2) = 0 then
PT[Length(PT)-I].Dir := 1+Random(Size) else
PT[Length(PT)-I].Dir := -1-Random(Size);
end;
ven:
end;
//A function that tells, if a creature already ownes a weapon
function TGame.OwnedAlready(I, L: Integer): Boolean;
var
J: Integer;
begin
Result := False;
if (Length(CR[L].myGunsI) > 0) then
for J := 0 to Length(CR[L].myGunsI)-1 do
if (CR[L].myGunsI[J].Index = I) then
Result := True;
end;
var
ptdelete: Integer;
procedure DeleteParticle(P: Integer);
begin
Inc(PtDelete);
PT[P] := PT[Length(PT)-PtDelete];
end;
// DDDDDD
// DD DD aaaaa w w
// DD DD rr rrr a aa ww ww
// DD DD rrr r aa ww w ww
// DD DD rrr aaaaaa ww www ww
// DD DD rr aa aa ww ww ww ww
// DDDDDD rr aaaaa www www
procedure TGame.Draw;
var
I, J, I2, J2, L, Lg: Integer;
Bool: Boolean;
R, G, B: Real;
begin
glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity;
//Terrain
//Draw Polygons
glTranslatef(-tpx, -tpy, 0);
glCallList(PolyList);
glEnable(GL_TEXTURE_2D);
//Stuff on Terrain
if Back then
for I := 0 to StuffCount do
with ST[I] do
if ((X > tpX-sX)
and (X < tpX+(XdZ*2)))
and ((Y > tpY-sY)
and (Y < tpY+(YdZ*2))) then
DrawTex(X-tpX, Y-tpy, Stv[pIndex].sX, Stv[pIndex].sY, 0, True, Stv[pIndex].Index);
//end Stuff on Terrain
//end Terrain
//Creatures&Weapons
for I2 := 0 to Length(CR)-1 do
with CR[I2] do
if (Dead = False) or (I2 = 0) then
if ((X > tpx-sX)
and (X < tpx+(XdZ*2)))
and ((Y > tpy-sY)
and (Y < tpy+(YdZ*2))) then
begin
//Creatures
if (JumpPic) and (Air)
and (T[Round(X)+Sx div 2, Round(Y)+Sy+26]=Sky) then
begin
Pic := PicN+1;
if G < -27 then Pic := PicN+2;
if G < -34 then Pic := PicN+3;
if G < -40 then Pic := PicN+4;
if G > 7 then Pic := PicN+1;
if T[Round(X)+Sx div 2, Round(Y)+350]=Dirt then Pic := PicN+3;
if T[Round(X)+Sx div 2, Round(Y)+150]=Dirt then Pic := PicN+2;
if T[Round(X)+Sx div 2, Round(Y)+50]=Dirt then Pic := PicN+1;
end;
if myGun.Index = -1 then
Pic2 := Pic else
Pic2 := 1;
//@HACK: user upper body hack
if I2 = 0 then
begin
if Dir = 1 then
DrawCRTex(X-tpX-((64-sX) / 2),
Y-tpy-((64-sY) / 2),
64, 64, 0, True,
Cre[ Pic2, PicIndex ].Index,
Cre[ Pic, PicIndex ].Index)
else
DrawCRTex(X-tpX-((64-sX) / 2),
Y-tpy-((64-sY) / 2),
64, 64, 0, False,
Cre[ Pic2, PicIndex ].Index,
Cre[ Pic, PicIndex ].Index);
end else
begin
if Dir = 1 then
DrawTex(X-tpX-((64-sX) / 2),
Y-tpy-((64-sY) / 2),
64, 64, 0, True,
Cre[ Pic, PicIndex ].Index)
else
DrawTex(X-tpX-((64-sX) / 2),
Y-tpy-((64-sY) / 2),
64, 64, 0, False,
Cre[ Pic, PicIndex ].Index);
end;
//end Creatures
if (myGun.Index > -1) and (Length(myGunsI) > 0) then
begin
//Tilts the gun while reloading
if (dotTimeSince(ClipTimer)) < (GN[myGun.Index].ClipTime) then
R := 15 else
R := 0;
//Weapons
// if CR[I2].myGun.Index <> -1 then
For J2 := 0 to Length(GN)-1 do
if J2 = myGun.Index then
if Dir = 1 then
DrawTex(X+((sX-((sX+GN[J2].sX) div 2)))-tpx-((64-GN[J2].sX) / 2)+GN[J2].pX,
Y+GN[J2].pY-tpy-((16-GN[J2].sY) / 2)+GunY,
64, 16, -R, True,
GB[J2].Index)
else
DrawTex(X+((sX-((sX+GN[J2].sX) div 2)))-tpx-((64-GN[J2].sX) / 2)-GN[J2].pX,
Y+GN[J2].pY-tpy-((16-GN[J2].sY) / 2)+GunY,
64, 16, R, False,
GB[J2].Index);
//end Weapons
end;
end;
//The weapons on the ground
if Length(LGN) > 0 then
For I := 0 to Length(LGN)-1 do
if ((LGN[I].X > tpx-GN[LGN[I].Index].sX)
and (LGN[I].X < tpx+(XdZ*2)))
and ((LGN[I].Y > tpy-GN[LGN[I].Index].sY)
and (LGN[I].Y < tpy+(YdZ*2))) then
if LGN[I].Dir = 1 then
DrawTex(LGN[I].X-tpx-((64-GN[LGN[I].Index].sX) / 2),
LGN[I].Y-tpy-((16-GN[LGN[I].Index].sY) / 2),
64, 16, 1, True,
GB[LGN[I].Index].Index)
else
DrawTex(LGN[I].X-tpx-((64-GN[LGN[I].Index].sX) / 2),
LGN[I].Y-tpy-((16-GN[LGN[I].Index].sY) / 2),
64, 16, 1, False,
GB[LGN[I].Index].Index);
//end Creatures&Weapons
glFinish;
glDisable(GL_TEXTURE_2D);
//* _____ __ * _____ * ________* __ *____ *__ * _____ *______ * *
// *][I][_ * _[]_ ][I][_ ]IIIIII[ ][ * _]II[ ][ ]III[ ]IIII[
//* ][__][ _][][_ * ][__][ ][ ][ _][ ][ * ][__* ][___ * *
// ][II[ _][__][_ ][I][ * ][ * ][ ][_ * ][ * ]II[ ]II[_
// * ][ * ]IIIIII[ ][ ][_ ][ * ][ ][___* ][__ * ][___ * ___I[ * *
// *][ * ][ * ][ * ][ ][ * ][ *][ * ]II[ *]III[ ]III[ ]IIII[ *
if (Part) then
begin
if (Length(PT) > 0) then
begin
PtDelete := 0;
for I := 0 to Length(PT)-1 do
With PT[I] do
begin
//Calculate
Case Tip of
Blood:
begin
X := X+Dir;
Y := Y+g;
g := g+(Random(15)*0.1);
end;
Bullet:
if Random(15) = 0 then
X := 0//Deletes the particle
else
begin
if Random(10) = 0 then
g := -g;
if Random(2) = 0 then
begin
if g < 0 then
g := g-0.01-0.001*Random(150)
else
g := g+0.01+0.001*Random(150);
Y := Y+g+(Random(2)-Random(4))*0.2;
end;
X := X+Dir*Random(5)-1;
Clr := Clr+Random(50);
end;
Explosion:
if (Random(6) = 0) then
X := 0//Deletes the particle
else
begin
X := X+Dir;
Y := Y+g;
g := g+(Random(15)*0.1)-(Random(15)*0.1);
if Random(25) = 0 then
g := -g*5;
end;
Dissolve:
begin
g := g + 1 + Random(2);
Y := Y + g;
if (Random(10) = 0) then
X := Random(2)-Random(2);
end;
end;
//end Calculate
if I > Length(PT)-PtDelete then
Break;
if (X <= 2)
or (Y <= 2)
or (X >= tx)
or (Y >= ty)
or (X < tpx-20)
or (X > tpx+(XdZ*2)+20)
or (((Y < tpy-20)
or (Y > tpy+(YdZ*2)+20))
and (Random(7) = 0)
and (Length(PT) > 1500))
or (T[Round(X), Round(Y)]=Dirt) then
begin
DeleteParticle(I);
Continue;
end;
//Draw
glBegin(GL_POINTS);
if ((X > tpx)
and (X < tpx+(XdZ*2)))
and((Y > tpy)
and (Y < tpy+(YdZ*2)))
then
begin
J := Random(150)+50;
Case Tip of
Blood: glColor4f( 1-Random(J)*0.002, Random(J)*0.002, Random(J)*0.002, 0);
Bullet: if Random(2)=0 then
glColor4f((Rs*Clr+(0.1+0.1*Random(5))*J) / (Clr+J),
(Gs*Clr+(0.1+0.1*Random(5))*J) / (Clr+J),
(Bs*Clr+(0.1+0.1*Random(5))*J) / (Clr+J), 0)
else
glColor4f((Rs*Clr+0.4*J) / (Clr+J),
(Gs*Clr+0.4*J) / (Clr+J),
(Bs*Clr+0.4*J) / (Clr+J), 0);
Explosion:
begin
if Random(2) = 1 then
glColor4f(1-Random(5)*0.1,
Random(5)*0.1,
Random(5)*0.1, 0) else
if Random(2) = 1 then
glColor4f(J*0.01+Random(5)*0.1-Random(5)*0.1,
J*0.01+Random(5)*0.1-Random(5)*0.1,
Random(4)*0.1, 0)
else
if Random(2) = 1 then
glColor4f(J*0.001, J*0.001, J*0.001, 0);
end;
Dissolve:
begin
R := (Clr mod $100) / $FF;
G := ((Clr div $100) mod $100) / $FF;
B := (Clr div $10000) / $FF;
I2 := Random(10);
J := Random(5);
glColor4f( (R*I2+Rs*J)/(I2+J),
(G*I2+Gs*J)/(I2+J),
(B*I2+Bs*J)/(I2+J), 0);
end;
end;
glVertex2f( X-tpx, Y-tpy );
end;
glEnd();
//end Draw
end;
if PtDelete > 0 then
try
Setlength(PT, Length(PT)-PtDelete);
except
Setlength(PT, 0);
end;
end;
//Snow
if WeatherType = 1 then
begin
glBegin(GL_POINTS);
glColor4f(1,1,1,0);
J := 0;
for I := 0 to Length(Weather)-1 do
with Weather[I] do
begin
//Calculates&Draws the snow
//Draws the "trail"
if Dir > 0 then
begin
if (Quality >= Medium)
and (X > tpx)
and (X < tpx+(XdZ*2))
and (Y > tpy)
and (Y < tpy+(YdZ*2))
then
begin
glColor4f((1+Rs)/2,(1+Gs)/2,(1+Bs)/2, 0);
glVertex2f(X-tpx, Y-tpy);
glColor4f(1,1,1,0);
end;
//Drops snow
if (T[X,Y+Dir]=Sky) or (T[X,Y+Random(Dir)]=Sky) then
begin
if (Random(2) = 0) then
X := X+Random(Wind+1)-1 else
if (Random(2) = 0) then
X := X+Random(2)-Random(2);
Y := Y+Dir+Random(2);
end;
//Draws snow and tells how much is there in the sky
if (T[X,Y]=Sky) then
Inc(J)
else
begin
Dir := 0;
if random(5)=0 then
Y := Y+Random(4)-1;
end;
end;
if (X > tpx)
and (X < tpx+(XdZ*2))
and (Y > tpy)
and (Y < tpy+(YdZ*2))
then
glVertex2f(X-tpx, Y-tpy);
end;
//Deletes the duplicated snowflakes - and a lot of them...
// if (Length(Weather) >= MaxWeather-(MaxWeather div 10)-Random(MaxWeather div 5)) then
for L := 0 to 75 do
begin
I2 := 0;
repeat
J2 := Random(Length(Weather));
until Weather[J2].Dir = 0;
for I := 0 to Length(Weather)-1 do
with Weather[I] do
if Dir = 0 then
if (X = Weather[J2].X)
and (Y = Weather[J2].Y)
and (I <> J2) then
begin
Weather[I] := Weather[Length(Weather)-1];
repeat
J2 := Random(Length(Weather));
until Weather[J2].Dir = 0;
Inc(I2);
end;
SetLength(Weather, Length(Weather)-I2);
end;
//Makes sure there is enough snow in the sky
if (J < WeatherInTheSky) then
begin
if (Length(Weather)+(WeatherInTheSky-J) < MaxWeather) then
L := WeatherInTheSky-J
else
L := MaxWeather-Length(Weather);
SetLength(Weather, Length(Weather)+L);
for I := Length(Weather)-L-1 to Length(Weather)-1 do
with Weather[I] do
begin
repeat
X := Random(tX);
Y := Random(tY);
until (T[X,Y]=Sky);
Dir := Random(5)+1;
end;
end;
glEnd();
end;
end;
//end Particles
//PowerMeter
glBegin(GL_QUADS);
if CR[0].Pwr <> CR[0].OrgPwr then
begin
glColor4f(0, 0.5, 0, 0);
glVertex2f(10+(CR[0].Pwr / 4), 10);
glVertex2f(10+(CR[0].Pwr / 4), 20);
glVertex2f(10+(CR[0].OrgPwr / 4), 20);
glVertex2f(10+(CR[0].OrgPwr / 4), 10);
end;
glColor4f(1, 0, 0, 0);
glVertex2f(10, 10);
glVertex2f(10, 20);
glColor4f(0, 1, 0, 0);
glVertex2f(10+(CR[0].Pwr / 4), 20);
glVertex2f(10+(CR[0].Pwr / 4), 10);
glEnd();
//end PowerMeter
glEnable(GL_TEXTURE_2D);
Text(Round(CR[0].OrgPwr / 4)+30, 5, 'Kills:'+IntToStr(CR[0].Kills)+' Deaths:'+IntToStr(CR[0].Deaths), 20);
if (CR[0].myGun.Index > -1) and (Length(CR[0].myGunsI) > 0) then
begin
Text(10, 30, GN[CR[0].myGun.Index].Tip, 20);
if (dotTimeSince(CR[0].ClipTimer) < GN[CR[0].myGun.Index].ClipTime) then
Text(10, 55, 'Reloading', 16);
end;
if Pause then
Text(XdZ-(64 div 2)*Length('PAUSED'), YdZ-(64 div 2), 'PAUSED', 64);
if CR[0].Dead then
Text(XdZ-(100 div 2)*Length('DEAD'), YdZ-(100 div 2), 'DEAD', 100);
// Text(0, 350, IntToStr(Length(LGN)), 32);
// J := 0;
// if (CR[0].myGun <> -1) and (Length(CR[0].myGunsI) > 0) then
// for I := 0 to Length(CR)-1 do
// J := J + Length(CR[I].myGunsI);
// Text(0, 400, IntToStr(J), 32);
// Text(0, 450, IntToStr(J+Length(LGN)), 32);
if GameOver then
begin
if MapCnt >= Length(Maps) then
Text(XdZ-(85 div 2)*Length('GAME OVER'), YdZ-(85 div 2), 'GAME OVER', 85)
else
Text(XdZ-(60 div 2)*Length('STAGE CLEARED'), YdZ-(60 div 2), 'STAGE CLEARED', 60);
end;
// Text(0, 300, IntToStr(Round(FPSDisp)), 64);
// Text(0, 370, IntToStr(FPSundercount), 64);
// Text(0, 450, IntToStr(Length(PT)), 64);
glDisable(GL_TEXTURE_2D);
SwapBuffers(DC);
//Context.PageFlip;
if GameOver then
Sleep(1500);
end;
//Read this function at your own risk... its UGLY, non-commented, and tottaly random
procedure TGame.CreatureAI(var C: RCreature; Tg: RCreature);
var //Creature, its target
I, J: Integer;
label
Up;
begin
With C do
try
//The cheapest AI - not used
(* if AITip = 'Dumberer' then
if Random(AiL*3) = 0 then
if (X = eX)
and (Random(3) = 0) then
begin
if Random(2) = 0 then
Act := 'Right' else
Act := 'Left';
end else
if Random(AiL*4) = 0 then
begin
if Random(2) = 0 then
Act := 'Right' else
Act := 'Left';
end else
if (Tg.X > X) then
Act := 'Right' else
Act := 'Left';*)
try
//the new ai
if AITip = 'Dumberer' then
if Random(5)=0 then
begin
if Act <> 'Walk' then Act := '';
if (abs(Y-tg.Y) < 30+Random(18))
and (abs(X-tg.X) < XdZ+Random(20))
and (myGun.Index <> -1)
and (Random(5)=0) then
begin
Act := 'Shoot';
if tg.X > X then Dir := 1 else Dir := -1;
end else
if (X>30)
and (T[Trunc(X-Random(15)), Trunc(Y+(sY/1.5))]=Dirt) and (T[Trunc(X-Random(30)), Trunc(Y)]=Sky)
and (Air = False)
and (Random(8)=0) then
begin
Act := 'Jump';
Dir := -1;
end else
if (X>30)
and (T[Trunc(X+Random(15)), Trunc(Y+(sY/1.5))]=Dirt) and (T[Trunc(X+Random(30)), Trunc(Y)]=Sky)
and (Air = False)
and (Random(8)=0) then
begin
Act := 'Jump';
Dir := +1;
end else
if ((X > (Spd*2) div 4) and (Y > 15) and (X > 50))
and ((T[Trunc(X-Random((Spd*2) div 4)), Trunc(Y-Random(15))]=Dirt)
or (T[Trunc(X-Random((Spd*2) div 4)), Trunc(Y+(sY/2))]=Dirt)
or (T[Trunc(X-Random((Spd*2) div 4)), Trunc(Y+sY)]=Dirt))
and (T[Trunc(X-Random(40)), Trunc(Y+sY)]=Sky)
and (T[Trunc(X-Random(50)), Trunc(Y+(sY/2))]=Sky)
and (Air = False)
and (Random(4)=0) then
begin
Act := 'Jump';
Dir := -1;
end else
if ((X > (Spd*2) div 4) and (Y > 15) and (X > 50))
and ((T[Trunc(X+sX+Random((Spd*2) div 4)), Trunc(Y-Random(15))]=Dirt)
or (T[Trunc(X+sX+Random((Spd*2) div 4)), Trunc(Y+(sY/2))]=Dirt)
or (T[Trunc(X+sX+Random((Spd*2) div 4)), Trunc(Y+sY)]=Dirt))
and (T[Trunc(X+sX+Random(40)), Trunc(Y+sY)]=Sky)
and (T[Trunc(X+sX+Random(50)), Trunc(Y+(sY/2))]=Sky)
and (Air = False)
and (Random(4)=0) then
begin
Act := 'Jump';
Dir := 1;
end else
if (abs(Y-tg.Y) > 150)
and (((Random(5)=0)
and (X > tX/15)
and (X < (14*tX)/15))
or ((Random(7)=0)
and (X > tX/10)
and (X < (9*tX)/10))
or ((Random(15)=0)
and (X > tX/7)
and (X < (6*tX)/7)))
then
begin
if X < tX/3 then
Dir := -1
else if X > (2*tX)/3 then
Dir := 1;
if Random(30) = 0 then
Act := 'Jump'
else
Act := 'Walk';
end else
if (abs(X-eX) = 0)
and (Air = False)
and (Random(3)=0) then
begin
if Random(3)=0 then
Act := 'Jump';
if Random(4)=0 then
Dir := -Dir;
end else
if (abs(X-eX) < 3)
and (Air = False)
and (Random(5)=0) then
begin
if Random(4)=0 then
Act := 'Jump';
if Random(2)=0 then
Dir := -Dir;
end else
if (X > tg.X)
and (Random(2)=0) then
Dir := -1
else
if (X < tg.X)
and (Random(2)=0) then
Dir := 1;
if (Act = '')
or (Random(70)=0) then
begin
Act := 'Walk';
(* if (X > tg.X) then
Dir := -1
else
if (X < tg.X) then
Dir := 1;*)
end;
end;
except
end;
//The cheaper AI
if AITip = 'Dumber' then
if Random(AiL*3) = 0 then
if (Random(AiL) = 0)
and (X < Random(250)) then
begin
Act := 'Walk';
Dir := 1;
end else
if (Random(AiL) = 0)
and (X > tx-Random(250)) then
begin
Act := 'Walk';
Dir := -1;
end else
if (X>25) and (Y > 100)
and(((T[Round(X+25), Round(Y-99)]=Sky) and (T[Round(X+25), Round(Y-90)]=Dirt))
or ((T[Round(X+25), Round(Y-90)]=Sky) and (T[Round(X+25), Round(Y-80)]=Dirt))
or ((T[Round(X+20), Round(Y-80)]=Sky) and (T[Round(X+20), Round(Y-70)]=Dirt))
or ((T[Round(X+20), Round(Y-70)]=Sky) and (T[Round(X+20), Round(Y-60)]=Dirt))
or ((T[Round(X+20), Round(Y-60)]=Sky) and (T[Round(X+20), Round(Y-50)]=Dirt))
or ((T[Round(X+20), Round(Y-50)]=Sky) and (T[Round(X+20), Round(Y-40)]=Dirt))
or ((T[Round(X+20), Round(Y-40)]=Sky) and (T[Round(X+20), Round(Y-30)]=Dirt)))
and (Tg.Y+50 < Y)
and (Act = 'Walk')
and (Air = False) then
begin
Act := 'Jump';
if Random(2) = 0 then
Dir := 1
else
Dir := -1;
end else
if (X > 26) and (Y > 100) then
if (((T[Round(X-25), Round(Y-99)]=Sky) and (T[Round(X-25), Round(Y-90)]=Dirt))
or ((T[Round(X-25), Round(Y-90)]=Sky) and (T[Round(X-25), Round(Y-80)]=Dirt))
or ((T[Round(X-20), Round(Y-80)]=Sky) and (T[Round(X-20), Round(Y-70)]=Dirt))
or ((T[Round(X-20), Round(Y-70)]=Sky) and (T[Round(X-20), Round(Y-60)]=Dirt))
or ((T[Round(X-20), Round(Y-60)]=Sky) and (T[Round(X-20), Round(Y-50)]=Dirt))
or ((T[Round(X-20), Round(Y-50)]=Sky) and (T[Round(X-20), Round(Y-40)]=Dirt))
or ((T[Round(X-20), Round(Y-40)]=Sky) and (T[Round(X-20), Round(Y-30)]=Dirt)))
and (Act = 'Walk')
and (Tg.Y+50 < Y)
and (Air = False) then
begin
Act := 'Jump';
if Random(2) = 0 then
Dir := 1
else
Dir := -1;
end else
if (Random(AiL*7) = 0)
and (myGun.Index <> -1) then
Act := 'Shoot' else
if (X = eX)
and (Random(3) = 0) then
begin
if (Tg.X > X) then
begin
if (Air = False) then
Act := 'Jump';
if Random(2) = 0 then
Dir := 1
else
Dir := -1;
end else
begin
if (Air = False) then
Act := 'Jump';
if Random(2) = 0 then
Dir := 1
else
Dir := -1;
end;
end else
if (X > 40) then
if ((T[Round(X-15), Round(Y+20)]=Sky) and (T[Round(X-40), Round(Y+20)]=Dirt))
and (Act = 'Walk')
and (Tg.Y+50 < Y)
and (Air = False) then
begin
Act := 'Jump';
Dir := -1;
end else
if ((T[Round(X+15), Round(Y+20)]=Sky) and (T[Round(X+40), Round(Y+20)]=Dirt))
and (Act = 'Walk')
and (Tg.Y+50 < Y)
and (Air = False) then
begin
Act := 'Jump';
Dir := 1;
end else
if (Random(AiL*2) = 0)
and (myGun.Index <> -1) then
begin
Repeat
TgIndex := Random(Length(CR));
Until (CR[TgIndex].Name <> Name);
if X < CR[TgIndex].X then Dir := +1 else
if X > CR[TgIndex].X then Dir := -1;
end else
if Random(AiL*4) = 0 then
begin
Act := 'Walk';
if Random(2) = 0 then
Dir := 1
else
Dir := -1;
end else
if (Tg.X > X) then
begin
Act := 'Walk';
if Random(2) = 0 then
Dir := 1
else
Dir := -1;
end;
//The little better AI
if (AITip = 'Dumb')
and (Random(AiL*2) = 0) then
if (Random(AiL*4) = 0)
and (X < Random(150)) then
begin
Act := 'Walk';
Dir := 1;
end else
if (Random(AiL*4) = 0)
and (X > tx-Random(150)) then
begin
Act := 'Walk';
Dir := -1;
end else
if (Random(AiL*10) = 0)
and (myGun.Index <> -1) then
Act := 'Shoot' else
if (Random(AiL*7) = 0) then
Act := 'Jump' else
if (Tg.Y+sY < Y)
and (Air = False)
and (Random(AiL) = 0) then
begin
For I := Round(X-50) to Round(X+sX+50) do
For J := Round(Y-150) to Round(Y) do
if (X > 52) and (Y > 152)
and (X < tx-sx-52) and (Y < ty) then
if (T[I, J]=Sky)
and (T[I-1, J+1]=Dirt)
and (T[I-1, J+2]=Dirt)
and (T[I-5, J+1]=Dirt)
and (T[I-5, J+2]=Dirt)
and (T[I, J+1]=Dirt)
and (T[I, J+2]=Dirt)
and (T[I+1, J+1]=Sky)
and (T[I+1, J+2]=Sky)
and (T[I+5, J+1]=Sky)
and (T[I+5, J+2]=Sky)
then
begin
Act := 'Jump';
if I > X+sX then
begin
Act := 'Walk';
Dir := 1;
end else
if I < X then
begin
Act := 'Walk';
Dir := -1;
end else
if Random(2) = 0 then
begin
Act := 'Walk';
if Random(2) = 0 then
Dir := 1
else
Dir := -1;
end;
end;
end else
if (Random(AiL*2) = 0)
and (myGun.Index <> -1) then
begin
if X < CR[TgIndex].X then Dir := +1 else
if X > CR[TgIndex].X then Dir := -1;
if (X < CR[TgIndex].X+1000)
and (X > CR[TgIndex].X-1000)
and (Y < CR[TgIndex].Y+300)
and (Y > CR[TgIndex].Y-300)
then
Act := 'Shoot';
end else
if ((X = eX) and (Act <> 'Shoot') and (Random(AiL) = 0))
or ((X = eX) and (Act = 'Shoot') and (Random(AiL*6) = 0)) then
begin
if (Tg.X > X) then
begin
if (Air = False) then
Act := 'Jump';
if Random(2) = 0 then
Dir := -1
else
Dir := +1;
end else
begin
if (Air = False) then
Act := 'Jump';
if Random(2) = 0 then
Dir := -1
else
Dir := +1;
end;
end else
if ((T[Round(X+15), Round(Y+20)]=Sky) and (T[Round(X+40), Round(Y+20)]=Dirt))
and (Act = 'Walk')
and (Tg.Y+50 < Y)
and (Air = False) then
begin
Act := 'Jump';
Dir := +1;
end else
if (X > 50) and (Y > 75) then
if ((T[Round(X-15), Round(Y+20)]=Sky) and (T[Round(X-40), Round(Y+20)]=Dirt))
and (Act = 'Walk')
and (Tg.Y+50 < Y)
and (Air = False) then
begin
Act := 'Jump';
Dir := -1;
end else
if Random(AiL*3) = 0 then
begin
if Random(2) = 0 then
begin
Act := 'Walk';
if Random(2) = 0 then
Dir := 1
else
Dir := -1;
end;
end else
if (Tg.X > X) then
begin
Act := 'Walk';
if Random(2) = 0 then
Dir := 1
else
Dir := -1;
end;
if (Random(AiL*5) = 0)
and (HitBy <> 0) then
begin
TgIndex := HitBy;
HitBy := 0;
if X < CR[TgIndex].X then Dir := +1 else
if X > CR[TgIndex].X then Dir := -1;
Act := 'Shoot';
end;
if (Act = 'Shoot') and (Random(AiL*3) = 0) then
begin
if X < CR[TgIndex].X then Dir := +1 else
if X > CR[TgIndex].X then Dir := -1;
end else
if Act = 'Jump' then
begin
g := 15;
Y := Y - Round(g);
Air := True;
Act := 'Walk';
end;
eX := X;
if (dotTimeSince(DeadT) < 7000)
and (Act = 'Shoot') then
Act := 'Walk';
except
end;//With C
//Result := C;
end;
//One of the main procedures in this game... calculates movement, collision detection, gravity
procedure TGame.Calculate;
var
I, I2, J, J2, LGCnt, Counter, LG, X, Y, L: Integer;
bool: Boolean;
label
GoOut;
begin//Calculate
//Gun Calculate
if Length(LGN) > 0 then
For L := 0 to Length(LGN)-1 do
With GN[LGN[L].Index] do
if (LGN[L].Air) then
begin
X := LGN[L].X;
Y := LGN[L].Y;
if (T[ X, Y] = False)
or (T[ X, Y+(sY div 4)] = False)
or (T[ X, Y+(sY div 2)] = False)
or (T[ X, Y+(sY div 2)+(sY div 4)] = False)
then
repeat
X := X + 1;
until (T[ X, Y])
and (T[ X, Y+(sY div 4)])
and (T[ X, Y+(sY div 2)])
and (T[ X, Y+(sY div 2)+(sY div 4)]);
if (T[ X+sX, Y] = False)
or (T[ X+sX, Y+(sY div 4)] = False)
or (T[ X+sX, Y+(sY div 2)] = False)
or (T[ X+sX, Y+(sY div 2)+(sY div 4)] = False)
then
repeat
X := X - 1;
until (T[ X+sX, Y])
and (T[ X+sX, Y+(sY div 4)])
and (T[ X+sX, Y+(sY div 2)])
and (T[ X+sX, Y+(sY div 2)+(sY div 4)]);
if (T[ X, Y+sY] = False)
or (T[ X+(sX div 4), Y+sY] = False)
or (T[ X+(sX div 2), Y+sY] = False)
or (T[ X+(sX div 2)+(sX div 4), Y+sY] = False)
or (T[ X+sX, Y+sY] = False)
then
repeat
Y := Y - 1;
LGN[L].Air := False;
if (T[ X, Y+sY])
and (T[ X+(sX div 4), Y+sY])
and (T[ X+(sX div 2), Y+sY])
and (T[ X+(sX div 2)+(sX div 4), Y+sY])
and (T[ X+(sX), Y+sY])
then LGN[L].Air := True;
until (T[ X, Y+sY])
and (T[ X+(sX div 4), Y+sY])
and (T[ X+(sX div 2), Y+sY])
and (T[ X+(sX div 2)+(sX div 4), Y+sY])
and (T[ X+sX, Y+sY]);
if ((T[ X, Y+sY])
or (T[ X+(sX div 4), Y+sY])
or (T[ X+(sX div 2), Y+sY])
or (T[ X+(sX div 2)+(sX div 4), Y+sY])
or (T[ X+(sX), Y+sY]))
then
begin
LGN[L].g := LGN[L].g - 2;
Y := Y - LGN[L].g;
end;
if (T[ X, Y+sY] = False)
or (T[ X+(sX div 4), Y+sY] = False)
or (T[ X+(sX div 2), Y+sY] = False)
or (T[ X+(sX div 2)+(sX div 4), Y+sY] = False)
or (T[ X+sX, Y+sY] = False)
then
repeat
Y := Y - 1;
LGN[L].Air := False;
until (T[ X, Y+sY])
and (T[ X+(sX div 4), Y+sY])
and (T[ X+(sX div 2), Y+sY])
and (T[ X+(sX div 2)+(sX div 4), Y+sY])
and (T[ X+sX, Y+sY]);
For I := X to X+sX do
if (T[ I, Y+sY] = False) then
begin
LGN[L].g := 0;
LGN[L].Air := False;
end;
LGN[L].X := X;
LGN[L].Y := Y;
end;
//end Gun Calculate
//Kreature Calculate
For L := 0 to Length(CR)-1 do
if CR[L].Dead = False then
begin
try
if (CR[CR[L].TgIndex].Dead)
or ((CR[L].TgIndex <> 0)
and (Random(75) = 0)) then
Repeat
CR[L].TgIndex := Random(Length(CR));
Until (CR[CR[L].TgIndex].Name <> CR[L].Name)
and (CR[CR[L].TgIndex].Dead = False);
if (CR[L].Pwr > 0) and (CR[L].Dead = False) then
begin
if (Loading = False) then
begin
//Weapon pick up routine
if (Length(LGN) > 0)
and (Length(CR[L].myGunsI) < Length(GN)) then
repeat
bool := False;
Lg := 0;
for I := 0 to Length(LGN)-1 do
if (abs(CR[L].X-LGN[I].X) < CR[L].sX+GN[LGN[I].Index].sX)
and (abs(CR[L].Y-LGN[I].Y) < CR[L].sY+GN[LGN[I].Index].sY) then //fast check if the gun is even close to the creature
if (OwnedAlready(LGN[I].Index, L) = False) then //and if its already owned by the creature
if ((CR[L].X < LGN[I].X) //then the slow check
and (CR[L].X+CR[L].sX > LGN[I].X)
and (CR[L].Y < LGN[I].Y)
and (CR[L].Y+CR[L].sY > LGN[I].Y))
or ((CR[L].X > LGN[I].X)
and (CR[L].X+CR[L].sX < LGN[I].X)
and (CR[L].Y > LGN[I].Y)
and (CR[L].Y+CR[L].sY < LGN[I].Y))
or ((CR[L].X < LGN[I].X+GN[LGN[I].Index].sX)
and (CR[L].X+CR[L].sX > LGN[I].X+GN[LGN[I].Index].sX)
and (CR[L].Y < LGN[I].Y+GN[LGN[I].Index].sY)
and (CR[L].Y+CR[L].sY > LGN[I].Y+GN[LGN[I].Index].sY))
or ((CR[L].X > LGN[I].X+GN[LGN[I].Index].sX)
and (CR[L].X+CR[L].sX < LGN[I].X+GN[LGN[I].Index].sX)
and (CR[L].Y > LGN[I].Y+GN[LGN[I].Index].sY)
and (CR[L].Y+CR[L].sY < LGN[I].Y+GN[LGN[I].Index].sY))
or ((CR[L].X < LGN[I].X+(GN[LGN[I].Index].sX div 2))
and (CR[L].X+CR[L].sX > LGN[I].X+(GN[LGN[I].Index].sX div 2))
and (CR[L].Y < LGN[I].Y+(GN[LGN[I].Index].sY div 2))
and (CR[L].Y+CR[L].sY > LGN[I].Y+(GN[LGN[I].Index].sY div 2)))
or ((CR[L].X > LGN[I].X+(GN[LGN[I].Index].sX div 2))
and (CR[L].X+CR[L].sX < LGN[I].X+(GN[LGN[I].Index].sX div 2))
and (CR[L].Y > LGN[I].Y+(GN[LGN[I].Index].sY div 2))
and (CR[L].Y+CR[L].sY < LGN[I].Y+(GN[LGN[I].Index].sY div 2)))
then
with CR[L] do
begin
SetLength(myGunsI, Length(myGunsI)+1);
myGunsI[Length(myGunsI)-1].Index := LGN[I].Index;
myGunsI[Length(myGunsI)-1].Clip := GN[LGN[I].Index].ClipSize;
ShootI := dotTime;
//@TODO move this bit to AI probably
if ((Name <> 'User')
and (Random(15) = 0))
or (myGun.Index = -1) then
myGun := myGunsI[Length(myGunsI)-1];
if Length(myGunsI) > 1 then
for J2 := 0 to Length(myGunsI)*2 do
for J := 0 to Length(myGunsI)-2 do
if MyGunsI[J].Index > MyGunsI[J+1].Index then
begin
I2 := MyGunsI[J].Index;
MyGunsI[J].Index := MyGunsI[J+1].Index;
MyGunsI[J+1].Index := I2;
end;
LGN[I] := LGN[Length(LGN)-1-Lg];
Inc(Lg);
bool := True;
end;
if bool then
SetLength(LGN, Length(LGN)-Lg);
until bool = False;
//Weapon Shooting
if (Length(CR[L].myGunsI) > 0) and (CR[L].myGun.Index > -1) then
if (((KP and (CR[L].Act = 'Shoot')) or (MP and (CR[L].ActM = 'Shoot'))) and (CR[L].Name = 'User'))
or (((CR[L].Act = 'Shoot') and (CR[L].Name <> 'User'))) then
if (dotTimeSince(CR[L].ClipTimer)) > (GN[CR[L].myGun.Index].ClipTime) then
if (dotTimeSince(CR[L].ShootI)) > ((GN[CR[L].myGun.Index].Interval)+Random(GN[CR[L].myGun.Index].Interval div 4)-Random(GN[CR[L].myGun.Index].Interval div 4)) then
begin
if GN[CR[L].myGun.Index].TT = 'ShotGun' then
begin
for I := 0 to 5+Random(5) do
begin
SetLength(BL, Length(BL)+1);
With BL[Length(BL)-1] do
begin
Typ := GN[CR[L].myGun.Index].Tip;
Dir := CR[L].Dir;
Case CR[L].Dir of
+1: X := Round(CR[L].X)+GN[CR[L].myGun.Index].sX;
-1: X := Round(CR[L].X)+CR[L].sX-GN[CR[L].myGun.Index].sX;
end;
Y := Round(CR[L].Y)+GN[CR[L].myGun.Index].pY+(GN[CR[L].myGun.Index].sY div 2)+Random(3)-Random(3);
Owner.Name := CR[L].Name;
Owner.Index := CR[L].Index;
Owner.HisGun := CR[L].myGun;
Dmg := GN[CR[L].myGun.Index].Dmg div 5;
TT := GN[CR[L].myGun.Index].TT;
ET := GN[CR[L].myGun.Index].ET;
DirY := I-Random(8);
CR[L].ShootI := dotTime;
end;
end;
Dec(CR[L].myGun.Clip);
if (CR[L].myGun.Clip <= 0) then
begin
CR[L].ClipTimer := dotTime;
CR[L].myGun.Clip := GN[CR[L].myGun.Index].ClipSize;
end;
end else
begin
SetLength(BL, Length(BL)+1);
With BL[Length(BL)-1] do
begin
Typ := GN[CR[L].myGun.Index].Tip;
Dir := CR[L].Dir;
Case CR[L].Dir of
+1: X := Round(CR[L].X)+GN[CR[L].myGun.Index].sX;
-1: X := Round(CR[L].X)+CR[L].sX-GN[CR[L].myGun.Index].sX;
end;
Y := Round(CR[L].Y)+GN[CR[L].myGun.Index].pY+(GN[CR[L].myGun.Index].sY div 2)+Random(3)-Random(3);
Owner.Name := CR[L].Name;
Owner.Index:= CR[L].Index;
Owner.HisGun := CR[L].myGun;
Dmg := GN[CR[L].myGun.Index].Dmg;
TT := GN[CR[L].myGun.Index].TT;
ET := GN[CR[L].myGun.Index].ET;
CR[L].ShootI := dotTime;
Dec(CR[L].myGun.Clip);
if (CR[L].myGun.Clip <= 0) then
begin
CR[L].ClipTimer := dotTime;
CR[L].myGun.Clip := GN[CR[L].myGun.Index].ClipSize;
end;
end;
end;
end;
//end Weapon Shooting
//Moving
if (dotTimeSince(CR[L].PicT) > CR[L].PicInt)
and (CR[L].PicShowStyle = 1) then
begin
CR[L].PicT := dotTime;
if CR[L].Pic >= CR[L].PicN then
CR[L].Pic := 0;
Inc(CR[L].Pic);
end else
if (dotTimeSince(CR[L].PicT) > CR[L].PicInt)
and (CR[L].Spd > 5)
then
begin
CR[L].PicT := dotTime;
Inc(CR[L].Pic);
if CR[L].Pic >= CR[L].PicN then
CR[L].Pic := 1;
if (CR[L].Spd < 5)
and (CR[L].PicShowStyle = 0) then
CR[L].Pic := 1;
end else
if (CR[L].Spd < 5)
and (CR[L].Pic <> CR[L].MainPic) then
begin
CR[L].Pic := CR[L].MainPic;
end;
if (CR[L].Act = 'Walk') then
with CR[L] do
begin
X := X + (Spd*0.04)*Dir;
end else if (CR[L].Name = 'User') then
CR[L].Spd := 0;
//end Moving
end;//not Loading
//Terrain collision-detection
X := Round(CR[L].X);
Y := Round(CR[L].Y);
for I := 1 to 25 do
begin
if (T[ X+(CR[L].sX)+1, Y] = False)
or (T[ X+(CR[L].sX)+1, Y+(CR[L].sY div 4)] = False)
or (T[ X+(CR[L].sX)+1, Y+(CR[L].sY div 2)] = False)
then
X := X-1;
if (T[ X-1, Y] = False)
or (T[ X-1, Y+(CR[L].sY div 4)] = False)
or (T[ X-1, Y+(CR[L].sY div 2)] = False)
then
X := X+1;
if (T[ X+((CR[L].sX) div 2), Y] = False) then
Y := Y+1;
end;
Counter := 0;
if (T[ X, Y+CR[L].sY] = False)
or (T[ X+(CR[L].sX div 4), Y+CR[L].sY] = False)
or (T[ X+(CR[L].sX div 2), Y+CR[L].sY] = False)
or (T[ X+(CR[L].sX div 2)+(CR[L].sX div 4), Y+CR[L].sY] = False)
or (T[ X+CR[L].sX, Y+CR[L].sY] = False)
then
repeat
Y := Y - 1;
CR[L].Air := False;
if CR[L].Air = False then CR[L].g := -5;
Inc(Counter);
until ((T[ X, Y+CR[L].sY])
and (T[ X+(CR[L].sX div 4), Y+CR[L].sY])
and (T[ X+(CR[L].sX div 2), Y+CR[L].sY])
and (T[ X+(CR[L].sX div 2)+(CR[L].sX div 4), Y+CR[L].sY])
and (T[ X+CR[L].sX, Y+CR[L].sY]))
or (Counter > 100000);
if (T[ X, Y+CR[L].sY])
or (T[ X+(CR[L].sX div 4), Y+CR[L].sY])
or (T[ X+(CR[L].sX div 2), Y+CR[L].sY])
or (T[ X+(CR[L].sX div 2)+(CR[L].sX div 4), Y+CR[L].sY])
or (T[ X+CR[L].sX, Y+CR[L].sY])
then
begin
CR[L].g := CR[L].g - 2;
LG := Y;
if CR[L].g < 0 then
LGcnt := 1 else
LGcnt := -1;
repeat
Y := Y + LGcnt;
if (T[ X, Y+CR[L].sY ] = False)
or (T[ X+(CR[L].sX div 4), Y+CR[L].sY ] = False)
or (T[ X+(CR[L].sX div 2), Y+CR[L].sY ] = False)
or (T[ X+(CR[L].sX div 2)+(CR[L].sX div 4), Y+CR[L].sY ] = False)
or (T[ X+CR[L].sX, Y+CR[L].sY ] = False)
then
begin
CR[L].Air := False;
LGcnt := 2;
end;
until (Y = LG - CR[L].g)
or (LGcnt = 2);
if (T[ X+(CR[L].sX div 4), Y+1] = False)
or (T[ X+(CR[L].sX div 2), Y ] = False)
or (T[ X+(CR[L].sX div 2)+(CR[L].sX div 4), Y+1] = False)
then
begin
if (CR[L].g > 0) then
CR[L].g := -CR[L].g+(CR[L].g div 3);
for I := 1 to 50 do
if (T[ X+(CR[L].sX div 4), Y+1] = False)
or (T[ X+(CR[L].sX div 2), Y ] = False)
or (T[ X+(CR[L].sX div 2)+(CR[L].sX div 4), Y+1] = False)
then
Y := Y+1;
end;
if (T[ X+(CR[L].sX div 4), Y+CR[L].sY])
and (T[ X+(CR[L].sX div 2), Y+CR[L].sY])
and (T[ X+(CR[L].sX div 2)+(CR[L].sX div 4), Y+CR[L].sY])
then CR[L].Air := True;
if CR[L].Air = False then CR[L].g := -5;
end;
Counter := 0;
if (T[ X, Y+CR[L].sY] = False)
or (T[ X+(CR[L].sX div 4), Y+CR[L].sY] = False)
or (T[ X+(CR[L].sX div 2), Y+CR[L].sY] = False)
or (T[ X+(CR[L].sX div 2)+(CR[L].sX div 4), Y+CR[L].sY] = False)
or (T[ X+CR[L].sX, Y+CR[L].sY] = False)
then
repeat
Y := Y - 1;
CR[L].Air := False;
if CR[L].Air = False then CR[L].g := -5;
Inc(Counter)
until ((T[ X, Y+CR[L].sY])
and (T[ X+(CR[L].sX div 4), Y+CR[L].sY])
and (T[ X+(CR[L].sX div 2), Y+CR[L].sY])
and (T[ X+(CR[L].sX div 2)+(CR[L].sX div 4), Y+CR[L].sY])
and (T[ X+CR[L].sX, Y+CR[L].sY]))
or (Counter > 100000);
if (T[ X+(CR[L].sX div 4), Y+1] = False)
or (T[ X+(CR[L].sX div 2), Y ] = False)
or (T[ X+(CR[L].sX div 2)+(CR[L].sX div 4), Y+1] = False)
then
begin
if (CR[L].g > 0) then
CR[L].g := -CR[L].g+(CR[L].g div 3);
for I := 1 to 50 do
if (T[ X+(CR[L].sX div 4), Y+1] = False)
or (T[ X+(CR[L].sX div 2), Y ] = False)
or (T[ X+(CR[L].sX div 2)+(CR[L].sX div 4), Y+1] = False)
then
Y := Y+1;
if CR[L].Air = False then CR[L].g := -5;
end;
CR[L].X := X;
CR[L].Y := Y;
if (Loading = False) then
begin
//Creatures Bleed
if (CR[L].Pwr < CR[L].OrgPwr/6) then
begin
P_Blood( CR[L].X+(CR[L].sX div 2), CR[L].Y+(CR[L].sY div 2), ((200 div CR[L].Pwr)+25) div 2, Random(3)+2, 0);
if Random(2) = 0 then
CR[L].Pwr := CR[L].Pwr - 1;
CR[L].Spd := CR[L].Pwr;
end;
//end Creatures Bleed
//AI
if (CR[L].Name <> 'User') then CreatureAI(CR[L], CR[CR[L].TgIndex]);
//end AI
end;
end else
if (CR[L].Dead = False) and (Loading = False) then
begin
//Respawn
//Makes particle effects when someone gets killed
if Part then
begin
//Some blood
if CR[L].X > CR[CR[L].HitBy].X then
J2 := 1
else
J2 := -1;
P_Blood(Random(CR[L].sX)+CR[L].X, Random(CR[L].sY)+CR[L].Y, 300, 25, J2);
P_Blood(CR[L].X+(CR[L].sX div 2), CR[L].Y+(CR[L].sY div 2), 100, 10, 0);
P_Blood(CR[L].X+(CR[L].sX div 2), CR[L].Y+(CR[L].sY div 2), 65, 20, J2);
//A small explosion
P_Explode(CR[L].X+(CR[L].sX div 2), CR[L].Y+(CR[L].sY div 2), 'Tiny');
//And a effect, to dissolve a killed creature
// if Quality <> 'Low' then
P_Dissolve(L);
end;
//end particle effects
//Drops weapons
if Length(CR[L].myGunsI) > 0 then
for J2 := 0 to Length(CR[L].myGunsI)-1 do
begin
J := Length(LGN);
SetLength(LGN, Length(LGN)+1);
LGN[J].Index := CR[L].myGunsI[J2].Index;
LGN[J].X := -Random(5)+Round(CR[L].X+((CR[L].sX-((CR[L].sX+GN[LGN[J].Index].sX) div 2))));
LGN[J].Y := -Random(5)+Round(CR[L].Y+GN[LGN[J].Index].pY);
LGN[J].Air := True;
LGN[J].g := 5;
LGN[J].Dir := CR[L].Dir;
end;
SetLength(CR[L].myGunsI, 0);
CR[L].myGun.Index := -1;
if (CR[L].HitBy <> 0) then//if a monster hit another monster, it reappears
begin
if L = 0 then //if its djuk, make the DEAD sign
with CR[0] do
begin
Dead := True;
Draw;
Sleep(650);
eX := RP[0].X;
J2 := 0;
For I := 1 to RespawnPointCount-1 do
if (abs(RP[I].X-X) > abs(eX-X)) or (Random(17)=5)then
begin
eX := RP[I].X;
J2 := I;
end;
// J2 := Random(RespawnPointCount);
CR[L].X := RP[J2].X-(CR[L].sX div 2);
CR[L].Y := RP[J2].Y-(CR[L].sY div 2);
CR[L].eX := CR[L].X+1;
CR[L].eY := CR[L].Y+1;
CR[L].g := 0;
CR[L].Air := True;
CR[L].Spd := Random(CR[L].OrgSpd div 2) + (CR[L].OrgSpd div 2);
CR[L].Pwr := CR[L].OrgPwr;
CR[L].Deaths := CR[L].Deaths + 1;
if CR[L].X < CR[CR[L].TgIndex].X then CR[L].Dir := +1 else
if CR[L].X > CR[CR[L].TgIndex].X then CR[L].Dir := -1;
if X < XdZ then
TpX := 0
else
TpX := Round(X)-XdZ;
if Y < YdZ then
tpY := 0
else
TpY := Round(Y)-YdZ;
P_Dissolve(L);
Draw;
Sleep(100);
Dead := False;
DeadT := dotTime;
end else
begin
J2 := Random(RespawnPointCount);
CR[L].X := RP[J2].X-(CR[L].sX div 2);
CR[L].Y := RP[J2].Y-(CR[L].sY div 2);
CR[L].eX := CR[L].X+1;
CR[L].eY := CR[L].Y+1;
CR[L].g := 0;
CR[L].Air := True;
CR[L].Spd := Random(CR[L].OrgSpd div 2) + (CR[L].OrgSpd div 2);
CR[L].Pwr := CR[L].OrgPwr;
CR[L].Deaths := CR[L].Deaths + 1;
if CR[L].X < CR[CR[L].TgIndex].X then CR[L].Dir := +1 else
if CR[L].X > CR[CR[L].TgIndex].X then CR[L].Dir := -1;
P_Dissolve(L);
Repeat
CR[L].TgIndex := Random(Length(CR));
Until (CR[CR[L].TgIndex].Name <> CR[L].Name)
and (CR[CR[L].TgIndex].Dead = False);
end;
end else
if (L <> 0) and (CR[L].HitBy = 0) then // .... Djuk shot some monster, add to score and kill the monster once and for all
begin
CR[L].Dead := True;
CR[0].Kills := CR[0].Kills+1;
end;
//end Respawn
end;
except
raise exception.Create('Error #1');
CR[L].X := CR[L].eX;
CR[L].Y := CR[L].eY;
Exit;
end;
CR[L].eX := CR[L].X;
CR[L].eY := CR[L].Y;
end;
//end Kreature Calculate
//Bullets Calculate
if Length(BL) > 0 then
For I := 0 to Length(BL)-1 do
With BL[I] do
if Typ <> '' then
begin
// For J := 0 to Spd div 4 do
repeat
if T[ X, Y ] then
begin
if (X >= tX)
or (X <= 0) then
begin
Typ := '';
goto GoOut;
end;
if GN[Owner.HisGun.Index].TT = 'ShotGun' then
J := 4 else
J := 10;
//Makes the trail particles
if (Part)
and (X > tpx-15)
and (X < tpx+(XdZ*2)+15)
and (Y > tpy-15)
and (Y < tpy+(YdZ*2)+15) then
for I2 := 1 to J do
if (Random(2) = 1) then
begin
SetLength(PT, Length(PT)+1);
PT[Length(PT)-1].Dir := Dir;
PT[Length(PT)-1].X := X+I2;
PT[Length(PT)-1].Y := Y+Random(2)-Random(2);
if Random(4)=0 then
PT[Length(PT)-1].g := 0.1*(I2+1)
else
PT[Length(PT)-1].g := -0.1*(I2+1);
PT[Length(PT)-1].Tip := Bullet;
PT[Length(PT)-1].Clr := 5;
end;
//Moves the bullet 8px (noone is thiner, so there is no need for more precision)
if GN[Owner.HisGun.Index].TT = 'ShotGun' then
begin
Y := Y + Random(DirY);
if DirY > 0 then
DirY := DirY-Random(2)
else if DirY < 0 then
DirY := DirY+Random(2)
end else
if Random(2) = 1 then
Y := Y + Random(2) - Random(2);
X := X + (Dir*8);
For I2 := 0 to Length(CR)-1 do
if (CR[I2].Dead = False) then
if (Owner.Name <> CR[I2].Name) then //Disables friendly fire
if (Y > CR[I2].Y)
and (Y < CR[I2].Y+CR[I2].sY)
and (X > CR[I2].X)
and (X < CR[I2].X+CR[I2].sX) then
begin
CR[I2].HitBy := Owner.Index;
CR[I2].Pwr := CR[I2].Pwr-Dmg+Random(30)-Random(30);
if (CR[I2].Pwr <= 0) then
CR[I2].Pwr := -1
else
begin
P_Blood(X+Random(5)-Random(5), Y+Random(5)-Random(5), 50+Random(25)-Random(10), 3, Dir);
CR[I2].X := CR[I2].X+(Random(Dmg div 25)*Dir);
end;
Typ := '';
Break;
end;
end;
if X < 0 then X := 0;
if X > tX then X := tX;
if Y < 0 then Y := 0;
if Y > tY then Y := tY;
until (Typ = '') or (T[ X, Y ] = False);
GoOut:
P_Explode(X, Y, ET);
end;
SetLength(BL, 0);
//end Bullet Calculate
//Moves the view, so the player is in the middle of screen
//@TODO: make it not so sudden
if CR[0].X < XdZ then
TpX := 0
else
TpX := Round(CR[0].X)-XdZ;
if CR[0].Y < YdZ then
tpY := 0
else
TpY := Round(CR[0].Y)-YdZ;
//Stops player, if no button is pressed, or his speed is low
//@TODO does this cause bleeding stops?
if (CR[0].Name='User') and ((KP = False) or (CR[0].Spd < 5)) then
CR[0].Spd := 0;
//if everybody dies, its gameover or stage cleared
GameOver := True;
for I := 1 to Length(CR)-1 do
if CR[I].Dead = False then
GameOver := False;
if GameOver then
begin
Draw;
LoadMap;
end;
end;//Calculate
procedure TGame.LoadMap;
var
I, J, I2, J2, cnt: Integer;
Fo: File of Integer;
bool: Boolean;
label
TryAgain;
begin
Loading := True;
Gameover := False;
if MapCnt >= Length(Maps) then
begin
Excape := True;
Exit;
end;
cnt := 0;
SetLength(Poly1, 0);
SetLength(Poly2, 0);
AssignFile(FO, 'data/Terrain/'+Maps[MapCnt]+'/1.pmp');
Reset(FO);
Read(FO, tx);
Read(FO, ty);
I := 0;
repeat
SetLength(Poly1, I+1);
Read(FO, Poly1[I].X);
Read(FO, Poly1[I].Y);
Inc(I);
until eof(FO);
CloseFile(FO);
if FileExists('data/Terrain/'+Maps[MapCnt]+'/2.pmp') then
begin
AssignFile(FO, 'data/Terrain/'+Maps[MapCnt]+'/2.pmp');
Reset(FO);
Read(FO, I);
Read(FO, J);
if I > tx then tx := I;
if J > ty then ty := J;
I := 0;
repeat
SetLength(Poly2, I+1);
Read(FO, Poly2[I].X);
Read(FO, Poly2[I].Y);
Inc(I);
until eof(FO);
CloseFile(FO);
end;
SetLength(T, 0);
Setlength(T, tx*2, ty*2);
SetLength(TmB, 0);
SetLength(TmB, (XdZ*2)*(YdZ*2));
glClearColor(0, 0, 0, 0);
glClear(GL_COLOR_BUFFER_BIT);
glBindTexture(GL_TEXTURE_2D, LIndex); //The Loading pic
glLoadIdentity;
//Map Tracing (Drawing the polygons, making a mask out of them)
//The code for map tracing has to be done differently on ATi cards
if (glGetString(GL_VENDOR) = 'ATI Technologies Inc.') then
begin
J2 := 0;
repeat
I2 := 0;
Inc(J2);
repeat
Inc(I2);
glClear(GL_COLOR_BUFFER_BIT);
glTranslatef(-(I2-1)*XdZ*2, -(J2-1)*YdZ*2, 0);
glColor4f(1, 1, 1, 0);
glBegin(GL_POLYGON);
for I := 0 to Length(Poly1)-1 do
if Poly1[I].X = -1 then
begin
glend;
glBegin(GL_POLYGON);
end else
glVertex2f(Poly1[I].X, Poly1[I].Y);
glend;
if Length(Poly2) > 0 then
begin
glColor4f(0, 0, 0, 0);
glBegin(GL_POLYGON);
for I := 0 to Length(Poly2)-1 do
if Poly2[I].X = -1 then
begin
glend;
glBegin(GL_POLYGON);
end else
glVertex2f(Poly2[I].X, Poly2[I].Y);
glend;
end;
glFinish;
glReadPixels(0, 0, XdZ*2, YdZ*2, GL_RGBA, GL_UNSIGNED_BYTE, @TmB[0]);
for I := 0 to XdZ*2-1 do
for J := 0 to YdZ*2-1 do
if (I+((I2-1)*XdZ*2) < tx)
and ((YdZ*2-J)+((J2-1)*YdZ*2) < ty) then
begin
if (TmB[I+(J*XdZ*2)] <> 0) then
T[ I+((I2-1)*XdZ*2), (YdZ*2-J)+((J2-1)*YdZ*2) ] := True
else
T[ I+((I2-1)*XdZ*2), (YdZ*2-J)+((J2-1)*YdZ*2) ] := False;
end;
//Loading Fadein effect
cnt := cnt+1;
glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity;
glEnable(GL_TEXTURE_2D);
glColor4f(cnt/((tx/XdZ)*(ty/YdZ)), cnt/((tx/XdZ)*(ty/YdZ)), cnt/((tx/XdZ)*(ty/YdZ)), 1);
glBegin(GL_QUADS);
glTexCoord2f(0, 0);
glVertex2f (XdZ-256, YdZ-64);
glTexCoord2f(0, 1);
glVertex2f (XdZ-256, YdZ+64);
glTexCoord2f(1, 1);
glVertex2f (XdZ+256, YdZ+64);
glTexCoord2f(1, 0);
glVertex2f (XdZ+256, YdZ-64);
glend;
SwapBuffers(DC);
//Context.PageFlip;
glDisable(GL_TEXTURE_2D);
until (XdZ*(I2+1) > tx);
until (YdZ*(J2+1) > ty);
end else //Map tracing for cards other than ATi
begin
glClearColor(0.5, 0.5, 0.5, 0);
J2 := 0;
repeat
I2 := 0;
Inc(J2);
repeat
Inc(I2);
glClear(GL_COLOR_BUFFER_BIT);
glTranslatef(-(I2-1)*XdZ*2, -(J2-1)*YdZ*2, 0);
glColor4f(1, 1, 1, 0);
glBegin(GL_POLYGON);
for I := 0 to Length(Poly1)-1 do
if Poly1[I].X = -1 then
begin
glend;
glBegin(GL_POLYGON);
end else
glVertex2f(Poly1[I].X, Poly1[I].Y);
glend;
if Length(Poly2) > 0 then
begin
glColor4f(0.5,0.5,0.5,0);
glBegin(GL_POLYGON);
for I := 0 to Length(Poly2)-1 do
if Poly2[I].X = -1 then
begin
glend;
glBegin(GL_POLYGON);
end else
glVertex2f(Poly2[I].X, Poly2[I].Y);
glend;
end;
glFinish;
glReadPixels(0, 0, XdZ*2, YdZ*2, GL_RGBA, GL_UNSIGNED_BYTE, @TmB[0]);
for I := 0 to XdZ*2-1 do
for J := 0 to YdZ*2-1 do
if (I+((I2-1)*XdZ*2) < tx)
and ((YdZ*2-J)+((J2-1)*YdZ*2) < ty) then
begin
if (TmB[I+(J*XdZ*2)] > $FFFFFFFF-512) then
T[ I+((I2-1)*XdZ*2), (YdZ*2-J)+((J2-1)*YdZ*2) ] := True
else
T[ I+((I2-1)*XdZ*2), (YdZ*2-J)+((J2-1)*YdZ*2) ] := False;
end;
//Loading Fadein effect
cnt := cnt+1;
glClearColor(0, 0, 0, 0);
glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity;
glEnable(GL_TEXTURE_2D);
glColor3f(cnt/((tx/XdZ)*(ty/YdZ)), cnt/((tx/XdZ)*(ty/YdZ)), cnt/((tx/XdZ)*(ty/YdZ)));
glBegin(GL_QUADS);
glTexCoord2f(0, 0);
glVertex2f (XdZ-256, YdZ-64);
glTexCoord2f(0, 1);
glVertex2f (XdZ-256, YdZ+64);
glTexCoord2f(1, 1);
glVertex2f (XdZ+256, YdZ+64);
glTexCoord2f(1, 0);
glVertex2f (XdZ+256, YdZ-64);
glend;
SwapBuffers(DC);
//Context.PageFlip;
glDisable(GL_TEXTURE_2D);
glClearColor(0.5, 0.5, 0.5, 0);
until (XdZ*(I2+1) > tx);
until (YdZ*(J2+1) > ty);
end;
//end Map Tracing
SetLength(TmB, 0);
Inc(MapCnt);
//Loading Screen
glLoadIdentity;
glClearColor(0, 0, 0, 0);
glClear(GL_COLOR_BUFFER_BIT);
glBindTexture(GL_TEXTURE_2D, LIndex);
glEnable(GL_TEXTURE_2D);
glBegin(GL_QUADS);
glColor3f(1, 1, 1);//this time fully visible
glTexCoord2f(0, 0);
glVertex2f (XdZ-256, YdZ-64);
glTexCoord2f(0, 1);
glVertex2f (XdZ-256, YdZ+64);
glTexCoord2f(1, 1);
glVertex2f (XdZ+256, YdZ+64);
glTexCoord2f(1, 0);
glVertex2f (XdZ+256, YdZ-64);
glend;
SwapBuffers(DC);
//Context.PageFlip;
glDisable(GL_TEXTURE_2D);
//ReSpawn points (the points where creatures appear, after they are killed)
for I2 := 0 to RespawnPointCount-1 do
repeat
RP[I2].X := Random(tX-150)+75;
RP[I2].Y := Random(tY-150)+75;
Bool := True;
if (T[ RP[I2].X, RP[I2].Y ] = False) then
Bool := False
else
For I := RP[I2].X - 35 to RP[I2].X + 35 do
For J := RP[I2].Y - 35 to RP[I2].Y + 35 do
if T[ I, J ] = False then
begin
Bool := False;
Break;
end;
until Bool;
//end ReSpawn points
//Spawn (Putting creatures on respawn points)
for I := 0 to Length(CR)-1 do
begin
J2 := Random(RespawnPointCount);
CR[I].X := RP[J2].X-(CR[I].sX div 2);
CR[I].Y := RP[J2].Y-(CR[I].sY div 2);
CR[I].eX := CR[I].X+1;
CR[I].eY := CR[I].Y+1;
CR[I].g := 0;
CR[I].Spd := Random(CR[I].OrgSpd div 2) + (CR[I].OrgSpd div 2);
CR[I].Pwr := CR[I].OrgPwr;
CR[I].Dead := False;
CR[I].PicT := dotTime;
CR[I].ShootI := dotTime;
CR[I].Index := I;
CR[I].HitBy := 1;
CR[I].myGun.Index := -1;
SetLength(CR[I].myGunsI, 0);
Repeat
CR[I].TgIndex := Random(Length(CR));
Until (CR[CR[I].TgIndex].Name <> CR[I].Name);
if CR[I].X < CR[CR[I].TgIndex].X then CR[I].Dir := +1 else
if CR[I].X > CR[CR[I].TgIndex].X then CR[I].Dir := -1;
end;
//end Spawn
//Makes guns - the ones lying on the ground
SetLength(LGN, Length(CR)*4);
for I := 0 to Length(LGN)-1 do
begin
LGN[I].Index := Random(Length(GN));
LGN[I].g := 1;
LGN[I].Air := True;
LGN[I].Dir := random(3)-1;
repeat
LGN[I].X := Random(tX-130)+65;
LGN[I].Y := Random(tY-130)+65;
Bool := True;
if T[ LGN[I].X, LGN[I].Y ] = False then
Bool := False
else
for I2 := LGN[I].X-65 to LGN[I].X+65 do
for J2 := LGN[I].Y-17 to LGN[I].Y+17 do
if T[I2, J2] = False then
begin
Bool := False;
Break;
end;
until Bool;
end;
tx := tx+100;
ty := ty+100;
//PreCalculation - makes some calculation loops before starting, so that creatures don't just drop form the air at the beggining :)
For I := 1 to 75 do
Calculate;
if PolyList <> -1 then
glDeleteLists(PolyList, 1);
//Compiles a display list for the map
PolyList := glGenLists(1);
glNewList(PolyList, GL_COMPILE);
(* if Smooth then
begin
glColor4f((Rs*2+Rt)/3, (Gs*2+Gt)/3, (Bs*2+Bt)/3, 0);
I2 := +1; J2 := +1;
for J := 0 to 3 do
begin
glBegin(GL_POLYGON);
case j of
1: begin I2 := +1; J2 := -1; end;
2: begin I2 := -1; J2 := +1; end;
3: begin I2 := -1; J2 := -1; end;
end;
for I := 0 to Length(Poly1)-1 do
if Poly1[I].X = -1 then
begin
glend;
glBegin(GL_POLYGON);
end else
glVertex2f(Poly1[I].X-I2, Poly1[I].Y+J2);
glend;
end;
end;*)
glBegin(GL_POLYGON);
glColor4f(Rs, Gs, Bs, 0);
for I := 0 to Length(Poly1)-1 do
if Poly1[I].X = -1 then
begin
glend;
glBegin(GL_POLYGON);
end else
glVertex2f(Poly1[I].X, Poly1[I].Y);
glend;
glBegin(GL_POLYGON);
glColor4f(Rt, Gt, Bt, 0);
for I := 0 to Length(Poly2)-1 do
if Poly2[I].X = -1 then
begin
glend;
glBegin(GL_POLYGON);
end else
glVertex2f(Poly2[I].X, Poly2[I].Y);
glend;
glLoadIdentity;
glEndList;
SetLength(Poly1, 0);
SetLength(Poly2, 0);
//Deals with the particles and weather
if Part then
begin
Wind := Random(3);
SetLength(PT, 0);
//Simplified&Optimized(TM) snow make and drop
if (Quality = High) then
begin
SetLength(Weather, 35000);
MaxWeather := 40000;
WeatherInTheSky := 3000;
end else if (Quality = Medium) then
begin
SetLength(Weather, 20000);
MaxWeather := 35000;
WeatherInTheSky := 2000;
end else
begin
SetLength(Weather, 6000);
MaxWeather := 15000;
WeatherInTheSky := 1250;
end;
for I := 0 to Length(Weather)-1 do
with Weather[I] do
begin
repeat
X := Random(tX);
Y := Random(tY);
until (T[X,Y]);
Dir := Random(4)+1;
with Weather[I] do
while T[X,Y] do
Y := Y+Dir;
end;
//Deletes duplicate snow particles
for cnt := 0 to 2000 do
begin
I2 := 0;
J2 := Random(Length(Weather));
for I := 0 to Length(Weather)-1 do
with Weather[I] do
if (X = Weather[J2].X)
and (Y = Weather[J2].Y)
and (I <> J2) then
begin
Weather[I] := Weather[Length(Weather)-1];
J2 := Random(Length(Weather));
Inc(I2);
end;
SetLength(Weather, Length(Weather)-I2);
end;
SetLength(Weather, Length(Weather)+WeatherInTheSky);
for I := Length(Weather)-WeatherInTheSky-1 to Length(Weather)-1 do
with Weather[I] do
begin
repeat
X := Random(tX);
Y := Random(tY);
until (T[X,Y]);
Dir := Random(5)+1;
end;
if Length(Weather) > MaxWeather then
SetLength(Weather, MaxWeather);
end;
//Background pics setting
glLoadIdentity;
glClearColor(0, 0, 0, 0);
glBindTexture(GL_TEXTURE_2D, LIndex);
glEnable(GL_TEXTURE_2D);
if back then
For I2 := 0 to StuffCount do
begin
TryAgain:
if I2 > stOrgStvari then
ST[I2] := ST[Random(stOrgStvari)];
bool := True;
cnt := 0;
repeat
I := Random(tX-88)+44;
J := Random(tY-88)+44;
Inc(cnt);
//This condition is in all 3 picture types, so it speeds up the checking
if (T[ I+(ST[I2].sX div 2), J+ST[I2].sY] = False) then
Continue;
//Makes sure, things aren't too close to each other
bool := True;
if (I2 > 0) then
begin
if (ST[I2].Tip = 'T') then
for J2 := 0 to I2-1 do
if (ST[J2].Tip = 'T') then
if (abs(ST[J2].X-I) < 35)
and (abs(ST[J2].Y-J) < 30)
then
bool := False;
if (ST[I2].Tip = 'L') then
for J2 := 0 to I2-1 do
if (ST[J2].Tip = 'L') then
if (abs(ST[J2].X-I) < ST[J2].sX+ST[I2].sX)
and (abs(ST[J2].Y-J) < 3)
then
bool := False;
end;
if (cnt >= 50000) then
begin
if (I2 > stOrgStvari) then
goto TryAgain
else
begin
I := -512;
J := -512;
Break;
end;
end;
until ((ST[I2].Tip = 'T')
and (T[ I+(ST[I2].sX div 2), J+(ST[I2].sY) ])
and (T[ I+(ST[I2].sX div 2), J ])
and (T[ I, J+(ST[I2].sY div 2) ])
and (T[ I+(ST[I2].sX), J+(ST[I2].sY div 2) ])
and (T[ I+(ST[I2].sX div 2), J+(ST[I2].sY+1) ] = False))
or ((ST[I2].Tip = 'B')
and (T[ I+(ST[I2].sX div 2), J+1 ])
and (T[ I+(ST[I2].sX div 2), J+(ST[I2].sY) ])
and (T[ I+5, J+(ST[I2].sY div 2) ])
and (T[ I+(ST[I2].sX)-5, J+(ST[I2].sY div 2) ])
and (T[ I+(ST[I2].sX div 2), J+(ST[I2].sY+1) ] = False)
and (T[ I+(ST[I2].sX)-5, J+(ST[I2].sY+1) ] = False)
and (T[ I+5, J+(ST[I2].sY+1) ] = False))
or ((ST[I2].Tip = 'L')
and (T[ I+(ST[I2].sX div 2), J+2 ])
and (T[ I+(ST[I2].sX div 2), J+1 ] = False)
and (T[ I+(ST[I2].sX)+1, J+1 ] = False)
and (T[ I-1, J+1 ] = False)
and (T[ I+(ST[I2].sX div 2), J+(ST[I2].sY div 2)]
and (T[ I+(ST[I2].sX div 2), J+ST[I2].sY])
or (Random(17)=7)))
and (bool);
ST[I2].X := I;
ST[I2].Y := J;
//Loading Fadeout effect
if I2 mod 5 = 0 then
begin
glColor3f(1-I2/StuffCount, 1-I2/StuffCount, 1-I2/StuffCount);
glBegin(GL_QUADS);
glTexCoord2f(0, 0);
glVertex2f (XdZ-256, YdZ-64);
glTexCoord2f(0, 1);
glVertex2f (XdZ-256, YdZ+64);
glTexCoord2f(1, 1);
glVertex2f (XdZ+256, YdZ+64);
glTexCoord2f(1, 0);
glVertex2f (XdZ+256, YdZ-64);
glend;
SwapBuffers(DC);
//Context.PageFlip;
end;
end else
For I := 50 downto 0 do //Loading Fadeout effect
begin
glColor3f(I/50, I/50, I/50);
glBegin(GL_QUADS);
glTexCoord2f(0, 0);
glVertex2f (XdZ-256, YdZ-64);
glTexCoord2f(0, 1);
glVertex2f (XdZ-256, YdZ+64);
glTexCoord2f(1, 1);
glVertex2f (XdZ+256, YdZ+64);
glTexCoord2f(1, 0);
glVertex2f (XdZ+256, YdZ-64);
glend;
SwapBuffers(DC);
//Context.PageFlip;
Sleep(6);
end;
glDisable(GL_TEXTURE_2D);
//end Background pics setting
glClearColor(Rt, Gt, Bt, 1);
Loading := False;
Draw;
end;
// - - - - //
// - - - - - - - - //
// - - - - - - - - - - - - - - - - - //
//---/---/---/---/---/---/---/---/---///
///-//-//-//-//-//-//-//-//-//-//-//-////
//-//-//-//-//-//-//-//-//-//-//-//-//-///
//-// THIS IS THE MAIN /-///
//-/ _ ____ ____ ____ /-///
//-/ I I I I I I I /-///
//-/ I I I I I I I /-///
//-/ I I I I I I___I /-///
//-/ I I I I I I /-///
//-/ I____ I____I _ I____I I /-///
//-// /-///
//-//-//-//-//-//-//-//-//-//-//-//-//-///
///-//-//-//-//-//-//-//-//-//-//-//-////
procedure TGame.Loop(Sender: Tobject; var Done: Boolean);
//Its set as the application.onidle event, so its called everytime, the processor has spare time
//var
// F: TextFile;
// I, J, I2, I3: Integer;
var
I: Integer;
TStr, Str: String;
F: TextFile;
var
TF: TextFile;
J, I2, J2, I3, p0, pl, cnt: Integer;
bool: Boolean;
FO: File of Integer;
label
bck;
begin//Loop
LoopT := (LoopT + (1000/dotTimeSince(FPS))) / 2;
FPS := dotTime;
(* if Loading then
begin
LoadMap;
Loading := False;
end;*)
if GameOver then
LoadMap;
if (Pause = False) then
Calculate;
try
Draw;
except
end;
//FPS Limiter
//(*
if 1000/dotTimeSince(FPS) > FPSLimit then
begin
FpsTim := Round(1000/FPSLimit-dotTimeSince(FPS));
if FpsTim > 1 then
Sleep(FpsTim-1);
end;
//*)
Done := Excape;
if Done then
EndItAll;
end;//Loop
//This procedure ends the game... well D00HHh..
procedure TGame.EndItAll;
begin
//glClear(GL_ALL_ATTRIB_BITS);
(*if RC <> 0 then
begin
wglMakeCurrent(0, 0);
wglDeleteContext(RC);
end;
ReleaseDC(Handle, DC);*)
//dotSetDisplayMode(0,0,0,0);
//WinExec('Djuk_Njuk.exe', SW_SHOWNORMAL);
//Application.Terminate;
//FIXME: ugly hack, because I was having problems with closing gl windows
ShellExecute(Handle, 'open', PWideChar(Application.ExeName), nil, nil, SW_SHOW);
DeactivateRenderingContext;
wglDeleteContext(RC);
ReleaseDC(Handle, DC);
MenuForm.Close;
// Application.Terminate;
//DjukNjuk.Hide;
// Application.Terminate;
//DjukNjuk.Hide;
//MenuForm.Show;
end;
//FORM
// ___ ___ _____ ___ _______ _____
// / \ | \ | | | | |
// | | | | | | | |
// | |__/ |-- | \ | |--
// | | \ | |-----\ | |
// \___/ | \ |____ / \ | |____
procedure TGame.FormCreate(Sender: TObject);
var
I: Integer;
TStr, Str: String;
F: TextFile;
var
TF: TextFile;
J, I2, J2, I3, p0, pl, cnt: Integer;
bool: Boolean;
FO: File of Integer;
begin//Create
RunT := dotTime;
Randomize;
try
if FindFirst('Config.cfg', faAnyFile, SRec) = 0 then
begin
AssignFile(F, 'Config.cfg');
Reset(F);
Readln(F, Tstr);
if TStr = 'High' then
begin
Part := True;
Back := True;
Smooth := True;
Quality := High;
end else
if TStr = 'Medium' then
begin
Part := True;
Back := True;
Smooth := False;
Quality := Medium;
end else
if TStr = 'Low' then
begin
Part := True;
Back := False;
Smooth := False;
Quality := Low;
end else
if TStr = 'Very Low' then
begin
Part := False;
Back := False;
Smooth := False;
Quality := Lowest;
end else
begin
Part := True;
Back := True;
Smooth := False;
Quality := Medium;
end;
Readln(F, I);
SetLength(CR, I+1);
Readln(F, Theme);
Readln(F, I);
if I = 0 then
BloodEnabled := False
else
BloodEnabled := True;
CloseFile(F);
end else
begin
Part := True;
Back := True;
Smooth := False;
BloodEnabled := True;
Quality := Medium;
if FindFirst('data/Terrain/Themes/inf.pci', faAnyFile, SRec) = 0 then
begin
AssignFile(F, 'data/Terrain/Themes/inf.pci');
Reset(F);
Readln(F, Theme);
CloseFile(F);
end else
Theme := 'Default';
SetLength(CR, 15+1);
//XdZ := 400;//800x600
//YdZ := 300;
//RR := 60;
end;
except
Part := True;
Back := True;
Smooth := False;
BloodEnabled := True;
Quality := Medium;
if FindFirst('data/Terrain/Themes/inf.pci', faAnyFile, SRec) = 0 then
begin
AssignFile(F, 'data/Terrain/Themes/inf.pci');
Reset(F);
Readln(F, Theme);
CloseFile(F);
end else
Theme := 'Default';
SetLength(CR, 15+1);
//XdZ := 400;//800x600
//YdZ := 300;
//RR := 60;
end;
XdZ := GetSystemMetrics(SM_CXSCREEN) div 2;
YdZ := GetSystemMetrics(SM_CYSCREEN) div 2;
// if Part then
// SetLength(PT, 0)
// else
// begin
SetLength(PT, 0);
SetLength(Weather, 0);
// end;
Left := 0;
Top := 0;
Width := XdZ*2;
Height := YdZ*2;
Cursor := crNone;
try
(*if Smooth then
begin
I := 25;
repeat
I := I-1;
Context.SetAttrib(WGL_SAMPLE_BUFFERS_ARB, 1);
Context.SetAttrib(WGL_SAMPLES_ARB, I);
if I = -1 then raise Exception.Create('');
until Context.InitGL;
end else
if Context.InitGL = False then
raise Exception.Create('');
*)
InitOpenGL;
DC := GetDC(Handle);
RC := CreateRenderingContext(DC, [opDoubleBuffered], 24, 0, 0, 0, 0, 0);
ActivateRenderingContext(DC, RC);
glViewport(0, 0, XdZ*2, YdZ*2);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, XdZ*2, YdZ*2, 0, -1, 1);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glEnable(GL_ALPHA_TEST);
glAlphaFunc(GL_LESS, 1/255); //This is $01000000 in RGB
//if (GetSystemMetrics(SM_CXSCREEN) <> XdZ*2)
//or (GetSystemMetrics(SM_CYSCREEN) <> YdZ*2) then
//dotSetDisplayMode(XdZ*2, YdZ*2, 16, RR);
except
ShowMessage('Could not initialize Graphics. Try another graphic setting or goto www.woodenstick.tk for support');
Application.Terminate;
end;
MapCnt := 0;
//Res := IntToStr(XdZ*2)+'x'+IntToStr(YdZ*2)+' '+IntToStr(RR)+'Hz';
//Weapons
AssignFile(TF, 'data/Weapons/inf.pci');
Reset(TF);
J := 1;
repeat
SetLength(GN, J+1);
SetLength(GB, J+2);//n,.jk
Readln(TF, TStr);
AssignFile(F, 'data/Weapons/'+TStr+'.pci');
Reset(F);
Readln(TF, GN[J].pY);
Readln(TF, GN[J].pX);
Readln(TF, GN[J].dmg);
Readln(TF, GN[J].TT);
Readln(TF, GN[J].ET);
Readln(TF, GN[J].Interval);
Readln(TF, GN[J].ClipSize);
Readln(TF, GN[J].ClipTime);
Readln(F, GN[J].sX);
Readln(F, GN[J].sY);
GN[J].Tip := TStr;
J2 := (64-GN[J].sX);
p0 := (16-GN[J].sY);
For I := 0 to 64 do
For I2 := 0 to 16 do
begin
GB[J].Pic[I+(I2*64)] := TransColor;
if (I <= 64-(J2 div 2))
and (I2 <= 16-(p0 div 2))
and (I >= 1+(J2 div 2) + (J2 mod 2))
and (I2 >= 1+(p0 div 2) + (p0 mod 2)) then
Readln(F, GB[J].Pic[ I+(I2*64) ]);
if (GB[J].Pic[I+(I2*64)] = $FFFFFF) then
GB[J].Pic[I+(I2*64)] := TransColor;
end;
glGenTextures(1, @GB[J].Index);
glBindTexture(GL_TEXTURE_2D, GB[J].Index);
glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA,64,16,0,GL_RGBA,GL_UNSIGNED_BYTE, @GB[J].Pic[0]);
CloseFile(F);
Inc(J);
until eof(TF);
CloseFile(TF);
//end Weapons
//Creatures
AssignFile(TF, 'data/Creatures/inf.pci');
Reset(TF);
PL := 0;
repeat
ReadLn(TF, TStr);
AssignFile(F, 'data/Creatures/'+TStr+'/inf.pci');
Reset(F);
Readln(F, CR[pl].sX);
Readln(F, CR[pl].sY);
Readln(F, CR[pl].PicN);
Readln(F, CR[pl].Name);
Readln(F, CR[pl].OrgSpd);
Readln(F, CR[pl].OrgPwr);
Readln(F, CR[pl].PicInt);
Readln(F, CR[pl].AITip);
Readln(F, CR[pl].AIL);
Readln(F, CR[pl].GunY);
//@HACK read animation style, dammit
if eof(F) = False then
CR[pl].PicShowStyle := 1
else
CR[pl].PicShowStyle := 0;
CloseFile(F);
CR[pl].PicIndex := pl;
CR[pl].Kills := 0;
CR[pl].Deaths := 0;
CR[pl].g := 0;
CR[pl].myGun.Index := -1;
SetLength(CR[pl].myGunsI, 0);
CR[pl].Spd := CR[pl].OrgSpd;
CR[pl].Pwr := -5;
CR[pl].Air := True;
CR[pl].Pic := 1;
CR[pl].MainPic := 1;
CR[pl].Act := '';
for J := 1 to CR[pl].PicN do
begin
J2 := (64-CR[pl].sX);
p0 := (64-CR[pl].sY);
AssignFile(FO, 'data/Creatures/'+TStr+'/'+IntToStr(J)+'.pci');
Reset(FO);
For I := 0 to 64 do
For I2 := 0 to 64 do
begin
Cre[ J, pl ].Pic[I+(I2*64)] := TransColor;
if (I <= 64-(J2 div 2))
and (I2 <= 64-(p0 div 2))
and (I >= 1+(J2 div 2) + (J2 mod 2))
and (I2 >= 1+(p0 div 2) + (p0 mod 2))
then
Read(FO, Cre[ J, pl ].Pic[I+(I2*64)]);
if (Cre[ J, pl ].Pic[I+(I2*64)] = $FFFFFF)
then
Cre[ J, pl ].Pic[I+(I2*64)] := TransColor;
end;
glGenTextures(1, @Cre[J, pl].Index);
glBindTexture(GL_TEXTURE_2D,Cre[J, pl].Index);
glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA,64,64,0,GL_RGBA,GL_UNSIGNED_BYTE, @Cre[J, pl].Pic[0]);
CloseFile(FO);
end;
J := 0;
while FindFirst('data/Creatures/'+TStr+'/Jump'+IntToStr(J)+'.pci', faAnyFile, SRec) = 0 do
begin
J2 := (64-CR[pl].sX);
p0 := (64-CR[pl].sY);
CR[pl].JumpPic := True;
AssignFile(FO, 'data/Creatures/'+TStr+'/Jump'+IntToStr(J)+'.pci');
Reset(FO);
For I := 0 to 64 do
For I2 := 0 to 64 do
begin
Cre[ CR[pl].PicN+1+J, pl ].Pic[I+(I2*64)] := TransColor;
if (I <= 64-(J2 div 2))
and (I2 <= 64-(p0 div 2))
and (I >= 1+(J2 div 2) + (J2 mod 2))
and (I2 >= 1+(p0 div 2) + (p0 mod 2))
then
Read(FO, Cre[ CR[pl].PicN+1+J, pl ].Pic[I+(I2*64)]);
if (Cre[ CR[pl].PicN+1+J, pl ].Pic[I+(I2*64)] = $FFFFFF)
then
Cre[ CR[pl].PicN+1+J, pl ].Pic[I+(I2*64)] := TransColor;
end;
glGenTextures(1, @Cre[CR[pl].PicN+1+J, pl].Index);
glBindTexture(GL_TEXTURE_2D,Cre[CR[pl].PicN+1+J, pl].Index);
glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA,64,64,0,GL_RGBA,GL_UNSIGNED_BYTE, @Cre[CR[pl].PicN+1+J, pl].Pic[0]);
CloseFile(FO);
Inc(J);
end;
Inc(pl);
if pl = Length(CR) then Break;
until eof(TF);
CloseFile(TF);
if pl < Length(CR)-1 then
begin
for I := pl to Length(CR)-1 do
begin
repeat
CR[I] := CR[Random(pl)];
until (CR[I].Name <> 'User') and (CR[I].Name <> '');
CR[I].Pic := Random(CR[I].PicN)+1;
CR[I].Spd := CR[I].OrgSpd+Random(5)-Random(15);
end;
end;
//end Creatures
CR[0].MainPic := 5;
AssignFile(F, 'data/Terrain/Themes/'+Theme+'/inf.pci');
Reset(F);
Readln(F, Rs);
Readln(F, Gs);
Readln(F, Bs);
Readln(F, Rt);
Readln(F, Gt);
Readln(F, Bt);
Readln(F, WeatherType);
CloseFile(F);
if (Theme = 'Default')
or (FindFirst('data/Terrain/Themes/'+Theme+'/0.pci', faAnyFile, SRec) <> 0)
then Back := False;
if Back then
begin
I2 := 0;
while FindFirst('data/Terrain/Themes/'+Theme+'/'+IntToStr(I2)+'.pci', faAnyFile, SRec) = 0 do
begin
AssignFile(F, 'data/Terrain/Themes/'+Theme+'/'+IntToStr(I2)+'.pci');
Reset(F);
Readln(F, ST[I2].Tip);
Readln(F, ST[I2].sX);
Readln(F, ST[I2].sY);
ST[I2].pIndex := I2;
if (ST[I2].Tip <> 'T')
and (ST[I2].Tip <> 'B')
and (ST[I2].Tip <> 'L') then
ST[I2] := ST[Random(I2-1)+1]//Not a normal pic, replaces it with a good one
else
with ST[I2] do
begin
SetLength(Stv, Length(Stv)+1);
pIndex := Length(Stv)-1;
if sX <= 8 then
Stv[pIndex].sX := 8 else
if sX <= 16 then
Stv[pIndex].sX := 16 else
if sX <= 32 then
Stv[pIndex].sX := 32 else
if sX <= 64 then
Stv[pIndex].sX := 64 else
Stv[pIndex].sX := 128;
if sY <= 8 then
Stv[pIndex].sY := 8 else
if sY <= 16 then
Stv[pIndex].sY := 16 else
if sY <= 32 then
Stv[pIndex].sY := 32 else
if sY <= 64 then
Stv[pIndex].sY := 64 else
Stv[pIndex].sY := 128;
For I := 0 to Stv[pIndex].sX do
For J := 0 to Stv[pIndex].sY do
begin
Stv[pIndex].Pic[I+(J*Stv[pIndex].sX)] := TransColor;
if ((I <= sX)
and (J <= sY))
and ((I >= 1)
and (J >= 1))
then
ReadLn(F, Stv[pIndex].Pic[I+(J*Stv[pIndex].sX)]);
if (Stv[pIndex].Pic[I+(J*Stv[pIndex].sX)] = $FFFFFF) then
Stv[pIndex].Pic[I+(J*Stv[pIndex].sX)] := TransColor;
end;
CloseFile(F);
glGenTextures(1, @Stv[pIndex].Index);
glBindTexture(GL_TEXTURE_2D,Stv[pIndex].Index);
glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA,Stv[pIndex].sX, Stv[pIndex].sY,0,GL_RGBA,GL_UNSIGNED_BYTE, @Stv[pIndex].Pic[0]);
end;
Inc(I2);
end;
stOrgStvari := I2;
end;
//Terrain
AssignFile(F, 'data/Terrain/inf.pci');
Reset(F);
I := 0;
while eof(F) = False do
begin
SetLength(Maps, I+1);
Readln(F, Maps[I]);
Inc(I);
end;
CloseFile(F);
//end Terrain
glClearColor(0, 0, 0, 0);
glClear(GL_COLOR_BUFFER_BIT);
//Loads the loading screen :)
AssignFile(CFl, 'data/Loading.pci');
Reset(CFl);
For I := 0 to 512-1 do
For I2 := 0 to 128-1 do
Read(CFl, LPic[ I+(I2*512) ]);
CloseFile(CFl);
glGenTextures(1, @LIndex);
glBindTexture(GL_TEXTURE_2D, LIndex);
glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA,512,128,0,GL_RGBA,GL_UNSIGNED_BYTE, @LPic[0]);
//Pisava
I2 := 0;
while FindFirst('data/font/'+IntToStr(I2)+'.pci', faAnyFile, SRec) = 0 do
begin
SetLength(TextFont, Length(TextFont)+1);
AssignFile(F, 'data/font/'+IntToStr(I2)+'.pci');
Reset(F);
Readln(F, TextFont[I2].Chr);
for I := 0 to FontSize do
for J := 0 to FontSize do
begin
Readln(F, I3);
if I3 = 0 then
TextFont[I2].Pic[I, J] := $FFFFFF
else
TextFont[I2].Pic[I, J] := TransColor;
end;
glGenTextures(1, @TextFont[I2].Index);
glBindTexture(GL_TEXTURE_2D, TextFont[I2].Index);
glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA,FontSize,FontSize,0,GL_RGBA,GL_UNSIGNED_BYTE, @TextFont[I2].Pic[0]);
CloseFile(F);
Inc(I2);
end;
//end Pisava
DeadT := dotTime;
Application.OnIdle := Loop;
end;procedure TGame.FormDestroy(Sender: TObject);
begin
end;
//Create
procedure Jump;
begin
CR[0].g := 17;
CR[0].Y := CR[0].Y - Round(CR[0].g);
CR[0].Air := True;
end;
procedure SwitchWeapon(K:Integer);
var
I: Integer;
begin
with CR[0] do
if Length(myGunsI) > 1 then
begin
for I := 0 to Length(MyGunsI)-1 do
if MyGun.Index = MyGunsI[I].Index then
MyGunsI[I].Clip := MyGun.Clip;
if K = 1 then
begin
if MyGun.Index = MyGunsI[Length(MyGunsI)-1].Index then
begin
MyGun.Index := MyGunsI[0].Index;
MyGun.Clip := MyGunsI[0].Clip;
end else
begin
for I := 0 to Length(MyGunsI)-1 do
if MyGun.Index = MyGunsI[I].Index then
begin
MyGun.Index := MyGunsI[I+1].Index;
MyGun.Clip := MyGunsI[I+1].Clip;
Break;
end;
end;
end else
begin
if MyGun.Index = MyGunsI[0].Index then
begin
MyGun.Index := MyGunsI[Length(MyGunsI)-1].Index;
MyGun.Clip := MyGunsI[Length(MyGunsI)-1].Clip;
end else
begin
for I := 0 to Length(MyGunsI)-1 do
if MyGun.Index = MyGunsI[I].Index then
begin
MyGun.Index := MyGunsI[I-1].Index;
MyGun.Clip := MyGunsI[I-1].Clip;
Break;
end;
end;
end;
end;
end;
(*function GetCharFromVirtualKey(Key: Word): char;
var
keyboardState: TKeyboardState;
asciiResult: Integer;
Reslut: string;
begin
GetKeyboardState(keyboardState) ;
SetLength(Reslut, 2);
asciiResult := ToAscii(key, MapVirtualKey(key, 0), keyboardState, @Reslut[1], 0) ;
case asciiResult of
0: Reslut := '';
1: SetLength(Reslut, 1);
2: SetLength(Reslut, 1);
else
Reslut := '';
end;
if length(Reslut)>0 then
Result := Reslut[1]
else
Result := ' ';
end;*)
procedure TGame.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
var
I, J: Integer;
function KeyExists: Boolean;
var
I, J: Integer;
begin
Result := False;
if Length(Keys) > 0 then
for I := 0 to Length(Keys)-1 do
for J := 0 to Length(Keys)-1 do
if (Keys[I] = Keys[J])
and (I <> J) then
Result := True;
end;
begin//FormKeyDown
SetLength(Keys, Length(Keys)+1);
Keys[Length(Keys)-1] := Key;
if KeyExists then
SetLength(Keys, Length(Keys)-1);
if (Pause = False) then
begin
if (Key = VK_SHIFT)
and (Running = False) then
begin
OrgSpd := CR[0].Spd;
OrgPicInt := CR[0].PicInt;
CR[0].PicInt := CR[0].PicInt div 2;
Running := True;
end;
if Key = VK_DELETE then
begin
CR[0].Pwr := -1;
CR[0].Act := '';
CR[0].ExAct := '';
CR[0].ActM := '';
end;
for J := Length(Keys)-1 downto 0 do
begin
if(Keys[J]=VK_LEFT) or (Keys[J]=65) then
begin
CR[0].exAct := CR[0].Act;
CR[0].Act := 'Walk';
CR[0].Dir := -1;
if Running then
CR[0].Spd := CR[0].OrgSpd+100
else
CR[0].Spd := CR[0].OrgSpd;
Break;
end;
if(Keys[J]=VK_RIGHT) or (Keys[J]=68) then
begin
CR[0].exAct := CR[0].Act;
CR[0].Act := 'Walk';
CR[0].Dir := 1;
if Running then
CR[0].Spd := CR[0].OrgSpd+100
else
CR[0].Spd := CR[0].OrgSpd;
Break;
end;
if(Keys[J]=VK_UP) or (Keys[J]=87) then
begin
CR[0].exAct := CR[0].Act;
MP := True;
CR[0].ActM := 'Jump';
For I := Round(CR[0].X)+10 to Round(CR[0].X)+CR[0].sX-10 do
if T[ I, Round(CR[0].Y)+50] = False then
CR[0].Air := False;
if CR[0].Air = False then
begin
CR[0].exAct := CR[0].Act;
MP := True;
CR[0].ActM := 'Jump';
Jump;
end;
Break;
end;
if(Keys[J]=VK_Space) then
begin
// CR[0].exAct := CR[0].Act;
CR[0].ActM := 'Shoot';
MP := True;
Break;
end;
end;
end;
if Key = VK_ESCAPE then
Excape := True;
if Key = VK_CONTROL then
begin
if (CR[0].exAct = 'Walk') then
CR[0].Act := CR[0].exAct
else
CR[0].Act := '';
SwitchWeapon(1);
end;
KP := True;
if key = vk_numpad0 then
Loadmap;
end;//end FormKeyDown
procedure TGame.FormKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
var
I, J, I2: Integer;
// TmBtn: Word;
begin//FormKeyUp
for I2 := 0 to Length(Keys)-1 do
if Keys[I2] = Key then
begin
// TmBtn := Keys[Length(Keys)-1];
// Keys[Length(Keys)-1] := Keys[I];
Keys[I2] := Keys[Length(Keys)-1];
SetLength(Keys, Length(Keys)-1);
for J := Length(Keys)-1 downto 0 do
begin
if(Keys[J]=VK_LEFT) or (Keys[J]=65) then
begin
CR[0].exAct := CR[0].Act;
CR[0].Act := 'Walk';
CR[0].Dir := -1;
if Running then
CR[0].Spd := CR[0].OrgSpd+100
else
CR[0].Spd := CR[0].OrgSpd;
Break;
end;
if(Keys[J]=VK_Right) or (Keys[J]=68) then
begin
CR[0].exAct := CR[0].Act;
CR[0].Act := 'Walk';
CR[0].Dir := 1;
if Running then
CR[0].Spd := CR[0].OrgSpd+100
else
CR[0].Spd := CR[0].OrgSpd;
Break;
end;
if(Keys[J]=VK_UP) or (Keys[J]=87) then
begin
// CR[0].exAct := CR[0].Act;
// MP := True;
// CR[0].ActM := 'Jump';
For I := Round(CR[0].X)+10 to Round(CR[0].X)+CR[0].sX-10 do
if T[ I, Round(CR[0].Y)+50] = False then
CR[0].Air := False;
if CR[0].Air = False then
begin
CR[0].exAct := CR[0].Act;
MP := True;
CR[0].ActM := 'Jump';
Jump;
end;
Break;
end;
if(Keys[J]=VK_SPACE) then
begin
CR[0].ActM := 'Shoot';
MP := True;
Break;
end;
end;
Break;
end;
if Key = VK_SPACE then
begin
MP := False;
CR[0].ActM := '';
end;
if Key = VK_SHIFT then
begin
CR[0].Spd := OrgSpd;
CR[0].PicInt := OrgPicInt;
Running := False;
end;
if Length(Keys) = 0 then
KP := False;
end;//end FormKeyUp
procedure TGame.FormMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
var
I: Word;
label
ven;
begin//FormMouseDown
MP := True;
if Button = mbMiddle then
begin
CR[0].ActM := '';
SwitchWeapon(1);
end else
if Pause = False then
if (Button = mbLeft) then
CR[0].ActM := 'Shoot' else
if (Button = mbRight) then
CR[0].ActM := 'Jump';
For I := Round(CR[0].X)+10 to Round(CR[0].X)+CR[0].sX-10 do
if T[ I, Round(CR[0].Y)+50] = False then
CR[0].Air := False;
if (CR[0].ActM = 'Jump') and (CR[0].Air = False) then Jump;
end;//end FormMouseDown
procedure TGame.FormMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
CR[0].ActM := '';
MP := False;
end;
procedure TGame.FormKeyPress(Sender: TObject; var Key: Char);
var
I: Integer;
begin
if AnsiUpperCase(Key) = 'P' then
if Pause then Pause := False else Pause := True;
if AnsiUpperCase(Key) = 'R' then
begin
CR[0].ClipTimer := dotTime;
CR[0].myGun.Clip := GN[CR[0].myGun.Index].ClipSize;
end;
//Everyone wants to kill you
if AnsiUpperCase(Key) = 'C' then
for I := 1 to Length(CR) do
CR[I].TgIndex := 0;
//Let AI play
if AnsiUpperCase(Key) = 'M' then
begin
if CR[0].name='User' then
begin
CR[0].name:='AIUser';
CR[0].AITip := 'Dumber';
CR[0].Act := '';
CR[0].Spd := CR[0].OrgSpd;
end else
CR[0].name:='User';
end;
end;
procedure TGame.FormMouseWheelDown(Sender: TObject; Shift: TShiftState;
MousePos: TPoint; var Handled: Boolean);
begin
CR[0].ActM := '';
SwitchWeapon(1);
end;
procedure TGame.FormMouseWheelUp(Sender: TObject; Shift: TShiftState;
MousePos: TPoint; var Handled: Boolean);
begin
CR[0].ActM := '';
SwitchWeapon(-1);
end;
end.
|
unit UFrmRegistro;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, UFrmCRUD, ExtCtrls, Menus, Buttons, StdCtrls
, URegraCRUD
, UDM
, UProximaVacina
, URepositorioProximaVacina
, URegraCRUDProximaVacina
, UUtilitarios, Mask
;
type
TFrmRegistro = class(TFrmCRUD)
edPaciente: TLabeledEdit;
GroupBox1: TGroupBox;
cbVacina: TComboBox;
lbVacina: TLabel;
cbDose: TComboBox;
lbDose: TLabel;
edData: TMaskEdit;
lbData: TLabel;
lbTelefone: TMaskEdit;
protected
FPROXIMAVACINA : TPROXIMAVACINA;
FRegraCRUDProximaVacina: TRegraCRUDProximaVacina;
procedure Inicializa; override;
procedure PreencheEntidade; override;
procedure PreencheFormulario; override;
procedure PosicionaCursorPrimeiroCampo; override;
procedure HabilitaCampos(const ceTipoOperacaoUsuario: TTipoOperacaoUsuario); override;
end;
var
FrmRegistro: TFrmRegistro;
implementation
uses
UOpcaoPesquisa
, UEntidade
, UFrmPesquisa
, UDialogo
;
{$R *.dfm}
{ TFrmRegistro }
procedure TFrmRegistro.HabilitaCampos(
const ceTipoOperacaoUsuario: TTipoOperacaoUsuario);
begin
inherited;
GroupBox1.Enabled := FTipoOperacaoUsuario In [touInsercao, touAtualizacao];
end;
procedure TFrmRegistro.Inicializa;
begin
inherited;
DefineEntidade(@FPROXIMAVACINA, TPROXIMAVACINA);
DefineRegraCRUD(@FregraCRUDPROXIMAVACINA, TRegraCRUDPROXIMAVACINA);
AdicionaOpcaoPesquisa(TOpcaoPesquisa
.Create
.AdicionaFiltro(FLD_NOME)
.DefineNomeCampoRetorno(FLD_ENTIDADE_ID)
.DefineNomePesquisa(STR_PROX_VACINA)
.DefineVisao(TBL_PROX_VACINA));
end;
procedure TFrmRegistro.PosicionaCursorPrimeiroCampo;
begin
inherited;
lbTelefone.SetFocus;
end;
procedure TFrmRegistro.PreencheEntidade;
begin
inherited;
FPROXIMAVACINA.SUS_CODIGO := lbTelefone.Text;
FPROXIMAVACINA.NOME := edPaciente.Text;
FPROXIMAVACINA.DATA_RETORNO := StrToDate(edData.Text);
FPROXIMAVACINA.DOSE := cbDose.Text;
FPROXIMAVACINA.VACINA_RETORNO := cbVacina.Text;
end;
procedure TFrmRegistro.PreencheFormulario;
begin
inherited;
lbTelefone.Text :=FPROXIMAVACINA.SUS_CODIGO ;
edPaciente.Text :=FPROXIMAVACINA.NOME ;
edData.Text := DateTOStr(FPROXIMAVACINA.DATA_RETORNO) ;
cbDose.Text :=FPROXIMAVACINA.DOSE;
cbVacina.Text :=FPROXIMAVACINA.VACINA_RETORNO ;
end;
end.
|
unit Financas.View.Principal;
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.Controls.Presentation, FMX.StdCtrls;
type
TViewPrincipal = class(TForm)
LayoutMain: TLayout;
ButtonDatabase: TButton;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
procedure ButtonDatabaseClick(Sender: TObject);
private
{ Private declarations }
FCompanyName: String;
FSystemName: String;
FVersion: String;
procedure ReadVersionInfo;
public
{ Public declarations }
end;
var
ViewPrincipal: TViewPrincipal;
implementation
{$R *.fmx}
uses Financas.Controller.ApplicationInfo.Factory, Financas.Controller.Listbox.Factory, Financas.View.Conexao;
procedure TViewPrincipal.ReadVersionInfo;
begin
FSystemName := TControllerApplicationInfoFactory.New.ProductName;
FCompanyName := TControllerApplicationInfoFactory.New.CompanyName;
FVersion := 'Versão ' + TControllerApplicationInfoFactory.New.FileVersion;
end;
procedure TViewPrincipal.ButtonDatabaseClick(Sender: TObject);
begin
ViewConexao := TViewConexao.Create(Self);
//
ViewConexao.ShowModal;
end;
procedure TViewPrincipal.FormClose(Sender: TObject; var Action: TCloseAction);
begin
if MessageDlg('Deseja encerrar o sistema?', TMsgDlgType.mtConfirmation, [TMsgDlgBtn.mbYes, TMsgDlgBtn.mbNo], 0, TMsgDlgBtn.mbYes) = mrYes then
Action := TCloseAction.caFree
else
Action := TCloseAction.caNone;
end;
procedure TViewPrincipal.FormCreate(Sender: TObject);
begin
ReadVersionInfo;
//
Caption := FSystemName + ' - ' + FVersion;
end;
procedure TViewPrincipal.FormShow(Sender: TObject);
begin
TControllerListboxFactory.New.Principal(LayoutMain).Exibir;
end;
end.
|
unit Diagram;
{$mode objfpc}{$H+}
interface
uses
Controls, FGL, TAGraph, TASeries,
Plots;
type
TDiagram = class;
TDiagramList = specialize TFPGList<TDiagram>;
TGraphLines = specialize TFPGMap<Pointer, TLineSeries>;
// An intermediate between TPlot and TChart.
// It is Controller in MVC-terms, while TPlot is Model and TChart is View.
TDiagram = class(TInterfacedObject, IPlotNotification)
private
FPlot: TPlot;
FChart: TChart;
FLines: TGraphLines;
procedure Create(APlot: TPlot; AParent: TCustomControl);
procedure CreateChart(AParent: TCustomControl);
procedure Notify(AOperation: TPlotOperation; APlot: TPlot; AGraph: TGraph);
procedure ProcessGraphAdded(AGraph: TGraph);
procedure ProcessGraphDeleted(AGraph: TGraph);
procedure ProcessGraphDestroying(AGraph: TGraph);
procedure ProcessGraphChanged(AGraph: TGraph);
procedure CreateLine(AGraph: TGraph);
procedure UpdateLine(AGraph: TGraph);
function GetLine(AGraph: TGraph): TLineSeries;
function GetCountTotal: Integer;
function GetCountVisible: Integer;
public
class function Create(APlot: TPlot; AParent: TCustomControl): TDiagram;
procedure Free;
procedure Rename; overload;
procedure Rename(AGraph: TGraph); overload;
property Plot: TPlot read FPlot;
property Chart: TChart read FChart;
property CountTotal: Integer read GetCountTotal;
property CountVisible: Integer read GetCountVisible;
end;
implementation
uses
Dialogs, Graphics,
OriUtils_TChart,
SpectrumStrings;
class function TDiagram.Create(APlot: TPlot; AParent: TCustomControl): TDiagram;
begin
Result := TDiagram(NewInstance);
Result.Create(APlot, AParent);
end;
procedure TDiagram.Create(APlot: TPlot; AParent: TCustomControl);
begin
FPlot := APlot;
CreateChart(AParent);
FLines := TGraphLines.Create;
if Assigned(FPlot.Owner) then
FPlot.Owner.RegisterNotifyClient(Self);
end;
procedure TDiagram.Free;
begin
if Assigned(FPlot.Owner) then
FPlot.Owner.UnRegisterNotifyClient(Self);
FLines.Free;
FPlot.Free;
FChart.Free;
FreeInstance;
end;
procedure TDiagram.CreateChart(AParent: TCustomControl);
var
M: Integer;
begin
FChart := TChart.Create(AParent);
FChart.Align := alClient;
FChart.Parent := AParent;
FChart.BackColor := clWindow;
//FChart.Margins.Left := 0;
//FChart.Margins.Right := 0;
//FChart.Margins.Top := 0;
//FChart.Margins.Bottom := 0;
FChart.LeftAxis.Grid.Style := psSolid;
FChart.LeftAxis.Grid.Color := clSilver;
FChart.BottomAxis.Grid.Style := psSolid;
FChart.BottomAxis.Grid.Color := clSilver;
M := FChart.Canvas.TextHeight('I');
FChart.MarginsExternal.Left := M;
FChart.MarginsExternal.Right := M;
FChart.MarginsExternal.Top := M;
FChart.MarginsExternal.Bottom := M;
end;
{%region Plot Notifications}
procedure TDiagram.Notify(AOperation: TPlotOperation; APlot: TPlot; AGraph: TGraph);
begin
case AOperation of
poGraphAdded: if APlot = FPlot then ProcessGraphAdded(AGraph);
poGraphChanged: if APlot = FPlot then ProcessGraphChanged(AGraph);
poGraphDeleted: if APlot = FPlot then ProcessGraphDeleted(AGraph);
poGraphDestroying: if APlot = FPlot then ProcessGraphDestroying(AGraph);
end;
end;
procedure TDiagram.ProcessGraphAdded(AGraph: TGraph);
begin
CreateLine(AGraph);
UpdateLine(AGraph);
end;
procedure TDiagram.ProcessGraphDeleted(AGraph: TGraph);
var
Line: TLineSeries;
begin
Line := GetLine(AGraph);
if Assigned(Line) then
FChart.DeleteSeries(Line);
// Do not destroy line, only remove it from chart
// Graph deletion can be undone, so line is still needed
end;
procedure TDiagram.ProcessGraphDestroying(AGraph: TGraph);
var
Line: TLineSeries;
begin
Line := GetLine(AGraph);
if Assigned(Line) then
FChart.DeleteSeries(Line);
FLines.Remove(AGraph);
Line.Free;
end;
procedure TDiagram.ProcessGraphChanged(AGraph: TGraph);
var
Line: TLineSeries;
begin
Line := GetLine(AGraph);
if Assigned(Line) then
Line.Title := AGraph.Title;
end;
{%endregion}
{%region Working With Line}
function TDiagram.GetLine(AGraph: TGraph): TLineSeries;
var
Index: Integer;
begin
Index := FLines.IndexOf(AGraph);
if Index >= 0
then Result := FLines.Data[Index]
else Result := nil;
end;
procedure TDiagram.CreateLine(AGraph: TGraph);
var
Line: TLineSeries;
begin
Line := GetLine(AGraph);
if not Assigned(Line) then
begin
Line := TLineSeries.Create(FChart);
Line.Tag := Integer(AGraph);
Line.Title := AGraph.Title;
Line.SeriesColor := GetLineSeriesColor(FChart);
FLines.Add(AGraph, Line);
FChart.AddSeries(Line);
end
else if not FChart.HasSeries(Line) then
FChart.AddSeries(Line);
end;
procedure TDiagram.UpdateLine(AGraph: TGraph);
var
I: Integer;
Line: TLineSeries;
begin
Line := GetLine(AGraph);
if Assigned(Line) then
begin
Line.BeginUpdate;
try
Line.Clear;
for I := 0 to AGraph.ValueCount-1 do
Line.AddXY(AGraph.ValuesX[I], AGraph.ValuesY[I]);
finally
Line.EndUpdate;
end;
end;
end;
{%endregion}
{%region Commands}
procedure TDiagram.Rename;
var
Title: String;
begin
Title := InputBox(Dlg_DiagramTitleCaption, Dlg_DiagramTitlePrompt, FPlot.Title);
if Title <> FPlot.Title then FPlot.SetTitle(Title);
end;
procedure TDiagram.Rename(AGraph: TGraph);
var
Title: String;
begin
Title := InputBox(Dlg_GraphTitleCaption, Dlg_GraphTitlePrompt, AGraph.Title);
if Title <> AGraph.Title then AGraph.SetTitle(Title);
end;
{%endregion}
{%region Properties}
function TDiagram.GetCountTotal: Integer;
begin
Result := FPlot.Count;
end;
function TDiagram.GetCountVisible: Integer;
var
I: Integer;
begin
Result := 0;
for I := 0 to FPlot.Count-1 do
if FLines[FPlot[I]].Active then Inc(Result);
end;
{%endregion}
end.
|
////////////////////////////////////////////
// Процедуры для работы с деревом
////////////////////////////////////////////
unit VT_Utils;
interface
uses GMGlobals, VirtualTrees, Classes, Types;
type
TCycleTreeProc = procedure (nd: PVirtualNode; CycleObject: pointer) of object;
TCycleTreeProcRef = reference to procedure (nd: PVirtualNode);
procedure CycleTree(root: PVirtualNode; proc: TCycleTreeProc; CycleObject: pointer = nil); overload;
procedure CycleTree(root: PVirtualNode; proc: TCycleTreeProcRef); overload;
procedure VST_SortByDragging(vst: TBaseVirtualTree; Pt: TPoint; Mode: TDropMode);
procedure DelNodeAndSelectNextSibling(Node: PVirtualNode);
procedure SelectNode(nd: PVirtualNode);
procedure UpdateSortOrder(header: TVTHeader; Column: TColumnIndex);
implementation
procedure UpdateSortOrder(header: TVTHeader; Column: TColumnIndex);
begin
if header.SortColumn = Column then
begin
if header.SortDirection = sdAscending then
header.SortDirection := sdDescending
else
header.SortDirection := sdAscending;
end
else
header.SortColumn := Column;
end;
procedure SelectNode(nd: PVirtualNode);
begin
TreeFromNode(nd).Selected[nd] := true;
TreeFromNode(nd).FocusedNode := nd;
TreeFromNode(nd).FullyVisible[nd] := true;
end;
procedure DelNodeAndSelectNextSibling(Node: PVirtualNode);
var nd: PVirtualNode;
tree: TBaseVirtualTree;
begin
nd := Node.NextSibling;
if nd = nil then
nd := Node.PrevSibling;
if (nd = nil) and (Node.Parent <> TreeFromNode(Node).RootNode) then
nd := Node.Parent;
tree := TreeFromNode(Node);
tree.DeleteNode(Node);
if nd <> nil then
SelectNode(nd);
end;
procedure CycleTree(root: PVirtualNode; proc: TCycleTreeProc; CycleObject: pointer = nil);
var nd: PVirtualNode;
Tree: TBaseVirtualTree;
begin
Tree := TreeFromNode(root);
if root = nil then
nd := Tree.RootNode.FirstChild
else
nd := root.FirstChild;
while nd <> nil do
begin
proc(nd, CycleObject);
CycleTree(nd, proc, CycleObject);
nd := nd.NextSibling;
end;
end;
procedure CycleTree(root: PVirtualNode; proc: TCycleTreeProcRef);
var
nd: PVirtualNode;
Tree: TBaseVirtualTree;
begin
Tree := TreeFromNode(root);
if root = nil then
nd := Tree.RootNode.FirstChild
else
nd := root.FirstChild;
while nd <> nil do
begin
proc(nd);
CycleTree(nd, proc);
nd := nd.NextSibling;
end;
end;
procedure VST_SortByDragging(vst: TBaseVirtualTree; Pt: TPoint; Mode: TDropMode);
var h: THitInfo;
begin
vst.GetHitTestInfoAt(Pt.X, Pt.Y, false, h);
if h.HitNode = vst.GetFirstSelected() then Exit;
if h.HitNode <> nil then
begin
case Mode of
dmAbove, dmOnNode: vst.MoveTo(vst.GetFirstSelected(), h.HitNode, amInsertBefore, false);
dmBelow: vst.MoveTo(vst.GetFirstSelected(), h.HitNode, amInsertAfter, false);
end;
end
else
vst.MoveTo(vst.GetFirstSelected(), vst.RootNode.LastChild, amInsertAfter, false);
end;
end.
|
(****************************************************************************)
(* *)
(* REV97.PAS - The Relativity Emag (coded in Turbo Pascal 7.0) *)
(* *)
(* "The Relativity Emag" was originally written by En|{rypt, |MuadDib|. *)
(* This source may not be copied, distributed or modified in any shape *)
(* or form. Some of the code has been derived from various sources and *)
(* units to help us produce a better quality electronic magazine to let *)
(* the scene know that we are THE BOSS. *)
(* *)
(* Program Notes : This program presents "The Relativity Emag" *)
(* *)
(* ASM/TP70 Coder : xxxxx xxxxxxxxx (En|{rypt) - xxxxxx@xxxxxxxxxx.xxx *)
(* ------------------------------------------------------------------------ *)
(* TP70 Coder : xxxxx xxxxxxxxx (|MuadDib|) - xxxxxx@xxxxxxxxxx.xxx *)
(* *)
(****************************************************************************)
{컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴}
(****************************************************************************)
(* Reserved Words - The Heading Specifies The Program Name And Parameters. *)
(****************************************************************************)
unit revconst;
interface
uses cdrom;
var
curcddrv:word;
startcd,cdroms:word;
playing,locked,pause:boolean;
mustype:byte;
const
MaxBoom=14;
Max = $ffff;
topics=18;
musdef=6;
fntdef=13;
radExt='.RAD';
hscExt='.HSC';
musimplemented=21;
maxhelp=4;
TYPE
ScreenType = array [0..3999] of Byte;
st12 = string[12];
sub = array[1..topics] of st12;
mus = array[1..musimplemented,1..3] of st12;
fnt = array[1..20] of st12;
TYPE
st22 = string[22];
Subscr = array[1..18] of st22;
hlp = array[1..maxhelp] of string;
na = set of 1..18;
pal = array [0..15,1..3] of byte;
naa = array [1..19] of na; {19 is the main}
subf = array [1..topics] of sub;
subs = array [1..topics+1] of subscr;
buf = array[1..max] of byte;
bu = ^buf;
var slutbuf:bu;
slut:longint;
help1,boom1:boolean;
type
configure = record
x1,y1,x2,y2:integer;
IntroFile:st12;
password:string;
psMenuFile:st12;
hpMenuFile:st12;
bmMenuFile:st12;
DefMenuFile:st12;
SecMenuFile:st12;
TrdMenuFile:st12;
EndMenuFile:st12;
EndMenuFile2:st12;
openinggif:st12;
openinggif2:st12;
openinggif3:st12;
midgif:st12;
midgif2:st12;
passgif:st12;
closinggif:st12;
closinggif2:st12;
closinggif3:st12;
muscfgfile:st12;
help_menu : hlp ;
scr : pal ;
Tag : naa ;
NotAvArr : naa ;
NotAvHelp : na;
subfile : subf;
subscreen : subs;
{--------------------------------------------------------------------}
music : mus;
muson : boolean;
lastmus,curmus : integer;
vol : byte;
{--------------------------------------------------------------------}
font : fnt;
curfnt : integer;
lastfnt : integer;
winon : boolean
{--------------------------------------------------------------------}
end;
cfg = ^configure;
var config:cfg;
{컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴}
(****************************************************************************)
(* Reserved Words - Associates And Stores An Identifier And Type In Memory. *)
(****************************************************************************)
var
mx,my : integer; {menu xy}
{--------------------------------------------------------------------}
{command line controllers}
cd,vga,adlib : boolean;
{--------------------------------------------------------------------}
cdsongpos : integer;
brightness : integer;
cdactpos : integer;
cdpos : integer;
brgt : integer;
cc : integer;
dep : integer;
ScreenAddr : ScreenType absolute $B800:$0000;
key : Char;
fname : string;
implementation
end.
|
program dining_philosophers2;
{$mode objfpc}{$H+}
uses
{$IFDEF UNIX}
cthreads,
{$ENDIF}
Classes, SysUtils, SyncObjs;
const
PHIL_COUNT = 5;
LIFESPAN = 7;
DELAY_RANGE = 950;
DELAY_LOW = 50;
PHIL_NAMES: array[1..PHIL_COUNT] of string = ('Aristotle', 'Kant', 'Spinoza', 'Marx', 'Russell');
type
TFork = TCriticalSection;
TPhilosopher = class;
var
Forks: array[1..PHIL_COUNT] of TFork;
Philosophers: array[1..PHIL_COUNT] of TPhilosopher;
type
TPhilosopher = class(TThread)
private
FName: string;
FLeftFork, FRightFork: TFork;
FLefty: Boolean;
procedure SetLefty(aValue: Boolean);
procedure SwapForks;
protected
procedure Execute; override;
public
constructor Create(const aName: string; aForkIdx1, aForkIdx2: Integer);
property Lefty: Boolean read FLefty write SetLefty;
end;
procedure TPhilosopher.SetLefty(aValue: Boolean);
begin
if Lefty = aValue then
exit;
FLefty := aValue;
SwapForks;
end;
procedure TPhilosopher.SwapForks;
var
Fork: TFork;
begin
Fork := FLeftFork;
FLeftFork := FRightFork;
FRightFork := Fork;
end;
procedure TPhilosopher.Execute;
var
LfSpan: Integer = LIFESPAN;
begin
while LfSpan > 0 do
begin
Dec(LfSpan);
WriteLn(FName, ' sits down at the table');
FLeftFork.Acquire;
FRightFork.Acquire;
WriteLn(FName, ' eating');
Sleep(Random(DELAY_RANGE) + DELAY_LOW);
FRightFork.Release;
FLeftFork.Release;
WriteLn(FName, ' is full and leaves the table');
if LfSpan = 0 then
continue;
WriteLn(FName, ' thinking');
Sleep(Random(DELAY_RANGE) + DELAY_LOW);
WriteLn(FName, ' is hungry');
end;
end;
constructor TPhilosopher.Create(const aName: string; aForkIdx1, aForkIdx2: Integer);
begin
inherited Create(True);
FName := aName;
FLeftFork := Forks[aForkIdx1];
FRightFork := Forks[aForkIdx2];
end;
procedure DinnerBegin;
var
I: Integer;
Phil: TPhilosopher;
begin
for I := 1 to PHIL_COUNT do
Forks[I] := TFork.Create;
for I := 1 to PHIL_COUNT do
Philosophers[I] := TPhilosopher.Create(PHIL_NAMES[I], I, Succ(I mod PHIL_COUNT));
Philosophers[Succ(Random(5))].Lefty := True;
for Phil in Philosophers do
Phil.Start;
end;
procedure WaitForDinnerOver;
var
Phil: TPhilosopher;
Fork: TFork;
begin
for Phil in Philosophers do
begin
Phil.WaitFor;
Phil.Free;
end;
for Fork in Forks do
Fork.Free;
end;
begin
Randomize;
DinnerBegin;
WaitForDinnerOver;
end.
|
// -------------------------------------------------------------------------------
// Escreva um programa Pascal para determinar o módulo de um número. Recordemo-nos de
// que
//
// modulo(X) =
// X se X >= 0
// -X se X < 0
//
// NB: Não utilize a função pré-definida (embutida) do Turbo Pascal abs(x).
// -------------------------------------------------------------------------------
// Autor : Fernando Gomes
// Data : 22/08/2021
// -------------------------------------------------------------------------------
Program Modulo_numero ;
var
x, modulo: real;
Begin
//Pede ao usuario que insira um numero
write('Digite o número: ');
//Le o numero
readln(x);
//Mostra o modulo do numero digiyado
if (x > 0) then
write('O módulo de ',x:5:2, ' e ',x:5:2)
else
begin
modulo := x * -1;
write('O módulo de ',x:5:2, ' e ',modulo:5:2);
end
End. |
unit YxdRBTree;
interface
{$IF RTLVersion>=24}
{$LEGACYIFEND ON}
{$IFEND}
{$IF defined(FPC) or defined(VER170) or defined(VER180) or defined(VER190) or defined(VER200) or defined(VER210)}
{$DEFINE USEINLINE}
{$IFEND}
uses
YxdMemPool,
SysUtils, Classes, SyncObjs;
type
/// <summary>比较函数</summary>
/// <param name='P1'>第一个要比较的参数</param>
/// <param name='P2'>第二个要比较的参数</param>
/// <returns> 如果P1<P2,返回小于0的值,如果P1>P2返回大于0的值,如果相等,返回0</returns>
TYXDCompare = function (P1, P2:Pointer): Integer of object;
type
PRBNode = ^TRBNode;
PPRBNode = ^PRBNode;
TRBNode = {$IFNDEF USEINLINE}object{$ELSE}packed record{$ENDIF}
private
FParentColor: IntPtr;
function GetParent: PRBNode;
procedure SetParent(const Value: PRBNode);
function RedParent: PRBNode; {$IFDEF USEINLINE}inline;{$ENDIF}
procedure SetBlack; {$IFDEF USEINLINE}inline;{$ENDIF}
public
Left: PRBNode; // 左结点
Right: PRBNode; // 右结点
Data: Pointer; // 附加数据成员
public
procedure Free;
procedure Assign(src: PRBNode);
// 重置为空结点,调用后IsEmpty将返回true
procedure Clear;
// 下一后根次序结点,对应于rb_next_postorder函数
function NextPostOrder: PRBNode;
// 下一个节点
function Next: PRBNode;
// 前一个结点
function Prior: PRBNode;
// 是否为空
function IsEmpty: Boolean; {$IFDEF USEINLINE}inline;{$ENDIF}
// 是否是黑结点
function IsBlack: Boolean; {$IFDEF USEINLINE}inline;{$ENDIF}
// 是否为红结点
function IsRed: Boolean; {$IFDEF USEINLINE}inline;{$ENDIF}
// 最深的最左结点
function LeftDeepest: PRBNode;
// 设置父结点和颜色
procedure SetParentAndColor(AParent: PRBNode; AColor:Integer); {$IFDEF USEINLINE}inline;{$ENDIF}
// 父结点
property Parent: PRBNode read GetParent write SetParent;
end;
type
TRBTree = class;
TRBCompare = TYXDCompare;
/// <summary>删除结点通知事件,在删除一个树结点时触发</summary>
/// <param name="ASender">触发事件的红黑树对象</param>
/// <param name="ANode">要删除的结点</param>
TRBDeleteNotify = procedure (ASender: TRBTree; ANode: PRBNode) of object;
// 下面三个事件我真没想到啥时需要,原Linux代码中触发了,我也就保留了
TRBRotateNotify = procedure (ASender: TRBTree; AOld, ANew: PRBNode) of object;
TRBPropagateNotify = procedure (ASender: TRBTree; ANode, AStop: PRBNode) of object;
TRBCopyNotify = TRBRotateNotify;
/// <summary>
/// 红黑树Delphi对象封装 (源自swish基于Linux 3.14.4内核红黑树实现)
/// </summary>
TRBTree = class
private
function GetIsEmpty: Boolean; {$IFDEF USEINLINE}inline;{$ENDIF}
protected
FRoot: PRBNode;
FCount: Integer;
FRBMempool: TMemPool;
FOnCompare: TYXDCompare;
FOnDelete: TRBDeleteNotify;
FOnRotate: TRBRotateNotify;
FOnCopy: TRBCopyNotify;
FOnPropagate: TRBPropagateNotify;
function EraseAugmented(node: PRBNode): PRBNode; {$IFDEF USEINLINE}inline;{$ENDIF}
procedure RotateSetParents(AOld, ANew: PRBNode; color: Integer); {$IFDEF USEINLINE}inline;{$ENDIF}
procedure EraseColor(AParent: PRBNode); {$IFDEF USEINLINE}inline;{$ENDIF}
procedure ChangeChild(AOld, ANew, parent: PRBNode); {$IFDEF USEINLINE}inline;{$ENDIF}
procedure DoCopy(node1, node2: PRBNode); {$IFDEF USEINLINE}inline;{$ENDIF}
procedure DoPropagate(node1, node2: PRBNode); {$IFDEF USEINLINE}inline;{$ENDIF}
procedure InsertColor(AChild: PRBNode); {$IFDEF USEINLINE}inline;{$ENDIF}
procedure InsertNode(node: PRBNode); {$IFDEF USEINLINE}inline;{$ENDIF}
procedure DoRotate(AOld,ANew: PRBNode); {$IFDEF USEINLINE}inline;{$ENDIF}
procedure LinkNode(node,parent: PRBNode; var rb_link: PRBNode); {$IFDEF USEINLINE}inline;{$ENDIF}
public
/// <summary>
/// 构造函数,传递一个大小比较函数进去,以便在插入和查找时能够正确的区分
/// </summary>
constructor Create(AOnCompare: TRBCompare); virtual;
destructor Destroy;override;
// 清除所有的结点
procedure Clear;
// 删除一个结点, 成功,返回被删除结点的Data数据成员地址,失败或不存在,返回nil
function Delete(AChild: PRBNode): Pointer; //rb_erase
// 首个结点
function First: PRBNode;//rb_first
// 最后一个结点
function Last: PRBNode; //rb_last
// 首个后根次序结点
function FirstPostOrder: PRBNode;//rb_first_postorder
// 插入一个数据,比较由构造时传入的事件回调函数处理, 成功,返回true (如果指定的数据相同内容已经存在,就会返回false)
function Insert(AData:Pointer):Boolean;
// 查找与指定的数据内容相同的结点, 返回找到的结点
function Find(AData:Pointer): PRBNode;
// 替换结点, 替换要自己保证内容和Src一致,否则可能造成树错乱,如果不能保证尝试删除+添加来完成替换
procedure Replace(Src, ANew: PRBNode);
// 判断树是否为空树
property IsEmpty: Boolean read GetIsEmpty;
// 比较函数,注意不要在树插入后更改比较算法
property OnCompare: TRBCompare read FOnCompare write FOnCompare;
// 删除事件响应函数
property OnDelete: TRBDeleteNotify read FOnDelete write FOnDelete;
// 旋转事件
property OnRotate: TRBRotateNotify read FOnRotate write FOnRotate;
// 复制事件
property OnCopy: TRBCopyNotify read FOnCopy write FOnCopy;
// 扩散事件
property OnPropagate: TRBPropagateNotify read FOnPropagate write FOnPropagate;
// 结点数量
property Count:Integer read FCount;
end;
implementation
const
RB_RED = 0;
RB_BLACK = 1;
{ TRBNode }
procedure TRBNode.Assign(src: PRBNode);
begin
FParentColor := src.FParentColor;
Left := src.Left;
Right := src.Right;
Data := src.Data;
end;
procedure TRBNode.Clear;
begin
FParentColor := IntPtr(@Self);
end;
procedure TRBNode.Free;
begin
if Left <> nil then begin
Left.Free;
Dispose(Left);
end;
if Right <> nil then begin
Right.Free;
Dispose(Right);
end;
end;
function TRBNode.GetParent: PRBNode;
begin
Result := PRBNode(IntPtr(FParentColor) and (not $3));
end;
function TRBNode.IsBlack: Boolean;
begin
Result := (IntPtr(FParentColor) and $1) <> 0;
end;
function TRBNode.IsEmpty: Boolean;
begin
Result := (FParentColor = IntPtr(@Self));
end;
function TRBNode.IsRed: Boolean;
begin
Result := ((IntPtr(FParentColor) and $1)=0);
end;
function TRBNode.LeftDeepest: PRBNode;
begin
Result := @Self;
while True do begin
if Result.Left <> nil then
Result := Result.Left
else if Result.Right <> nil then
Result := Result.Right
else
Break;
end;
end;
function TRBNode.Next: PRBNode;
var
node, LParent: PRBNode;
begin
if IsEmpty then
Result := nil
else begin
if Right <> nil then begin
Result := Right;
while Result.Left <> nil do
Result := Result.Left;
Exit;
end;
node := @Self;
repeat
LParent := node.Parent;
if Assigned(LParent) and (node = LParent.Right) then
node := LParent
else
Break;
until LParent = nil;
Result := LParent;
end;
end;
function TRBNode.NextPostOrder: PRBNode;
begin
Result := Parent;
if (Result <> nil) and (@Self = Result.Left) and (Result.Right <> nil) then
Result := Result.Right.LeftDeepest;
end;
function TRBNode.Prior: PRBNode;
var
node, AParent: PRBNode;
begin
if IsEmpty then
Result := nil
else begin
if (Left <> nil) then begin
Result := Left;
while (Result.Right <> nil) do
Result := Result.Right;
Exit;
end;
node := @Self;
repeat
AParent := node.Parent;
if (Parent <> nil) and (node = AParent.Left) then
node := AParent
else
Break;
until AParent = nil;
Result := AParent;
end;
end;
function TRBNode.RedParent: PRBNode;
begin
Result := PRBNode(FParentColor);
end;
procedure TRBNode.SetBlack;
begin
FParentColor := FParentColor or RB_BLACK;
end;
procedure TRBNode.SetParent(const Value: PRBNode);
begin
FParentColor := IntPtr(Value) or (IntPtr(FParentColor) and $1);
end;
procedure TRBNode.SetParentAndColor(AParent: PRBNode; AColor: Integer);
begin
FParentColor := IntPtr(AParent) or IntPtr(AColor);
end;
{ TRBTree }
procedure TRBTree.ChangeChild(AOld, ANew, parent: PRBNode);
begin
if parent <> nil then begin
if parent.Left = AOld then
parent.Left := ANew
else
parent.Right := ANew;
end else
FRoot := ANew;
end;
procedure TRBTree.Clear;
var
ANode: PRBNode;
begin
if Assigned(OnDelete) then begin
ANode := First;
while ANode<>nil do begin
OnDelete(Self, ANode);
ANode := ANode.Next;
end;
end;
if (FRoot <> nil) then begin
FRoot.Free;
Dispose(FRoot);
FRoot := nil;
end;
FCount := 0;
end;
constructor TRBTree.Create(AOnCompare: TRBCompare);
begin
FOnCompare := AOnCompare;
FRBMempool := TMemPool.Create(SizeOf(TRBNode), 1024);
end;
function TRBTree.Delete(AChild: PRBNode): Pointer;
var
rebalance: PRBNode;
begin
Result := AChild.Data;
rebalance := EraseAugmented(AChild);
if rebalance <> nil then
EraseColor(rebalance);
AChild.Left := nil;
AChild.Right := nil;
Dec(FCount);
if Assigned(FOnDelete) then
FOnDelete(Self, AChild);
AChild.Free;
Dispose(AChild);
end;
destructor TRBTree.Destroy;
begin
Clear;
inherited;
FreeAndNil(FRBMempool);
end;
procedure TRBTree.DoCopy(node1, node2: PRBNode);
begin
if Assigned(FOnCopy) then
FOnCopy(Self, node1, node2);
end;
procedure TRBTree.DoPropagate(node1, node2: PRBNode);
begin
if Assigned(FOnPropagate) then
FOnPropagate(Self, node1, node2);
end;
procedure TRBTree.DoRotate(AOld, ANew: PRBNode);
begin
if Assigned(FOnRotate) then
FOnRotate(Self, AOld, ANew);
end;
function TRBTree.EraseAugmented(node: PRBNode): PRBNode;
var
child, tmp, AParent, rebalance: PRBNode;
successor, child2: PRBNode;
pc, pc2: IntPtr;
begin
child := node.Right;
tmp := node.Left;
if tmp = nil then begin
pc := node.FParentColor;
AParent := node.Parent;
ChangeChild(node, child, AParent);
if child <> nil then begin
child.FParentColor := pc;
rebalance := nil;
end else if (pc and RB_BLACK)<>0 then
rebalance := AParent
else
rebalance := nil;
tmp := AParent;
end else if (child = nil) then begin
tmp.FParentColor:=node.FParentColor;
AParent := node.Parent;
ChangeChild(node, tmp, AParent);
rebalance := nil;
tmp := AParent;
end else begin
successor := child;
tmp := child.Left;
if tmp = nil then begin
AParent := successor;
child2 := successor.Right;
DoCopy(node, successor);
end else begin
repeat
AParent := successor;
successor := tmp;
tmp := tmp.Left;
until tmp=nil;
AParent.Left := successor.Right;
child2 := successor.Right;
successor.Right := child;
child.Parent := successor;
DoCopy(node, successor);
DoPropagate(AParent, successor);
end;
successor.Left := node.Left;
tmp := node.Left;
tmp.Parent := successor;
pc := node.FParentColor;
tmp := node.Parent;
ChangeChild(node, successor, tmp);
if child2 <> nil then begin
successor.FParentColor := pc;
child2.SetParentAndColor(AParent, RB_BLACK);
rebalance := nil;
end else begin
pc2 := successor.FParentColor;
successor.FParentColor := pc;
if (pc2 and RB_BLACK)<>0 then
rebalance := AParent
else
rebalance:=nil;
end;
tmp := successor;
end;
DoPropagate(tmp, nil);
Result := rebalance;
end;
procedure TRBTree.EraseColor(AParent: PRBNode);
var
node, sibling, tmp1, tmp2: PRBNode;
begin
node := nil;
while (true)do begin
sibling := AParent.Right;
if node <> sibling then begin
{.$REGION 'node<>sibling'}
if sibling.IsRed then begin
{.$REGION 'slbling.IsRed'}
AParent.Right := sibling.Left;
tmp1 := sibling.Left;
sibling.Left := AParent;
tmp1.SetParentAndColor(AParent, RB_BLACK);
RotateSetParents(AParent, sibling, RB_RED);
DoRotate(AParent, sibling);
sibling := tmp1;
end;
{.$ENDREGION 'slbling.IsRed'}
tmp1:=sibling.Right;
if (not Assigned(tmp1)) or tmp1.IsBlack then begin
{.$REGION 'tmp1.IsBlack'}
tmp2 := sibling.Left;
if (not Assigned(tmp2)) or tmp2.IsBlack then begin
{.$REGION 'tmp2.IsBlack'}
sibling.SetParentAndColor(AParent, RB_RED);
if AParent.IsRed then
AParent.SetBlack
else begin
Node:=AParent;
AParent:=node.Parent;
if Assigned(AParent) then
Continue;
end;
Break;
{.$ENDREGION 'tmp2.IsBlack'}
end;
sibling.Left := tmp2.Right;
tmp1 := tmp2.Right;
tmp2.Right := sibling;
AParent.Right := tmp2;
if (tmp1 <> nil) then
tmp1.SetParentAndColor(sibling, RB_BLACK);
DoRotate(sibling, tmp2);
tmp1 := sibling;
sibling := tmp2;
{.$ENDREGION 'tmp1.IsBlack'}
end;
AParent.Right := sibling.Left;
tmp2 := sibling.Left;
sibling.Left := AParent;
tmp1.SetParentAndColor(sibling, RB_BLACK);
if (tmp2 <> nil) then
tmp2.Parent:=AParent;
RotateSetParents(AParent, sibling, RB_BLACK);
DoRotate(AParent, sibling);
Break;
{.$ENDREGION 'node<>sibling'}
end else begin
{.$REGION 'RootElse'}
sibling := AParent.Left;
if (sibling.IsRed) then begin
{.$REGION 'Case 1 - right rotate at AParent'}
AParent.Left := sibling.Right;
tmp1 := sibling.Right;
sibling.Right := AParent;
tmp1.SetParentAndColor(AParent, RB_BLACK);
RotateSetParents(AParent, sibling, RB_RED);
DoRotate(AParent, sibling);
sibling := tmp1;
{.$ENDREGION 'Case 1 - right rotate at AParent'}
end;
tmp1 := sibling.Left;
if (tmp1=nil) or tmp1.IsBlack then begin
{.$REGION 'tmp1.IsBlack'}
tmp2 := sibling.Right;
if (tmp2=nil) or tmp2.IsBlack then begin
{.$REGION 'tmp2.IsBlack'}
sibling.SetParentAndColor(AParent, RB_RED);
if AParent.IsRed then
AParent.SetBlack
else begin
node := AParent;
AParent := node.Parent;
if Assigned(AParent) then
continue;
end;
break;
{.$ENDREGION 'tmp2.IsBlack'}
end;
sibling.Right := tmp2.Left;
tmp1 := tmp2.Left;
tmp2.Left := sibling;
AParent.Left := tmp2;
if Assigned(tmp1) then
tmp1.SetParentAndColor(sibling, RB_BLACK);
DoRotate(sibling, tmp2);
tmp1 := sibling;
sibling := tmp2;
{.$ENDREGION ''tmp1.IsBlack'}
end;
AParent.Left := sibling.Right;
tmp2 := sibling.Right;
sibling.Right := AParent;
tmp1.SetParentAndColor(sibling, RB_BLACK);
if Assigned(tmp2) then
tmp2.Parent := AParent;
RotateSetParents(AParent, sibling, RB_BLACK);
DoRotate(AParent, sibling);
Break;
{.$ENDREGION 'RootElse'}
end;
end;
end;
function TRBTree.Find(AData: Pointer): PRBNode;
var
rc:Integer;
begin
Result := FRoot;
while Assigned(Result) do begin
rc := OnCompare(AData,Result.Data);
if rc < 0 then
Result := Result.Left
else if rc>0 then
Result := Result.Right
else
Break;
end
end;
function TRBTree.First: PRBNode;
begin
Result := FRoot;
if Result<>nil then begin
while Assigned(Result.Left) do
Result := Result.Left;
end;
end;
function TRBTree.FirstPostOrder: PRBNode;
begin
if Assigned(FRoot) then
Result := FRoot.LeftDeepest
else
Result := nil;
end;
function TRBTree.GetIsEmpty: Boolean;
begin
Result := (FRoot = nil);
end;
function TRBTree.Insert(AData: Pointer): Boolean;
var
ANew: PPRBNode;
parent, AChild: PRBNode;
rc: Integer;
begin
parent := nil;
ANew := @FRoot;
while ANew^ <> nil do begin
parent := ANew^;
rc := OnCompare(AData, parent.Data);
if rc < 0 then
ANew := @parent.Left
else if rc > 0 then
ANew := @parent.Right
else begin //已存在
Result := False;
Exit;
end;
end;
New(AChild);
AChild.Data := AData;
LinkNode(AChild, parent, ANew^);
InsertNode(AChild);
Inc(FCount);
Result := True;
end;
procedure TRBTree.InsertColor(AChild: PRBNode);
begin
InsertNode(AChild);
end;
procedure TRBTree.InsertNode(node: PRBNode);
var
AParent, GParent, tmp: PRBNode;
begin
AParent := Node.RedParent;
while True do begin
if AParent = nil then begin
node.SetParentAndColor(nil, RB_BLACK);
Break;
end else if AParent.IsBlack then
Break;
gParent := AParent.RedParent;
tmp := gParent.Right;
if AParent <> tmp then begin
if (tmp <> nil) and tmp.IsRed then begin
tmp.SetParentAndColor(gParent, RB_BLACK);
AParent.SetParentAndColor(gParent, RB_BLACK);
node := gParent;
AParent := node.Parent;
node.SetParentAndColor(AParent, RB_RED);
continue;
end;
tmp := AParent.Right;
if node = tmp then begin
AParent.Right := node.Left;
tmp := node.Left;
node.Left := AParent;
if (tmp <> nil) then
tmp.SetParentAndColor(AParent, RB_BLACK);
AParent.SetParentAndColor(node, RB_RED);
DoRotate(AParent, node);//augment_rotate(parent,node)
AParent := node;
tmp := Node.Right;
end;
gParent.Left := tmp;
AParent.Right := gParent;
if tmp <> nil then
tmp.SetParentAndColor(gParent, RB_BLACK);
RotateSetParents(gParent, AParent, RB_RED);
DoRotate(gParent, AParent);
Break;
end else begin
tmp := gParent.Left;
if Assigned(tmp) and tmp.IsRed then begin
tmp.SetParentAndColor(gParent, RB_BLACK);
AParent.SetParentAndColor(gParent, RB_BLACK);
node:=gParent;
AParent:=node.Parent;
node.SetParentAndColor(AParent,RB_RED);
continue;
end;
tmp := AParent.Left;
if node = tmp then begin
AParent.Left := node.Right;
tmp := Node.Right;
node.Right := AParent;
if tmp <> nil then
tmp.SetParentAndColor(AParent, RB_BLACK);
AParent.SetParentAndColor(node, RB_RED);
DoRotate(AParent, node);
AParent := node;
tmp := node.Left;
end;
gParent.Right := tmp;
AParent.Left := gParent;
if tmp <> nil then
tmp.SetParentAndColor(gParent, RB_BLACK);
RotateSetParents(gparent, AParent, RB_RED);
DoRotate(gParent, AParent);
Break;
end;
end;
end;
function TRBTree.Last: PRBNode;
begin
Result := FRoot;
if Result<>nil then begin
while Assigned(Result.Right) do
Result := Result.Right;
end;
end;
procedure TRBTree.LinkNode(node, parent: PRBNode; var rb_link: PRBNode);
begin
node.FParentColor := IntPtr(parent);
node.Left := nil;
node.Right := nil;
rb_link := node;
end;
procedure TRBTree.Replace(Src, ANew: PRBNode);
var
parent: PRBNode;
begin
parent := Src.Parent;
ChangeChild(Src, ANew, parent);
if Assigned(Src.Left) then
Src.Left.SetParent(ANew)
else
Src.Right.SetParent(ANew);
ANew.Assign(Src);
end;
procedure TRBTree.RotateSetParents(AOld, ANew: PRBNode; color: Integer);
var
AParent: PRBNode;
begin
AParent := AOld.Parent;
ANew.FParentColor := AOld.FParentColor;
AOld.SetParentAndColor(ANew, color);
ChangeChild(AOld, ANew, AParent);
end;
end.
|
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
unit FireDAC.Phys.TDBXDef;
interface
uses
System.SysUtils, System.Classes, FireDAC.Stan.Intf, FireDAC.Phys.Intf;
type
// TFDPhysTDBXConnectionDefParams
// Generated for: FireDAC TDBX driver
/// <summary> TFDPhysTDBXConnectionDefParams class implements FireDAC TDBX driver specific connection definition class. </summary>
TFDPhysTDBXConnectionDefParams = class(TFDConnectionDefParams)
private
function GetDriverID: String;
procedure SetDriverID(const AValue: String);
function GetDBXAdvanced: String;
procedure SetDBXAdvanced(const AValue: String);
function GetDriverName: String;
procedure SetDriverName(const AValue: String);
function GetMetaDefCatalog: String;
procedure SetMetaDefCatalog(const AValue: String);
function GetMetaDefSchema: String;
procedure SetMetaDefSchema(const AValue: String);
function GetMetaCurCatalog: String;
procedure SetMetaCurCatalog(const AValue: String);
function GetMetaCurSchema: String;
procedure SetMetaCurSchema(const AValue: String);
function GetRDBMS: TFDRDBMSKind;
procedure SetRDBMS(const AValue: TFDRDBMSKind);
published
property DriverID: String read GetDriverID write SetDriverID stored False;
property DBXAdvanced: String read GetDBXAdvanced write SetDBXAdvanced stored False;
property DriverName: String read GetDriverName write SetDriverName stored False;
property MetaDefCatalog: String read GetMetaDefCatalog write SetMetaDefCatalog stored False;
property MetaDefSchema: String read GetMetaDefSchema write SetMetaDefSchema stored False;
property MetaCurCatalog: String read GetMetaCurCatalog write SetMetaCurCatalog stored False;
property MetaCurSchema: String read GetMetaCurSchema write SetMetaCurSchema stored False;
property RDBMS: TFDRDBMSKind read GetRDBMS write SetRDBMS stored False;
end;
implementation
uses
Data.DBXCommon, FireDAC.Stan.Consts;
// TFDPhysTDBXConnectionDefParams
// Generated for: FireDAC TDBX driver
{-------------------------------------------------------------------------------}
function TFDPhysTDBXConnectionDefParams.GetDriverID: String;
begin
Result := FDef.AsString[S_FD_ConnParam_Common_DriverID];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysTDBXConnectionDefParams.SetDriverID(const AValue: String);
begin
FDef.AsString[S_FD_ConnParam_Common_DriverID] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysTDBXConnectionDefParams.GetDBXAdvanced: String;
begin
Result := FDef.AsString[S_FD_ConnParam_TDBX_DBXAdvanced];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysTDBXConnectionDefParams.SetDBXAdvanced(const AValue: String);
begin
FDef.AsString[S_FD_ConnParam_TDBX_DBXAdvanced] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysTDBXConnectionDefParams.GetDriverName: String;
begin
Result := FDef.AsString[TDBXPropertyNames.DriverName];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysTDBXConnectionDefParams.SetDriverName(const AValue: String);
begin
FDef.AsString[TDBXPropertyNames.DriverName] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysTDBXConnectionDefParams.GetMetaDefCatalog: String;
begin
Result := FDef.AsString[S_FD_ConnParam_Common_MetaDefCatalog];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysTDBXConnectionDefParams.SetMetaDefCatalog(const AValue: String);
begin
FDef.AsString[S_FD_ConnParam_Common_MetaDefCatalog] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysTDBXConnectionDefParams.GetMetaDefSchema: String;
begin
Result := FDef.AsString[S_FD_ConnParam_Common_MetaDefSchema];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysTDBXConnectionDefParams.SetMetaDefSchema(const AValue: String);
begin
FDef.AsString[S_FD_ConnParam_Common_MetaDefSchema] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysTDBXConnectionDefParams.GetMetaCurCatalog: String;
begin
Result := FDef.AsString[S_FD_ConnParam_Common_MetaCurCatalog];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysTDBXConnectionDefParams.SetMetaCurCatalog(const AValue: String);
begin
FDef.AsString[S_FD_ConnParam_Common_MetaCurCatalog] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysTDBXConnectionDefParams.GetMetaCurSchema: String;
begin
Result := FDef.AsString[S_FD_ConnParam_Common_MetaCurSchema];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysTDBXConnectionDefParams.SetMetaCurSchema(const AValue: String);
begin
FDef.AsString[S_FD_ConnParam_Common_MetaCurSchema] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysTDBXConnectionDefParams.GetRDBMS: TFDRDBMSKind;
var
oManMeta: IFDPhysManagerMetadata;
begin
FDPhysManager.CreateMetadata(oManMeta);
Result := oManMeta.GetRDBMSKind(FDef.AsString[S_FD_ConnParam_Common_RDBMS]);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysTDBXConnectionDefParams.SetRDBMS(const AValue: TFDRDBMSKind);
var
oManMeta: IFDPhysManagerMetadata;
begin
FDPhysManager.CreateMetadata(oManMeta);
FDef.AsString[S_FD_ConnParam_Common_RDBMS] := oManMeta.GetRDBMSName(AValue);
end;
end.
|
unit DTMain;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, BASS;
type
TForm1 = class(TForm)
Button1: TButton;
CheckBox1: TCheckBox;
CheckBox2: TCheckBox;
CheckBox3: TCheckBox;
OpenDialog1: TOpenDialog;
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure CheckBox1Click(Sender: TObject);
procedure CheckBox2Click(Sender: TObject);
procedure CheckBox3Click(Sender: TObject);
private
{ Private-Deklarationen }
chan: DWORD;
procedure Error(msg: string);
public
{ Public-Deklarationen }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
const
ECHBUFLEN = 1200; // buffer length
FLABUFLEN = 350; // buffer length
var
d: ^DWORD;
rotdsp: HDSP; // DSP handle
rotpos: FLOAT; // cur.pos
echdsp: HDSP; // DSP handle
echbuf: array[0..ECHBUFLEN-1, 0..1] of SmallInt; // buffer
echpos: Integer; // cur.pos
fladsp: HDSP; // DSP handle
flabuf: array[0..FLABUFLEN-1, 0..2] of SmallInt; // buffer
flapos: Integer; // cur.pos
flas, flasinc: FLOAT; // sweep pos/min/max/inc
function fmod(a, b: FLOAT): FLOAT;
begin
Result := a - (b * Trunc(a / b));
end;
function Clip(a: Integer): Integer;
begin
if a <= -32768 then a := -32768
else if a >= 32767 then a := 32767;
Result := a;
end;
procedure Rotate(handle: HSYNC; channel: DWORD; buffer: Pointer; length, user: DWORD); stdcall;
var
lc, rc: SmallInt;
begin
d := buffer;
while (length > 0) do
begin
lc := LOWORD(d^); rc := HIWORD(d^);
lc := SmallInt(Trunc(sin(rotpos) * lc));
rc := SmallInt(Trunc(cos(rotpos) * rc));
d^ := MakeLong(lc, rc);
Inc(d);
rotpos := rotpos + fmod(0.00003, PI);
length := length - 4;
end;
end;
procedure Echo(handle: HSYNC; channel: DWORD; buffer: Pointer; length, user: DWORD); stdcall;
var
lc, rc: SmallInt;
l, r: Integer;
begin
d := buffer;
while (length > 0) do
begin
lc := LOWORD(d^); rc := HIWORD(d^);
l := lc + (echbuf[echpos, 1] div 2);
r := rc + (echbuf[echpos, 0] div 2);
echbuf[echpos, 0] := lc;
echbuf[echpos, 1] := rc;
lc := Clip(l);
rc := Clip(r);
d^ := MakeLong(lc, rc);
Inc(d);
Inc(echpos);
if (echpos = ECHBUFLEN) then echpos := 0;
length := length - 4;
end;
end;
procedure Flange(handle: HSYNC; channel: DWORD; buffer: Pointer; length, user: DWORD); stdcall;
var
lc, rc: SmallInt;
p1, p2, s: Integer;
f: FLOAT;
begin
d := buffer;
while (length > 0) do
begin
lc := LOWORD(d^); rc := HIWORD(d^);
p1 := (flapos + Trunc(flas)) mod FLABUFLEN;
p2 := (p1 + 1) mod FLABUFLEN;
f := fmod(flas, 1.0);
s := lc + Trunc(((1.0-f) * flabuf[p1, 0]) + (f * flabuf[p2, 0]));
flabuf[flapos, 0] := lc;
lc := Clip(s);
s := rc + Trunc(((1.0-f) * flabuf[p1, 1]) + (f * flabuf[p2, 1]));
flabuf[flapos, 1] := rc;
rc := Clip(s);
d^ := MakeLong(lc, rc);
Inc(d);
Inc(flapos);
if (flapos = FLABUFLEN) then flapos := 0;
flas := flas + flasinc;
if (flas < 0) or (flas > FLABUFLEN) then
flasinc := -flasinc;
length := length - 4;
end;
end;
procedure TForm1.Error(msg: string);
var
s: string;
begin
s := msg + #13#10 + '(error code: ' + IntToStr(BASS_ErrorGetCode) + ')';
MessageBox(handle, PChar(s), 'Error', MB_ICONERROR or MB_OK);
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
rotdsp := 0;
echdsp := 0;
fladsp := 0;
if (BASS_GetVersion <> MAKELONG(0,8)) then
begin
Error('BASS version 0.8 was not loaded');
Halt;
end;
// setup output - default device, 44100hz, stereo, 16 bits, no syncs (not used)
if not BASS_Init(-1, 44100, BASS_DEVICE_NOSYNC, handle) then
begin
Error('Can''t initialize device');
Halt;
end
else
BASS_Start;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
chattr: Integer;
begin
if OpenDialog1.Execute then
begin
// free both MOD and stream, it must be one of them! :)
BASS_MusicFree(chan);
BASS_StreamFree(chan);
chan := BASS_StreamCreateFile(FALSE, PChar(OpenDialog1.FileName), 0, 0, 0);
if (chan = 0) then
chan := BASS_MusicLoad(FALSE, PChar(OpenDialog1.FileName), 0, 0, BASS_MUSIC_LOOP or BASS_MUSIC_RAMP);
if (chan = 0) then
begin
// not a WAV/MP3 or MOD
Button1.Caption := 'click here to open a file...';
Error('Can''t play the file');
Exit;
end;
chattr := BASS_ChannelGetFlags(chan) and (BASS_SAMPLE_MONO or BASS_SAMPLE_8BITS);
if chattr > 0 then
begin
// not 16-bit stereo
Button1.Caption := 'click here to open a file...';
BASS_MusicFree(chan);
BASS_StreamFree(chan);
Error('16-bit stereo sources only');
Exit;
end;
Button1.Caption := OpenDialog1.FileName;
// setup DSPs on new channel
CheckBox1Click(Sender);
CheckBox2Click(Sender);
CheckBox3Click(Sender);
// play both MOD and stream, it must be one of them! :)
BASS_MusicPlay(chan);
BASS_StreamPlay(chan, FALSE, BASS_SAMPLE_LOOP);
end;
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
BASS_Free();
end;
procedure TForm1.CheckBox1Click(Sender: TObject);
begin
if CheckBox1.Checked then
begin
rotpos := 0.7853981;
rotdsp := BASS_ChannelSetDSP(chan, Rotate, 0);
end
else
BASS_ChannelRemoveDSP(chan, rotdsp);
end;
procedure TForm1.CheckBox2Click(Sender: TObject);
begin
if CheckBox2.Checked then
begin
FillChar(echbuf, SizeOf(echbuf), 0);
echpos := 0;
echdsp := BASS_ChannelSetDSP(chan, Echo, 0);
end
else
BASS_ChannelRemoveDSP(chan, echdsp);
end;
procedure TForm1.CheckBox3Click(Sender: TObject);
begin
if CheckBox3.Checked then
begin
FillChar(flabuf, SizeOf(flabuf), 0);
flapos := 0;
flas := FLABUFLEN / 2;
flasinc := 0.002;
fladsp := BASS_ChannelSetDSP(chan, Flange, 0);
end
else
BASS_ChannelRemoveDSP(chan, fladsp);
end;
end.
|
unit SchoolEntities;
{$mode objfpc}{$H+}
{$interfaces corba}
interface
uses
Classes, SysUtils;
type
TEntityType = (seRoot, seUser, seCourse, seLesson, seSlide, seInvitation, seSession,
seStudentSpot, seStudent, seTeacher, seUnknown);
TUser = class;
TCourse = class;
TLesson = class;
{ IORMInterface }
IORMInterface = interface ['{1CCA5072-5A35-4FAC-9E06-D65E7A5BBE94}']
function GetUser(aUser: TUser): Boolean;
function GetCourse(aCourse: TCOurse): Boolean;
function GetLesson(aLesson: TLesson): Boolean;
end;
{ TSchoolElement }
TSchoolElement = class(TPersistent)
private
FName: String;
FORM: IORMInterface; // CoursesDB
FTeacher: Int64;
function GetName: String;
procedure Initiate; virtual;
procedure SetName(AValue: String);
protected
procedure AssignTo(Dest: TPersistent); override;
function GetID64: Int64; virtual; abstract;
procedure SetID64(AValue: Int64); virtual; abstract;
public
class function EntityAlias: String;
class function EntityType: TEntityType; virtual;
property ORM: IORMInterface read FORM write FORM;
property Name: String read GetName write SetName;
property ID64: Int64 read GetID64 write SetID64;
property Teacher: Int64 read FTeacher write FTeacher;
end;
TSchoolElementClass = class of TSchoolElement;
{ TUser }
TUser = class(TSchoolElement)
private
Fid: Int64;
FLang: String;
FSession: Integer;
protected
procedure AssignTo(Dest: TPersistent); override;
function GetID64: Int64; override;
procedure SetID64(AValue: Int64); override;
public
constructor Create;
class function EntityType: TEntityType; override;
procedure Initiate; override;
published
property id: Int64 read Fid write Fid;
property Lang: String read FLang write FLang;
property Name;
property Session: Integer read FSession write FSession;
end;
TContentType = (stText, stPhoto, stVideo, stAudio, stVoice, stDocument, stUnknown);
{ TCourseElement }
TCourseElement = class(TSchoolElement)
private
Fid: Integer;
FInteractive: Boolean;
FMedia: String;
FMediaType: Byte;
FText: String;
function GetMediaType: TContentType;
procedure SetMediaType(AValue: TContentType);
protected
protected procedure AssignTo(Dest: TPersistent); override;
function GetID64: Int64; override;
procedure SetID64(AValue: Int64); override;
public
class function EntityType: TEntityType; override;
function GetParentID: Int64; virtual; abstract;
procedure Initiate; override;
property MediaType: TContentType read GetMediaType write SetMediaType;
published
property Name;
property id: Integer read Fid write Fid;
property Interactive: Boolean read FInteractive write FInteractive;
property Media: String read FMedia write FMedia;
property Media_Type: Byte read FMediaType write FMediaType;
property Text: String read FText write FText;
end;
TLicType=(ltOpen, ltPublic, ltPrivate);
TUserStatus=(usNone, usStudent, usTeacher, usUnknown);
{ TCourse }
TCourse = class(TCourseElement)
private
FContact: String;
FHistoryChat: String;
FOwner: Int64;
FShowContact: Boolean;
FTesting: Boolean;
FVisibility: Integer;
function GetLicType: TLicType;
procedure SetLicType(AValue: TLicType);
protected
protected procedure AssignTo(Dest: TPersistent); override;
public
class function EntityType: TEntityType; override;
function GetParentID: Int64; override;
procedure Initiate; override;
property LicType: TLicType read GetLicType write SetLicType;
published
property Owner: Int64 read FOwner write FOwner;
property Visibility: Integer read FVisibility write FVisibility;
property Contact: String read FContact write FContact;
property ShowContact: Boolean read FShowContact write FShowContact;
property Testing: Boolean read FTesting write FTesting;
property Teacher;
property HistoryChat: String read FHistoryChat write FHistoryChat;
end;
{ TLesson }
TLesson = class(TCourseElement)
private
FCourse: Integer;
protected
procedure AssignTo(Dest: TPersistent); override;
public
function GetParentID: Int64; override;
procedure Initiate; override;
class function EntityType: TEntityType; override;
published
property Course: Integer read FCourse write FCourse;
end;
{ TSlide }
TSlide = class(TCourseElement)
private
FLesson: Integer;
protected
procedure AssignTo(Dest: TPersistent); override;
public
class function EntityType: TEntityType; override;
function GetParentID: Int64; override;
procedure Initiate; override;
published
property Lesson: Integer read FLesson write FLesson;
end;
{ TInvitation }
TInvitation = class(TSchoolElement)
private
FApplied: Integer;
FCapacity: Integer;
FCourse: Integer;
FID: Integer;
FStatus: Integer;
function GetUserStatus: TUserStatus;
procedure SetUserStatus(AValue: TUserStatus);
protected
procedure AssignTo(Dest: TPersistent); override;
function GetID64: Int64; override;
procedure SetID64(AValue: Int64); override;
public
procedure Initiate; override;
class function EntityType: TEntityType; override;
property UserStatus: TUserStatus read GetUserStatus write SetUserStatus;
published
property ID: Integer read FID write FID;
property Applied: Integer read FApplied write FApplied;
property Capacity: Integer read FCapacity write FCapacity;
property Course: Integer read FCourse write FCourse;
property Status: Integer read FStatus write FStatus;
property Teacher;
end;
{ TStudentSpot }
TStudentSpot = class(TSchoolElement)
private
FCourse: Integer;
FID: Integer;
FLesson: Integer;
FStatus: Integer;
FUser: Int64;
F_Course: TCourse;
F_Lesson: TLesson;
F_User: TUser;
function GetUserStatus: TUserStatus;
function Get_Course: TCourse;
function Get_Lesson: TLesson;
function Get_User: TUser;
procedure SetUserStatus(AValue: TUserStatus);
protected
procedure AssignTo(Dest: TPersistent); override;
function GetID64: Int64; override;
procedure SetID64(AValue: Int64); override;
public
destructor Destroy; override;
procedure Initiate; override;
property UserStatus: TUserStatus read GetUserStatus write SetUserStatus;
property _User: TUser read Get_User;
property _Lesson: TLesson read Get_Lesson;
property _Course: TCourse read Get_Course;
published
property ID: Integer read FID write FID;
property User: Int64 read FUser write FUser;
property Course: Integer read FCourse write FCourse;
property Status: Integer read FStatus write FStatus;
property Teacher;
property Lesson: Integer read FLesson write FLesson;
end;
{ TSession }
TSession = class(TSchoolElement)
private
FEntity: String;
FEntityID: Integer;
FID: Integer;
FStudent: Int64;
protected
function GetID64: Int64; override;
procedure SetID64(AValue: Int64); override;
public
procedure AssignTo(Dest: TPersistent); override;
procedure Initiate; override;
function GetSourceEntityType: TEntityType;
class function EntityType: TEntityType; override;
published
property ID: Integer read FID write FID;
property SourceEntity: String read FEntity write FEntity;
property EntityID: Integer read FEntityID write FEntityID;
property Student: Int64 read FStudent write FStudent;
property Teacher;
end;
function EntityFromString(const aAlias: String): TEntityType;
function EntityTypeToString(aEntity: TEntityType): String;
function CaptionFromSchEntity(aEntity: TEntityType; Multiple: Boolean = False): String;
function LicTypeToCaption(const aLicType: TLicType): String;
function StringToUserStatus(const aAlias: String): TUserStatus;
function UserStatusToString(const aUserStatus: TUserStatus): String;
resourcestring
s_Users='Users';
s_Courses='Courses';
s_Lessons='Lessons';
s_Slides='Slides';
s_Invitations='Invitations';
s_ContactUs='Contact us';
s_User='User';
s_Course='Course';
s_Lesson='Lesson';
s_Slide='Slide';
s_Invitation='Invitation';
s_NotFound='Not found or no access!';
s_NotPassed='You have not passed the previous lesson';
s_AppliedFromAll='Applied %1d of %2d';
s_Public='Public';
s_Private='Private';
s_OpenSource='OpenSource';
s_TestOrAsk='Test / Ask the teacher';
s_Session='Dialogue';
s_Sessions='Dialogues';
s_Student='Student';
s_Students='Students';
s_Teacher='Teacher';
s_Teachers='Teachers';
s_HistoryChat='History chat';
s_GotMsg='You got a message';
s_WroteMsg='wrote you a message';
s_DYWntEntrDlg='Do you want to enter into a dialogue with him?';
s_YStudent='You are a student of the following courses';
s_YTeacher='You are a teacher of the following courses';
s_TakeCourses='Take courses';
s_TeachCourses='Teach courses';
var
SchoolClasses: array[TEntityType] of TSchoolElementClass =
(TSchoolElement, TUser, TCourse, TLesson, TSlide, TInvitation, TSession, TStudentSpot,
TStudentSpot, TStudentSpot, TSchoolElement);
implementation
uses
strutils
;
var
SchoolEntityNames: array[TEntityType] of String =
('root', 'user', 'course', 'lesson', 'slide', 'invitation', 'session', 'spot', 'student',
'teacher', '');
UserStatusNames: array[TUserStatus] of String =('none', 'student', 'teacher', '');
function LicTypeToCaption(const aLicType: TLicType): String;
begin
Result:=EmptyStr;
case aLicType of
ltOpen: Result:=s_OpenSource;
ltPublic: Result:=s_Public;
ltPrivate: Result:=s_Private;
end;
end;
function StringToUserStatus(const aAlias: String): TUserStatus;
begin
Result:=TUserStatus(AnsiIndexStr(aAlias, UserStatusNames));
end;
function UserStatusToString(const aUserStatus: TUserStatus): String;
begin
Result:=UserStatusNames[aUserStatus];
end;
function EntityFromString(const aAlias: String): TEntityType;
var
i: Integer;
begin
i:=AnsiIndexStr(aAlias, SchoolEntityNames);
case i of
0..Ord(High(TEntityType)): Result:=TEntityType(i);
else
Result:=seUnknown;
end;
end;
function EntityTypeToString(aEntity: TEntityType): String;
begin
Result:=SchoolEntityNames[aEntity];
end;
function CaptionFromSchEntity(aEntity: TEntityType; Multiple: Boolean = False): String;
begin
if Multiple then
case aEntity of
seUser: Result:=s_Users;
seCourse: Result:=s_Courses;
seLesson: Result:=s_Lessons;
seSlide: Result:=s_Slides;
seInvitation: Result:=s_Invitations;
seSession: Result:=s_Sessions;
seStudentSpot: Result:= s_Students;
seStudent: Result:=s_Students;
seTeacher: Result:=s_Teachers;
else
Result:=EmptyStr;
end
else
case aEntity of
seUser: Result:=s_User;
seCourse: Result:=s_Course;
seLesson: Result:=s_Lesson;
seSlide: Result:=s_Slide;
seInvitation: Result:=s_Invitation;
seSession: Result:=s_Session;
seStudentSpot: Result:=s_Student;
seStudent: Result:=s_Student;
seTeacher: Result:=s_Teacher;
else
Result:=EmptyStr;
end;
end;
{ TSession }
function TSession.GetID64: Int64;
begin
Result:=FID;
end;
procedure TSession.SetID64(AValue: Int64);
begin
FID:=AValue;
end;
procedure TSession.AssignTo(Dest: TPersistent);
var
aDest: TSession;
begin
inherited AssignTo(Dest);
if not (Dest is TSession) then
Exit;
aDest:=TSession(Dest);
aDest.FStudent:=FStudent;
aDest.FEntity:=FEntity;
aDest.FEntityID:=FEntityID;
end;
procedure TSession.Initiate;
begin
inherited Initiate;
FEntity:=EmptyStr;
FEntityID:=0;
FStudent:=0;
end;
function TSession.GetSourceEntityType: TEntityType;
begin
Result:=EntityFromString(FEntity);
end;
class function TSession.EntityType: TEntityType;
begin
Result:=seSession;
end;
{ TStudentSpot }
function TStudentSpot.GetUserStatus: TUserStatus;
begin
Result:=TUserStatus(FStatus);
end;
function TStudentSpot.Get_Course: TCourse;
begin
if not Assigned(FORM) then
Exit(nil);
if not Assigned(F_Course) then
F_Course:=TCourse.Create;
if F_Course.id<>FCourse then
begin
F_Course.id:=FCourse;
FORM.GetCourse(F_Course);
end;
Result:=F_Course;
end;
function TStudentSpot.Get_Lesson: TLesson;
begin
if not Assigned(FORM) then
Exit(nil);
if not Assigned(F_Lesson) then
F_Lesson:=TLesson.Create;
if F_Lesson.id<>FLesson then
begin
F_Lesson.id:=FLesson;
FORM.GetLesson(F_Lesson);
end;
Result:=F_Lesson;
end;
function TStudentSpot.Get_User: TUser;
begin
if not Assigned(FORM) then
Exit(nil);
if not Assigned(F_User) then
F_User:=TUser.Create;
if F_User.id<>FUser then
begin
F_User.id:=FUser;
FORM.GetUser(F_User);
end;
Result:=F_User;
end;
procedure TStudentSpot.SetUserStatus(AValue: TUserStatus);
begin
FStatus:=Ord(AValue);
end;
procedure TStudentSpot.AssignTo(Dest: TPersistent);
var
aDest: TStudentSpot;
begin
inherited AssignTo(Dest);
if not (Dest is TStudentSpot) then
Exit;
aDest:=TStudentSpot(Dest);
aDest.FUser:=FUser;
aDest.FCourse:=FCourse;
aDest.FStatus:=FStatus;
aDest.FLesson:=FLesson;
end;
function TStudentSpot.GetID64: Int64;
begin
Result:=FID;
end;
procedure TStudentSpot.SetID64(AValue: Int64);
begin
FID:=AValue;
end;
destructor TStudentSpot.Destroy;
begin
F_User.Free;
inherited Destroy;
end;
procedure TStudentSpot.Initiate;
begin
inherited Initiate;
FUser:=0;
FCourse:=0;
UserStatus:=usNone;
FLesson:=0;
end;
{ TInvitation }
function TInvitation.GetUserStatus: TUserStatus;
begin
Result:=TUserStatus(FStatus);
end;
procedure TInvitation.SetUserStatus(AValue: TUserStatus);
begin
FStatus:=Ord(AValue);
end;
procedure TInvitation.AssignTo(Dest: TPersistent);
var
aDest: TInvitation;
begin
inherited AssignTo(Dest);
if not (Dest is TInvitation) then
Exit;
aDest:=TInvitation(Dest);
aDest.FApplied:=FApplied;
aDest.FCapacity:=FCapacity;
aDest.FCourse:=FCourse;
aDest.FStatus:=FStatus;
end;
function TInvitation.GetID64: Int64;
begin
Result:=FID;
end;
procedure TInvitation.SetID64(AValue: Int64);
begin
FID:=AValue;
end;
procedure TInvitation.Initiate;
begin
inherited Initiate;
FCapacity:=0;
FApplied:=0;
FCourse:=0;
UserStatus:=usStudent;
end;
class function TInvitation.EntityType: TEntityType;
begin
Result:=seInvitation;
end;
{ TSlide }
procedure TSlide.Initiate;
begin
inherited;
FLesson:=0;
FInteractive:=True;
end;
procedure TSlide.AssignTo(Dest: TPersistent);
var
aDest: TSlide;
begin
inherited AssignTo(Dest);
if not (Dest is TSlide) then
Exit;
aDest:=TSlide(Dest);
aDest.FLesson:=FLesson;
end;
class function TSlide.EntityType: TEntityType;
begin
Result:=seSlide;
end;
function TSlide.GetParentID: Int64;
begin
Result:=FLesson;
end;
{ TLesson }
procedure TLesson.AssignTo(Dest: TPersistent);
var
aDest: TLesson;
begin
inherited AssignTo(Dest);
if not (Dest is TLesson) then
Exit;
aDest:=TLesson(Dest);
aDest.FCourse:=FCourse;
end;
function TLesson.GetParentID: Int64;
begin
Result:=FCourse;
end;
procedure TLesson.Initiate;
begin
inherited;
FCourse:=0;
end;
class function TLesson.EntityType: TEntityType;
begin
Result:=seLesson;
end;
{ TCourse }
function TCourse.GetLicType: TLicType;
begin
Result:=TLicType(FVisibility);
end;
procedure TCourse.SetLicType(AValue: TLicType);
begin
FVisibility:=Ord(AValue);
end;
procedure TCourse.AssignTo(Dest: TPersistent);
var
aDest: TCourse;
begin
inherited AssignTo(Dest);
if not (Dest is TCourse) then
Exit;
aDest:=TCourse(Dest);
aDest.FContact:=FContact;
aDest.FOwner:=FOwner;
aDest.FShowContact:=FShowContact;
aDest.FVisibility:=FVisibility;
aDest.FTesting:=FTesting;
aDest.HistoryChat:=FHistoryChat;
end;
class function TCourse.EntityType: TEntityType;
begin
Result:=seCourse;
end;
function TCourse.GetParentID: Int64;
begin
Result:=FOwner;
end;
procedure TCourse.Initiate;
begin
inherited;
FOwner:=0;
FVisibility:=0;
FContact:=EmptyStr;
FTesting:=False;
FHistoryChat:=EmptyStr;
end;
{ TCourseElement }
function TCourseElement.GetMediaType: TContentType;
begin
Result:=TContentType(FMediaType);
end;
procedure TCourseElement.SetMediaType(AValue: TContentType);
begin
FMediaType:=Ord(AValue);
end;
procedure TCourseElement.AssignTo(Dest: TPersistent);
var
aDest: TCourseElement;
begin
inherited AssignTo(Dest);
if not (Dest is TCourseElement) then
Exit;
aDest:=TCourseElement(Dest);
aDest.FInteractive:=FInteractive;
aDest.FMedia:=FMedia;
aDest.FMediaType:=FMediaType;
aDest.FText:=FText;
end;
function TCourseElement.GetID64: Int64;
begin
Result:=Fid;
end;
procedure TCourseElement.SetID64(AValue: Int64);
begin
Fid:=AValue;
end;
class function TCourseElement.EntityType: TEntityType;
begin
Result:=seCourse;
end;
procedure TCourseElement.Initiate;
begin
inherited Initiate;
FInteractive:=False;
FMedia:=EmptyStr;
FMediaType:=0;
FText:=EmptyStr;
end;
{ TSchoolElement }
function TSchoolElement.GetName: String;
begin
if FName<>EmptyStr then
Result:=FName
else begin
Result:=ClassName;
Removeleadingchars(Result, ['T', 't']);
end;
end;
procedure TSchoolElement.Initiate;
begin
FName:=EmptyStr;
FTeacher:=0;
end;
procedure TSchoolElement.SetName(AValue: String);
begin
FName:=AValue;
end;
procedure TSchoolElement.AssignTo(Dest: TPersistent);
begin
if not (Dest is TSchoolElement) then
begin
inherited AssignTo(Dest);
Exit;
end;
TSchoolElement(Dest).FName:=FName;
TSchoolElement(Dest).FTeacher:=FTeacher;
end;
class function TSchoolElement.EntityAlias: String;
begin
Result:=SchoolEntityNames[EntityType];
end;
class function TSchoolElement.EntityType: TEntityType;
begin
Result:=seUnknown;
end;
{ TUser }
procedure TUser.AssignTo(Dest: TPersistent);
var
aDest: TUser;
begin
inherited AssignTo(Dest);
if not (Dest is TUser) then
Exit
else begin
aDest:=TUser(Dest);
aDest.FLang:=FLang;
aDest.FSession:=FSession;
end;
end;
function TUser.GetID64: Int64;
begin
Result:=Fid;
end;
procedure TUser.SetID64(AValue: Int64);
begin
Fid:=AValue;
end;
constructor TUser.Create;
begin
Initiate;
end;
class function TUser.EntityType: TEntityType;
begin
Result:=seUser;
end;
procedure TUser.Initiate;
begin
inherited;
FLang:='en';
FSession:=0;
end;
end.
|
unit while_loop_3;
interface
var
G: Int32;
implementation
procedure Test;
var
x, y: Int32;
begin
G := 0;
x := 0;
while x < 10 do
begin
y := 0;
while y < 10 do
begin
y := y + 1;
G := G + 1;
end;
x := x + 1;
end;
end;
initialization
Test();
finalization
Assert(G = 100);
end. |
unit DBMain;
{$mode objfpc}{$H+}
interface
uses
connection_transaction, Classes, SysUtils, sqldb, DB, IBConnection, FileUtil,
SynHighlighterSQL, SynEdit, Forms, Controls, Graphics, Dialogs,
DBGrids, StdCtrls, ExtCtrls, Menus, Buttons, DBCtrls, FormConnect,
metadata, listview, aboutsdb, time_table, record_cards, query_filter;
type
{ TMainForm }
TMainForm = class(TForm)
DataSourceComponent: TDataSource;
DBGrid: TDBGrid;
ControlPanel: TPanel;
DBQuery: TSQLQuery;
MainMenu: TMainMenu;
EntryField: TMemo;
MenuTables: TMenuItem;
MenuOpenSQL: TMenuItem;
MenuDatabase: TMenuItem;
MenuConnect: TMenuItem;
MenuDisconnect: TMenuItem;
MenuHelp: TMenuItem;
MenuAbout: TMenuItem;
MenuExecSQL: TMenuItem;
MenuLists: TMenuItem;
MenuQuit: TMenuItem;
MenuStatements: TMenuItem;
EntryGridSplitter: TSplitter;
procedure ExecuteStatementsClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure MenuAboutClick(Sender: TObject);
procedure MenuConnectClick(Sender: TObject);
procedure MenuDisconnectClick(Sender: TObject);
procedure MenuExecSQLClick(Sender: TObject);
procedure MenuOpenSQLClick(Sender: TObject);
procedure ExecuteEntryFieldStatements;
procedure MenuQuitClick(Sender: TObject);
procedure TryToConnectDB;
procedure ShowDBTable(Sender: TObject);
procedure ShowTimeTable(Sender: TObject);
procedure RecordCardOkClick(Sender: TObject);
procedure TableFiltersPopup(Sender: TObject);
procedure TableFiltersPopupClick(Sender: TObject);
end;
var
MainForm: TMainForm;
implementation
{$R *.lfm}
{ TMainForm }
procedure TMainForm.ExecuteStatementsClick(Sender: TObject);
begin
ExecuteEntryFieldStatements;
ActiveControl := EntryField;
end;
procedure TMainForm.FormCreate(Sender: TObject);
var
i: integer;
miLists: array of TMenuItem;
miTables: array of TMenuItem;
begin
SetLength(miLists, Length(DBTables));
SetLength(miTables, Length(DBTables));
for i := Low(miLists) to High(miLists) do begin
miLists[i] := TMenuItem.Create(MainMenu);
miTables[i] := TMenuItem.Create(MainMenu);
with miLists[i] do begin
Caption := DBTables[i].Caption;
Tag := i;
OnClick := @ShowDBTable;
end;
with miTables[i] do begin
Caption := DBTables[i].Caption;
Tag := i;
OnClick := @ShowTimeTable;
end;
end;
MainMenu.Items[0].Add(miLists);
MainMenu.Items[1].Add(miTables);
CardsManager.OnRequestRefreshTables := @RecordCardOkClick;
end;
procedure TMainForm.MenuAboutClick(Sender: TObject);
begin
AboutProg.ShowModal;
end;
procedure TMainForm.MenuConnectClick(Sender: TObject);
begin
TryToConnectDB;
end;
procedure TMainForm.MenuDisconnectClick(Sender: TObject);
begin
with ConTran.DBConnection do begin
Connected := False;
Password := '';
end;
end;
procedure TMainForm.MenuExecSQLClick(Sender: TObject);
begin
DBQuery.Close;
DBQuery.SQL.Text := EntryField.Lines.Text;
DBQuery.ExecSQL;
end;
procedure TMainForm.ShowDBTable(Sender: TObject);
var
MI: TMenuItem;
begin
MI := (Sender as TMenuItem);
if TDBTableForm.FormExists(MI.Tag) then
TDBTableForm.FormSetFocus(MI.Tag)
else begin
DBTableForms[MI.Tag] := TDBTableForm.Create(DBTables[MI.Tag]);
DBTableForms[MI.Tag].Tag := MI.Tag;
DBTableForms[MI.Tag].OnShowAsTableClick := @ShowTimeTable;
DBTableForms[MI.Tag].OnFilterPopup := @TableFiltersPopup;
DBTableForms[MI.Tag].Show;
end;
end;
procedure TMainForm.ShowTimeTable(Sender: TObject);
var
MI: TMenuItem;
begin
MI := (Sender as TMenuItem);
if TTimeTable.FormExists(MI.Tag) then
TTimeTable.FormSetFocus(MI.Tag)
else begin
TimeTables[MI.Tag] := TTimeTable.Create(DBTables[MI.Tag]);
TimeTables[MI.Tag].Tag := MI.Tag;
TimeTables[MI.Tag].OnShowAsListClick := @ShowDBTable;
TimeTables[MI.Tag].OnFilterPopup := @TableFiltersPopup;
TimeTables[MI.Tag].Show;
end;
end;
procedure TMainForm.TryToConnectDB;
var
i: integer;
begin
if ConnectForm.ShowModal = mrOk then
with ConTran.DBConnection do begin
for i := 0 to High(DBTables) do
TDBTableForm.DestroyTableForm(i);
Connected := False;
DatabaseName := ConnectForm.DBPath.Text;
UserName := ConnectForm.DBUserName.Text;
Password := ConnectForm.DBPassword.Text;
Connected := True;
end;
end;
procedure TMainForm.MenuOpenSQLClick(Sender: TObject);
begin
ExecuteEntryFieldStatements;
end;
procedure TMainForm.ExecuteEntryFieldStatements;
begin
DBQuery.Close;
DBQuery.SQL.Text := EntryField.Lines.Text;
DBQuery.Open;
end;
procedure TMainForm.MenuQuitClick(Sender: TObject);
begin
Close;
end;
procedure TMainForm.RecordCardOkClick(Sender: TObject);
begin
TDBTableForm.RefreshLists;
TTimeTable.RefreshTables;
end;
procedure TMainForm.TableFiltersPopup(Sender: TObject);
var
i: integer;
PopMenu: TPopupMenu;
MenuItem: TMenuItem;
TimeTable: TTimeTable;
DBTableForm: TDBTableForm;
begin
PopMenu := Sender as TPopupMenu;
if PopMenu.Owner.ClassType = TTimeTable then
TimeTable := PopMenu.Owner as TTimeTable
else
DBTableForm := PopMenu.Owner as TDBTableForm;
PopMenu.Items.Clear;
for i := 0 to Length(DBTables) - 1 do begin
MenuItem := TMenuItem.Create(Self);
MenuItem.Caption := DBTables[i].Caption + ' (список)';
MenuItem.Visible := TDBTableForm.FormExists(i) and (DBTableForm <> DBTableForms[i]);
MenuItem.OnClick := @TableFiltersPopupClick;
MenuItem.Tag := i;
PopMenu.Items.Add(MenuItem);
end;
for i := 0 to Length(DBTables) - 1 do begin
MenuItem := TMenuItem.Create(Self);
MenuItem.Caption := DBTables[i].Caption + ' (таблица)';
MenuItem.Visible := TTimeTable.FormExists(i) and (TimeTable <> TimeTables[i]);
MenuItem.OnClick := @TableFiltersPopupClick;
MenuItem.Tag := i + Length(DBTables);
PopMenu.Items.Add(MenuItem);
end;
end;
procedure TMainForm.TableFiltersPopupClick(Sender: TObject);
var
MenuItem: TMenuItem;
FiltersFrom: TQueryFilterDynArray;
TimeTable: TTimeTable;
DBTableForm: TDBTableForm;
PopMenu: TPopupMenu;
begin
MenuItem := Sender as TMenuItem;
PopMenu := MenuItem.Parent.Owner as TPopupMenu;
if MenuItem.Tag < Length(DBTables) then
FiltersFrom := DBTableForms[MenuItem.Tag].Filters
else
FiltersFrom := TimeTables[MenuItem.Tag mod Length(DBTables)].Filters;
if PopMenu.Owner.ClassType = TTimeTable then begin
TimeTable := (MenuItem.Parent.Owner as TPopupMenu).Owner as TTimeTable;
TQueryFilter.CopyFilters(
TimeTable.Table, FiltersFrom, TimeTable.Filters, TimeTable.sbxFilters);
TimeTable.pmCopyFiltersFromClick(Sender);
end else begin
DBTableForm := (MenuItem.Parent.Owner as TPopupMenu).Owner as TDBTableForm;
TQueryFilter.CopyFilters(
DBTableForm.Table, FiltersFrom, DBTableForm.Filters, DBTableForm.sbxFilters);
DBTableForm.pmCopyFiltersClick(Sender);
end;
end;
end.
|
unit UnitClassInfoEx;
interface
uses
{$IFDEF VER230} // XE2
{$DEFINE HAS_UNITSCOPE}
{$ENDIF}
{$IFDEF VER240} // XE3
{$DEFINE HAS_UNITSCOPE}
{$ENDIF}
{$IFDEF VER250} // XE4
{$DEFINE HAS_UNITSCOPE}
{$ENDIF}
{$IFDEF HAS_UNITSCOPE}
WinAPI.Windows, System.TypInfo;
{$ELSE}
Windows, TypInfo;
{$ENDIF}
type
PTypeInfos = array of PTypeInfo;
TModules = array of HModule;
{$IFNDEF CPUX64}
// Delphi 早期版本NativeInt计算起来会有内部错误
NativeUInt = Cardinal;
NativeInt = Integer;
{$ENDIF}
// 获取一个指定模块中的类信息
function GetAllClassInfos_FromModule(AModule: HModule): PTypeInfos;
// 从system的Modulelist里面枚举模块,获取模块中类信息
function GetAllClassInfos_FromSystemModuleList(): PTypeInfos;
function GetProcessModules(): TModules;
implementation
const
MinClassTypeInfoSize = SizeOf(TTypeKind) + 2 { name } + SizeOf(Tclass) +
SizeOf(PPTypeInfo) + SizeOf(smallint) + 2 { unitname };
type
TMemoryRegion = record
BaseAddress: NativeInt;
MemorySize: NativeInt;
end;
TMemoryRegions = array of TMemoryRegion;
function EnumProcessModules(hProcess: THandle; lphModule: PDWORD; cb: DWORD;
var lpcbNeeded: DWORD): BOOL; stdcall; external 'psapi.dll';
function GetProcessModules(): TModules;
var
cb: DWORD;
ret: BOOL;
begin
if EnumProcessModules(GetCurrentProcess, nil, 0, cb) then
begin
SetLength(Result, cb div SizeOf(HModule));
if not EnumProcessModules(GetCurrentProcess, @Result[0], cb, cb) then
Result := nil;
end;
end;
function IsValidityMemoryBlock(MemoryRegions: TMemoryRegions;
address, Size: NativeUInt): Boolean;
var
MemoryRegion: TMemoryRegion;
i: Integer;
mbi: TMemoryBasicInformation;
begin
{
if VirtualQueryEx(GetCurrentProcess, Pointer(address), mbi, SizeOf(mbi)) <> 0
then
begin
GetTickCount;
end;
}
Result := False;
//for MemoryRegion in MemoryRegions do
for i := low(MemoryRegions) to High(MemoryRegions) do
begin
MemoryRegion := MemoryRegions[i];
if (address >= MemoryRegion.BaseAddress) and
((address + Size) <= (MemoryRegion.BaseAddress + MemoryRegion.MemorySize))
then
begin
Result := True;
Exit;
end;
end;
end;
procedure GetExecutableMemoryregions(var MemoryRegions: TMemoryRegions);
var
address: NativeUInt;
mbi: memory_basic_information;
processhandle: THandle;
stop: NativeUInt;
begin
processhandle := GetCurrentProcess;
SetLength(MemoryRegions, 0);
address := 0;
{$IFDEF CPUX64}
stop := $7FFFFFFFFFFFFFFF
{$ELSE}
stop := $7FFFFFFF;
{$ENDIF}
while (address < stop) and (VirtualQueryEx(processhandle, Pointer(address),
mbi, SizeOf(mbi)) <> 0) and ((address + mbi.RegionSize) > address) do
begin
if (mbi.state = MEM_COMMIT) and
(((mbi.Protect and PAGE_EXECUTE_READ) = PAGE_EXECUTE_READ) or
((mbi.Protect and PAGE_READWRITE) = PAGE_READWRITE) or
((mbi.Protect and PAGE_EXECUTE_READWRITE) = PAGE_EXECUTE_READWRITE)) then
begin
// executable
SetLength(MemoryRegions, Length(MemoryRegions) + 1);
MemoryRegions[Length(MemoryRegions) - 1].BaseAddress :=
NativeUInt(mbi.BaseAddress);
MemoryRegions[Length(MemoryRegions) - 1].MemorySize := mbi.RegionSize;
end;
inc(address, mbi.RegionSize);
end;
end;
procedure GetExecutableMemoryRegionsInRang(address, stop: NativeUInt;
var MemoryRegions: TMemoryRegions);
var
mbi: memory_basic_information;
processhandle: THandle;
begin
processhandle := GetCurrentProcess;
SetLength(MemoryRegions, 0);
while (address < stop) and (VirtualQueryEx(processhandle, Pointer(address),
mbi, SizeOf(mbi)) <> 0) and ((address + mbi.RegionSize) > address) do
begin
if (mbi.state = MEM_COMMIT) and
(((mbi.Protect and PAGE_EXECUTE_READ) = PAGE_EXECUTE_READ) or
((mbi.Protect and PAGE_READWRITE) = PAGE_READWRITE) or
((mbi.Protect and PAGE_EXECUTE_READWRITE) = PAGE_EXECUTE_READWRITE)) then
begin
// executable
SetLength(MemoryRegions, Length(MemoryRegions) + 1);
MemoryRegions[Length(MemoryRegions) - 1].BaseAddress :=
NativeUInt(mbi.BaseAddress);
MemoryRegions[Length(MemoryRegions) - 1].MemorySize := mbi.RegionSize;
end;
inc(address, mbi.RegionSize);
end;
end;
function IsValidityClassInfo(ProcessMemoryRegions: TMemoryRegions; p: PAnsiChar;
var RealResult: PTypeInfos): Boolean; forward;
function IsValidityString(p: PAnsiChar; Length: Byte): Boolean;
var
i: Integer;
begin
{
我假定Delphi的ClassName都是英文.中文的话实际上会被UTF8编码.
另外这个也不包含编译器编译时产生临时类的类名.
临时类名为了不和程序员手写的类重名一般都有@#$之类的
}
Result := True;
if p^ in ['a' .. 'z', 'A' .. 'Z', '_'] then
begin
for i := 0 to Length - 1 do
begin { 类名有时会有. ,比如内嵌类,UnitName也会有.泛型类名会有<> }
if not(p[i] in ['a' .. 'z', '<', '>', 'A' .. 'Z', '_', '.', '0' .. '9'])
then
begin
Result := False;
Exit;
end;
end;
end
else
Result := False;
end;
function FindTypeInfo(const RealResult: PTypeInfos; p: Pointer): Boolean;
var
i: Integer;
begin
Result := False;
for i := Low(RealResult) to High(RealResult) do
if RealResult[i] = p then
begin
Result := True;
Break;
end;
end;
procedure AddTypeInfo(var RealResult: PTypeInfos; p: PTypeInfo);
begin
//if FindTypeInfo(RealResult, p) then
if p^.Name = 'TForm1.TTT' then
begin
GetTickCount;
//Exit;
end;
SetLength(RealResult, Length(RealResult) + 1);
RealResult[Length(RealResult) - 1] := p;
end;
function IsValidityClassData(ProcessMemoryRegions: TMemoryRegions; p: PAnsiChar;
var RealResult: PTypeInfos): Boolean;
var
td: PTypeData;
parentInfo: PPTypeInfo;
parentFinded : Boolean;
begin
Result := False;
td := PTypeData(p);
parentInfo := td.parentInfo;
if not IsValidityString(@td.UnitName[1], Byte(td.UnitName[0])) then
Exit;
if GetTypeData(TypeInfo(TObject)) = td then
begin
Result := True;
Exit;
end;
if not IsValidityMemoryBlock(ProcessMemoryRegions, NativeUInt(parentInfo),
SizeOf(Pointer)) then
Exit;
if not IsValidityMemoryBlock(ProcessMemoryRegions, NativeUInt(parentInfo^),
MinClassTypeInfoSize) then
Exit;
{ 遍历ParentInfo,直到找到TObject为止 }
parentFinded := FindTypeInfo(RealResult, parentInfo^);
if parentFinded
or IsValidityClassInfo(ProcessMemoryRegions, PAnsiChar(parentInfo^),
RealResult) then
begin
Result := True;
if not parentFinded then
AddTypeInfo(RealResult, ParentInfo^);
Exit;
end;
end;
function IsValidityClassInfo(ProcessMemoryRegions: TMemoryRegions; p: PAnsiChar;
var RealResult: PTypeInfos): Boolean;
var
classNamelen: Byte;
classname: ansistring;
begin
Result := False;
if not IsValidityMemoryBlock(ProcessMemoryRegions, NativeUInt(p),
MinClassTypeInfoSize) then
Exit;
if IsBadReadPtr(p, MinClassTypeInfoSize) then
Exit;
if ord(p^) = ord(tkClass) then // ord(tkClass) = 7
begin
inc(p);
classNamelen := ord(p^);
SetLength(classname, classNamelen);
Move((p + 1)^, PAnsiChar(classname)^, classNamelen);
if (classNamelen in [1 .. $FE]) then { Shortstring第一个字节是长度,最多254个 }
begin
inc(p);
if IsValidityString(PAnsiChar(p), classNamelen) then
begin
// OutputDebugStringA(PAnsiChar(classname));
inc(p, classNamelen);
if IsValidityClassData(ProcessMemoryRegions, p, RealResult) then
begin
Result := True;
Exit;
end;
end;
end;
end;
end;
procedure GetRegionClassInfos(ProcessMemoryRegions: TMemoryRegions;
const MemoryRegion: TMemoryRegion; var RealResult: PTypeInfos);
var
p: PAnsiChar;
MaxAddr: NativeInt;
begin
p := PAnsiChar(MemoryRegion.BaseAddress);
MaxAddr := MemoryRegion.BaseAddress + MemoryRegion.MemorySize -
MinClassTypeInfoSize;
while NativeInt(p) < MaxAddr do
begin
if IsValidityClassInfo(ProcessMemoryRegions, p, RealResult) then
begin
AddTypeInfo(RealResult, PTypeInfo(p));
// OutputDebugStringA(PAnsiChar('classname = ' + PTypeInfo(p).Name));
inc(p, MinClassTypeInfoSize);
end
else
inc(p);
end;
end;
function _GetAllClassInfos_FromModule(ProcessMemoryRegions: TMemoryRegions;
AModule: HModule): PTypeInfos;
var
MemoryRegions: TMemoryRegions;
i: Integer;
addr, stop: NativeUInt;
dos: PImageDosHeader;
nt: PImageNtHeaders;
begin
Result := nil;
// SetLength(Result, 1);
// Result[0] := TypeInfo(TObject);
//
MemoryRegions := nil;
addr := AModule;
dos := PImageDosHeader(addr);
nt := PImageNtHeaders(addr + dos^._lfanew);
GetExecutableMemoryRegionsInRang(addr, addr + nt.OptionalHeader.SizeOfImage,
MemoryRegions);
for i := Low(MemoryRegions) to High(MemoryRegions) do
begin
GetRegionClassInfos(ProcessMemoryRegions, MemoryRegions[i], Result);
// OutputDebugString(PChar(format('(%d;%d)',[MemoryRegions[i].BaseAddress,MemoryRegions[i].MemorySize])));
end;
end;
function GetAllClassInfos_FromModule(AModule: HModule): PTypeInfos;
var
ProcessMemoryRegions: TMemoryRegions;
begin
GetExecutableMemoryregions(ProcessMemoryRegions);
Result := _GetAllClassInfos_FromModule(ProcessMemoryRegions, AModule);
end;
function GetAllClassInfos_FromSystemModuleList(): PTypeInfos;
var
ProcessMemoryRegions: TMemoryRegions;
lm: PLibModule;
moduleTypeInfos: PTypeInfos;
i: Integer;
oldLen: Integer;
s: string;
begin
Result := nil;
//SetLength(Result, 1);
//Result[0] := TypeInfo(TObject);
//
lm := LibModuleList;
GetExecutableMemoryregions(ProcessMemoryRegions);
while True do
begin
SetLength(s, MAX_PATH);
GetModuleFileName(lm.Instance, PChar(s), Length(s));
OutputDebugString(PChar(s));
moduleTypeInfos := _GetAllClassInfos_FromModule(ProcessMemoryRegions,
lm.Instance);
oldLen := Length(Result);
SetLength(Result, oldLen + Length(moduleTypeInfos));
for i := Low(moduleTypeInfos) to High(moduleTypeInfos) do
Result[oldLen + i] := moduleTypeInfos[i];
if lm.Next = nil then
Break;
lm := lm.Next;
end;
end;
end.
|
{**
* @Author: Du xinming
* @Contact: QQ<36511179>; Email<lndxm1979@163.com>
* @Version: 0.0
* @Date: 2019.1
* @Brief:
* @References:
* A PAINLESS GUIDE TO CRC ERROR DETECTION ALGORITHMS
* @Remark:
* TABLE ALGORITHM:
* r = 0;
* while (len--)
* r = ((r << 8) | *p++) ^ t[(r >> (W - 8)) & 0xFF];
*
* DIRECT TABLE ALGORITHM:
* r = 0;
* while (len--)
* r = (r << 8) ^ t[(r >> (W - 8)) ^ *p++];
*
* @Modifications:
*
*}
unit org.algorithms.crc;
interface
type
TCrc<T> = class
public type
TCrcTable = array [0..255] of T;
protected
FPoly: T;
FInit: T;
FXorOut: T;
FTable: TCrcTable;
FHiMask: T;
public
property Init: T read FInit;
property XorOut: T read FXorOut;
end;
TCrc8 = class(TCrc<Byte>)
public type
TCrc8Type = (
crc_8_ATM,
crc_8_ITU,
crc_8_ICODE,
crc_8_J1850
);
private
procedure GenTable;
public
constructor Create(Crc8Type: TCrc8Type = crc_8_ATM); overload;
constructor Create(Poly, Init, XorOut: Byte); overload;
function Compute(Msg: Pointer; nBytes: Integer): Byte; overload;
function Compute(Msg: Pointer; nBytes: Integer; Remander: Byte): Byte; overload;
end;
TCrc16 = class(TCrc<Word>)
public type
TCrc16Type = (
crc_16_CCITT_FFFF,
crc_16_CCITT_1D0F,
crc_16_GENIBUS,
crc_16_XMODEM,
crc_16_BUYPASS,
crc_16_DDS110,
crc_16_DECT_R,
crc_16_DECT_X,
crc_16_EN_13757,
crc_16_T10_DIF,
crc_16_TELEDISK
);
private
procedure GenTable;
public
constructor Create(Crc16Type: TCrc16Type = crc_16_CCITT_FFFF); overload;
constructor Create(Poly, Init, XorOut: Word); overload;
function Compute(Msg: Pointer; nBytes: Integer): Word; overload;
function Compute(Msg: Pointer; nBytes: Integer; Remander: Word): Word; overload;
end;
TCrc32 = class(TCrc<Cardinal>)
public type
TCrc32Type = (
crc_32_BZIP2,
crc_32_MPEG_2,
crc_32_POSIX,
crc_32_Q,
crc_32_XFER
);
private
procedure GenTable;
public
constructor Create(Crc32Type: TCrc32Type = crc_32_POSIX); overload;
constructor Create(Poly, Init, XorOut: Cardinal); overload;
function Compute(Msg: Pointer; nBytes: Integer): Cardinal; overload;
function Compute(Msg: Pointer; nBytes: Integer; Remander: Cardinal): Cardinal; overload;
end;
TCrc64 = class(TCrc<UInt64>)
public type
TCrc64Type = (
crc_64,
crc_64_WE
);
private
procedure GenTable;
public
constructor Create(Crc64Type: TCrc64Type = crc_64); overload;
constructor Create(Poly, Init, XorOut: UInt64); overload;
function Compute(Msg: Pointer; nBytes: Integer): UInt64; overload;
function Compute(Msg: Pointer; nBytes: Integer; Remander: UInt64): UInt64; overload;
end;
implementation
{ TCrc8 }
function TCrc8.Compute(Msg: Pointer; nBytes: Integer): Byte;
var
reg: Byte;
I: Integer;
buf: PByte;
begin
buf := Msg;
reg := FInit;
for I := 0 to nBytes - 1 do begin
reg := (reg shl 8) xor FTable[reg xor buf^];
Inc(buf);
end;
Result := reg xor FXorOut;
end;
constructor TCrc8.Create(Crc8Type: TCrc8Type);
begin
FHiMask := $80;
case Crc8Type of
// crc_8_ATM
crc_8_ATM: begin
FPoly := $07;
FInit := $00;
FXorOut := $00;
end;
// crc_8_ITU
crc_8_ITU: begin
FPoly := $07;
FInit := $00;
FXorOut := $55;
end;
// crc_8_ICODE
crc_8_ICODE: begin
FPoly := $1D;
FInit := $FD;
FXorOut := $00;
end;
// crc_8_J1850
crc_8_J1850: begin
FPoly := $1D;
FInit := $FF;
FXorOut := $FF;
end;
end;
GenTable();
end;
function TCrc8.Compute(Msg: Pointer; nBytes: Integer; Remander: Byte): Byte;
var
reg: Byte;
I: Integer;
buf: PByte;
begin
buf := Msg;
reg := Remander;
for I := 0 to nBytes - 1 do begin
reg := (reg shl 8) xor FTable[reg xor buf^];
Inc(buf);
end;
Result := reg;
end;
constructor TCrc8.Create(Poly, Init, XorOut: Byte);
begin
FHiMask := $80;
FPoly := Poly;
FInit := Init;
FXorOut := XorOut;
GenTable();
end;
procedure TCrc8.GenTable;
var
I, J, reg: Byte;
begin
for I := 0 to 255 do begin
reg := I; //
for J := 0 to 7 do begin
if reg and FHiMask <> 0 then
reg := (reg shl 1) xor FPoly
else
reg := reg shl 1;
end;
FTable[I] := reg;
end;
end;
{ TCrc16 }
function TCrc16.Compute(Msg: Pointer; nBytes: Integer; Remander: Word): Word;
var
reg: Word;
I: Integer;
buf: PByte;
begin
buf := Msg;
reg := Remander;
for I := 0 to nBytes - 1 do begin
reg := (reg shl 8) xor FTable[(reg shr 8) xor buf^];
Inc(buf);
end;
Result := reg;
end;
function TCrc16.Compute(Msg: Pointer; nBytes: Integer): Word;
var
reg: Word;
I: Integer;
buf: PByte;
begin
buf := Msg;
reg := FInit;
for I := 0 to nBytes - 1 do begin
reg := (reg shl 8) xor FTable[(reg shr 8) xor buf^];
Inc(buf);
end;
Result := reg xor FXorOut;
end;
constructor TCrc16.Create(Poly, Init, XorOut: Word);
begin
FHiMask := $8000;
FPoly := Poly;
FInit := Init;
FXorOut := XorOut;
GenTable();
end;
constructor TCrc16.Create(Crc16Type: TCrc16Type);
begin
FHiMask := $8000;
case Crc16Type of
// crc_16_CCITT
crc_16_CCITT_FFFF: begin
FPoly := $1021;
FInit := $FFFF;
FXorOut := $0000;
end;
crc_16_CCITT_1D0F: begin
FPoly := $1021;
FInit := $1D0F;
FXorOut := $0000;
end;
crc_16_GENIBUS: begin
FPoly := $1021;
FInit := $FFFF;
FXorOut := $FFFF;
end;
crc_16_XMODEM: begin
FPoly := $1021;
FInit := $0000;
FXorOut := $0000;
end;
// crc_16_BUYPASS
crc_16_BUYPASS: begin
FPoly := $8005;
FInit := $0000;
FXorOut := $0000;
end;
crc_16_DDS110: begin
FPoly := $8005;
FInit := $800D;
FXorOut := $0000;
end;
crc_16_DECT_R: begin
FPoly := $0589;
FInit := $0000;
FXorOut := $0001;
end;
crc_16_DECT_X: begin
FPoly := $0589;
FInit := $0000;
FXorOut := $0000;
end;
crc_16_EN_13757: begin
FPoly := $3D65;
FInit := $0000;
FXorOut := $FFFF;
end;
crc_16_T10_DIF: begin
FPoly := $8BB7;
FInit := $0000;
FXorOut := $0000;
end;
crc_16_TELEDISK: begin
FPoly := $A097;
FInit := $0000;
FXorOut := $0000;
end;
end;
GenTable();
end;
procedure TCrc16.GenTable;
var
I, J, reg: Word;
begin
for I := 0 to 255 do begin
reg := I shl 8; // 只关注有效位,或者说将有效位移到高8位
for J := 0 to 7 do begin
if reg and FHiMask <> 0 then
reg := (reg shl 1) xor FPoly
else
reg := reg shl 1;
end;
FTable[I] := reg;
end;
end;
{ TCrc32 }
function TCrc32.Compute(Msg: Pointer; nBytes: Integer; Remander: Cardinal): Cardinal;
var
reg: Cardinal;
I: Integer;
buf: PByte;
begin
buf := Msg;
reg := Remander;
for I := 0 to nBytes - 1 do begin
reg := (reg shl 8) xor FTable[(reg shr 24) xor buf^];
Inc(buf);
end;
Result := reg;
end;
function TCrc32.Compute(Msg: Pointer; nBytes: Integer): Cardinal;
var
reg: Cardinal;
I: Integer;
buf: PByte;
begin
buf := Msg;
reg := FInit;
for I := 0 to nBytes - 1 do begin
reg := (reg shl 8) xor FTable[(reg shr 24) xor buf^];
Inc(buf);
end;
Result := reg xor FXorOut;
end;
constructor TCrc32.Create(Poly, Init, XorOut: Cardinal);
begin
FHiMask := $80000000;
FPoly := Poly;
FInit := Init;
FXorOut := XorOut;
GenTable();
end;
constructor TCrc32.Create(Crc32Type: TCrc32Type);
begin
FHiMask := $80000000;
case Crc32Type of
crc_32_BZIP2: begin
FPoly := $04C11DB7;
FInit := $FFFFFFFF;
FXorOut := $FFFFFFFF;
end;
crc_32_MPEG_2: begin
FPoly := $04C11DB7;
FInit := $FFFFFFFF;
FXorOut := $00000000;
end;
// crc_32_POSIX
crc_32_POSIX: begin
FPoly := $04C11DB7;
FInit := $00000000;
FXorOut := $FFFFFFFF;
end;
crc_32_Q: begin
FPoly := $814141AB;
FInit := $00000000;
FXorOut := $00000000;
end;
crc_32_XFER: begin
FPoly := $000000AF;
FInit := $00000000;
FXorOut := $00000000;
end;
end;
GenTable();
end;
procedure TCrc32.GenTable;
var
I, J, reg: Cardinal;
begin
for I := 0 to 255 do begin
reg := I shl 24; // 只关注有效位,或者说将有效位移到高8位
for J := 0 to 7 do begin
if reg and FHiMask <> 0 then
reg := (reg shl 1) xor FPoly
else
reg := reg shl 1;
end;
FTable[I] := reg;
end;
end;
{ TCrc64 }
function TCrc64.Compute(Msg: Pointer; nBytes: Integer; Remander: UInt64): UInt64;
var
reg: UInt64;
I: Integer;
buf: PByte;
begin
buf := Msg;
reg := Remander;
for I := 0 to nBytes - 1 do begin
reg := (reg shl 8) xor FTable[(reg shr 56) xor buf^];
Inc(buf);
end;
Result := reg;
end;
function TCrc64.Compute(Msg: Pointer; nBytes: Integer): UInt64;
var
reg: UInt64;
I: Integer;
buf: PByte;
begin
buf := Msg;
reg := FInit;
for I := 0 to nBytes - 1 do begin
reg := (reg shl 8) xor FTable[(reg shr 56) xor buf^];
Inc(buf);
end;
Result := reg xor FXorOut;
end;
constructor TCrc64.Create(Poly, Init, XorOut: UInt64);
begin
FHiMask := $8000000000000000;
FPoly := Poly;
FInit := Init;
FXorOut := XorOut;
GenTable();
end;
constructor TCrc64.Create(Crc64Type: TCrc64Type);
begin
FHiMask := $8000000000000000;
case Crc64Type of
crc_64: begin
FPoly := $42F0E1EBA9EA3693;
FInit := $0000000000000000;
FXorOut := $0000000000000000;
end;
crc_64_WE: begin
FPoly := $42F0E1EBA9EA3693;
FInit := $FFFFFFFFFFFFFFFF;
FXorOut := $FFFFFFFFFFFFFFFF;
end;
end;
GenTable();
end;
procedure TCrc64.GenTable;
var
I, J, reg: UInt64;
begin
for I := 0 to 255 do begin
reg := I shl 56; // 只关注有效位,或者说将有效位移到高8位
for J := 0 to 7 do begin
if reg and FHiMask <> 0 then
reg := (reg shl 1) xor FPoly
else
reg := reg shl 1;
end;
FTable[I] := reg;
end;
end;
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{*******************************************************}
{ Helpers for C++ Variant binding. }
{*******************************************************}
unit System.Internal.VarHlpr;
{$HPPEMIT NOUSINGNAMESPACE}
interface
procedure VariantClear(var V: Variant);
procedure VariantArrayRedim(var V: Variant; High: Integer);
procedure VariantCast(const src: Variant; var dst: Variant; vt: Integer);
procedure VariantCpy(const src: Variant; var dst: Variant);
procedure VariantAdd(const src: Variant; var dst: Variant);
procedure VariantSub(const src: Variant; var dst: Variant);
procedure VariantMul(const src: Variant; var dst: Variant);
procedure VariantDiv(const src: Variant; var dst: Variant);
procedure VariantMod(const src: Variant; var dst: Variant);
procedure VariantAnd(const src: Variant; var dst: Variant);
procedure VariantOr(const src: Variant; var dst: Variant);
procedure VariantXor(const src: Variant; var dst: Variant);
procedure VariantShl(const src: Variant; var dst: Variant);
procedure VariantShr(const src: Variant; var dst: Variant);
function VariantAdd2(const V1: Variant; const V2: Variant): Variant;
function VariantSub2(const V1: Variant; const V2: Variant): Variant;
function VariantMul2(const V1: Variant; const V2: Variant): Variant;
function VariantDiv2(const V1: Variant; const V2: Variant): Variant;
function VariantMod2(const V1: Variant; const V2: Variant): Variant;
function VariantAnd2(const V1: Variant; const V2: Variant): Variant;
function VariantOr2(const V1: Variant; const V2: Variant): Variant;
function VariantXor2(const V1: Variant; const V2: Variant): Variant;
function VariantShl2(const V1: Variant; const V2: Variant): Variant;
function VariantShr2(const V1: Variant; const V2: Variant): Variant;
function VariantNot(const V1: Variant): Variant;
function VariantNeg(const V1: Variant): Variant;
function VariantGetElement(const V: Variant; i1: integer): Variant; overload;
function VariantGetElement(const V: Variant; i1, i2: integer): Variant; overload;
function VariantGetElement(const V: Variant; i1, i2, i3: integer): Variant; overload;
function VariantGetElement(const V: Variant; i1, i2, i3, i4: integer): Variant; overload;
function VariantGetElement(const V: Variant; i1, i2, i3, i4, i5: integer): Variant; overload;
procedure VariantPutElement(var V: Variant; const data: Variant; i1: integer); overload;
procedure VariantPutElement(var V: Variant; const data: Variant; i1, i2: integer); overload;
procedure VariantPutElement(var V: Variant; const data: Variant; i1, i2, i3: integer); overload;
procedure VariantPutElement(var V: Variant; const data: Variant; i1, i2, i3, i4: integer); overload;
procedure VariantPutElement(var V: Variant; const data: Variant; i1, i2, i3, i4, i5: integer); overload;
procedure VariantFromUnicodeString(var V: Variant; const Str: UnicodeString);
procedure VariantToUnicodeString(const V: Variant; var Str: UnicodeString);
function GetTypeInfoHelper(I: Cardinal): Pointer;
{$NODEFINE GetTypeInfoHelper}
implementation
uses System.Variants,
System.Classes,
System.UITypes,
System.Types;
{ C++Builder helpers, implementation }
procedure VariantClear(var V: Variant);
begin
VarClear(V);
end;
procedure VariantCast(const src: Variant; var dst: Variant; vt: Integer);
begin
VarCast(dst, src, vt);
end;
procedure VariantArrayRedim(var V: Variant; High: Integer);
begin
VarArrayRedim(V, High);
end;
procedure VariantCpy(const src: Variant; var dst: Variant);
begin
dst := src;
end;
procedure VariantAdd(const src: Variant; var dst: Variant);
begin
dst := dst + src;
end;
procedure VariantSub(const src: Variant; var dst: Variant);
begin
dst := dst - src;
end;
procedure VariantMul(const src: Variant; var dst: Variant);
begin
dst := dst * src;
end;
procedure VariantDiv(const src: Variant; var dst: Variant);
begin
dst := dst / src;
end;
procedure VariantMod(const src: Variant; var dst: Variant);
begin
dst := dst mod src;
end;
procedure VariantAnd(const src: Variant; var dst: Variant);
begin
dst := dst and src;
end;
procedure VariantOr(const src: Variant; var dst: Variant);
begin
dst := dst or src;
end;
procedure VariantXor(const src: Variant; var dst: Variant);
begin
dst := dst xor src;
end;
procedure VariantShl(const src: Variant; var dst: Variant);
begin
dst := dst shl src;
end;
procedure VariantShr(const src: Variant; var dst: Variant);
begin
dst := dst shr src;
end;
function VariantCmpEQ(const v1: Variant; const V2: Variant): Boolean;
begin
Result := v1 = v2;
end;
function VariantCmpLT(const V1: Variant; const V2: Variant): Boolean;
begin
Result := V1 < V2;
end;
function VariantCmpGT(const V1: Variant; const V2: Variant): Boolean;
begin
Result := V1 > V2;
end;
function VariantAdd2(const V1: Variant; const V2: Variant): Variant;
begin
Result := v1 + V2;
end;
function VariantSub2(const V1: Variant; const V2: Variant): Variant;
begin
Result := V1 - V2;
end;
function VariantMul2(const V1: Variant; const V2: Variant): Variant;
begin
Result := V1 * V2;
end;
function VariantDiv2(const V1: Variant; const V2: Variant): Variant;
begin
Result := V1 / V2;
end;
function VariantMod2(const V1: Variant; const V2: Variant): Variant;
begin
Result := V1 mod V2;
end;
function VariantAnd2(const V1: Variant; const V2: Variant): Variant;
begin
Result := V1 and V2;
end;
function VariantOr2(const V1: Variant; const V2: Variant): Variant;
begin
Result := V1 or V2;
end;
function VariantXor2(const V1: Variant; const V2: Variant): Variant;
begin
Result := V1 xor V2;
end;
function VariantShl2(const V1: Variant; const V2: Variant): Variant;
begin
Result := V1 shl V2;
end;
function VariantShr2(const V1: Variant; const V2: Variant): Variant;
begin
Result := V1 shr V2;
end;
function VariantNot(const V1: Variant): Variant;
begin
Result := not V1;
end;
function VariantNeg(const V1: Variant): Variant;
begin
Result := -V1;
end;
function VariantGetElement(const V: Variant; i1: integer): Variant; overload;
begin
Result := V[i1];
end;
function VariantGetElement(const V: Variant; i1, i2: integer): Variant; overload;
begin
Result := V[i1, i2];
end;
function VariantGetElement(const V: Variant; i1, i2, i3: integer): Variant; overload;
begin
Result := V[I1, i2, i3];
end;
function VariantGetElement(const V: Variant; i1, i2, i3, i4: integer): Variant; overload;
begin
Result := V[i1, i2, i3, i4];
end;
function VariantGetElement(const V: Variant; i1, i2, i3, i4, i5: integer): Variant; overload;
begin
Result := V[i1, i2, i3, i4, i5];
end;
procedure VariantPutElement(var V: Variant; const data: Variant; i1: integer); overload;
begin
V[i1] := data;
end;
procedure VariantPutElement(var V: Variant; const data: Variant; i1, i2: integer); overload;
begin
V[i1, i2] := data;
end;
procedure VariantPutElement(var V: Variant; const data: Variant; i1, i2, i3: integer); overload;
begin
V[i1, i2, i3] := data;
end;
procedure VariantPutElement(var V: Variant; const data: Variant; i1, i2, i3, i4: integer); overload;
begin
V[i1, i2, i3, i4] := data;
end;
procedure VariantPutElement(var V: Variant; const data: Variant; i1, i2, i3, i4, i5: integer); overload;
begin
V[i1, i2, i3, i4, i5] := data;
end;
procedure VariantFromUnicodeString(var V: Variant; const Str: UnicodeString);
begin
V := Str;
end;
procedure VariantToUnicodeString(const V: Variant; var Str: UnicodeString);
begin
Str := V;
end;
type
{$SCOPEDENUMS ON}
TypeInfoIndex = (tiiBoolean=1,
tiiByte=2,
tiiShortInt=3,
tiiWord=4,
tiiSmallInt=5,
tiiLongInt=6,
tiiLongWord=7,
tiiInt64=8,
tiiUInt64=9,
tiiFloat=10,
tiiDouble=11,
tiiExtended=12,
tiiAnsiChar=13,
tiiWideChar=14,
tiiCurrency=15,
tiiTDateTime=16,
tiiAnsiString=17,
tiiUnicodeString=18,
tiiWideString=19,
tiiTPointF=20,
tiiTAlphaColor=21,
tiiTNotifyEvent=22,
tiiIInterface=23,
tiiIInvokable=24,
tiiVariant=25,
tiiOleVariant=26,
tiiLast,
tiiMakeAnInt = MaxInt shr 1);
{$SCOPEDENUMS OFF}
function GetTypeInfoHelper(I: Cardinal): Pointer;
begin
Result := nil;
if (I >= Cardinal(TypeInfoIndex.tiiLast)) then
Exit;
case TypeInfoIndex(I) of
TypeInfoIndex.tiiBoolean: Result := System.TypeInfo(System.Boolean);
TypeInfoIndex.tiiByte: Result := System.TypeInfo(System.Byte);
TypeInfoIndex.tiiShortInt: Result := System.TypeInfo(System.ShortInt);
TypeInfoIndex.tiiWord: Result := System.TypeInfo(System.Word);
TypeInfoIndex.tiiSmallInt: Result := System.TypeInfo(System.SmallInt);
TypeInfoIndex.tiiLongInt: Result := System.TypeInfo(System.LongInt);
TypeInfoIndex.tiiLongWord: Result := System.TypeInfo(System.LongWord);
TypeInfoIndex.tiiInt64: Result := System.TypeInfo(System.Int64);
TypeInfoIndex.tiiUInt64: Result := System.TypeInfo(System.UInt64);
TypeInfoIndex.tiiFloat: Result := System.TypeInfo(System.Single);
TypeInfoIndex.tiiDouble: Result := System.TypeInfo(System.Double);
TypeInfoIndex.tiiExtended: Result := System.TypeInfo(System.Extended);
{$IFNDEF NEXTGEN}
TypeInfoIndex.tiiAnsiChar: Result := System.TypeInfo(System.AnsiChar);
{$ENDIF}
TypeInfoIndex.tiiWideChar: Result := System.TypeInfo(System.WideChar);
TypeInfoIndex.tiiCurrency: Result := System.TypeInfo(System.Currency);
TypeInfoIndex.tiiTDateTime: Result := System.TypeInfo(System.TDateTime);
{$IFNDEF NEXTGEN}
TypeInfoIndex.tiiAnsiString: Result := System.TypeInfo(System.AnsiString);
{$ENDIF}
TypeInfoIndex.tiiUnicodeString: Result := System.TypeInfo(System.UnicodeString);
{$IFNDEF NEXTGEN}
TypeInfoIndex.tiiWideString: Result := System.TypeInfo(System.WideString);
{$ENDIF}
TypeInfoIndex.tiiTPointF: Result := System.TypeInfo(System.Types.TPointF);
TypeInfoIndex.tiiTAlphaColor: Result := System.TypeInfo(System.UITypes.TAlphaColor);
TypeInfoIndex.tiiTNotifyEvent: Result := System.TypeInfo(System.Classes.TNotifyEvent);
TypeInfoIndex.tiiIInterface: Result := System.TypeInfo(System.IInterface);
TypeInfoIndex.tiiIInvokable: Result := System.TypeInfo(System.IInvokable);
TypeInfoIndex.tiiVariant: Result := System.TypeInfo(System.Variant);
TypeInfoIndex.tiiOleVariant: Result := System.TypeInfo(System.OleVariant);
end;
end;
end.
|
{*******************************************************}
{ }
{ Delphi Visual Component Library }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
{*******************************************************}
{ }
{ NOTE: On Windows XP and later there is a window }
{ class style (CS_DROPSHADOW) that can be }
{ specified in the CreateParams method of a }
{ TWinControl class to render the same effect as }
{ this control provides. }
{ }
{*******************************************************}
unit Vcl.ShadowWnd;
interface
uses Winapi.Windows, Winapi.Messages, System.Classes, Vcl.Controls, Vcl.Forms, Vcl.Graphics;
type
{ TShadowWindow }
TControlSide = (csRight, csBottom);
TShadowWindow = class(TCustomControl)
private
FControl: TControl;
FDesktop: TBitmap;
FSide: TControlSide;
{$IF NOT DEFINED(CLR)}
FRGB: COLORREF;
H,L,S: Word;
FCachedFade: Integer;
FCachedclr: COLORREF;
FCachedHue,
FCachedSat,
FCachedLum: Word;
{$IFEND}
procedure SetControl(const Value: TControl);
protected
procedure CreateParams(var Params: TCreateParams); override;
procedure Paint; override;
procedure WMEraseBkgnd(var Message: TWMEraseBkgnd); message WM_ERASEBKGND;
procedure Notification(AComponent: TComponent; Operation: TOperation);
override;
public
constructor Create(AOwner: TComponent); override;
constructor CreateShadow(AOwner: TComponent; ControlSide: TControlSide); virtual;
destructor Destroy; override;
procedure SetBounds(ALeft: Integer; ATop: Integer; AWidth: Integer;
AHeight: Integer); override;
property Control: TControl read FControl write SetControl;
property Side: TControlSide read FSide write FSide;
end;
implementation
uses System.SysUtils, System.Contnrs, System.Types, Vcl.GraphUtil;
const
Darkness = 58; // Darkness of the shadow
{ TShadowWindow }
constructor TShadowWindow.Create(AOwner: TComponent);
begin
inherited;
Side := csRight;
FDeskTop := TBitmap.Create;
FDesktop.HandleType := bmDDB;
{$IF DEFINED(CLR)}
Hide;
{$ELSE}
FDesktop.PixelFormat := pf24bit;
Hide;
FCachedclr := 0;
FCachedFade := 0;
{$IFEND}
ParentWindow := Vcl.Forms.Application.Handle;
end;
constructor TShadowWindow.CreateShadow(AOwner: TComponent;
ControlSide: TControlSide);
begin
Create(AOwner);
Side := ControlSide;
end;
destructor TShadowWindow.Destroy;
begin
FDeskTop.Free;
inherited;
end;
procedure TShadowWindow.CreateParams(var Params: TCreateParams);
begin
inherited CreateParams(Params);
with Params do
begin
if ParentWindow <> 0 then
Style := Style and not WS_CHILD or WS_POPUP or WS_OVERLAPPED;
WindowClass.Style := CS_SAVEBITS or CS_DBLCLKS or not (CS_HREDRAW or not CS_VREDRAW);
ExStyle := ExStyle or WS_EX_TOPMOST;
end;
end;
procedure TShadowWindow.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if (Operation = opRemove) and (AComponent = FControl) then
begin
FControl := nil;
Visible := False;
end;
end;
procedure TShadowWindow.Paint;
begin
inherited Paint;
Canvas.StretchDraw(System.Types.Rect(0,0,Width,Height), FDeskTop);
end;
procedure TShadowWindow.SetControl(const Value: TControl);
var
Pt: TPoint;
begin
if Assigned(FControl) then
FControl.RemoveFreeNotification(Self);
FControl := Value;
if not Assigned(FControl) then exit;
FControl.FreeNotification(Self);
if FControl.Parent <> nil then
Pt := FControl.ClientToScreen(FControl.ClientRect.TopLeft)
else
Pt := FControl.BoundsRect.TopLeft;
Hide;
case FSide of
csRight:
begin
if Control.Height <= 4 then
Exit;
SetBounds(Pt.X + Control.Width, Pt.Y + 4, 4, Control.Height - 4);
end;
csBottom:
begin
if Control.Width <= 4 then
Exit;
SetBounds(Pt.X + 4, Pt.Y + Control.Height, Control.Width, 4);
end;
end;
Show;
end;
procedure TShadowWindow.WMEraseBkgnd(var Message: TWMEraseBkgnd);
begin
Message.Result := 0;
end;
{$IF DEFINED(CLR)}
procedure TShadowWindow.SetBounds(ALeft, ATop, AWidth, AHeight: Integer);
function GetLum(X, Y: Integer): Integer;
var
H,L,S: Word;
Lum: Integer;
begin
ColorRGBToHLS(FDeskTop.Canvas.Pixels[X,Y], H, L, S);
Lum := L;
Result := Lum
end;
procedure CalcShadowColor(X, Y: Integer; Multiplier: Integer; FadeValue: Integer);
var
Clr: TColor;
begin
Clr := FDeskTop.Canvas.Pixels[X,Y];
FDeskTop.Canvas.Pixels[X,Y] := ColorAdjustLuma(Clr, FadeValue, False);
end;
var
DC: HDC;
X, Y: Integer;
begin
inherited;
if Visible then exit;
FDeskTop.Width := Width;
FDeskTop.Height := Height;
DC := GetDC(GetDeskTopWindow);
try
StretchBlt(FDeskTop.Canvas.Handle, 0, 0, Width, Height, DC,
Left, Top, Width, Height, SRCCOPY);
finally
ReleaseDC(GetDeskTopWindow, DC);
end;
case Side of
csRight:
begin
for X := 0 to Width - 1 do
begin
for Y := X to Height - 1 do
begin
if GetLum(X, Y) < Darkness then Continue;
if (Y <= Width) then
CalcShadowColor(X, Y, X, -Darkness + (X * 15) + (Width - Y) * 10)
else if (Y >= Height) then
CalcShadowColor(X, Y, X, -Darkness - ((Width - X) * 15) - ((Height - 8)- Y) * 15)
else
CalcShadowColor(X, Y, X, -Darkness + X * 15);
end;
end;
end;
csBottom:
for Y := 0 to Height - 1 do
begin
for X := Y to Width - 1 - Y do
begin
if GetLum(X, Y) < Darkness then Continue;
if (X <= Height) then
CalcShadowColor(X, Y, Y, -Darkness + (Y * 15) + (Height - X) * 10)
else if (X >= Width - Height) then
CalcShadowColor(X, Y, Y, -Darkness - ((Height - Y) * 15) - ((Width - 8)- X) * 15)
else
CalcShadowColor(X, Y, Y, -Darkness + Y * 15);
end;
end;
end;
end;
{$IFEND}
{$IF NOT DEFINED(CLR)}
const
MaxPixels = 4096;
IntensityCutoff = 140;
type
PRGBTripleArray = ^TRGBTripleArray;
TRGBTripleArray = array[0..MaxPixels - 1] of TRGBTriple;
procedure TShadowWindow.SetBounds(ALeft, ATop, AWidth, AHeight: Integer);
procedure CalcShadowColor(var RGBTriple: TRGBTriple; FadeValue: Integer);
var
Clr: TColor;
begin
Clr := ColorHLSToRGB(H, L + FadeValue, S);
RGBTriple.rgbtBlue := GetBValue(Clr);
RGBTriple.rgbtGreen := GetGValue(Clr);
RGBTriple.rgbtRed := GetRValue(Clr);
end;
procedure ColorRGBToHLS(clrRGB: COLORREF; var Hue, Luminance, Saturation: Word);
begin
if clrRGB = FCachedclr then
begin
Hue := FCachedHue;
Luminance := FCachedLum;
Saturation := FCachedSat;
end
else
begin
Vcl.GraphUtil.ColorRGBToHLS(clrRGB, Hue, Luminance, Saturation);
FCachedHue := Hue;
FCachedLum := Luminance;
FCachedSat := Saturation;
FCachedclr := clrRGB;
end;
end;
var
DC: HDC;
X, Y: Integer;
RGBArray: PRGBTripleArray;
begin
inherited;
if Visible then exit;
FDeskTop.Width := Width;
FDeskTop.Height := Height;
DC := GetDC(GetDeskTopWindow);
try
BitBlt(FDeskTop.Canvas.Handle, 0, 0, Width, Height, DC, Left, Top, SRCCOPY);
finally
ReleaseDC(GetDeskTopWindow, DC);
end;
case Side of
csRight:
for Y := 0 to Height - 1 do
begin
RGBArray := FDeskTop.Scanline[Y];
for X := 0 to Width - 1 do
begin
if Y - X < 0 then continue;
with RGBArray[X] do
begin
FRGB := RGB(rgbtRed, rgbtGreen, rgbtBlue);
ColorRGBToHLS(FRGB, H, L, S);
end;
if L < Darkness then
Continue;
if (Y <= Width) then
CalcShadowColor(RGBArray[X], -Darkness + (X * 15) + (Width - Y) * 10)
else if (Y >= Height) then
CalcShadowColor(RGBArray[X], -Darkness - ((Width - X) * 15) - ((Height - 8)- Y) * 15)
else
CalcShadowColor(RGBArray[X], -Darkness + X * 15);
end;
end;
csBottom:
for Y := 0 to Height - 1 do
begin
RGBArray := FDeskTop.Scanline[Y];
for X := Y to Width - 1 - Y do
begin
with RGBArray[X] do
begin
FRGB := RGB(rgbtRed, rgbtGreen, rgbtBlue);
ColorRGBToHLS(FRGB, H, L, S);
end;
if L < Darkness then Continue;
if (X <= Height) then
CalcShadowColor(RGBArray[X], -Darkness + (Y * 15) + (Height - X) * 10)
else if (X >= Width - Height) then
CalcShadowColor(RGBArray[X], -Darkness - ((Height - Y) * 15) - ((Width - 8)- X) * 15)
else
CalcShadowColor(RGBArray[X], -Darkness + Y * 15);
end;
end;
end;
end;
{$IFEND}
end.
|
unit ProducersExcelDataModule;
interface
uses
System.SysUtils, System.Classes, ExcelDataModule, Excel2010, Vcl.OleServer,
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,
CustomExcelTable, ProducerInterface;
{$WARN SYMBOL_PLATFORM OFF}
type
TProducersExcelTable = class(TCustomExcelTable)
private
FProducerInt: IProducer;
function GetName: TField;
function GetProducerType: TField;
protected
function CheckProducer: Boolean;
procedure SetFieldsInfo; override;
public
constructor Create(AOwner: TComponent); override;
function CheckRecord: Boolean; override;
property Name: TField read GetName;
property ProducerInt: IProducer read FProducerInt write FProducerInt;
property ProducerType: TField read GetProducerType;
end;
TProducersExcelDM = class(TExcelDM)
private
function GetExcelTable: TProducersExcelTable;
{ Private declarations }
protected
function CreateExcelTable: TCustomExcelTable; override;
public
property ExcelTable: TProducersExcelTable read GetExcelTable;
{ Public declarations }
end;
implementation
{ %CLASSGROUP 'Vcl.Controls.TControl' }
{$R *.dfm}
uses System.Variants, System.Math, FieldInfoUnit, ProgressInfo, ErrorType,
RecordCheck;
constructor TProducersExcelTable.Create(AOwner: TComponent);
begin
inherited;
end;
function TProducersExcelTable.CheckProducer: Boolean;
var
ARecordCheck: TRecordCheck;
begin
Assert(ProducerInt <> nil);
// Ищем производителя с таким-же именем без учёта регистра
Result := not ProducerInt.Exist(Name.Value);
// Если нашли такого-же производителя
if not Result then
begin
ARecordCheck.ErrorType := etWarring;
ARecordCheck.Row := ExcelRow.AsInteger;
ARecordCheck.Col := Name.Index + 1;
ARecordCheck.ErrorMessage := Name.AsString;
ARecordCheck.Description := 'Такой производитель уже существует.';
ProcessErrors(ARecordCheck);
end;
end;
function TProducersExcelTable.CheckRecord: Boolean;
begin
Result := inherited;
if Result then
begin
// Проверяем что такой производитель существует
Result := CheckProducer;
end;
end;
function TProducersExcelTable.GetName: TField;
begin
Result := FieldByName('Name');
end;
function TProducersExcelTable.GetProducerType: TField;
begin
Result := FieldByName('ProducerType');
end;
procedure TProducersExcelTable.SetFieldsInfo;
begin
FieldsInfo.Add(TFieldInfo.Create('Name', True,
'Название производителя не может быть пустым'));
FieldsInfo.Add(TFieldInfo.Create('Products'));
FieldsInfo.Add(TFieldInfo.Create('ProducerType', True,
'Тип производителя не может быть пустым'));
end;
function TProducersExcelDM.CreateExcelTable: TCustomExcelTable;
begin
Result := TProducersExcelTable.Create(Self);
end;
function TProducersExcelDM.GetExcelTable: TProducersExcelTable;
begin
Result := CustomExcelTable as TProducersExcelTable;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.