text stringlengths 14 6.51M |
|---|
unit Entidade.DespesaFixa;
interface
uses SimpleAttributes;
type
TDESPESA_FIXA = class
private
FVALOR: Double;
FDESCRICAO: string;
FVENCIMENTO: Integer;
FID_TIPO_LANCAMENTO: Integer;
FID_CONGREGACAO: Integer;
FID: Integer;
FID_FORNECEDOR: Integer;
FID_IGREJA: Integer;
procedure SetDESCRICAO(const Value: string);
procedure SetID(const Value: Integer);
procedure SetID_CONGREGACAO(const Value: Integer);
procedure SetID_FORNECEDOR(const Value: Integer);
procedure SetID_IGREJA(const Value: Integer);
procedure SetID_TIPO_LANCAMENTO(const Value: Integer);
procedure SetVALOR(const Value: Double);
procedure SetVENCIMENTO(const Value: Integer);
published
[PK,AutoInc]
property ID :Integer read FID write SetID;
property DESCRICAO:string read FDESCRICAO write SetDESCRICAO;
property ID_FORNECEDOR:Integer read FID_FORNECEDOR write SetID_FORNECEDOR;
property VENCIMENTO:Integer read FVENCIMENTO write SetVENCIMENTO;
property VALOR:Double read FVALOR write SetVALOR;
property ID_IGREJA:Integer read FID_IGREJA write SetID_IGREJA;
property ID_CONGREGACAO:Integer read FID_CONGREGACAO write SetID_CONGREGACAO;
property ID_TIPO_LANCAMENTO:Integer read FID_TIPO_LANCAMENTO write SetID_TIPO_LANCAMENTO;
end;
implementation
{ TDESPESA_FIXA }
procedure TDESPESA_FIXA.SetDESCRICAO(const Value: string);
begin
FDESCRICAO := Value;
end;
procedure TDESPESA_FIXA.SetID(const Value: Integer);
begin
FID := Value;
end;
procedure TDESPESA_FIXA.SetID_CONGREGACAO(const Value: Integer);
begin
FID_CONGREGACAO := Value;
end;
procedure TDESPESA_FIXA.SetID_FORNECEDOR(const Value: Integer);
begin
FID_FORNECEDOR := Value;
end;
procedure TDESPESA_FIXA.SetID_IGREJA(const Value: Integer);
begin
FID_IGREJA := Value;
end;
procedure TDESPESA_FIXA.SetID_TIPO_LANCAMENTO(const Value: Integer);
begin
FID_TIPO_LANCAMENTO := Value;
end;
procedure TDESPESA_FIXA.SetVALOR(const Value: Double);
begin
FVALOR := Value;
end;
procedure TDESPESA_FIXA.SetVENCIMENTO(const Value: Integer);
begin
FVENCIMENTO := Value;
end;
end.
|
unit uResourcestring;
interface
uses SysUtils;
resourcestring
APPLICATIONTITLE = 'Rock And Roll v2.0 ~ The Mega Man Editor';
APPLICATIONTITLESHORT = 'Rock And Roll v2.0';
implementation
end.
|
unit GX_ProofreaderExpert;
{$I GX_CondDefine.inc}
interface
uses
GX_ProofreaderData, GX_ConfigurationInfo, GX_Experts;
type
TCodeProofreaderExpert = class(TGX_Expert)
private
FProofreaderData: TProofreaderData;
protected
procedure SetActive(New: Boolean); override;
procedure InternalSaveSettings(Settings: TExpertSettings); override;
public
destructor Destroy; override;
function GetActionCaption: string; override;
class function GetName: string; override;
procedure Execute(Sender: TObject); override;
procedure Configure; override;
end;
implementation
uses
SysUtils, Dialogs, Controls,
GX_ProofreaderConfig, GX_ProofreaderDefaults, GX_MessageBox;
type
TCreateDefaultTablesMessage = class(TGxQuestionBoxAdaptor)
protected
function GetMessage: string; override;
end;
{ TCreateDefaultTablesMessage }
function TCreateDefaultTablesMessage.GetMessage: string;
resourcestring
SDefaultTablesCreated = 'Could not find the Code Proofreader data file:'
+ sLineBreak + '%s' + sLineBreak +
'Would you like to create the default replacement rules and dictionary entries?';
begin
Result := Format(SDefaultTablesCreated, [FData]);
end;
{ TCodeProofreaderExpert }
procedure TCodeProofreaderExpert.Execute(Sender: TObject);
begin
Configure;
end;
procedure TCodeProofreaderExpert.Configure;
var
CreatedDataToConfigure: Boolean;
Dlg: TfmProofreaderConfig;
FileName: string;
begin
CreatedDataToConfigure := False;
try
if FProofreaderData = nil then
begin
FProofreaderData := TProofreaderData.Create(ConfigurationKey);
CreatedDataToConfigure := True;
end;
FileName := FProofreaderData.XmlFileName;
if (not FileExists(FileName)) and
(ShowGxMessageBox(TCreateDefaultTablesMessage, FileName) = mrYes) then
begin
AddDefaultReplacementEntries(FProofreaderData);
AddDefaultDictionaryEntries(FProofreaderData);
FProofreaderData.SaveData;
end;
Dlg := TfmProofreaderConfig.Create(nil, Self, FProofreaderData);
try
SetFormIcon(Dlg);
Dlg.ShowModal;
finally
FreeAndNil(Dlg);
end;
SaveSettings;
finally
if CreatedDataToConfigure then
FreeAndNil(FProofreaderData);
end;
end;
destructor TCodeProofreaderExpert.Destroy;
begin
FreeAndNil(FProofreaderData);
inherited Destroy;
end;
function TCodeProofreaderExpert.GetActionCaption: string;
resourcestring
SProofMenuCaption = 'Code &Proofreader...';
begin
Result := SProofMenuCaption;
end;
class function TCodeProofreaderExpert.GetName: string;
begin
Result := 'CodeProofreader';
end;
procedure TCodeProofreaderExpert.InternalSaveSettings(Settings: TExpertSettings);
begin
inherited InternalSaveSettings(Settings);
if Assigned(FProofreaderData) then
FProofreaderData.SaveSettings(Settings);
end;
procedure TCodeProofreaderExpert.SetActive(New: Boolean);
begin
inherited SetActive(New);
if Active then
begin
if not Assigned(FProofreaderData) then
FProofreaderData := TProofreaderData.Create(ConfigurationKey);
FProofreaderData.ReloadData;
end
else
FreeAndNil(FProofreaderData);
end;
initialization
RegisterGX_Expert(TCodeProofreaderExpert);
end.
|
unit Settings_Form;
interface
uses
Windows,
Messages,
SysUtils,
Classes,
Graphics,
Controls,
Forms,
Dialogs,
ExtCtrls,
vtPanel,
l3Types,
l3InternalInterfaces,
OvcBase,
vcmInterfaces,
vcmBase,
vcmEntityForm,
vcmEntities,
vcmContainerForm,
vcmBaseEntities,
vcmComponent,
nsConfigurationList,
ConfigInterfaces,
l3InterfacedComponent,
vcmExternalInterfaces,
PrimSettings_Form
;
type
Tcf_Settings = class(TvcmContainerFormRef, Il3CommandTarget)
Entities : TvcmEntities;
procedure vcmContainerFormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure vcmContainerFormShow(Sender: TObject);
procedure vcmContainerFormClose(Sender: TObject;
var Action: TCloseAction);
private
// private fields
f_Filled : Boolean;
protected
// protected methods
procedure Cleanup;
override;
{-}
end;
implementation
uses
l3String,
afwFacade,
vcmBaseMenuManager,
vcmForm,
StdRes,
nsSettings,
nsAppConfig,
nsUtils,
OvcCmd,
OvcConst,
bsInterfaces
;
{$R *.DFM}
procedure Tcf_Settings.Cleanup;
begin
f_Filled := false;
inherited;
end;
procedure Tcf_Settings.vcmContainerFormKeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
Var
l_Controller : TOvcController;
l_Msg: TWMKeyDown;
l_Target: Il3CommandTarget;
begin
l_Controller := GetDefController;
if l_Controller <> nil then
with l_Controller.EntryCommands do
begin
l_Msg.CharCode := Key;
l_Msg.KeyData := 0;
if Supports(Self, Il3CommandTarget, l_Target) and
(l_Controller.EntryCommands.TranslateUsing([OvcCmd.scDefaultTableName],
TMessage(l_Msg), GetTickCount,
l_Target) = ccShortCut) then
Key := 0;
end;
end;
procedure Tcf_Settings.vcmContainerFormShow(Sender: TObject);
var
l_Swap: TCursor;
begin
// Делаем это здесь, т.к. необходимо чтобы toolbar-ы были созданы и мы могли
// бы сообщить DocksHeight
if not f_Filled then
begin
l_Swap := Screen.Cursor;
Screen.Cursor := crHourGlass;
try
f_ManagerConf.FillDialog(self.as_IvcmEntityForm, DocksHeight);
finally
Screen.Cursor := l_Swap;
end;
f_Filled := True;
end;
end;
procedure Tcf_Settings.vcmContainerFormClose(Sender: TObject;
var Action: TCloseAction);
begin
f_ManagerConf.DoneEditing;
f_Filled := False;
end;
end. |
{
Unfortunately, Turbo Pascal does not do a very good job of rounding
numbers when using the built-in REAL data type. For instance:
WRITELN(87.75:8:1);
returns:
87.7 Yikes!
This program contains two routines to round REALs and demonstrates the
problem with the PASCAL str function (which also applies to WRITELN).
The function HalfAdjust will round 5 or more up and 4 or less down.
The function rounded will round 6 or more up and 4 or less down and 5
will round to an even value (the most correct mathematically).
John Lucas [70441,2451]
}
function HalfAdjust(r : real; width, decimals : integer) : string;
{ always round up on "5" }
var
temp : string;
half : real;
begin
case decimals of
0 : half := 0.5;
1 : half := 0.05;
2 : half := 0.005;
3 : half := 0.0005;
4 : half := 0.00005;
5 : half := 0.000005;
6 : half := 0.0000005;
7 : half := 0.00000005;
8 : half := 0.000000005;
9 : half := 0.0000000005;
10 : half := 0.00000000005;
11 : half := 0.000000000005;
else half := 0.0;
end;
if r<0 then
r := r-half
else
r := r+half;
str(r:0:11,temp);
if decimals=0 then
dec(temp[0],12)
else
dec(temp[0],11-decimals);
dec(width,length(temp));
if width>0 then begin
move(temp[1],temp[succ(width)],length(temp));
inc(temp[0],width);
fillchar(temp[1],width,' ')
end;
HalfAdjust := temp
end; {HalfAdjust}
function rounded(r : real; width, decimals : integer) : string;
{ round on "5" to an even value }
var
temp : string;
point : integer;
i : integer;
label 1;
begin
str(r:0:11,temp);
insert('0',temp,1);
point := length(temp)-11;
delete(temp,point,1);
if temp[point+decimals]='5' then
if odd(ord(temp[point+decimals-1])) then
for i := pred(point) downto 1 do
if temp[i]='9' then
temp[i] := '0'
else
begin
inc(temp[i]);
{break}
goto 1
end;
1: insert('.',temp,point);
if temp[1]='0' then
delete(temp,1,1);
if decimals=0 then
dec(temp[0],12)
else
dec(temp[0],11-decimals);
dec(width,length(temp));
if width>0 then begin
move(temp[1],temp[succ(width)],length(temp));
inc(temp[0],width);
fillchar(temp[1],width,' ')
end;
rounded := temp
end; {rounded}
var
q,r : real;
i : integer;
procedure show(r : real);
var
rh,rr,rs : string;
begin
str(r:12:0,rs);
rh := HalfAdjust(r,12,0);
rr := rounded(r,12,0);
write(r,rh,rr,rs);
if rs<>rh then write(' wrong');
writeln;
end;
begin
q := 0.499999999;
r := 0.50;
writeln(' Value HalfAdjust() rounded() str()');
for i := 190 to 199 do begin
show(q+i);
show(r+i);
end;
end.
|
unit GenericParametersUnit;
interface
uses
REST.Json.Types, HttpQueryMemberAttributeUnit, JSONNullableAttributeUnit,
SysUtils, Rtti, System.JSON,
CommonTypesUnit;
type
TGenericParameters = class
private
const
IsNullFieldCaption = 'FIsNull';
ValueFieldCaption = 'FValue';
protected
[JSONMarshalled(False)]
FConvertBooleansToInteger: boolean;
[JSONMarshalled(False)]
FParametersCollection: TListStringPair;
[JSONMarshalled(False)]
FBodyParametersCollection: TListStringPair;
public
constructor Create; virtual;
destructor Destroy; override;
procedure AddParameter(Key, Value: String);
procedure ReplaceParameter(Key, Value: String);
procedure AddBodyParameter(Key, Value: String);
property BodyParameters: TListStringPair read FBodyParametersCollection;
function ToJsonString: String;
function ToJsonValue: TJSONValue;
function Serialize(ApiKey: String = ''): TListStringPair;
end;
implementation
{ TGenericParameters }
uses
Math,
MarshalUnMarshalUnit, UtilsUnit;
procedure TGenericParameters.AddBodyParameter(Key, Value: String);
begin
FBodyParametersCollection.Add(TStringPair.Create(Key, Value));
end;
procedure TGenericParameters.AddParameter(Key, Value: String);
begin
// FParametersCollection.Add(TStringPair.Create(Key, TUtils.EncodeURL(Value)));
FParametersCollection.Add(TStringPair.Create(Key, Value));
end;
constructor TGenericParameters.Create;
begin
Inherited;
FConvertBooleansToInteger := True;
FParametersCollection := TListStringPair.Create;
FBodyParametersCollection := TListStringPair.Create;
end;
destructor TGenericParameters.Destroy;
begin
FreeAndNil(FParametersCollection);
FreeAndNil(FBodyParametersCollection);
inherited;
end;
procedure TGenericParameters.ReplaceParameter(Key, Value: String);
var
i: integer;
begin
for i := 0 to FParametersCollection.Count - 1 do
if (FParametersCollection[i].Key = Key) then
begin
FParametersCollection.Remove(FParametersCollection[i]);
Break;
end;
AddParameter(Key, Value);
end;
function TGenericParameters.Serialize(ApiKey: String): TListStringPair;
function GetHttpAttribute(Field: TRttiField): HttpQueryMemberAttribute;
var
Attr: TCustomAttribute;
begin
Result := nil;
for Attr in Field.GetAttributes do
if Attr is HttpQueryMemberAttribute then
Exit(HttpQueryMemberAttribute(Attr));
end;
function IsNullableField(Field: TRttiField; out IsRequired: boolean): boolean;
var
Attr: TCustomAttribute;
begin
IsRequired := False;
Result := False;
for Attr in Field.GetAttributes do
if Attr is NullableAttribute then
begin
IsRequired := NullableAttribute(Attr).IsRequired;
Exit(True);
end;
end;
function GetNullableFieldValue(Field: TRttiField): TValue;
var
RttiRecord: TRttiRecordType;
ValueField, IsNullField: TRttiField;
IsNull: boolean;
Ptr: Pointer;
begin
if (not Field.FieldType.IsRecord) then
raise Exception.Create('The field marked attribute "Nullable" must be a record.');
RttiRecord := Field.FieldType.AsRecord;
Ptr := Field.GetValue(Self).GetReferenceToRawData;
IsNullField := RttiRecord.GetField(IsNullFieldCaption);
if (IsNullField <> nil) and (IsNullField.FieldType.TypeKind = tkEnumeration) then
IsNull := IsNullField.GetValue(Ptr).AsBoolean
else
raise Exception.Create(Format(
'The field marked attribute "JSONNullableAttribute" must have a field "%s: boolean"', [IsNullFieldCaption]));
if (IsNull) then
Exit(TValue.From(nil));
ValueField := RttiRecord.GetField(ValueFieldCaption);
if (ValueField = nil) then
raise Exception.Create(Format(
'Unsupported type (%d) of the field marked attribute "JSONNullableAttribute"', [Integer(IsNullField.FieldType.TypeKind)]))
else
Result := ValueField.GetValue(Ptr);
end;
var
ctx: TRttiContext;
RttiType: TRttiType;
Field: TRttiField;
Value: TValue;
Attr: HttpQueryMemberAttribute;
FieldName, FieldValue: String;
Param: TStringPair;
IsRequired: boolean;
begin
Result := TListStringPair.Create;
if (ApiKey <> EmptyStr) then
Result.Add(TStringPair.Create('api_key', ApiKey));
for Param in FParametersCollection do
Result.Add(Param);
ctx := TRttiContext.Create;
try
rttiType := ctx.GetType(Self.ClassType);
for Field in rttiType.GetFields do
begin
Attr := GetHttpAttribute(Field);
if (Attr = nil) then
Continue;
if (IsNullableField(Field, IsRequired)) then
Value := GetNullableFieldValue(Field)
else
Value := Field.GetValue(Self);
FieldName := Attr.Name;
if (Value.IsEmpty) then
begin
if Attr.IsRequired then
FieldValue := Attr.DefaultValue
else
Continue;
end
else
begin
if (Value.Kind = tkFloat) then
FieldValue := FloatToStr(Value.AsExtended, DottedFormat)
else
FieldValue := Value.ToString;
if (Value.Kind = tkEnumeration) and (FConvertBooleansToInteger) then
if Value.AsBoolean then
FieldValue := '1'
else
FieldValue := '0';
end;
Result.Add(TStringPair.Create(FieldName, FieldValue));
end;
finally
ctx.Free;
end;
end;
function TGenericParameters.ToJsonString: String;
begin
Result := TMarshalUnMarshal.ToJson(Self);
end;
function TGenericParameters.ToJsonValue: TJSONValue;
begin
Result := TMarshalUnMarshal.ToJsonValue(Self);
end;
end.
|
{ CSI 1101-X, Winter, 1999 }
{ Assignment 2 }
{ Identification: Mark Sattolo, student# 428500 }
{ tutorial group DGD-4, t.a. = Manon Sanscartier }
program a2 (input,output) ;
label 190;
type
element_type = real ;
pointer = ^node ; { CHANGED FROM ASSIGNMENT #1 }
node = record
value: element_type ;
next: pointer
end ;
list = pointer ; { CHANGED FROM ASSIGNMENT #1 }
{ variable for the main program - NOT to be referenced anywhere else }
var YESorNO: char ;
{ The following global variable is used for memory management.
You might find it useful while debugging your code, but the
solutions you hand in must not refer to this variable in any way. }
memory_count: integer ;
{****** MEMORY MANAGEMENT PROCEDURES *********}
procedure get_node( var P: pointer ); { Returns a pointer to a new node. }
begin
memory_count := memory_count + 1 ;
new( P )
end ;
{ return_node - Make the node pointed at by P "free" (available to get_node). }
procedure return_node(var P: pointer) ; { parameter L not needed }
begin
memory_count := memory_count - 1 ;
P^.value := -9999.99 ; { "scrub" memory to aid debugging }
dispose( P )
end ;
{************************************************************}
procedure create_empty ( var L: list ) ; { Sets list L to be empty. }
begin
L := nil
end ;
procedure write_list ( var L:list );
var
p: pointer ;
size: integer ;
begin
if L = nil then
writeln('Empty list.')
else
begin
size := 0 ;
p := L ;
while p <> nil do
begin
write( ' ', p^.value:7:2 ) ;
p := p^.next ;
size := size + 1 ;
end ; { while }
writeln;
writeln('Size of List is: ', size, '.') ;
end ; { else }
end ; { procedure }
procedure delete_first (var L:list) ;
var
p: pointer ;
begin
if L = nil then
begin
writeln('Error: List is empty') ;
goto 190 ; { halt }
end { if }
else
begin
p := L ;
L := p^.next ;
return_node(p) ;
end { else }
end; { procedure }
procedure pointer_to_Nth(var L:list; N: integer; var P:pointer);
var
counter, size: integer;
begin
size := 0 ;
p := L ;
while p <> nil do
begin
p := p^.next ;
size := size + 1 ;
end ; { while }
if (N < 1) or (N > size) then
begin
writeln('Error: Position "', N, '" is outside the range [0 - ', size, '] of the list.') ;
while L <> nil do delete_first( L ) ;
goto 190 ; { halt }
end { if }
else
begin
p := L ;
for counter := 1 to N-1 do
p := p^.next ;
end; { else }
end; { procedure }
procedure insert_at_front(var L:list; V: element_type) ;
var
p: pointer;
begin
get_node(p) ;
p^.value := V ;
p^.next := L ;
L := p ;
end; { procedure }
procedure insert_after_P( V: element_type; P: pointer) ;
var
q : pointer ;
begin
get_node(q) ;
q^.value := V ;
q^.next := p^.next ;
p^.next := q ;
end; { procedure }
procedure assignment2 ;
var L: list ;
P: pointer ;
position: integer ;
val: element_type ;
done: boolean ;
begin
create_empty( L );
repeat
writeln('Enter a position (0 to current list length)',
' and a number (empty line to quit): ' ) ;
done := eoln ;
if not done
then begin
readln(position,val) ;
if position = 0
then insert_at_front(L,val)
else begin
pointer_to_Nth(L,position,P);
insert_after_P(val,P)
end ;
writeln;
writeln('Here is the list after this insertion: ');
write_list( L );
writeln
end
else readln { clear the empty line }
until done ;
{ to finish off, return all the nodes in L back to the global pool }
while L <> nil do delete_first( L )
end; { procedure }
{**** YOU MUST CHANGE THIS PROCEDURE TO DESCRIBE YOURSELF ****}
procedure identify_myself ; { Writes who you are to the screen }
begin
writeln ;
writeln('CSI 1101-X (winter, 1999). Assignment 2.') ;
writeln('Mark Sattolo, student# 428500.') ;
writeln('tutorial section DGD-4, t.a. = Manon Sanscartier');
writeln
end ; { procedure }
begin { main program }
memory_count := 0 ;
identify_myself ;
repeat
assignment2 ;
190: writeln('Amount of dynamic memory allocated but not returned (should be 0) ', memory_count:0) ;
writeln('Do you wish to continue (y or n) ?') ;
readln(YESorNO);
until (YESorNO <> 'y')
end.
|
unit DAO.CCEPDistribuidor;
interface
uses
FireDAC.Comp.Client, System.SysUtils, DAO.Conexao, Model.CCEPDistribuidor;
type
TCCEPDistribuidorDAO = class
private
FConexao : TConexao;
public
constructor Create;
function Inserir(ACCEP: TCCEPDistribuidor): Boolean;
function Alterar(ACCEP: TCCEPDistribuidor): Boolean;
function Excluir(ACCEP: TCCEPDistribuidor): Boolean;
function Pesquisar(aParam: array of variant): TFDQuery;
end;
const
TABLENAME = 'tbcepagente';
implementation
{ TCCEPDistribuidorDAO }
uses Control.Sistema;
function TCCEPDistribuidorDAO.Alterar(ACCEP: TCCEPDistribuidor): Boolean;
var
FDQuery : TFDQuery;
begin
try
Result := False;
FDQuery := FConexao.ReturnQuery();
FDQuery.ExecSQL('update ' + TABLENAME + ' set cod_cabeca_cep = :cod_cabeca_cep, ' +
'cod_grupo = :cod_grupo, id_faixa = :id_faixa, des_log = :des_log ' +
'where cod_Agente = :cod_Agente',
[ACCEP.CCEP, ACCEP.Grupo, ACCEP.Faixa, ACCEP.LOG, ACCEP.CodigoDistribuidor]);
Result := True;
finally
FDquery.Close;
FDquery.Connection.Close;
FDQuery.Free;
end;
end;
constructor TCCEPDistribuidorDAO.Create;
begin
FConexao := TSistemaControl.GetInstance.Conexao;
end;
function TCCEPDistribuidorDAO.Excluir(ACCEP: TCCEPDistribuidor): Boolean;
var
FDQuery : TFDQuery;
begin
try
Result := False;
FDQuery := FConexao.ReturnQuery();
FDQuery.ExecSQL('delete from ' + TABLENAME + ' where cod_Agente = :cod_agente', [ACCEP.CodigoDistribuidor]);
Result := True;
finally
FDquery.Close;
FDquery.Connection.Close;
FDQuery.Free;
end;
end;
function TCCEPDistribuidorDAO.Inserir(ACCEP: TCCEPDistribuidor): Boolean;
var
FDQuery : TFDQuery;
begin
try
Result := False;
FDQuery := FConexao.ReturnQuery();
FDQuery.ExecSQL('insert into ' + TABLENAME + ' (cod_agente, cod_cabeca_cep cod_grupo, id_faixa, des_log) ' +
'values (:cod_agente, :cod_cabeca_cep, :cod_grupo, :id_faixa, :des_log)',
[ACCEP.CodigoDistribuidor, ACCEP.CCEP, ACCEP.Grupo, ACCEP.Faixa, ACCEP.LOG]);
Result := True;
finally
FDquery.Close;
FDquery.Connection.Close;
FDQuery.Free;
end;
end;
function TCCEPDistribuidorDAO.Pesquisar(aParam: array of variant): TFDQuery;
var
FDQuery: TFDQuery;
begin
FDQuery := FConexao.ReturnQuery();
if Length(aParam) < 2 then Exit;
FDQuery.SQL.Clear;
FDQuery.SQL.Add('select cod_agente, cod_cabeca_cep cod_grupo, id_faixa, des_log from ' + TABLENAME);
if aParam[0] = 'AGENTE' then
begin
FDQuery.SQL.Add('where cod_agente = :cod_agente');
FDQuery.ParamByName('cod_agente').AsInteger := aParam[1];
end;
if aParam[0] = 'CCEP' then
begin
FDQuery.SQL.Add('where cod_cabeca_cep = :cod_cabeca_cep');
FDQuery.ParamByName('cod_cabeca_cep').AsInteger := aParam[1];
end;
if aParam[0] = 'FILTRO' then
begin
FDQuery.SQL.Add('where ' + aParam[1]);
end;
if aParam[0] = 'APOIO' then
begin
FDQuery.SQL.Clear;
FDQuery.SQL.Add('select ' + aParam[1] + ' from ' + TABLENAME + ' ' + aParam[2]);
end;
FDQuery.Open;
Result := FDQuery;
end;
end.
|
{ ***************************************************************************
Copyright (c) 2015-2019 Kike Pérez
Unit : Quick.Config.Base
Description : Quick Config Base classes
Author : Kike Pérez
Version : 1.5
Created : 26/01/2017
Modified : 12/02/2019
This file is part of QuickLib: https://github.com/exilon/QuickLib
***************************************************************************
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*************************************************************************** }
unit Quick.Config.Base;
interface
{$i QuickLib.inc}
uses
Classes,
SysUtils,
Quick.Json.Serializer;
type
TAppConfig = class;
IAppConfigProvider = interface
['{D55B1EBF-47F6-478B-8F70-9444575CB825}']
procedure Load(cConfig : TAppConfig);
procedure Save(cConfig : TAppConfig);
end;
TSerializeProperty = (spPublic, spPublished);
TAppConfigProvider = class(TInterfacedObject,IAppConfigProvider)
private
fCreateIfNotExists : Boolean;
fSerializeLevel : TSerializeProperty;
fUseEnumNames : Boolean;
protected
procedure Load(cConfig : TAppConfig); virtual; abstract;
procedure Save(cConfig : TAppConfig); virtual; abstract;
public
constructor Create;
property CreateIfNotExists : Boolean read fCreateIfNotExists write fCreateIfNotExists;
property SerializeLevel : TSerializeProperty read fSerializeLevel write fSerializeLevel;
property UseEnumNames : Boolean read fUseEnumNames write fUseEnumNames;
end;
TApplyConfigEvent = procedure of object;
TAppConfig = class
private
fOnApplyConfig : TApplyConfigEvent;
fJsonIndent: Boolean;
fLastSaved : TDateTime;
protected
fProvider : TAppConfigProvider;
public
constructor Create(aConfigProvider : TAppConfigProvider);
destructor Destroy; override;
{$IFNDEF FPC}[TNotSerializableProperty]{$ENDIF}
property OnApplyConfig : TApplyConfigEvent read fOnApplyConfig write fOnApplyConfig;
{$IFNDEF FPC}[TNotSerializableProperty]{$ENDIF}
property JsonIndent : Boolean read fJsonIndent write fJsonIndent;
{$IFNDEF FPC}[TNotSerializableProperty]{$ENDIF}
property LastSaved : TDateTime read fLastSaved write fLastSaved;
procedure Apply;
//override this method to provide your class initialization
procedure Init; virtual;
procedure DefaultValues; virtual;
procedure Load; virtual;
procedure Save; virtual;
function ToJSON : string;
procedure FromJSON(const json : string);
end;
EAppConfig = class(Exception);
implementation
{ TAppConfigProviderBase }
constructor TAppConfigProvider.Create;
begin
fCreateIfNotExists := True;
fSerializeLevel := spPublished;
fUseEnumNames := True;
end;
{ TAppConfig }
constructor TAppConfig.Create(aConfigProvider : TAppConfigProvider);
begin
fProvider := aConfigProvider;
fJsonIndent := True;
fLastSaved := 0;
Init;
end;
procedure TAppConfig.Apply;
begin
if Assigned(fOnApplyConfig) then fOnApplyConfig;
end;
procedure TAppConfig.DefaultValues;
begin
//inherit to set default values if no config exists before
end;
destructor TAppConfig.Destroy;
begin
if Assigned(fProvider) then fProvider.Free;
inherited;
end;
function TAppConfig.ToJSON : string;
var
Serializer : TJsonSerializer;
begin
Result := '';
try
serializer := TJsonSerializer.Create(slPublishedProperty,fProvider.UseEnumNames);
try
Result := serializer.ObjectToJSON(Self,fJsonIndent);
finally
serializer.Free;
end;
except
on e : Exception do raise Exception.Create(e.Message);
end;
end;
procedure TAppConfig.FromJSON(const json : string);
var
Serializer : TJsonSerializer;
begin
try
serializer := TJsonSerializer.Create(slPublishedProperty,fProvider.UseEnumNames);
try
serializer.JsonToObject(Self,json);
finally
serializer.Free;
end;
except
on e : Exception do raise Exception.Create(e.Message);
end;
end;
procedure TAppConfig.Init;
begin
//override to create private classes
end;
procedure TAppConfig.Load;
begin
if not Assigned(fProvider) then raise EAppConfig.Create('No provider assigned!');
fProvider.Load(Self);
end;
procedure TAppConfig.Save;
begin
if not Assigned(fProvider) then raise EAppConfig.Create('No provider assigned!');
fProvider.Save(Self);
fLastSaved := Now();
end;
end.
|
{
Author: William Yang
Website: http://www.pockhero.com
}
unit Graphix.Web2Button;
interface
uses
System.SysUtils, System.Classes, System.Types, System.UITypes, System.UIConsts,
FMX.Types, FMX.Controls, FMX.StdCtrls, FMX.Objects,
Graphix.Helpers, FMX.Layouts;
type
TWeb2BaseButton = class(TSpeedButton)
private
FText: TText;
FImage: TImage;
FUpdateButtonCount: Integer;
FButton, FButtonOver, FButtonDown: TBitmap;
FTextMargin: TBounds;
FButtonActiveBitmap: TBitmap;
FHoverActive: Boolean;
FTextLift: Boolean;
procedure SetButtonBitmap(const Value: TBitmap);
procedure SetButtonDownBitmap(const Value: TBitmap);
procedure SetButtonOverBitmap(const Value: TBitmap);
procedure SetTextMargin(const Value: TBounds);
procedure TextMarginChange(ASender: TObject);
procedure SetButtonActiveBitmap(const Value: TBitmap);
procedure SetHoverActive(const Value: Boolean);
procedure SetTextLift(const Value: Boolean);
protected
FDefault: Boolean;
FCancel: Boolean;
procedure TrySetImage(const AImages: array of TBitmap);
procedure SetIsPressed(const Value: Boolean); override;
procedure DialogKey(var Key: Word; Shift: TShiftState); override;
procedure Resize; override;
procedure Loaded; override;
procedure ApplyStyle; override;
function GetStyleObject: TFmxObject; override;
function FindTextObject: TFmxObject; override;
procedure RecreateButton; virtual;
procedure UpdateImage; virtual;
procedure BeginUpdateButton; virtual;
procedure EndUpdateButton; virtual;
procedure DoMouseEnter;override;
procedure DoMouseLeave;override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Single); override;
property ButtonBitmap: TBitmap read fButton write SetButtonBitmap;
property ButtonOverBitmap: TBitmap read FButtonOver write SetButtonOverBitmap;
property ButtonDownBitmap: TBitmap read FButtonDown write SetButtonDownBitmap;
property ButtonActiveBitmap: TBitmap read FButtonActiveBitmap write SetButtonActiveBitmap;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure LoadBitmaps(AFilename: String); overload;
procedure LoadBitmaps(AFilename, AFilenameOver, AFilenameDown, AFilenameActive: String); overload;
procedure LoadBitmaps(ABitmap: TBitmap;
const ABitmapOver: TBitmap = nil;
const ABitmapDown: TBitmap = nil;
const ABitmapActive: TBitmap = nil); overload;
published
property HoverActive: Boolean read FHoverActive write SetHoverActive;
property TextMargin: TBounds read FTextMargin write SetTextMargin;
property TextLift: Boolean read FTextLift write SetTextLift;
property StaysPressed default False;
property Action;
property Align default TAlignLayout.alNone;
property Anchors;
property AutoTranslate default True;
property Cancel: Boolean read FCancel write FCancel default False;
property CanFocus default True;
property CanParentFocus;
property ClipChildren default False;
property ClipParent default False;
property Cursor default crDefault;
property Default: Boolean read FDefault write FDefault default False;
property DesignVisible default True;
property DisableFocusEffect;
property DragMode default TDragMode.dmManual;
property EnableDragHighlight default True;
property Enabled default True;
property Font;
property StyledSettings;
property Height;
property HelpContext;
property HelpKeyword;
property HelpType;
property HitTest default True;
property IsPressed default False;
property Locked default False;
property Padding;
property ModalResult default mrNone;
property Opacity;
property Margins;
property PopupMenu;
property Position;
property RepeatClick default False;
property RotationAngle;
property RotationCenter;
property Scale;
property StyleLookup;
property TabOrder;
property Text;
property Trimming;
property TextAlign default TTextAlign.taCenter;
property TouchTargetExpansion;
property Visible default True;
property Width;
property WordWrap default False;
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;
TWeb2ImageButton = class(TWeb2BaseButton)
private
FAutosize: Boolean;
procedure SetAutosize(const Value: Boolean);
published
property Autosize: Boolean read FAutosize write SetAutosize;
property ButtonBitmap;
property ButtonOverBitmap;
property ButtonDownBitmap;
property ButtonActiveBitmap;
end;
TWeb2Button = class(TWeb2BaseButton)
private
{ Private declarations }
FUpdateButtonCount: Integer;
FCancel: Boolean;
FImage: TImage;
FButtonBackground: TBitmap;
FButtonLightOverlay: TBitmap;
FColor: TAlphaColor;
FXRadius: Single;
FYRadius: Single;
FButtonMask: TBitmap;
FCorners: TCorners;
FSides: TSides;
procedure SetColor(const Value: TAlphaColor);
procedure SetXRadius(const Value: Single);
procedure SetYRadius(const Value: Single);
procedure SetCorners(const Value: TCorners);
procedure SetSides(const Value: TSides);
protected
{ Protected declarations }
procedure RecreateButton; override;
procedure CreateButton; virtual;
procedure CreateButtonMask; virtual;
procedure CreateDownEffect; virtual;
procedure CreateOverEffect; virtual;
procedure RecreateButtonBackground; virtual;
procedure RecreateLightOverlay; virtual;
procedure UpdateImage; override;
property Sides: TSides read FSides write SetSides;
property Corners: TCorners read FCorners write SetCorners;
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property Color: TAlphaColor read FColor write SetColor;
property XRadius: Single read FXRadius write SetXRadius;
property YRadius: Single read FYRadius write SetYRadius;
end;
TWeb2TabButton = class(TWeb2Button)
private
FTabPosition: TSide;
procedure SetTabPosition(const Value: TSide);
protected
procedure RecreateButton; override;
procedure CreateButton; override;
procedure CreateButtonMask; override;
procedure CreateDownEffect; override;
procedure CreateOverEffect; override;
procedure RecreateButtonBackground; override;
procedure RecreateLightOverlay; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property TabPosition: TSide read FTabPosition write SetTabPosition;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('Graphix', [TWeb2ImageButton, TWeb2Button, TWeb2TabButton]);
end;
function BrightColor(Start, Stop: TAlphaColor): TAlphaColor;
begin
if TAlphaColorRec(Start).A + TAlphaColorRec(Stop).A < $FF then
TAlphaColorRec(Result).A := TAlphaColorRec(Start).A + TAlphaColorRec(Stop).A
else
TAlphaColorRec(Result).A := $FF;
if TAlphaColorRec(Start).R + TAlphaColorRec(Stop).R < $FF then
TAlphaColorRec(Result).R := TAlphaColorRec(Start).R + TAlphaColorRec(Stop).R
else
TAlphaColorRec(Result).R := $FF;
if TAlphaColorRec(Start).G + TAlphaColorRec(Stop).G < $FF then
TAlphaColorRec(Result).G := TAlphaColorRec(Start).G + TAlphaColorRec(Stop).G
else
TAlphaColorRec(Result).G := $FF;
if TAlphaColorRec(Start).B + TAlphaColorRec(Stop).B < $FF then
TAlphaColorRec(Result).B := TAlphaColorRec(Start).B + TAlphaColorRec(Stop).B
else
TAlphaColorRec(Result).B := $FF;
end;
{ TWeb2Button }
constructor TWeb2Button.Create(AOwner: TComponent);
begin
inherited;
FButtonBackground := TBitmap.Create;
FButtonLightOverlay := TBitmap.Create;
FButtonMask := TBitmap.Create;
FXRadius := 12;
FYRadius := 12;
FColor := $FF7fe0f8;
FCorners := AllCorners;
FSides := AllSides;
end;
destructor TWeb2Button.Destroy;
begin
FButtonMask.Free;
FButtonBackground.Free;
FButtonLightOverlay.Free;
inherited;
end;
procedure TWeb2Button.CreateButtonMask;
var
r: TRectF;
begin
R := RectF(0, 0, Width, Height);
FButtonMask.SetSize(Trunc(Width), Trunc(Height));
// FButtonMask.PixelFormat :=
FButtonMask.Canvas.BeginScene();
try
with FButtonMask.Canvas do
begin
Clear($FF000000);
Fill.Kind := TBrushKind.bkSolid;
Fill.Color := $FFFF0000;
FillRect(r, FXRadius, YRadius, FCorners, 1);
end;
finally
FButtonMask.Canvas.EndScene();
end;
end;
procedure TWeb2Button.RecreateLightOverlay;
var
r: TRectF;
begin
FButtonLightOverlay.SetSize(Trunc(Width), Trunc(Height));
with FButtonLightOverlay.Canvas do
begin
BeginScene();
try
ClearRect(RectF(0, 0, Width, Height), $00000000);
r.Top := -Height*0.5;
r.Left := -Width*1.1*0.5;
r.Right := Width*1.1;
r.Bottom := Height*0.6;
Fill.Kind := TBrushKind.bkSolid;
Fill.Color := $50FFFFFF;
Stroke.Kind := TBrushKind.bkNone;
FillEllipse(r, 1);
finally
EndScene();
end;
end;
// FButtonLightOverlay.ApplyMask(FButtonMask);
end;
procedure TWeb2Button.RecreateButtonBackground;
var
r: TRectF;
begin
FButtonBackground.SetSize(Trunc(Width), Trunc(Height));
// FButtonBackground.Clear(0);
with FButtonBackground.Canvas do
begin
BeginScene();
try
R := RectF(0, 0, Width, Height);
Fill.Kind := TBrushKind.bkGradient;
Fill.Gradient.Color := fColor.Brighten(20);
Fill.Gradient.Color1 := fColor;
FillRect(r, FXRadius, YRadius, FCorners, 1);
if fDefault then
begin
Stroke.Kind := TBrushKind.bkSolid;
Stroke.Color := $C0FFFFFF;
Stroke.Thickness := 2;
DrawRectSides(r, FXRadius, YRadius, FCorners, 1, FSides);
end else
begin
Stroke.Kind := TBrushKind.bkSolid;
Stroke.Color := $C0000000;
Stroke.Thickness := 1;
DrawRectSides(r, FXRadius, YRadius, FCorners, 1, FSides);
//
// Stroke.Color := $E0FFFFFF;
// r.Inflate(-1, -1);
// DrawRectSides(r, FXRadius, YRadius, FCorners, 1, FSides);
end;
finally
EndScene();
end;
end;
// FButtonBackground.SaveToFile('button-back.png');
end;
procedure TWeb2Button.CreateButton;
var
r: TRectF;
tmp: TBitmap;
begin
FButton.SetSize(Trunc(Width), Trunc(Height));
with FButton.Canvas do
begin
BeginScene();
try
R := RectF(0, 0, Width, Height);
Clear($00000000);
DrawBitmap(FButtonBackground, R, R, 1);
DrawBitmap(FButtonLightOverlay, R, R, 1);
finally
EndScene();
end;
end;
// FButtonMask.SaveToFile('button-mask.png');
FButton.ApplyMask(FButtonMask);
end;
procedure TWeb2Button.CreateOverEffect;
var
r: TRectF;
begin
FButtonOver.SetSize(Trunc(Width), Trunc(Height));
with FButtonOver.Canvas do
begin
BeginScene();
try
R := RectF(0, 0, Width, Height);
Clear($00000000);
DrawBitmap(FButtonBackground, R, R, 1);
DrawBitmap(FButtonLightOverlay, R, R, 1);
Fill.Kind := TBrushKind.bkSolid;
Fill.Color := $40FFFFFF;
FillRect(r, FXRadius, YRadius, FCorners, 1);
Stroke.Kind := TBrushKind.bkSolid;
Stroke.Color := FColor.Darken(40);
Stroke.Thickness := 1;
DrawRectSides(r, FXRadius, YRadius, FCorners, 1, FSides);
r.Inflate(-1, -1, -1, -1);
Stroke.Color := FColor.Brighten(60);
DrawRectSides(r, FXRadius, YRadius, FCorners, 1, FSides);
// Stroke.Color := FColor.Brighten(20);
// r.Inflate(-1, -1, -1, -1);
// DrawRectSides(r, FXRadius, YRadius, FCorners, 1, FSides);
finally
EndScene();
end;
end;
FButtonOver.ApplyMask(FButtonMask);
end;
procedure TWeb2Button.CreateDownEffect;
var
r: TRectF;
begin
FButtonDown.SetSize(Trunc(Width), Trunc(Height));
with FButtonDown.Canvas do
begin
BeginScene();
try
R := RectF(0, 0, Width, Height);
Clear($00000000);
DrawBitmap(FButtonBackground, R, R, 1);
DrawBitmap(FButtonLightOverlay, R, R, 1);
Fill.Kind := TBrushKind.bkSolid;
Fill.Color := $20000000;
FillRect(r, FXRadius, YRadius, FCorners, 1);
Stroke.Kind := TBrushKind.bkSolid;
Stroke.Color := FColor.Darken(40);
Stroke.Thickness := 1;
DrawRectSides(r, FXRadius, YRadius, FCorners, 1, FSides);
Stroke.Color := FColor.Darken(20);
r.Inflate(-1, -1);
DrawRectSides(r, FXRadius, YRadius, FCorners, 1, FSides);
finally
EndScene();
end;
end;
FButtonDown.ApplyMask(FButtonMask);
end;
procedure TWeb2Button.RecreateButton;
begin
if (csLoading in ComponentState) or (FUpdateButtonCount > 0) then
begin
Exit;
end;
CreateButtonMask;
RecreateLightOverlay;
RecreateButtonBackground;
CreateButton;
CreateOverEffect;
CreateDownEffect;
UpdateImage;
end;
procedure TWeb2Button.SetColor(const Value: TAlphaColor);
begin
FColor := Value;
RecreateButton;
end;
procedure TWeb2Button.SetCorners(const Value: TCorners);
begin
FCorners := Value;
RecreateButton;
end;
procedure TWeb2Button.SetSides(const Value: TSides);
begin
FSides := Value;
RecreateButton;
end;
procedure TWeb2Button.SetXRadius(const Value: Single);
begin
FXRadius := Value;
RecreateButton;
end;
procedure TWeb2Button.SetYRadius(const Value: Single);
begin
FYRadius := Value;
RecreateButton;
end;
procedure TWeb2Button.UpdateImage;
begin
inherited;
if FText <> nil then
begin
if FColor.Brightness > 0.5 then
FText.Color := TAlphaColorRec.Black
else
FText.Color := TAlphaColorRec.White;
end;
end;
{ TWeb2TabButton }
constructor TWeb2TabButton.Create(AOwner: TComponent);
begin
inherited;
FCorners := [TCorner.crTopLeft, TCorner.crTopRight];
FSides := [TSide.sdTop, TSide.sdLeft, TSide.sdRight];
end;
procedure TWeb2TabButton.CreateButton;
begin
inherited;
end;
procedure TWeb2TabButton.CreateButtonMask;
begin
inherited;
end;
procedure TWeb2TabButton.CreateDownEffect;
begin
inherited;
end;
procedure TWeb2TabButton.CreateOverEffect;
begin
inherited;
end;
destructor TWeb2TabButton.Destroy;
begin
inherited;
end;
procedure TWeb2TabButton.RecreateButton;
begin
inherited RecreateButton;
end;
procedure TWeb2TabButton.RecreateButtonBackground;
var
r: TRectF;
mask: TBitmap;
begin
inherited;
r := RectF(0, 0, Width, Height);
mask := TBitmap.Create( Trunc(Width), Trunc(Height));
with mask.Canvas do
begin
BeginScene();
try
Fill.Kind := TBrushKind.bkGradient;
Fill.Gradient.Color := $FFFFFFFF;
Fill.Gradient.Color1 := $FFD00000;
r.Bottom := Height*0.9;
FillRect(r, 0, 0, fCorners, 1);
Fill.Kind := TBrushKind.bkGradient;
Fill.Gradient.Color := $FFD00000;
Fill.Gradient.Color1 := $FF000000;
r.Top := r.Bottom;
r.Bottom := Height;
FillRect(r, 0, 0, fCorners, 1);
finally
EndScene();
end;
end;
// mask.SaveToFile('button-back-mask.png');
FButtonBackground.ApplyMask(mask);
mask.Free;
// FButtonBackground.SaveToFile('button-back-masked.png');
end;
procedure TWeb2TabButton.RecreateLightOverlay;
begin
inherited;
end;
procedure TWeb2TabButton.SetTabPosition(const Value: TSide);
begin
FTabPosition := Value;
case FTabPosition of
TSide.sdTop:
begin
FSides := AllSides - [TSide.sdBottom];
FCorners := AllCorners - [TCorner.crBottomLeft, TCorner.crBottomRight];
end;
TSide.sdLeft:
begin
FSides := AllSides - [TSide.sdRight];
FCorners := AllCorners - [TCorner.crTopRight, TCorner.crBottomRight];
end;
TSide.sdRight:
begin
FSides := AllSides - [TSide.sdLeft];
FCorners := AllCorners - [TCorner.crTopLeft, TCorner.crBottomLeft];
end;
TSide.sdBottom:
begin
FSides := AllSides - [TSide.sdTop];
FCorners := AllCorners - [TCorner.crTopLeft, TCorner.crTopRight];
end;
end;
RecreateButton;
end;
{ TWeb2BaseButton }
procedure TWeb2BaseButton.ApplyStyle;
begin
inherited;
FImage := TImage(FindStyleResource('image'));
FText := TText(FindStyleResource('text'));
UpdateImage;
end;
procedure TWeb2BaseButton.BeginUpdateButton;
begin
Inc(FUpdateButtonCount);
end;
procedure TWeb2BaseButton.TextMarginChange(ASender: TObject);
begin
UpdateImage;
end;
constructor TWeb2BaseButton.Create(AOwner: TComponent);
begin
inherited;
Cursor := crHandPoint;
FTextMargin := TBounds.Create(RectF(0, 0, 0, 0));
FTextMargin.OnChange := TextMarginChange;
FUpdateButtonCount := 0;
FButton := TBitmap.Create;
FButtonOver := TBitmap.Create;
FButtonDown := TBitmap.Create;
FButtonActiveBitmap := TBitmap.Create;
FTextLift := False;
end;
destructor TWeb2BaseButton.Destroy;
begin
FButton.Free;
FButtonOver.Free;
FButtonDown.Free;
FButtonActiveBitmap.Free;
FTextMargin.Free;
inherited;
end;
procedure TWeb2BaseButton.DialogKey(var Key: Word; Shift: TShiftState);
begin
inherited;
if Default and (Key = vkReturn) then
begin
Click;
Key := 0;
end;
if Cancel and (Key = vkEscape) then
begin
Click;
Key := 0;
end;
end;
procedure TWeb2BaseButton.DoMouseEnter;
begin
inherited;
if FHoverActive and IsMouseOver then
begin
Click;
IsPressed := True;
end;
UpdateImage;
end;
procedure TWeb2BaseButton.DoMouseLeave;
begin
inherited;
UpdateImage;
end;
procedure TWeb2BaseButton.EndUpdateButton;
begin
Dec(FUpdateButtonCount);
RecreateButton;
end;
function TWeb2BaseButton.FindTextObject: TFmxObject;
begin
if fText = nil then
begin
FText := TText(FindStyleResource('text'));
end;
Result := fText;
end;
function TWeb2BaseButton.GetStyleObject: TFmxObject;
var
image: TImage;
begin
Result := TLayout.Create(nil);
image := TImage.Create(Result);
with image do
begin
Align := TAlignLayout.alClient;
Parent := Result;
HitTest := False;
StyleName := 'image';
end;
with TText.Create(Result) do
begin
StyleName := 'text';
HitTest := False;
Parent := image;
AutoSize := True;
Align := TAlignLayout.alCenter;
end;
end;
procedure TWeb2BaseButton.LoadBitmaps(AFilename: String);
begin
LoadBitmaps(AFilename, ChangeFileExt(AFilename, '-over.png'),
ChangeFileExt(AFilename, '-down.png'),
ChangeFileExt(AFilename, '-active.png'));
end;
procedure TWeb2BaseButton.LoadBitmaps(AFilename, AFilenameOver, AFilenameDown,
AFilenameActive: String);
begin
if FileExists(AFilename) then
FButton.LoadFromFile(AFilename);
if FileExists(AFilenameOver) then
FButtonOver.LoadFromFile(AFilenameOver);
if FileExists(AFilenameDown) then
FButtonDown.LoadFromFile(AFilenameDown);
if FileExists(AFilenameActive) then
FButtonActiveBitmap.LoadFromFile(AFilenameActive);
end;
procedure TWeb2BaseButton.LoadBitmaps(ABitmap: TBitmap; const ABitmapOver,
ABitmapDown, ABitmapActive: TBitmap);
begin
if Assigned(ABitmap) and (not ABitmap.IsEmpty) then
FButton.Assign(ABitmap);
if Assigned(ABitmapOver) and (not ABitmapOver.IsEmpty) then
FButtonOver.Assign(ABitmapOver);
if Assigned(ABitmapDown) and (not ABitmapDown.IsEmpty) then
FButtonDown.Assign(ABitmapDown);
if Assigned(ABitmapActive) and (not ABitmapActive.IsEmpty) then
FButtonActiveBitmap.Assign(ABitmapActive);
end;
procedure TWeb2BaseButton.Loaded;
begin
inherited;
RecreateButton;
end;
procedure TWeb2BaseButton.MouseDown(Button: TMouseButton; Shift: TShiftState; X,
Y: Single);
begin
inherited;
UpdateImage;
end;
procedure TWeb2BaseButton.MouseUp(Button: TMouseButton; Shift: TShiftState; X,
Y: Single);
begin
inherited;
UpdateImage;
end;
procedure TWeb2BaseButton.RecreateButton;
begin
// Do nothing
end;
procedure TWeb2BaseButton.Resize;
begin
inherited;
RecreateButton;
end;
procedure TWeb2BaseButton.SetButtonActiveBitmap(const Value: TBitmap);
begin
FButtonActiveBitmap.Assign(Value);
end;
procedure TWeb2BaseButton.SetButtonBitmap(const Value: TBitmap);
begin
fButton.Assign(Value);
UpdateImage;
end;
procedure TWeb2BaseButton.SetButtonDownBitmap(const Value: TBitmap);
begin
FButtonDown.Assign(Value);
UpdateImage;
end;
procedure TWeb2BaseButton.SetButtonOverBitmap(const Value: TBitmap);
begin
FButtonOver.Assign(Value);
UpdateImage;
end;
procedure TWeb2BaseButton.SetHoverActive(const Value: Boolean);
begin
FHoverActive := Value;
if IsMouseOver then
begin
Click;
IsPressed := True;
end;
end;
procedure TWeb2BaseButton.SetIsPressed(const Value: Boolean);
begin
inherited;
UpdateImage;
end;
procedure TWeb2BaseButton.SetTextLift(const Value: Boolean);
begin
FTextLift := Value;
end;
procedure TWeb2BaseButton.SetTextMargin(const Value: TBounds);
begin
FTextMargin.Assign(Value);
end;
procedure TWeb2BaseButton.TrySetImage(const AImages: array of TBitmap);
var
i: TBitmap;
begin
if FImage <> nil then
begin
for i in AImages do
begin
if (i <> nil) and (not i.IsEmpty) then
begin
fImage.Bitmap.PlatformCopy(i);
Break;
end;
end;
end;
end;
procedure TWeb2BaseButton.UpdateImage;
begin
Self.BeginUpdate;
try
if FImage <> nil then
begin
if (IsPressed and StaysPressed) and (not IsMouseOver) then
begin
TrySetImage([FButtonActiveBitmap, FButtonDown, FButton]);
end else if IsPressed then
begin
TrySetImage([FButtonDown, FButton]);
end else if IsMouseOver then
begin
TrySetImage([FButtonOver, FButton]);
end
else
begin
TrySetImage([FButton]);
end;
end;
if FTextLift and (FText <> nil) then
begin
FText.Margins.Assign(FTextMargin);
if IsPressed then
FText.Margins.Top := FTextMargin.Top
else if IsMouseOver then
FText.Margins.Top := FTextMargin.Top-1
else
FText.Margins.Top := FTextMargin.Top;
end;
finally
Self.EndUpdate;
Self.Repaint;
end;
end;
{ TWeb2ImageButton }
procedure TWeb2ImageButton.SetAutosize(const Value: Boolean);
begin
FAutosize := Value;
if FAutoSize and (not FButton.IsEmpty) then
begin
Width := FButton.Width;
Height := FButton.Height;
end;
end;
end.
|
{ behavior3delphi - a Behavior3 client library (Behavior Trees) for Delphi
by Dennis D. Spreen <dennis@spreendigital.de>
see Behavior3.pas header for full license information }
unit Behavior3.Decorators.Limiter;
interface
uses
System.JSON,
Behavior3, Behavior3.Core.Decorator, Behavior3.Core.BaseNode, Behavior3.Core.Tick;
type
(**
* This decorator limit the number of times its child can be called. After a
* certain number of times, the Limiter decorator returns `FAILURE` without
* executing the child.
*
* @module b3
* @class Limiter
* @extends Decorator
**)
TB3Limiter = class(TB3Decorator)
private
protected
public
MaxLoop: Integer;
constructor Create; override;
(**
* Open method.
* @method open
* @param {Tick} tick A tick instance.
**)
procedure Open(Tick: TB3Tick); override;
(**
* Tick method.
* @method tick
* @param {Tick} tick A tick instance.
* @return {Constant} A state constant.
**)
function Tick(Tick: TB3Tick): TB3Status; override;
procedure Load(JsonNode: TJSONValue); override;
end;
implementation
{ TB3Limiter }
uses
Behavior3.Helper, Behavior3.Core.BehaviorTree;
constructor TB3Limiter.Create;
begin
inherited;
(**
* Node name. Default to `Limiter`.
* @property {String} name
* @readonly
**)
Name := 'Limiter';
(**
* Node title. Default to `Limit X Activations`. Used in Editor.
* @property {String} title
* @readonly
**)
Title := 'Limit <maxLoop> Activations';
(**
* Node parameters.
* @property {String} parameters
* @readonly
**)
MaxLoop := 1;
end;
procedure TB3Limiter.Open(Tick: TB3Tick);
begin
Tick.Blackboard.&Set('i', 0, Tick.Tree.Id, Id);
end;
function TB3Limiter.Tick(Tick: TB3Tick): TB3Status;
var
I: Integer;
Status: TB3Status;
begin
if not Assigned(Child) then
begin
Result := Behavior3.Error;
Exit;
end;
I := Tick.Blackboard.Get('i', Tick.tree.id, Id).AsInteger;
if I < MaxLoop then
begin
Status := Child._Execute(Tick);
if (Status = Behavior3.Success) or (Status = Behavior3.Failure) then
Tick.Blackboard.&Set('i', I + 1, Tick.Tree.Id, Id);
Result := Status;
end
else
Result := Behavior3.Failure;
end;
procedure TB3Limiter.Load(JsonNode: TJSONValue);
begin
inherited;
MaxLoop := LoadProperty(JsonNode, 'maxLoop', MaxLoop);
end;
end.
|
unit ArraySubroutines;
interface
procedure GenerateArray(var A : Array of Integer);
procedure PrintArray(A : Array of Integer);
procedure Swap(var a, b : Integer);
implementation
procedure GenerateArray(var A : Array of Integer);
var
i, size : Integer;
begin
Randomize;
size := Length(A);
for i := Low(A) to High(A) do begin
A[i] := Random(MaxInt) mod (3 * size);
end;
end;
procedure PrintArray(A : Array of Integer);
var
i : Integer;
begin
for i := Low(A) to High(A) do begin
Write(A[i], ' ');
end;
WriteLn;
end;
procedure Swap(var a : Integer; var b: Integer);
var
tmp: Integer;
begin
tmp := A;
A := b;
b := tmp;
end;
end.
|
unit FindUnit.DcuDecompiler;
interface
uses
Classes, FindUnit.Utils, Windows, ShellAPI;
const
DCU32INT_EXECUTABLE = 'dcu32int.exe';
type
TDcuDecompiler = class(TObject)
private
FDir: string;
FFiles: TStringList;
FExecutablePath: string;
FGeneratedFiles: TStringList;
procedure CreateDirs;
function ProcessUnit(FileName: string; OutRedir: boolean): Integer;
procedure ProcessFilesInternal(AFiles: TStringList);
procedure ProcessFilesFromExe(AFiles: TStringList);
procedure FixeGeneratedFiles;
procedure FixeGeneratedFile(AFile: string);
public
constructor Create;
destructor Destroy; override;
procedure ProcessFiles(AFiles: TStringList);
function Dcu32IntExecutableExists: Boolean;
end;
function Dcu32IntExecutableExists: Boolean;
function GetDcu32ExecutablePath: string;
implementation
uses
SysUtils{$IFDEF UNICODE}, AnsiStrings{$ENDIF}, Log4Pascal;
{ TDcuDecompiler }
function GetDcu32ExecutablePath: string;
var
Dcu: TDcuDecompiler;
begin
Dcu := TDcuDecompiler.Create;
Result := Dcu.FExecutablePath;
Dcu.Free;
end;
function Dcu32IntExecutableExists: Boolean;
var
Dcu: TDcuDecompiler;
begin
Dcu := TDcuDecompiler.Create;
Result := Dcu.Dcu32IntExecutableExists;
Dcu.Free;
end;
procedure TDcuDecompiler.CreateDirs;
begin
FDir := FindUnitDcuDir;
FExecutablePath := FindUnitDir + DCU32INT_EXECUTABLE;
CreateDir(FDir);
end;
function TDcuDecompiler.Dcu32IntExecutableExists: Boolean;
begin
Result := FileExists(FExecutablePath);
end;
destructor TDcuDecompiler.Destroy;
begin
FGeneratedFiles.Free;
inherited;
end;
procedure TDcuDecompiler.FixeGeneratedFile(AFile: string);
var
FileS: TStringList;
I: Integer;
Line: string;
DeleteLine: Boolean;
MustSave: Boolean;
begin
if not FileExists(AFile) then
begin
Logger.Error('TDcuDecompiler.FixeGeneratedFile: File not fount after process: %s', [AFile]);
Exit;
end;
MustSave := False;
FileS := TStringList.Create;
FileS.LoadFromFile(AFile);
for I := FileS.Count -1 downto 0 do
begin
Line := Trim(FileS[i]);
if Line = '' then
DeleteLine := False;
if (DeleteLine) or (Pos(';;', Line) > 0) then
begin
MustSave := True;
DeleteLine := True;
FileS.Delete(I);
end;
end;
if MustSave then
FileS.SaveToFile(AFile);
FileS.Free;
end;
procedure TDcuDecompiler.FixeGeneratedFiles;
var
FileS: string;
begin
for FileS in FGeneratedFiles do
FixeGeneratedFile(FileS);
end;
function TDcuDecompiler.ProcessUnit(FileName: string; OutRedir: boolean): Integer;
//var
// UnitFromDcu: TUnit;
begin
// Result := 0;
// try
// FileName := ExpandFileName(FileName);
// UnitFromDcu := nil;
// try
// UnitFromDcu := GetDCUByName(FileName, '', 0, false, dcuplWin32, 0);
// finally
// if UnitFromDcu = nil then
// UnitFromDcu := MainUnit;
// if UnitFromDcu <> nil then
// UnitFromDcu.Show;
// end;
// except
// on E: Exception do
// begin
// Result := 1;
// end;
// end;
// UnitFromDcu.Free;
end;
constructor TDcuDecompiler.Create;
begin
FGeneratedFiles := TStringList.Create;
CreateDirs;
end;
procedure TDcuDecompiler.ProcessFiles(AFiles: TStringList);
begin
// ProcessFilesInternal(AFiles);
ProcessFilesFromExe(AFiles);
FixeGeneratedFiles;
end;
procedure TDcuDecompiler.ProcessFilesFromExe(AFiles: TStringList);
var
I: Integer;
FileNameOut: string;
InputParams: string;
begin
if not Dcu32IntExecutableExists then
Exit;
for I := 0 to AFiles.Count -1 do
begin
if (not FileExists(AFiles[i])) then
Continue;
if Pos('\', AFiles[i]) = 1 then
Continue;
FileNameOut := ExtractFileName(AFiles[i]);
FileNameOut := StringReplace(FileNameOut, '.dcu', '.pas', [rfReplaceAll, rfIgnoreCase]);
FileNameOut := FDir + FileNameOut;
FGeneratedFiles.Add(FileNameOut);
try
InputParams := Format('"%s" "-I" "-X%s"', [AFiles[i], FileNameOut]);
ShellExecute(0, 'open', PChar(FExecutablePath), PChar(InputParams), nil, SW_HIDE);
except
on e: exception do
Logger.Error('TDcuDecompiler.ProcessFile[%s]: %s', [AFiles[i], E.Message]);
end;
end;
end;
procedure TDcuDecompiler.ProcessFilesInternal(AFiles: TStringList);
var
I: Integer;
FileNameOut: string;
DeveSair: Boolean;
begin
{I'not using this method 'cause there are to much leaks on dcu32int that by now
make it unusable on a single exe'}
// DeveSair := True;
// if DeveSair then
// Exit;
//
// for I := 0 to AFiles.Count -1 do
// begin
// FileNameOut := FDir + ExtractFileName(AFiles[i]);
// try
// Writer := InitOut(FileNameOut);
// try
// ProcessUnit(AFiles[i], True);
// finally
// Writer.Free;
// Writer := nil;
// end;
// FreeStringWriterList;
// except
// on e: exception do
// Logger.Error('TDcuDecompiler.ProcessFile[%s]: %s', [AFiles[i], E.Message]);
// end;
// end;
end;
end.
|
{====================================================}
{ }
{ EldoS Visual Components }
{ }
{ Copyright (c) 1998-2003, EldoS Corporation }
{ }
{====================================================}
{$include elpack2.inc}
{$ifdef ELPACK_SINGLECOMP}
{$I ElPack.inc}
{$else}
{$ifdef LINUX}
{$I ../ElPack.inc}
{$else}
{$I ..\ElPack.inc}
{$endif}
{$endif}
unit ElClipMon;
interface
uses
SysUtils,
Classes,
Messages,
Controls,
ElCBFmts,
Windows,
{$ifdef VCL_6_USED}
Types,
{$endif}
ElBaseComp;
type
TElClipboardMonitor = class(TElBaseComponent)
protected
FPrevHandle : HWND;
FDataFormats: TStrings;
FOnChange: TNotifyEvent;
procedure WndProc(var Message : TMessage); override;
procedure DoSetEnabled(AEnabled : boolean);override;
procedure TriggerChangeEvent; virtual;
function GetDataFormats: TStrings;
public
destructor Destroy; override;
function GetDataString(const Format : String): string;
function HasDataFormat(Format : integer): Boolean;
property DataFormats: TStrings read GetDataFormats;
published
property Enabled;
property OnChange: TNotifyEvent read FOnChange write FOnChange;
end;
implementation
procedure TElClipboardMonitor.WndProc(var Message : TMessage);
begin
inherited;
if Message.Msg = WM_CHANGECBCHAIN then
begin
if HWND(Message.wParam) = FPrevHandle then
FPrevHandle := Message.lParam
else
with Message do
Result := SendMessage(FPrevHandle, Msg, wParam, lParam);
end
else
if Message.Msg = WM_DRAWCLIPBOARD then
begin
TriggerChangeEvent;
with Message do
Result := SendMessage(FPrevHandle, Msg, wParam, lParam);
end;
end;
procedure TElClipboardMonitor.DoSetEnabled(AEnabled : boolean);
begin
if not AEnabled then
ChangeClipboardChain(Handle, FPrevHandle);
inherited;
if AEnabled then
FPrevHandle := SetClipboardViewer(Handle);
end;
procedure TElClipboardMonitor.TriggerChangeEvent;
begin
if Assigned(FOnChange) then FOnChange(Self);
end;
function TElClipboardMonitor.GetDataFormats: TStrings;
var AFmt : integer;
begin
if FDataFormats = nil then
FDataFormats := TStringList.Create;
FDataFormats.Clear;
OpenClipboard(0);
try
AFmt := 0;
repeat
AFmt := EnumClipboardFormats(AFmt);
FDataFormats.AddObject( GetFormatName(AFmt), TObject(Pointer(AFmt)) );
until AFmt = 0;
Result := FDataFormats;
finally
CloseClipboard;
end;
end;
destructor TElClipboardMonitor.Destroy;
begin
inherited;
FDataFormats.Free;
end;
function TElClipboardMonitor.GetDataString(const Format : String): string;
var i : integer;
H : THandle;
Buf: PChar;
Len: integer;
begin
if DataFormats.IndexOf(Format) = -1 then
raise Exception.CreateFmt('No format %s present', [Format]);
OpenClipboard(Handle);
try
i := GetFormatIndex(Format);
if i = 0 then
Result := ''
else
begin
H := GetClipboardData(i);
Buf := GlobalLock(H);
Len := GlobalSize(H);
SetLength(Result, Len);
Move(Buf^, Result[1], Len);
GlobalUnlock(H);
end;
finally
CloseClipboard;
end;
end;
function TElClipboardMonitor.HasDataFormat(Format : integer): Boolean;
begin
Result := DataFormats.IndexOfObject(TObject(Pointer(Format))) <> -1;
end;
end.
|
unit FiveIsometricMap;
interface
uses
Classes, IsometricMap, IsometricMapTypes, FocusTypes;
type
TZoomLevel = IsometricMap.TZoomLevel;
const
cDefaultZoomDelta = 10;
type
TFiveIsometricMap =
class(TIsometricMap)
public
constructor Create(Owner : TComponent); override;
private
fZoomDelta : integer;
published
property ZoomDelta : integer read fZoomDelta write fZoomDelta default cDefaultZoomDelta;
public
procedure ZoomIn;
procedure ZoomOut;
procedure ZoomMax;
procedure ZoomMin;
private
procedure ViewRegionUpdated(var msg); message verbViewRegionUpdated;
end;
implementation
// TFiveIsometricMap
constructor TFiveIsometricMap.Create(Owner : TComponent);
begin
inherited;
Width := 202;
Height := 102;
fZoomDelta := cDefaultZoomdelta;
end;
procedure TFiveIsometricMap.ZoomIn;
var
zoom : TZoomLevel;
begin
zoom := ZoomLevel;
if zoom < high(zoom) - fZoomDelta
then ZoomLevel := zoom + fZoomDelta
else ZoomLevel := high(zoom);
end;
procedure TFiveIsometricMap.ZoomOut;
var
zoom : TZoomLevel;
begin
zoom := ZoomLevel;
if zoom > low(zoom) + fZoomDelta
then ZoomLevel := zoom - fZoomDelta
else ZoomLevel := low(zoom);
end;
procedure TFiveIsometricMap.ZoomMax;
begin
ZoomLevel := high(ZoomLevel);
end;
procedure TFiveIsometricMap.ZoomMin;
begin
ZoomLevel := low(ZoomLevel);
end;
procedure TFiveIsometricMap.ViewRegionUpdated(var msg);
begin
InvalidateIsometric(true);
end;
end.
|
{
$Project$
$Workfile$
$Revision$
$DateUTC$
$Id$
This file is part of the Indy (Internet Direct) project, and is offered
under the dual-licensing agreement described on the Indy website.
(http://www.indyproject.org/)
Copyright:
(c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved.
}
{
$Log$
}
{
Rev 1.4 5/12/2003 12:30:58 AM GGrieve
Get compiling again with DotNet Changes
Rev 1.3 10/12/2003 1:49:26 PM BGooijen
Changed comment of last checkin
Rev 1.2 10/12/2003 1:43:24 PM BGooijen
Changed IdCompilerDefines.inc to Core\IdCompilerDefines.inc
Rev 1.0 11/14/2002 02:13:56 PM JPMugaas
}
unit IdBlockCipherIntercept;
{
UnitName: IdBlockCipherIntercept
Author: Andrew P.Rybin [magicode@mail.ru]
Creation: 27.02.2002
Version: 0.9.0b
Purpose: Secure communications
}
interface
{$i IdCompilerDefines.inc}
uses
Classes,
IdGlobal,
IdException,
IdResourceStringsProtocols,
IdIntercept;
const
IdBlockCipherBlockSizeDefault = 16;
IdBlockCipherBlockSizeMax = 256;
// why 256? not any block ciphers that can - or should - be used beyond this
// length. You can extend this if you like. But the longer it is, the
// more network traffic is wasted
//256, as currently the last byte of the block is used to store the block size
type
TIdBlockCipherIntercept = class;
// OnSend and OnRecieve Events will always be called with a blockSize Data
TIdBlockCipherIntercept = class(TIdConnectionIntercept)
protected
FBlockSize: Integer;
FIncoming : TIdBytes;
procedure Decrypt (var VData : TIdBytes); virtual;
procedure Encrypt (var VData : TIdBytes); virtual;
procedure SetBlockSize(const Value: Integer);
procedure InitComponent; override;
public
procedure Receive(var VBuffer: TIdBytes); override; //Decrypt
procedure Send(var VBuffer: TIdBytes); override; //Encrypt
procedure CopySettingsFrom (ASrcBlockCipherIntercept: TIdBlockCipherIntercept); // warning: copies Data too
published
property BlockSize: Integer read FBlockSize write SetBlockSize default IdBlockCipherBlockSizeDefault;
end;
EIdBlockCipherInterceptException = EIdException; {block length}
implementation
uses
IdResourceStrings,
SysUtils;
//const
// bitLongTail = $80; //future: for IdBlockCipherBlockSizeMax>256
procedure TIdBlockCipherIntercept.Encrypt(var VData : TIdBytes);
begin
if Assigned(FOnSend) then begin
FOnSend(Self, VData);
end;//ex: EncryptAES(LTempIn, ExpandedKey, LTempOut);
end;
procedure TIdBlockCipherIntercept.Decrypt(var VData : TIdBytes);
Begin
if Assigned(FOnReceive) then begin
FOnReceive(Self, VData);
end;//ex: DecryptAES(LTempIn, ExpandedKey, LTempOut);
end;
procedure TIdBlockCipherIntercept.Send(var VBuffer: TIdBytes);
var
LSrc, LBlock : TIdBytes;
LSize, LCount, LMaxDataSize: Integer;
LCompleteBlocks, LRemaining: Integer;
begin
LSrc := nil; // keep the compiler happy
LSize := Length(VBuffer);
if LSize > 0 then begin
LSrc := VBuffer;
LMaxDataSize := FBlockSize - 1;
SetLength(VBuffer, ((LSize + LMaxDataSize - 1) div LMaxDataSize) * FBlockSize);
SetLength(LBlock, FBlockSize);
LCompleteBlocks := LSize div LMaxDataSize;
LRemaining := LSize mod LMaxDataSize;
//process all complete blocks
for LCount := 0 to LCompleteBlocks-1 do
begin
CopyTIdBytes(LSrc, LCount * LMaxDataSize, LBlock, 0, LMaxDataSize);
LBlock[LMaxDataSize] := LMaxDataSize;
Encrypt(LBlock);
CopyTIdBytes(LBlock, 0, VBuffer, LCount * FBlockSize, FBlockSize);
end;
//process the possible remaining bytes, ie less than a full block
if LRemaining > 0 then
begin
CopyTIdBytes(LSrc, LSize - LRemaining, LBlock, 0, LRemaining);
LBlock[LMaxDataSize] := LRemaining;
Encrypt(LBlock);
CopyTIdBytes(LBlock, 0, VBuffer, Length(VBuffer) - FBlockSize, FBlockSize);
end;
end;
// let the next Intercept in the chain encode its data next
// RLebeau: DO NOT call inherited! It will trigger the OnSend event
// again with the entire altered buffer as input, which can cause user
// code to re-encrypt the already-encrypted data. We do not want that
// here! Just call the next Intercept directly...
//inherited Send(VBuffer);
if Intercept <> nil then begin
Intercept.Send(VBuffer);
end;
end;
procedure TIdBlockCipherIntercept.Receive(var VBuffer: TIdBytes);
var
LBlock : TIdBytes;
LSize, LCount, LPos, LMaxDataSize, LCompleteBlocks: Integer;
LRemaining: Integer;
begin
// let the next Intercept in the chain decode its data first
// RLebeau: DO NOT call inherited! It will trigger the OnReceive event
// with the entire decoded buffer as input, which can cause user
// code to decrypt data prematurely/incorrectly. We do not want that
// here! Just call the next Intercept directly...
//inherited Receive(VBuffer);
if Intercept <> nil then begin
Intercept.Receive(VBuffer);
end;
LPos := 0;
AppendBytes(FIncoming, VBuffer);
LSize := Length(FIncoming);
if LSize >= FBlockSize then
begin
// the length of ABuffer when we have finished is currently unknown, but must be less than
// the length of FIncoming. We will reserve this much, then reallocate at the end
SetLength(VBuffer, LSize);
SetLength(LBlock, FBlockSize);
LMaxDataSize := FBlockSize - 1;
LCompleteBlocks := LSize div FBlockSize;
LRemaining := LSize mod FBlockSize;
for LCount := 0 to LCompleteBlocks-1 do
begin
CopyTIdBytes(FIncoming, LCount * FBlockSize, LBlock, 0, FBlockSize);
Decrypt(LBlock);
if (LBlock[LMaxDataSize] = 0) or (LBlock[LMaxDataSize] >= FBlockSize) then begin
raise EIdBlockCipherInterceptException.CreateFmt(RSBlockIncorrectLength, [LBlock[LMaxDataSize]]);
end;
CopyTIdBytes(LBlock, 0, VBuffer, LPos, LBlock[LMaxDataSize]);
Inc(LPos, LBlock[LMaxDataSize]);
end;
if LRemaining > 0 then begin
CopyTIdBytes(FIncoming, LSize - LRemaining, FIncoming, 0, LRemaining);
end;
SetLength(FIncoming, LRemaining);
end;
SetLength(VBuffer, LPos);
end;
procedure TIdBlockCipherIntercept.CopySettingsFrom(ASrcBlockCipherIntercept: TIdBlockCipherIntercept);
Begin
FBlockSize := ASrcBlockCipherIntercept.FBlockSize;
FData := ASrcBlockCipherIntercept.FData; // not sure that this is actually safe
FOnConnect := ASrcBlockCipherIntercept.FOnConnect;
FOnDisconnect:= ASrcBlockCipherIntercept.FOnDisconnect;
FOnReceive := ASrcBlockCipherIntercept.FOnReceive;
FOnSend := ASrcBlockCipherIntercept.FOnSend;
end;
procedure TIdBlockCipherIntercept.SetBlockSize(const Value: Integer);
Begin
if (Value > 0) and (Value <= IdBlockCipherBlockSizeMax) then begin
FBlockSize := Value;
end;
end;
procedure TIdBlockCipherIntercept.InitComponent;
begin
inherited InitComponent;
FBlockSize := IdBlockCipherBlockSizeDefault;
SetLength(FIncoming, 0);
end;
end.
|
unit ipf_disk;
interface
uses {$ifdef windows}windows,{$else}main_engine,{$endif}dialogs;
function ipf_format(DrvNum:byte;longi_ini:dword;datos:pbyte):boolean;
implementation
uses disk_file_format;
type
tipf_header=packed record
name:array[0..3] of ansichar;
size:dword;
crc32:dword;
end;
tipf_info=packed record
mediaType:dword;
encoderType:dword;
encoderRev:dword;
fileKey:dword;
fileRev:dword;
origin:dword;
minTrack:dword;
maxTrack:dword;
minSide:dword;
maxSide:dword;
creationDate:dword;
creationTime:dword;
platforms:dword;
diskNumber:dword;
creatorId:dword;
reserved:array[0..5] of dword;
end;
tipf_imge=packed record
track:dword;
side:dword;
density:dword;
signatType:dword;
trackBytes:dword;
startBytePos:dword;
startBitPos:dword;
dataBits:dword;
gapBits:dword;
trackBits:dword;
blockCount:dword;
encoderProcess:dword;
trackFlags:dword;
dataKey:dword;
reserved:array[0..2] of dword;
end;
tipf_data=packed record
lenghtExtra:dword;
bitSize:dword;
crc:dword;
dataKey:dword;
end;
tipf_block=packed record
dataBits:dword;
gapBits:dword;
gapOffset:dword;
cellType:dword;
encoderType:dword;
blockFlags:dword;
gapDefault:dword;
dataOffset:dword;
end;
function big_to_little(val:dword):dword;
var
res:dword;
begin
res:=(val shr 24) or ((val shr 8) and $ff00) or ((val shl 8) and $ff0000) or ((val and $ff) shl 24);
big_to_little:=res;
end;
function ipf_format(DrvNum:byte;longi_ini:dword;datos:pbyte):boolean;
var
ipf_header:^tipf_header;
ipf_info:^tipf_info;
ipf_imge:^tipf_imge;
ipf_data:^tipf_data;
ipf_block:^tipf_block;
buffer_data,buffer_temp,buffer_temp2,track_data_temp,track_data_temp2:pbyte;
imge_data:array[0..1,0..82] of ^tipf_imge;
f,side_number,track_number,dataHead,dataSizeWidth,dataType:byte;
posicion,posicion_data_sector,dataLenght,total_sectores:dword;
g,sector_count:integer;
track_found,salir:boolean;
begin
ipf_format:=false;
if datos=nil then exit;
clear_disk(drvnum);
for track_number:=0 to 82 do begin
imge_data[0,track_number]:=nil;
imge_data[1,track_number]:=nil;
end;
getmem(ipf_header,sizeof(tipf_header));
copymemory(ipf_header,datos,12);posicion:=12;
inc(datos,12);
getmem(track_data_temp,$10000);
while posicion<longi_ini do begin
copymemory(ipf_header,datos,12);
ipf_header.size:=big_to_little(ipf_header.size)-12;
inc(datos,12);
inc(posicion,12);
if ipf_header.name='INFO' then begin
getmem(ipf_info,sizeof(tipf_info));
copymemory(ipf_info,datos,sizeof(tipf_info));
ipf_info.maxTrack:=big_to_little(ipf_info.maxTrack);
ipf_info.maxSide:=big_to_little(ipf_info.maxSide);
dsk[drvnum].DiskHeader.nbof_tracks:=ipf_info.maxTrack;
dsk[drvnum].DiskHeader.nbof_heads:=ipf_info.maxSide;
freemem(ipf_info);
inc(datos,ipf_header.size);
inc(posicion,ipf_header.size);
end;
if ipf_header.name='IMGE' then begin
getmem(ipf_imge,sizeof(tipf_imge));
copymemory(ipf_imge,datos,sizeof(tipf_imge));
ipf_imge.track:=big_to_little(ipf_imge.track);
ipf_imge.side:=big_to_little(ipf_imge.side);
ipf_imge.blockCount:=big_to_little(ipf_imge.blockCount);
ipf_imge.dataKey:=big_to_little(ipf_imge.dataKey);
getmem(imge_data[ipf_imge.side,ipf_imge.track],sizeof(tipf_imge));
copymemory(imge_data[ipf_imge.side,ipf_imge.track],ipf_imge,sizeof(tipf_imge));
freemem(ipf_imge);
inc(datos,ipf_header.size);
inc(posicion,ipf_header.size);
end;
if ipf_header.name='DATA' then begin
getmem(ipf_data,sizeof(tipf_data));
copymemory(ipf_data,datos,sizeof(tipf_data));
ipf_data.lenghtExtra:=big_to_little(ipf_data.lenghtExtra);
ipf_data.dataKey:=big_to_little(ipf_data.dataKey);
inc(datos,ipf_header.size);
inc(posicion,ipf_header.size);
//Continuo si tengo datos extra...
getmem(buffer_data,ipf_data.lenghtExtra);
copymemory(buffer_data,datos,ipf_data.lenghtExtra);
inc(datos,ipf_data.lenghtExtra);
inc(posicion,ipf_data.lenghtExtra);
//Ya he llegado, ahora hago cosas con los datos!
//Primero busco la informacion del track, relacionando el dataKey de los dos
track_found:=false;
for side_number:=0 to dsk[drvnum].DiskHeader.nbof_heads do begin
for track_number:=0 to dsk[drvnum].DiskHeader.nbof_tracks do begin
if imge_data[side_number,track_number]<>nil then begin
if imge_data[side_number,track_number].dataKey=ipf_data.dataKey then track_found:=true;
end;
if track_found then break;
end;
if track_found then break;
end;
//Vale, ya tengo los datos del track
if track_found then begin
dsk[DrvNum].Tracks[side_number,track_number].track_number:=imge_data[side_number,track_number].track;
dsk[DrvNum].Tracks[side_number,track_number].side_number:=imge_data[side_number,track_number].side;
buffer_temp:=buffer_data;
//Primero copio el bloque que hay dentro de los datos
getmem(ipf_block,sizeof(tipf_block));
posicion_data_sector:=0;
total_sectores:=0;
for sector_count:=0 to (imge_data[side_number,track_number].blockCount-1) do begin
copymemory(ipf_block,buffer_temp,sizeof(tipf_block));
//Donde empiezan los datos??
ipf_block.dataOffset:=big_to_little(ipf_block.dataOffset);
//OK, me voy a por los datos
buffer_temp2:=buffer_data;
inc(buffer_temp2,ipf_block.dataOffset);
//Ya estoy apuntando a los datos, analizo lo que hay...
salir:=false;
while not(salir) do begin
dataHead:=buffer_temp2^;inc(buffer_temp2);
if dataHead=0 then salir:=true
else begin
dataSizeWidth:=dataHead shr 5;
dataType:=dataHead and $1f;
dataLenght:=0;
for f:=0 to (dataSizeWidth-1) do begin
dataLenght:=dataLenght+(buffer_temp2^ shl (8*(dataSizeWidth-1-f)));
inc(buffer_temp2);
end;
case dataType of
1:begin //Sync...
track_data_temp2:=track_data_temp;
inc(track_data_temp2,posicion_data_sector);
copymemory(track_data_temp2,buffer_temp2,dataLenght);
posicion_data_sector:=posicion_data_sector+dataLenght;
inc(buffer_temp2,dataLenght);
end;
2:begin //Datos... ESTOS SI!
case buffer_temp2^ of
$fc:begin //la informacion del track
track_data_temp2:=track_data_temp;
inc(track_data_temp2,posicion_data_sector);
copymemory(track_data_temp2,buffer_temp2,dataLenght);
posicion_data_sector:=posicion_data_sector+dataLenght;
inc(buffer_temp2,dataLenght);
end;
$fe,$ff:begin //informacion del sector (numero, trac, size)
track_data_temp2:=track_data_temp;
inc(track_data_temp2,posicion_data_sector);
copymemory(track_data_temp2,buffer_temp2,dataLenght);
posicion_data_sector:=posicion_data_sector+dataLenght;
//IDAM data, deberia ser algo entre $FF y $FC, estandar $FE
inc(buffer_temp2);
dsk[drvnum].Tracks[side_number,track_number].sector[total_sectores].track:=buffer_temp2^;
inc(buffer_temp2);
dsk[drvnum].Tracks[side_number,track_number].sector[total_sectores].head:=buffer_temp2^;
inc(buffer_temp2);
dsk[drvnum].Tracks[side_number,track_number].sector[total_sectores].sector:=buffer_temp2^;
inc(buffer_temp2);
dsk[drvnum].Tracks[side_number,track_number].sector[total_sectores].sector_size:=buffer_temp2^;
inc(buffer_temp2);
inc(buffer_temp2,dataLenght-5); //CRC data
end;
$f8..$fb:begin //contenido del sector
dsk[drvnum].Tracks[side_number,track_number].sector[total_sectores].posicion_data:=posicion_data_sector+1;
//Copio los datos en un buffer temporal...
track_data_temp2:=track_data_temp;
inc(track_data_temp2,posicion_data_sector);
//DAM o DDAM Data
//Si es $FA o $FB track normal, si es $F8 o $F9 track borrado
dsk[drvnum].Tracks[side_number,track_number].sector[total_sectores].status2:=(not(buffer_temp2^) and $2) shl 5;
copymemory(track_data_temp2,buffer_temp2,dataLenght);
inc(posicion_data_sector,dataLenght);
dsk[drvnum].Tracks[side_number,track_number].sector[total_sectores].data_length:=dataLenght-3;
inc(buffer_temp2,dataLenght);
total_sectores:=total_sectores+1;
track_data_temp2:=track_data_temp;
inc(track_data_temp2,posicion_data_sector);
for f:=0 to 79 do begin
track_data_temp2^:=$f7;
inc(track_data_temp2);
inc(posicion_data_sector);
end;
end;
else begin
track_data_temp2:=track_data_temp;
inc(track_data_temp2,posicion_data_sector);
copymemory(track_data_temp2,buffer_temp2,dataLenght);
posicion_data_sector:=posicion_data_sector+dataLenght;
inc(buffer_temp2,dataLenght);
end;
end;
end;
3:begin //InterGAP...
track_data_temp2:=track_data_temp;
inc(track_data_temp2,posicion_data_sector);
copymemory(track_data_temp2,buffer_temp2,dataLenght);
posicion_data_sector:=posicion_data_sector+dataLenght;
inc(buffer_temp2,dataLenght);
end;
4:MessageDlg('GAP data found in data section!', mtInformation,[mbOk], 0);
5:begin //Sectores debiles... Tengo toda la informacion del sector, excepto los datos, que me los invento
//Me posiciono en los datos del sector
track_data_temp2:=track_data_temp;
inc(track_data_temp2,posicion_data_sector);
dsk[drvnum].Tracks[side_number,track_number].sector[total_sectores-1].status1:=$20;
dsk[drvnum].Tracks[side_number,track_number].sector[total_sectores-1].status2:=$20;
dsk[drvnum].Tracks[side_number,track_number].sector[total_sectores-1].data_length:=dataLenght*3;
dsk[drvnum].Tracks[side_number,track_number].sector[total_sectores-1].multi:=true;
dsk[drvnum].cont_multi:=3;
dsk[drvnum].max_multi:=3;
inc(posicion_data_sector,dataLenght*3);
for f:=0 to 2 do begin
for g:=0 to ((dataLenght shr 1)-1) do begin
track_data_temp2^:=$e5;
inc(track_data_temp2);
end;
for g:=0 to ((dataLenght shr 1)-1) do begin
track_data_temp2^:=random(256);
inc(track_data_temp2);
end;
end;
end;
end;
end;
end;
inc(buffer_temp,sizeof(tipf_block));
end;
freemem(ipf_block);
end else MessageDlg('There is IMGE but no track DATA found!', mtInformation,[mbOk], 0);
//Vale, ya tengo todos los datos del track...
dsk[DrvNum].Tracks[side_number,track_number].number_sector:=total_sectores;
getmem(dsk[drvnum].Tracks[side_number,track_number].data,posicion_data_sector);
copymemory(dsk[drvnum].Tracks[side_number,track_number].data,track_data_temp,posicion_data_sector);
dsk[drvnum].Tracks[side_number,track_number].track_lenght:=posicion_data_sector;
freemem(buffer_data);
freemem(ipf_data);
end;
end;
//check_protections(drvnum,false);
dsk[drvnum].abierto:=true;
freemem(ipf_header);
freemem(track_data_temp);
ipf_format:=true;
end;
end.
|
{******************************************************************************}
{ }
{ Hook and Translate }
{ }
{ The contents of this file are subject to the MIT License (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at https://opensource.org/licenses/MIT }
{ }
{ 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 Global.pas. }
{ }
{ Contains various graphics related classes and subroutines required for }
{ creating a chart and its nodes, and visual chart interaction. }
{ }
{ Unit owner: Mišel Krstović }
{ Last modified: March 8, 2010 }
{ }
{******************************************************************************}
unit Global;
interface
uses Windows, IniFiles, SysUtils;
//define the structure of the SetHookHandle function in transhook.dll
type
TSetHookHandle = procedure(HookHandle: HHook); stdcall;
var
LibLoaded: boolean; //true if transhook.dll is already loaded
LibHandle: HInst; //dll handle
HookProcAdd: pointer; //memory address of hook procedure in windows
GHookInstalled: boolean;
SetHookHandle: TSetHookHandle;
CurrentHook: HHook; //contains the handle of the currently installed hook
SettingsPath: String;
GlobalINIFile: TMemIniFile;
function LoadHookProc: boolean;
function SetupGlobalHook: boolean;
function RemoveGlobalHook: boolean;
implementation
const
BLANK_TRANSLATION = '';
function DllPath : String;
var
Path : Array[0..MAX_PATH-1] of char;
begin
if IsLibrary then SetString(Result, path, GetModuleFileName(hInstance, path, sizeof(path)))
else result := ParamStr(0);
end;
function GetKey(Section : String; Key : String) : String;
begin
result := BLANK_TRANSLATION;
Section := trim(Section);
Key := trim(Key);
try
if Key<>'' then result := GlobalIniFile.ReadString(Section, Key, BLANK_TRANSLATION);
finally
if result=BLANK_TRANSLATION then result := Key;
end;
end;
{
LoadHookProc
------------
This function loads the hook procedure from the dll created in transhook.dll
and obtains a handle for the dll and the address of the procedure in the
dll. The procedure will be called 'GlobalWndProcHook'
This procedure also loads the SetHookHandle procedure in transhook.dll. As
explained in the dll code, this procedure is simply used to inform the dll
of the handle for the current hook, which is needed to call CallNextHookEx
and also to initialise the keyarray (see the dll code).
}
function LoadHookProc: boolean;
begin
//attempt to load the dll containing our hook proc
LibHandle:=LoadLibrary('transhook.dll');
if LibHandle=0 then begin //if loading fails, exit and return false
LoadHookProc:=false;
exit;
end;
//once the dll is loaded, get the address in the dll of our hook proc
HookProcAdd:=GetProcAddress(LibHandle,'GlobalWndProcHook');
@SetHookHandle:=GetProcAddress(LibHandle,'SetHookHandle');
if (HookProcAdd=nil)or(@SetHookHandle=nil) then begin //if loading fails, unload library, exit and return false
FreeLibrary(LibHandle);
LoadHookProc:=false;
exit;
end;
LoadHookProc:=true;
end;
{
SetupGlobalHook
---------------
This function installs a global hook. To the install a global hook, we first have
to load the hook procedure that we have written from transhook.dll, using the LoadHookProc
above. If succesful use the setwindowshookex function specifying the hook type as WH_CALLWNDPROC,
the address of the hook procedure is that loaded from transhook.dll, the hMod is the handle
of the loaded transhook.dll and the threadid is set to 0 to indicate a global hook.
}
function SetupGlobalHook: boolean;
var
FoundHandle,
FoundThreadId : HWND;
ClassName_ : String;
begin
SetupGlobalHook:=false;
if LibLoaded=false then LibLoaded:=LoadHookProc; //if transhook isnt loaded, load it
if LibLoaded=false then exit; //if dll loading fails, exit
ClassName_ := trim(GetKey('System','ClassName'));
FoundHandle := FindWindow(PChar(ClassName_), nil);
if FoundHandle<>0 then begin
FoundThreadID := GetWindowThreadProcessId(FoundHandle, nil);
CurrentHook := setwindowshookex(WH_CALLWNDPROC,HookProcAdd,LibHandle,FoundThreadID); //install hook
SetHookHandle(CurrentHook);
if CurrentHook<>0 then SetupGlobalHook:=true; //return true if it worked
end;
end;
function RemoveGlobalHook: boolean;
begin
result := UnhookWindowsHookEx(CurrentHook);
end;
initialization
SettingsPath := ExtractFilePath(DllPath)+PathDelim+'Settings.ini';
if GlobalIniFile=nil then begin
GlobalIniFile := TMemIniFile.Create(SettingsPath);
GlobalIniFile.CaseSensitive := false;
end;
end.
|
unit kwGetMember;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Библиотека "ScriptEngine"
// Модуль: "w:/common/components/rtl/Garant/ScriptEngine/kwGetMember.pas"
// Начат: 15.02.2012 19:15
// Родные Delphi интерфейсы (.pas)
// Generated from UML model, root element: <<ScriptKeyword::Class>> Shared Delphi Scripting::ScriptEngine::MembersWorking::MembersWorkingPack::GetMember
//
// Добирается до вложенного слова
// Пример:
// {code}
// : WithTest
//
// : A
// : B
// : C
// 'Hello' .
// ;
// 20 .
// ;
// 10 .
// ;
//
// :: A B ; DO
// :: A B C ; DO
//
// ;
//
// WithTest
// {code}
//
//
// Все права принадлежат ООО НПП "Гарант-Сервис".
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ! Полностью генерируется с модели. Править руками - нельзя. !
{$Include ..\ScriptEngine\seDefine.inc}
interface
{$If not defined(NoScripts)}
uses
kwCompiledWord,
tfwScriptingInterfaces,
l3Interfaces,
l3ParserInterfaces
;
{$IfEnd} //not NoScripts
{$If not defined(NoScripts)}
type
{$Include ..\ScriptEngine\tfwAnonimousWord.imp.pas}
TkwGetMember = {final} class(_tfwAnonimousWord_)
{* Добирается до вложенного слова
Пример:
[code]
: WithTest
: A
: B
: C
'Hello' .
;
20 .
;
10 .
;
:: A B ; DO
:: A B C ; DO
;
WithTest
[code] }
private
// private fields
f_PrevWord : TkwCompiledWord;
protected
// realized methods
function EndBracket(const aContext: TtfwContext): AnsiString; override;
protected
// overridden protected methods
procedure Cleanup; override;
{* Функция очистки полей объекта. }
procedure BeforeCompile(const aPrevContext: TtfwContext;
var theNewContext: TtfwContext); override;
procedure AfterCompile(var aPrevContext: TtfwContext;
var theNewContext: TtfwContext;
aCompiled: TkwCompiledWord); override;
procedure UnknownWord(var aContext: TtfwContext;
var theCompiled: TkwCompiledWord;
const aPrevFinder: Il3KeywordFinder); override;
function CompiledWordClass: RkwCompiledWord; override;
function SupressNextImmediate: Boolean; override;
procedure AfterCodePartAdded(aWord: TtfwWord;
var aCtx: TtfwContext); override;
public
// overridden public methods
class function GetWordNameForRegister: AnsiString; override;
end;//TkwGetMember
{$IfEnd} //not NoScripts
implementation
{$If not defined(NoScripts)}
uses
kwCompiledMembersPath,
l3Parser,
kwInteger,
kwString,
SysUtils,
TypInfo,
l3Base,
kwIntegerFactory,
kwStringFactory,
l3String,
l3Chars,
tfwAutoregisteredDiction,
tfwScriptEngine
;
{$IfEnd} //not NoScripts
{$If not defined(NoScripts)}
type _Instance_R_ = TkwGetMember;
{$Include ..\ScriptEngine\tfwAnonimousWord.imp.pas}
// start class TkwGetMember
function TkwGetMember.EndBracket(const aContext: TtfwContext): AnsiString;
//#UC START# *4DB6C99F026E_4F3BCBF303D6_var*
//#UC END# *4DB6C99F026E_4F3BCBF303D6_var*
begin
//#UC START# *4DB6C99F026E_4F3BCBF303D6_impl*
Result := ';';
//#UC END# *4DB6C99F026E_4F3BCBF303D6_impl*
end;//TkwGetMember.EndBracket
procedure TkwGetMember.Cleanup;
//#UC START# *479731C50290_4F3BCBF303D6_var*
//#UC END# *479731C50290_4F3BCBF303D6_var*
begin
//#UC START# *479731C50290_4F3BCBF303D6_impl*
f_PrevWord := nil;
inherited;
//#UC END# *479731C50290_4F3BCBF303D6_impl*
end;//TkwGetMember.Cleanup
class function TkwGetMember.GetWordNameForRegister: AnsiString;
{-}
begin
Result := '::';
end;//TkwGetMember.GetWordNameForRegister
procedure TkwGetMember.BeforeCompile(const aPrevContext: TtfwContext;
var theNewContext: TtfwContext);
//#UC START# *4DB6CDDA038B_4F3BCBF303D6_var*
//#UC END# *4DB6CDDA038B_4F3BCBF303D6_var*
begin
//#UC START# *4DB6CDDA038B_4F3BCBF303D6_impl*
inherited;
f_PrevWord := nil;
//#UC END# *4DB6CDDA038B_4F3BCBF303D6_impl*
end;//TkwGetMember.BeforeCompile
procedure TkwGetMember.AfterCompile(var aPrevContext: TtfwContext;
var theNewContext: TtfwContext;
aCompiled: TkwCompiledWord);
//#UC START# *4DB6CE2302C9_4F3BCBF303D6_var*
var
l_L : TtfwWordRefList;
l_Index : Integer;
l_W : TtfwWord;
l_C : TtfwWord;
//#UC END# *4DB6CE2302C9_4F3BCBF303D6_var*
begin
//#UC START# *4DB6CE2302C9_4F3BCBF303D6_impl*
l_L := aCompiled.Code;
CompilerAssert((l_L <> nil) AND
(l_L.Count > 0{1}),
'Пустой путь к элементу',
aPrevContext
);
l_W := nil;
for l_Index := 0 to Pred(l_L.Count) do
begin
l_C := l_L.Items[l_Index];
CompilerAssert((l_C Is TkwCompiledWord),
Format('Элемент %s не является компилировнным словом',
[l_C.Key.AsString]),
aPrevContext
);
if (l_W <> nil) then
begin
CompilerAssert(TkwCompiledWord(l_C).ParentWord = l_W,
Format('Элемент %s не является дочерним к %s',
[
l_C.Key.AsString,
l_W.Key.AsString
]),
aPrevContext
);
end;//l_W <> nil
l_W := l_C;
end;//for l_Index
DoCompiledWord(l_L.Last, aPrevContext);
(* while (aCompiled.Code.Count > 1) do
aCompiled.Code.Delete(0);*)
// - оставляем только последний элемент
inherited;
//#UC END# *4DB6CE2302C9_4F3BCBF303D6_impl*
end;//TkwGetMember.AfterCompile
procedure TkwGetMember.UnknownWord(var aContext: TtfwContext;
var theCompiled: TkwCompiledWord;
const aPrevFinder: Il3KeywordFinder);
//#UC START# *4DB6F2760023_4F3BCBF303D6_var*
(*var
l_KW : TtfwKeyWord;
l_W : TtfwWord;*)
//#UC END# *4DB6F2760023_4F3BCBF303D6_var*
begin
//#UC START# *4DB6F2760023_4F3BCBF303D6_impl*
(* Assert(f_PrevWord <> nil);
l_KW := (f_PrevWord.LocalDictionary.Keywords.DRbyName[aContext.rParser.TokenLongString]);
Assert(l_KW <> nil);
l_W := l_KW.Word;
if (l_W <> nil) then
begin
theCompiled.DoAddCodePart(l_W, false, aContext);
AfterCodePartAdded(l_W, aContext);
end//l_W <> nil
else*)
// есресь <<LibSupport>> - СТЕРЕОТИП
inherited;
//#UC END# *4DB6F2760023_4F3BCBF303D6_impl*
end;//TkwGetMember.UnknownWord
function TkwGetMember.CompiledWordClass: RkwCompiledWord;
//#UC START# *4DBAEE0D028D_4F3BCBF303D6_var*
//#UC END# *4DBAEE0D028D_4F3BCBF303D6_var*
begin
//#UC START# *4DBAEE0D028D_4F3BCBF303D6_impl*
Result := TkwCompiledMembersPath;
//#UC END# *4DBAEE0D028D_4F3BCBF303D6_impl*
end;//TkwGetMember.CompiledWordClass
function TkwGetMember.SupressNextImmediate: Boolean;
//#UC START# *4F3AB3B101FC_4F3BCBF303D6_var*
//#UC END# *4F3AB3B101FC_4F3BCBF303D6_var*
begin
//#UC START# *4F3AB3B101FC_4F3BCBF303D6_impl*
Result := true;
//#UC END# *4F3AB3B101FC_4F3BCBF303D6_impl*
end;//TkwGetMember.SupressNextImmediate
procedure TkwGetMember.AfterCodePartAdded(aWord: TtfwWord;
var aCtx: TtfwContext);
//#UC START# *4F3BCE1501F0_4F3BCBF303D6_var*
//#UC END# *4F3BCE1501F0_4F3BCBF303D6_var*
begin
//#UC START# *4F3BCE1501F0_4F3BCBF303D6_impl*
f_PrevWord := (aWord As TkwCompiledWord);
aCtx.rParser.KeyWords := f_PrevWord;
// - чтобы можно было искать ВНУТРИ aWord
//#UC END# *4F3BCE1501F0_4F3BCBF303D6_impl*
end;//TkwGetMember.AfterCodePartAdded
{$IfEnd} //not NoScripts
initialization
{$If not defined(NoScripts)}
{$Include ..\ScriptEngine\tfwAnonimousWord.imp.pas}
{$IfEnd} //not NoScripts
end. |
unit DAO.Funcoes;
interface
uses DAO.Base, Model.Funcoes, Generics.Collections, System.Classes;
type
TFuncoesDAO = class(TDAO)
public
function Insert(aFuncoes: Model.Funcoes.TFuncoes): Boolean;
function Update(aFuncoes: Model.Funcoes.TFuncoes): Boolean;
function Delete(sFiltro: String): Boolean;
function FindFuncoes(sFiltro: String): TObjectList<Model.Funcoes.TFuncoes>;
end;
const
TABLENAME = 'CAD_FUNCOES';
implementation
uses System.SysUtils, FireDAC.Comp.Client, Data.DB;
function TFuncoesDAO.Insert(aFuncoes: TFuncoes): Boolean;
var
sSQL : System.string;
begin
Result := False;
aFuncoes.ID := GetKeyValue(TABLENAME, 'ID_FUNCAO');
sSQL := 'INSERT INTO ' + TABLENAME + ' '+
'(ID_FUNCAO, DES_FUNCAO, DES_LOG) ' +
'VALUES ' +
'(:ID, :DESCRICAO, :LOG);';
Connection.ExecSQL(sSQL,[aFuncoes.ID, aFuncoes.Descricao, aFuncoes.Log],
[ftInteger, ftString, ftString]);
Result := True;
end;
function TFuncoesDAO.Update(aFuncoes: TFuncoes): Boolean;
var
sSQL: System.string;
begin
Result := False;
sSQL := 'UPDATE ' + TABLENAME + ' ' +
'SET ' +
'DES_FUNCAO = :DESCRICAO, DES_LOG = :LOG ' +
'WHERE ID_FUNCAO = :ID;';
Connection.ExecSQL(sSQL,[aFuncoes.Descricao, aFuncoes.Log, aFuncoes.ID],
[ftString, ftString, ftInteger]);
Result := True;
end;
function TFuncoesDAO.Delete(sFiltro: string): Boolean;
var
sSQL : String;
begin
Result := False;
sSQL := 'DELETE FROM ' + TABLENAME + ' ';
if not sFiltro.IsEmpty then
begin
sSQl := sSQL + sFiltro;
end
else
begin
Exit;
end;
Connection.ExecSQL(sSQL);
Result := True;
end;
function TFuncoesDAO.FindFuncoes(sFiltro: string): TObjectList<Model.Funcoes.TFuncoes>;
var
FDQuery: TFDQuery;
funcoes: TObjectList<TFuncoes>;
begin
FDQuery := TFDQuery.Create(nil);
try
FDQuery.Connection := Connection;
FDQuery.SQL.Clear;
FDQuery.SQL.Add('SELECT * FROM ' + TABLENAME);
if not sFiltro.IsEmpty then
begin
FDQuery.SQL.Add(sFiltro);
end;
FDQuery.Open();
funcoes := TObjectList<TFuncoes>.Create();
while not FDQuery.Eof do
begin
funcoes.Add(TFuncoes.Create(FDQuery.FieldByName('ID_FUNCAO').AsInteger, FDQuery.FieldByName('DES_FUNCAO').AsString,
FDQuery.FieldByName('DES_LOG').AsString));
FDQuery.Next;
end;
finally
FDQuery.Free;
end;
Result := funcoes;
end;
end.
|
unit StockDetail_Get_163;
interface
uses
BaseApp;
procedure GetStockDataDetail_163_All(App: TBaseApp);
implementation
uses
Windows,
define_datasrc,
define_price,
define_dealitem,
define_dealstore_file,
DB_DealItem,
DB_DealItem_Load,
DB_DealItem_Save,
UtilsHttp,
UtilsLog,
StockDayDataAccess,
StockDayData_Load,
StockDetailData_Get_163;
procedure DownloadDealItemDayDetailData(App: TBaseApp; AStockItem: PRT_DealItem; AHttpClientSession: PHttpClientSession);
var
tmpDayData: TStockDayDataAccess;
begin
tmpDayData := TStockDayDataAccess.Create(FilePath_DBType_Item, AStockItem, Src_163, weightNone);
try
try
if LoadStockDayData(App, tmpDayData) then
begin
Log('', 'Dowload Stock Detail:' + AStockItem.sCode);
if GetStockDataDetail_163(App, tmpDayData, AHttpClientSession) then
begin
Log('', 'Dowload Stock Detail ok:' + AStockItem.sCode);
Sleep(100);
end;
end;
except
Log('', 'Dowload Stock Detail error:' + AStockItem.sCode);
end;
finally
tmpDayData.Free;
end;
end;
procedure GetStockDataDetail_163_All(App: TBaseApp);
var
tmpDBStockItem: TDBDealItem;
tmpHttpClientSession: THttpClientSession;
i: integer;
begin
FillChar(tmpHttpClientSession, SizeOf(tmpHttpClientSession), 0);
tmpHttpClientSession.IsKeepAlive := true;
tmpDBStockItem := TDBDealItem.Create(FilePath_DBType_Item, 0);
try
LoadDBStockItemDic(App, tmpDBStockItem);
for i := 0 to tmpDBStockItem.RecordCount - 1 do
begin
if 0 = tmpDBStockItem.Items[i].EndDealDate then
begin
DownloadDealItemDayDetailData(App, tmpDBStockItem.Items[i], @tmpHttpClientSession);
end;
end;
finally
tmpDBStockItem.Free;
end;
end;
end.
|
{ This program finds and prints the "double characters"
(e.g., "ee", ""oo) in a file.}
program doubleChars;
const
BLANK = ' ';
var
oldchar, newchar: char;
begin
oldchar := BLANK;
while not eof do
begin
read(newchar);
if (newchar <> BLANK) and (oldchar = newchar)
then writeln(oldchar, newchar);
oldchar := newchar
end;
end.
|
{
$Project$
$Workfile$
$Revision$
$DateUTC$
$Id$
This file is part of the Indy (Internet Direct) project, and is offered
under the dual-licensing agreement described on the Indy website.
(http://www.indyproject.org/)
Copyright:
(c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved.
}
{
$Log$
}
unit IdTraceRoute;
interface
{$i IdCompilerDefines.inc}
uses
IdIcmpClient, IdRawBase, IdRawClient, IdThread;
type
TIdTraceRoute = class(TIdCustomICMPClient)
protected
FResolveHostNames : Boolean;
procedure DoReply; override;
public
procedure Trace;
published
{$IFDEF DOTNET_2_OR_ABOVE}
property IPVersion;
{$ENDIF}
property PacketSize;
property ReceiveTimeout;
property ResolveHostNames : Boolean read FResolveHostNames write FResolveHostNames;
property OnReply;
end;
implementation
uses
IdGlobal, IdStack;
{ TIdTraceRoute }
procedure TIdTraceRoute.DoReply;
begin
if FResolveHostNames and
(PosInStrArray(FReplyStatus.FromIpAddress, ['0.0.0.0', '::0']) = -1) then {do not localize}
begin
//resolve IP to hostname
try
FReplyStatus.HostName := GStack.HostByAddress(FReplyStatus.FromIpAddress, FBinding.IPVersion);
except
{
We do things this way because we are likely have a reverse DNS
failure if you have a computer with IP address and no DNS name at all.
}
FReplyStatus.HostName := FReplyStatus.FromIpAddress;
end;
end;
inherited DoReply;
end;
procedure TIdTraceRoute.Trace;
//In traceroute, there are a maximum of thirty echo request packets. You start
//requests with a TTL of one and keep sending them until you get to thirty or you
//get an echo response (whatever comes sooner).
var i : Integer;
lSeq : Cardinal;
LTTL : Integer;
LIPAddr : String;
begin
// PacketSize := 64;
//We do things this way because we only want to resolve the destination host name
//only one time. Otherwise, there's a performance penalty for earch DNS resolve.
LIPAddr := GStack.ResolveHost(FHost, FBinding.IPVersion);
LSeq := $1;
LTTL := 1;
TTL := LTTL;
for i := 1 to 30 do
begin
ReplyStatus.PacketNumber := i;
InternalPing(LIPAddr, '', LSeq);
case ReplyStatus.ReplyStatusType of
rsErrorTTLExceeded,
rsTimeout : ;
else
Break;
end;
Inc(LTTL);
TTL := LTTL;
LSeq := LSeq * 2;
end;
end;
end.
|
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls;
type
TForm1 = class(TForm)
RgpColor: TRadioGroup;
private
{ Private-Deklarationen }
protected
procedure WMNCPaint(var Msg: TWMNCPaint) ; message WM_NCPAINT;
procedure WMNCACTIVATE(var Msg: TWMNCActivate) ; message WM_NCACTIVATE;
function GetColor:TColor;
procedure DrawCaptionText;
public
{ Public-Deklarationen }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
{ TForm1 }
procedure TForm1.DrawCaptionText;
const
captionText = 'Delphi Praxis Demo';
var
canvas: TCanvas;
begin
canvas := TCanvas.Create;
try
canvas.Handle := GetWindowDC(Self.Handle);
with canvas do
begin
// Bereich überm Fenster
Brush.Color := clLime;
Rectangle(0, 0, Width-1, 23);
// Rahmen
Pen.Color := GetColor;
Pen.Width := 7;
Brush.Style := bsClear;
Polygon([Point(0,0), Point(Width-1, 0),
Point(Width-1, Height-1), Point(0, Height-1)]);
Brush.Style := bsClear;
Font.Color := clBlack;
TextOut(20, 6, captionText) ;
end;
finally
ReleaseDC(Self.Handle, canvas.Handle) ;
canvas.Free;
end;
end;
function TForm1.GetColor: TColor;
begin
case RgpColor.ItemIndex of
0:
Result := clRed;
1:
Result := clGreen;
2:
Result := clYellow;
else
Result := clBlack;
end;
end;
procedure TForm1.WMNCACTIVATE(var Msg: TWMNCActivate);
begin
DrawCaptionText;
Msg.Result := 0;
end;
procedure TForm1.WMNCPaint(var Msg: TWMNCPaint);
begin
DrawCaptionText;
Msg.Result := 0;
end;
end.
|
unit GX_IdeUtils;
{ A number of utility functions that work directly on the
IDE using mechanism provided by the VCL.
None of the functions in this unit use the "official"
way through the Open Tools API, as the Open Tools API
does not deliver whatever is needed here.
See GX_OtaUtils.pas for routines that make use of the
officially exposed functionality. }
interface
{$I GX_CondDefine.inc}
uses
Graphics, Forms, Menus, ComCtrls, Controls, Classes;
type
{$IFDEF GX_VER160_up}
IDEEditBufferString = UTF8String;
{$ELSE}
IDEEditBufferString = AnsiString;
{$ENDIF}
const
EditorFormClassName = 'TEditWindow';
EditorControlName = 'Editor';
EditorControlClassName = 'TEditControl';
// Returns a reference to the main form of the IDE (TAppBuilder)
function GetIdeMainForm: TCustomForm;
// Returns the height of a IDE main menu item
function GetMainMenuItemHeight: Integer;
// Returns the height of a standard OS menu item
function GetStandardMenuItemHeight: Integer;
// Returns a reference to the IDE's component palette tab control.
// May return nil.
function GetComponentPaletteTabControl: TTabControl;
// Returns a reference to the Object Inspector form.
// May return nil.
function GetObjectInspectorForm: TCustomForm;
function GetComponentPalettePopupMenu: TPopupMenu;
// Returns True of AForm is an editor form in the IDE,
// False otherwise. AForm may be nil.
function IsIdeEditorForm(AForm: TCustomForm): Boolean;
function IsEditControl(Control: TControl): Boolean;
// Get the actual TEditControl embedded in the given IDE editor form
function GetIDEEditControl(Form: TCustomForm): TWinControl;
function GetIDEFormNamed(const FormName: string): TCustomForm;
// We can cause internal editor kernel AVs if we change the editor text
// while the replace confirmation dialog is up, so we detect that case here
function IsReplaceConfirmDialogOnScreen: Boolean;
// Return the IDE's root directory (the installation directory).
// Returns an empty string if the information could not be retrieved.
function GetIdeRootDirectory: string;
// Return the IDE's version identifier, such as ENT, CSS, PRO, STD,
// or the empty string if unknown
function GetIdeEdition: string;
// Get the IDE's editor background color
function GetIdeEditorBackgroundColor: TColor;
function GetIdeEnvironmentOverrides(Overrides: TStrings): Boolean;
// Set the PopupMode property in Delphi 8+ to get the z-order/layering right
procedure SetNonModalFormPopupMode(Form: TCustomForm);
procedure SetModalFormPopupMode(Form: TCustomForm);
function GetIDEVersionID: string;
function RunningWindows: Boolean;
function RunningDelphi8: Boolean;
function RunningDelphi8OrGreater: Boolean;
function RunningDelphi7OrLess: Boolean;
function RunningDelphi7OrGreater: Boolean;
function RunningDelphi2005: Boolean;
function RunningBDS2006OrLess: Boolean;
function RunningBDS2006: Boolean;
function RunningBDS2006OrGreater: Boolean;
function RunningDelphi2007OrLess: Boolean;
function RunningDelphi2007: Boolean;
function RunningDelphi2007OrGreater: Boolean;
function RunningRS2009: Boolean;
function RunningRS2009OrGreater: Boolean;
function RunningRS2010OrGreater: Boolean;
function RunningRSXE: Boolean;
function RunningRSXEOrGreater: Boolean;
function RunningCPPBuilder: Boolean;
function IDEHasWelcomePage: Boolean;
function FileIsWelcomePage(const FileName: string): Boolean;
function IDEEditorEncodingIsUTF8: Boolean;
implementation
uses
{$IFOPT D+} GX_DbugIntf, {$ENDIF}
SysUtils, Windows, Registry,
GX_GenericUtils, GX_GxUtils, GX_OtaUtils, StrUtils;
function GetIdeMainForm: TCustomForm;
begin
Assert(Assigned(Application));
Result := Application.FindComponent('AppBuilder') as TCustomForm;
{$IFOPT D+}
if Result = nil then
SendDebugError('Unable to find AppBuilder!');
{$ENDIF}
end;
function GetMainMenuItemHeight: Integer;
{$IFDEF GX_VER150_up}
var
MainForm: TCustomForm;
Component: TComponent;
begin
Result := 23;
MainForm := GetIdeMainForm;
Component := nil;
if MainForm <> nil then
Component := MainForm.FindComponent('MenuBar');
if (Component is TControl) then
Result := TControl(Component).ClientHeight; // This is approximate?
{$ELSE}
begin
Result := GetSystemMetrics(SM_CYMENU);
{$ENDIF}
end;
function GetStandardMenuItemHeight: Integer;
begin
Result := GetSystemMetrics(SM_CYMENU);
if Result < 1 then
Result := 20; // Guess instead of raising an error? This should never happen.
end;
function GetComponentPaletteTabControl: TTabControl;
var
MainForm: TCustomForm;
begin
Result := nil;
MainForm := GetIdeMainForm;
if MainForm <> nil then
Result := MainForm.FindComponent('TabControl') as TTabControl;
{$IFOPT D+}
if (Result = nil) and (ComponentPaletteAvailable) then
SendDebugError('Unable to find component palette TTabControl!');
{$ENDIF}
end;
function GetObjectInspectorForm: TCustomForm;
var
MainForm: TCustomForm;
begin
Result := nil;
MainForm := GetIdeMainForm;
if MainForm <> nil then
Result := (MainForm.FindComponent('PropertyInspector') as TCustomForm);
if Result = nil then
Result := GetIDEFormNamed('PropertyInspector');
{$IFOPT D+}
if Result = nil then
SendDebugError('Unable to find object inspector!');
{$ENDIF}
end;
function GetComponentPalettePopupMenu: TPopupMenu;
var
MainForm: TCustomForm;
begin
Result := nil;
MainForm := GetIdeMainForm;
if MainForm <> nil then
Result := (MainForm.FindComponent('PaletteMenu') as TPopupMenu);
{$IFOPT D+}
if Result = nil then
SendDebugError('Unable to find PaletteMenu!');
{$ENDIF}
end;
function IsIdeEditorForm(AForm: TCustomForm): Boolean;
begin
Result := (AForm <> nil) and
(StrBeginsWith('EditWindow_', AForm.Name)) and
(AForm.ClassName = EditorFormClassName) and
(not (csDesigning in AForm.ComponentState));
end;
function IsEditControl(Control: TControl): Boolean;
begin
Result := False;
if Assigned(Control) then
Result := Control.ClassName = EditorControlClassName;
end;
function GetIDEEditControl(Form: TCustomForm): TWinControl;
var
Component: TComponent;
begin
Assert(Assigned(Form));
Result := nil;
Component := (Form.FindComponent(EditorControlName) as TWinControl);
if Assigned(Component) then
if Component is TWinControl then
Result := Component as TWinControl;
end;
function GetIDEFormNamed(const FormName: string): TCustomForm;
var
i: Integer;
begin
Result := nil;
for i := 0 to Screen.CustomFormCount - 1 do
begin
if Screen.CustomForms[i].Name = FormName then
begin
Result := Screen.CustomForms[i];
Break;
end;
end;
end;
// We can cause internal editor kernel AVs if we change the editor text
// while the replace confirmation dialog is up, so we detect that case here
function IsReplaceConfirmDialogOnScreen: Boolean;
const
ConfirmDialogClassName = 'TMessageForm';
var
AForm: TForm;
i: Integer;
begin
Result := False;
Assert(Assigned(Screen));
// We search in reverse order, since what we're looking for
// should usually be last
for i := Screen.FormCount - 1 downto 0 do
begin
AForm := Screen.Forms[i];
Assert(Assigned(AForm));
if SameText(AForm.ClassName, ConfirmDialogClassName) then
begin
// Make sure it lives in the main VCL module (package or not)
if FindClassHInstance(AForm.ClassType) = VclInstance then
begin
// Now some weak heuristics (don't localize the component names).
if Assigned(AForm.FindComponent('Yes')) and
Assigned(AForm.FindComponent('No')) and
Assigned(AForm.FindComponent('Cancel')) and
Assigned(AForm.FindComponent('All')) then
begin
Result := True;
Break;
end;
end;
end;
end;
end;
function GetIdeRootDirectory: string;
const
BinDirPostfix = PathDelim + 'Bin';
begin
Result := '';
try
with TRegistry.Create do
try
RootKey := HKEY_LOCAL_MACHINE;
if OpenKeyReadOnly(GxOtaGetIdeBaseRegistryKey) then
begin
Result := ReadString('RootDir');
CloseKey;
end;
finally
Free;
end;
except
on E: Exception do
GxLogException(E, 'Error in GetIdeRootDirectory');
end;
if not DirectoryExists(Result) then
begin
Result := RemoveSlash(ExtractFilePath(Application.ExeName));
if SameText(RightStr(Result, Length(BinDirPostfix)), BinDirPostfix) then
Result := DeleteRight(Result, Length(BinDirPostfix))
else
Result := '';
end;
Result := AddSlash(Result);
end;
function GetIdeEdition: string;
begin
Result := '';
with TRegistry.Create do
try
RootKey := HKEY_LOCAL_MACHINE;
if OpenKeyReadOnly(GxOtaGetIdeBaseRegistryKey) then
begin
Result := ReadString('Version');
CloseKey;
end;
finally
Free;
end;
end;
function GetIdeEditorBackgroundColor: TColor;
const
RegAddKey = '\Editor\Highlight\Whitespace'; // do not localize
var
Reg: TRegistry;
Value: Integer;
const
IdePalette: array [0..15] of TColor = (clBlack, clMaroon, clGreen,
clOlive, clNavy, clPurple, clTeal, clLtGray, clDkGray, clRed,
clLime, clYellow, clBlue, clFuchsia, clAqua, clWhite);
begin
Result := clWindow;
Reg := TRegistry.Create;
try
if Reg.OpenKey(GxOtaGetIdeBaseRegistryKey + RegAddKey, False) then
begin
if Reg.ValueExists('Default Background') then
begin
if Reg.GetDataType('Default Background') = rdString then
begin
if SameText(Reg.ReadString('Default Background'), 'False') then
begin
if Reg.ValueExists('Background Color') then
begin
if Reg.GetDataType('Background Color') = rdInteger then
begin
Value := Reg.ReadInteger('Background Color');
if (Value > 15) or (Value < 0) then
Value := 15;
Result := IdePalette[Value];
end;
end;
end;
end;
end;
end;
finally
FreeAndNil(Reg);
end;
{$IFOPT D+}SendDebug('IDE Background Color is: ' + ColorToString(Result) + ' '); {$ENDIF}
end;
function GetIdeEnvironmentOverrides(Overrides: TStrings): Boolean;
var
Reg: TRegistry;
Names: TStringList;
i: Integer;
Value: string;
begin
Assert(Assigned(Overrides));
Overrides.Clear;
Result := True;
Names := nil;
Reg := TRegistry.Create;
try
Names := TStringList.Create;
if Reg.OpenKey(GxOtaGetIdeBaseRegistryKey + '\Environment Variables', False) then
begin
Reg.GetValueNames(Names);
for i := 0 to Names.Count - 1 do begin
Value := Reg.ReadString(Names[i]);
Overrides.Add(Names[i] + '=' + Value);
end;
end;
finally
FreeAndNil(Reg);
FreeAndNil(Names);
end;
end;
procedure SetNonModalFormPopupMode(Form: TCustomForm);
begin //FI:W519
{$IFDEF GX_VER160_up}
if Assigned(Form) then
Form.PopupMode := pmExplicit;
{$ENDIF GX_VER160_up}
end;
procedure SetModalFormPopupMode(Form: TCustomForm);
begin //FI:W519
{$IFDEF GX_VER160_up}
if Assigned(Form) then
Form.PopupMode := pmAuto;
{$ENDIF GX_VER160_up}
end;
function GetIDEVersionID: string;
var
RegKey: string;
LastSlashPos: Integer;
Version: string;
begin
RegKey := GxOtaGetIdeBaseRegistryKey;
LastSlashPos := LastCharPos(RegKey, '\');
Version := Copy(RegKey, LastSlashPos + 1, 999);
Result := Version;
if RunningDelphi8OrGreater then
Result := 'BDS' + Version;
end;
function RunningWindows: Boolean;
begin
{$IFDEF MSWINDOWS}
Result := True;
{$ELSE}
Result := False;
{$ENDIF}
end;
function RunningDelphi8: Boolean;
begin
{$IFDEF VER160}
Result := True;
{$ELSE}
Result := False;
{$ENDIF}
end;
function RunningDelphi8OrGreater: Boolean;
begin
{$IFDEF GX_VER160_up}
Result := True;
{$ELSE}
Result := False;
{$ENDIF}
end;
function RunningDelphi7OrLess: Boolean;
begin
Result := not RunningDelphi8OrGreater;
end;
function RunningDelphi7OrGreater: Boolean;
begin
{$IFDEF GX_VER150_up}
Result := True;
{$ELSE}
Result := False;
{$ENDIF}
end;
function RunningDelphi2005: Boolean;
begin
{$IFDEF VER170}
Result := True;
{$ELSE}
Result := False;
{$ENDIF}
end;
function RunningDelphi2007: Boolean;
begin
{$IFDEF VER185}
Result := True;
{$ELSE}
Result := False;
{$ENDIF}
end;
function RunningDelphi2007OrLess: Boolean;
begin
{$IFDEF GX_VER200_up}
Result := False;
{$ELSE}
Result := True;
{$ENDIF}
end;
function RunningDelphi2007OrGreater: Boolean;
begin
{$IFDEF GX_VER185_up}
Result := True;
{$ELSE}
Result := False;
{$ENDIF}
end;
function RunningRS2009: Boolean;
begin
{$IFDEF VER200}
Result := True;
{$ELSE}
Result := False;
{$ENDIF}
end;
function RunningRSXE: Boolean;
begin
{$IFDEF VER220}
Result := True;
{$ELSE}
Result := False;
{$ENDIF}
end;
function RunningRSXEOrGreater: Boolean;
begin
{$IFDEF GX_VER220_up}
Result := True;
{$ELSE}
Result := False;
{$ENDIF}
end;
function RunningRS2009OrGreater: Boolean;
begin
{$IFDEF GX_VER200_up}
Result := True;
{$ELSE}
Result := False;
{$ENDIF}
end;
function RunningRS2010OrGreater: Boolean;
begin
{$IFDEF GX_VER210_up}
Result := True;
{$ELSE}
Result := False;
{$ENDIF}
end;
function RunningBDS2006OrGreater: Boolean;
begin
{$IFDEF GX_VER180_up}
Result := True;
{$ELSE}
Result := False;
{$ENDIF}
end;
function RunningBDS2006OrLess: Boolean;
begin
Result := not RunningDelphi2007OrGreater;
end;
function RunningBDS2006: Boolean;
begin
{$IFDEF VER180}
Result := True;
{$ELSE}
Result := False;
{$ENDIF}
end;
// This is whether we are running C++Builder Version 6, not if the IDE has C++ support (like BDS2006+)
function RunningCPPBuilder: Boolean;
begin
{$IFDEF BCB}
Result := True;
{$ELSE}
Result := False;
{$ENDIF}
end;
function IDEHasWelcomePage: Boolean;
begin
Result := RunningDelphi8OrGreater;
end;
function FileIsWelcomePage(const FileName: string): Boolean;
begin
Result := IDEHasWelcomePage and StringInArray(FileName, ['default.htm', 'bds:/default.htm']);
end;
function IDEEditorEncodingIsUTF8: Boolean;
begin
Result := RunningDelphi8OrGreater;
end;
end.
|
object DmCompanies: TDmCompanies
OldCreateOrder = False
Left = 304
Top = 161
Height = 370
Width = 417
object DataCompanies: TIBDataSet
Database = DmMain.IBDatabase1
Transaction = IBTransaction1
BufferChunks = 1000
CachedUpdates = False
DeleteSQL.Strings = (
'delete from COMPANIES'
'where'
' ID = :OLD_ID and'
' NAME = :OLD_NAME and'
' TAX_CODE = :OLD_TAX_CODE')
InsertSQL.Strings = (
'insert into COMPANIES'
' (ID, NAME, TAX_CODE)'
'values'
' (:ID, :NAME, :TAX_CODE)')
RefreshSQL.Strings = (
'Select '
' ID,'
' NAME,'
' TAX_CODE,'
' NAME_UPPER'
'from COMPANIES '
'where'
' ID = :ID and'
' NAME = :NAME and'
' TAX_CODE = :TAX_CODE')
SelectSQL.Strings = (
'select c.id, c.name, c.tax_code from companies c')
ModifySQL.Strings = (
'update COMPANIES'
'set'
' ID = :ID,'
' NAME = :NAME,'
' TAX_CODE = :TAX_CODE'
'where'
' ID = :OLD_ID and'
' NAME = :OLD_NAME and'
' TAX_CODE = :OLD_TAX_CODE')
GeneratorField.Field = 'ID'
GeneratorField.Generator = 'G_MASTER'
Left = 48
Top = 40
object DataCompaniesID: TIntegerField
FieldName = 'ID'
Required = True
end
object DataCompaniesNAME: TIBStringField
FieldName = 'NAME'
Size = 50
end
object DataCompaniesTAX_CODE: TIBStringField
FieldName = 'TAX_CODE'
Size = 16
end
end
object DataLocations: TIBDataSet
Database = DmMain.IBDatabase1
Transaction = IBTransaction1
AfterInsert = DataLocationsAfterInsert
BufferChunks = 1000
CachedUpdates = False
DeleteSQL.Strings = (
'delete from LOCATIONS'
'where'
' ID = :OLD_ID')
InsertSQL.Strings = (
'insert into LOCATIONS'
' (ID, ID_COMPANY, ADDRESS, FAX, PHONE, STATE, TOWN, ZIP)'
'values'
' (:ID, :ID_COMPANY, :ADDRESS, :FAX, :PHONE, :STATE, :TOWN, :ZIP' +
')')
RefreshSQL.Strings = (
'Select '
' ID,'
' ID_COMPANY,'
' ADDRESS,'
' TOWN,'
' ZIP,'
' STATE,'
' PHONE,'
' FAX'
'from LOCATIONS '
'where'
' ID = :ID')
SelectSQL.Strings = (
'select ID, ID_COMPANY, ADDRESS, FAX, '
' PHONE, STATE, TOWN, ZIP '
'from LOCATIONS'
'where ID_COMPANY = :id')
ModifySQL.Strings = (
'update LOCATIONS'
'set'
' ID = :ID,'
' ID_COMPANY = :ID_COMPANY,'
' ADDRESS = :ADDRESS,'
' FAX = :FAX,'
' PHONE = :PHONE,'
' STATE = :STATE,'
' TOWN = :TOWN,'
' ZIP = :ZIP'
'where'
' ID = :OLD_ID')
GeneratorField.Field = 'ID'
GeneratorField.Generator = 'G_MASTER'
DataSource = dsCompanies
Left = 48
Top = 104
object DataLocationsID: TIntegerField
FieldName = 'ID'
Required = True
end
object DataLocationsID_COMPANY: TIntegerField
FieldName = 'ID_COMPANY'
Required = True
end
object DataLocationsADDRESS: TIBStringField
FieldName = 'ADDRESS'
Size = 40
end
object DataLocationsFAX: TIBStringField
FieldName = 'FAX'
Size = 15
end
object DataLocationsPHONE: TIBStringField
FieldName = 'PHONE'
Size = 15
end
object DataLocationsSTATE: TIBStringField
FieldName = 'STATE'
Size = 4
end
object DataLocationsTOWN: TIBStringField
FieldName = 'TOWN'
Size = 30
end
object DataLocationsZIP: TIBStringField
FieldName = 'ZIP'
Size = 10
end
end
object DataPeople: TIBDataSet
Database = DmMain.IBDatabase1
Transaction = IBTransaction1
AfterInsert = DataPeopleAfterInsert
BufferChunks = 1000
CachedUpdates = False
DeleteSQL.Strings = (
'delete from PEOPLE'
'where'
' ID = :OLD_ID')
InsertSQL.Strings = (
'insert into PEOPLE'
' (ID, ID_COMPANY, ID_LOCATION, KEY_CONTACT, NAME, EMAIL, FAX, P' +
'HONE)'
'values'
' (:ID, :ID_COMPANY, :ID_LOCATION, :KEY_CONTACT, :NAME, :EMAIL, ' +
':FAX, :PHONE)')
RefreshSQL.Strings = (
'Select '
' ID,'
' ID_COMPANY,'
' ID_LOCATION,'
' NAME,'
' PHONE,'
' FAX,'
' EMAIL,'
' KEY_CONTACT'
'from PEOPLE '
'where'
' ID = :ID')
SelectSQL.Strings = (
'select ID, ID_COMPANY, ID_LOCATION, KEY_CONTACT, NAME, EMAIL, FA' +
'X, PHONE'
'from PEOPLE'
'where ID_COMPANY = :id')
ModifySQL.Strings = (
'update PEOPLE'
'set'
' ID = :ID,'
' ID_COMPANY = :ID_COMPANY,'
' ID_LOCATION = :ID_LOCATION,'
' KEY_CONTACT = :KEY_CONTACT,'
' NAME = :NAME,'
' EMAIL = :EMAIL,'
' FAX = :FAX,'
' PHONE = :PHONE'
'where'
' ID = :OLD_ID')
GeneratorField.Field = 'ID'
GeneratorField.Generator = 'G_MASTER'
DataSource = dsCompanies
Left = 48
Top = 168
object DataPeopleID: TIntegerField
FieldName = 'ID'
Required = True
end
object DataPeopleID_COMPANY: TIntegerField
FieldName = 'ID_COMPANY'
Required = True
end
object DataPeopleID_LOCATION: TIntegerField
FieldName = 'ID_LOCATION'
Required = True
end
object DataPeopleKEY_CONTACT: TIBStringField
FieldName = 'KEY_CONTACT'
Required = True
Size = 1
end
object DataPeopleNAME: TIBStringField
FieldName = 'NAME'
Required = True
Size = 50
end
object DataPeopleEMAIL: TIBStringField
FieldName = 'EMAIL'
Size = 50
end
object DataPeopleFAX: TIBStringField
FieldName = 'FAX'
Size = 15
end
object DataPeoplePHONE: TIBStringField
FieldName = 'PHONE'
Size = 15
end
end
object dsCompanies: TDataSource
DataSet = DataCompanies
Left = 120
Top = 40
end
object IBTransaction1: TIBTransaction
Active = False
DefaultDatabase = DmMain.IBDatabase1
Params.Strings = (
'read_committed'
'rec_version'
'nowait')
AutoStopAction = saNone
Left = 120
Top = 104
end
end
|
unit ZMHash19;
(*
ZMHash19.pas - Hash list for entries
Copyright (C) 2009, 2010 by Russell J. Peters, Roger Aelbrecht,
Eric W. Engler and Chris Vleghert.
This file is part of TZipMaster Version 1.9.
TZipMaster is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
TZipMaster is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with TZipMaster. If not, see <http://www.gnu.org/licenses/>.
contact: problems@delphizip.org (include ZipMaster in the subject).
updates: http://www.delphizip.org
DelphiZip maillist subscribe at http://www.freelists.org/list/delphizip
modified 2009-04-21
---------------------------------------------------------------------------*)
interface
uses
ZipMstr19, ZMIRec19, ZMCore19;
const
HDEBlockEntries = 511; // number of entries per block
type
PHashedDirEntry = ^THashedDirEntry;
THashedDirEntry = record
Next: PHashedDirEntry;
ZRec: TZMIRec;
end;
// for speed and efficiency allocate blocks of entries
PHDEBlock = ^THDEBlock;
THDEBlock = packed record
Entries: array [0..(HDEBlockEntries -1)] of THashedDirEntry;
Next: PHDEBlock;
end;
TZMDirHashList = class(TObject)
private
fLastBlock: PHDEBlock;
fNextEntry: Cardinal;
{$IFNDEF UNICODE}
FWorker: TZMCore;
{$ENDIF}
function GetEmpty: boolean;
function GetSize: Cardinal;
procedure SetEmpty(const Value: boolean);
procedure SetSize(const Value: Cardinal);
protected
Chains: array of PHashedDirEntry;
fBlocks: Integer;
//1 chain of removed nodes
fEmpties: PHashedDirEntry;
procedure DisposeBlocks;
function GetEntry: PHashedDirEntry;
function Same(Entry: PHashedDirEntry; Hash: Cardinal; const Str: String):
Boolean;
public
function Add(const Rec: TZMIRec): TZMIRec;
procedure AfterConstruction; override;
procedure AutoSize(Req: Cardinal);
procedure BeforeDestruction; override;
procedure Clear;
function Find(const FileName: String): TZMIRec;
//1 return true if removed
function Remove(const ZDir: TZMIRec): boolean;
property Empty: boolean read GetEmpty write SetEmpty;
property Size: Cardinal read GetSize write SetSize;
{$IFNDEF UNICODE}
property Worker: TZMCore read FWorker write FWorker;
{$ENDIF}
end;
implementation
uses
SysUtils, Windows, ZMMatch19;
const
ChainsMax = 65537;
ChainsMin = 61;
CapacityMin = 64;
function TZMDirHashList.Add(const Rec: TZMIRec): TZMIRec;
var
Entry: PHashedDirEntry;
Hash: Cardinal;
Idx: Integer;
Parent: PHashedDirEntry;
S: String;
begin
Assert(Rec <> nil, 'nil ZipDirEntry');
if Chains = nil then
Size := 1283;
Result := nil;
S := Rec.FileName;
Hash := Rec.Hash;
Idx := Hash mod Cardinal(Length(Chains));
Entry := Chains[Idx];
if Entry = nil then
begin
Entry := GetEntry;
Entry.ZRec := Rec;
Entry.Next := nil;
Chains[Idx] := Entry;
end
else
begin
repeat
if Same(Entry, Hash, S) then
begin
Result := Entry.ZRec; // duplicate name
exit;
end;
Parent := Entry;
Entry := Entry.Next;
if Entry = nil then
begin
Entry := GetEntry;
Entry.ZRec := nil;
Parent.Next := Entry;
end;
until (Entry.ZRec = nil);
// we have an entry so fill in the details
Entry.ZRec := Rec;
Entry.Next := nil;
end;
end;
procedure TZMDirHashList.AfterConstruction;
begin
inherited;
fBlocks := 0;
fLastBlock := nil;
fEmpties := nil;
fNextEntry := HIGH(Cardinal);
end;
// set size to a reasonable prime number
procedure TZMDirHashList.AutoSize(Req: Cardinal);
const
PrimeSizes: array[0..29] of Cardinal =
(61, 131, 257, 389, 521, 641, 769, 1031, 1283, 1543, 2053, 2579, 3593,
4099, 5147, 6151, 7177, 8209, 10243, 12289, 14341, 16411, 18433, 20483,
22521, 24593, 28687, 32771, 40961, 65537);
var
i: Integer;
begin
if Req < 12000 then
begin
// use next higher size
for i := 0 to HIGH(PrimeSizes) do
if PrimeSizes[i] >= Req then
begin
Req := PrimeSizes[i];
break;
end;
end
else
begin
// use highest smaller size
for i := HIGH(PrimeSizes) downto 0 do
if PrimeSizes[i] < Req then
begin
Req := PrimeSizes[i];
break;
end;
end;
SetSize(Req);
end;
procedure TZMDirHashList.BeforeDestruction;
begin
Clear;
inherited;
end;
procedure TZMDirHashList.Clear;
begin
DisposeBlocks;
Chains := nil; // empty it
end;
procedure TZMDirHashList.DisposeBlocks;
var
TmpBlock: PHDEBlock;
begin
while fLastBlock <> nil do
begin
TmpBlock := fLastBlock;
fLastBlock := TmpBlock^.Next;
Dispose(TmpBlock);
end;
fBlocks := 0;
fLastBlock := nil;
fEmpties := nil;
fNextEntry := HIGH(Cardinal);
end;
function TZMDirHashList.Find(const FileName: String): TZMIRec;
var
Entry: PHashedDirEntry;
Hash: Cardinal;
idx: Cardinal;
begin
Result := nil;
if Chains = nil then
exit;
Hash := HashFunc(FileName);
idx := Hash mod Cardinal(Length(Chains));
Entry := Chains[idx];
// check entries in this chain
while Entry <> nil do
begin
if Same(Entry, Hash, FileName) then
begin
Result := Entry.ZRec;
break;
end
else
Entry := Entry.Next;
end;
end;
function TZMDirHashList.GetEmpty: boolean;
begin
Result := Chains = nil;
end;
// return address in allocated block
function TZMDirHashList.GetEntry: PHashedDirEntry;
var
TmpBlock: PHDEBlock;
begin
if fEmpties <> nil then
begin
Result := fEmpties; // last emptied
fEmpties := fEmpties.Next;
end
else
begin
if (fBlocks < 1) or (fNextEntry >= HDEBlockEntries) then
begin
// we need a new block
New(TmpBlock);
ZeroMemory(TmpBlock, sizeof(THDEBlock));
TmpBlock^.Next := fLastBlock;
fLastBlock := TmpBlock;
Inc(fBlocks);
fNextEntry := 0;
end;
Result := @fLastBlock^.Entries[fNextEntry];
Inc(fNextEntry);
end;
end;
function TZMDirHashList.GetSize: Cardinal;
begin
Result := Length(Chains);
end;
function TZMDirHashList.Remove(const ZDir: TZMIRec): boolean;
var
Entry: PHashedDirEntry;
FileName: String;
Hash: Cardinal;
idx: Cardinal;
Prev: PHashedDirEntry;
begin
Result := false;
if (ZDir = nil) or (Chains = nil) then
exit;
FileName := ZDir.FileName;
Hash := ZDir.Hash;
idx := Hash mod Cardinal(Length(Chains));
Entry := Chains[idx];
Prev := nil;
while Entry <> nil do
begin
if Same(Entry, Hash, FileName) and (Entry.ZRec = ZDir) then
begin
// we found it so unlink it
if Prev = nil then
begin
// first in chain
Chains[idx] := Entry.Next; // link to next
end
else
begin
Prev.Next := Entry.Next; // link to next
end;
Entry.Next := fEmpties; // link to removed
fEmpties := Entry;
Entry.ZRec := nil;
Result := True;
break;
end
else
begin
Prev := Entry;
Entry := Entry.Next;
end;
end;
end;
function TZMDirHashList.Same(Entry: PHashedDirEntry; Hash: Cardinal; const Str:
String): Boolean;
var
IRec: TZMIRec;
begin
IRec := Entry^.ZRec;
Result := (Hash = IRec.Hash) and
{$IFDEF UNICODE}
(FileNameComp(Str, IRec.FileName) = 0);
{$ELSE}
(FileNameComp(Str, IRec.FileName, Worker.UseUTF8) = 0);
{$ENDIF}
end;
procedure TZMDirHashList.SetEmpty(const Value: boolean);
begin
if Value then
Clear;
end;
procedure TZMDirHashList.SetSize(const Value: Cardinal);
var
TableSize: Integer;
begin
Clear;
if Value > 0 then
begin
TableSize := Value;
// keep within reasonable limits
if TableSize < ChainsMin then
TableSize := ChainsMin
else
if TableSize > ChainsMax then
TableSize := ChainsMax;
SetLength(Chains, TableSize);
ZeroMemory(Chains, Size * sizeof(PHashedDirEntry));
end;
end;
end.
|
unit uMsg;
interface
uses Classes,
// Own units
UCommon;
type
TMsg = class(THODObject)
private
FTyping: Boolean;
procedure SetTyping(const Value: Boolean);
function CutChar(cnt: Byte = 1): string;
public
MsgList: TStringList;
//** Конструктор.
constructor Create;
destructor Destroy; override;
procedure Clear;
procedure Add(const S: string);
procedure AddEmpty;
procedure TypeChar(Ch: Char);
procedure Exec;
property Typing: Boolean read FTyping write SetTyping;
end;
const
MsgMin = 4;
MsgMax = 33;
InpChar = '_';
var
Msg: TMsg;
implementation
uses SysUtils, uVars;
{ TMsg }
procedure TMsg.Add(const S: string);
begin
MsgList.Insert(0, S);
end;
procedure TMsg.AddEmpty;
var
i: Byte;
B: Boolean;
begin
B := True;
for i := 0 to MsgMax do
if (MsgList[i] <> '') then
begin
B := False;
Break;
end;
if B then
Clear
else
MsgList.Insert(0, '');
end;
procedure TMsg.Clear;
var
i: Byte;
begin
MsgList.Clear;
for i := 0 to MsgMax do
MsgList.Append('');
end;
constructor TMsg.Create;
begin
MsgList := TStringList.Create;
end;
function TMsg.CutChar(cnt: Byte = 1): string;
begin
Result := Copy(MsgList[0], 1, Length(MsgList[0]) - cnt);
end;
destructor TMsg.Destroy;
begin
MsgList.Free;
inherited;
end;
procedure TMsg.Exec;
type
NCmd = (cFov, cVmap, cSound, cMusic);
const
VMVals: array[NCmd] of string = ('Game.FOV', 'Game.VMap', 'Music.Sound',
'Music.Music');
Cmds: array[NCmd] of string = ('FOV', 'VMap', 'Sound', 'Music');
var
Cmd: string;
Val : integer;
i : NCmd;
begin
FTyping := False;
Cmd := AnsiLowerCase(Trim(CutChar));
for I := Low(ncmd) to high(NCmd) do
if Cmd = AnsiLowerCase(cmds[i]) then
begin
Val := 1 - VM.GetInt(vmvals[i]);
VM.SetInt(vmvals[i], Val); // assume sound is only on(1) or off(0)
MsgList[0] := Format('%s %s %d', [cmds[i], 'set to', Val]);
exit;
end;
if vm.IsVar(cmd) then
begin
MsgList[0] := Format('%s = %s', [cmd, vm.GetStr(cmd)]);
exit;
end;
MsgList[0] := CutChar;
if Trim(MsgList[0]) = '' then
MsgList.Delete(0);
end;
procedure TMsg.SetTyping(const Value: Boolean);
begin
if Value = FTyping then
Exit;
FTyping := Value;
if Value then
MsgList.Insert(0, InpChar)
else
MsgList.Delete(0);
end;
procedure TMsg.TypeChar(Ch: Char);
begin
case Ch of
' '..'~': MsgList[0] := CutChar + Ch + InpChar;
#13: Exec; // enter
#8: MsgList[0] := CutChar(2) + InpChar; // backspace
end;
end;
initialization
Msg := TMsg.Create;
Msg.Clear;
finalization
Msg.Free;
end.
|
unit TestStepParams;
interface
uses
TestFramework, StepParamIntf, StepParams, StepParamsIntf, TestBaseClasses;
type
TestTStepParams = class(TParseContext)
strict private
FStepParams: IStepParams;
FParam: Variant;
public
procedure SetUp; override;
procedure TearDown; override;
procedure RaiseExceptionIfParamTypeIsInvalid;
procedure RaiseExceptionIfTrySetInvalidParamType;
published
procedure ShouldAddSomeStepParams;
procedure ShouldGetStepParamByName;
procedure ShouldGetAndSetStepParamByName;
procedure ShouldGetAndSetStepParamByIndex;
procedure ShouldRaiseExceptionIfParamNotIsStringOrInteger;
procedure ShouldRaiseExceptionIfTrySetInvalidParamType;
procedure ShouldClearParams;
end;
implementation
uses
StepParam, Dialogs, dSpecUtils, Rtti, TypInfo, Variants, DB;
procedure TestTStepParams.RaiseExceptionIfParamTypeIsInvalid;
var
LParam: IStepParam;
begin
LParam := FStepParams[FParam];
end;
procedure TestTStepParams.RaiseExceptionIfTrySetInvalidParamType;
var
LParam: IStepParam;
begin
LParam := TStepParam.Create;
LParam.Name := 'Name';
LParam.Value := 'Name';
FStepParams[FParam] := LParam;
end;
procedure TestTStepParams.SetUp;
begin
FStepParams := TStepParams.Create;
end;
procedure TestTStepParams.TearDown;
begin
FParam := null;
FStepParams := nil;
end;
procedure TestTStepParams.ShouldAddSomeStepParams;
begin
Specify.That(FStepParams.Add('New param')).Should.Not_.Be.Nil_;
Specify.That(FStepParams['New param']).Should.Not_.Be.Nil_;
end;
procedure TestTStepParams.ShouldClearParams;
begin
FStepParams.Add('Test Param');
FStepParams.Clear;
Specify.That(FStepParams['Test Param']).Should.Be.Nil_;
end;
procedure TestTStepParams.ShouldGetAndSetStepParamByIndex;
var
LParam: IStepParam;
begin
LParam := TStepParam.Create;
LParam.Name := 'Name';
LParam.Value := 'Name';
FStepParams[0] := LParam;
Specify.That(FStepParams[0]).Should.Be.Assigned;
Specify.That(FStepParams[0].Name).Should.Equal(LParam.Name);
end;
procedure TestTStepParams.ShouldGetAndSetStepParamByName;
var
LParam: IStepParam;
begin
LParam := TStepParam.Create;
LParam.Name := 'Name';
LParam.Value := 'Name';
FStepParams['Name'] := LParam;
Specify.That(FStepParams['Name']).Should.Be.Assigned;
Specify.That(FStepParams['Name'].Name).Should.Equal(LParam.Name);
end;
procedure TestTStepParams.ShouldGetStepParamByName;
begin
FStepParams.Add('New param');
Specify.That(FStepParams.ByName('New param')).Should.Not_.Be.Nil_;
Specify.That(FStepParams.ByName('New param')).Should.Support(IStepParam);
Specify.That(FStepParams.ByName('New param').Name).Should.Equal('New param');
end;
procedure TestTStepParams.ShouldRaiseExceptionIfParamNotIsStringOrInteger;
begin
FParam := 1.89;
CheckException(RaiseExceptionIfParamTypeIsInvalid, EInvalidParamType);
end;
procedure TestTStepParams.ShouldRaiseExceptionIfTrySetInvalidParamType;
begin
FParam := 1.89;
CheckException(RaiseExceptionIfTrySetInvalidParamType, EInvalidParamType);
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestTStepParams.Suite);
end.
|
unit ExtAIMsgActions;
interface
uses
Classes, SysUtils,
ExtAICommonClasses, ExtAISharedNetworkTypes, ExtAISharedInterface;
// Packing and unpacking of Actions in the message
type
TExtAIMsgActions = class
private
// Main variables
fStream: TKExtAIMsgStream;
// Triggers
fOnSendAction : TExtAIEventNewMsg;
fOnGroupOrderAttackUnit : TGroupOrderAttackUnit;
fOnGroupOrderWalk : TGroupOrderWalk;
fOnLog : TLog;
// Send Actions
procedure InitMsg(aTypeAction: TExtAIMsgTypeAction);
procedure FinishMsg();
procedure SendAction();
// Unpack Actions
procedure GroupOrderAttackUnitR();
procedure GroupOrderWalkR();
procedure LogR();
// Others
procedure NillEvents();
public
constructor Create();
destructor Destroy(); override;
// Connection to callbacks
property OnSendAction : TExtAIEventNewMsg write fOnSendAction;
property OnGroupOrderAttackUnit : TGroupOrderAttackUnit write fOnGroupOrderAttackUnit;
property OnGroupOrderWalk : TGroupOrderWalk write fOnGroupOrderWalk;
property OnLog : TLog write fOnLog;
// Pack actions
procedure GroupOrderAttackUnitW(aGroupID, aUnitID: Integer);
procedure GroupOrderWalkW(aGroupID, aX, aY, aDir: Integer);
procedure LogW(aLog: UnicodeString);
procedure ReceiveAction(aData: Pointer; aActionType, aLength: Cardinal);
end;
implementation
uses
ExtAILog;
{ TExtAIMsgActions }
constructor TExtAIMsgActions.Create();
begin
Inherited Create;
fStream := TKExtAIMsgStream.Create();
fStream.Clear;
NillEvents();
end;
destructor TExtAIMsgActions.Destroy();
begin
NillEvents();
fStream.Free;
Inherited;
end;
procedure TExtAIMsgActions.NillEvents();
begin
fOnGroupOrderAttackUnit := nil;
fOnGroupOrderWalk := nil;
fOnLog := nil;
end;
procedure TExtAIMsgActions.InitMsg(aTypeAction: TExtAIMsgTypeAction);
begin
// Clear stream and create head with predefined 0 length
fStream.Clear;
fStream.WriteMsgType(mkAction, Cardinal(aTypeAction), TExtAIMsgLengthData(0));
end;
procedure TExtAIMsgActions.FinishMsg();
var
MsgLenght: TExtAIMsgLengthData;
begin
// Replace 0 length with correct number
MsgLenght := fStream.Size - SizeOf(TExtAIMsgKind) - SizeOf(TExtAIMsgTypeAction) - SizeOf(TExtAIMsgLengthData);
fStream.Position := SizeOf(TExtAIMsgKind) + SizeOf(TExtAIMsgTypeAction);
fStream.Write(MsgLenght, SizeOf(MsgLenght));
// Send Action
SendAction();
end;
procedure TExtAIMsgActions.SendAction();
begin
// Send message
if Assigned(fOnSendAction) then
fOnSendAction(fStream.Memory, fStream.Size);
end;
procedure TExtAIMsgActions.ReceiveAction(aData: Pointer; aActionType, aLength: Cardinal);
begin
fStream.Clear();
fStream.Write(aData^, aLength);
fStream.Position := 0;
case TExtAIMsgTypeAction(aActionType) of
taGroupOrderAttackUnit: GroupOrderAttackUnitR();
taGroupOrderWalk: GroupOrderWalkR();
taLog: LogR();
else begin end;
end;
end;
// Actions
procedure TExtAIMsgActions.GroupOrderAttackUnitW(aGroupID, aUnitID: Integer);
begin
InitMsg(taGroupOrderAttackUnit);
fStream.Write(aGroupID);
fStream.Write(aUnitID);
FinishMsg();
end;
procedure TExtAIMsgActions.GroupOrderAttackUnitR();
var
GroupID, UnitID: Integer;
begin
fStream.Read(GroupID);
fStream.Read(UnitID);
if Assigned(fOnGroupOrderAttackUnit) then
fOnGroupOrderAttackUnit(GroupID, UnitID);
end;
procedure TExtAIMsgActions.GroupOrderWalkW(aGroupID, aX, aY, aDir: Integer);
begin
InitMsg(taGroupOrderWalk);
fStream.Write(aGroupID);
fStream.Write(aX);
fStream.Write(aY);
fStream.Write(aDir);
FinishMsg();
end;
procedure TExtAIMsgActions.GroupOrderWalkR();
var
GroupID, X, Y, Dir: Integer;
begin
fStream.Read(GroupID);
fStream.Read(X);
fStream.Read(Y);
fStream.Read(Dir);
if Assigned(fOnGroupOrderWalk) then
fOnGroupOrderWalk(GroupID, X, Y, Dir);
end;
procedure TExtAIMsgActions.LogW(aLog: UnicodeString);
begin
InitMsg(taLog);
fStream.WriteW(aLog);
FinishMsg();
end;
procedure TExtAIMsgActions.LogR();
var
Txt: UnicodeString;
begin
fStream.ReadW(Txt);
if Assigned(fOnLog) then
fOnLog(Txt);
end;
end.
|
unit ExtractorComment;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TCommentForm = class(TForm)
DescMemo: TMemo;
OkBtn: TButton;
CancelBtn: TButton;
procedure FormResize(Sender: TObject);
public
function ShowCommentModal(Comment: string): boolean;
end;
var
CommentForm: TCommentForm;
implementation
uses
SFXBehavior;
{$R *.dfm}
procedure TCommentForm.FormResize(Sender: TObject);
begin
DescMemo.Width := ClientWidth - 2 * DescMemo.Left;
DescMemo.Height := ClientHeight - 3 * DescMemo.Top - OkBtn.Height;
CancelBtn.Top := 2 * DescMemo.Top + DescMemo.Height;
OkBtn.Top := CancelBtn.Top;
OkBtn.Left := ClientWidth - OkBtn.Width - CancelBtn.Left;
end;
function TCommentForm.ShowCommentModal(Comment: string): boolean;
begin
DescMemo.Text := TrimRight(StripBehavior(Comment));
result := ShowModal() = mrOk;
end;
end.
|
unit TaskBarMenu;
interface
uses
SysUtils, Classes, Menus, Messages, Windows, Forms, Controls;
type
TTaskBarMenu = class(TPopupMenu)
private
hookHandle : THandle;
oldWndProc: Pointer;
newWndProc: Pointer;
protected
procedure Hook;
procedure UnHook;
procedure AppWndProc(var Msg: TMessage);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
end;
procedure Register;
implementation
const
WM_TASKBAR_MENU = $0313; // magic!
WM_POPUP_MENU = WM_USER + 1; //custom message
var
thisOnce : TTaskBarMenu = nil;
procedure Register;
begin
RegisterComponents('FFSNew', [TTaskBarMenu]);
end;
{ TTaskBarMenu }
procedure TTaskBarMenu.AppWndProc(var Msg: TMessage);
begin
case Msg.Msg of
WM_TASKBAR_MENU: PostMessage(hookHandle, WM_POPUP_MENU, 0, 0);
WM_POPUP_MENU: Popup(Mouse.CursorPos.X, Mouse.CursorPos.Y);
else
Msg.Result := CallWindowProc(oldWndProc, hookHandle, Msg.Msg, Msg.wParam, Msg.lParam);
end;
end; (*AppWndProc*)
constructor TTaskBarMenu.Create(AOwner: TComponent);
begin
if Assigned(thisOnce) then
begin
raise Exception.Create('Only one instance of this component can be used per application!');
end
else
begin
inherited;
thisOnce := self;
hookHandle := Application.Handle;
Hook;
end;
end; (*Create*)
destructor TTaskBarMenu.Destroy;
begin
thisOnce := nil;
UnHook;
inherited;
end; (*Destroy*)
procedure TTaskBarMenu.Hook;
begin
oldWndProc := Pointer(GetWindowLong(hookHandle, GWL_WNDPROC));
newWndProc := MakeObjectInstance(AppWndProc);
if not (csDesigning in ComponentState) then SetWindowLong(hookHandle, GWL_WNDPROC, longint(newWndProc));
end; (*Hook*)
procedure TTaskBarMenu.UnHook;
begin
SetWindowLong(hookHandle, GWL_WNDPROC, longint(oldWndProc));
if Assigned(newWndProc) then FreeObjectInstance(newWndProc);
NewWndProc := nil;
end; (*UnHook*)
end.
|
unit Model.PlanilhaEntradasSPLOG;
interface
uses Generics.Collections;
type
TPlanilhaEntradaSPLOG = class
private
FCodigoUltimaOcorrencia: String;
FICMSTransporte: String;
FFreteValor: String;
FPesoCalculado: String;
FPares: String;
FPlacaColeta: String;
FNumeroFatura: String;
FEmissaoUltimoRomaneio: String;
FTipoCalculo: String;
FValorCalculado: String;
FUFDestino: String;
FDespacho: String;
FAtraso: String;
FCNPJPagador: String;
FCTRC: String;
FLocalizacaoAtual: String;
FEmissaoFatura: String;
FReembolso: String;
FValor: String;
FValorCTRCOrigem: String;
FColeta: String;
FEnderecoEntrega: String;
FCNPJDestinatario: String;
FHora: STring;
FPedido: String;
FM3Cubadora: String;
FCapaRemessa: String;
FDataPrevisaoEntrega: String;
FResultadoComercial: String;
FPrococoloCTe: String;
FUsaCubadora: String;
FRecebidoPor: String;
FDataInclusaoUltimaOcorrencia: String;
FImpostoCliente: String;
FLocalEntrega: String;
FValorICMSOrigem: String;
FTipoUltimaPendencia: String;
FDACTE: String;
FPesoCubado: String;
FDistanciaKM: String;
FTipoDocumento: String;
FM3NF: String;
FDataUltimaPendencia: String;
FPraca: String;
FDataEntregaRealizada: String;
FTipoMercadoria: String;
FNomeRemetente: String;
FUltimoRomaneio: String;
FSerieCTRCOrigem: String;
FVolumes: String;
FNF: String;
FCidadeRemetente: String;
FCAT: String;
FSEGM2: String;
FDataAutorizacao: String;
FCFOP: String;
FPedagio: String;
FPesoNF: String;
FNumeroCTRCOrigem: String;
FTabelaCalculo: String;
FTRT: String;
FFreteFOBCTRCOrigem: String;
FValorFreteComissao: String;
FOutros: String;
FSuframa: String;
FSEGM1: String;
FCNPJTRemetente: String;
FValorBaixa: String;
FCTe: String;
FPacoteArquivo: String;
FTipoFreteOrigem: String;
FTDA: String;
FAdicionalFrete: String;
FTEmissao: String;
FEmissaoCTRCOrigem: String;
FUltimaOcorrencia: String;
FCidadeDestino: String;
FSituacao: String;
FValorMercadoria: String;
FImpostos: String;
FITR: String;
FEspecieMercadoria: String;
FNumeroDocumentoRecebedor: String;
FPesoReal: String;
FTipoFrete: String;
FPesoBalanca: String;
FDescricaoUltimaPendencia: String;
FTDE: String;
FCEPEntrega: String;
FSEGM: String;
FM3Conferente: String;
FCodigoUltimaPendencia: String;
FPlaca: String;
FOBS2: String;
FLogin: String;
FControle: String;
FOBS3: String;
FDiferenciada: String;
FUFRemetente: String;
FAliquotaICMS: String;
FDemaisNotasFiscais: String;
FDataEntregaAgendada: String;
FNomePagador: String;
FOBS1: String;
FICMSST: String;
FGRIS: String;
FTAR: String;
FFretePeso: String;
FM3: String;
FNomeDestinatario: String;
FVencimentoFatura: String;
FDevCanhotoNF: String;
FTAS: String;
FEmissao: String;
FDANFE: String;
public
property TipoFrete : String read FTipoFrete write FTipoFrete;
property CTRC : String read FCTRC write FCTRC;
property CTe: String read FCTe write FCTe;
property DACTE: String read FDACTE write FDACTE;
property PrococoloCTe: String read FPrococoloCTe write FPrococoloCTe;
property DataAutorizacao: String read FDataAutorizacao write FDataAutorizacao;
property Situacao: String read FSituacao write FSituacao;
property TipoDocumento: String read FTipoDocumento write FTipoDocumento;
property Controle: String read FControle write FControle;
property PlacaColeta: String read FPlacaColeta write FPlacaColeta;
property Emissao: String read FEmissao write FEmissao;
property Hora: STring read FHora write FHora;
property Login: String read FLogin write FLogin;
property CNPJTRemetente: String read FCNPJTRemetente write FCNPJTRemetente;
property SEGM: String read FSEGM write FSEGM;
property NomeRemetente: String read FNomeRemetente write FNomeRemetente;
property CidadeRemetente: String read FCidadeRemetente write FCidadeRemetente;
property UFRemetente: String read FUFRemetente write FUFRemetente;
property CNPJDestinatario: String read FCNPJDestinatario write FCNPJDestinatario;
property SEGM1: String read FSEGM1 write FSEGM1;
property NomeDestinatario: String read FNomeDestinatario write FNomeDestinatario;
property Praca: String read FPraca write FPraca;
property Diferenciada: String read FDiferenciada write FDiferenciada;
property CidadeDestino: String read FCidadeDestino write FCidadeDestino;
property UFDestino: String read FUFDestino write FUFDestino;
property LocalEntrega: String read FLocalEntrega write FLocalEntrega;
property EnderecoEntrega: String read FEnderecoEntrega write FEnderecoEntrega;
property CidadeEntrega: String read FValor write FValor;
property CEPEntrega: String read FCEPEntrega write FCEPEntrega;
property DistanciaKM: String read FDistanciaKM write FDistanciaKM;
property CNPJPagador: String read FCNPJPagador write FCNPJPagador;
property SEGM2: String read FSEGM2 write FSEGM2;
property NomePagador: String read FNomePagador write FNomePagador;
property TipoMercadoria: String read FTipoMercadoria write FTipoMercadoria;
property EspecieMercadoria: String read FEspecieMercadoria write FEspecieMercadoria;
property NF: String read FNF write FNF;
property Volumes: String read FVolumes write FVolumes;
property Pares: String read FPares write FPares;
property PesoReal: String read FPesoReal write FPesoReal;
property M3: String read FM3 write FM3;
property PesoCubado: String read FPesoCubado write FPesoCubado;
property PesoCalculado: String read FPesoCalculado write FPesoCalculado;
property FretePeso: String read FFretePeso write FFretePeso;
property FreteValor: String read FFreteValor write FFreteValor;
property Despacho: String read FDespacho write FDespacho;
property CAT: String read FCAT write FCAT;
property ITR: String read FITR write FITR;
property GRIS: String read FGRIS write FGRIS;
property Coleta: String read FColeta write FColeta;
property TDE: String read FTDE write FTDE;
property Pedagio: String read FPedagio write FPedagio;
property Suframa: String read FSuframa write FSuframa;
property Outros: String read FOutros write FOutros;
property Impostos: String read FImpostos write FImpostos;
property TAS: String read FTAS write FTAS;
property Reembolso: String read FReembolso write FReembolso;
property ImpostoCliente: String read FImpostoCliente write FImpostoCliente;
property DevCanhotoNF: String read FDevCanhotoNF write FDevCanhotoNF;
property TRT: String read FTRT write FTRT;
property AdicionalFrete: String read FAdicionalFrete write FAdicionalFrete;
property TDA: String read FTDA write FTDA;
property TAR: String read FTAR write FTAR;
property ValorCalculado: String read FValorCalculado write FValorCalculado;
property ValorFreteComissao: String read FValorFreteComissao write FValorFreteComissao;
property TipoCalculo: String read FTipoCalculo write FTipoCalculo;
property TabelaCalculo: String read FTabelaCalculo write FTabelaCalculo;
property ResultadoComercial: String read FResultadoComercial write FResultadoComercial;
property ValorBaixa: String read FValorBaixa write FValorBaixa;
property NumeroFatura: String read FNumeroFatura write FNumeroFatura;
property EmissaoFatura: String read FEmissaoFatura write FEmissaoFatura;
property VencimentoFatura: String read FVencimentoFatura write FVencimentoFatura;
property ICMSTransporte: String read FICMSTransporte write FICMSTransporte;
property ICMSST: String read FICMSST write FICMSST;
property ValorMercadoria: String read FValorMercadoria write FValorMercadoria;
property CodigoUltimaPendencia: String read FCodigoUltimaPendencia write FCodigoUltimaPendencia;
property DataUltimaPendencia: String read FDataUltimaPendencia write FDataUltimaPendencia;
property DescricaoUltimaPendencia: String read FDescricaoUltimaPendencia write FDescricaoUltimaPendencia;
property TipoUltimaPendencia: String read FTipoUltimaPendencia write FTipoUltimaPendencia;
property CodigoUltimaOcorrencia: String read FCodigoUltimaOcorrencia write FCodigoUltimaOcorrencia;
property DataInclusaoUltimaOcorrencia: String read FDataInclusaoUltimaOcorrencia write FDataInclusaoUltimaOcorrencia;
property UltimaOcorrencia: String read FUltimaOcorrencia write FUltimaOcorrencia;
property DataPrevisaoEntrega: String read FDataPrevisaoEntrega write FDataPrevisaoEntrega;
property DataEntregaAgendada: String read FDataEntregaAgendada write FDataEntregaAgendada;
property DataEntregaRealizada: String read FDataEntregaRealizada write FDataEntregaRealizada;
property Atraso: String read FAtraso write FAtraso;
property RecebidoPor: String read FRecebidoPor write FRecebidoPor;
property NumeroDocumentoRecebedor: String read FNumeroDocumentoRecebedor write FNumeroDocumentoRecebedor;
property SerieCTRCOrigem: String read FSerieCTRCOrigem write FSerieCTRCOrigem;
property NumeroCTRCOrigem: String read FNumeroCTRCOrigem write FNumeroCTRCOrigem;
property EmissaoCTRCOrigem: String read FEmissaoCTRCOrigem write FEmissaoCTRCOrigem;
property ValorCTRCOrigem: String read FValorCTRCOrigem write FValorCTRCOrigem;
property FreteFOBCTRCOrigem: String read FFreteFOBCTRCOrigem write FFreteFOBCTRCOrigem;
property TipoFreteOrigem: String read FTipoFreteOrigem write FTipoFreteOrigem;
property ValorICMSOrigem: String read FValorICMSOrigem write FValorICMSOrigem;
property DemaisNotasFiscais: String read FDemaisNotasFiscais write FDemaisNotasFiscais;
property OBS1: String read FOBS1 write FOBS1;
property OBS2: String read FOBS2 write FOBS2;
property OBS3: String read FOBS3 write FOBS3;
property PacoteArquivo: String read FPacoteArquivo write FPacoteArquivo;
property CapaRemessa: String read FCapaRemessa write FCapaRemessa;
property LocalizacaoAtual: String read FLocalizacaoAtual write FLocalizacaoAtual;
property UltimoRomaneio: String read FUltimoRomaneio write FUltimoRomaneio;
property EmissaoUltimoRomaneio: String read FEmissaoUltimoRomaneio write FEmissaoUltimoRomaneio;
property Placa: String read FPlaca write FPlaca;
property PesoNF: String read FPesoNF write FPEsoNF;
property PesoBalanca: String read FPesoBalanca write FPesoBalanca;
property M3NF: String read FM3NF write FM3NF;
property M3Cubadora: String read FM3Cubadora write FM3Cubadora;
property M3Conferente: String read FM3Conferente write FM3Conferente;
property UsaCubadora: String read FUsaCubadora write FUsaCubadora;
property Pedido: String read FPedido write FPedido;
property CFOP: String read FCFOP write FCFOP;
property AliquotaICMS: String read FAliquotaICMS write FAliquotaICMS;
property DANFE: String read FDANFE write FDANFE;
function GetPlanilha(sFile: String): TObjectList<TPlanilhaEntradaSPLOG>;
end;
implementation
{ TPlanilhaEntradaEntregas }
uses DAO.PlanilhaEntradaSPLOG;
function TPlanilhaEntradaSPLOG.GetPlanilha(sFile: String): TObjectList<TPlanilhaEntradaSPLOG>;
var
planilha : TPlanilhaEntradaSPLOGDAO;
begin
try
planilha := TPlanilhaEntradaSPLOGDAO.Create;
Result := planilha.GetPlanilha(sFile);
finally
planilha.Free;
end;
end;
end.
|
object fmProcedureListOptions: TfmProcedureListOptions
Left = 410
Top = 219
BorderIcons = [biSystemMenu]
BorderStyle = bsDialog
Caption = 'Procedure List Configuration'
ClientHeight = 196
ClientWidth = 526
Color = clBtnFace
Font.Charset = ANSI_CHARSET
Font.Color = clWindowText
Font.Height = -12
Font.Name = 'Tahoma'
Font.Style = []
OldCreateOrder = False
Position = poScreenCenter
Scaled = False
OnShow = FormShow
DesignSize = (
526
196)
PixelsPerInch = 96
TextHeight = 14
object btnOK: TButton
Left = 350
Top = 159
Width = 75
Height = 26
Anchors = [akRight, akBottom]
Caption = 'OK'
Default = True
ModalResult = 1
TabOrder = 2
OnClick = btnOKClick
end
object btnCancel: TButton
Left = 437
Top = 159
Width = 75
Height = 26
Anchors = [akRight, akBottom]
Cancel = True
Caption = 'Cancel'
ModalResult = 2
TabOrder = 3
end
object gbCodeView: TGroupBox
Left = 288
Top = 9
Width = 225
Height = 140
Anchors = [akTop, akRight]
Caption = 'Code View'
TabOrder = 1
object lblDock: TLabel
Left = 16
Top = 50
Width = 27
Height = 14
Caption = 'Dock'
FocusControl = cbCVDock
end
object cbCVDock: TComboBox
Left = 64
Top = 46
Width = 145
Height = 22
Style = csDropDownList
ItemHeight = 14
TabOrder = 1
OnChange = cbCVDockChange
Items.Strings = (
'Top'
'Left'
'Right'
'Bottom')
end
object pnlCVFont: TPanel
Left = 16
Top = 78
Width = 105
Height = 41
Caption = 'AaBbYyZz'
TabOrder = 2
end
object btnChangeCodeViewFont: TButton
Left = 130
Top = 86
Width = 85
Height = 25
Caption = 'Change Font'
TabOrder = 3
OnClick = btnChangeCodeViewFontClick
end
object chkShowCodeView: TCheckBox
Left = 16
Top = 22
Width = 113
Height = 17
Caption = 'Show code view'
TabOrder = 0
end
end
object gbDialog: TGroupBox
Left = 12
Top = 9
Width = 265
Height = 140
Anchors = [akLeft, akTop, akRight]
Caption = 'Procedure List'
TabOrder = 0
object pnlDialogFont: TPanel
Left = 16
Top = 88
Width = 105
Height = 41
Caption = 'AaBbYyZz'
TabOrder = 3
end
object btnChgDialogFont: TButton
Left = 134
Top = 96
Width = 85
Height = 25
Caption = 'Change Font'
TabOrder = 4
OnClick = btnChgDialogFontClick
end
object chkShowObjectName: TCheckBox
Left = 16
Top = 22
Width = 246
Height = 17
Caption = 'Show object names'
TabOrder = 0
end
object chkMatchAnywhere: TCheckBox
Left = 16
Top = 65
Width = 246
Height = 17
Caption = 'Match anywhere in the name'
TabOrder = 2
end
object chkMatchClass: TCheckBox
Left = 16
Top = 43
Width = 246
Height = 17
Caption = 'Match in both class and method names'
TabOrder = 1
end
end
end
|
unit uDMMSS;
interface
uses
System.SysUtils, System.Classes, FireDAC.Stan.Intf, FireDAC.Stan.Option,
FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def,
FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.VCLUI.Wait,
FireDAC.Phys.ODBCBase, FireDAC.Phys.MSSQL, FireDAC.Comp.UI, Data.DB,
FireDAC.Comp.Client, uConfig, FireDAC.Stan.Param, FireDAC.DatS,
FireDAC.DApt.Intf, FireDAC.DApt, FireDAC.Comp.DataSet;
type
TDMMSS = class(TDataModule)
Conexao: TFDConnection;
FDGUIxWaitCursor1: TFDGUIxWaitCursor;
FDPhysMSSQLDriverLink1: TFDPhysMSSQLDriverLink;
Qry: TFDQuery;
procedure DataModuleCreate(Sender: TObject);
private
{ Private declarations }
procedure CarregarIni();
public
{ Public declarations }
end;
var
DMMSS: TDMMSS;
implementation
{%CLASSGROUP 'Vcl.Controls.TControl'}
{$R *.dfm}
{ TDMMSS }
procedure TDMMSS.CarregarIni;
var
Config: TConfig;
begin
Config := TConfig.Create(tpBanco.banMSS);
try
Config.Carregar();
Conexao.Params.Values['HostName'] := Config.HostName;
Conexao.Params.Values['Port'] := Config.Porta.ToString;
Conexao.Params.Values['DataBase'] := Config.DataBase;
Conexao.Params.Values['Server'] := Config.Servidor;
Conexao.Params.Values['User_Name'] := Config.User_Name;
Conexao.Params.Values['Password'] := Config.Password;
finally
FreeAndNil(Config);
end;
end;
procedure TDMMSS.DataModuleCreate(Sender: TObject);
begin
CarregarIni();
end;
end.
|
unit MFichas.Model.Caixa.Metodos.Suprimento;
interface
uses
System.SysUtils,
System.Bluetooth,
MFichas.Model.Caixa.Interfaces,
MFichas.Model.Entidade.CAIXA,
MFichas.Model.Entidade.CAIXAOPERACOES,
MFichas.Model.Conexao.Interfaces,
MFichas.Model.Conexao.Factory,
MFichas.Controller.Types;
type
TModelCaixaMetodosSuprimento = class(TInterfacedObject, iModelCaixaMetodosSuprimento)
private
[weak]
FParent : iModelCaixa;
FValorSuprimento: Currency;
FOperador : String;
FBluetooth : iModelConexaoBluetooth;
constructor Create(AParent: iModelCaixa);
procedure Imprimir;
procedure Gravar;
procedure LimparEntidade;
public
destructor Destroy; override;
class function New(AParent: iModelCaixa): iModelCaixaMetodosSuprimento;
function SetValorSuprimento(AValue: Currency): iModelCaixaMetodosSuprimento;
function SetOperador(AOperador: String) : iModelCaixaMetodosSuprimento;
function &End : iModelCaixaMetodos;
end;
implementation
{ TModelCaixaMetodosSuprimento }
function TModelCaixaMetodosSuprimento.&End: iModelCaixaMetodos;
begin
//TODO: IMPLEMENTAR METODO DE SUPRIMENTO
Result := FParent.Metodos;
Imprimir;
Gravar;
LimparEntidade;
end;
procedure TModelCaixaMetodosSuprimento.Gravar;
var
LCaixaOperacoes: TCAIXAOPERACOES;
begin
FParent.DAO.Modify(FParent.Entidade);
FParent.Entidade.OPERACOES.Add(TCAIXAOPERACOES.Create);
LCaixaOperacoes := FParent.Entidade.OPERACOES.Last;
LCaixaOperacoes.CAIXA := FParent.Entidade.GUUID;
LCaixaOperacoes.TIPO := Integer(ocSuprimento);
LCaixaOperacoes.VALOR := FValorSuprimento;
LCaixaOperacoes.OPERADOR := FOperador;
FParent.DAO.Update(FParent.Entidade);
end;
procedure TModelCaixaMetodosSuprimento.Imprimir;
var
LSocket: TBluetoothSocket;
begin
FBluetooth.ConectarDispositivo(LSocket);
LSocket.SendData(TEncoding.UTF8.GetBytes(chr(27) + chr(33) + chr(0)));
LSocket.SendData(TEncoding.UTF8.GetBytes(chr(27) + chr(97) + chr(49)));
LSocket.SendData(TEncoding.UTF8.GetBytes('SUPRIMENTO' + chr(10)));
LSocket.SendData(TEncoding.UTF8.GetBytes(chr(27) + chr(97) + chr(49)));
LSocket.SendData(TEncoding.UTF8.GetBytes(chr(27) + chr(33) + chr(1)));
LSocket.SendData(TEncoding.UTF8.GetBytes(chr(27) + chr(97) + chr(49)));
LSocket.SendData(TEncoding.UTF8.GetBytes(DateTimeToStr(Now) + chr(10)));
LSocket.SendData(TEncoding.UTF8.GetBytes(chr(27) + chr(33) + chr(0)));
LSocket.SendData(TEncoding.UTF8.GetBytes(chr(27) + chr(100) + chr(1)));
LSocket.SendData(TEncoding.UTF8.GetBytes('------------------------' + chr(10)));
LSocket.SendData(TEncoding.UTF8.GetBytes(chr(27) + chr(33) + chr(1)));
LSocket.SendData(TEncoding.UTF8.GetBytes('(+)VALOR: ' + FormatCurr('#,##0.00', FValorSuprimento) + chr(10)));
LSocket.SendData(TEncoding.UTF8.GetBytes(chr(27) + chr(33) + chr(0)));
LSocket.SendData(TEncoding.UTF8.GetBytes('------------------------' + chr(10)));
LSocket.SendData(TEncoding.UTF8.GetBytes(chr(10)));
LSocket.SendData(TEncoding.UTF8.GetBytes(chr(10)));
end;
procedure TModelCaixaMetodosSuprimento.LimparEntidade;
begin
FParent.Entidade.OPERACOES.Clear;
end;
constructor TModelCaixaMetodosSuprimento.Create(AParent: iModelCaixa);
begin
FParent := AParent;
FBluetooth := TModelConexaoFactory.New.ConexaoBluetooth;
end;
destructor TModelCaixaMetodosSuprimento.Destroy;
begin
inherited;
end;
class function TModelCaixaMetodosSuprimento.New(AParent: iModelCaixa): iModelCaixaMetodosSuprimento;
begin
Result := Self.Create(AParent);
end;
function TModelCaixaMetodosSuprimento.SetOperador(
AOperador: String): iModelCaixaMetodosSuprimento;
begin
Result := Self;
FOperador := AOperador;
end;
function TModelCaixaMetodosSuprimento.SetValorSuprimento(
AValue: Currency): iModelCaixaMetodosSuprimento;
begin
Result := Self;
if AValue <= 0 then
raise Exception.Create(
'Para fazer um suprimento, insira um valor maior que R$0.'
);
FValorSuprimento := AValue;
end;
end.
|
unit samples;
interface
uses {$IFDEF WINDOWS}windows,{$ENDIF}
dialogs,sysutils,sound_engine,file_engine,main_engine;
const
MAX_SAMPLES=30;
MAX_CHANNELS=6;
type
tipo_nombre_samples=record
nombre:string;
restart,loop:boolean;
end;
tipo_audio=record
long:dword;
playing:boolean;
data:pword;
pos:dword;
restart,loop:boolean;
tsample:byte;
amp:single;
end;
ptipo_audio=^tipo_audio;
tipo_samples=record
num_samples:byte;
audio:array[0..MAX_SAMPLES] of ptipo_audio;
tsample_use:array[0..MAX_CHANNELS] of boolean;
tsample_reserved:array[0..MAX_CHANNELS] of integer;
amp:single;
end;
ptipo_samples=^tipo_samples;
var
data_samples:ptipo_samples;
samples_loaded:boolean;
function convert_wav(source:pbyte;var data:pword;source_long:dword;var long:dword):boolean;
function load_samples(const nombre_samples:array of tipo_nombre_samples;amp:single=1;parent:boolean=false;name:string=''):boolean;
function load_samples_raw(sample_data:pword;longitud:dword;restart,loop:boolean;amp:single=1):boolean;
procedure start_sample(num:byte);
procedure samples_update;
procedure stop_sample(num:byte);
procedure close_samples;
procedure reset_samples;
procedure stop_all_samples;
function sample_status(num:byte):boolean;
procedure change_vol_sample(num_sample:byte;amp:single);
implementation
uses init_games;
type
theader=packed record
magic1:array[0..3] of ansichar;
size:dword;
magic2:array[0..3] of ansichar;
end;
tchunk_info=packed record
name:array[0..3] of ansichar;
size:dword;
end;
tfmt_info=packed record
audio_format:word;
num_channles:word;
sample_rate:dword;
byte_rate:dword;
block_aling:word;
bits_per_sample:word;
end;
function convert_wav(source:pbyte;var data:pword;source_long:dword;var long:dword):boolean;
var
h:integer;
f,longitud:dword;
salir,fmt,datos:boolean;
temp,temp_w:word;
data2:pword;
lsamples_m,lsamples_loop:single;
header:^theader;
chunk:^tchunk_info;
fmt_info:^tfmt_info;
ptemp:pbyte;
begin
convert_wav:=false;
longitud:=0;
ptemp:=source;
getmem(header,sizeof(theader));
copymemory(header,ptemp,12);
inc(ptemp,12);
inc(longitud,12);
if header.magic1<>'RIFF' then begin
freemem(header);
exit;
end;
if header.magic2<>'WAVE' then begin
freemem(header);
exit;
end;
freemem(header);
getmem(chunk,sizeof(tchunk_info));
fmt:=false;
datos:=false;
salir:=false;
while not(salir) do begin
copymemory(chunk,ptemp,8);
inc(ptemp,8);
inc(longitud,8);
if chunk.name='fmt ' then begin
getmem(fmt_info,sizeof(tfmt_info));
copymemory(fmt_info,ptemp,16);
inc(ptemp,chunk.size);
inc(longitud,chunk.size);
//Tipo de compresion
if fmt_info.audio_format<>1 then begin //Solo soporto PCM!
freemem(chunk);
freemem(fmt_info);
exit;
end;
//Numero de canales
if ((fmt_info.num_channles<>1) and (fmt_info.num_channles<>2)) then begin
freemem(chunk);
freemem(fmt_info);
exit;
end;
//Samples seg.
lsamples_m:=FREQ_BASE_AUDIO/fmt_info.sample_rate;
lsamples_loop:=lsamples_m;
fmt:=true;
end;
if chunk.name='data' then begin
if not(fmt) then begin
freemem(chunk);
freemem(fmt_info);
exit;
end;
//Y ahora resampleado a 44100, 16bits, mono
if (fmt_info.bits_per_sample=16) then chunk.size:=chunk.size shr 1;
if (fmt_info.num_channles=2) then chunk.size:=chunk.size shr 1;
long:=round(chunk.size*lsamples_m)+1;
getmem(data,long*2);
data2:=data;
for f:=0 to (chunk.size-1) do begin
if fmt_info.bits_per_sample=8 then begin
temp:=byte(ptemp^-128) shl 8;
inc(ptemp);inc(longitud);
if fmt_info.num_channles=2 then begin
temp:=(temp+(byte(ptemp^-128) shl 8)) shr 1;
inc(ptemp);
end;
end else begin
copymemory(@temp,ptemp,2);
inc(ptemp,2);inc(longitud,2);
if fmt_info.num_channles=2 then begin
copymemory(@temp_w,ptemp,2);
inc(ptemp,2);
temp:=(temp+temp_w) shr 1;
end;
end;
for h:=0 to (trunc(lsamples_loop)-1) do begin
data2^:=temp;
inc(data2);
end;
lsamples_loop:=(lsamples_loop-trunc(lsamples_loop))+lsamples_m;
end;
datos:=true;
end;
if ((chunk.name='fact') or (chunk.name='list') or (chunk.name='cue') or (chunk.name='plst') or (chunk.name='labl') or (chunk.name='ltxt') or (chunk.name='smpl') or (chunk.name='note') or (chunk.name='inst')) then begin
//Longitud
inc(ptemp,chunk.size);
inc(longitud,chunk.size);
end;
if (fmt and datos) then begin
salir:=true;
convert_wav:=true;
end;
if longitud>source_long then salir:=true;
end;
freemem(chunk);
freemem(fmt_info);
end;
function load_samples_raw(sample_data:pword;longitud:dword;restart,loop:boolean;amp:single=1):boolean;
var
sample_pos:byte;
begin
load_samples_raw:=false;
//Inicializo los samples
if data_samples=nil then begin
getmem(data_samples,sizeof(tipo_samples));
data_samples.num_samples:=1;
sample_pos:=0;
end else begin
sample_pos:=data_samples.num_samples;
data_samples.num_samples:=data_samples.num_samples+1;
end;
//Inicializo el sample
getmem(data_samples.audio[sample_pos],sizeof(tipo_audio));
data_samples.audio[sample_pos].pos:=0;
data_samples.amp:=amp;
data_samples.audio[sample_pos].playing:=false;
getmem(data_samples.audio[sample_pos].data,longitud*2);
//cargar datos sample
data_samples.audio[sample_pos].long:=longitud;
data_samples.audio[sample_pos].restart:=restart;
data_samples.audio[sample_pos].loop:=loop;
copymemory(data_samples.audio[sample_pos].data,sample_data,longitud*2);
//Inicializar solo el sample
if ((data_samples.num_samples-1)<=MAX_CHANNELS) then begin
data_samples.tsample_reserved[data_samples.num_samples-1]:=init_channel;
data_samples.tsample_use[data_samples.num_samples-1]:=false;
end;
load_samples_raw:=true;
end;
function load_samples(const nombre_samples:array of tipo_nombre_samples;amp:single=1;parent:boolean=false;name:string=''):boolean;
var
f,sample_size:word;
ptemp:pbyte;
longitud:integer;
nombre_zip:string;
crc:dword;
begin
if parent then begin
nombre_zip:=name;
end else begin
for f:=1 to GAMES_CONT do begin
if GAMES_DESC[f].grid=main_vars.tipo_maquina then begin
nombre_zip:=GAMES_DESC[f].zip+'.zip';
break;
end;
end;
end;
load_samples:=false;
//Inicializo los samples
getmem(data_samples,sizeof(tipo_samples));
//Inicializo un buffer
getmem(ptemp,$100000);
sample_size:=sizeof(nombre_samples) div sizeof(tipo_nombre_samples);
for f:=0 to (sample_size-1) do begin
if not(load_file_from_zip(Directory.Arcade_samples+nombre_zip,nombre_samples[f].nombre,ptemp,longitud,crc,false)) then begin
freemem(data_samples);
data_samples:=nil;
freemem(ptemp);
exit;
end;
//Inicializo el sample
getmem(data_samples.audio[f],sizeof(tipo_audio));
data_samples.audio[f].data:=nil;
data_samples.audio[f].pos:=0;
data_samples.audio[f].playing:=false;
//cargar datos wav
if not(convert_wav(ptemp,data_samples.audio[f].data,longitud,data_samples.audio[f].long)) then begin
MessageDlg('Error loading sample file: '+'"'+nombre_samples[f].nombre+'"', mtError,[mbOk], 0);
freemem(data_samples);
data_samples:=nil;
freemem(ptemp);
exit;
end;
data_samples.audio[f].restart:=nombre_samples[f].restart;
data_samples.audio[f].loop:=nombre_samples[f].loop;
data_samples.audio[f].amp:=1;
end;
freemem(ptemp);
data_samples.num_samples:=sample_size;
data_samples.amp:=amp;
//Inicializar solor los necesarios...
for f:=0 to MAX_CHANNELS do data_samples.tsample_reserved[f]:=-1;
if (sample_size-1)>MAX_CHANNELS then sample_size:=MAX_CHANNELS;
for f:=0 to (sample_size-1) do begin
data_samples.tsample_reserved[f]:=init_channel;
data_samples.tsample_use[f]:=false;
end;
load_samples:=true;
end;
procedure reset_samples;
var
f:byte;
begin
if data_samples=nil then exit;
for f:=0 to data_samples.num_samples-1 do begin
data_samples.audio[f].playing:=false;
data_samples.audio[f].pos:=0;
end;
for f:=0 to MAX_CHANNELS do data_samples.tsample_use[f]:=false;
end;
function first_sample_free:byte;
var
f:byte;
begin
for f:=0 to MAX_CHANNELS do begin
if (not(data_samples.tsample_use[f]) and (data_samples.tsample_reserved[f]<>-1)) then begin
data_samples.tsample_use[f]:=true;
first_sample_free:=data_samples.tsample_reserved[f];
exit;
end;
end;
//Si no hay libres, que coja el primero...
first_sample_free:=data_samples.tsample_reserved[0];
end;
procedure start_sample(num:byte);
begin
if data_samples=nil then exit;
//Si no esta en marcha que comience
if not(data_samples.audio[num].playing) then begin
data_samples.audio[num].playing:=true;
data_samples.audio[num].pos:=0;
data_samples.audio[num].tsample:=first_sample_free;
end else begin //Si ya ha empezado, pero puede volver a comenzar lo hace
if data_samples.audio[num].restart then data_samples.audio[num].pos:=0;
end;
end;
procedure stop_sample(num:byte);
begin
if data_samples=nil then exit;
if data_samples.audio[num].playing then begin
data_samples.audio[num].playing:=false;
data_samples.tsample_use[data_samples.audio[num].tsample]:=false;
end;
end;
function sample_status(num:byte):boolean;
begin
if data_samples<>nil then sample_status:=data_samples.audio[num].playing;
end;
procedure stop_all_samples;
var
f:word;
begin
if data_samples=nil then exit;
for f:=0 to (data_samples.num_samples-1) do begin
if data_samples.audio[f].playing then begin
data_samples.audio[f].playing:=false;
data_samples.tsample_use[data_samples.audio[f].tsample]:=false;
end;
end;
end;
procedure samples_update;
var
f:word;
ptemp:pword;
begin
if data_samples=nil then exit;
for f:=0 to (data_samples.num_samples-1) do begin
if data_samples.audio[f].playing then begin
ptemp:=data_samples.audio[f].data;
inc(ptemp,data_samples.audio[f].pos);
data_samples.audio[f].pos:=data_samples.audio[f].pos+1;
tsample[data_samples.audio[f].tsample,sound_status.posicion_sonido]:=trunc(smallint(ptemp^)*data_samples.amp*data_samples.audio[f].amp);
if data_samples.audio[f].pos=data_samples.audio[f].long then begin
if data_samples.audio[f].loop then begin
data_samples.audio[f].pos:=0;
end else begin
data_samples.audio[f].playing:=false;
data_samples.tsample_use[data_samples.audio[f].tsample]:=false;
end;
end;
end;
end;
end;
procedure close_samples;
var
f:byte;
begin
if data_samples=nil then exit;
for f:=0 to data_samples.num_samples-1 do begin
if data_samples.audio[f]<>nil then begin
if data_samples.audio[f].data<>nil then freemem(data_samples.audio[f].data);
freemem(data_samples.audio[f]);
end;
end;
freemem(data_samples);
data_samples:=nil;
end;
procedure change_vol_sample(num_sample:byte;amp:single);
begin
data_samples.audio[num_sample].amp:=amp;
end;
end.
|
{$REGION 'Copyright (C) CMC Development Team'}
{ **************************************************************************
Copyright (C) 2015 CMC Development Team
CMC is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
CMC is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with CMC. If not, see <http://www.gnu.org/licenses/>.
************************************************************************** }
{ **************************************************************************
Additional Copyright (C) for this modul:
Chromaprint: Audio fingerprinting toolkit
Copyright (C) 2010-2012 Lukas Lalinsky <lalinsky@gmail.com>
Lomont FFT: Fast Fourier Transformation
Original code by Chris Lomont, 2010-2012, http://www.lomont.org/Software/
************************************************************************** }
{$ENDREGION}
{$REGION 'Notes'}
{ **************************************************************************
See CP.Chromaprint.pas for more information
************************************************************************** }
unit CP.Fingerprint;
{$IFDEF FPC}
{$MODE delphi}
{$ENDIF}
interface
uses
Classes, SysUtils,
CP.Def,
CP.AudioConsumer, CP.SilenceRemover, CP.Image, CP.Chroma, CP.Filter,
CP.Imagebuilder, CP.FeatureVectorConsumer, CP.FFT, CP.AudioProcessor,
CP.FingerprintCalculator, CP.FingerprinterConfiguration;
type
{ TFingerprinter }
TFingerprinter = class(TAudioConsumer)
private
FSilenceRemover: TSilenceRemover;
FImage: TImage;
FImageBuilder: TImageBuilder;
FChroma: TChroma;
FChromaNormalizer: TChromaNormalizer;
FChromaFilter: TChromaFilter;
FFFT: TFFT;
FAudioProcessor: TAudioProcessor;
FFingerprintCalculator: TFingerprintCalculator;
FConfig: TFingerprinterConfiguration;
public
constructor Create(config: TFingerprinterConfiguration = nil);
destructor Destroy; override;
function SetOption(const Name: PWideChar; Value: integer): boolean;
function Start(Sample_Rate, NumChannels: integer): boolean;
function Finish: TUINT32Array;
procedure Consume(Input: TSmallintArray; AOffset: integer; Length: integer); override;
end;
implementation
{ TFingerprinter }
constructor TFingerprinter.Create(config: TFingerprinterConfiguration);
begin
FImage := TImage.Create(12, 0);
if (config = nil) then
config := TFingerprinterConfigurationTest1.Create;
FImageBuilder := TImageBuilder.Create(FImage);
FChromaNormalizer := TChromaNormalizer.Create(FImageBuilder);
FChromaFilter := TChromaFilter.Create(config.FilterCoefficients, config.NumFilterCoefficients, FChromaNormalizer);
FChroma := TChroma.Create(cMIN_FREQ, cMAX_FREQ, cFRAME_SIZE, cSAMPLE_RATE, FChromaFilter);
FFFT := TFFT.Create(cFRAME_SIZE, cOVERLAP, FChroma);
if (config.RemoveSilence) then
begin
FSilenceRemover := TSilenceRemover.Create(FFFT);
FSilenceRemover.threshold := config.SilenceThreshold;
FAudioProcessor := TAudioProcessor.Create(cSAMPLE_RATE, FSilenceRemover);
end
else
begin
FSilenceRemover := nil;
FAudioProcessor := TAudioProcessor.Create(cSAMPLE_RATE, FFFT);
end;
FFingerprintCalculator := TFingerprintCalculator.Create(config.classifiers);
FConfig := config;
end;
destructor TFingerprinter.Destroy;
begin
FConfig.Free;
FFingerprintCalculator.Free;
FAudioProcessor.Free;
if (FSilenceRemover <> nil) then
FSilenceRemover.Free;
FFFT.Free;
FChroma.Free;
FChromaFilter.Free;
FChromaNormalizer.Free;
FImageBuilder.Free;
FImage.Free;
inherited Destroy;
end;
function TFingerprinter.SetOption(const Name: PWideChar; Value: integer): boolean;
begin
Result := False;
if Name = 'silence_threshold' then
begin
if (FSilenceRemover <> nil) then
begin
FSilenceRemover.threshold := Value;
Result := True;
end;
end;
end;
function TFingerprinter.Start(Sample_Rate, NumChannels: integer): boolean;
begin
if (not FAudioProcessor.Reset(Sample_Rate, NumChannels)) then
begin
// FIXME save error message somewhere
Result := False;
Exit;
end;
FFFT.Reset();
FChroma.Reset();
FChromaFilter.Reset();
FChromaNormalizer.Reset();
if FImage <> nil then
FImage.Free;
FImage := TImage.Create(12); // XXX
FImageBuilder.Reset(FImage);
Result := True;
end;
function TFingerprinter.Finish: TUINT32Array;
begin
FAudioProcessor.Flush();
Result := FFingerprintCalculator.Calculate(FImage);
end;
procedure TFingerprinter.Consume(Input: TSmallintArray; AOffset: integer; Length: integer);
begin
FAudioProcessor.Consume(Input, AOffset, Length);
end;
end.
|
unit FindUnit.PasParser;
interface
uses
ComCtrls, Classes, SysUtils, DelphiAST.Classes, Generics.Collections, FindUnit.Utils,
SimpleParser.Lexer.Types, FindUnit.Header, FindUnit.IncluderHandlerInc;
type
TPasFile = class(TObject)
private
FHashKey: string;
FLastModification: TDateTime;
FOriginUnitName: string;
FLists: TObjectList<TStringList>;
FClasses: TStringList;
FProcedures: TStringList;
FFunctions: TStringList;
FConstants: TStringList;
FVariables: TStringList;
procedure PrepareList(List: TStringList; const Description: string);
public
constructor Create;
destructor Destroy; override;
property OriginUnitName: string read FOriginUnitName write FOriginUnitName;
property LastModification: TDateTime read FLastModification write FLastModification;
property Classes: TStringList read FClasses;
property Procedures: TStringList read FProcedures;
property Functions: TStringList read FFunctions;
property Constants: TStringList read FConstants;
property Variables: TStringList read FVariables;
function GetListFromType(ListType: TListType): TStringList;
end;
TPasFileParser = class(TObject)
private
FFilePath: string;
FResultItem: TPasFile;
FUnitNode: TSyntaxNode;
FInterfaceNode: TSyntaxNode;
FIncluder: IIncludeHandler;
procedure GetUnitName;
procedure GetFileLastModification;
procedure GetClasses;
procedure GetMethods;
procedure GetVariables;
procedure GetConstants;
function HaveInterfaceNode: Boolean;
public
constructor Create(const FilePath: string);
function Process: TPasFile;
procedure SetIncluder(Includer: IIncludeHandler);
end;
implementation
uses
IOUtils, DelphiAST.Consts, DelphiAST, Log4PAscal;
{ TFindUnitItem }
constructor TPasFile.Create;
procedure CreateAndAdd(var List: TStringList);
begin
List := TStringList.Create;
List.Sorted := True;
FLists.Add(List);
end;
begin
FLists := TObjectList<TStringList>.Create;
CreateAndAdd(FClasses);
CreateAndAdd(FProcedures);
CreateAndAdd(FFunctions);
CreateAndAdd(FConstants);
CreateAndAdd(FVariables);
end;
destructor TPasFile.Destroy;
begin
FLists.Free;
inherited;
end;
function TPasFile.GetListFromType(ListType: TListType): TStringList;
begin
case ListType of
ltClasses: Result := FClasses;
ltProcedures: Result := FProcedures;
ltFunctions: Result := FFunctions;
ltContants: Result := FConstants;
ltVariables: Result := FVariables;
end;
end;
procedure TPasFile.PrepareList(List: TStringList; const Description: string);
var
I: Integer;
begin
List.Sorted := False;
List.Text := Trim(List.Text);
for I := 0 to List.Count -1 do
if Description = '' then
List[I] := FOriginUnitName + '.' + List[i]
else
List[I] := FOriginUnitName + '.' + List[i] + ' - ' + Description;
List.Sorted := True;
end;
const
Identifications: array[0..4] of String = (
'',
'Procedure',
'Function',
'Constant',
'Variable'
);
{ TFindUnitParser }
constructor TPasFileParser.Create(const FilePath: string);
begin
inherited Create;
FFilePath := FilePath;
end;
procedure TPasFileParser.GetClasses;
var
SectionTypesNode: TSyntaxNode;
TypeNode: TSyntaxNode;
TypeDesc: TSyntaxNode;
Description: string[50];
ItemClassName: string;
begin
SectionTypesNode := FInterfaceNode.FindNode(ntTypeSection);
while SectionTypesNode <> nil do
begin
TypeNode := SectionTypesNode.FindNode(ntTypeDecl);
while TypeNode <> nil do
begin
try
Description := ' - Class';
ItemClassName := TypeNode.GetAttribute(anName);
TypeDesc := TypeNode.FindNode(ntType);
if TypeDesc <> nil then
begin
Description := TypeDesc.GetAttribute(anType);
if Description = '' then
Description := 'Enum';
Description[1] := UpCase(Description[1]);
Description := ' - ' + Description;
end;
FResultItem.FClasses.Add(ItemClassName + Description);
except
on e: exception do
Logger.Error('TFindUnitParser.GetClasses: %s', [e.Message]);
end;
SectionTypesNode.DeleteChild(TypeNode);
TypeNode := SectionTypesNode.FindNode(ntTypeDecl);
end;
FInterfaceNode.DeleteChild(SectionTypesNode);
SectionTypesNode := FInterfaceNode.FindNode(ntTypeSection);
end;
end;
procedure TPasFileParser.GetConstants;
var
ConstantsNode: TSyntaxNode;
ConstantItem: TSyntaxNode;
Name: TSyntaxNode;
begin
ConstantsNode := FInterfaceNode.FindNode(ntConstants);
while ConstantsNode <> nil do
begin
ConstantItem := ConstantsNode.FindNode(ntConstant);
while ConstantItem <> nil do
begin
Name := ConstantItem.FindNode(ntName);
FResultItem.FConstants.Add(TValuedSyntaxNode(Name).Value);
ConstantsNode.DeleteChild(ConstantItem);
ConstantItem := ConstantsNode.FindNode(ntConstant);
end;
FInterfaceNode.DeleteChild(ConstantsNode);
ConstantsNode := FInterfaceNode.FindNode(ntConstants);
end;
end;
procedure TPasFileParser.GetFileLastModification;
begin
FResultItem.FLastModification := IOUtils.TFile.GetLastWriteTime(FFilePath);
end;
procedure TPasFileParser.GetMethods;
var
MethodNode: TSyntaxNode;
begin
MethodNode := FInterfaceNode.FindNode(ntMethod);
while MethodNode <> nil do
begin
if MethodNode.GetAttribute(anKind) = 'procedure' then
FResultItem.FProcedures.Add(MethodNode.GetAttribute(anName))
else
FResultItem.FFunctions.Add(MethodNode.GetAttribute(anName));
FInterfaceNode.DeleteChild(MethodNode);
MethodNode := FInterfaceNode.FindNode(ntMethod);
end;
end;
procedure TPasFileParser.GetUnitName;
begin
FResultItem.OriginUnitName := FUnitNode.GetAttribute(anName);
end;
procedure TPasFileParser.GetVariables;
var
VariablesNode: TSyntaxNode;
Variable: TSyntaxNode;
VariableName: TSyntaxNode;
Attr: TPair<TAttributeName, string>;
begin
VariablesNode := FInterfaceNode.FindNode(ntVariables);
while VariablesNode <> nil do
begin
Variable := VariablesNode.FindNode(ntVariable);
while Variable <> nil do
begin
VariableName := Variable.FindNode(ntName);
FResultItem.FVariables.Add(TValuedSyntaxNode(VariableName).Value);
VariablesNode.DeleteChild(Variable);
Variable := VariablesNode.FindNode(ntVariable);
end;
FInterfaceNode.DeleteChild(VariablesNode);
VariablesNode := FInterfaceNode.FindNode(ntVariables);
end;
end;
function TPasFileParser.HaveInterfaceNode: Boolean;
begin
FInterfaceNode := FUnitNode.FindNode(ntInterface);
Result := FInterfaceNode <> nil;
end;
function TPasFileParser.Process: TPasFile;
begin
FUnitNode := nil;
Result := nil;
if not FileExists(FFilePath) then
begin
Logger.Debug('TFindUnitParser.Process: File do not exists %s', [FFilePath]);
Exit;
end;
try
try
FUnitNode := TPasSyntaxTreeBuilder.Run(FFilePath, True, FIncluder);
except
on E: ESyntaxTreeException do
begin
FUnitNode := e.SyntaxTree;
e.SyntaxTree := nil;
end;
end;
if FUnitNode = nil then
begin
Exit;
end;
FResultItem := TPasFile.Create;
Result := FResultItem;
try
GetUnitName;
GetFileLastModification;
if not HaveInterfaceNode then
Exit;
GetClasses;
GetMethods;
GetVariables;
GetConstants;
finally
FUnitNode.Free;
end;
except
on E: Exception do
begin
Logger.Error('TFindUnitParser.Process: Trying to parse %s. Msg: %s', [FFilePath, E.Message]);
Result := nil;
end;
end;
end;
procedure TPasFileParser.SetIncluder(Includer: IIncludeHandler);
begin
FIncluder := Includer;
end;
end.
|
PROGRAM textToAscii;
USES
Sysutils,
crt;
VAR
text : STRING;
i : LONGINT;
BEGIN
TextBackground(White);
TextColor(Black);
ClrScr();
writeln('Insert text you want to code!');
writeln('-----------------------------');
write('Text: ');
readln(text);
writeln('--------------------------------------------------------------');
write('ASCII Code: ');
FOR i := 1 TO length(text) DO
Write (ord(text[i]), ' ');
writeln();
writeln('--------------------------------------------------------------');
writeln('Press any key to exit!');
readkey();
END.
|
object HouseRepository: THouseRepository
OldCreateOrder = False
OnCreate = DataModuleCreate
Height = 513
Width = 751
object HousesQuery: TFDQuery
SQL.Strings = (
'SELECT '
' h."ID", '
' h."Favorite", '
' h."Address", '
' h."City", '
' h."State", '
' h."ZipCode", '
' h."Beds", '
' h."Baths", '
' h."HouseSize", '
' h."LotSize", '
' h."Price", '
' h."Coordinates", '
' h."Features", '
' h."YearBuilt", '
' h."Type", '
' h."Status", '
' h."Image", '
' ah."AgentId"'
'from "House" h '
'LEFT join "AgentHouse" ah '
' on h."ID" = ah."HouseId" '
'order by h."ID"')
Left = 96
Top = 72
object HousesQueryID: TLargeintField
FieldName = 'ID'
Origin = '"ID"'
ProviderFlags = [pfInUpdate, pfInWhere, pfInKey]
end
object HousesQueryFavorite: TBooleanField
FieldName = 'Favorite'
Origin = '"Favorite"'
end
object HousesQueryAddress: TWideStringField
FieldName = 'Address'
Origin = '"Address"'
Size = 100
end
object HousesQueryCity: TWideStringField
FieldName = 'City'
Origin = '"City"'
Size = 100
end
object HousesQueryState: TWideStringField
FieldName = 'State'
Origin = '"State"'
Size = 2
end
object HousesQueryZipCode: TWideStringField
FieldName = 'ZipCode'
Origin = '"ZipCode"'
Size = 10
end
object HousesQueryBeds: TIntegerField
FieldName = 'Beds'
Origin = '"Beds"'
end
object HousesQueryBaths: TIntegerField
FieldName = 'Baths'
Origin = '"Baths"'
end
object HousesQueryHouseSize: TIntegerField
FieldName = 'HouseSize'
Origin = '"HouseSize"'
end
object HousesQueryLotSize: TFMTBCDField
FieldName = 'LotSize'
Origin = '"LotSize"'
Precision = 18
Size = 2
end
object HousesQueryPrice: TCurrencyField
FieldName = 'Price'
Origin = '"Price"'
end
object HousesQueryCoordinates: TWideStringField
FieldName = 'Coordinates'
Origin = '"Coordinates"'
Size = 100
end
object HousesQueryFeatures: TWideMemoField
FieldName = 'Features'
Origin = '"Features"'
BlobType = ftWideMemo
end
object HousesQueryYearBuilt: TIntegerField
FieldName = 'YearBuilt'
Origin = '"YearBuilt"'
end
object HousesQueryType: TSmallintField
FieldName = 'Type'
Origin = '"Type"'
end
object HousesQueryStatus: TSmallintField
FieldName = 'Status'
Origin = '"Status"'
end
object HousesQueryImage: TWideStringField
FieldName = 'Image'
Origin = '"Image"'
Size = 2000
end
object HousesQueryAgentId: TLargeintField
AutoGenerateValue = arDefault
FieldName = 'AgentId'
Origin = '"AgentId"'
end
end
end
|
{
Clever Internet Suite
Copyright (C) 2013 Clever Components
All Rights Reserved
www.CleverComponents.com
}
unit clDnsServer;
interface
{$I clVer.inc}
{$IFDEF DELPHI7}
{$WARN UNSAFE_CODE OFF}
{$WARN UNSAFE_TYPE OFF}
{$WARN UNSAFE_CAST OFF}
{$ENDIF}
uses
{$IFNDEF DELPHIXE2}
Classes, SysUtils, Contnrs,{$IFDEF DEMO} Windows,{$ENDIF}
{$ELSE}
System.Classes, System.SysUtils, System.Contnrs,{$IFDEF DEMO} Winapi.Windows,{$ENDIF}
{$ENDIF}
clUdpServer, clDnsMessage, clSocketUtils{$IFDEF LOGGER}, clLogger{$ENDIF};
type
EclDnsServerError = class(EclUdpServerError)
public
constructor Create(AErrorCode: Integer; ADummy: Boolean = False); overload;
constructor Create(const AErrorMsg: string; AErrorCode: Integer; ADummy: Boolean = False); overload;
end;
TclDnsCacheEntry = class
private
FName: string;
FRecordType: Integer;
FCreatedOn: TDateTime;
FNameServers: TclDnsRecordList;
FAnswers: TclDnsRecordList;
FAdditionalRecords: TclDnsRecordList;
function CheckExpired(ARecords: TclDnsRecordList; AMaxCacheTTL: Integer): Boolean;
public
constructor Create;
destructor Destroy; override;
procedure Clear;
function IsExpired(AMaxCacheTTL: Integer): Boolean;
procedure Load(ACachedResponse: TclDnsMessage);
property Name: string read FName write FName;
property RecordType: Integer read FRecordType write FRecordType;
property NameServers: TclDnsRecordList read FNameServers;
property Answers: TclDnsRecordList read FAnswers;
property AdditionalRecords: TclDnsRecordList read FAdditionalRecords;
property CreatedOn: TDateTime read FCreatedOn write FCreatedOn;
end;
TclDnsServer = class;
TclDnsCommandInfo = class
private
FCode: Integer;
FServer: TclDnsServer;
function SearchHandedZone(AConnection: TclUdpUserConnection; const AQueryName: string; AResponse: TclDnsMessage): Boolean;
function SearchCachedZone(AConnection: TclUdpUserConnection; AQuery, AResponse: TclDnsMessage): Boolean;
function ResolveCachedZone(AConnection: TclUdpUserConnection; AQuery: TclDnsMessage): TclDnsMessage;
procedure FillCachedResponse(ACacheEntry: TclDnsCacheEntry; AResponse: TclDnsMessage);
procedure ClearResponseRecords(AResponse: TclDnsMessage);
protected
procedure AddARecord(const AName: string; ARecords: TclDnsRecordList; AResponse: TclDnsMessage);
procedure FillAdditionalRecords(ARecords: TclDnsRecordList; AResponse: TclDnsMessage); virtual; abstract;
public
constructor Create(ACode: Integer);
procedure Execute(AConnection: TclUdpUserConnection; AQuery, AResponse: TclDnsMessage);
property Code: Integer read FCode write FCode;
property Server: TclDnsServer read FServer;
end;
TclDnsACommandInfo = class(TclDnsCommandInfo)
protected
procedure FillAdditionalRecords(ARecords: TclDnsRecordList; AResponse: TclDnsMessage); override;
public
constructor Create;
end;
TclDnsAAAACommandInfo = class(TclDnsCommandInfo)
protected
procedure FillAdditionalRecords(ARecords: TclDnsRecordList; AResponse: TclDnsMessage); override;
public
constructor Create;
end;
TclDnsNSCommandInfo = class(TclDnsCommandInfo)
protected
procedure FillAdditionalRecords(ARecords: TclDnsRecordList; AResponse: TclDnsMessage); override;
public
constructor Create;
end;
TclDnsCNAMECommandInfo = class(TclDnsCommandInfo)
protected
procedure FillAdditionalRecords(ARecords: TclDnsRecordList; AResponse: TclDnsMessage); override;
public
constructor Create;
end;
TclDnsSOACommandInfo = class(TclDnsCommandInfo)
protected
procedure FillAdditionalRecords(ARecords: TclDnsRecordList; AResponse: TclDnsMessage); override;
public
constructor Create;
end;
TclDnsPTRCommandInfo = class(TclDnsCommandInfo)
protected
procedure FillAdditionalRecords(ARecords: TclDnsRecordList; AResponse: TclDnsMessage); override;
public
constructor Create;
end;
TclDnsMXCommandInfo = class(TclDnsCommandInfo)
protected
procedure FillAdditionalRecords(ARecords: TclDnsRecordList; AResponse: TclDnsMessage); override;
public
constructor Create;
end;
TclDnsTXTCommandInfo = class(TclDnsCommandInfo)
protected
procedure FillAdditionalRecords(ARecords: TclDnsRecordList; AResponse: TclDnsMessage); override;
public
constructor Create;
end;
TclDnsCommandList = class
private
FList: TObjectList;
FServer: TclDnsServer;
function GetItem(Index: Integer): TclDnsCommandInfo;
function GetCount: Integer;
public
constructor Create(AServer: TclDnsServer);
destructor Destroy; override;
procedure Add(ACommand: TclDnsCommandInfo);
function CommandByCode(ACode: Integer): TclDnsCommandInfo;
procedure Delete(Index: Integer);
procedure Clear;
property Items[Index: Integer]: TclDnsCommandInfo read GetItem; default;
property Count: Integer read GetCount;
property Server: TclDnsServer read FServer;
end;
TclDnsQueryEvent = procedure (Sender: TObject; AConnection: TclUdpUserConnection; AQuery: TclDnsMessage) of object;
TclDnsResponseEvent = procedure (Sender: TObject; AConnection: TclUdpUserConnection; AQuery, AResponse: TclDnsMessage) of object;
TclDnsRecordsEvent = procedure (Sender: TObject; AConnection: TclUdpUserConnection; const AName: string;
ARecords: TclDnsRecordList) of object;
TclDnsCacheEvent = procedure (Sender: TObject; AConnection: TclUdpUserConnection; const AName: string;
ARecordType: Integer; var ACacheEntry: TclDnsCacheEntry) of object;
TclDnsAddCacheEvent = procedure (Sender: TObject; AConnection: TclUdpUserConnection; const AName: string;
ARecordType: Integer; ACacheEntry: TclDnsCacheEntry) of object;
TclDnsDeleteCacheEvent = procedure (Sender: TObject; AConnection: TclUdpUserConnection; const AName: string;
ARecordType: Integer) of object;
TclDnsResolveRecordsEvent = procedure (Sender: TObject; AConnection: TclUdpUserConnection; const AName: string;
ARecordType: Integer; AResponse: TclDnsMessage; var Handled: Boolean) of object;
TclDnsServer = class(TclUdpServer)
private
FCommands: TclDnsCommandList;
FMaxCacheTTL: Integer;
FMaxRecursiveQueries: Integer;
FUseRecursiveQueries: Boolean;
FUseCaching: Boolean;
FRootNameServers: TStrings;
FOnSendResponse: TclDnsResponseEvent;
FOnGetCachedRecords: TclDnsCacheEvent;
FOnGetHandedRecords: TclDnsRecordsEvent;
FOnDeleteCachedRecords: TclDnsDeleteCacheEvent;
FOnAddCachedRecords: TclDnsAddCacheEvent;
FOnResolveCachedRecords: TclDnsResolveRecordsEvent;
FOnReceiveQuery: TclDnsQueryEvent;
FTimeOut: Integer;
procedure SetRootNameServers(const Value: TStrings);
procedure SendResponse(AConnection: TclUdpUserConnection; AQuery, AResponse: TclDnsMessage);
procedure InitResponse(AConnection: TclUdpUserConnection; AQuery, AResponse: TclDnsMessage);
procedure CheckQuery(AQuery: TclDnsMessage);
procedure HandleCommandData(AConnection: TclUdpUserConnection; AData: TStream);
procedure FillDefaultRootNameServers;
protected
procedure DoSendResponse(AConnection: TclUdpUserConnection; AQuery, AResponse: TclDnsMessage); virtual;
procedure DoGetCachedRecords(AConnection: TclUdpUserConnection; const AName: string; ARecordType: Integer;
var ACacheEntry: TclDnsCacheEntry); virtual;
procedure DoGetHandedRecords(AConnection: TclUdpUserConnection; const AName: string; ARecords: TclDnsRecordList); virtual;
procedure DoDeleteCachedRecords(AConnection: TclUdpUserConnection; const AName: string; ARecordType: Integer); virtual;
procedure DoAddCachedRecords(AConnection: TclUdpUserConnection; const AName: string; ARecordType: Integer;
ACacheEntry: TclDnsCacheEntry); virtual;
procedure DoResolveCachedRecords(AConnection: TclUdpUserConnection; const AName: string; ARecordType: Integer;
AResponse: TclDnsMessage; var Handled: Boolean); virtual;
procedure DoReceiveQuery(AConnection: TclUdpUserConnection; AQuery: TclDnsMessage); virtual;
procedure GetCommands; virtual;
function CreateDefaultConnection: TclUdpUserConnection; override;
procedure DoReadPacket(AConnection: TclUdpUserConnection; AData: TStream); override;
procedure DoDestroy; override;
public
constructor Create(AOwner: TComponent); override;
property Commands: TclDnsCommandList read FCommands;
published
property Port default DefaultDnsPort;
property MaxCacheTTL: Integer read FMaxCacheTTL write FMaxCacheTTL default 800000;
property MaxRecursiveQueries: Integer read FMaxRecursiveQueries write FMaxRecursiveQueries default 4;
property UseRecursiveQueries: Boolean read FUseRecursiveQueries write FUseRecursiveQueries default True;
property UseCaching: Boolean read FUseCaching write FUseCaching default True;
property RootNameServers: TStrings read FRootNameServers write SetRootNameServers;
property TimeOut: Integer read FTimeOut write FTimeOut default 1000;
property OnReceiveQuery: TclDnsQueryEvent read FOnReceiveQuery write FOnReceiveQuery;
property OnSendResponse: TclDnsResponseEvent read FOnSendResponse write FOnSendResponse;
property OnGetHandedRecords: TclDnsRecordsEvent read FOnGetHandedRecords write FOnGetHandedRecords;
property OnGetCachedRecords: TclDnsCacheEvent read FOnGetCachedRecords write FOnGetCachedRecords;
property OnDeleteCachedRecords: TclDnsDeleteCacheEvent read FOnDeleteCachedRecords write FOnDeleteCachedRecords;
property OnAddCachedRecords: TclDnsAddCacheEvent read FOnAddCachedRecords write FOnAddCachedRecords;
property OnResolveCachedRecords: TclDnsResolveRecordsEvent read FOnResolveCachedRecords write FOnResolveCachedRecords;
end;
implementation
uses
clDnsQuery, clSocket;
{ TclDnsServer }
procedure TclDnsServer.CheckQuery(AQuery: TclDnsMessage);
begin
if (AQuery.Queries.Count <> 1) then
begin
raise EclDnsServerError.Create(DnsFormatErrorCode);
end;
if (AQuery.Queries[0].RecordClass <> rcInternet) then
begin
raise EclDnsServerError.Create(DnsFormatErrorCode);
end;
end;
constructor TclDnsServer.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FCommands := TclDnsCommandList.Create(Self);
GetCommands();
Port := DefaultDnsPort;
FMaxCacheTTL := 800000;
FMaxRecursiveQueries := 4;
FUseRecursiveQueries := True;
FUseCaching := True;
FTimeOut := 1000;
FRootNameServers := TStringList.Create();
FillDefaultRootNameServers();
end;
function TclDnsServer.CreateDefaultConnection: TclUdpUserConnection;
begin
Result := TclUdpUserConnection.Create();
end;
procedure TclDnsServer.DoAddCachedRecords(AConnection: TclUdpUserConnection; const AName: string; ARecordType: Integer;
ACacheEntry: TclDnsCacheEntry);
begin
if Assigned(OnAddCachedRecords) then
begin
OnAddCachedRecords(Self, AConnection, AName, ARecordType, ACacheEntry);
end;
end;
procedure TclDnsServer.DoDeleteCachedRecords(AConnection: TclUdpUserConnection; const AName: string; ARecordType: Integer);
begin
if Assigned(OnDeleteCachedRecords) then
begin
OnDeleteCachedRecords(Self, AConnection, AName, ARecordType);
end;
end;
procedure TclDnsServer.DoDestroy;
begin
FRootNameServers.Free();
FCommands.Free();
inherited DoDestroy();
end;
procedure TclDnsServer.DoGetCachedRecords(AConnection: TclUdpUserConnection; const AName: string; ARecordType: Integer;
var ACacheEntry: TclDnsCacheEntry);
begin
if Assigned(OnGetCachedRecords) then
begin
OnGetCachedRecords(Self, AConnection, AName, ARecordType, ACacheEntry);
end;
end;
procedure TclDnsServer.DoGetHandedRecords(AConnection: TclUdpUserConnection; const AName: string; ARecords: TclDnsRecordList);
begin
if Assigned(OnGetHandedRecords) then
begin
OnGetHandedRecords(Self, AConnection, AName, ARecords);
end;
end;
procedure TclDnsServer.DoReadPacket(AConnection: TclUdpUserConnection; AData: TStream);
begin
{$IFDEF DEMO}
{$IFNDEF STANDALONEDEMO}
if FindWindow('TAppBuilder', nil) = 0 then
begin
MessageBox(0, 'This demo version can be run under Delphi/C++Builder IDE only. ' +
'Please visit www.clevercomponents.com to purchase your ' +
'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST);
ExitProcess(1);
end;
{$ENDIF}
{$ENDIF}
inherited DoReadPacket(AConnection, AData);
HandleCommandData(AConnection, AData);
end;
procedure TclDnsServer.DoReceiveQuery(AConnection: TclUdpUserConnection; AQuery: TclDnsMessage);
begin
if Assigned(OnReceiveQuery) then
begin
OnReceiveQuery(Self, AConnection, AQuery);
end;
end;
procedure TclDnsServer.DoResolveCachedRecords(AConnection: TclUdpUserConnection; const AName: string; ARecordType: Integer;
AResponse: TclDnsMessage; var Handled: Boolean);
begin
if Assigned(OnResolveCachedRecords) then
begin
OnResolveCachedRecords(Self, AConnection, AName, ARecordType, AResponse, Handled);
end;
end;
procedure TclDnsServer.DoSendResponse(AConnection: TclUdpUserConnection; AQuery, AResponse: TclDnsMessage);
begin
if Assigned(OnSendResponse) then
begin
OnSendResponse(Self, AConnection, AQuery, AResponse);
end;
end;
procedure TclDnsServer.FillDefaultRootNameServers;
begin
FRootNameServers.Add('A.ROOT-SERVERS.NET');
FRootNameServers.Add('B.ROOT-SERVERS.NET');
FRootNameServers.Add('C.ROOT-SERVERS.NET');
FRootNameServers.Add('D.ROOT-SERVERS.NET');
FRootNameServers.Add('E.ROOT-SERVERS.NET');
FRootNameServers.Add('F.ROOT-SERVERS.NET');
FRootNameServers.Add('G.ROOT-SERVERS.NET');
FRootNameServers.Add('H.ROOT-SERVERS.NET');
FRootNameServers.Add('I.ROOT-SERVERS.NET');
FRootNameServers.Add('J.ROOT-SERVERS.NET');
FRootNameServers.Add('K.ROOT-SERVERS.NET');
FRootNameServers.Add('L.ROOT-SERVERS.NET');
FRootNameServers.Add('M.ROOT-SERVERS.NET');
end;
procedure TclDnsServer.GetCommands;
begin
Commands.Add(TclDnsACommandInfo.Create());
Commands.Add(TclDnsAAAACommandInfo.Create());
Commands.Add(TclDnsNSCommandInfo.Create());
Commands.Add(TclDnsCNAMECommandInfo.Create());
Commands.Add(TclDnsSOACommandInfo.Create());
Commands.Add(TclDnsPTRCommandInfo.Create());
Commands.Add(TclDnsMXCommandInfo.Create());
Commands.Add(TclDnsTXTCommandInfo.Create());
end;
procedure TclDnsServer.HandleCommandData(AConnection: TclUdpUserConnection; AData: TStream);
var
query, response: TclDnsMessage;
info: TclDnsCommandInfo;
begin
{$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'HandleCommandData');{$ENDIF}
query := nil;
response := nil;
try
query := TclDnsMessage.Create();
response := TclDnsMessage.Create();
try
AData.Position := 0;
query.Parse(AData);
DoReceiveQuery(AConnection, query);
CheckQuery(query);
info := Commands.CommandByCode(query.Queries[0].RecordType);
if (info = nil) then
begin
raise EclDnsServerError.Create(DnsNotImplementedCode);
end;
InitResponse(AConnection, query, response);
info.Execute(AConnection, query, response);
SendResponse(AConnection, query, response);
except
on E: EclDnsError do
begin
InitResponse(AConnection, query, response);
response.Header.ResponseCode := E.ErrorCode;
SendResponse(AConnection, query, response);
end;
on E: EclDnsServerError do
begin
InitResponse(AConnection, query, response);
response.Header.ResponseCode := E.ErrorCode;
SendResponse(AConnection, query, response);
end;
end;
finally
response.Free();
query.Free();
end;
{$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'HandleCommandData'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'HandleCommandData', E); raise; end; end;{$ENDIF}
end;
procedure TclDnsServer.InitResponse(AConnection: TclUdpUserConnection; AQuery, AResponse: TclDnsMessage);
begin
AResponse.Header.ID := AQuery.Header.ID;
AResponse.Header.IsQuery := False;
AResponse.Header.OpCode := AQuery.Header.OpCode;
AResponse.Header.IsRecursionDesired := AQuery.Header.IsRecursionDesired;
AResponse.Header.IsRecursionAvailable := UseRecursiveQueries;
AResponse.Queries.Add(AQuery.Queries[0].Clone());
end;
procedure TclDnsServer.SendResponse(AConnection: TclUdpUserConnection; AQuery, AResponse: TclDnsMessage);
var
stream: TStream;
begin
{$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'SendResponse');{$ENDIF}
stream := TMemoryStream.Create();
try
AResponse.Build(stream);
if (stream.Size > DatagramSize) then
begin
AResponse.Header.IsTruncated := True;
stream.Size := 0;
AResponse.Build(stream);
stream.Size := DatagramSize;
end;
stream.Position := 0;
AConnection.WriteData(stream);
DoSendResponse(AConnection, AQuery, AResponse);
finally
stream.Free();
end;
{$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'SendResponse'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'SendResponse', E); raise; end; end;{$ENDIF}
end;
procedure TclDnsServer.SetRootNameServers(const Value: TStrings);
begin
FRootNameServers.Assign(Value);
end;
{ TclDnsCacheEntry }
function TclDnsCacheEntry.CheckExpired(ARecords: TclDnsRecordList; AMaxCacheTTL: Integer): Boolean;
var
i: Integer;
begin
Result := True;
if ((CreatedOn + AMaxCacheTTL / SecsPerDay) < Now()) then
begin
Exit;
end;
for i := 0 to ARecords.Count - 1 do
begin
if ((CreatedOn + ARecords[i].TTL / SecsPerDay) < Now()) then
begin
Exit;
end;
end;
Result := False;
end;
procedure TclDnsCacheEntry.Clear;
begin
FName := '';
FRecordType := 0;
FNameServers.Clear();
FAnswers.Clear();
FAdditionalRecords.Clear();
end;
constructor TclDnsCacheEntry.Create;
begin
inherited Create();
FNameServers := TclDnsRecordList.Create();
FAnswers := TclDnsRecordList.Create();
FAdditionalRecords := TclDnsRecordList.Create();
FCreatedOn := Now();
end;
destructor TclDnsCacheEntry.Destroy;
begin
FAdditionalRecords.Free();
FAnswers.Free();
FNameServers.Free();
inherited Destroy();
end;
function TclDnsCacheEntry.IsExpired(AMaxCacheTTL: Integer): Boolean;
begin
Result := CheckExpired(Answers, AMaxCacheTTL) or CheckExpired(NameServers, AMaxCacheTTL)
or CheckExpired(AdditionalRecords, AMaxCacheTTL);
end;
procedure TclDnsCacheEntry.Load(ACachedResponse: TclDnsMessage);
begin
Clear();
if (ACachedResponse.Queries.Count = 1) then
begin
FName := ACachedResponse.Queries[0].Name;
FRecordType := ACachedResponse.Queries[0].RecordType;
end;
FAnswers.Assign(ACachedResponse.Answers);
FNameServers.Assign(ACachedResponse.NameServers);
FAdditionalRecords.Assign(ACachedResponse.AdditionalRecords);
end;
{ TclDnsCommandList }
procedure TclDnsCommandList.Add(ACommand: TclDnsCommandInfo);
begin
FList.Add(ACommand);
ACommand.FServer := FServer;
end;
procedure TclDnsCommandList.Clear;
begin
FList.Clear();
end;
function TclDnsCommandList.CommandByCode(ACode: Integer): TclDnsCommandInfo;
var
i: Integer;
begin
for i := 0 to Count - 1 do
begin
Result := Items[i];
if (Result.Code = ACode) then Exit;
end;
Result := nil;
end;
constructor TclDnsCommandList.Create(AServer: TclDnsServer);
begin
inherited Create();
FServer := AServer;
FList := TObjectList.Create(True);
end;
procedure TclDnsCommandList.Delete(Index: Integer);
begin
FList.Delete(Index);
end;
destructor TclDnsCommandList.Destroy;
begin
FList.Free();
inherited Destroy();
end;
function TclDnsCommandList.GetCount: Integer;
begin
Result := FList.Count;
end;
function TclDnsCommandList.GetItem(Index: Integer): TclDnsCommandInfo;
begin
Result := TclDnsCommandInfo(FList[Index]);
end;
{ TclDnsCommandInfo }
procedure TclDnsCommandInfo.AddARecord(const AName: string; ARecords: TclDnsRecordList; AResponse: TclDnsMessage);
var
i: Integer;
rec: TclDnsRecord;
begin
for i := 0 to ARecords.Count - 1 do
begin
rec := ARecords[i];
if ((DnsRecordTypes[rtARecord] = rec.RecordType) and SameText(rec.Name, AName)) then
begin
AResponse.AdditionalRecords.Add(rec.Clone());
Exit;
end;
end;
end;
procedure TclDnsCommandInfo.ClearResponseRecords(AResponse: TclDnsMessage);
begin
AResponse.Answers.Clear();
AResponse.NameServers.Clear();
AResponse.AdditionalRecords.Clear();
end;
constructor TclDnsCommandInfo.Create(ACode: Integer);
begin
inherited Create();
FCode := ACode;
end;
procedure TclDnsCommandInfo.Execute(AConnection: TclUdpUserConnection; AQuery, AResponse: TclDnsMessage);
var
handled: Boolean;
begin
{$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'Execute');{$ENDIF}
handled := SearchHandedZone(AConnection, AQuery.Queries[0].Name, AResponse);
if (not handled) then
begin
handled := SearchCachedZone(AConnection, AQuery, AResponse);
end;
if (not handled) then
begin
ClearResponseRecords(AResponse);
raise EclDnsServerError.Create(DnsNameErrorCode);
end;
{$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'Execute'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'Execute', E); raise; end; end;{$ENDIF}
end;
procedure TclDnsCommandInfo.FillCachedResponse(ACacheEntry: TclDnsCacheEntry; AResponse: TclDnsMessage);
begin
AResponse.Answers.Assign(ACacheEntry.Answers);
AResponse.NameServers.Assign(ACacheEntry.NameServers);
AResponse.AdditionalRecords.Assign(ACacheEntry.AdditionalRecords);
end;
function TclDnsCommandInfo.ResolveCachedZone(AConnection: TclUdpUserConnection; AQuery: TclDnsMessage): TclDnsMessage;
var
handled: Boolean;
client: TclDnsQuery;
begin
{$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'ResolveCachedZone');{$ENDIF}
Result := nil;
if (not Server.UseRecursiveQueries) then
begin
Exit;
end;
Result := TclDnsMessage.Create();
try
handled := False;
Server.DoResolveCachedRecords(AConnection, AQuery.Queries[0].Name, AQuery.Queries[0].RecordType, Result, handled);
if (handled) then
begin
Exit;
end;
client := TclDnsQuery.Create(nil);
try
client.RootNameServers := Server.RootNameServers;
client.UseRecursiveQueries := True;
client.AutodetectServer := False;
client.MaxRecursiveQueries := Server.MaxRecursiveQueries;
client.TimeOut := Server.TimeOut;
try
client.Resolve(AQuery, Result);
{$IFDEF LOGGER}clPutLogMessage(Self, edInside, 'ResolveCachedZone - record resolved');{$ENDIF}
except
on EclSocketError do
begin
{$IFDEF LOGGER}clPutLogMessage(Self, edInside, 'ResolveCachedZone - resolve error, next rootname attempt');{$ENDIF}
end;
end;
finally
client.Free();
end;
except
Result.Free();
raise;
end;
{$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'ResolveCachedZone'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'ResolveCachedZone', E); raise; end; end;{$ENDIF}
end;
function TclDnsCommandInfo.SearchCachedZone(AConnection: TclUdpUserConnection; AQuery, AResponse: TclDnsMessage): Boolean;
var
queryName: string;
recordType: Integer;
cacheEntry: TclDnsCacheEntry;
cachedResponse: TclDnsMessage;
begin
{$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'SearchCachedZone');{$ENDIF}
queryName := AQuery.Queries[0].Name;
recordType := AQuery.Queries[0].RecordType;
AResponse.Header.IsAuthoritativeAnswer := False;
if (not Server.UseCaching) then
begin
Result := False;
Exit;
end;
ClearResponseRecords(AResponse);
cacheEntry := nil;
cachedResponse := nil;
try
Server.DoGetCachedRecords(AConnection, queryName, recordType, cacheEntry);
if (cacheEntry <> nil) then
begin
if (cacheEntry.IsExpired(Server.MaxCacheTTL)) then
begin
Server.DoDeleteCachedRecords(AConnection, queryName, recordType);
cacheEntry.Free();
cacheEntry := nil;
end;
end;
if (cacheEntry = nil) then
begin
cachedResponse := ResolveCachedZone(AConnection, AQuery);
if ((cachedResponse.Answers.Count > 0) or (cachedResponse.NameServers.Count > 0)) then
begin
cacheEntry := TclDnsCacheEntry.Create();
cacheEntry.Load(cachedResponse);
cacheEntry.Name := queryName;
cacheEntry.RecordType := recordType;
Server.DoAddCachedRecords(AConnection, queryName, recordType, cacheEntry);
end;
end;
Result := (cacheEntry <> nil);
if Result then
begin
FillCachedResponse(cacheEntry, AResponse);
end;
finally
cachedResponse.Free();
cacheEntry.Free();
end;
{$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'SearchCachedZone'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'SearchCachedZone', E); raise; end; end;{$ENDIF}
end;
function TclDnsCommandInfo.SearchHandedZone(AConnection: TclUdpUserConnection;
const AQueryName: string; AResponse: TclDnsMessage): Boolean;
var
i, ind: Integer;
name: string;
records: TclDnsRecordList;
rec, soaRec: TclDnsRecord;
begin
{$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'SearchHandedZone');{$ENDIF}
ClearResponseRecords(AResponse);
records := TclDnsRecordList.Create();
try
Result := False;
name := AQueryName;
repeat
records.Clear();
Server.DoGetHandedRecords(AConnection, name, records);
if (records.Count > 0) then
begin
soaRec := records.ItemByType(DnsRecordTypes[rtSOARecord]);
AResponse.Header.IsAuthoritativeAnswer := (soaRec <> nil);
if (soaRec <> nil) then
begin
for i := 0 to records.Count - 1 do
begin
rec := records[i];
if SameText(rec.Name, AQueryName) then
begin
if (rec.RecordType = Code) then
begin
AResponse.Answers.Add(rec.Clone());
Result := True;
end else
if (rec is TclDnsCNAMERecord) then
begin
Result := SearchHandedZone(AConnection, TclDnsCNAMERecord(rec).PrimaryName, AResponse);
if (AResponse.Answers.Count > 0) then
begin
AResponse.Answers.Insert(0, rec.Clone());
end;
Exit;
end;
end;
end;
if (Result) then
begin
FillAdditionalRecords(records, AResponse);
end else
begin
AResponse.NameServers.Add(soaRec.Clone());
end;
end else
begin
for i := 0 to records.Count - 1 do
begin
rec := records[i];
if (rec is TclDnsNSRecord) then
begin
AResponse.NameServers.Add(rec.Clone());
AddARecord(TclDnsNSRecord(rec).NameServer, records, AResponse);
end;
end;
end;
Result := (AResponse.Answers.Count > 0) or (AResponse.NameServers.Count > 0);
Break;
end;
ind := Pos('.', name);
if (ind > 0) then
begin
Delete(name, 1, ind);
end else
begin
name := '';
end;
until (name = '');
finally
records.Free();
end;
{$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'SearchHandedZone'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'SearchHandedZone', E); raise; end; end;{$ENDIF}
end;
{ EclDnsServerError }
constructor EclDnsServerError.Create(AErrorCode: Integer; ADummy: Boolean);
begin
inherited Create(EclDnsError.GetMessageText(AErrorCode), AErrorCode);
end;
constructor EclDnsServerError.Create(const AErrorMsg: string; AErrorCode: Integer; ADummy: Boolean);
begin
inherited Create(AErrorMsg, AErrorCode);
end;
{ TclDnsACommandInfo }
constructor TclDnsACommandInfo.Create;
begin
inherited Create(DnsRecordTypes[rtARecord]);
end;
procedure TclDnsACommandInfo.FillAdditionalRecords(ARecords: TclDnsRecordList; AResponse: TclDnsMessage);
var
i: Integer;
rec: TclDnsRecord;
begin
for i := 0 to ARecords.Count - 1 do
begin
rec := ARecords[i];
if (rec is TclDnsNSRecord) then
begin
AResponse.NameServers.Add(rec.Clone());
AddARecord(TclDnsNSRecord(rec).NameServer, ARecords, AResponse);
end;
end;
end;
{ TclDnsNSCommandInfo }
constructor TclDnsNSCommandInfo.Create;
begin
inherited Create(DnsRecordTypes[rtNSRecord]);
end;
procedure TclDnsNSCommandInfo.FillAdditionalRecords(ARecords: TclDnsRecordList; AResponse: TclDnsMessage);
var
i: Integer;
rec: TclDnsRecord;
begin
for i := 0 to ARecords.Count - 1 do
begin
rec := ARecords[i];
if (rec is TclDnsNSRecord) then
begin
AddARecord(TclDnsNSRecord(rec).NameServer, ARecords, AResponse);
end;
end;
end;
{ TclDnsCNAMECommandInfo }
constructor TclDnsCNAMECommandInfo.Create;
begin
inherited Create(DnsRecordTypes[rtCNAMERecord]);
end;
procedure TclDnsCNAMECommandInfo.FillAdditionalRecords(ARecords: TclDnsRecordList; AResponse: TclDnsMessage);
var
i, j: Integer;
primaryName: string;
rec, respRec: TclDnsRecord;
begin
for i := 0 to AResponse.Answers.Count - 1 do
begin
respRec := AResponse.Answers[i];
if (respRec is TclDnsCNAMERecord) then
begin
primaryName := TclDnsCNAMERecord(respRec).PrimaryName;
if (ARecords.ItemByName(primaryName) <> nil) then
begin
for j := 0 to ARecords.Count - 1 do
begin
rec := ARecords[j];
if (rec is TclDnsNSRecord) then
begin
AResponse.NameServers.Add(rec.Clone());
AddARecord(TclDnsNSRecord(rec).NameServer, ARecords, AResponse);
end;
end;
end;
end;
end;
end;
{ TclDnsSOACommandInfo }
constructor TclDnsSOACommandInfo.Create;
begin
inherited Create(DnsRecordTypes[rtSOARecord]);
end;
procedure TclDnsSOACommandInfo.FillAdditionalRecords(ARecords: TclDnsRecordList; AResponse: TclDnsMessage);
var
soaRec: TclDnsRecord;
begin
soaRec := AResponse.Answers.ItemByType(DnsRecordTypes[rtSOARecord]);
if (soaRec <> nil) then
begin
AddARecord(TclDnsSOARecord(soaRec).PrimaryNameServer, ARecords, AResponse);
end;
end;
{ TclDnsPTRCommandInfo }
constructor TclDnsPTRCommandInfo.Create;
begin
inherited Create(DnsRecordTypes[rtPTRRecord]);
end;
procedure TclDnsPTRCommandInfo.FillAdditionalRecords(ARecords: TclDnsRecordList; AResponse: TclDnsMessage);
var
i: Integer;
rec: TclDnsRecord;
begin
for i := 0 to ARecords.Count - 1 do
begin
rec := ARecords[i];
if (rec is TclDnsNSRecord) then
begin
AResponse.NameServers.Add(rec.Clone());
AddARecord(TclDnsNSRecord(rec).NameServer, ARecords, AResponse);
end;
end;
end;
{ TclDnsMXCommandInfo }
constructor TclDnsMXCommandInfo.Create;
begin
inherited Create(DnsRecordTypes[rtMXRecord]);
end;
procedure TclDnsMXCommandInfo.FillAdditionalRecords(ARecords: TclDnsRecordList; AResponse: TclDnsMessage);
var
i: Integer;
rec: TclDnsRecord;
begin
for i := 0 to AResponse.Answers.Count - 1 do
begin
rec := AResponse.Answers[i];
if (rec is TclDnsMXRecord) then
begin
AddARecord(TclDnsMXRecord(rec).MailServer, ARecords, AResponse);
end;
end;
for i := 0 to ARecords.Count - 1 do
begin
rec := ARecords[i];
if (rec is TclDnsNSRecord) then
begin
AResponse.NameServers.Add(rec.Clone());
AddARecord(TclDnsNSRecord(rec).NameServer, ARecords, AResponse);
end;
end;
end;
{ TclDnsTXTCommandInfo }
constructor TclDnsTXTCommandInfo.Create;
begin
inherited Create(DnsRecordTypes[rtTXTRecord]);
end;
procedure TclDnsTXTCommandInfo.FillAdditionalRecords(ARecords: TclDnsRecordList; AResponse: TclDnsMessage);
var
i: Integer;
rec: TclDnsRecord;
begin
for i := 0 to ARecords.Count - 1 do
begin
rec := ARecords[i];
if (rec is TclDnsNSRecord) then
begin
AResponse.NameServers.Add(rec.Clone());
AddARecord(TclDnsNSRecord(rec).NameServer, ARecords, AResponse);
end;
end;
end;
{ TclDnsAAAACommandInfo }
constructor TclDnsAAAACommandInfo.Create;
begin
inherited Create(DnsRecordTypes[rtAAAARecord]);
end;
procedure TclDnsAAAACommandInfo.FillAdditionalRecords(
ARecords: TclDnsRecordList; AResponse: TclDnsMessage);
var
i: Integer;
rec: TclDnsRecord;
begin
for i := 0 to ARecords.Count - 1 do
begin
rec := ARecords[i];
if (rec is TclDnsNSRecord) then
begin
AResponse.NameServers.Add(rec.Clone());
AddARecord(TclDnsNSRecord(rec).NameServer, ARecords, AResponse);
end;
end;
end;
end.
|
unit clEnderecoAgente;
interface
uses
clEndereco, clConexao;
type
TEnderecoAgente = class(TEndereco)
private
function getCodigo: Integer;
function getSequencia: Integer;
function getTipo: String;
function getCorrespondencia: Integer;
procedure setCodigo(const Value: Integer);
procedure setSequencia(const Value: Integer);
procedure setTipo(const Value: String);
procedure setCorrespondencia(const Value: Integer);
constructor Create;
destructor Destroy;
protected
// declaração de atributos
_codigo: Integer;
_sequencia: Integer;
_tipo: String;
_correspondencia: Integer;
_conexao: TConexao;
public
// declaração das propriedades da classe, encapsulamento de atributos
property Codigo: Integer read getCodigo write setCodigo;
property Sequencia: Integer read getSequencia write setSequencia;
property Tipo: String read getTipo write setTipo;
property Correspondencia: Integer read getCorrespondencia
write setCorrespondencia;
// na linha acima antes do ponto e virgula (setCidade) pressione Ctrl + Shift + C
// para gerar os métodos acessores getter e setter automaticamente
// declaração de métodos
procedure MaxSeq;
function Validar(): Boolean;
function Merge(): Boolean;
function Delete(Filtro: String): Boolean;
function getObject(Id: String; Filtro: String): Boolean;
function Insert(): Boolean;
function Update(): Boolean;
function EnderecoJaExiste(): Boolean;
end;
const
TABLENAME = 'TBENDERECOSAGENTES';
implementation
uses SysUtils, Dialogs, udm, clUtil, ZDataset, ZAbstractRODataset, DB;
{ TEnderecoAgente }
constructor TEnderecoAgente.Create;
begin
_conexao := TConexao.Create;
if (not _conexao.VerifyConnZEOS(0)) then
begin
MessageDlg('Erro ao estabelecer conexão ao banco de dados (' +
Self.ClassName + ') !', mtError, [mbCancel], 0);
end;
end;
destructor TEnderecoAgente.Destroy;
begin
_conexao.Free;
end;
function TEnderecoAgente.getCodigo: Integer;
begin
Result := _codigo;
end;
function TEnderecoAgente.getSequencia: Integer;
begin
Result := _sequencia;
end;
function TEnderecoAgente.getTipo: String;
begin
Result := _tipo;
end;
function TEnderecoAgente.getCorrespondencia: Integer;
begin
Result := _correspondencia;
end;
function TEnderecoAgente.Delete(Filtro: String): Boolean;
begin
try
Result := False;
with dm.QryCRUD do
begin
Close;
SQL.Clear;
SQL.Add('DELETE FROM ' + TABLENAME);
if Filtro = 'CODIGO' then
begin
SQL.Add('WHERE COD_AGENTE =:CODIGO');
ParamByName('CODIGO').AsInteger := Self.Codigo;
end
else if Filtro = 'TIPO' then
begin
SQL.Add('WHERE COD_AGENTE =:CODIGO AND DES_TIPO = :TIPO');
ParamByName('CODIGO').AsInteger := Self.Codigo;
ParamByName('TIPO').AsString := Self.Tipo;
end;
if not(dm.ZConn.Ping) then
begin
dm.ZConn.PingServer;
end;
ExecSQL;
end;
dm.QryCRUD.Close;
dm.QryCRUD.SQL.Clear;
Result := True;
Except
on E: Exception do
ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' +
E.Message);
end;
end;
function TEnderecoAgente.getObject(Id, Filtro: String): Boolean;
begin
try
Result := False;
if TUtil.Empty(Id) then
Exit;
with dm.QryGetObject do
begin
Close;
SQL.Clear;
SQL.Add('SELECT * FROM ' + TABLENAME);
if Filtro = 'TIPO' then
begin
SQL.Add(' WHERE COD_AGENTE =:CODIGO AND DES_TIPO =:TIPO');
ParamByName('CODIGO').AsInteger := Self.Codigo;
ParamByName('TIPO').AsString := Id;
end
else if Filtro = 'CODIGO' then
begin
SQL.Add(' WHERE COD_AGENTE = :CODIGO');
ParamByName('CODIGO').AsInteger := StrToInt(Id);
end;
if not(dm.ZConn.Ping) then
begin
dm.ZConn.PingServer;
end;
Open;
if not IsEmpty then
begin
First;
Self.Codigo := dm.QryGetObject.FieldByName('COD_AGENTE').AsInteger;
Self.Sequencia := dm.QryGetObject.FieldByName('SEQ_ENDERECO').AsInteger;
Self.Tipo := dm.QryGetObject.FieldByName('DES_TIPO').AsString;
Self.Endereco := dm.QryGetObject.FieldByName('DES_LOGRADOURO').AsString;
Self.Numero := dm.QryGetObject.FieldByName('NUM_LOGRADOURO').AsString;
Self.Complemento := dm.QryGetObject.FieldByName
('DES_COMPLEMENTO').AsString;
Self.Bairro := dm.QryGetObject.FieldByName('DES_BAIRRO').AsString;
Self.Cidade := dm.QryGetObject.FieldByName('NOM_CIDADE').AsString;
Self.Cep := dm.QryGetObject.FieldByName('NUM_CEP').AsString;
Self.Referencia := dm.QryGetObject.FieldByName
('DES_REFERENCIA').AsString;
Self.UF := dm.QryGetObject.FieldByName('UF_ESTADO').AsString;
Self.Correspondencia := dm.QryGetObject.FieldByName
('DOM_CORRESPONDENCIA').AsInteger;
end
else
begin
Close;
SQL.Clear;
Exit;
end;
end;
Result := True;
Except
on E: Exception do
ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' +
E.Message);
end;
end;
function TEnderecoAgente.Insert(): Boolean;
begin
try
Result := False;
MaxSeq;
with dm.QryCRUD do
begin
Close;
SQL.Clear;
SQL.Text := 'INSERT INTO ' + TABLENAME + ' ( ' + 'COD_AGENTE, ' +
'SEQ_ENDERECO, ' + 'DES_TIPO, ' + 'DOM_CORRESPONDENCIA, ' +
'DES_LOGRADOURO, ' + 'NUM_LOGRADOURO, ' + 'DES_COMPLEMENTO, ' +
'DES_BAIRRO, ' + 'NOM_CIDADE, ' + 'UF_ESTADO, ' + 'NUM_CEP, ' +
'DES_REFERENCIA ' + ') ' + 'VALUES(' + ':CODIGO, ' + ':SEQUENCIA, ' +
':TIPO, ' + ':CORRESPONDENCIA, ' + ':ENDERECO, ' + ':NUMERO, ' +
':COMPLEMENTO, ' + ':BAIRRO, ' + ':CIDADE, ' + ':UF, ' + ':CEP, ' +
':REFERENCIA ' + ') ';
ParamByName('CODIGO').AsInteger := Self.Codigo;
ParamByName('SEQUENCIA').AsInteger := Self.Sequencia;
ParamByName('TIPO').AsString := Self.Tipo;
ParamByName('CORRESPONDENCIA').AsInteger := Self.Correspondencia;
ParamByName('ENDERECO').AsString := Self.Endereco;
ParamByName('NUMERO').AsString := Self.Numero;
ParamByName('COMPLEMENTO').AsString := Self.Complemento;
ParamByName('BAIRRO').AsString := Self.Bairro;
ParamByName('CIDADE').AsString := Self.Cidade;
ParamByName('UF').AsString := Self.UF;
ParamByName('CEP').AsString := Self.Cep;
ParamByName('REFERENCIA').AsString := Self.Referencia;
if not(dm.ZConn.Ping) then
begin
dm.ZConn.PingServer;
end;
ExecSQL;
end;
dm.QryCRUD.Close;
dm.QryCRUD.SQL.Clear;
Result := True;
Except
on E: Exception do
ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' +
E.Message);
end;
end;
function TEnderecoAgente.Merge: Boolean;
begin
// nada implementado aqui, INSERT e UPDATE executados diretamente
// o modificador de acesso deste método pode ser definido como private!
// ou sua declaração pode ser até mesmo removida,
// não foi removida para manter a padronização de código.
Result := False;
end;
function TEnderecoAgente.Update(): Boolean;
begin
try
Result := False;
with dm.QryCRUD do
begin
Close;
SQL.Clear;
SQL.Text := 'UPDATE ' + TABLENAME + ' SET ' + 'DES_TIPO = :TIPO, ' +
'DOM_CORRESPONDENCIA = :CORRESPONDENCIA, ' +
'DES_LOGRADOURO = :ENDERECO, ' + 'NUM_LOGRADOURO = :NUMERO, ' +
'DES_COMPLEMENTO = :COMPLEMENTO, ' + 'DES_BAIRRO = :BAIRRO, ' +
'NOM_CIDADE = :CIDADE, ' + 'UF_ESTADO = :UF, ' + 'NUM_CEP = :CEP, ' +
'DES_REFERENCIA = :REFERENCIA ' +
'WHERE COD_AGENTE = :CODIGO AND SEQ_ENDERECO = :SEQUENCIA';
ParamByName('CODIGO').AsInteger := Self.Codigo;
ParamByName('SEQUENCIA').AsInteger := Self.Sequencia;
ParamByName('TIPO').AsString := Self.Tipo;
ParamByName('CORRESPONDENCIA').AsInteger := Self.Correspondencia;
ParamByName('ENDERECO').AsString := Self.Endereco;
ParamByName('NUMERO').AsString := Self.Numero;
ParamByName('COMPLEMENTO').AsString := Self.Complemento;
ParamByName('BAIRRO').AsString := Self.Bairro;
ParamByName('CIDADE').AsString := Self.Cidade;
ParamByName('UF').AsString := Self.UF;
ParamByName('CEP').AsString := Self.Cep;
ParamByName('REFERENCIA').AsString := Self.Referencia;
if not(dm.ZConn.Ping) then
begin
dm.ZConn.PingServer;
end;
ExecSQL;
end;
dm.QryCRUD.Close;
dm.QryCRUD.SQL.Clear;
Result := True;
Except
on E: Exception do
ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' +
E.Message);
end;
end;
function TEnderecoAgente.Validar: Boolean;
begin
// Na validação de dados podemos colocar qualquer atributo para ser validado
// codigo abaixo deve ser customizado por cada leitor!
Result := True;
end;
function TEnderecoAgente.EnderecoJaExiste(): Boolean;
begin
try
Result := False;
with dm.QryGetObject do
begin
Close;
SQL.Clear;
SQL.Add('SELECT * FROM ' + TABLENAME);
SQL.Add(' WHERE COD_AGENTE = :CODIGO AND DES_TIPO = :TIPO');
ParamByName('CODIGO').AsInteger := Self.Codigo;
ParamByName('TIPO').AsString := Self.Tipo;
if not(dm.ZConn.Ping) then
begin
dm.ZConn.PingServer;
end;
Open;
if not(IsEmpty) then
Result := True;
end;
dm.QryGetObject.Close;
dm.QryGetObject.SQL.Clear;
Except
on E: Exception do
ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' +
E.Message);
end;
end;
procedure TEnderecoAgente.MaxSeq;
begin
Try
with dm.QryGetObject do
begin
Close;
SQL.Clear;
SQL.Text := 'SELECT MAX(SEQ_ENDERECO) AS SEQUENCIA FROM ' + TABLENAME +
' WHERE COD_AGENTE = :CODIGO';
ParamByName('CODIGO').AsInteger := Self.Codigo;
if not(dm.ZConn.Ping) then
begin
dm.ZConn.PingServer;
end;
Open;
if not(IsEmpty) then
First;
end;
Self.Sequencia := (dm.QryGetObject.FieldByName('SEQUENCIA').AsInteger) + 1;
dm.QryGetObject.Close;
dm.QryGetObject.SQL.Clear;
Except
on E: Exception do
ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' +
E.Message);
end;
end;
procedure TEnderecoAgente.setCodigo(const Value: Integer);
begin
_codigo := Value;
end;
procedure TEnderecoAgente.setTipo(const Value: String);
begin
_tipo := Value;
end;
procedure TEnderecoAgente.setSequencia(const Value: Integer);
begin
_sequencia := Value;
end;
procedure TEnderecoAgente.setCorrespondencia(const Value: Integer);
begin
_correspondencia := Value;
end;
end.
|
unit IPersist;
interface
uses
System.Variants, System.Classes, db, System.SysUtils, DBTables, FireDAC.Stan.Intf, FireDAC.Stan.Option,
FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async,
FireDAC.Phys, FireDAC.Phys.FB, FireDAC.Phys.FBDef, FireDAC.VCLUI.Wait, FireDAC.Comp.Client, FireDAC.Stan.Param, FireDAC.Dapt;
type
TTableEvent = procedure(Sender : TObject; var CanExecute : Boolean) of Object;
TMyFieldType = (ftString, ftMemo, ftFloat, ftData, ftInteger, ftUnknow);
TPK = array of string;
IField = interface
['{B9C38549-2E2D-46BA-8CA8-EFEFAA563AC3}']
function GetName : string;
function GetValue : Variant;
function GetFieldType : TMyFieldType;
function GetIsPk : Boolean;
function GetString : string;
function GetFloat : Double;
function GetDate : TDateTime;
function GetInteger : Integer;
function GetAsValue : Variant;
function GetIsModified: Boolean;
procedure SetName(AName : string);
procedure SetValue(AValue : Variant);
procedure SetFieldType(AFieldType : TMyFieldType);
procedure SetIsPk(AIsPk : Boolean);
procedure SetString(AString : string);
procedure SetFloat(AFloat : Double);
procedure SetDate(ADate : TDateTime);
procedure SetInteger(AInteger : Integer);
procedure SetAsValue(AValue : Variant);
property Name: String read GetName write SetName;
property FieldType: TMyFieldType read GetFieldType write SetFieldType;
property IsPk: Boolean read GetIsPK write SetIsPk;
property IsModified: Boolean read GetIsModified;
property asString : string read GetString write SetString;
property asFloat : Double read GetFloat write SetFloat;
property asDate : TDateTime read GetDate write SetDate;
property asInteger : Integer read GetInteger write SetInteger;
property asValue : Variant read GetAsValue write SetAsValue;
end;
ITable = interface
['{F28A59FB-4649-4BD5-8C15-8D1542ECE948}']
function GetTableName: String;
function GetIFields(index : Integer): IFIeld;
function FieldCount: Integer;
function FieldByName(AName : string): IField;
function GetLog: Boolean;
function GetFileLog: string;
function Insert(): Integer;
function Update(): Integer;
function Delete(): Integer;
function Select(AFields : string): Boolean;
function GetOnBeforeInsert: TTableEvent;
function GetOnBeforeUpdate: TTableEvent;
function GetOnBeforeDelete: TTableEvent;
procedure SetTableName(ATableName : string);
procedure SetLog(AValue : Boolean);
procedure SetFileLog(AFileLog : string);
procedure SetOnBeforeInsert(AValue : TTableEvent);
procedure SetOnBeforeUpdate(AValue : TTableEvent);
procedure SetOnBeforeDelete(AValue : TTableEvent);
property TableName : string read GetTableName write SetTableName;
property Fields[index : Integer] : IField read GetIFIelds;
property UseLog : Boolean read GetLog write SetLog;
property FileLog : string read GetFileLog write SetFileLog;
property OnBeforeInsert : TTableEvent read GetOnBeforeInsert write SetOnBeforeInsert;
property OnBeforeUpdate : TTableEvent read GetOnBeforeUpdate write SetOnBeforeUpdate;
property OnBeforeDelete : TTableEvent read GetOnBeforeDelete write SetOnBeforeDelete;
end;
//****************************Classes********************************************************
TUtil = class
class function VarToDateTime(AValue : Variant): TDateTime;
class function VarToString(AValue : Variant): String;
class function VarToInteger(AValue : Variant): Integer;
class function VarToFloat(AValue : Variant): Double;
class function FieldTypeToMyFieldType(AValue: TFieldType): TMyFieldType;
class function MyFieldTypeToStr(AField : TMyFieldType) : string;
class function GetInterfaceByPointer(APoiter : IUnknown) : Pointer;
class procedure ReleaseInterfaceByPointer(APointer : Pointer);
end;
TField = class(TInterfacedObject, IFIeld)
private
FName: String;
FFieldType: TMyFieldType;
FIsPk: Boolean;
FValue: Variant;
FIsModified : Boolean;
protected
function GetName : string; virtual;
function GetValue : Variant; virtual;
function GetFieldType : TMyFieldType; virtual;
function GetIsPk : Boolean; virtual;
function GetString : string; virtual;
function GetFloat : Double; virtual;
function GetDate : TDateTime; virtual;
function GetInteger : Integer; virtual;
function GetAsValue : Variant; virtual;
function GetIsModified: Boolean;
procedure SetName(AName : string); virtual;
procedure SetValue(AValue : Variant); virtual;
procedure SetFieldType(AFieldType : TMyFieldType); virtual;
procedure SetIsPk(AIsPk : Boolean); virtual;
procedure SetString(AString : string); virtual;
procedure SetFloat(AFloat : Double); virtual;
procedure SetDate(ADate : TDateTime); virtual;
procedure SetInteger(AInteger : Integer); virtual;
procedure SetAsValue(AValue : Variant); virtual;
public
constructor Create(AName: string; AFieldType : TMyFieldType; AIsPk : Boolean);
end;
TTable = class(TInterfacedObject, ITable)
private
FConnection : TFDConnection;
FTableName : string;
FList : TList;
FPK : Array of string;
FLog : Boolean;
FFileLog : string;
FOnBeforeDelete: TTableEvent;
FOnBeforeUpdate: TTableEvent;
FOnBeforeInsert: TTableEvent;
function hasFieldModified():Boolean;
procedure doFreeList;
protected
function GetTableName: String; virtual;
function GetIFields(index : Integer): IFIeld; virtual;
function FieldCount(): Integer; virtual;
function FieldByName(AFieldName : string): IField; virtual;
function IsPk(AField : String):Boolean;
function GetLog : Boolean;
function GetFileLog: string;
function GetOnBeforeInsert: TTableEvent;
function GetOnBeforeUpdate: TTableEvent;
function GetOnBeforeDelete: TTableEvent;
procedure SetTableName(ATableName : string); virtual;
procedure doLoadFields; virtual;
procedure doCopyPk(LPk : array of string);
procedure SetLog(AValue : Boolean);
procedure SetFileLog(AFileLog : string);
procedure SetOnBeforeInsert(AValue : TTableEvent);
procedure SetOnBeforeUpdate(AValue : TTableEvent);
procedure SetOnBeforeDelete(AValue : TTableEvent);
public
function Insert(): Integer;
function Update(): Integer;
function Delete(): Integer;
function Select(AFields : string): Boolean;
constructor Create(AConnection : TFDConnection ; ATableName : string; LPk : array of String);
destructor Destroy; override;
end;
implementation
{ TField }
constructor TField.Create(AName: string; AFieldType : TMyFieldType; AIsPk : Boolean);
begin
inherited Create;
if (AFieldType = IPersist.ftUnknow) then
raise Exception.Create('Tipo de campo ['+AName+'] inválido');
FName := AName;
FFieldType := AFieldType;
FIsPk := AIsPk;
FValue := null;
FIsModified := False;
end;
function TField.GetAsValue: Variant;
begin
Result := FValue;
end;
function TField.GetDate: TDateTime;
begin
Result := TUtil.VarToDateTime(FValue);
end;
function TField.GetFieldType: TMyFieldType;
begin
Result := FFieldType;
end;
function TField.GetFloat: Double;
begin
Result := TUtil.VarToFloat(FValue);
end;
function TField.GetInteger: Integer;
begin
Result := TUtil.VarToInteger(FValue);
end;
function TField.GetIsModified: Boolean;
begin
Result := FIsModified;
end;
function TField.GetIsPk: Boolean;
begin
Result := FIsPk;
end;
function TField.GetName: string;
begin
Result := UpperCase(FName);
end;
function TField.GetString: string;
begin
Result := TUtil.VarToString(FValue);
end;
function TField.GetValue: Variant;
begin
Result := FValue;
end;
procedure TField.SetAsValue(AValue: Variant);
begin
if AValue <> FValue then
begin
FValue := AValue;
FIsModified := True;
end;
end;
procedure TField.SetDate(ADate: TDateTime);
begin
if ADate <> FValue then
begin
FValue := ADate;
FIsModified := True;
end;
end;
procedure TField.SetFieldType(AFieldType: TMyFieldType);
begin
FFieldType := AFieldType;
end;
procedure TField.SetFloat(AFloat: Double);
begin
if AFloat <> FValue then
begin
FValue := AFloat;
FIsModified := True;
end;
end;
procedure TField.SetInteger(AInteger: Integer);
begin
if AInteger <> FValue then
begin
FValue := AInteger;
FIsModified := True;
end;
end;
procedure TField.SetIsPk(AIsPk: Boolean);
begin
FIsPk := AIsPk;
end;
procedure TField.SetName(AName: string);
begin
FName := UpperCase(AName);
end;
procedure TField.SetString(AString: string);
begin
if AString <> FValue then
begin
FValue := AString;
FIsModified := True;
end;
end;
procedure TField.SetValue(AValue: Variant);
begin
if AValue <> FValue then
begin
FValue := AValue;
FIsModified := True;
end;
end;
{ TConvert }
class function TUtil.FieldTypeToMyFieldType(AValue: TFieldType): TMyFieldType;
begin
Result := IPersist.ftUnknow;
case AValue of
db.ftString: Result := IPersist.ftString;
db.ftSmallint,
db.ftInteger,
db.ftWord,
db.ftLargeint: Result := IPersist.ftInteger;
db.ftFloat,
db.ftCurrency,
db.ftBCD: Result := IPersist.ftFloat;
db.ftDate,
db.ftTime,
db.ftDateTime,
db.ftTimeStamp: Result := IPersist.ftData;
db.ftBlob,
db.ftMemo,
db.ftFmtMemo: Result := IPersist.ftMemo;
end;
end;
class function TUtil.GetInterfaceByPointer(APoiter: IInterface): Pointer;
begin
APoiter._AddRef;
Result := Pointer(APoiter);
end;
class function TUtil.MyFieldTypeToStr(AField: TMyFieldType): string;
begin
end;
class procedure TUtil.ReleaseInterfaceByPointer(APointer: Pointer);
var
I: IUnknown;
begin
Pointer(I) := APointer;
end;
class function TUtil.VarToDateTime(AValue: Variant): TDateTime;
begin
try
Result := System.Variants.VarToDateTime(AValue);
except
Result := 0;
end;
end;
class function TUtil.VarToFloat(AValue: Variant): Double;
begin
try
Result := AValue;
except
Result := 0;
end;
end;
class function TUtil.VarToInteger(AValue: Variant): Integer;
begin
try
Result := AValue;
except
Result := 0;
end;
end;
class function TUtil.VarToString(AValue: Variant): String;
begin
try
Result := System.Variants.VarToStr(AValue);
except
Result := '';
end;
end;
{ TTable }
constructor TTable.Create(AConnection : TFDConnection ; ATAbleName : string; LPk : array of String);
begin
inherited Create;
FConnection := AConnection;
FTableName := ATAbleName;
FList := TList.Create;
FLog := False;
doCopyPK(LPk);
doLoadFields;
end;
function TTable.Delete: Integer;
var
LQuery : TFDQuery;
I : Integer;
LFieldName : string;
LFieldValue : Variant;
LSeparador : String;
LCanExecute : Boolean;
begin
Result := 0;
try
LQuery := TFDQuery.Create(nil);
try
if hasFieldModified then
begin
LQuery.Connection := FConnection;
LQuery.SQL.Add(' DELETE FROM '+FTableName);
LQuery.SQL.Add(' WHERE ');
LSeparador := '';
for I := 0 to FieldCount - 1 do
if GetIFields(I).IsPk then
begin
LFieldName := GetIFields(I).Name;
LQuery.SQL.Add(LSeparador + LFieldName + ' = :'+LFieldName);
LSeparador := ' AND ';
end;
//Param List
LSeparador := '';
for I := 0 to FieldCount - 1 do
if GetIFields(I).IsPk then
begin
LFieldName := GetIFields(I).Name;
LFieldValue := GetIFields(I).AsValue;
case GetIFields(I).FieldType of
ftString :
begin
LQuery.ParamByName(LFieldName).DataType := db.ftString;
LQuery.ParamByName(LFieldName).Value := LFieldValue;
end;
ftMemo:
begin
LQuery.ParamByName(LFieldName).DataType := db.ftMemo;
LQuery.ParamByName(LFieldName).Value := LFieldValue;
end;
ftFloat:
begin
LQuery.ParamByName(LFieldName).DataType := db.ftFloat;
LQuery.ParamByName(LFieldName).Value := LFieldValue;
end;
ftData:
begin
if GetIFields(I).asDate = 0 then
LFieldValue := null
else
LFieldValue := GetIFields(I).asDate;
LQuery.ParamByName(LFieldName).DataType := db.ftDate;
LQuery.ParamByName(LFieldName).Value := LFieldValue;
end;
ftInteger:
begin
LQuery.ParamByName(LFieldName).DataType := db.ftInteger;
LQuery.ParamByName(LFieldName).Value := LFieldValue;
end;
ftUnknow:
else
raise Exception.Create('Campo: ' + LFieldName +' com tipo de dado não esperado.');
end;
end;
end else
Exit;
if ITable(Self).UseLog then
begin
if Trim(ITable(Self).FileLog) = '' then
raise Exception.Create('FileLog não pode ser vazio');
LQuery.SQL.SaveToFile(ITable(Self).FileLog);
end;
LCanExecute := True;
//Verifica se o evento foi programado
if Assigned(FOnBeforeDelete) then
FOnBeforeDelete(Self, LCanExecute);
if not(LCanExecute) then
raise Exception.Create('Processo interrompido pelo usuário');
LQuery.ExecSQL;
Result := LQuery.RowsAffected;
finally
LQuery.Close;
end;
except
on E : Exception do
raise Exception.Create(E.Message + ' on TTable.Update.');
end;
end;
destructor TTable.Destroy;
begin
doFreeList;
inherited;
end;
procedure TTable.doCopyPk(LPk: array of string);
var
LTam,
LCount : Integer;
begin
LTam := High(LPk);
SetLength(FPk, LTam + 1);
for LCount := Low(LPk) to LTam do
FPK[LTam] := LPk[LCount];
end;
procedure TTable.doFreeList;
var
I : Integer;
begin
for I := FList.Count - 1 downto 0 do
begin
TUtil.ReleaseInterfaceByPointer(FList[I]);
FList[I] := nil;
end;
FList.Pack;
FList.Free;
end;
procedure TTable.doLoadFields;
var
LQuery : TFDQuery;
I : Integer;
LField : IField;
begin
LQuery := TFDQuery.Create(nil);
try
LQuery.Connection := FConnection;
LQuery.SQL.Clear;
LQuery.SQL.Add('SELECT * FROM ' + ITable(Self).TableName + ' WHERE 1 = 2');
LQuery.Open;
for I := 0 to LQuery.FieldCount - 1 do
begin
LField := TField.Create(LQuery.Fields[I].FieldName, TUtil.FieldTypeToMyFieldType(LQuery.Fields[I].DataType),
IsPk(LQuery.Fields[I].FieldName));
FList.Add(TUtil.GetInterfaceByPointer(LField));
end;
finally
LQuery.Close;
LQuery.Free;
end;
end;
function TTable.FieldByName(AFieldName: string): IField;
var
I : Integer;
begin
Result := nil;
AFieldName := UpperCase(AFieldName);
for I := 0 to FieldCount - 1 do
if ITable(Self).Fields[I].Name = AFieldName then
begin
Result := ITable(Self).Fields[I];
Break;
end;
end;
function TTable.FieldCount: Integer;
begin
Result := FList.Count;
end;
function TTable.GetFileLog: string;
begin
Result := FFileLog;
end;
function TTable.GetIFields(index: Integer): IFIeld;
begin
if index < 0 then
raise Exception.Create('Indice fora da lista');
if index > (FList.Count - 1) then
raise Exception.Create('Indice fora da lista');
Result := IUnknown(FList.Items[index]) as IFIeld;
end;
function TTable.GetLog: Boolean;
begin
Result := FLog;
end;
function TTable.GetOnBeforeDelete: TTableEvent;
begin
Result := FOnBeforeDelete;
end;
function TTable.GetOnBeforeInsert: TTableEvent;
begin
Result := FOnBeforeInsert;
end;
function TTable.GetOnBeforeUpdate: TTableEvent;
begin
Result := FOnBeforeUpdate;
end;
function TTable.GetTableName: String;
begin
Result := FTableName;
end;
function TTable.hasFieldModified: Boolean;
var
I : Integer;
begin
Result := false;
for I := 0 to FieldCount - 1 do
begin
if GetIFields(I).IsModified then
begin
Result := True;
Break;
end;
end;
end;
function TTable.Insert: Integer;
var
LQuery : TFDQuery;
I : Integer;
LFieldName : string;
LFieldValue : Variant;
LSeparador : String;
LCanExecute : Boolean;
begin
Result := 0;
try
LQuery := TFDQuery.Create(nil);
try
if hasFieldModified then
begin
LQuery.Connection := FConnection;
LQuery.SQL.Add(' INSERT INTO '+FTableName);
LQuery.SQL.Add(' (');
LSeparador := '';
//Fields
for I := 0 to FieldCount - 1 do
if GetIFields(I).IsModified then
begin
LFieldName := GetIFields(I).Name;
LQuery.SQL.Add(LSeparador + LFieldName);
LSeparador := ',';
end;
LQuery.SQL.Add(' )');
//Values
LQuery.SQL.Add(' VALUES');
LQuery.SQL.Add(' (');
LSeparador := '';
for I := 0 to FieldCount - 1 do
if GetIFields(I).IsModified then
begin
LFieldName := GetIFields(I).Name;
LQuery.SQL.Add(LSeparador +':'+ LFieldName);
LSeparador := ',';
end;
LQuery.SQL.Add(' )');
//Param List
LSeparador := '';
for I := 0 to FieldCount - 1 do
if GetIFields(I).IsModified then
begin
LFieldName := GetIFields(I).Name;
LFieldValue := GetIFields(I).AsValue;
case GetIFields(I).FieldType of
ftString :
begin
LQuery.ParamByName(LFieldName).DataType := db.ftString;
LQuery.ParamByName(LFieldName).Value := LFieldValue;
end;
ftMemo:
begin
LQuery.ParamByName(LFieldName).DataType := db.ftMemo;
LQuery.ParamByName(LFieldName).Value := LFieldValue;
end;
ftFloat:
begin
LQuery.ParamByName(LFieldName).DataType := db.ftFloat;
LQuery.ParamByName(LFieldName).Value := LFieldValue;
end;
ftData:
begin
if GetIFields(I).asDate = 0 then
LFieldValue := null
else
LFieldValue := GetIFields(I).asDate;
LQuery.ParamByName(LFieldName).DataType := db.ftDate;
LQuery.ParamByName(LFieldName).Value := LFieldValue;
end;
ftInteger:
begin
LQuery.ParamByName(LFieldName).DataType := db.ftInteger;
LQuery.ParamByName(LFieldName).Value := LFieldValue;
end;
ftUnknow:
else
raise Exception.Create('Campo: ' + LFieldName +' com tipo de dado não esperado.');
end;
end;
end else
Exit;
if ITable(Self).UseLog then
begin
if Trim(ITable(Self).FileLog) = '' then
raise Exception.Create('FileLog não pode ser vazio');
LQuery.SQL.SaveToFile(ITable(Self).FileLog);
end;
LCanExecute := True;
//Verifica se o evento foi programado
if Assigned(FOnBeforeInsert) then
FOnBeforeInsert(Self, LCanExecute);
if not(LCanExecute) then
raise Exception.Create('Processo interrompido pelo usuário');
LQuery.ExecSQL;
Result := LQuery.RowsAffected;
finally
LQuery.Close;
end;
except
on E : Exception do
raise Exception.Create(E.Message + ' on TTable.Insert.');
end;
end;
function TTable.IsPk(AField: String): Boolean;
var
I : Integer;
begin
AField := UpperCase(AField);
Result := False;
for I := Low(FPk) to High(FPk) do
if UpperCase(FPk[I]) = AField then
begin
Result := True;
Break;
end;
end;
function TTable.Select(AFields: string): Boolean;
var
LQuery : TFDQuery;
I : Integer;
LFieldName : string;
LFieldValue : Variant;
LSeparador : String;
begin
Result := False;
try
LQuery := TFDQuery.Create(nil);
try
LQuery.Connection := FConnection;
LQuery.SQL.Add(' SELECT '+AFields+' FROM '+GetTableName);
LQuery.SQL.Add(' WHERE ');
LSeparador := '';
for I := 0 to FieldCount - 1 do
if GetIFields(I).IsPk then
begin
LFieldName := GetIFields(I).Name;
LQuery.SQL.Add(LSeparador + LFieldName + ' = :'+LFieldName);
LSeparador := ' AND ';
end;
//Param List
LSeparador := '';
for I := 0 to FieldCount - 1 do
if GetIFields(I).IsModified or GetIFields(I).IsPk then
begin
LFieldName := GetIFields(I).Name;
LFieldValue := GetIFields(I).AsValue;
case GetIFields(I).FieldType of
ftString :
begin
LQuery.ParamByName(LFieldName).DataType := db.ftString;
LQuery.ParamByName(LFieldName).Value := LFieldValue;
end;
ftMemo:
begin
LQuery.ParamByName(LFieldName).DataType := db.ftMemo;
LQuery.ParamByName(LFieldName).Value := LFieldValue;
end;
ftFloat:
begin
LQuery.ParamByName(LFieldName).DataType := db.ftFloat;
LQuery.ParamByName(LFieldName).Value := LFieldValue;
end;
ftData:
begin
if GetIFields(I).asDate = 0 then
LFieldValue := null
else
LFieldValue := GetIFields(I).asDate;
LQuery.ParamByName(LFieldName).DataType := db.ftDate;
LQuery.ParamByName(LFieldName).Value := LFieldValue;
end;
ftInteger:
begin
LQuery.ParamByName(LFieldName).DataType := db.ftInteger;
LQuery.ParamByName(LFieldName).Value := LFieldValue;
end;
ftUnknow:
else
raise Exception.Create('Campo: ' + LFieldName +' com tipo de dado não esperado.');
end;
end;
if ITable(Self).UseLog then
begin
if Trim(ITable(Self).FileLog) = '' then
raise Exception.Create('FileLog não pode ser vazio');
LQuery.SQL.SaveToFile(ITable(Self).FileLog);
end;
LQuery.Open;
Result := not(LQuery.IsEmpty);
for I := 0 to LQuery.FieldCount - 1 do
begin
FieldByName(LQuery.Fields[I].FieldName).asValue := null;
if Result then
FieldByName(LQuery.Fields[I].FieldName).asValue := LQuery.Fields[I].Value;
end;
finally
LQuery.Close;
end;
except
on E : Exception do
raise Exception.Create(E.Message + ' on TTable.Select.');
end;
end;
procedure TTable.SetFileLog(AFileLog: string);
begin
FFileLog := AFileLog;
end;
procedure TTable.SetLog(AValue: Boolean);
begin
FLog := AValue;
end;
procedure TTable.SetOnBeforeDelete(AValue: TTableEvent);
begin
FOnBeforeDelete := AValue;
end;
procedure TTable.SetOnBeforeInsert(AValue: TTableEvent);
begin
FOnBeforeInsert := AValue;
end;
procedure TTable.SetOnBeforeUpdate(AValue: TTableEvent);
begin
FOnBeforeUpdate := AValue;
end;
procedure TTable.SetTableName(ATableName: string);
begin
FTableName := ATableName;
end;
function TTable.Update: Integer;
var
LQuery : TFDQuery;
I : Integer;
LFieldName : string;
LFieldValue : Variant;
LSeparador : String;
LCanExecute : Boolean;
begin
Result := 0;
try
LQuery := TFDQuery.Create(nil);
try
if hasFieldModified then
begin
LQuery.Connection := FConnection;
LQuery.SQL.Add(' UPDATE '+FTableName);
LQuery.SQL.Add(' SET');
LSeparador := '';
//Fields
for I := 0 to FieldCount - 1 do
if (GetIFields(I).IsModified) and not(GetIFields(I).IsPk) then
begin
LFieldName := GetIFields(I).Name;
LQuery.SQL.Add(LSeparador + LFieldName + ' = :'+LFieldName);
LSeparador := ',';
end;
LQuery.SQL.Add(' WHERE ');
LSeparador := '';
for I := 0 to FieldCount - 1 do
if GetIFields(I).IsPk then
begin
LFieldName := GetIFields(I).Name;
LQuery.SQL.Add(LSeparador + LFieldName + ' = :'+LFieldName);
LSeparador := ' AND ';
end;
//Param List
LSeparador := '';
for I := 0 to FieldCount - 1 do
if GetIFields(I).IsModified or GetIFields(I).IsPk then
begin
LFieldName := GetIFields(I).Name;
LFieldValue := GetIFields(I).AsValue;
case GetIFields(I).FieldType of
ftString :
begin
LQuery.ParamByName(LFieldName).DataType := db.ftString;
LQuery.ParamByName(LFieldName).Value := LFieldValue;
end;
ftMemo:
begin
LQuery.ParamByName(LFieldName).DataType := db.ftMemo;
LQuery.ParamByName(LFieldName).Value := LFieldValue;
end;
ftFloat:
begin
LQuery.ParamByName(LFieldName).DataType := db.ftFloat;
LQuery.ParamByName(LFieldName).Value := LFieldValue;
end;
ftData:
begin
if GetIFields(I).asDate = 0 then
LFieldValue := null
else
LFieldValue := GetIFields(I).asDate;
LQuery.ParamByName(LFieldName).DataType := db.ftDate;
LQuery.ParamByName(LFieldName).Value := LFieldValue;
end;
ftInteger:
begin
LQuery.ParamByName(LFieldName).DataType := db.ftInteger;
LQuery.ParamByName(LFieldName).Value := LFieldValue;
end;
ftUnknow:
else
raise Exception.Create('Campo: ' + LFieldName +' com tipo de dado não esperado.');
end;
end;
end else
Exit;
if ITable(Self).UseLog then
begin
if Trim(ITable(Self).FileLog) = '' then
raise Exception.Create('FileLog não pode ser vazio');
LQuery.SQL.SaveToFile(ITable(Self).FileLog);
end;
LCanExecute := True;
//Verifica se o evento foi programado
if Assigned(FOnBeforeUpdate) then
FOnBeforeUpdate(Self, LCanExecute);
if not(LCanExecute) then
raise Exception.Create('Processo interrompido pelo usuário');
LQuery.ExecSQL;
Result := LQuery.RowsAffected;
finally
LQuery.Close;
end;
except
on E : Exception do
raise Exception.Create(E.Message + ' on TTable.Update.');
end;
end;
end.
|
program ROMAN ( OUTPUT ) ;
//***********************
// write roman numerals
//***********************
var X , Y : INTEGER ;
begin (* HAUPTPROGRAMM *)
Y := 1 ;
repeat
X := Y ;
WRITE ( X , ' ' ) ;
while X >= 1000 do
begin
WRITE ( 'm' ) ;
X := X - 1000
end (* while *) ;
if X >= 500 then
begin
WRITE ( 'd' ) ;
X := X - 500
end (* then *) ;
while X >= 100 do
begin
WRITE ( 'c' ) ;
X := X - 100
end (* while *) ;
if X >= 50 then
begin
WRITE ( 'l' ) ;
X := X - 50
end (* then *) ;
while X >= 10 do
begin
WRITE ( 'x' ) ;
X := X - 10
end (* while *) ;
if X >= 5 then
begin
WRITE ( 'v' ) ;
X := X - 5
end (* then *) ;
while X >= 1 do
begin
WRITE ( 'i' ) ;
X := X - 1
end (* while *) ;
WRITELN ;
Y := 2 * Y ;
until Y > 5000
end (* HAUPTPROGRAMM *) .
|
unit Commune_APIUtilities;
{ ==============================================================================================================================
Centralize Utilities for accessing the Windows API
MIT License
Copyright (c) 2020 Keith Latham
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
============================================================================================================================== }
{$IF DECLARED(FireMonkeyVersion)}
{$DEFINE HAS_FMX}
{$ELSE}
{$DEFINE HAS_VCL}
{$ENDIF}
interface
uses
ActiveX,
ComObj,
ShlObj,
System.Types,
Winapi.Windows,
Winapi.KnownFolders,
System.Classes
{$IFDEF HAS_FMX}
,
FMX.Types
{$ENDIF}
;
type
dwOperationFlags = DWORD;
type
TFileSystemBindData = class(TInterfacedObject, IFileSystemBindData)
fw32fd: TWin32FindData;
function GetFindData(var w32fd: TWin32FindData): HRESULT; stdcall;
function SetFindData(var w32fd: TWin32FindData): HRESULT; stdcall;
end;
type
fsScaleFactor = (fss_Byte, fss_KiloByte, fss_Megabyte, fss_Gigabyte, fss_Terabyte, fss_Petabyte);
type
tFileOperationProgressSink = class(TInterfacedObject, IFileOperationProgressSink)
function FinishOperations(hrResult: HRESULT): HRESULT; virtual; stdcall;
function PauseTimer: HRESULT; virtual; stdcall;
function PostCopyItem(dwFlags: DWORD; const psiItem: IShellItem; const psiDestinationFolder: IShellItem;
pszNewName: LPCWSTR; hrCopy: HRESULT; const psiNewlyCreated: IShellItem): HRESULT; virtual; stdcall;
function PostDeleteItem(dwFlags: DWORD; const psiItem: IShellItem; hrDelete: HRESULT;
const psiNewlyCreated: IShellItem): HRESULT; virtual; stdcall;
function PostMoveItem(dwFlags: DWORD; const psiItem: IShellItem; const psiDestinationFolder: IShellItem;
pszNewName: LPCWSTR; hrMove: HRESULT; const psiNewlyCreated: IShellItem): HRESULT; virtual; stdcall;
function PostNewItem(dwFlags: DWORD; const psiDestinationFolder: IShellItem; pszNewName: LPCWSTR;
pszTemplateName: LPCWSTR; dwFileAttributes: DWORD; hrNew: HRESULT; const psiNewItem: IShellItem): HRESULT;
virtual; stdcall;
function PostRenameItem(dwFlags: DWORD; const psiItem: IShellItem; pszNewName: LPCWSTR; hrRename: HRESULT;
const psiNewlyCreated: IShellItem): HRESULT; virtual; stdcall;
function PreCopyItem(dwFlags: DWORD; const psiItem: IShellItem; const psiDestinationFolder: IShellItem;
pszNewName: LPCWSTR): HRESULT; virtual; stdcall;
function PreDeleteItem(dwFlags: DWORD; const psiItem: IShellItem): HRESULT; virtual; stdcall;
function PreMoveItem(dwFlags: DWORD; const psiItem: IShellItem; const psiDestinationFolder: IShellItem;
pszNewName: LPCWSTR): HRESULT; virtual; stdcall;
function PreNewItem(dwFlags: DWORD; const psiDestinationFolder: IShellItem; pszNewName: LPCWSTR): HRESULT;
virtual; stdcall;
function PreRenameItem(dwFlags: DWORD; const psiItem: IShellItem; pszNewName: LPCWSTR): HRESULT; virtual; stdcall;
function ResetTimer: HRESULT; virtual; stdcall;
function ResumeTimer: HRESULT; virtual; stdcall;
function StartOperations: HRESULT; virtual; stdcall;
function UpdateProgress(iWorkTotal: UINT; iWorkSoFar: UINT): HRESULT; virtual; stdcall;
end;
type
tAPIUtility = class
private
class function API_GetDriveType(aDriveLetter: pChar): integer;
class function API_GetDriveTypeString(aDriveLetter: pChar): string;
class function API_GetVolumeLabel(DriveChar: pChar): string;
class function API_IFileOperation(const aFunction: cardinal; const SourceFile, TargetFile: string)
: boolean; static;
class function API_SHFileOperation(const aFunction: cardinal; const SourceFile, TargetFile: string;
const aOwnerHandle: HWnd = 0): boolean;
class procedure COM_FileOperation_Close; static;
class function COM_FileOperation_INITCopy(aFileOp: IFileOperation; const aSourceFile, aTargetFile: string)
: HRESULT; static;
class function COM_FileOperation_INITDelete(aFileOp: IFileOperation; const aSourceFile: string): HRESULT; static;
class function COM_FileOperation_INITMove(aFileOp: IFileOperation; const aSourceFile, aTargetFile: string)
: HRESULT; static;
class function COM_FileOperation_INITRename(aFileOp: IFileOperation; const aSourceFile, aTargetFile: string)
: HRESULT; static;
class function COM_FileOperation_Open(const aCoInit: Longint; const aOPFlags: dwOperationFlags;
out aHresult: HRESULT): IFileOperation; static;
class function COM_FileOperation_SetSource(const aSourceFile, aTargetDir: string; out pbc: IBindCtx;
out aHresult: HRESULT): IShellItem; static;
class function COM_FileOperation_SetTarget(const aTargetDir: string; pbc: IBindCtx; out aHresult: HRESULT)
: IShellItem; static;
public
class function EnumerateAllDrives: tStringList;
class function EnumerateDirectories(const aRoot: string): tStringList;
class function EnumerateLogicalDrives: tStringList;
class function EnumeratePathFiles(aPath: string; aFilter: string = '*.*'): tStringList;
class function FileCopy(const aFrom, aTo: string): boolean;
class function FileCopyX(const aFrom, aTo: string): boolean; static;
class function FileDelete(const aFrom: string): boolean;
class function FileDeleteX(const aFrom: string): boolean;
class function FileMove(const aFrom, aTo: string): boolean;
class function FileRename(const aFrom, aTo: string): boolean;
class function FileSizeOf(aFile: string; aScale: fsScaleFactor = fss_Byte): nativeint;
class function KnownFolderPath(const aKnownFolderCSIDL: integer): string; overload;
class function KnownFolderPath(const aKnownFolderGUID: tGUID): string; overload;
class function SanitizeFilename(aInputFileName: string): string;
end;
type
tKnownFolder = class
public
class function ProgramDataPath: string;
end;
implementation
uses
// CodeSiteLogging,
System.StrUtils,
System.SysUtils,
// JclAnsiStrings,
Winapi.ShellAPI,
FMX.Platform.Win,
System.IOUtils,
System.Math;
{ tAPIUtility }
{ ----------------------------------------------------------------------------------------------------------------------------- }
class function tAPIUtility.API_GetDriveType(aDriveLetter: pChar): integer;
var
TargetDrive: pChar;
begin
TargetDrive := pChar(aDriveLetter + ':\');
result := GetDriveType(TargetDrive);
// Codesite.Send('API_GetDriveType ' + aDriveLetter, Result);
end;
{ ----------------------------------------------------------------------------------------------------------------------------- }
class function tAPIUtility.API_GetDriveTypeString(aDriveLetter: pChar): string;
var
myDriveType: integer;
begin
myDriveType := API_GetDriveType(aDriveLetter);
case myDriveType of
DRIVE_UNKNOWN: result := 'UNKNOWN';
DRIVE_NO_ROOT_DIR: result := 'NO_ROOT_DIR';
DRIVE_REMOVABLE: result := 'REMOVABLE';
DRIVE_FIXED: result := 'FIXED';
DRIVE_REMOTE: result := 'REMOTE';
DRIVE_CDROM: result := 'CDROM';
DRIVE_RAMDISK: result := 'RAMDISK';
end;
// Codesite.Send('API_GetDriveTypeString ' + aDriveLetter, Result);
end;
{ ----------------------------------------------------------------------------------------------------------------------------- }
class function tAPIUtility.API_GetVolumeLabel(DriveChar: pChar): string;
var
Buf: array [0 .. MAX_PATH] of Char;
NotUsed: DWORD;
VolumeFlags: DWORD;
VolumeInfo: array [0 .. MAX_PATH] of Char;
VolumeSerialNumber: DWORD;
begin
VolumeInfo[0] := 'C'; // do something nonsensical to keep the compiler happy
GetVolumeInformation(pChar(DriveChar + ':\'), Buf, SizeOf(VolumeInfo), @VolumeSerialNumber, NotUsed,
VolumeFlags, nil, 0);
SetString(result, Buf, StrLen(Buf)); { Set return result }
result := AnsiUpperCase(result);
// Codesite.Send('API_GetVolumeLabel ' + DriveChar, Result);
end;
class function tAPIUtility.API_IFileOperation(const aFunction: cardinal; const SourceFile, TargetFile: string): boolean;
{ ----------------------------------------------------------------------------------------------------------------------------- }
const
myApartment: shortint = (COINIT_APARTMENTTHREADED or COINIT_DISABLE_OLE1DDE);
// Yes to all for any dialog box // Do NOT allow progress box to be minimized
myOPFlags: dwOperationFlags = (FOF_NOCONFIRMATION or FOFX_NOMINIMIZEBOX or FOFX_DONTDISPLAYSOURCEPATH or
FOF_NOCONFIRMMKDIR);
var
fileOp: IFileOperation;
r: HRESULT;
begin
result := false;
fileOp := COM_FileOperation_Open(myApartment, myOPFlags, r); // CoInitializeEx;
if succeeded(r) then
begin
// set up the copy operation
case aFunction of
FO_COPY: r := COM_FileOperation_INITCopy(fileOp, SourceFile, TargetFile);
FO_MOVE: r := COM_FileOperation_INITMove(fileOp, SourceFile, TargetFile);
FO_DELETE: r := COM_FileOperation_INITDelete(fileOp, SourceFile);
FO_RENAME: r := COM_FileOperation_INITRename(fileOp, SourceFile, TargetFile);
else
begin
end;
end;
// execute
if succeeded(r) then r := fileOp.PerformOperations;
result := succeeded(r);
OleCheck(r);
end;
COM_FileOperation_Close; // CoUninitialize;
end;
{ ----------------------------------------------------------------------------------------------------------------------------- }
class function tAPIUtility.API_SHFileOperation(const aFunction: cardinal; const SourceFile, TargetFile: string;
const aOwnerHandle: HWnd = 0): boolean;
{ ----------------------------------------------------------------------------------------------------------------------------- }
// FMX callers will need to use FormToHWND(aOwnerHandle) to get the HWnd;
var
Aborted: boolean;
SHFoSInfo: TSHFileOpStruct;
Source: string;
Target: string;
begin
Aborted := false;
Source := SourceFile + #0;
Target := TargetFile + #0;
with SHFoSInfo do
begin
Wnd := aOwnerHandle;
// Wnd := hWndOwner;
// Wnd := FmxHandleToHWND(aOwnerHandle);
{ From Microsoft's Help:
wFunc = Operation to perform. This member can be one of the following values:
FO_COPY Copies the files specified by pFrom to the location specified by pTo.
FO_DELETE Deletes the files specified by pFrom (pTo is ignored).
FO_MOVE Moves the files specified by pFrom to the location specified by pTo.
FO_RENAME Renames the files specified by pFrom. }
wFunc := aFunction;
pFrom := pWideChar(Source);
pTo := pWideChar(Target);
fFlags := FOF_NOCONFIRMMKDIR; // AND FOF_NOCONFIRMATION;
fAnyOperationsAborted := Aborted;
SHFoSInfo.lpszProgressTitle := pFrom;
end;
try
SHFileOperation(SHFoSInfo);
finally
result := not Aborted;
end;
end;
{ ----------------------------------------------------------------------------------------------------------------------------- }
class procedure tAPIUtility.COM_FileOperation_Close;
{ ======= }
begin
CoUninitialize;
end;
{ ----------------------------------------------------------------------------------------------------------------------------- }
class function tAPIUtility.COM_FileOperation_INITCopy(aFileOp: IFileOperation;
const aSourceFile, aTargetFile: string): HRESULT;
{ ======= }
var
destFileFolder, destFileName: string;
siSrcFile: IShellItem;
siDestFolder: IShellItem;
pbc: IBindCtx;
begin
destFileFolder := ExtractFileDir(aTargetFile);
destFileName := ExtractFileName(aTargetFile);
// get source shell item
siSrcFile := COM_FileOperation_SetSource(aSourceFile, destFileFolder, pbc, result);
// get destination folder shell item
siDestFolder := COM_FileOperation_SetTarget(destFileFolder, pbc, result);
// add copy operation to file operation list
if succeeded(result) then result := aFileOp.CopyItem(siSrcFile, siDestFolder, pChar(destFileName), nil);
end;
{ ----------------------------------------------------------------------------------------------------------------------------- }
class function tAPIUtility.COM_FileOperation_INITDelete(aFileOp: IFileOperation; const aSourceFile: string): HRESULT;
{ ======= }
var
siSrcFile: IShellItem;
pbc: IBindCtx;
begin
// get source shell item
siSrcFile := COM_FileOperation_SetSource(aSourceFile, '', pbc, result);
// add copy operation to file operation list
if succeeded(result) then result := aFileOp.DeleteItem(siSrcFile, nil);
end;
{ ----------------------------------------------------------------------------------------------------------------------------- }
class function tAPIUtility.COM_FileOperation_INITMove(aFileOp: IFileOperation;
const aSourceFile, aTargetFile: string): HRESULT;
begin
{ TODO : Implement this routine }
result := E_NOTIMPL;
end;
{ ----------------------------------------------------------------------------------------------------------------------------- }
class function tAPIUtility.COM_FileOperation_INITRename(aFileOp: IFileOperation;
const aSourceFile, aTargetFile: string): HRESULT;
begin
{ TODO : Implement this routine }
result := E_NOTIMPL;
end;
// class function tAPIUtility.API_IFileOperation(const aFunction: cardinal; const SourceFile, TargetFile: string;
// const aOwnerHandle: HWnd = 0): boolean;
/// / begin
/// /
/// / function CopyFileIFileOperationForceDirectories(const srcFile, destFile : string) : boolean;
/// / works on Windows >= Vista and 2008 server
// var
// r : HRESULT;
// fileOp : IFileOperation;
// siSrcFile : IShellItem;
// siDestFolder : IShellItem;
// destFileFolder, destFileName: string;
// pbc : IBindCtx;
// w32fd : TWin32FindData;
// ifs : TFileSystemBindData;
// begin
// result := false;
//
// destFileFolder := ExtractFileDir(TargetFile);
// destFileName := ExtractFileName(TargetFile);
//
// // init com
// r := CoInitializeEx(nil, COINIT_APARTMENTTHREADED or COINIT_DISABLE_OLE1DDE);
// if Succeeded(r) then begin
// // create IFileOperation interface
// r := CoCreateInstance(CLSID_FileOperation, nil, CLSCTX_ALL, IFileOperation, fileOp);
// if Succeeded(r) then begin
// // set operations flags
// r := fileOp.SetOperationFlags(FOF_NOCONFIRMATION or FOFX_NOMINIMIZEBOX);
// if Succeeded(r) then begin
// // get source shell item
// r := SHCreateItemFromParsingName(pChar(SourceFile), nil, IShellItem, siSrcFile);
// if Succeeded(r) then begin
// // create binding context to pretend there is a folder there
// if not DirectoryExists(destFileFolder) then begin
// ZeroMemory(@w32fd, SizeOf(TWin32FindData));
// w32fd.dwFileAttributes := FILE_ATTRIBUTE_DIRECTORY;
// ifs := TFileSystemBindData.Create;
// ifs.SetFindData(w32fd);
// r := CreateBindCtx(0, pbc);
// r := pbc.RegisterObjectParam(STR_FILE_SYS_BIND_DATA, ifs);
// end
// else pbc := nil;
//
// // get destination folder shell item
// r := SHCreateItemFromParsingName(pChar(destFileFolder), pbc, IShellItem, siDestFolder);
//
// // add copy operation
// if Succeeded(r) then r := fileOp.CopyItem(siSrcFile, siDestFolder, pChar(destFileName), nil);
// end;
//
// // execute
// if Succeeded(r) then r := fileOp.PerformOperations;
//
// result := Succeeded(r);
//
// OleCheck(r);
// end;
// end;
//
// CoUninitialize;
// end;
// end;
{ ----------------------------------------------------------------------------------------------------------------------------- }
class function tAPIUtility.COM_FileOperation_Open(const aCoInit: Longint; const aOPFlags: dwOperationFlags;
out aHresult: HRESULT): IFileOperation;
{ ======= }
begin
result := nil;
// initialize COM
aHresult := CoInitializeEx(nil, aCoInit);
if (aHresult <> RPC_E_CHANGED_MODE) then
begin
// create IFileOperation interface
aHresult := CoCreateInstance(CLSID_FileOperation, // we are doing a file operation
nil, // not an aggregate
CLSCTX_ALL, // any execution context
IFileOperation, // interface class
result); // interface object result
end;
// set operations flags
if succeeded(aHresult) then aHresult := result.SetOperationFlags(aOPFlags);
end;
{ ----------------------------------------------------------------------------------------------------------------------------- }
class function tAPIUtility.COM_FileOperation_SetSource(const aSourceFile, aTargetDir: string; out pbc: IBindCtx;
out aHresult: HRESULT): IShellItem;
{ ======= }
var
w32fd: TWin32FindData;
ifs: TFileSystemBindData;
begin
aHresult := SHCreateItemFromParsingName(pChar(aSourceFile), // source file (directory?) name
nil, // no bind context (yet)
IShellItem, // we want a shell item interface
result); // resulting source file shell item interface
if succeeded(aHresult) then
begin
// create binding context to pretend there is a folder there
if ((length(aTargetDir) > 0) and (not DirectoryExists(aTargetDir))) then
begin
ZeroMemory(@w32fd, SizeOf(TWin32FindData));
w32fd.dwFileAttributes := FILE_ATTRIBUTE_DIRECTORY;
ifs := TFileSystemBindData.Create;
ifs.SetFindData(w32fd);
aHresult := CreateBindCtx(0, pbc);
aHresult := pbc.RegisterObjectParam(STR_FILE_SYS_BIND_DATA, ifs);
end
else pbc := nil;
end;
end;
{ ----------------------------------------------------------------------------------------------------------------------------- }
class function tAPIUtility.COM_FileOperation_SetTarget(const aTargetDir: string; pbc: IBindCtx; out aHresult: HRESULT)
: IShellItem;
{ ======= }
begin
aHresult := SHCreateItemFromParsingName(pChar(aTargetDir), pbc, IShellItem, result);
end;
class function tAPIUtility.EnumerateAllDrives: tStringList;
{ ----------------------------------------------------------------------------------------------------------------------------- }
var
DriveList: tStringList;
DriveString: string;
myDriveChar: pChar;
myDriveString: string;
myDriveTarget: string;
myDriveType: integer;
myVolumeLabel: string;
begin
result := tStringList.Create;
DriveList := EnumerateLogicalDrives;
try
for DriveString in DriveList do
begin
myDriveChar := pChar(DriveString);
myDriveType := API_GetDriveType(myDriveChar);
if (myDriveType > 0) then
begin
myDriveTarget := DriveString + ':';
myDriveString := API_GetDriveTypeString(myDriveChar);
myVolumeLabel := API_GetVolumeLabel(myDriveChar);
result.Add(myDriveTarget + '=<' + myVolumeLabel + '> (' + myDriveString + ')');
end;
end;
finally
DriveList.Free;
end;
end;
{ ----------------------------------------------------------------------------------------------------------------------------- }
class function tAPIUtility.EnumerateDirectories(const aRoot: string): tStringList;
procedure HandleFind(asr: tSearchRec; aresult: tStringList);
begin
if ((asr.Attr and faDirectory) = faDirectory) and (asr.Name <> '.') and (asr.Name <> '..') then
aresult.Add(asr.Name);
end;
var
sr: tSearchRec;
begin
result := tStringList.Create;
if FindFirst(aRoot + '*', faDirectory, sr) = 0 then
repeat HandleFind(sr, result);
until FindNext(sr) <> 0;
end;
{ ----------------------------------------------------------------------------------------------------------------------------- }
class function tAPIUtility.EnumerateLogicalDrives: tStringList;
var
i: integer;
length: integer;
MyStr: pChar;
const
Size: integer = 200;
begin
result := tStringList.Create;
GetMem(MyStr, Size);
length := GetLogicalDriveStrings(Size, MyStr);
for i := 0 to length - 1 do
if (MyStr[i] >= 'A') and (MyStr[i] <= 'Z') then result.Add(MyStr[i]);
FreeMem(MyStr);
end;
{ ----------------------------------------------------------------------------------------------------------------------------- }
class function tAPIUtility.EnumeratePathFiles(aPath: string; aFilter: string = '*.*'): tStringList;
var
thisFile: string;
begin
result := tStringList.Create;
for thisFile in TDirectory.GetFiles(aPath, aFilter, tSearchOption.soTopDirectoryOnly) do
begin
result.Add(thisFile);
end;
end;
{ ----------------------------------------------------------------------------------------------------------------------------- }
class function tAPIUtility.FileCopy(const aFrom, aTo: string): boolean;
begin
// codesite.Send('(Redirected to FileCopyX) FileCopy SOURCE: ' + aFrom + ' ==> TARGET: ' + aTo);
// result := tAPIUtility.API_SHFileOperation(FO_Copy, aFrom, aTo, 0);
result := tAPIUtility.FileCopyX(aFrom, aTo);
end;
{ ----------------------------------------------------------------------------------------------------------------------------- }
class function tAPIUtility.FileCopyX(const aFrom, aTo: string): boolean;
{ class function API_IFileOperation(const aFunction: cardinal; const SourceFile, TargetFile: string): boolean; static;
}
begin
// codesite.Send('FileCopyX SOURCE: ' + aFrom + ' ==> TARGET: ' + aTo);
result := tAPIUtility.API_IFileOperation(FO_COPY, aFrom, aTo);
end;
{ ----------------------------------------------------------------------------------------------------------------------------- }
class function tAPIUtility.FileDelete(const aFrom: string): boolean;
begin
// codesite.Send('(Redirected to FileDeleteX) FileDelete SOURCE: ' + aFrom);
// result := tAPIUtility.API_SHFileOperation(FO_DELETE, aFrom, aTo, 0);
result := tAPIUtility.FileDeleteX(aFrom);
end;
{ ----------------------------------------------------------------------------------------------------------------------------- }
class function tAPIUtility.FileDeleteX(const aFrom: string): boolean;
begin
result := tAPIUtility.API_IFileOperation(FO_DELETE, aFrom, '');
end;
{ ----------------------------------------------------------------------------------------------------------------------------- }
class function tAPIUtility.FileMove(const aFrom, aTo: string): boolean;
begin
result := tAPIUtility.API_SHFileOperation(FO_MOVE, aFrom, aTo, 0);
end;
{ ----------------------------------------------------------------------------------------------------------------------------- }
class function tAPIUtility.FileRename(const aFrom, aTo: string): boolean;
begin
result := tAPIUtility.API_SHFileOperation(FO_RENAME, aFrom, aTo, 0);
end;
{ ----------------------------------------------------------------------------------------------------------------------------- }
class function tAPIUtility.FileSizeOf(aFile: string; aScale: fsScaleFactor = fss_Byte): nativeint;
var
bytecount: nativeint;
F: file of byte;
scaled: extended;
scaler: extended;
begin
AssignFile(F, aFile);
reset(F);
try
bytecount := FileSize(F);
finally
closefile(F);
end;
scaler := IntPower(1024, ord(aScale));
scaled := bytecount / scaler;
result := ceil(scaled);
end;
{ ----------------------------------------------------------------------------------------------------------------------------- }
class function tAPIUtility.KnownFolderPath(const aKnownFolderCSIDL: integer): string;
var
myHandle: tHandle;
myToken: cardinal;
myFlags: cardinal;
mypszPath: array [0 .. MAX_PATH] of Char;
APIResult: integer;
begin
myHandle := 0;
myToken := 0;
myFlags := 0;
APIResult := SHGetFolderPath(myHandle, aKnownFolderCSIDL, myToken, myFlags, mypszPath);
result := mypszPath;
end;
{ ----------------------------------------------------------------------------------------------------------------------------- }
class function tAPIUtility.KnownFolderPath(const aKnownFolderGUID: tGUID): string;
// REMEMBER: add Winapi.ShlObj to USES
var
path: LPWSTR;
begin
if succeeded(SHGetKnownFolderPath(aKnownFolderGUID, 0, 0, path)) then
begin
try
result := path;
finally
CoTaskMemFree(path);
end;
end
else result := '';
end;
{ ----------------------------------------------------------------------------------------------------------------------------- }
class function tAPIUtility.SanitizeFilename(aInputFileName: string): string;
var
ANSI: AnsiString;
begin
result := aInputFileName;
result := AnsiReplaceStr(result, '/', '_');
result := AnsiReplaceStr(result, '\', '_');
result := AnsiReplaceStr(result, '"', '''');
result := AnsiReplaceStr(result, '#', 'No.');
result := AnsiReplaceStr(result, '%23', 'No.');
ANSI := AnsiString(result);
result := ANSI;
// If you have access to the JEDI JCL library, then StrSmartCase makes the filename look pretty
// you will have to uncomment the "JCLAnsiStrings" line in the implementation uses clause too
// result := string(StrSmartCase(ANSI, [' ', #9, '\', #13, #10]));
end;
{ TFileSystemBindData }
{ ----------------------------------------------------------------------------------------------------------------------------- }
function TFileSystemBindData.GetFindData(var w32fd: TWin32FindData): HRESULT;
begin
w32fd := fw32fd;
result := S_OK;
end;
{ ----------------------------------------------------------------------------------------------------------------------------- }
function TFileSystemBindData.SetFindData(var w32fd: TWin32FindData): HRESULT;
begin
fw32fd := w32fd;
result := S_OK;
end;
{ tFileOperationProgressSink }
const
FileOperationSuccessfull: HRESULT = 0;
{ ----------------------------------------------------------------------------------------------------------------------------- }
function tFileOperationProgressSink.FinishOperations(hrResult: HRESULT): HRESULT;
begin
result := FileOperationSuccessfull;
end;
{ ----------------------------------------------------------------------------------------------------------------------------- }
function tFileOperationProgressSink.PauseTimer: HRESULT;
begin
result := FileOperationSuccessfull;
end;
{ ----------------------------------------------------------------------------------------------------------------------------- }
function tFileOperationProgressSink.PostCopyItem(dwFlags: DWORD; const psiItem, psiDestinationFolder: IShellItem;
pszNewName: LPCWSTR; hrCopy: HRESULT; const psiNewlyCreated: IShellItem): HRESULT;
begin
result := FileOperationSuccessfull;
end;
{ ----------------------------------------------------------------------------------------------------------------------------- }
function tFileOperationProgressSink.PostDeleteItem(dwFlags: DWORD; const psiItem: IShellItem; hrDelete: HRESULT;
const psiNewlyCreated: IShellItem): HRESULT;
begin
result := FileOperationSuccessfull;
end;
{ ----------------------------------------------------------------------------------------------------------------------------- }
function tFileOperationProgressSink.PostMoveItem(dwFlags: DWORD; const psiItem, psiDestinationFolder: IShellItem;
pszNewName: LPCWSTR; hrMove: HRESULT; const psiNewlyCreated: IShellItem): HRESULT;
begin
result := FileOperationSuccessfull;
end;
{ ----------------------------------------------------------------------------------------------------------------------------- }
function tFileOperationProgressSink.PostNewItem(dwFlags: DWORD; const psiDestinationFolder: IShellItem;
pszNewName, pszTemplateName: LPCWSTR; dwFileAttributes: DWORD; hrNew: HRESULT; const psiNewItem: IShellItem): HRESULT;
begin
result := FileOperationSuccessfull;
end;
{ ----------------------------------------------------------------------------------------------------------------------------- }
function tFileOperationProgressSink.PostRenameItem(dwFlags: DWORD; const psiItem: IShellItem; pszNewName: LPCWSTR;
hrRename: HRESULT; const psiNewlyCreated: IShellItem): HRESULT;
begin
result := FileOperationSuccessfull;
end;
{ ----------------------------------------------------------------------------------------------------------------------------- }
function tFileOperationProgressSink.PreCopyItem(dwFlags: DWORD; const psiItem, psiDestinationFolder: IShellItem;
pszNewName: LPCWSTR): HRESULT;
begin
result := FileOperationSuccessfull;
end;
{ ----------------------------------------------------------------------------------------------------------------------------- }
function tFileOperationProgressSink.PreDeleteItem(dwFlags: DWORD; const psiItem: IShellItem): HRESULT;
begin
result := FileOperationSuccessfull;
end;
{ ----------------------------------------------------------------------------------------------------------------------------- }
function tFileOperationProgressSink.PreMoveItem(dwFlags: DWORD; const psiItem, psiDestinationFolder: IShellItem;
pszNewName: LPCWSTR): HRESULT;
begin
result := FileOperationSuccessfull;
end;
{ ----------------------------------------------------------------------------------------------------------------------------- }
function tFileOperationProgressSink.PreNewItem(dwFlags: DWORD; const psiDestinationFolder: IShellItem;
pszNewName: LPCWSTR): HRESULT;
begin
result := FileOperationSuccessfull;
end;
{ ----------------------------------------------------------------------------------------------------------------------------- }
function tFileOperationProgressSink.PreRenameItem(dwFlags: DWORD; const psiItem: IShellItem;
pszNewName: LPCWSTR): HRESULT;
begin
result := FileOperationSuccessfull;
end;
{ ----------------------------------------------------------------------------------------------------------------------------- }
function tFileOperationProgressSink.ResetTimer: HRESULT;
begin
result := FileOperationSuccessfull;
end;
{ ----------------------------------------------------------------------------------------------------------------------------- }
function tFileOperationProgressSink.ResumeTimer: HRESULT;
begin
result := FileOperationSuccessfull;
end;
{ ----------------------------------------------------------------------------------------------------------------------------- }
function tFileOperationProgressSink.StartOperations: HRESULT;
begin
result := FileOperationSuccessfull;
end;
{ ----------------------------------------------------------------------------------------------------------------------------- }
function tFileOperationProgressSink.UpdateProgress(iWorkTotal, iWorkSoFar: UINT): HRESULT;
begin
{ TODO : }
result := E_NOTIMPL;
end;
{ tKnownFolder }
{ ----------------------------------------------------------------------------------------------------------------------------- }
class function tKnownFolder.ProgramDataPath: string;
begin
{ DONE : move this to commune utilities }
result := tAPIUtility.KnownFolderPath(FOLDERID_ProgramData);
end;
end.
|
unit AutoCompletePanel;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs,
ExtCtrls, StdCtrls, LCLType;
type
TAutocompleteEvent = procedure(Sender: TObject; SearchText: string; Items: TStrings) of object;
{ TAutoCompletePanel }
TAutoCompletePanel = class(TCustomPanel)
private
FOnSearch: TAutocompleteEvent;
FOnSelectionChange: TNotifyEvent;
FSelectedObject: TObject;
FSelectedObjectText: string;
FLabel: TLabel;
FEdit: TEdit;
FListBox: TListBox;
procedure OnEditChange(Sender: TObject);
procedure OnEditEnter(Sender: TObject);
procedure OnEditExit(Sender: TObject);
procedure OnEditKeyDown(Sender: TObject; var Key: word; Shift: TShiftState);
procedure OnListBoxClick(Sender: TObject);
procedure SetFSelectedObject(AValue: TObject);
procedure SetFSelectedObjectText(AValue: string);
protected
public
procedure ShowListBox;
procedure HideListBox;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property SelectedObject: TObject read FSelectedObject write SetFSelectedObject;
property SelectedObjectText: string read FSelectedObjectText
write SetFSelectedObjectText;
published
property OnSearch: TAutocompleteEvent read FOnSearch write FOnSearch;
property OnSelectionChange: TNotifyEvent read FOnSelectionChange write FOnSelectionChange;
property TabOrder;
property Anchors;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('FPC Paymo Widget', [TAutoCompletePanel]);
end;
{ TAutoCompletePanel }
procedure TAutoCompletePanel.OnEditEnter(Sender: TObject);
begin
if Assigned(FOnSearch) then
begin
FListBox.Items.Clear;
FOnSearch(Self, FEdit.Caption, FListBox.Items);
end;
ShowListBox;
end;
procedure TAutoCompletePanel.OnEditChange(Sender: TObject);
begin
if Assigned(FOnSearch) then
begin
FListBox.Items.Clear;
FOnSearch(Self, FEdit.Caption, FListBox.Items);
end;
end;
procedure TAutoCompletePanel.OnEditExit(Sender: TObject);
begin
HideListBox;
end;
procedure TAutoCompletePanel.OnEditKeyDown(Sender: TObject; var Key: word;
Shift: TShiftState);
var
iPos: integer;
begin
if (key = VK_TAB) then
exit;
if (key = VK_ESCAPE) then
begin
HideListBox;
exit;
end;
ShowListBox;
if (key = VK_DOWN) then
begin
key := 0;
if (FListBox.Items.Count > 0) then
begin
iPos := FListBox.ItemIndex;
Inc(iPos);
if (iPos > FListBox.Items.Count - 1) then
iPos := 0;
FListBox.ItemIndex := iPos;
end;
exit;
end;
if (key = VK_UP) then
begin
key := 0;
if (FListBox.Items.Count > 0) then
begin
iPos := FListBox.ItemIndex;
Dec(iPos);
if (iPos < 0) then
iPos := FListBox.Items.Count - 1;
FListBox.ItemIndex := iPos;
end;
exit;
end;
if Key = VK_RETURN then
begin
OnListBoxClick(nil);
end;
end;
procedure TAutoCompletePanel.OnListBoxClick(Sender: TObject);
begin
if FListBox.ItemIndex > -1 then
begin
SelectedObjectText := FListBox.Items[FListBox.ItemIndex];
FSelectedObject := FListBox.Items.Objects[FListBox.ItemIndex];
HideListBox;
if Assigned(FOnSelectionChange) then
FOnSelectionChange(Self);
end;
end;
procedure TAutoCompletePanel.SetFSelectedObject(AValue: TObject);
begin
if FSelectedObject = AValue then
Exit;
FSelectedObject := AValue;
end;
procedure TAutoCompletePanel.SetFSelectedObjectText(AValue: string);
begin
if FSelectedObjectText = AValue then Exit;
FSelectedObjectText := AValue;
FLabel.Caption := FSelectedObjectText;
FLabel.Hint := FSelectedObjectText;
end;
procedure TAutoCompletePanel.ShowListBox;
begin
Height := FLabel.Height + FEdit.Height + FListBox.Height;
Self.BringToFront;
end;
procedure TAutoCompletePanel.HideListBox;
begin
Height := FLabel.Height + FEdit.Height;
FEdit.Caption := '';
end;
constructor TAutoCompletePanel.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
BevelOuter := bvNone;
BorderWidth := 0;
Caption := '';
// ListBox
FListBox := TListBox.Create(Self);
FListBox.Align := alTop;
FListBox.OnClick := @OnListBoxClick;
FListBox.TabStop := False;
FListBox.Parent := Self;
// Edit
FEdit := TEdit.Create(Self);
FEdit.OnEnter := @OnEditEnter;
FEdit.OnKeyDown := @OnEditKeyDown;
FEdit.OnChange := @OnEditChange;
FEdit.OnClick := @OnEditEnter;
FEdit.Align := alTop;
FEdit.Parent := Self;
// Label
FLabel := TLabel.Create(Self);
FLabel.Align := alTop;
FLabel.Caption := ' ';
FLabel.Parent := Self;
FLabel.ShowHint := True;
OnExit := @OnEditExit;
SetInitialBounds(0, 0, 200, FLabel.Height + FEdit.Height);
end;
destructor TAutoCompletePanel.Destroy;
begin
FEdit.Free;
FListBox.Free;
inherited Destroy;
end;
end.
|
unit DB.Conect;
interface
Uses
Vcl.ComCtrls,
Base.Color,
FireDAC.Comp.Client,
Base.GetConexao,
Winapi.Messages,
Vcl.Dialogs,
System.JSON,
Base.System.JSON.Helper,
Base.System.JsonFiles,
System.SysUtils,
System.Win.ScktComp,
Winapi.Windows,
Base.Key,
Base.Crypt,
Form.Modulo;
Type
TDBConect = Class
Protected
{ Protected class }
Private
{ Private Class }
Public
{ Public Class }
class function SelectTable(pTable: String; pFields: String = '';
pOrder: String = ''; pSQL: String = ''; pRename: String = ''): TFDQuery;
class function UpdateTable(tTabela: String; tCampo: String; tValor: String;
SqlExtra: String = ''): TFDQuery;
class function ConectaDB(Log: TRichEdit): Boolean;
End;
implementation
Uses
Base.Struct;
class function TDBConect.ConectaDB(Log: TRichEdit): Boolean;
begin
With DM.Connection Do
begin
Try
Connected := False;
// Params.Clear;
Params.Values['Database'] := JsonConection.DB;
Params.Values['DriverID'] := 'MySQL';
Params.Values['Port'] := IntToStr(JsonConection.PORTA_MYSQL);
Params.Values['Server'] := JsonConection.IP;
// Params.Values['HostName']:= Conexao.IP;
Params.Values['UserName'] := JsonConection.User;
Params.Values['Password'] := Crypt('D', JsonConection.SENHA);
Result := True;
Connected := True;
LogDB.DBLog(Log, 'MYSQL DB:', 0);
LogDB.DBLog(Log,
'.......................................................................'
+ '............................................................OK!!!',
0);
Except
On E: Exception Do
begin
LogDB.DBLog(Log, E.Message, 1);
LogDB.DBLog(Log, 'MYSQL: ' +
'...........................................................Falha.',
1);
Result := False;
exit;
end;
End;
end;
end;
class function TDBConect.UpdateTable(tTabela: String; tCampo: String;
tValor: String; SqlExtra: String = ''): TFDQuery;
Var
Conect: TGetConexao;
begin
// cria a class de conexão
Conect := TGetConexao.Create;
// cria uma nova query
Result := TFDQuery.Create(Nil);
try
with Result Do
begin
Connection := Conect.Conexao;
Close;
SQL.clear;
SQL.Add('UPDATE ' + tTabela); // Monta update dinamico
SQL.Add('SET ' + tCampo + '=' + tValor);
// verifica se foi informado um sql extra
if SqlExtra <> '' then
SQL.Add(SqlExtra); // adciona o sql extra no select
ExecSQL;
// DM.Connection.Commit;
end;
Except
// ShowMessage
// ('Ocorreu um erro com o update, verifique se os parametros estão corretos');
end;
end;
class function TDBConect.SelectTable(pTable: String; pFields: String = '';
pOrder: String = ''; pSQL: String = ''; pRename: String = ''): TFDQuery;
Var
Conect: TGetConexao;
begin
Conect := TGetConexao.Create;
Result := TFDQuery.Create(Nil); // Cria uma Query dinamica
Result.Name := pTable;
try
with Result Do
begin
Connection := Conect.Conexao;
if pFields = '' then
pFields := '*';
Close;
SQL.clear;
SQL.Add('SELECT ' + pFields + ' FROM ' + pTable + '' + pRename);
// Monta select dinamico
if pSQL <> '' then
SQL.Add(pSQL);
if pOrder <> '' then
SQL.Add('ORDER BY ' + pOrder);
open;
// DM.Connection.Commit;
end;
Except
//
end;
end;
end.
|
unit uFirebirdConnection;
interface
uses uIConnection, Data.DB, Data.SqlExpr, System.SysUtils, Data.DBXFirebird;
type
TFirebirdConnection = class(TInterfacedObject, IConnection)
private
FConnection: TSQLConnection;
function GetConnection: TSQLConnection;
public
constructor Create(EndDB: string);
destructor Destroy; override;
function GetQuery: TSQLQuery;
property Connection: TSQLConnection read GetConnection;
end;
implementation
{ TOIFirebirdConnection }
uses uMJD.Messages;
constructor TFirebirdConnection.Create(EndDB: string);
begin
FConnection := TSQLConnection.Create(nil);
FConnection.Close;
FConnection.ConnectionName := '';
FConnection.DriverName := 'Firebird';
FConnection.GetDriverFunc := 'getSQLDriverINTERBASE';
FConnection.LibraryName := 'dbxfb.dll';
FConnection.LoadParamsOnConnect := False;
FConnection.LoginPrompt := false;
FConnection.VendorLib := 'fbclient.dll';
FConnection.Params.Clear;
FConnection.Params.Add('DriverName=Firebird');
FConnection.Params.Add(Format('Database=%s', [EndDB]));
FConnection.Params.Add('RoleName=RoleName');
FConnection.Params.Add('User_Name=sysdba');
FConnection.Params.Add('Password=masterkey');
FConnection.Params.Add('ServerCharSet=win1252');
FConnection.Params.Add('SQLDialect=3');
FConnection.Params.Add('ErrorResourceFile=');
FConnection.Params.Add('LocaleCode=0000');
FConnection.Params.Add('BlobSize=-1');
FConnection.Params.Add('CommitRetain=False');
FConnection.Params.Add('WaitOnLocks=True');
FConnection.Params.Add('IsolationLevel=ReadCommitted');
FConnection.Params.Add('Trim Char=False');
try
try
FConnection.Open;
except
on e: exception do
raise EConnectionError.CreateFmt(rsErroConexaoBD, [e.Message]);
end;
finally
FConnection.Close;
end;
end;
destructor TFirebirdConnection.Destroy;
begin
FConnection.Close();
FConnection.Free();
inherited;
end;
function TFirebirdConnection.GetConnection: TSQLConnection;
begin
Result := FConnection;
end;
function TFirebirdConnection.GetQuery: TSQLQuery;
begin
Result := TSQLQuery.Create(nil);
Result.SQLConnection := Connection;
end;
end.
|
{ Date Created: 5/25/00 5:01:02 PM }
unit InfoTRCKCODETable;
interface
uses
Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf;
type
TInfoTRCKCODERecord = record
PCode: String[2];
PDescription: String[30];
End;
TInfoTRCKCODEBuffer = class(TDataBuf)
protected
function PtrIndex(Index:integer):Pointer;override;
public
Data: TInfoTRCKCODERecord
end;
TEIInfoTRCKCODE = (InfoTRCKCODEPrimaryKey);
TInfoTRCKCODETable = class( TDBISAMTableAU )
private
FDFCode: TStringField;
FDFDescription: TStringField;
procedure SetPCode(const Value: String);
function GetPCode:String;
procedure SetPDescription(const Value: String);
function GetPDescription:String;
procedure SetEnumIndex(Value: TEIInfoTRCKCODE);
function GetEnumIndex: TEIInfoTRCKCODE;
protected
procedure CreateFields; virtual;
procedure SetActive(Value: Boolean); override;
procedure LoadFieldDefs(AStringList:TStringList);override;
procedure LoadIndexDefs(AStringList:TStringList);override;
public
function GetDataBuffer:TInfoTRCKCODERecord;
procedure StoreDataBuffer(ABuffer:TInfoTRCKCODERecord);
property DFCode: TStringField read FDFCode;
property DFDescription: TStringField read FDFDescription;
property PCode: String read GetPCode write SetPCode;
property PDescription: String read GetPDescription write SetPDescription;
procedure Validate; virtual;
published
property Active write SetActive;
property EnumIndex: TEIInfoTRCKCODE read GetEnumIndex write SetEnumIndex;
end; { TInfoTRCKCODETable }
procedure Register;
implementation
procedure TInfoTRCKCODETable.CreateFields;
begin
FDFCode := CreateField( 'Code' ) as TStringField;
FDFDescription := CreateField( 'Description' ) as TStringField;
end; { TInfoTRCKCODETable.CreateFields }
procedure TInfoTRCKCODETable.SetActive(Value: Boolean);
begin
inherited SetActive(Value);
if Active then
CreateFields;
end; { TInfoTRCKCODETable.SetActive }
procedure TInfoTRCKCODETable.Validate;
begin
{ Enter Validation Code Here }
end; { TInfoTRCKCODETable.Validate }
procedure TInfoTRCKCODETable.SetPCode(const Value: String);
begin
DFCode.Value := Value;
end;
function TInfoTRCKCODETable.GetPCode:String;
begin
result := DFCode.Value;
end;
procedure TInfoTRCKCODETable.SetPDescription(const Value: String);
begin
DFDescription.Value := Value;
end;
function TInfoTRCKCODETable.GetPDescription:String;
begin
result := DFDescription.Value;
end;
procedure TInfoTRCKCODETable.LoadFieldDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('Code, String, 2, N');
Add('Description, String, 30, N');
end;
end;
procedure TInfoTRCKCODETable.LoadIndexDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('PrimaryKey, Code, Y, Y, N, N');
end;
end;
procedure TInfoTRCKCODETable.SetEnumIndex(Value: TEIInfoTRCKCODE);
begin
case Value of
InfoTRCKCODEPrimaryKey : IndexName := '';
end;
end;
function TInfoTRCKCODETable.GetDataBuffer:TInfoTRCKCODERecord;
var buf: TInfoTRCKCODERecord;
begin
fillchar(buf, sizeof(buf), 0);
buf.PCode := DFCode.Value;
buf.PDescription := DFDescription.Value;
result := buf;
end;
procedure TInfoTRCKCODETable.StoreDataBuffer(ABuffer:TInfoTRCKCODERecord);
begin
DFCode.Value := ABuffer.PCode;
DFDescription.Value := ABuffer.PDescription;
end;
function TInfoTRCKCODETable.GetEnumIndex: TEIInfoTRCKCODE;
var iname : string;
begin
iname := uppercase(indexname);
if iname = '' then result := InfoTRCKCODEPrimaryKey;
end;
(********************************************)
(************ Register Component ************)
(********************************************)
procedure Register;
begin
RegisterComponents( 'Info Tables', [ TInfoTRCKCODETable, TInfoTRCKCODEBuffer ] );
end; { Register }
function TInfoTRCKCODEBuffer.PtrIndex(index:integer):Pointer;
begin
result := nil;
case index of
1 : result := @Data.PCode;
2 : result := @Data.PDescription;
end;
end;
end. { InfoTRCKCODETable }
|
unit fHexadecimalEntry;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, DanHexEdit,cMegaROM, cConfiguration;
type
TfrmHex = class(TForm)
lblDescription: TLabel;
txtHexEntry: TDanHexEdit;
cmdOK: TButton;
cmdCancel: TButton;
procedure cmdOKClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
_Caption, _Description, _InitValue : String;
_MaxLength, _ReturnValue : Integer;
{ Private declarations }
public
property Caption : String read _Caption write _Caption;
property Description : String read _Description write _Description;
property InitValue : String read _InitValue write _InitValue;
property MaxLength : Integer read _MaxLength write _MaxLength;
property ReturnValue : Integer read _ReturnValue write _ReturnValue;
{ Public declarations }
end;
var
frmHex: TfrmHex;
implementation
{$R *.dfm}
procedure TfrmHex.cmdOKClick(Sender: TObject);
begin
ReturnValue := StrToInt('$' + txtHexEntry.Text);
end;
procedure TfrmHex.FormShow(Sender: TObject);
begin
Caption := _Caption;
lblDescription.Caption := _Description;
txtHexEntry.MaxLength := _MaxLength;
txtHexEntry.Text := _InitValue;
end;
procedure TfrmHex.FormCreate(Sender: TObject);
begin
_Caption := 'Enter a hexadecimal value';
_Description := 'Enter a hexadecimal value:';
_InitValue := '00';
_MaxLength := 2;
end;
end.
|
{*******************************************************}
{ }
{ EldoS MlGen Demo }
{ }
{ Copyright (c) 1999-2003 Mikhail Chernyshev }
{ }
{*******************************************************}
unit clMlDemo;
interface
uses
Windows, SysUtils, Messages, Classes, ElMlGen;
type
TDemoMLGen = class (TBaseElMLGen)
private
FCellWidths: array of array of integer;
FColWidths: array of integer;
FLinesOnPage: Integer;
FMultipage: Boolean;
FOnProcessMessages: TNotifyEvent;
FOutputFileName: string;
FOutputStream: TFileStream;
FUseFooter: Boolean;
FUseHeader: Boolean;
procedure FreeArrays;
protected
procedure AfterExecute; override;
procedure BeforeExecute; override;
procedure IfFound(IfName : string; TagParameters : TStringParameters; var
ResultValue : boolean); override;
procedure LoopIteration(LoopNumb: integer; LoopName: string; TagParameters
: TStringParameters; var LoopDone : boolean); override;
procedure MacroFound(MacroName : string; TagParameters : TStringParameters;
var MacroResult : string; var UseTranslationTable : boolean);
override;
procedure PageBegin(PageNumb : integer); override;
procedure PageEnd(PageNumb : integer); override;
procedure WriteString(Value : string); override;
property OnProcessMessages: TNotifyEvent read FOnProcessMessages write
FOnProcessMessages;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure FillCellWidths;
function GetFileName(FileNumb : integer): string;
function GetTotalFilesCount: Integer;
property LinesOnPage: Integer read FLinesOnPage write FLinesOnPage;
property Multipage: Boolean read FMultipage write FMultipage;
property OutputFileName: string read FOutputFileName write FOutputFileName;
property UseFooter: Boolean read FUseFooter write FUseFooter;
property UseHeader: Boolean read FUseHeader write FUseHeader;
end;
implementation
uses frmMain;
{
********************************** TDemoMLGen **********************************
}
constructor TDemoMLGen.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
// FOutputStream := nil;
end;{TDemoMLGen.Create}
destructor TDemoMLGen.Destroy;
begin
FreeArrays;
if Assigned(FOutputStream) then
begin
FOutputStream.Free;
FOutputStream := nil;
end;
inherited Destroy;
end;{TDemoMLGen.Destroy}
procedure TDemoMLGen.AfterExecute;
begin
FreeArrays;
end;{TDemoMLGen.AfterExecute}
procedure TDemoMLGen.BeforeExecute;
begin
FillCellWidths;
end;{TDemoMLGen.BeforeExecute}
procedure TDemoMLGen.FillCellWidths;
var
i, j, k, Cols, Rows: Integer;
begin
Cols := MainForm.StringGrid.ColCount;
Rows := MainForm.StringGrid.RowCount;
SetLength(FCellWidths, Rows);
SetLength(FColWidths, Cols);
for i := 0 to Cols - 1 do
FColWidths[i] := 0;
for i := 0 to Rows - 1 do
begin
SetLength(FCellWidths[i], Cols);
for j := 0 to Cols - 1 do
begin
k := Length(MainForm.StringGrid.Cells[j, i]);
FCellWidths[i,j] := k;
if FColWidths[j] < k then
FColWidths[j] := k;
end;
end; // for
end;{TDemoMLGen.FillCellWidths}
procedure TDemoMLGen.FreeArrays;
var
i: Integer;
begin
for i := 0 to High(FCellWidths) do
begin
FCellWidths[i] := nil;
end; // for
FCellWidths := nil;
FColWidths := nil;
end;{TDemoMLGen.FreeArrays}
function TDemoMLGen.GetFileName(FileNumb : integer): string;
var
s: string;
begin
Result := FOutputFileName;
if FMultipage and (FileNumb > 1) then
begin
s := ExtractFileExt(Result);
Insert(Format('%d', [FileNumb]), Result, Length(Result) - Length(s) + 1);
end;
end;{TDemoMLGen.GetFileName}
function TDemoMLGen.GetTotalFilesCount: Integer;
var
i, j: Integer;
begin
if FMultipage then
begin
i := FLinesOnPage;
j := Length(FCellWidths);
Result := j div i;
if (j mod i) <> 0 then
inc(Result);
end
else
Result := 1;
end;{TDemoMLGen.GetTotalFilesCount}
procedure TDemoMLGen.IfFound(IfName : string; TagParameters : TStringParameters;
var ResultValue : boolean);
var
s: string;
i, j: Integer;
begin
if IfName = 'Header' then
begin
ResultValue := (PageCount = 1) or FUseHeader;
end
else
if IfName = 'Footer' then
begin
ResultValue := (PageCount = 1) or FUseFooter;
end
else
if IfName = 'NotLastCol' then
begin
s := TagParameters.GetValueByNameEx('loop', '');
if s = '' then
Raise Exception.Create('В теге <if name="NotLastCol"> должен быть параметр loop с именем цикла');
j := -1;
for i := 0 to LoopCount - 1 do
begin
if LoopName[i] = s then
begin
j := i;
break;
end;
end; // for
if j < 0 then
Raise Exception.Create(Format('Цикл указанный в теге <if name="NotLastCol" loop="%s"> не найден', [s]));
ResultValue := (LoopCounter[j] + 1) <> MainForm.StringGrid.ColCount;
end
else
if IfName = 'FileExist' then
begin
i := TagParameters.FindItemByName('offset');
if i < 0 then
i := PageCount - 1
else
i := PageCount + StrToInt(TagParameters.Value[i]) - 1;
ResultValue := (i >= 0) and (i < GetTotalFilesCount);
end
// For internal test
else
if IfName = 'test' then
begin
s := TagParameters.GetValueByNameEx('a', '');
ResultValue := s <> '1';
end
//^^^ For internal test
else
Raise Exception.Create('Unknown condition name');
end;{TDemoMLGen.IfFound}
procedure TDemoMLGen.LoopIteration(LoopNumb: integer; LoopName: string;
TagParameters : TStringParameters; var LoopDone : boolean);
begin
if LoopName = 'Rows' then
begin
LoopDone := (LoopCounter[LoopNumb] + 1) >= MainForm.StringGrid.RowCount;
if not LoopDone then
begin
// Проверка не пора ли начать новый файл
if FMultipage then
begin
if LoopCountersCurrentPage[LoopNumb] >= FLinesOnPage then
NextPage;
end;
end;
end
else
if (LoopName = 'Cols') or (LoopName = 'Header') then
begin
LoopDone := LoopCounter[LoopNumb] >= MainForm.StringGrid.ColCount;
end
else
Raise Exception.Create('Unknown loop name');
end;{TDemoMLGen.LoopIteration}
procedure TDemoMLGen.MacroFound(MacroName : string; TagParameters :
TStringParameters; var MacroResult : string; var UseTranslationTable :
boolean);
function GetWidth(aCol, aRow : integer) : Integer;
var
i : Integer;
begin
Result := TagParameters.FindItemByName('width');
if Result >= 0 then
if TagParameters.Value[Result] <> 'auto' then
Result := StrToInt(TagParameters.Value[Result])
else begin
if aCol >= 0 then
Result := FColWidths[aCol]
else begin
Result := 0;
for i := 0 to High(FColWidths) do
Result := Result + FColWidths[i];
end;
end;
end;
function CalcSeparatorWidth(Space : Integer) : Integer;
var
i : Integer;
begin
Result := 0;
for i := 0 to High(FColWidths) do
begin
Result := Result + FColWidths[i] + Space;
end; // for
end;
var
i, w : Integer;
Col, Row : Integer;
c : Char;
s : string;
begin
if MacroName = 'Cell' then
begin
Col := LoopCounterStr['Cols'];
Row := LoopCounterStr['Rows'] + 1;
w := GetWidth(Col, Row);
MacroResult := MainForm.StringGrid.Cells[Col, Row];
if w > 0 then
MacroResult := SetStrWidth(MacroResult, w);
end
else
if MacroName = 'CellHeader' then
begin
Col := LoopCounterStr['Header'];
w := GetWidth(Col, 0);
MacroResult := MainForm.StringGrid.Cells[Col, 0];
if w > 0 then
MacroResult := SetStrWidth(MacroResult, w);
end
else
if MacroName = 'Row' then
begin
Row := LoopCounterStr['Rows'] + 1;
w := GetWidth(-1, Row);
MacroResult := MainForm.StringGrid.Cells[0, Row];
if MainForm.StringGrid.ColCount > 1 then
MacroResult := MacroResult + ' ';
for i := 1 to MainForm.StringGrid.ColCount - 1 do
begin
if i <> 1 then
MacroResult := MacroResult + ', ';
MacroResult := MacroResult + #39 + MainForm.StringGrid.Cells[i, Row] + #39;
end; // for
if w > 0 then
MacroResult := SetStrWidth(MacroResult, w);
end
else
if MacroName = 'FileName' then
begin
i := TagParameters.FindItemByName('offset');
if i < 0 then
i := 0
else
i := StrToInt(TagParameters.Value[i]);
MacroResult := ExtractFileName(GetFileName(PageCount + i));
end
else
if MacroName = 'FileNumb' then
begin
i := TagParameters.FindItemByName('offset');
if i < 0 then
i := 0
else
i := StrToInt(TagParameters.Value[i]);
MacroResult := IntToStr(PageCount + i);
end
else
if MacroName = 'TotalFileNumb' then
begin
MacroResult := IntToStr(GetTotalFilesCount);
end
else
if MacroName = 'Separator' then
begin
i := TagParameters.FindItemByName('spacecol');
if i < 0 then
i := 0
else
i := StrToInt(TagParameters.Value[i]);
w := CalcSeparatorWidth(i);
i := TagParameters.FindItemByName('space');
if i < 0 then
i := 0
else
i := StrToInt(TagParameters.Value[i]);
inc(w, i);
i := TagParameters.FindItemByName('char');
if i < 0 then
c := '-'
else begin
s := TagParameters.Value[i];
if Length(s) > 0 then
c := s[1]
else
c := '-';
end;
SetLength(MacroResult, w);
if w > 0 then
Fillchar(MacroResult[1], w, c);
end
else
// Raise Exception.Create('Unknown macro name');
MacroResult := 'Unknown macro name';
end;{TDemoMLGen.MacroFound}
procedure TDemoMLGen.PageBegin(PageNumb : integer);
begin
if Assigned(FOutputStream) then
Raise Exception.Create('Internal error. Outpust stream already exist.');
FOutputStream := TFileStream.Create(GetFileName(PageNumb), fmCreate or fmShareDenyWrite);
end;{TDemoMLGen.PageBegin}
procedure TDemoMLGen.PageEnd(PageNumb : integer);
begin
FOutputStream.Free;
FOutputStream := nil;
end;{TDemoMLGen.PageEnd}
procedure TDemoMLGen.WriteString(Value : string);
begin
FOutputStream.WriteBuffer(Value[1], Length(Value));
end;{TDemoMLGen.WriteString}
end.
|
unit clContatoEntregador;
interface
uses
clContatos, clConexao;
type
TContatoEntregador = class(TContatos)
private
constructor Create;
destructor Destroy;
function getCodigo: Integer;
function getSequencia: Integer;
procedure setCodigo(const Value: Integer);
procedure setSequencia(const Value: Integer);
protected
_codigo: Integer;
_sequencia: Integer;
_conexao: TConexao;
public
property Codigo: Integer read getCodigo write setCodigo;
property Sequencia: Integer read getSequencia write setSequencia;
procedure MaxSeq;
function Validar(): Boolean;
function Delete(filtro: String): Boolean;
function getObject(Id: String; filtro: String): Boolean;
function Insert(): Boolean;
function Update(): Boolean;
end;
const
TABLENAME = 'TBCONTATOSENTREGADORES';
implementation
uses SysUtils, Dialogs, udm, clUtil, ZDataset, ZAbstractRODataset, DB;
{ TContatoEntregador }
constructor TContatoEntregador.Create;
begin
_conexao := TConexao.Create;
if (not _conexao.VerifyConnZEOS(0)) then
begin
MessageDlg('Erro ao estabelecer conexão ao banco de dados (' +
Self.ClassName + ') !', mtError, [mbCancel], 0);
end;
end;
destructor TContatoEntregador.Destroy;
begin
_conexao.Free;
end;
function TContatoEntregador.getCodigo: Integer;
begin
Result := _codigo;
end;
function TContatoEntregador.getSequencia: Integer;
begin
Result := _sequencia;
end;
procedure TContatoEntregador.MaxSeq;
begin
Try
with dm.QryGetObject do
begin
Close;
SQL.Clear;
SQL.Text := 'SELECT MAX(SEQ_CONTATO) AS SEQUENCIA FROM ' + TABLENAME +
' WHERE COD_ENTREGADOR = :CODIGO';
ParamByName('CODIGO').AsString := IntToStr(Self.Codigo);
dm.ZConn.PingServer;
Open;
if not(IsEmpty) then
First;
end;
Self.Sequencia := (dm.QryGetObject.FieldByName('SEQUENCIA').AsInteger) + 1;
dm.QryGetObject.Close;
dm.QryGetObject.SQL.Clear;
Except
on E: Exception do
ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' +
E.Message);
end;
end;
function TContatoEntregador.Validar(): Boolean;
begin
Result := False;
if not(TUtil.Empty(Self.EMail)) then
begin
if not(TUtil.ValidaEMail(pChar(Self.EMail))) then
begin
MessageDlg('Endereço de E-Mail inválido.', mtWarning, [mbOK], 0);
Exit;
end;
end;
Result := True;
end;
function TContatoEntregador.Delete(filtro: String): Boolean;
begin
try
Result := False;
with dm.QryCRUD do
begin
Close;
SQL.Clear;
SQL.Add('DELETE FROM ' + TABLENAME);
if filtro = 'CODIGO' then
begin
SQL.Add('WHERE COD_ENTREGADOR =:CODIGO');
ParamByName('CODIGO').AsInteger := Self.Codigo;
end
else if filtro = 'TIPO' then
begin
SQL.Add('WHERE COD_ENTREGADOR =:CODIGO AND SEQ_CONTATO = :SEQUENCIA');
ParamByName('CODIGO').AsInteger := Self.Codigo;
ParamByName('SEQUENCIA').AsInteger := Self.Sequencia;
end;
dm.ZConn.PingServer;
ExecSQL;
end;
dm.QryCRUD.Close;
dm.QryCRUD.SQL.Clear;
Result := True;
Except
on E: Exception do
ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' +
E.Message);
end;
end;
function TContatoEntregador.getObject(Id, filtro: String): Boolean;
begin
try
Result := False;
if TUtil.Empty(Id) then
Exit;
with dm.QryGetObject do
begin
Close;
SQL.Clear;
SQL.Add('SELECT * FROM ' + TABLENAME);
if filtro = 'SEQUENCIA' then
begin
SQL.Add(' WHERE COD_ENTREGADOR = :CODIGO AND SEQ_CONTATO = :SEQUENCIA');
ParamByName('CODIGO').AsInteger := Self.Codigo;
ParamByName('SEQUENCIA').AsInteger := StrToInt(Id);
end
else if filtro = 'CODIGO' then
begin
SQL.Add(' WHERE COD_ENTREGADOR = :CODIGO');
ParamByName('CODIGO').AsInteger := StrToInt(Id);
end;
dm.ZConn.PingServer;
Open;
if not IsEmpty then
First;
end;
if dm.QryGetObject.RecordCount > 0 then
begin
if filtro = 'SEQUENCIA' then
begin
Self.Codigo := dm.QryGetObject.FieldByName('COD_ENTREGADOR').AsInteger;
Self.Sequencia := dm.QryGetObject.FieldByName('SEQ_CONTATO').AsInteger;
Self.Contato := dm.QryGetObject.FieldByName('DES_CONTATO').AsString;
Self.Telefone := dm.QryGetObject.FieldByName('NUM_TELEFONE').AsString;
Self.EMail := dm.QryGetObject.FieldByName('DES_EMAIL').AsString;
dm.QryGetObject.Close;
dm.QryGetObject.SQL.Clear;
Result := True;
end;
Result := True;
end
else
begin
dm.QryGetObject.Close;
dm.QryGetObject.SQL.Clear;
end;
Except
on E: Exception do
ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' +
E.Message);
end;
end;
function TContatoEntregador.Insert(): Boolean;
begin
try
Result := False;
MaxSeq;
with dm.QryCRUD do
begin
Close;
SQL.Clear;
SQL.Text := 'INSERT INTO ' + TABLENAME + ' ( ' + 'COD_ENTREGADOR, ' +
'SEQ_CONTATO, ' + 'DES_CONTATO, ' + 'NUM_TELEFONE, ' + 'DES_EMAIL ' +
') ' + 'VALUES(' + ':CODIGO, ' + ':SEQUENCIA, ' + ':CONTATO, ' +
':TELEFONE, ' + ':EMAIL ' + ') ';
ParamByName('CODIGO').AsInteger := Self.Codigo;
ParamByName('SEQUENCIA').AsInteger := Self.Sequencia;
ParamByName('CONTATO').AsString := Self.Contato;
ParamByName('TELEFONE').AsString := Self.Telefone;
ParamByName('EMAIL').AsString := Self.EMail;
dm.ZConn.PingServer;
ExecSQL;
end;
dm.QryCRUD.Close;
dm.QryCRUD.SQL.Clear;
Result := True;
Except
on E: Exception do
ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' +
E.Message);
end;
end;
function TContatoEntregador.Update(): Boolean;
begin
try
Result := False;
with dm.QryCRUD do
begin
Close;
SQL.Clear;
SQL.Text := 'UPDATE ' + TABLENAME + ' SET ' + 'DES_CONTATO = :CONTATO, ' +
'NUM_TELEFONE = :TELEFONE, ' + 'DES_EMAIL = :EMAIL ' + 'WHERE ' +
'COD_ENTREGADOR = :CODIGO AND SEQ_CONTATO = :SEQUENCIA';
ParamByName('CODIGO').AsInteger := Self.Codigo;
ParamByName('SEQUENCIA').AsInteger := Self.Sequencia;
ParamByName('CONTATO').AsString := Self.Contato;
ParamByName('TELEFONE').AsString := Self.Telefone;
ParamByName('EMAIL').AsString := Self.EMail;
dm.ZConn.PingServer;
ExecSQL;
end;
dm.QryCRUD.Close;
dm.QryCRUD.SQL.Clear;
Result := True;
Except
on E: Exception do
ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' +
E.Message);
end;
end;
procedure TContatoEntregador.setCodigo(const Value: Integer);
begin
_codigo := Value;
end;
procedure TContatoEntregador.setSequencia(const Value: Integer);
begin
_sequencia := Value;
end;
end.
|
unit fcDemoRichEdit;
{
//
// Components : TfcDemoRichEdit
//
// Copyright (c) 1999 by Woll2Woll Software
//
}
interface
{$i fcIfDef.pas}
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ComCtrls;
type
TfcDemoRichEdit = class(TCustomRichEdit)
private
ReloadStream: TStream;
UseReloadStream: boolean;
protected
procedure GetLines(Stream: TStream); virtual;
procedure SetLines(Stream: TStream); virtual;
procedure DefineProperties(Filer: TFiler); override;
procedure CreateWnd; override;
procedure DestroyWnd; override;
public
destructor Destroy; override;
published
property Align;
property Alignment;
property BorderStyle;
property Color;
property Ctl3D;
property DragCursor;
property DragMode;
property Enabled;
property Font;
property HideSelection;
property HideScrollBars;
property ImeMode;
property ImeName;
// property Lines;
property MaxLength;
property ParentColor;
property ParentCtl3D;
property ParentFont;
property ParentShowHint;
property PlainText;
property PopupMenu;
property ReadOnly;
property ScrollBars;
property ShowHint;
property TabOrder;
property TabStop default True;
property Visible;
property WantTabs;
property WantReturns;
property WordWrap;
property OnChange;
property OnDragDrop;
property OnDragOver;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnResizeRequest;
property OnSelectionChange;
property OnStartDrag;
property OnProtectChange;
property OnSaveClipboard;
end;
implementation
procedure TfcDemoRichEdit.DefineProperties(Filer: TFiler);
begin
inherited;
Filer.DefineBinaryProperty('RichEditLines', GetLines, SetLines, True);
end;
procedure TfcDemoRichEdit.GetLines(Stream: TStream);
begin
Lines.LoadFromStream(Stream);
end;
procedure TfcDemoRichEdit.SetLines(Stream: TStream);
begin
Lines.SaveToStream(Stream);
end;
procedure TfcDemoRichEdit.CreateWnd;
begin
inherited CreateWnd;
{ Stream in after setting ole callback routines }
if (useReloadStream) and (ReloadStream<>nil) then begin
ReloadStream.position:= 0;
Lines.LoadFromStream(ReloadStream);
end;
end;
procedure TfcDemoRichEdit.DestroyWnd;
begin
useReloadStream:= False;
if not (csDestroying in ComponentState) then
begin
if ReloadStream=Nil then ReloadStream:= TMemoryStream.create
else ReloadStream.position:= 0;
Lines.SaveToStream(ReloadStream);
useReloadStream:= True;
end;
inherited DestroyWnd;
end;
destructor TfcDemoRichEdit.Destroy;
begin
ReloadStream.Free;
inherited Destroy;
end;
end.
|
unit sdlgameinterface;
{
$Id: sdlgameinterface.pas,v 1.4 2005/08/03 18:57:31 savage Exp $
}
{******************************************************************************}
{ }
{ JEDI-SDL : Pascal units for SDL - Simple DirectMedia Layer }
{ Game Interface Base class }
{ }
{ The initial developer of this Pascal code was : }
{ Dominqiue Louis <Dominique@SavageSoftware.com.au> }
{ }
{ Portions created by Dominqiue Louis are }
{ Copyright (C) 2000 - 2001 Dominqiue Louis. }
{ }
{ }
{ Contributor(s) }
{ -------------- }
{ }
{ }
{ Obtained through: }
{ Joint Endeavour of Delphi Innovators ( Project JEDI ) }
{ }
{ You may retrieve the latest version of this file at the Project }
{ JEDI home page, located at http://delphi-jedi.org }
{ }
{ The contents of this file are used with permission, 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/MPL-1.1.html }
{ }
{ Software distributed under the License is distributed on an }
{ "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or }
{ implied. See the License for the specific language governing }
{ rights and limitations under the License. }
{ }
{ Description }
{ ----------- }
{ }
{ }
{ }
{ }
{ }
{ }
{ }
{ Requires }
{ -------- }
{ The SDL Runtime libraris on Win32 : SDL.dll on Linux : libSDL.so }
{ They are available from... }
{ http://www.libsdl.org . }
{ }
{ Programming Notes }
{ ----------------- }
{ }
{ }
{ }
{ }
{ Revision History }
{ ---------------- }
{ September 23 2004 - DL : Initial Creation }
{
$Log: sdlgameinterface.pas,v $
Revision 1.4 2005/08/03 18:57:31 savage
Various updates and additions. Mainly to handle OpenGL 3D Window support and better cursor support for the mouse class
Revision 1.3 2004/10/17 18:41:49 savage
Slight Change to allow Reseting of Input Event handlers
Revision 1.2 2004/09/30 22:35:47 savage
Changes, enhancements and additions as required to get SoAoS working.
}
{******************************************************************************}
interface
uses
sdl,
sdlwindow;
type
TGameInterfaceClass = class of TGameInterface;
TGameInterface = class( TObject )
private
FNextGameInterface : TGameInterfaceClass;
protected
Dragging : Boolean;
Loaded : Boolean;
procedure FreeSurfaces; virtual;
procedure Render; virtual; abstract;
procedure Close; virtual;
procedure Update( aElapsedTime : single ); virtual;
procedure MouseDown( Button : Integer; Shift: TSDLMod; MousePos : TPoint ); virtual;
procedure MouseMove( Shift: TSDLMod; CurrentPos : TPoint; RelativePos : TPoint ); virtual;
procedure MouseUp( Button : Integer; Shift: TSDLMod; MousePos : TPoint ); virtual;
procedure MouseWheelScroll( WheelDelta : Integer; Shift: TSDLMod; MousePos : TPoint ); virtual;
procedure KeyDown( var Key: TSDLKey; Shift: TSDLMod; unicode : UInt16 ); virtual;
public
MainWindow : TSDLCustomWindow;
procedure ResetInputManager;
procedure LoadSurfaces; virtual;
function PointIsInRect( Point : TPoint; x, y, x1, y1 : integer ) : Boolean;
constructor Create( const aMainWindow : TSDLCustomWindow );
destructor Destroy; override;
property NextGameInterface : TGameInterfaceClass read FNextGameInterface write FNextGameInterface;
end;
implementation
{ TGameInterface }
procedure TGameInterface.Close;
begin
FNextGameInterface := nil;
end;
constructor TGameInterface.Create( const aMainWindow : TSDLCustomWindow );
begin
inherited Create;
MainWindow := aMainWindow;
FNextGameInterface := TGameInterface;
ResetInputManager;
end;
destructor TGameInterface.Destroy;
begin
if Loaded then
FreeSurfaces;
inherited;
end;
procedure TGameInterface.FreeSurfaces;
begin
Loaded := False;
end;
procedure TGameInterface.KeyDown(var Key: TSDLKey; Shift: TSDLMod; unicode: UInt16);
begin
end;
procedure TGameInterface.LoadSurfaces;
begin
Loaded := True;
end;
procedure TGameInterface.MouseDown(Button: Integer; Shift: TSDLMod; MousePos: TPoint);
begin
Dragging := True;
end;
procedure TGameInterface.MouseMove(Shift: TSDLMod; CurrentPos, RelativePos: TPoint);
begin
end;
procedure TGameInterface.MouseUp(Button: Integer; Shift: TSDLMod; MousePos: TPoint);
begin
Dragging := True;
end;
procedure TGameInterface.MouseWheelScroll(WheelDelta: Integer; Shift: TSDLMod; MousePos: TPoint);
begin
end;
function TGameInterface.PointIsInRect( Point : TPoint; x, y, x1, y1: integer ): Boolean;
begin
if ( Point.x >= x )
and ( Point.y >= y )
and ( Point.x <= x1 )
and ( Point.y <= y1 ) then
result := true
else
result := false;
end;
procedure TGameInterface.ResetInputManager;
var
temp : TSDLNotifyEvent;
begin
MainWindow.InputManager.Mouse.OnMouseDown := MouseDown;
MainWindow.InputManager.Mouse.OnMouseMove := MouseMove;
MainWindow.InputManager.Mouse.OnMouseUp := MouseUp;
MainWindow.InputManager.Mouse.OnMouseWheel := MouseWheelScroll;
MainWindow.InputManager.KeyBoard.OnKeyDown := KeyDown;
temp := Render;
MainWindow.OnRender := temp;
temp := Close;
MainWindow.OnClose := temp;
MainWindow.OnUpdate := Update;
end;
procedure TGameInterface.Update(aElapsedTime: single);
begin
end;
end.
|
unit Main;
{$mode objfpc}{$H+}
interface
uses
Classes, Forms, Controls, Dialogs, StdCtrls, ComCtrls, Menus, ActnList,
ExtCtrls, LCLIntf, LCLType, IRC, ChannelList, SysUtils, IRCViewIntf;
type
{ TMainForm }
TMainForm = class(TForm, IIRCView)
ActionExit: TAction;
ActionPart: TAction;
ActionCloseTab: TAction;
ActionChat: TAction;
ActionCloseChat: TAction;
ActionConfig: TAction;
ActionConnect: TAction;
ActionDisconnect: TAction;
ActionList: TActionList;
EditFilter: TEdit;
EditInput: TEdit;
ImageListTrayIcons: TImageList;
MainMenu: TMainMenu;
MemoServidor: TMemo;
MenuItemExit: TMenuItem;
MenuItemConnect: TMenuItem;
MenuItemDisconnect: TMenuItem;
MenuItemCloseChannel: TMenuItem;
MenuItemCloseChat: TMenuItem;
MenuItemChat: TMenuItem;
MenuItemCloseTab: TMenuItem;
MenuItemCloseActiveTab: TMenuItem;
MenuItemConfig: TMenuItem;
MenuItemServer: TMenuItem;
PageControl: TPageControl;
PanelRoot: TPanel;
PanelLeft: TPanel;
PanelRight: TPanel;
PopupMenuTray: TPopupMenu;
PopupMenuPageControl: TPopupMenu;
PopupMenuTreeView: TPopupMenu;
StatusBar: TStatusBar;
TabServer: TTabSheet;
TimerPing: TTimer;
TimerConnection: TTimer;
TrayIcon: TTrayIcon;
TreeViewUsers: TTreeView;
procedure ActionChatExecute(Sender: TObject);
procedure ActionPartExecute(Sender: TObject);
procedure ActionCloseChatExecute(Sender: TObject);
procedure ActionCloseTabExecute(Sender: TObject);
procedure ActionConnectExecute(Sender: TObject);
procedure ActionConfigExecute(Sender: TObject);
procedure ActionDisconnectExecute(Sender: TObject);
procedure ActionExitExecute(Sender: TObject);
procedure EditFilterKeyDown(Sender: TObject; var Key: word; Shift: TShiftState);
procedure EditFilterKeyUp(Sender: TObject; var Key: word; Shift: TShiftState);
procedure EditInputKeyDown(Sender: TObject; var Key: word; Shift: TShiftState);
procedure EditInputKeyUp(Sender: TObject; var Key: word; Shift: TShiftState);
procedure ApplicationActivate(Sender: TObject);
procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
procedure FormShow(Sender: TObject);
procedure FormWindowStateChange(Sender: TObject);
procedure PageControlChange(Sender: TObject);
procedure PageControlMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: integer);
procedure PopupMenuTreeViewPopup(Sender: TObject);
procedure TimerConnectionTimer(Sender: TObject);
procedure TimerPingTimer(Sender: TObject);
procedure TrayIconClick(Sender: TObject);
procedure TreeViewUsersDblClick(Sender: TObject);
procedure TreeViewUsersSelectionChanged(Sender: TObject);
private
FIRC: TIRC;
FChannelList: TChannelList;
procedure AddNicksToChannel(const Channel: TChannel; const List: TStrings);
procedure AddNicksToTreeView(const Channel: TChannel);
procedure AddUserToTreeView(const User: TUser; const Channel: TChannel);
procedure ConfigureMemo(var Memo: TMemo);
procedure SetColors;
function GetTab(const ACaption: string): TObject;
function GetNode(const ACaption: string; ParentNode: TObject): TObject;
function IsActiveTabChannel: boolean;
function IsChatTabOpen(const Nome: string): boolean;
function IsSelectedNodeUser: boolean;
function IsSelectedNodeChannel: boolean;
procedure MostrarConfig;
procedure OnNickListReceived(const ChannelName: string; List: TStrings);
procedure OnMessageReceived(const Channel, Message: string; OwnMessage: boolean);
procedure UpdateNodeText(Node: TObject; AText: string);
procedure UpdateTabCaption(Tab: TObject; ACaption: string);
procedure RemoveChannelFromList(const Channel: string);
procedure RemoveNickFromChannelList(const Nick: string; const ChannelName: string);
procedure OnShowPopup(const Msg: string);
function GetTabByName(const Channel: string): TTabSheet;
function NewChannelTab(const Channel: string): TTabSheet;
procedure SelectChannelTab;
procedure SetFocusEditInput;
procedure StopTrayIconAnimation;
procedure ServerMessage(const AText: string);
procedure NotifyChanged;
public
constructor Create(TheOwner: TComponent); override;
destructor Destroy; override;
end;
var
MainForm: TMainForm;
implementation
uses FileUtil, ConfigForm, config, StringUtils, IRCUtils, TreeviewHelper;
{$R *.lfm}
const
DefaultFontSize = 11;
BackGroundColor = $00222827;
FontColor = $00D0D0D0;
LightColor = $00D0D0D0;
procedure TMainForm.ActionDisconnectExecute(Sender: TObject);
begin
FIRC.Disconnect;
end;
procedure TMainForm.ActionExitExecute(Sender: TObject);
begin
Close;
end;
procedure TMainForm.EditFilterKeyDown(Sender: TObject; var Key: word; Shift: TShiftState);
begin
if (Key = VK_RETURN) and IsSelectedNodeUser then
ActionChat.Execute;
end;
procedure TMainForm.EditFilterKeyUp(Sender: TObject; var Key: word; Shift: TShiftState);
begin
if Key = VK_RETURN then
Exit;
TreeViewUsers.BeginUpdate;
try
TreeViewUsers.FilterNodes(EditFilter.Text);
TreeViewUsers.FullExpand;
finally
TreeViewUsers.EndUpdate;
end;
end;
procedure TMainForm.EditInputKeyDown(Sender: TObject; var Key: word; Shift: TShiftState);
var
word, Nick: string;
CarretPos: TPoint;
begin
if (key <> VK_TAB) or (EditInput.Text = '') then
Exit;
word := TStringUtils.GetWordAtCursor(EditInput.Text, EditInput.CaretPos.x);
Nick := FChannelList.AutoComplete(FIRC.ActiveChannel, word);
if Nick <> '' then
begin
EditInput.Text := StringReplace(EditInput.Text, word, Nick, []);
CarretPos.x := Pos(Nick, EditInput.Text) + Length(Nick);
CarretPos.y := EditInput.CaretPos.y;
EditInput.CaretPos := CarretPos;
end;
Key := VK_UNDEFINED;
end;
procedure TMainForm.ActionConnectExecute(Sender: TObject);
begin
FIRC.Connect;
end;
procedure TMainForm.ActionConfigExecute(Sender: TObject);
begin
MostrarConfig;
end;
procedure TMainForm.ActionCloseChatExecute(Sender: TObject);
begin
GetTabByName(TIRCUtils.RemoveOPVoicePrefix(TreeViewUsers.Selected.Text)).Free;
end;
procedure TMainForm.ActionCloseTabExecute(Sender: TObject);
var
TabToClose: TTabSheet;
begin
if PageControl.ActivePage = nil then
Exit;
if Sender is TTabSheet then
TabToClose := TTabSheet(Sender)
else
TabToClose := PageControl.ActivePage;
if TabToClose = TabServer then
Exit;
if IsActiveTabChannel then
FIRC.Part(PageControl.ActivePage.Caption)
else
GetTabByName(PageControl.ActivePage.Caption).Free;
end;
procedure TMainForm.ActionChatExecute(Sender: TObject);
begin
SelectChannelTab;
end;
procedure TMainForm.ActionPartExecute(Sender: TObject);
begin
FIRC.Part(TreeViewUsers.Selected.Text);
end;
procedure TMainForm.EditInputKeyUp(Sender: TObject; var Key: word; Shift: TShiftState);
begin
if Key <> VK_RETURN then
Exit;
FIRC.SendMessage(EditInput.Text);
EditInput.Clear;
end;
procedure TMainForm.ApplicationActivate(Sender: TObject);
begin
StopTrayIconAnimation;
end;
procedure TMainForm.FormClose(Sender: TObject; var CloseAction: TCloseAction);
begin
FIRC.Disconnect;
end;
procedure TMainForm.FormShow(Sender: TObject);
begin
if FIRC.IsConnected then
Exit;
if not FileExistsUTF8(DefaultConfigFile) then
MostrarConfig;
FIRC.Connect;
end;
procedure TMainForm.FormWindowStateChange(Sender: TObject);
begin
AutoScroll := WindowState <> wsMinimized;
end;
procedure TMainForm.OnMessageReceived(const Channel, Message: string; OwnMessage: boolean);
var
Tab: TTabSheet;
Memo: TMemo;
function NickNameInMessage: boolean;
begin
Result := (Pos(FIRC.NickName, Message) > 0);
end;
function AnimateTrayIcon: boolean;
begin
Result := (not OwnMessage) and (not Application.Active) and ((Channel[1] <> '#') or NickNameInMessage);
end;
begin
if Message = '' then
Exit;
if AnimateTrayIcon then
TrayIcon.Animate := True; //Should not toggle, more messages may have triggered this
Tab := GetTab(Channel) as TTabSheet;
Memo := Tab.Components[0] as TMemo;
Memo.Lines.Add(Message);
end;
procedure TMainForm.UpdateTabCaption(Tab: TObject; ACaption: string);
begin
(Tab as TTabSheet).Caption := ACaption;
end;
procedure TMainForm.UpdateNodeText(Node: TObject; AText: string);
begin
(Node as TTreeNode).Text := AText;
end;
procedure TMainForm.MostrarConfig;
var
F: TFormConfig;
begin
F := TFormConfig.Create(nil);
try
F.ShowModal;
finally
F.Free;
end;
end;
procedure TMainForm.ConfigureMemo(var Memo: TMemo);
begin
Memo.Align := alClient;
Memo.ScrollBars := ssVertical;
Memo.ReadOnly := True;
Memo.Cursor := crArrow;
Memo.Font.Size := DefaultFontSize;
Memo.TabStop := False;
Memo.BorderStyle := bsSingle;
Memo.Color := BackGroundColor;
Memo.Font.Color := FontColor;
Memo.Invalidate;
end;
procedure TMainForm.SetColors;
begin
EditFilter.Color := LightColor;
EditInput.Color := BackGroundColor;
;
EditInput.Font.Color := FontColor;
TreeViewUsers.BackgroundColor := LightColor;
end;
function TMainForm.GetTab(const ACaption: string): TObject;
var
ChannelName: string;
begin
ChannelName := TIRCUtils.RemoveOPVoicePrefix(ACaption);
Result := GetTabByName(ChannelName);
if Result = nil then
Result := NewChannelTab(ChannelName);
end;
function TMainForm.GetNode(const ACaption: string; ParentNode: TObject): TObject;
begin
if ParentNode = nil then
Result := TreeViewUsers.Items.Add(nil, ACaption)
else
Result := TreeViewUsers.Items.AddChild(ParentNode as TTreeNode, ACaption);
TreeViewUsers.AlphaSort;
end;
function TMainForm.IsActiveTabChannel: boolean;
begin
Result := TreeViewUsers.Items.FindTopLvlNode(PageControl.ActivePage.Caption) <> nil;
end;
function TMainForm.IsChatTabOpen(const Nome: string): boolean;
begin
Result := GetTabByName(TIRCUtils.RemoveOPVoicePrefix(Nome)) <> nil;
end;
function TMainForm.IsSelectedNodeUser: boolean;
begin
Result := (TreeViewUsers.Selected <> nil) and (TreeViewUsers.Selected.Parent <> nil);
end;
function TMainForm.IsSelectedNodeChannel: boolean;
begin
Result := (TreeViewUsers.Selected <> nil) and (TreeViewUsers.Selected.Parent = nil);
end;
procedure TMainForm.AddNicksToChannel(const Channel: TChannel; const List: TStrings);
var
Nick: string;
begin
for Nick in List do
Channel.Users.Add(TUser.Create(Nick));
end;
procedure TMainForm.AddNicksToTreeView(const Channel: TChannel);
var
User: TUser;
begin
TreeViewUsers.BeginUpdate;
try
Channel.Node := TreeViewUsers.Items.FindTopLvlNode(Channel.Name);
for User in Channel.Users do
User.Node := TreeViewUsers.Items.AddChild(TTreeNode(Channel.Node), User.NickNameInChannel);
TreeViewUsers.AlphaSort;
finally
TreeViewUsers.EndUpdate;
end;
end;
procedure TMainForm.AddUserToTreeView(const User: TUser; const Channel: TChannel);
begin
User.Node := TreeViewUsers.Items.AddChild(TTreeNode(Channel.Node), User.NickNameInChannel);
TreeViewUsers.AlphaSort;
end;
procedure TMainForm.PageControlChange(Sender: TObject);
begin
if PageControl.ActivePage = TabServer then
FIRC.ActiveChannel := ''
else
FIRC.ActiveChannel := PageControl.ActivePage.Caption;
SetFocusEditInput;
end;
procedure TMainForm.PageControlMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: integer);
var
TabIndex: integer;
begin
if Button <> mbRight then
Exit;
TabIndex := PageControl.IndexOfTabAt(X, Y);
if TabIndex >= 0 then
PageControl.ActivePage := PageControl.Pages[TabIndex];
end;
procedure TMainForm.PopupMenuTreeViewPopup(Sender: TObject);
var
IsChatOpen: boolean;
begin
IsChatOpen := IsChatTabOpen(TreeViewUsers.Selected.Text);
ActionPart.Visible := IsSelectedNodeChannel;
ActionChat.Visible := IsSelectedNodeUser and (not IsChatOpen);
ActionCloseChat.Visible := IsSelectedNodeUser and IsChatOpen;
end;
procedure TMainForm.TimerConnectionTimer(Sender: TObject);
begin
//TODO: Timer and this logic must be on the IRC class
if FIRC.IsConnected then
StatusBar.Panels[0].Text := Format('Connected. %s@%s', [FIRC.NickName, FIRC.HostName])
else
begin
StatusBar.Panels[0].Text := 'Disconnected. Reconnecting... \o/';
FIRC.Disconnect;
FIRC.Connect;
end;
end;
procedure TMainForm.TimerPingTimer(Sender: TObject);
begin
if FIRC.IsConnected then
FIRC.Ping;
end;
procedure TMainForm.TrayIconClick(Sender: TObject);
begin
StopTrayIconAnimation;
if WindowState = wsMinimized then
Application.Restore
else
Application.Minimize;
end;
procedure TMainForm.TreeViewUsersDblClick(Sender: TObject);
begin
SelectChannelTab;
end;
procedure TMainForm.TreeViewUsersSelectionChanged(Sender: TObject);
var
Selected: TTreeNode;
Tab: TTabSheet;
begin
Selected := TreeViewUsers.Selected;
if Selected = nil then
Exit;
Tab := GetTabByName(TIRCUtils.RemoveOPVoicePrefix(Selected.Text));
if Tab = nil then
Exit;
PageControl.ActivePage := Tab;
end;
procedure TMainForm.RemoveChannelFromList(const Channel: string);
begin
FChannelList.ChannelByName(Channel).Node.Free;
end;
procedure TMainForm.RemoveNickFromChannelList(const Nick: string; const ChannelName: string);
var
User: TUser;
Channel: TChannel;
begin
Channel := FChannelList.ChannelByName(ChannelName);
if Channel = nil then
Exit;
User := Channel.Users.UserByNick(Nick);
if (User <> nil) then
User.Node.Free;
end;
procedure TMainForm.OnShowPopup(const Msg: string);
begin
ShowMessage(Msg);
end;
function TMainForm.GetTabByName(const Channel: string): TTabSheet;
var
I: integer;
begin
for I := 0 to PageControl.PageCount - 1 do
begin
Result := PageControl.Pages[I];
if UpperCase(Result.Caption) = UpperCase(Channel) then
Exit;
end;
Result := nil;
end;
function TMainForm.NewChannelTab(const Channel: string): TTabSheet;
var
Memo: TMemo;
begin
Result := TTabSheet.Create(PageControl);
Result.PageControl := PageControl;
Result.Caption := Channel;
Memo := TMemo.Create(Result);
Memo.Parent := Result;
ConfigureMemo(Memo);
end;
procedure TMainForm.SelectChannelTab;
begin
if (TreeViewUsers.Selected = nil) or (TreeViewUsers.Selected.Parent = nil) then
Exit;
PageControl.ActivePage := GetTab(TreeViewUsers.Selected.Text) as TTabSheet;
end;
procedure TMainForm.SetFocusEditInput;
begin
if EditInput.CanFocus then
EditInput.SetFocus;
end;
procedure TMainForm.StopTrayIconAnimation;
begin
TrayIcon.Animate := False;
TrayIcon.Icon.Assign(Application.Icon);
end;
procedure TMainForm.ServerMessage(const AText: string);
begin
MemoServidor.Append(AText);
end;
procedure TMainForm.NotifyChanged;
begin
TreeViewUsers.Invalidate;
end;
procedure TMainForm.OnNickListReceived(const ChannelName: string; List: TStrings);
var
Channel: TChannel;
begin
Channel := FChannelList.ChannelByName(ChannelName);
AddNicksToChannel(Channel, List);
AddNicksToTreeView(Channel);
end;
constructor TMainForm.Create(TheOwner: TComponent);
begin
inherited Create(TheOwner);
Application.OnActivate := @ApplicationActivate;
TrayIcon.Icons := ImageListTrayIcons;
TrayIcon.AnimateInterval := 1250;
FChannelList := TChannelList.Create(Self);
FIRC := TIRC.Create(FChannelList);
FIRC.OnMessageReceived := @OnMessageReceived;
FIRC.OnNickListReceived := @OnNickListReceived;
FIRC.OnShowPopup := @OnShowPopup;
ConfigureMemo(MemoServidor);
SetColors;
end;
destructor TMainForm.Destroy;
begin
FIRC.Free;
FChannelList.Free;
inherited Destroy;
end;
end.
|
{ *********************************************************************************** }
{ * CryptoLib Library * }
{ * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * }
{ * Github Repository <https://github.com/Xor-el> * }
{ * Distributed under the MIT software license, see the accompanying file LICENSE * }
{ * or visit http://www.opensource.org/licenses/mit-license.php. * }
{ * Acknowledgements: * }
{ * * }
{ * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * }
{ * development of this library * }
{ * ******************************************************************************* * }
(* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *)
unit ClpStreamSorter;
interface
uses
Classes,
ClpStreamHelper,
ClpIndefiniteLengthInputStream,
ClpDefiniteLengthInputStream,
ClpConstructedOctetStream,
ClpCryptoLibTypes;
type
TStreamSorter = class sealed(TObject)
public
class function Read(input: TStream; var buffer: TCryptoLibByteArray;
offset, count: Int32): Int32; static;
class function ReadByte(input: TStream): Int32; static;
end;
implementation
{ TStreamSorter }
class function TStreamSorter.Read(input: TStream;
var buffer: TCryptoLibByteArray; offset, count: Int32): Int32;
begin
if input is TIndefiniteLengthInputStream then
begin
Result := (input as TIndefiniteLengthInputStream).
Read(buffer, offset, count);
end
else if input is TDefiniteLengthInputStream then
begin
Result := (input as TDefiniteLengthInputStream).Read(buffer, offset, count);
end
else if input is TConstructedOctetStream then
begin
Result := (input as TConstructedOctetStream).Read(buffer, offset, count);
end
else
begin
Result := input.Read(buffer[offset], count);
end;
end;
class function TStreamSorter.ReadByte(input: TStream): Int32;
begin
if input is TIndefiniteLengthInputStream then
begin
Result := (input as TIndefiniteLengthInputStream).ReadByte();
end
else if input is TDefiniteLengthInputStream then
begin
Result := (input as TDefiniteLengthInputStream).ReadByte();
end
else if input is TConstructedOctetStream then
begin
Result := (input as TConstructedOctetStream).ReadByte();
end
else
begin
Result := input.ReadByte();
end;
end;
end.
|
unit define_datasrc;
interface
uses
define_dealitem;
type
TDealDataSource = (
src_unknown,
src_all,
src_ctp,
src_offical,
src_tongdaxin,
src_tonghuasun,
src_dazhihui,
src_sina,
src_163,
src_qq,
src_xq
);
const
DataSrc_All = 1;
DataSrc_CTP = 11;
DataSrc_Standard = 12; // 来至官方 证券交易所
DataSrc_TongDaXin = 21; // 通达信
DataSrc_TongHuaSun = 22; // 同花顺
DataSrc_DaZhiHui = 23; // 大智慧
DataSrc_Sina = 31;
DataSrc_163 = 32;
DataSrc_QQ = 33;
DataSrc_XQ = 34; // 雪球
function GetDataSrcCode(ADataSrc: integer): AnsiString;
function GetStockCode_163(AStockItem: PRT_DealItem): AnsiString;
function GetStockCode_Sina(AStockItem: PRT_DealItem): AnsiString;
function GetStockCode_QQ(AStockItem: PRT_DealItem): AnsiString;
function GetDealDataSource(ASourceCode: integer): TDealDataSource;
function GetDealDataSourceCode(ASource: TDealDataSource): integer;
function GetDataSrcName(ADataSrc: TDealDataSource): string;
implementation
uses
define_dealmarket,
SysUtils;
(*//
上证指数
http://quotes.money.163.com/0000001.html#2b17
深证成指
http://quotes.money.163.com/1399001.html
沪深300
http://quotes.money.163.com/1399300.html
上证综合指数
http://finance.sina.com.cn/realstock/company/sh000001/nc.shtml
深证成份指数
http://finance.sina.com.cn/realstock/company/sz399001/nc.shtml
http://hq.sinajs.cn/list=s_sh000001,s_sz399001,s_sz399006
通达信
999999 上证
399001 深成指
//*)
function GetDataSrcName(ADataSrc: TDealDataSource): string;
begin
Result := '';
case ADataSrc of
Src_All: Result := 'All';
Src_CTP: Result := 'Ctp';
src_offical: Result := 'offical';
Src_tongdaxin: Result := 'TDX_tongdaxin';
Src_tonghuasun: Result := 'tonghuasun';
Src_dazhihui: Result := 'DZH_dazhihui';
Src_Sina: Result := 'sina';
Src_163: Result := '163';
Src_QQ: Result := 'qq';
Src_XQ: Result := 'xq';
end;
end;
function GetDealDataSource(ASourceCode: integer): TDealDataSource;
begin
Result := src_unknown;
case ASourceCode of
DataSrc_All: Result := src_all;
DataSrc_CTP: Result := src_ctp;
DataSrc_Standard: Result := src_offical;
DataSrc_tongdaxin: Result := src_tongdaxin;
DataSrc_tonghuasun: Result := src_tonghuasun;
DataSrc_dazhihui: Result := src_dazhihui;
DataSrc_Sina: Result := src_sina;
DataSrc_163: Result := src_163;
DataSrc_QQ: Result := src_qq;
DataSrc_XQ: Result := src_xq;
end;
end;
function GetDealDataSourceCode(ASource: TDealDataSource): integer;
begin
Result := 0;
case ASource of
src_all: Result := DataSrc_All;
src_ctp: Result := DataSrc_Ctp;
src_offical: Result := DataSrc_Standard;
src_tongdaxin: Result := DataSrc_tongdaxin;
src_tonghuasun: Result := DataSrc_tonghuasun;
src_dazhihui: Result := DataSrc_dazhihui;
src_sina: Result := DataSrc_sina;
src_163: Result := DataSrc_163;
src_qq: Result := DataSrc_qq;
src_xq: Result := DataSrc_xq;
end;
end;
function GetDataSrcCode(ADataSrc: integer): AnsiString;
begin
Result := '';
case ADataSrc of
DataSrc_CTP : Result := 'ctp';
DataSrc_Standard : Result := 'gov'; // official 来至官方 证券交易所
DataSrc_Sina : Result := 'sina';
DataSrc_163 : Result := '163';
DataSrc_QQ : Result := 'qq';
DataSrc_XQ : Result := 'xq'; // 雪球
DataSrc_TongDaXin : Result := 'tdx'; // 通达信
DataSrc_TongHuaSun : Result := 'ths'; // 同花顺
DataSrc_DaZhiHui : Result := 'dzh'; // 大智慧
end;
end;
function GetStockCode_163(AStockItem: PRT_DealItem): AnsiString;
var
tmpCode: string;
begin
Result := '';
tmpCode := getSimpleStockCodeByPackCode(AStockItem.iCode);
if DBType_Index_China = AStockItem.DBType then
begin
if '999999' = AStockItem.sCode then
begin
Result := '0' + '000001';
exit;
end;
end;
if Market_SH = AStockItem.sMarketCode then
begin
Result := '0' + tmpCode;
exit;
end;
if Market_SZ = AStockItem.sMarketCode then
begin
Result := '1' + tmpCode;
exit;
end;
if 6 = Length(tmpCode) then
begin
if tmpCode[1] = '6' then
begin
Result := '0' + tmpCode;
end else
begin
Result := '1' + tmpCode;
end;
end;
end;
// http://vip.stock.finance.sina.com.cn/corp/go.php/vMS_MarketHistory/stockid/000001/type/S.phtml
function GetStockCode_Sina(AStockItem: PRT_DealItem): AnsiString;
var
tmpCode: string;
begin
Result := '';
tmpCode := getSimpleStockCodeByPackCode(AStockItem.iCode);
if DBType_Index_China = AStockItem.DBType then
begin
if '999999' = AStockItem.sCode then
begin
Result := Market_SH + '000001';
exit;
end;
end;
if 6 = Length(tmpCode) then
begin
if tmpCode[1] = '6' then
begin
Result := Market_SH + tmpCode;
end else
begin
Result := Market_SZ + tmpCode;
end;
end;
end;
function GetStockCode_QQ(AStockItem: PRT_DealItem): AnsiString;
begin
Result := GetStockCode_Sina(AStockItem);
end;
end.
|
unit mnSynParamsHint;
{$mode objfpc}{$H+}
{**
* MiniLib project
*
* This file is part of the "Mini Library"
*
* @url http://www.sourceforge.net/projects/minilib
* @license modifiedLGPL (modified of http://www.gnu.org/licenses/lgpl.html)
* See the file COPYING.MLGPL, included in this distribution,
* @author Zaher Dirkey
*}
{$DEFINE HintClickWorkaround} // Workaround for issue 21952
interface
uses
Classes, SysUtils, Types, Character,
// LCL
LCLProc, LCLIntf, LCLType, LMessages, Graphics, Forms,
Controls, StdCtrls, ExtCtrls, Menus, Themes,
// LazUtils
LazUTF8,
// SynEdit
SynEditMiscProcs, SynEditKeyCmds, SynEdit, SynEditTypes, SynEditPlugins, mnSynCompletion;
type
TSynShowParamsHint = class;
{ TSynBaseHint }
TSynBaseHint = class(THintWindow)
private
FBorderColor: TColor;
FParamsHint: TSynShowParamsHint;
protected
public
constructor Create(AOwner: TComponent); override;
function CalcHintRect(MaxWidth: Integer; const AHint: string; AData: pointer): TRect; override;
procedure Paint; override;
property BorderColor: TColor read FBorderColor write FBorderColor;
end;
TOnGetHintString = procedure(AEditor: TCustomSynEdit; Token: string; ParamIndex: Integer; out AHint: String) of object;
TOnGetHintExists = procedure(AEditor: TCustomSynEdit; Token: string; FunctionsOnly: Boolean; var Exists: Boolean) of object;
{ TSynShowParamsHint }
TSynShowParamsHint = class(TLazSynMultiEditPlugin) //experimental
private
FEndOfTokenChr: string;
FHint: TSynBaseHint;
FExecCommandID: TSynEditorCommand;
FOnGetHintString: TOnGetHintString;
FOnGetHintExists: TOnGetHintExists;
FShortCut: TShortCut;
FParenChr: string;
FLongLineHintTime: Integer;
FHintTimer: TTimer;
FUsePrettyText: Boolean;
//Cache it
FLastToken: string;
FLastParamIndex: Integer;
FLastHint: string;
protected
function GetPreviousToken(aEditor: TCustomSynEdit; out Value: string; out Index: Integer): Boolean;
{$IFDEF HintClickWorkaround}
procedure HintWindowMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
{$ENDIF}
procedure OnHintTimer(Sender: TObject);
procedure ShowHint(AEditor: TCustomSynEdit);
function HideHint: Boolean;
procedure DoGetHintString(AEditor: TCustomSynEdit; Token: string; ParamIndex: Integer; out AHint: String); virtual;
function GetHintString(AEditor: TCustomSynEdit; Token: string; ParamIndex: Integer): string;
function DoGetHintExists(AEditor: TCustomSynEdit; Token: string): Boolean; virtual;
function GetHintExists(AEditor: TCustomSynEdit; Token: string): Boolean;
function FindFunction(AEditor: TCustomSynEdit; out charIndex, AIndex: Integer; out AString: string): Boolean;
function FindToken(AEditor: TCustomSynEdit; out charIndex, AIndex: Integer; out AString: string): Boolean;
procedure KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); virtual;
procedure StatusChange(Sender: TObject; Changes: TSynStatusChanges); virtual;
procedure SetEditor(const Value: TCustomSynEdit); override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure DoEditorAdded(AValue: TCustomSynEdit); override;
procedure DoEditorRemoving(AValue: TCustomSynEdit); override;
procedure SetShortCut(Value: TShortCut);
procedure TranslateKey(Sender: TObject; Code: word; SState: TShiftState;
var Data: pointer; var IsStartOfCombo: boolean; var Handled: boolean;
var Command: TSynEditorCommand; FinishComboOnly: Boolean;
var ComboKeyStrokes: TSynEditKeyStrokes);
procedure ProcessSynCommand(Sender: TObject; AfterProcessing: boolean;
var Handled: boolean; var Command: TSynEditorCommand;
var AChar: TUTF8Char; Data: pointer; HandlerData: pointer);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Execute(aEditor: TCustomSynEdit);
property Hint: TSynBaseHint read FHint;
published
//use () in pair
property ParenChr: string read FParenChr write FParenChr; //TODO
property ShortCut: TShortCut read FShortCut write SetShortCut;
property ExecCommandID: TSynEditorCommand read FExecCommandID write FExecCommandID;
property Editor;
property UsePrettyText: Boolean read FUsePrettyText write FUsePrettyText;
property EndOfTokenChr: string read FEndOfTokenChr write FEndOfTokenChr;
property OnGetHintString: TOnGetHintString read FOnGetHintString write FOnGetHintString;
property OnGetHintExists: TOnGetHintExists read FOnGetHintExists write FOnGetHintExists;
end;
implementation
{ TSynBaseHint }
constructor TSynBaseHint.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Canvas.Brush.Style := bsSolid;
BorderWidth := 1;
end;
function TSynBaseHint.CalcHintRect(MaxWidth: Integer; const AHint: string; AData: pointer): TRect;
var
S: string;
begin
if FParamsHint.UsePrettyText then
S := StripFormatCommands(Hint)
else
S := AHint;
Result := Rect(0, 0, Canvas.TextWidth(S) + BorderWidth * 2 + 4, Canvas.TextHeight(S) + BorderWidth * 2 + 4); //4 margines
end;
procedure TSynBaseHint.Paint;
var
R: TRect;
begin
//inherited;
R := ClientRect;
Canvas.Brush.Color := Color;
Canvas.Pen.Color := BorderColor;
Canvas.Pen.Width := BorderWidth;
// Canvas.FillRect(R);
Canvas.Rectangle(R);
InflateRect(R, -BorderWidth, -BorderWidth);
InflateRect(R, -2, -2);
if FParamsHint.UsePrettyText then
FormattedTextOut(Canvas, R, Hint, False, nil)
else
Canvas.TextOut(R.Left, R.Top, Hint);
end;
{ TSynShowParamsHint }
constructor TSynShowParamsHint.Create(AOwner: TComponent);
begin
inherited;
FParenChr := '()';
FShortCut := Menus.ShortCut(Ord(' '), [ssCtrl, ssShift]);
FExecCommandID := AllocatePluginKeyRange(1);
FHint := TSynBaseHint.Create(Self);
FHint.FParamsHint := Self;
FHint.FormStyle := fsSystemStayOnTop;
{$IFDEF HintClickWorkaround}
FHint.OnMouseDown :=@HintWindowMouseDown;
{$ENDIF}
FHintTimer := TTimer.Create(nil);
FHintTimer.Enabled := False;
FHintTimer.OnTimer := @OnHintTimer;
FHintTimer.Interval := 0;
FLongLineHintTime := 0;
end;
procedure TSynShowParamsHint.SetShortCut(Value: TShortCut);
begin
FShortCut := Value;
end;
destructor TSynShowParamsHint.Destroy;
begin
FreeAndNil(FHint);
FreeAndNil(FHintTimer);
inherited;
end;
procedure TSynShowParamsHint.Execute(aEditor: TCustomSynEdit);
begin
ShowHint(aEditor);
end;
procedure TSynShowParamsHint.TranslateKey(Sender: TObject; Code: word; SState: TShiftState;
var Data: pointer; var IsStartOfCombo: boolean; var Handled: boolean;
var Command: TSynEditorCommand; FinishComboOnly: Boolean;
var ComboKeyStrokes: TSynEditKeyStrokes);
var
i: integer;
ShortCutKey: Word;
ShortCutShift: TShiftState;
begin
if (Code = VK_UNKNOWN) or Handled or FinishComboOnly or (FExecCommandID = ecNone) then exit;
i := IndexOfEditor(Sender as TCustomSynEdit);
if i >= 0 then begin
ShortCutToKey(FShortCut, ShortCutKey, ShortCutShift);
if (SState = ShortCutShift) and (Code = ShortCutKey) then begin
Command := FExecCommandID;
Handled := True;
end;
end;
end;
function SynParamsHintCallBack(Sender:TObject; S: string): Boolean;
begin
Result := True;
end;
procedure TSynShowParamsHint.ProcessSynCommand(Sender: TObject; AfterProcessing: boolean;
var Handled: boolean; var Command: TSynEditorCommand; var AChar: TUTF8Char; Data: pointer;
HandlerData: pointer);
var
i: integer;
begin
if Handled or (Command <> FExecCommandID) then
exit;
i := IndexOfEditor(Sender as TCustomSynEdit);
if i >= 0 then begin
with sender as TCustomSynEdit do begin
if not ReadOnly then begin
Editor := Sender as TCustomSynEdit; // Will set Form.SetCurrentEditor
Execute(Editor);
Handled := True;
end;
end;
end;
end;
procedure TSynShowParamsHint.DoGetHintString(AEditor: TCustomSynEdit; Token: string; ParamIndex: Integer; out AHint: String);
begin
end;
function TSynShowParamsHint.GetHintString(AEditor: TCustomSynEdit; Token: string; ParamIndex: Integer): string;
begin
DoGetHintString(AEditor, Token, ParamIndex, Result);
if Assigned(FOnGetHintString) then
FOnGetHintString(AEditor, Token, ParamIndex, Result);
if Result = '' then
Result := Token;
end;
function TSynShowParamsHint.DoGetHintExists(AEditor: TCustomSynEdit; Token: string): Boolean;
begin
Result := True;
end;
function TSynShowParamsHint.GetHintExists(AEditor: TCustomSynEdit; Token: string): Boolean;
begin
Result := DoGetHintExists(AEditor, Token);
if Assigned(FOnGetHintExists) then
FOnGetHintExists(AEditor, Token, True, Result);
end;
//* ported from Delphi version of SynEdit example
//TODO need to bypass string " or ' with escape
function TSynShowParamsHint.FindFunction(AEditor: TCustomSynEdit; out charIndex, AIndex: Integer; out AString: string): Boolean;
var
aLine, lookup: string;
SavePos, X, StartX,
ParenCounter,
lLocation : Integer;
FoundMatch : Boolean;
begin
with Editor do
begin
aLine := LineText;
//go back from the cursor and find the first open paren
X := CaretX;
if X > length(aLine) then
X := length(aLine)
else
Dec(X);
AIndex := 0;
charIndex := 0;
FoundMatch := False;
lLocation := 0;
while (X > 0) and not(FoundMatch) do
begin
if aLine[X] = ',' then
begin
Inc(lLocation);
Dec(X);
end else if aLine[X] = ')' then
begin
//We found a close, go till it's opening paren
ParenCounter := 1;
dec(X);
while (X > 0) and (ParenCounter > 0) do
begin
if aLine[X] = ')' then inc(ParenCounter)
else if aLine[X] = '(' then dec(ParenCounter);
dec(X);
end;
if X > 0 then dec(X); //eat the open paren
end else if aLine[X] = '(' then
begin
//we have a valid open paren, lets see what the word before it is
StartX := X;
while (X > 0) and not IsIdentChar(aLine[X])do
Dec(X);
if X > 0 then
begin
SavePos := X;
While (X > 0) and IsIdentChar(aLine[X]) do
Dec(X);
Inc(X);
lookup := Copy(aLine, X, SavePos - X + 1);
FoundMatch := GetHintExists(AEditor, Lookup);
if FoundMatch then
begin
AString := lookup;
AIndex := lLocation;
charIndex := X;
end
else
begin
X := StartX;
dec(X);
end;
end;
end
else
Dec(X)
end;
end;
Result := FoundMatch;
end;
function TSynShowParamsHint.FindToken(AEditor: TCustomSynEdit; out charIndex, AIndex: Integer; out AString: string): Boolean;
var
StartX, EndX: integer;
Line: string;
begin
//if (agent == llGetOwner() || llGetPermiss|ions()) //* must return llGetPermissions
AEditor.GetWordBoundsAtRowCol(AEditor.LogicalCaretXY, StartX, EndX);
Line := AEditor.LineText;
AString := Copy(Line, StartX, EndX - StartX);
charIndex := StartX;
AIndex := 0;
Result := (AString <> '') and GetHintExists(AEditor, AString);
if not Result then
begin
Result := FindFunction(AEditor, charIndex, AIndex, AString);
//Result := AEditor.GetWordAtRowCol(AEditor.LogicalCaretXY);
//Result := GetPreviousToken(AEditor, Astring, charIndex);
end;
end;
procedure TSynShowParamsHint.ShowHint(AEditor: TCustomSynEdit);
var
R: TRect;
P: TPoint;
charIndex, paramIndex: Integer;
AToken: string;
begin
if FindToken(aEditor, charIndex, paramIndex, AToken) then
begin
FHintTimer.Enabled := False;
if AToken <> '' then
begin
if (FLastToken = AToken) and (FLastParamIndex = paramIndex) then //reduce recall huge find in list
FHint.Hint := FLastHint
else
begin
FHint.Hint := GetHintString(AEditor, AToken, paramIndex);
FLastToken := AToken;
FLastParamIndex := paramIndex;
FLastHint := FHint.Hint;
end;
if FHint.Hint <> '' then
begin
FHint.Font.Assign(AEditor.Font);
//* https://gitlab.com/freepascal.org/lazarus/lazarus/-/issues/32260
FHint.Font.PixelsPerInch := Screen.PixelsPerInch;
FHint.Color := AEditor.Color;
P := Point(charIndex, AEditor.LogicalCaretXY.Y);
P := AEditor.LogicalToPhysicalPos(P);
//charIndex := AEditor.LogicalToPhysicalPos(Point(charIndex, AEditor.LogicalCaretXY.Y));
P := AEditor.RowColumnToPixels(P);
P := AEditor.ClientToScreen(P);
P.Y := P.Y + AEditor.LineHeight + 1;
//P := AEditor.ClientToScreen(Point(AEditor.CaretXPix, AEditor.CaretYPix + AEditor.LineHeight + 1));
R := FHint.CalcHintRect(Application.MainForm.Monitor.Width, FHint.Hint, nil);
OffsetRect(R, P.X, P.Y);
//InflateRect(R, 2, 2);
FHint.HintRect := R;
if (not FHint.IsVisible) and (FLongLineHintTime > 0) then
FHintTimer.Enabled := True
else
OnHintTimer(nil);
end;
end
else
FHint.Hide;
end
else
FHint.Hide;
end;
function TSynShowParamsHint.GetPreviousToken(aEditor: TCustomSynEdit; out Value: string; out Index: Integer): Boolean;
var
s: string;
i: integer;
begin
Index := -1;
Value := '';
Result := False;
if aEditor <> nil then
begin
s := aEditor.LineText;
i := aEditor.LogicalCaretXY.X - 1;
if i > length(s) then
Result := False
else
begin
while (i > 0) and (s[i] > ' ') and (pos(s[i], FEndOfTokenChr) = 0) do
Begin
Dec(i);
end;
Value := Copy(s, i + 1, aEditor.LogicalCaretXY.X - i - 1);
Index := i + 1;
Result := True;
end;
end;
end;
{$IFDEF HintClickWorkaround}
procedure TSynShowParamsHint.HintWindowMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
{var
p: TPoint;}
begin
{ p := ScreenToClient(FHint.ClientToScreen(Point(X, Y)));
MouseDown(Button, Shift, p.X, p.Y); }
end;
{$ENDIF}
procedure TSynShowParamsHint.OnHintTimer(Sender: TObject);
begin
FHintTimer.Enabled := False;
FHint.ActivateHint(FHint.Hint);
FHint.Invalidate;
end;
function TSynShowParamsHint.HideHint: Boolean;
begin
FHintTimer.Enabled := False;
Result := FHint.Visible = True;
FHint.Visible := False;
end;
procedure TSynShowParamsHint.KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
var
Handled: Boolean;
begin
inherited;
if Key = VK_UNKNOWN then
exit;
Handled:=true;
case Key of
VK_RETURN,
VK_ESCAPE:
begin
HideHint;
Handled := False;
end;
VK_UP,
VK_DOWN:
begin
HideHint;
Handled := False;
end
else
begin
if FHint.Visible then
begin
ShowHint(Sender as TCustomSynEdit);
end;
Handled := False;
end;
end;
if Handled then
Key:=VK_UNKNOWN;
end;
procedure TSynShowParamsHint.StatusChange(Sender: TObject; Changes: TSynStatusChanges);
begin
if (scFocus in Changes) or (scCaretY in Changes) then
begin
HideHint;
end;
end;
procedure TSynShowParamsHint.SetEditor(const Value: TCustomSynEdit);
begin
if Editor <> Value then
begin
if Editor <> nil then
begin
Editor.UnregisterBeforeKeyDownHandler(@KeyDown);
RemoveFreeNotification( Editor );
end;
inherited;
if Editor <> nil then
begin
Editor.RegisterBeforeKeyDownHandler(@KeyDown);
FreeNotification(Editor);
end;
end;
end;
procedure TSynShowParamsHint.Notification(AComponent: TComponent; Operation: TOperation);
begin
if (Operation = opRemove) then
begin
if Editor = AComponent then
Editor := nil
else if AComponent is TCustomSynEdit then
RemoveEditor(TCustomSynEdit(AComponent));
end;
inherited;
end;
procedure TSynShowParamsHint.DoEditorAdded(AValue: TCustomSynEdit);
begin
inherited DoEditorAdded(AValue);
AValue.RegisterCommandHandler(@ProcessSynCommand, nil);
AValue.RegisterStatusChangedHandler(@StatusChange, [scCaretY, scFocus]);
AValue.RegisterKeyTranslationHandler(@TranslateKey);
end;
procedure TSynShowParamsHint.DoEditorRemoving(AValue: TCustomSynEdit);
begin
inherited DoEditorRemoving(AValue);
AValue.UnregisterCommandHandler(@ProcessSynCommand);
AValue.UnregisterStatusChangedHandler(@StatusChange);
AValue.UnRegisterKeyTranslationHandler(@TranslateKey);
end;
end.
|
program FolgenMaximum (input, output);
{ liest eine Folge von 5 integer-Zahlen ein und bestimmt das Maxmimum }
const
FELDGROESSE = 5;
type
tIndex = 1..FELDGROESSE;
tZahlenFeld = array [tIndex] of integer;
var
Feld : tZahlenFeld;
Maximum : integer;
i,
MaxPos : tIndex;
begin
{ Einlesen des Feldes }
writeln ('Geben Sie ', FELDGROESSE:2, ' Werte ein:');
for i := 1 to FELDGROESSE do
readln(Feld[i]);
{ Bestimmen des Maximums }
Maximum := Feld[1];
for i := 2 to FELDGROESSE do
if Feld[i] > Maximum then
begin
Maximum := Feld[i];
MaxPos := i;
end;
writeln ('Die groesste Zahl ist ', Maximum, ' und wurde an ', MaxPos, '. Stelle eingegeben');
end. { FolgenMaximum }
|
{ SYN <input file name> [ options ]
*
* Version of the SST program specific to SYN input files.
}
program syn;
%include 'sst2.ins.pas';
const
max_msg_parms = 8; {max parameters we can pass to a message}
var
fnam_in, {input file name from command line}
fnam_out, {output file name}
fnam_config, {target machine configuration file}
gnam: {generic leaf name of input file}
%include '(cog)lib/string_treename.ins.pas';
ext:
%include '(cog)lib/string80.ins.pas';
stack_loc: util_stack_loc_handle_t; {unused subroutine return argument}
i: sys_int_machine_t; {scratch integer and loop counter}
univ_p: univ_ptr; {scratch arbitrary pointer}
timing: boolean; {TRUE if supposed to print timing info}
uname_set: boolean; {TRUE if -UNAME command line option used}
timer_all: sys_timer_t; {timer for whole program}
timer_front: sys_timer_t; {timer for front end}
timer_back: sys_timer_t; {timer for back end}
sec_all, sec_front, sec_back, sec_base: real; {seconds for parts of the program}
pc_all, pc_front, pc_back, pc_base: real; {percent time for parts of the program}
opt: {command line option name}
%include '(cog)lib/string32.ins.pas';
parm: {command line option parameter}
%include '(cog)lib/string_treename.ins.pas';
pick: sys_int_machine_t; {number of token picked from list}
msg_parm: {message parameter references}
array[1..max_msg_parms] of sys_parm_msg_t;
stat: sys_err_t; {completion status code}
str_all: string_var4_t := {ALL command line option parameter}
[max := sizeof(str_all.str), len := 3, str := 'ALL'];
label
next_opt, done_opts;
begin
sys_timer_init (timer_all); {init timer for whole program}
sys_timer_start (timer_all); {start timing the whole program}
sys_timer_init (timer_front); {init the other timers}
sys_timer_init (timer_back);
string_cmline_init; {init for command line processing}
string_cmline_token (fnam_in, stat); {get input file name from command line}
string_cmline_req_check (stat); {input file name is required on command line}
{
* Init to defaults before processing command line options.
}
sst_level_debug := 0;
sst_level_unused := 1;
timing := false;
sst_local_ins := false;
sst_ins := false;
sst_ins_tnam.max := sizeof(sst_ins_tnam.str);
sst_ins_tnam.len := 0;
sst_writeall := false;
sst_oname_unique.max := sizeof(sst_oname_unique);
sst_oname_unique.len := 0;
uname_set := false;
sys_cognivis_dir ('lib', fnam_config);
string_appends (fnam_config, '/config_sst'(0));
sst_gui := false;
{
* Back here for each new command line option.
}
next_opt:
string_cmline_token (opt, stat); {get next command line option name}
if string_eos(stat) then goto done_opts; {exhausted command line ?}
sys_error_abort (stat, 'string', 'cmline_opt_err', nil, 0);
string_upcase (opt); {make upper case for matching list}
string_tkpick80 ( {pick option name from list}
opt, {option name}
'-OUT -CONFIG -DEBUG -SHOW_UNUSED -TIME',
pick); {number of picked option}
case pick of {do routine for specific option}
{
* -OUT <output file name>
}
1: begin
string_cmline_token (fnam_out, stat);
end;
{
* -CONFIG <config file name>
}
2: begin
string_cmline_token (fnam_config, stat);
end;
{
* -DEBUG level
}
3: begin
string_cmline_token_int (sst_level_debug, stat);
sst_level_debug := max(sst_level_debug, 0); {clip negative numbers to zero}
end;
{
* -SHOW_UNUSED level
}
4: begin
string_cmline_token (parm, stat);
string_cmline_parm_check (stat, opt);
string_upcase (parm);
if string_equal(parm, str_all)
then begin {parm was "ALL"}
sst_level_unused := sst_level_unused_all_k;
end
else begin {parm wasn't "ALL", it better be a number}
string_t_int (parm, sst_level_unused, stat);
sst_level_unused := max(sst_level_unused, 0); {prevent negative numbers}
end
;
end;
{
* -TIME
}
5: begin
timing := true;
end;
{
* Illegal command line option.
}
otherwise
string_cmline_opt_bad; {complain about bad OPT and bomb}
end; {end of command line option case statement}
string_cmline_parm_check (stat, opt); {check for parameter error}
goto next_opt; {back for next command line option}
done_opts: {done with all the command line options}
if (not uname_set) and sst_ins then begin {need default unique name ?}
string_generic_fnam (sst_ins_tnam, ''(0), parm); {make leafname of -INS file}
for i := 1 to parm.len do begin {once for each character in PARM}
if parm.str[i] = '.'
then begin {hit . character in file name}
exit;
end
else begin {regular file name character}
string_append1 (sst_oname_unique, parm.str[i]);
end
;
end; {back for next input token character}
end; {done defaulting -UNAME}
{
* Done reading command line.
*
* Initialize the back end.
}
sst_init ( {init SST library}
40, {max length of any symbol}
util_top_mem_context); {parent memory context}
sst_config_out (fnam_config); {get target machine configuration info}
case sst_config.lang of {chose back end driver and initialize it}
sst_lang_c_k: sst_w_c_init; {output language is C}
otherwise
sys_msg_parm_int (msg_parm[1], ord(sst_config.lang));
sys_message_bomb ('sst', 'language_unsupported', msg_parm, 1);
end;
{
* Initialize the front end.
}
sst_r_syn_init; {init the SYN interpretation front end}
{
* Run the front end.
* The input source code will be read and "compiled" into data structures
* in memory.
}
sys_timer_start (timer_front); {start timer for front end}
sst_r.doit^ (fnam_in, gnam, stat);
sys_timer_stop (timer_front); {stop timer for front end}
if sys_stat_match (sst_subsys_k, sst_stat_err_handled_k, stat) then begin
sys_exit_error; {exit quietly with error condition}
end;
sys_error_abort (stat, 'sst', 'readin', nil, 0);
{
* Reset state between running the front and back ends.
}
sst_scope_p := sst_scope_root_p; {reset current scope to root scope}
sst_names_p := sst_scope_p;
sst_opc_p := sst_opc_first_p; {reset current opcode to first in list}
sst_opc_next_pp := nil; {this should no longer be used}
util_stack_loc_start (sst_stack, stack_loc, univ_p); {get address of stack start}
util_stack_popto (sst_stack, univ_p); {reset stack to empty}
sst_flag_used_opcodes (sst_opc_first_p); {propagate USED flags to all used symbols}
{
* Run the back end.
* The data structures in memory will be used to write the output source code.
}
if fnam_out.len > 0 then begin {output file name was explicitly specified ?}
string_copy (fnam_out, gnam); {explicitly set generic output file name}
end;
string_copy (sst_config.suffix_fnam, ext); {make output file suffix in simple str}
string_fill (ext);
string_fnam_extend (gnam, ext.str, fnam_config); {make extended file name}
string_treename (fnam_config, fnam_out); {make full output file tree name}
file_delete_name (fnam_out, stat); {delete output file before trying to write it}
discard( file_not_found(stat) ); {OK if output file not already present}
sys_msg_parm_vstr (msg_parm[1], fnam_out);
sys_error_abort (stat, 'file', 'delete', msg_parm, 1);
sys_timer_start (timer_back); {start timer for back end}
sst_w.doit^ (fnam_out, stat); {create the output source code}
sys_timer_stop (timer_back); {stop timer for back end}
if sys_stat_match (sst_subsys_k, sst_stat_err_handled_k, stat) then begin
sys_exit_error; {exit quietly with error condition}
end;
sys_error_abort (stat, 'sst', 'writeout', nil, 0);
{
* Print timing info, if requested.
}
sys_timer_stop (timer_all); {stop timing the whole program}
if timing then begin {user requested timing info be printed ?}
sec_all := sys_timer_sec(timer_all); {seconds for whole program}
sec_front := sys_timer_sec(timer_front); {seconds for front end}
sec_back := sys_timer_sec(timer_back); {seconds for back end}
sec_base := sec_all - sec_front - sec_back; {seconds for base translator}
pc_all := 100.0; {make times in percent of total}
pc_front := 100.0 * sec_front / sec_all;
pc_back := 100.0 * sec_back / sec_all;
pc_base := 100.0 * sec_base / sec_all;
sys_msg_parm_real (msg_parm[1], sec_front);
sys_msg_parm_real (msg_parm[2], pc_front);
sys_msg_parm_real (msg_parm[3], sec_base);
sys_msg_parm_real (msg_parm[4], pc_base);
sys_msg_parm_real (msg_parm[5], sec_back);
sys_msg_parm_real (msg_parm[6], pc_back);
sys_msg_parm_real (msg_parm[7], sec_all);
sys_msg_parm_real (msg_parm[8], pc_all);
sys_message_parms ('sst', 'timing_info', msg_parm, 8); {print timing info}
end;
end.
|
unit U_SaveLoadOptions;
interface
uses IniFiles, Variants;
const
IniFileName = 'options.ini';
type
ROptionIni = record
section : string;
key : string;
value : Variant;
end;
TOptionsIni = record
options : array of ROptionIni;
procedure AddOption(section, key: string; value: Variant);
procedure SaveOptions;
procedure Clear;
end;
procedure SaveParamToIniFiles(section, key: string; value: Variant);
function LoadParamFromIniFiles(section, key: string; VarT: TVarType): Variant;
implementation
uses U_my;
//********* SaveParamToIniFiles ******************************
//Процедура сохраниения настройки в ini файл
// seсtion - название секции (string)
// key - название ключевого поля (string)
// value - тип сохраняемых данных:
// varInteger - целочисленные данные
// varDouble - дробный числа
// varDate - тип дат
// varBoolean - булев тип
// varString - строковый тип
procedure SaveParamToIniFiles(section, key: string; value: Variant);
var
Ini: TIniFile;
begin
Ini := TIniFile.Create(ApplicationFilePath + IniFileName);
case VarType(value) of
varInteger: Ini.WriteInteger(section, key, value); //Значение типа Integer
varDouble : Ini.WriteFloat(section, key, value); //Значение типа Double
varDate : Ini.WriteDateTime(section, key, value);
varBoolean: Ini.WriteBool(section, key, value);
varString : Ini.WriteString(section, key, value);
end;
Ini.UpdateFile;
Ini.Free;
end;
//********* LoadParamFromIniFiles *****************************
// Процедура загрузки параметров из ini файла
// seсtion - название секции (string)
// key - название ключевого поля (string)
function LoadParamFromIniFiles(section, key: string; VarT: TVarType): Variant;
var
Ini: TIniFile;
begin
Ini := TIniFile.Create(ApplicationFilePath + IniFileName);
case VarT of
varInteger: Result := Ini.ReadInteger(section, key, 0); //Значение типа Integer
varDouble : Result := Ini.ReadFloat(section, key, 0); //Значение типа Double
varDate : Result := Ini.ReadDateTime(section, key, 0);
varBoolean: Result := Ini.ReadBool(section, key, false);
varString : Result := Ini.ReadString(section, key, '');
end;
Ini.UpdateFile;
Ini.Free;
end;
{ TOptionsIni }
procedure TOptionsIni.AddOption(section, key: string; value: Variant);
var
option: ROptionIni;
begin
option.section := section;
option.key := key;
option.value := value;
SetLength(options, High(options)+2);
options[High(options)] := option;
end;
procedure TOptionsIni.Clear;
begin
options := nil;
end;
procedure TOptionsIni.SaveOptions;
var
Ini: TIniFile;
i: Integer;
begin
Ini := TIniFile.Create(ApplicationFilePath + IniFileName);
for i := 0 to High(options) do
begin
case VarType(options[i].value) of
varInteger: Ini.WriteInteger(options[i].section, options[i].key, options[i].value); //Значение типа Integer
varDouble : Ini.WriteFloat(options[i].section, options[i].key, options[i].value); //Значение типа Double
varDate : Ini.WriteDateTime(options[i].section, options[i].key, options[i].value);
varBoolean: Ini.WriteBool(options[i].section, options[i].key, options[i].value);
varString : Ini.WriteString(options[i].section, options[i].key, options[i].value);
end;
end;
Ini.UpdateFile;
Ini.Free;
end;
end.
|
(* ***** BEGIN LICENSE BLOCK *****
* Version: GNU GPL 2.0
*
* The contents of this file are subject to the
* GNU General Public License Version 2.0; you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
* http://www.gnu.org/licenses/gpl.html
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is GuiSettings (https://code.google.com/p/escan-notifier/)
*
* The Initial Developer of the Original Code is
* Yann Papouin <yann.papouin at @ gmail.com>
*
* ***** END LICENSE BLOCK ***** *)
unit GuiSettings;
interface
uses
Windows,
Messages,
SysUtils,
Variants,
Classes,
Graphics,
Controls,
Forms,
Dialogs,
JvComponentBase,
JvFormPlacement,
StdCtrls,
SpTBXEditors,
SpTBXItem,
SpTBXControls,
ActnList,
ComCtrls, ACS_Classes, NewACDSAudio, ACS_Converters, ACS_WinMedia, ACS_smpeg;
type
TSettingsForm = class(TForm)
FormStorage: TJvFormStorage;
SpTBXLabel1: TSpTBXLabel;
SpTBXLabel2: TSpTBXLabel;
PreviewLabel: TSpTBXEdit;
ScanLabel: TSpTBXEdit;
SpTBXGroupBox1: TSpTBXGroupBox;
Background: TSpTBXPanel;
Footer: TSpTBXPanel;
ButtonOk: TSpTBXButton;
ButtonCancel: TSpTBXButton;
Actions: TActionList;
Add: TAction;
Remove: TAction;
ChoosePath: TAction;
Ok: TAction;
Cancel: TAction;
Browse: TAction;
Edit: TAction;
SpTBXGroupBox2: TSpTBXGroupBox;
SpTBXLabel3: TSpTBXLabel;
ScanSound: TSpTBXComboBox;
EpsonScanLanguage: TSpTBXComboBox;
SpTBXLabel4: TSpTBXLabel;
SoundTest: TSpTBXSpeedButton;
Play: TAction;
Stop: TAction;
MP3In: TMP3In;
AudioCache: TAudioCache;
DSAudioOut: TDSAudioOut;
SendMail: TSpTBXCheckBox;
EMailAddress: TSpTBXEdit;
SmtpUsername: TSpTBXEdit;
SmtpPassword: TSpTBXEdit;
SmtpHost: TSpTBXEdit;
SmtpPort: TSpTBXSpinEdit;
procedure OkExecute(Sender: TObject);
procedure CancelExecute(Sender: TObject);
procedure ScanSoundChange(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure EpsonScanLanguageChange(Sender: TObject);
procedure LabelChange(Sender: TObject);
procedure DSAudioOutDone(Sender: TComponent);
procedure StopExecute(Sender: TObject);
procedure PlayExecute(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
private
{ Déclarations privées }
FEpsonScanLanguageChanging : boolean;
public
{ Déclarations publiques }
end;
var
SettingsForm: TSettingsForm;
implementation
{$R *.dfm}
uses
JclFileUtils,
GuiMain;
const
ESLG_CUSTOM = 0;
ESLG_DUTCH = 1;
ESLG_ENGLISH = 2;
ESLG_FRENCH = 3;
ESLG_GERMAN = 4;
ESLG_ITALIAN = 5;
ESLG_PORTUGUESE = 6;
ESLG_RUSSIAN = 7;
ESLG_SPANISH = 8;
ESLG_UKRAINIAN = 9;
procedure TSettingsForm.EpsonScanLanguageChange(Sender: TObject);
begin
FEpsonScanLanguageChanging := true;
case EpsonScanLanguage.ItemIndex of
ESLG_CUSTOM:
begin
end;
ESLG_DUTCH:
begin
PreviewLabel.Text := 'Voorbeeldscan wordt gemaakt';
ScanLabel.Text := 'Bezig met scannen';
end;
ESLG_ENGLISH:
begin
PreviewLabel.Text := 'Preview scan in progress';
ScanLabel.Text := 'Scanning';
end;
ESLG_FRENCH:
begin
PreviewLabel.Text := 'Pré-numérisation en cours';
ScanLabel.Text := 'Numérisation';
end;
ESLG_GERMAN:
begin
PreviewLabel.Text := 'Vorschauscannen läuft';
ScanLabel.Text := 'Scanvorgang läuft.';
end;
ESLG_ITALIAN:
begin
PreviewLabel.Text := 'Anteprima in corso';
ScanLabel.Text := 'Scansione in corso';
end;
ESLG_PORTUGUESE:
begin
PreviewLabel.Text := 'Pré-digitalização em curso';
ScanLabel.Text := 'A Digitalizar';
end;
ESLG_RUSSIAN:
begin
PreviewLabel.Text := 'Предварительное сканирование';
ScanLabel.Text := 'Сканирование';
end;
ESLG_SPANISH:
begin
PreviewLabel.Text := 'Pre-exploración en proceso';
ScanLabel.Text := 'Escaneando';
end;
ESLG_UKRAINIAN:
begin
PreviewLabel.Text := 'Відбувається попереднє сканування';
ScanLabel.Text := 'Сканування';
end;
end;
FEpsonScanLanguageChanging := false;
end;
procedure TSettingsForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
if ModalResult = mrNone then
CanClose := false;
end;
procedure TSettingsForm.FormCreate(Sender: TObject);
var
i: integer;
FileList: TStringList;
begin
ScanSound.Clear;
FileList := TStringList.Create;
BuildFileList(MainForm.SoundPath + '*.mp3', faAnyFile, FileList);
for i := 0 to FileList.Count - 1 do
begin
ScanSound.Items.Add(MainForm.SoundPath+FileList[i]);
end;
FileList.Free;
end;
procedure TSettingsForm.CancelExecute(Sender: TObject);
begin
FormStorage.RestoreFormPlacement;
ModalResult := mrCancel;
end;
procedure TSettingsForm.OkExecute(Sender: TObject);
begin
FormStorage.SaveFormPlacement;
ModalResult := mrOk;
end;
procedure TSettingsForm.LabelChange(Sender: TObject);
begin
if not FEpsonScanLanguageChanging then
EpsonScanLanguage.ItemIndex := ESLG_CUSTOM;
end;
procedure TSettingsForm.ScanSoundChange(Sender: TObject);
begin
if not FileExists((Sender as TSpTBXComboBox).Text) then
begin
(Sender as TSpTBXComboBox).Font.Color := clRed;
Play.Enabled := false;
end
else
begin
(Sender as TSpTBXComboBox).ParentFont := true;
Play.Enabled := true;
end;
end;
procedure TSettingsForm.DSAudioOutDone(Sender: TComponent);
begin
Stop.Execute;
end;
procedure TSettingsForm.PlayExecute(Sender: TObject);
begin
MP3In.Filename := ScanSound.Text;
if FileExists(MP3In.Filename) then
begin
DSAudioOut.Run;
SoundTest.Action := Stop;
end;
end;
procedure TSettingsForm.StopExecute(Sender: TObject);
begin
DSAudioOut.Stop;
SoundTest.Action := Play;
end;
end.
|
unit MaskEditFMX.Main;
interface
uses
System.SysUtils, System.Classes, FMX.Types, FMX.Controls,
FMX.Controls.Presentation, FMX.Edit, Providers.Mascaras.Types,
Providers.Mascaras.Factory, System.UITypes;
type
TMaskEditFMX = class(TEdit)
private
FMaskType: TMaskType;
BackspaceDeleteKey: Boolean;
const
FilterCharDefault = '0123456789';
procedure SetMaskType(const Value: TMaskType);
procedure EditKeyDown(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState);
function ExecutaMascara(Value: string): string;
procedure SettingsMaskType;
protected
procedure EditTyping(Sender: TObject);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property MaskType: TMaskType read FMaskType write SetMaskType;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('CustomFMX', [TMaskEditFMX]);
end;
{ TMaskEditFMX }
procedure TMaskEditFMX.EditTyping(Sender: TObject);
begin
if not(BackspaceDeleteKey) then
begin
TThread.Queue(nil,
procedure
var
LStr: String;
begin
if not(Text.Trim.IsEmpty) then
LStr := ExecutaMascara(Text);
Text := LStr;
CaretPosition := Text.Length;
end);
end;
end;
function TMaskEditFMX.ExecutaMascara(Value: string): string;
begin
case MaskType of
mtCPF : Result := TMascaras.CPF.ExecMask(Value);
mtCNPJ: Result := TMascaras.CNPJ.ExecMask(Value);
mtTelefone: Result := TMascaras.Telefone.ExecMask(Value);
mtCelular: Result := TMascaras.Celular.ExecMask(Value);
mtDate: Result := TMascaras.Data.ExecMask(Value);
mtCEP: Result := TMascaras.CEP.ExecMask(Value);
mtHora: Result := TMascaras.Hora.ExecMask(Value);
else
Result := Value;
end;
end;
constructor TMaskEditFMX.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
KeyboardType := TVirtualKeyboardType.PhonePad;
TextSettings.HorzAlign := TTextAlign.Center;
OnTyping := EditTyping;
OnKeyDown := EditKeyDown;
end;
destructor TMaskEditFMX.Destroy;
begin
inherited Destroy;
end;
procedure TMaskEditFMX.EditKeyDown(Sender: TObject; var Key: Word;
var KeyChar: Char; Shift: TShiftState);
begin
BackspaceDeleteKey := Key in [8, 46];
end;
procedure TMaskEditFMX.SetMaskType(const Value: TMaskType);
begin
FMaskType := Value;
SettingsMaskType;
end;
procedure TMaskEditFMX.SettingsMaskType;
begin
case FMaskType of
mtCPF:
begin
FilterChar := FilterCharDefault + '.-';
MaxLength := 14;
end;
mtCNPJ:
begin
FilterChar := FilterCharDefault + './-';
MaxLength := 18;
end;
mtTelefone:
begin
FilterChar := FilterCharDefault + '()-';
MaxLength := 13;
end;
mtCelular:
begin
FilterChar := FilterCharDefault + '()-';
MaxLength := 14;
end;
mtDate:
begin
FilterChar := FilterCharDefault + '/';
MaxLength := 10;
end;
mtCEP:
begin
FilterChar := FilterCharDefault + '-';
MaxLength := 9;
end;
mtHora:
begin
FilterChar := FilterCharDefault + ':';
MaxLength := 5;
end;
end;
end;
end.
|
{ GDAX/Coinbase-Pro client library
Copyright (c) 2018 mr-highball
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
}
unit gdax.api.products;
{$i gdax.inc}
interface
uses
Classes, SysUtils, gdax.api.types, gdax.api.consts, gdax.api;
type
{ TGDAXProductImpl }
TGDAXProductImpl = class(TGDAXRestApi,IGDAXProduct)
public
const
PROP_ID = 'id';
PROP_BASE_CUR = 'base_currency';
PROP_QUOTE_CUR = 'quote_currency';
PROP_BASE_MIN = 'base_min_size';
PROP_BASE_MAX = 'base_max_size';
PROP_QUOTE_INC = 'quote_increment';
PROP_MIN_MARKET_FUNDS = 'min_market_funds';
PROP_MAX_MARKET_FUNDS = 'max_market_funds';
strict private
FBaseCurrency: String;
FBaseMaxSize: Extended;
FBaseMinSize: Extended;
FMinMarketFunds,
FMaxMarketFunds : Extended;
FID: String;
FQuoteCurrency: String;
FQuoteIncrement: Extended;
protected
function GetBaseCurrency: String;
function GetBaseMaxSize: Extended;
function GetBaseMinSize: Extended;
function GetID: String;
function GetMaxMarket: Extended;
function GetMinMarket: Extended;
function GetQuoteCurrency: String;
function GetQuoteIncrement: Extended;
procedure SetBaseCurrency(Const AValue: String);
procedure SetBaseMaxSize(Const AValue: Extended);
procedure SetBaseMinSize(Const AValue: Extended);
procedure SetID(Const AValue: String);
procedure SetMaxMarket(const AValue: Extended);
procedure SetMinMarket(const AValue: Extended);
procedure SetQuoteCurrency(Const AValue: String);
procedure SetQuoteIncrement(Const AValue: Extended);
strict protected
function GetEndpoint(Const AOperation: TRestOperation): String; override;
function DoLoadFromJSON(Const AJSON: String;
out Error: String): Boolean;override;
function DoGetSupportedOperations: TRestOperations; override;
public
property ID : String read GetID write SetID;
property BaseCurrency : String read GetBaseCurrency write SetBaseCurrency;
property QuoteCurrency : String read GetQuoteCurrency write SetQuoteCurrency;
property BaseMinSize : Extended read GetBaseMinSize write SetBaseMinSize; deprecated;
property BaseMaxSize : Extended read GetBaseMaxSize write SetBaseMaxSize; deprecated;
property QuoteIncrement : Extended read GetQuoteIncrement
write SetQuoteIncrement;
property MinMarketFunds : Extended read GetMinMarket write SetMinMarket;
property MaxMarketFunds : Extended read GetMaxMarket write SetMaxMarket; deprecated;
end;
{ TGDAXProductsImpl }
TGDAXProductsImpl = class(TGDAXRestApi,IGDAXProducts)
strict private
FQuoteCurrency: String;
FProducts: TGDAXProductList;
function GetProducts: TGDAXProductList;
function GetQuoteCurrency: String;
procedure SetQuoteCurrency(Const AValue: String);
strict protected
function DoGetSupportedOperations: TRestOperations; override;
function GetEndpoint(Const AOperation: TRestOperation): String; override;
function DoLoadFromJSON(Const AJSON: String; out Error: String): Boolean;override;
public
property QuoteCurrency : String read GetQuoteCurrency write SetQuoteCurrency;
property Products : TGDAXProductList read GetProducts;
constructor Create; override;
destructor Destroy; override;
end;
implementation
uses
fpjson,
jsonparser;
{ TGDAXProductsImpl }
function TGDAXProductsImpl.GetProducts: TGDAXProductList;
begin
Result := FProducts;
end;
function TGDAXProductsImpl.GetQuoteCurrency: String;
begin
Result := FQuoteCurrency;
end;
procedure TGDAXProductsImpl.SetQuoteCurrency(Const AValue: String);
begin
FQuoteCurrency := AValue;
end;
function TGDAXProductsImpl.DoGetSupportedOperations: TRestOperations;
begin
Result:=[roGet];
end;
function TGDAXProductsImpl.GetEndpoint(
Const AOperation: TRestOperation): String;
begin
Result := GDAX_END_API_PRODUCT;
end;
function TGDAXProductsImpl.DoLoadFromJSON(Const AJSON: String; out
Error: String): Boolean;
var
I : Integer;
LJSON : TJSONArray;
LProdJSON : TJSONObject;
LProdCur : String;
LProduct : IGDAXProduct;
begin
Result := False;
try
LJSON := TJSONArray(GetJSON(AJSON));
if not Assigned(LJSON) then
raise Exception.Create(E_BADJSON);
try
//iterate returned array of products
for I := 0 to Pred(LJSON.Count) do
begin
LProdJSON := TJSONObject(LJSON.Items[I]);
//check to make sure we can parse this object
if not Assigned(LProdJSON) then
begin
Error := Format(E_BADJSON_PROP,['product index:'+IntToStr(I)]);
Exit;
end;
//we can filter for a particular quote currency, so check this here
if not FQuoteCurrency.IsEmpty then
begin
LProdCur := LProdJSON.Get(TGDAXProductImpl.PROP_QUOTE_CUR);
LProdCur := LProdCur.Trim.ToLower;
//have a matching quote currency means this index is valid
if LProdCur = FQuoteCurrency.Trim.ToLower then
begin
LProduct := TGDAXProductImpl.Create;
if LProduct.LoadFromJSON(LProdJSON.AsJSON, Error) then
FProducts.Add(LProduct);
end;
end
//all products
else
begin
LProduct := TGDAXProductImpl.Create;
if LProduct.LoadFromJSON(LProdJSON.AsJson, Error) then
FProducts.Add(LProduct);
end;
end;
Result := True;
finally
LJSON.Free;
end;
except on E:Exception do
Error := E.Message;
end;
end;
constructor TGDAXProductsImpl.Create;
begin
inherited Create;
FProducts := TGDAXProductList.Create;
end;
destructor TGDAXProductsImpl.Destroy;
begin
FProducts.Free;
inherited Destroy;
end;
{ TGDAXProductImpl }
function TGDAXProductImpl.GetBaseCurrency: String;
begin
Result := FBaseCurrency;
end;
function TGDAXProductImpl.GetBaseMaxSize: Extended;
begin
Result := FBaseMaxSize;
end;
function TGDAXProductImpl.GetBaseMinSize: Extended;
begin
Result := FBaseMinSize;
end;
function TGDAXProductImpl.GetID: String;
begin
Result := FID;
end;
function TGDAXProductImpl.GetMaxMarket: Extended;
begin
Result := FMaxMarketFunds;
end;
function TGDAXProductImpl.GetMinMarket: Extended;
begin
Result := FMinMarketFunds;
end;
function TGDAXProductImpl.GetQuoteCurrency: String;
begin
Result := FQuoteCurrency;
end;
function TGDAXProductImpl.GetQuoteIncrement: Extended;
begin
Result := FQuoteIncrement;
end;
procedure TGDAXProductImpl.SetBaseCurrency(const AValue: String);
begin
FBaseCurrency := AValue;
end;
procedure TGDAXProductImpl.SetBaseMaxSize(const AValue: Extended);
begin
FBaseMaxSize := AValue;
end;
procedure TGDAXProductImpl.SetBaseMinSize(const AValue: Extended);
begin
FBaseMinSize := AValue;
end;
procedure TGDAXProductImpl.SetID(const AValue: String);
begin
FID := AValue;
end;
procedure TGDAXProductImpl.SetMaxMarket(const AValue: Extended);
begin
FMaxMarketFunds := AValue;
end;
procedure TGDAXProductImpl.SetMinMarket(const AValue: Extended);
begin
FMinMarketFunds := AValue;
end;
procedure TGDAXProductImpl.SetQuoteCurrency(const AValue: String);
begin
FQuoteCurrency := AValue;
end;
procedure TGDAXProductImpl.SetQuoteIncrement(const AValue: Extended);
begin
FQuoteIncrement := AValue;
end;
function TGDAXProductImpl.DoLoadFromJSON(const AJSON: String; out Error: String
): Boolean;
var
LJSON : TJSONObject;
begin
Result := False;
try
LJSON := TJSONObject(GetJSON(AJSON));
if not Assigned(LJSON) then
raise Exception.Create(E_BADJSON);
try
FID := LJSON.Get(PROP_ID);
FBaseCurrency := LJSON.Get(PROP_BASE_CUR);
if Assigned(LJSON.Find(PROP_BASE_MIN)) then
FBaseMinSize := 0.00000001
else
FBaseMinSize := LJSON.Get(PROP_BASE_MIN, 0.00000001);
if Assigned(LJSON.Find(PROP_BASE_MAX)) then
FBaseMaxSize := 99999999
else
FBaseMaxSize := LJSON.Get(PROP_BASE_MAX, 99999999);
FQuoteCurrency := LJSON.Get(PROP_QUOTE_CUR);
FQuoteIncrement := LJSON.Get(PROP_QUOTE_INC);
if Assigned(LJSON.Find(PROP_MIN_MARKET_FUNDS)) then
FMinMarketFunds := LJSON.Get(PROP_MIN_MARKET_FUNDS, 0.00000001);
if Assigned(LJSON.Find(PROP_MAX_MARKET_FUNDS)) then
FMaxMarketFunds := LJSON.Get(PROP_MAX_MARKET_FUNDS, 99999999);
Result := True;
finally
LJSON.Free;
end;
except on E:Exception do
Error := E.Message;
end;
end;
function TGDAXProductImpl.DoGetSupportedOperations: TRestOperations;
begin
Result:=[roGet];
end;
function TGDAXProductImpl.GetEndpoint(const AOperation: TRestOperation): String;
begin
Result := Format(GDAX_END_API_PRODUCTS,[FID]);
end;
end.
|
unit vtPILSizedImgCopyDlg;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, vtPngImgList,
vtInterfaces
;
type
TvtPILCopySizedDlg = class(TForm)
cbxFrom: TGroupBox;
rb16from: TRadioButton;
Label1: TLabel;
rb24from: TRadioButton;
rb32from: TRadioButton;
GroupBox1: TGroupBox;
rb16to: TRadioButton;
rb24to: TRadioButton;
rb32to: TRadioButton;
Image1: TImage;
Bevel1: TBevel;
Button1: TButton;
Button2: TButton;
procedure rb16fromClick(Sender: TObject);
procedure rb24fromClick(Sender: TObject);
procedure rb32fromClick(Sender: TObject);
procedure rb16toClick(Sender: TObject);
procedure rb24toClick(Sender: TObject);
procedure rb32toClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
f_SizeFrom: TvtPILSize;
f_SizeTo: TvtPILSize;
procedure EnableRBTo(aSize: TvtPILSize; aEnable: Boolean);
procedure pm_SetSizeFrom(const Value: TvtPILSize);
procedure pm_SetSizeTo(const Value: TvtPILSize);
function SizeToRB(aSize: TvtPILSize): TRadiobutton;
{ Private declarations }
public
property SizeFrom: TvtPILSize read f_SizeFrom write pm_SetSizeFrom;
property SizeTo: TvtPILSize read f_SizeTo write pm_SetSizeTo;
{ Public declarations }
end;
var
vtPILCopySizedDlg: TvtPILCopySizedDlg;
implementation
{$R *.dfm}
procedure TvtPILCopySizedDlg.EnableRBTo(aSize: TvtPILSize; aEnable: Boolean);
var
l_RadioButton: TRadioButton;
begin
l_Radiobutton := SizeToRB(aSize);
if (not aEnable) and (aSize = SizeTo) then
begin
case SizeTo of
ps16x16: SizeTo := ps24x24;
ps24x24,
ps32x32: SizeTo := ps16x16;
end;
end;
l_RadioButton.Enabled := aEnable
end;
procedure TvtPILCopySizedDlg.pm_SetSizeFrom(const Value: TvtPILSize);
begin
if f_SizeFrom <> Value then
begin
EnableRBTo(f_SizeFrom, True);
f_SizeFrom := Value;
EnableRBTo(f_SizeFrom, False);
end;
end;
procedure TvtPILCopySizedDlg.pm_SetSizeTo(const Value: TvtPILSize);
begin
f_SizeTo := Value;
SizeToRB(Value).Checked := True;
end;
procedure TvtPILCopySizedDlg.rb16fromClick(Sender: TObject);
begin
SizeFrom := ps16x16;
end;
function TvtPILCopySizedDlg.SizeToRB(aSize: TvtPILSize): TRadiobutton;
begin
case aSize of
ps16x16: Result := rb16to;
ps24x24: Result := rb24to;
ps32x32: Result := rb32to;
end;
end;
procedure TvtPILCopySizedDlg.rb24fromClick(Sender: TObject);
begin
SizeFrom := ps24x24;
end;
procedure TvtPILCopySizedDlg.rb32fromClick(Sender: TObject);
begin
SizeFrom := ps32x32;
end;
procedure TvtPILCopySizedDlg.rb16toClick(Sender: TObject);
begin
SizeTo := ps16x16;
end;
procedure TvtPILCopySizedDlg.rb24toClick(Sender: TObject);
begin
SizeTo := ps24x24;
end;
procedure TvtPILCopySizedDlg.rb32toClick(Sender: TObject);
begin
SizeTo := ps32x32;
end;
procedure TvtPILCopySizedDlg.FormCreate(Sender: TObject);
begin
f_SizeFrom := ps16x16;
f_SizeTo := ps24x24;
end;
end.
|
unit Rects;
// Copyright (c) 1996 Jorge Romero Gomez, Merchise.
interface
uses
Windows;
function RectSize( const R : TRect) : TPoint;
function RectFromSize( x, y : integer; const Size : TPoint) : TRect;
function RectFromBounds( x, y : integer; Width, Height : integer ) : TRect;
procedure MovePoint( var P : TPoint; OfsX, OfsY : integer );
procedure MoveRect( var R : TRect; const Point : TPoint );
function GetBoundingRect( NewPos, OldPos : TPoint; Width, Height : integer ) : TRect;
implementation
function GetBoundingRect( NewPos, OldPos : TPoint; Width, Height : integer ) : TRect;
begin
with Result do
begin
if OldPos.X > NewPos.X
then
begin
Left := NewPos.X;
Right := OldPos.X + Width;
end
else
begin
Left := OldPos.X;
Right := NewPos.X + Width;
end;
if OldPos.Y > NewPos.Y
then
begin
Top := NewPos.Y;
Bottom := OldPos.Y + Height;
end
else
begin
Top := OldPos.Y;
Bottom := NewPos.Y + Height;
end;
end;
end;
procedure MovePoint( var P : TPoint; OfsX, OfsY : integer );
begin
with P do
begin
Inc( x, OfsX );
Inc( y, OfsY );
end;
end;
procedure MoveRect( var R : TRect; const Point : TPoint );
begin
OffsetRect( R, Point.X, Point.Y );
end;
function RectSize( const R : TRect) : TPoint;
begin
with Result, R do
begin
x := Right - Left;
y := Bottom - Top;
end;
end;
function RectFromBounds( x, y : integer; Width, Height : integer ) : TRect;
begin
with Result do
begin
Left := x;
Right := x + Width;
Top := y;
Bottom := y + Height;
end;
end;
function RectFromSize( x, y : integer; const Size : TPoint) : TRect;
begin
with Result do
begin
Left := x;
Right := x + Size.X;
Top := y;
Bottom := y + Size.Y;
end;
end;
end.
|
unit RTTIUtils;
interface
type
TRTTIUtils = class
private
public
class procedure ExecutarMetodo<T : Class>(Sender : T; aMethod : String; aParam : String);
end;
implementation
uses
System.RTTI;
{ TRTTIUtils }
class procedure TRTTIUtils.ExecutarMetodo<T>(Sender : T; aMethod : String; aParam : String);
var
ctxRtti : TRttiContext;
typRtti : TRttiType;
metRtti : TRttiMethod;
aParams : Array of TValue;
begin
ctxRtti := TRttiContext.Create;
try
typRtti := ctxRtti.GetType(Sender.ClassType);
metRtti := typRtti.GetMethod(aMethod);
SetLength(aParams, 1);
aParams[0] := aParam;
metRtti.Invoke(Sender, aParams);
finally
ctxRtti.Free;
end;
end;
end.
|
{
$Project$
$Workfile$
$Revision$
$DateUTC$
$Id$
This file is part of the Indy (Internet Direct) project, and is offered
under the dual-licensing agreement described on the Indy website.
(http://www.indyproject.org/)
Copyright:
(c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved.
}
{
$Log$
}
{
Rev 1.9 10/26/2004 8:45:26 PM JPMugaas
Should compile.
Rev 1.8 10/26/2004 8:42:58 PM JPMugaas
Should be more portable with new references to TIdStrings and TIdStringList.
Rev 1.7 5/19/2004 10:44:28 PM DSiders
Corrected spelling for TIdIPAddress.MakeAddressObject method.
Rev 1.6 2/3/2004 11:34:26 AM JPMugaas
Should compile.
Rev 1.5.1.0 2/3/2004 11:32:26 AM JPMugaas
Should compile.
Rev 1.5 2/1/2004 2:44:20 AM JPMugaas
Bindings editor should be fully functional including IPv6 support.
Rev 1.4 2/1/2004 1:03:34 AM JPMugaas
This now work properly in both Win32 and DotNET. The behavior had to change
in DotNET because of some missing functionality and because implementing that
functionality creates more problems than it would solve.
Rev 1.3 2003.12.31 10:42:22 PM czhower
Warning removed
Rev 1.2 10/15/2003 10:12:32 PM DSiders
Added localization comments.
Rev 1.1 2003.10.11 5:47:46 PM czhower
-VCL fixes for servers
-Chain suport for servers (Super core)
-Scheduler upgrades
-Full yarn support
Rev 1.0 11/13/2002 08:43:58 AM JPMugaas
}
unit IdDsnPropEdBindingVCL;
interface
{$I IdCompilerDefines.inc}
uses
Classes,
{$IFDEF WIDGET_KYLIX}
QActnList, QStdCtrls, QForms, QExtCtrls, QControls, QComCtrls, QGraphics, Qt,
{$ENDIF}
{$IFDEF WIDGET_VCL_LIKE}
ActnList, StdCtrls, Buttons, ExtCtrls, Graphics, Controls, ComCtrls, Forms, Dialogs,
{$ENDIF}
{$IFDEF HAS_UNIT_Types}
Types,
{$ENDIF}
{$IFDEF WINDOWS}
Windows,
{$ENDIF}
{$IFDEF LCL}
LResources,
{$ENDIF}
IdSocketHandle;
{
Design Note: It turns out that in DotNET, there are no services file functions and
IdPorts does not work as expected in DotNET. It is probably possible to read the
services file ourselves but that creates some portability problems as the placement
is different in every operating system.
e.g.
Linux and Unix-like systems - /etc
Windows 95, 98, and ME - c:\windows
Windows NT systems - c:\winnt\system32\drivers\etc
Thus, it will undercut whatever benefit we could get with DotNET.
About the best I could think of is to use an edit control because
we can't offer anything from the services file in DotNET.
TODO: Maybe there might be a way to find the location in a more elegant
manner than what I described.
}
type
TIdDsnPropEdBindingVCL = class(TForm)
{$IFDEF USE_TBitBtn}
btnOk: TBitBtn;
btnCancel: TBitBtn;
{$ELSE}
btnOk: TButton;
btnCancel: TButton;
{$ENDIF}
lblBindings: TLabel;
edtPort: TComboBox;
rdoBindingType: TRadioGroup;
lblIPAddress: TLabel;
lblPort: TLabel;
btnNew: TButton;
btnDelete: TButton;
ActionList1: TActionList;
btnBindingsNew: TAction;
btnBindingsDelete: TAction;
edtIPAddress: TComboBox;
lbBindings: TListBox;
procedure btnBindingsNewExecute(Sender: TObject);
procedure btnBindingsDeleteExecute(Sender: TObject);
procedure btnBindingsDeleteUpdate(Sender: TObject);
procedure edtPortKeyPress(Sender: TObject; var Key: Char);
procedure edtIPAddressChange(Sender: TObject);
procedure edtPortChange(Sender: TObject);
procedure rdoBindingTypeClick(Sender: TObject);
procedure lbBindingsClick(Sender: TObject);
private
procedure SetHandles(const Value: TIdSocketHandles);
procedure SetIPv4Addresses(const Value: TStrings);
procedure SetIPv6Addresses(const Value: TStrings);
procedure UpdateBindingList;
protected
FInUpdateRoutine : Boolean;
FHandles : TIdSocketHandles;
FDefaultPort : Integer;
FIPv4Addresses : TStrings;
FIPv6Addresses : TStrings;
fCreatedStack : Boolean;
FCurrentHandle : TIdSocketHandle;
procedure UpdateEditControls;
function PortDescription(const PortNumber: integer): string;
public
Constructor Create(AOwner : TComponent); overload; override;
constructor Create; reintroduce; overload;
Destructor Destroy; override;
function Execute : Boolean;
function GetList: string;
procedure SetList(const AList: string);
property Handles : TIdSocketHandles read FHandles write SetHandles;
property DefaultPort : Integer read FDefaultPort write FDefaultPort;
property IPv4Addresses : TStrings read FIPv4Addresses write SetIPv4Addresses;
property IPv6Addresses : TStrings read FIPv6Addresses write SetIPv6Addresses;
end;
var
IdPropEdBindingEntry: TIdDsnPropEdBindingVCL;
procedure FillHandleList(const AList: string; ADest: TIdSocketHandles);
function GetListValues(const ASocketHandles : TIdSocketHandles) : String;
implementation
uses
IdGlobal,
IdIPAddress,
IdDsnCoreResourceStrings, IdStack,
IdStackBSDBase,
SysUtils;
const
IPv6Wildcard1 = '::'; {do not localize}
{CH IPv6Wildcard2 = '0:0:0:0:0:0:0:0'; } {do not localize}
IPv6Loopback = '::1'; {do not localize}
IPv4Wildcard = '0.0.0.0'; {do not localize}
IPv4Loopback = '127.0.0.1'; {do not localize}
function IsValidIP(const AAddr : String): Boolean;
var
LIP : TIdIPAddress;
begin
LIP := TIdIPAddress.MakeAddressObject(AAddr);
Result := Assigned(LIP);
if Result then begin
FreeAndNil(LIP);
end;
end;
procedure FillHandleList(const AList: string; ADest: TIdSocketHandles);
var
LItems: TStringList;
i: integer;
LIPVersion: TIdIPVersion;
LAddr, LText: string;
LPort: integer;
begin
ADest.Clear;
LItems := TStringList.Create;
try
LItems.CommaText := AList;
for i := 0 to LItems.Count-1 do begin
if Length(LItems[i]) > 0 then begin
if LItems[i][1] = '[' then begin
// ipv6
LIPVersion := Id_IPv6;
LText := Copy(LItems[i], 2, MaxInt);
LAddr := Fetch(LText, ']:');
LPort := StrToIntDef(LText, -1);
end else begin
// ipv4
LIPVersion := Id_IPv4;
LText := LItems[i];
LAddr := Fetch(LText, ':');
LPort := StrToIntDef(LText, -1);
//Note that 0 is legal and indicates the server binds to a random port
end;
if IsValidIP(LAddr) and (LPort > -1) and (LPort < 65536) then begin
with ADest.Add do begin
IPVersion := LIPVersion;
IP := LAddr;
Port := LPort;
end;
end;
end;
end;
finally
LItems.Free;
end;
end;
{ TIdDsnPropEdBindingVCL }
function NumericOnly(const AText : String) : String;
var
i : Integer;
begin
Result := '';
for i := 1 to Length(AText) do
begin
if IsNumeric(AText[i]) then begin
Result := Result + AText[i];
end else begin
Break;
end;
end;
if Length(Result) = 0 then begin
Result := '0';
end;
end;
function IndexOfNo(const ANo : Integer; AStrings : TStrings) : Integer;
begin
for Result := 0 to AStrings.Count-1 do
begin
if ANo = IndyStrToInt(NumericOnly(AStrings[Result])) then begin
Exit;
end;
end;
Result := -1;
end;
function GetDisplayString(ASocketHandle: TIdSocketHandle): string;
begin
Result := '';
case ASocketHandle.IPVersion of
Id_IPv4 : Result := Format('%s:%d',[ASocketHandle.IP, ASocketHandle.Port]);
Id_IPv6 : Result := Format('[%s]:%d',[ASocketHandle.IP, ASocketHandle.Port]);
end;
end;
function GetListValues(const ASocketHandles : TIdSocketHandles) : String;
var i : Integer;
begin
Result := '';
for i := 0 to ASocketHandles.Count -1 do begin
Result := Result + ',' + GetDisplayString(ASocketHandles[i]);
end;
Delete(Result,1,1);
end;
constructor TIdDsnPropEdBindingVCL.Create(AOwner: TComponent);
var
i : Integer;
begin
inherited CreateNew(AOwner, 0);
{$IFNDEF WIDGET_KYLIX}
Borderstyle := bsDialog;
{$ENDIF}
BorderIcons := [biSystemMenu];
// Width := 480;
// Height := 252;
ClientWidth := 472;
{$IFDEF USE_TBitBtn}
ClientHeight := 230;
{$ELSE}
ClientHeight := 225;
{$ENDIF}
Constraints.MaxWidth := Width;
Constraints.MaxHeight := Height;
Constraints.MinWidth := Width;
Constraints.MinHeight := Height;
Position := poScreenCenter;
lblBindings := TLabel.Create(Self);
lbBindings := TListBox.Create(Self);
ActionList1 := TActionList.Create(Self);
btnBindingsNew := TAction.Create(Self);
btnBindingsDelete := TAction.Create(Self);
btnNew := TButton.Create(Self);
btnDelete := TButton.Create(Self);
lblIPAddress := TLabel.Create(Self);
edtIPAddress := TComboBox.Create(Self);
lblPort := TLabel.Create(Self);
edtPort := TComboBox.Create(Self);
rdoBindingType := TRadioGroup.Create(Self);
{$IFDEF USE_TBitBtn}
btnOk := TBitBtn.Create(Self);
btnCancel := TBitBtn.Create(Self);
{$ELSE}
btnOk := TButton.Create(Self);
btnCancel := TButton.Create(Self);
{$ENDIF}
with lblBindings do
begin
Name := 'lblBindings'; {do not localize}
Parent := Self;
Left := 8;
Top := 8;
Width := 35;
Height := 13;
Caption := '&Binding'; {do not localize}
end;
with lbBindings do
begin
Name := 'lbBindings'; {do not localize}
Parent := Self;
Left := 8;
Top := 24;
Width := 137;
Height := 161;
ItemHeight := 13;
TabOrder := 8;
OnClick := lbBindingsClick;
end;
with ActionList1 do
begin
Name := 'ActionList1'; {do not localize}
end;
with btnBindingsNew do
begin
Name := 'btnBindingsNew'; {do not localize}
Caption := RSBindingNewCaption;
OnExecute := btnBindingsNewExecute;
end;
with btnBindingsDelete do
begin
Name := 'btnBindingsDelete'; {do not localize}
Caption := RSBindingDeleteCaption;
OnExecute := btnBindingsDeleteExecute;
OnUpdate := btnBindingsDeleteUpdate;
end;
with btnNew do
begin
Name := 'btnNew'; {do not localize}
Parent := Self;
Left := 152;
Top := 72;
Width := 75;
Height := 25;
Action := btnBindingsNew;
TabOrder := 6;
end;
with btnDelete do
begin
Name := 'btnDelete'; {do not localize}
Parent := Self;
Left := 152;
Top := 104;
Width := 75;
Height := 25;
Action := btnBindingsDelete;
TabOrder := 7;
end;
with lblIPAddress do
begin
Name := 'lblIPAddress'; {do not localize}
Parent := Self;
Left := 240;
Top := 8;
Width := 54;
Height := 13;
Caption := RSBindingHostnameLabel;
Enabled := False;
end;
with edtIPAddress do
begin
Name := 'edtIPAddress'; {do not localize}
Parent := Self;
Left := 240;
Top := 24;
Width := 221;
Height := 21;
Enabled := False;
ItemHeight := 13;
TabOrder := 3;
OnChange := edtIPAddressChange;
end;
with lblPort do
begin
Name := 'lblPort'; {do not localize}
Parent := Self;
Left := 240;
Top := 56;
Width := 22;
Height := 13;
Caption := RSBindingPortLabel;
Enabled := False;
FocusControl := edtPort;
end;
with edtPort do
begin
Name := 'edtPort'; {do not localize}
Parent := Self;
Left := 240;
Top := 72;
Width := 221;
Height := 21;
Enabled := False;
ItemHeight := 13;
TabOrder := 4;
OnChange := edtPortChange;
OnKeyPress := edtPortKeyPress;
end;
with rdoBindingType do
begin
Name := 'rdoBindingType'; {do not localize}
Parent := Self;
Left := 240;
Top := 120;
Width := 221;
Height := 65;
Caption := RSBindingIPVerLabel;
Enabled := False;
Items.Add(RSBindingIPV4Item);
Items.Add(RSBindingIPV6Item);
TabOrder := 5;
OnClick := rdoBindingTypeClick;
end;
with btnOk do
begin
Name := 'btnOk'; {do not localize}
Parent := Self;
Anchors := [akRight, akBottom];
Left := 306;
Top := 193;
Width := 75;
{$IFDEF USE_TBitBtn}
Height := 30;
Kind := bkOk;
{$ELSE}
Height := 25;
Caption := RSOk;
Default := True;
ModalResult := 1;
{$ENDIF}
TabOrder := 0;
end;
with btnCancel do
begin
Name := 'btnCancel'; {do not localize}
Parent := Self;
Anchors := [akRight, akBottom];
Left := 386;
Top := 193;
Width := 75;
{$IFDEF USE_TBitBtn}
Height := 30;
Kind := bkCancel;
{$ELSE}
Height := 25;
Cancel := True;
Caption := RSCancel;
ModalResult := 2;
{$ENDIF}
Anchors := [akRight, akBottom];
TabOrder := 1;
end;
FHandles := TIdSocketHandles.Create(nil);
FIPv4Addresses := TStringList.Create;
FIPv6Addresses := TStringList.Create;
SetIPv4Addresses(nil);
SetIPv6Addresses(nil);
TIdStack.IncUsage;
try
GStack.AddLocalAddressesToList(FIPv4Addresses);
finally
TIdStack.DecUsage;
end;
edtPort.Items.BeginUpdate;
try
edtPort.Items.Add(PortDescription(0));
for i := 0 to IdPorts.Count - 1 do begin
edtPort.Items.Add(PortDescription(PtrInt(IdPorts[i])));
end;
finally
edtPort.Items.EndUpdate;
end;
AutoScroll := False;
Caption := RSBindingFormCaption;
{$IFDEF WIDGET_VCL}
Scaled := False;
{$ENDIF}
Font.Color := clBtnText;
Font.Height := -11;
Font.Name := 'MS Sans Serif'; {Do not Localize}
Font.Style := [];
Position := poScreenCenter;
PixelsPerInch := 96;
FInUpdateRoutine := False;
UpdateEditControls;
end;
destructor TIdDsnPropEdBindingVCL.Destroy;
begin
FreeAndNil(FIPv4Addresses);
FreeAndNil(FIPv6Addresses);
FreeAndNil(FHandles);
inherited Destroy;
end;
function TIdDsnPropEdBindingVCL.PortDescription(const PortNumber: integer): string;
var
LList: TStringList;
begin
if PortNumber = 0 then begin
Result := IndyFormat('%d: %s', [PortNumber, RSBindingAny]);
end else begin
Result := ''; {Do not Localize}
LList := TStringList.Create;
try
GBSDStack.AddServByPortToList(PortNumber, LList);
if LList.Count > 0 then begin
Result := Format('%d: %s', [PortNumber, LList.CommaText]); {Do not Localize}
end;
finally
LList.Free;
end;
end;
end;
procedure TIdDsnPropEdBindingVCL.SetHandles(const Value: TIdSocketHandles);
begin
FHandles.Assign(Value);
UpdateBindingList;
end;
procedure TIdDsnPropEdBindingVCL.btnBindingsNewExecute(Sender: TObject);
begin
FCurrentHandle := FHandles.Add;
FCurrentHandle.IP := IPv4Wildcard;
FCurrentHandle.Port := FDefaultPort;
UpdateBindingList;
edtIPAddress.Items.Assign(FIPv4Addresses);
UpdateEditControls;
end;
procedure TIdDsnPropEdBindingVCL.UpdateEditControls;
var
i : Integer;
begin
if Assigned(FCurrentHandle) then
begin
i := IndexOfNo(FCurrentHandle.Port,edtPort.Items);
if i = -1 then begin
edtPort.Text := IntToStr(FCurrentHandle.Port);
end else begin
edtPort.ItemIndex := i;
end;
case FCurrentHandle.IPVersion of
Id_IPv4 :
begin
rdoBindingType.ItemIndex := 0;
edtIPAddress.Items.Assign(FIPv4Addresses);
end;
Id_IPv6 :
begin
rdoBindingType.ItemIndex := 1;
edtIPAddress.Items.Assign(FIPv6Addresses);
end;
end;
if edtIPAddress.Style = csDropDown then begin
edtIPAddress.Text := FCurrentHandle.IP;
end else begin
edtIPAddress.ItemIndex := edtIPAddress.Items.IndexOf(FCurrentHandle.IP);
end;
end
else
begin
edtIPAddress.Text := '';
//in LCL, the line below caused an index out of range error.
{$IFDEF WIDGET_VCL}
edtPort.ItemIndex := -1; //-2;
{$ENDIF}
edtPort.Text := '';
end;
lblIPAddress.Enabled := Assigned(FCurrentHandle);
edtIPAddress.Enabled := Assigned(FCurrentHandle);
lblPort.Enabled := Assigned(FCurrentHandle);
edtPort.Enabled := Assigned(FCurrentHandle);
rdoBindingType.Enabled := Assigned(FCurrentHandle);
{$IFDEF WIDGET_KYLIX}
//WOrkaround for CLX quirk that might be Kylix 1
for i := 0 to rdoBindingType.ControlCount -1 do begin
rdoBindingType.Controls[i].Enabled := Assigned(FCurrentHandle);
end;
{$ENDIF}
{$IFDEF WIDGET_VCL_LIKE}
//The Win32 VCL does not change the control background to a greyed look
//when controls are disabled. This quirk is not present in CLX.
if Assigned(FCurrentHandle) then
begin
edtIPAddress.Color := clWindow;
edtPort.Color := clWindow;
end else
begin
edtIPAddress.Color := clBtnFace;
edtPort.Color := clBtnFace;
end;
{$ENDIF}
end;
procedure TIdDsnPropEdBindingVCL.btnBindingsDeleteExecute(Sender: TObject);
var
LSH : TIdSocketHandle;
begin
if lbBindings.ItemIndex >= 0 then
begin
// Delete is not available in D4's collection classes
// This should work just as well.
LSH := Handles[lbBindings.ItemIndex];
FreeAndNil(LSH);
FCurrentHandle := nil;
UpdateBindingList;
end;
lbBindingsClick(nil);
UpdateEditControls;
end;
procedure TIdDsnPropEdBindingVCL.btnBindingsDeleteUpdate(Sender: TObject);
begin
btnBindingsDelete.Enabled := lbBindings.ItemIndex >= 0;
end;
procedure TIdDsnPropEdBindingVCL.SetIPv4Addresses(const Value: TStrings);
begin
if Assigned(Value) then begin
FIPv4Addresses.Assign(Value);
end;
// Ensure that these two are always present
if FIPv4Addresses.IndexOf(IPv6Loopback) = -1 then begin
FIPv4Addresses.Insert(0, IPv4Loopback);
end;
if FIPv4Addresses.IndexOf(IPv4Wildcard) = -1 then begin
FIPv4Addresses.Insert(0, IPv4Wildcard);
end;
end;
procedure TIdDsnPropEdBindingVCL.SetIPv6Addresses(const Value: TStrings);
begin
if Assigned(Value) then begin
FIPv6Addresses.Assign(Value);
end;
// Ensure that these two are always present
if FIPv6Addresses.IndexOf(IPv6Loopback) = -1 then begin
FIPv6Addresses.Insert(0, IPv6Loopback);
end;
if FIPv6Addresses.IndexOf(IPv6Wildcard1) = -1 then begin
FIPv6Addresses.Insert(0, IPv6Wildcard1);
end;
end;
procedure TIdDsnPropEdBindingVCL.edtPortKeyPress(Sender: TObject; var Key: Char);
begin
// RLebeau 1/7/09: using Char() for #128-#255 because in D2009, the compiler
// may change characters >= #128 from their Ansi codepage value to their true
// Unicode codepoint value, depending on the codepage used for the source code.
// For instance, #128 may become #$20AC...
if (Key > Chr(31)) and (Key < Chr(128)) then begin
if not IsNumeric(Key) then begin
Key := #0;
end;
end;
end;
procedure TIdDsnPropEdBindingVCL.edtIPAddressChange(Sender: TObject);
begin
FCurrentHandle.IP := edtIPAddress.Text;
UpdateBindingList;
end;
procedure TIdDsnPropEdBindingVCL.edtPortChange(Sender: TObject);
begin
if Assigned(FCurrentHandle) then begin
FCurrentHandle.Port := IndyStrToInt(NumericOnly(edtPort.Text), 0);
end;
UpdateBindingList;
end;
procedure TIdDsnPropEdBindingVCL.rdoBindingTypeClick(Sender: TObject);
begin
case rdoBindingType.ItemIndex of
0 :
begin
if FCurrentHandle.IPVersion <> Id_IPv4 then
begin
FCurrentHandle.IPVersion := Id_IPv4;
edtIPAddress.Items.Assign(FIPv4Addresses);
FCurrentHandle.IP := IPv4Wildcard;
end;
end;
1 :
begin
if FCurrentHandle.IPVersion <> Id_IPv6 then
begin
FCurrentHandle.IPVersion := Id_IPv6;
edtIPAddress.Items.Assign(FIPv6Addresses);
FCurrentHandle.IP := IPv6Wildcard1;
end;
end;
end;
UpdateEditControls;
UpdateBindingList;
end;
function TIdDsnPropEdBindingVCL.GetList: string;
begin
Result := GetListValues(Handles);
end;
procedure TIdDsnPropEdBindingVCL.lbBindingsClick(Sender: TObject);
begin
if lbBindings.ItemIndex >= 0 then begin
FCurrentHandle := FHandles[lbBindings.ItemIndex];
end else begin
FCurrentHandle := nil;
end;
UpdateEditControls;
end;
procedure TIdDsnPropEdBindingVCL.SetList(const AList: string);
begin
FCurrentHandle := nil;
FillHandleList(AList, Handles);
UpdateBindingList;
UpdateEditControls;
end;
procedure TIdDsnPropEdBindingVCL.UpdateBindingList;
var
i: integer;
selected: integer;
s: string;
begin
//in Lazarus, for some odd reason, if you have more than one binding,
//the routine is called while the items are updated
if FInUpdateRoutine then begin
Exit;
end;
FInUpdateRoutine := True;
try
selected := lbBindings.ItemIndex;
lbBindings.Items.BeginUpdate;
try
if lbBindings.Items.Count = FHandles.Count then begin
for i := 0 to FHandles.Count - 1 do begin
s := GetDisplayString(FHandles[i]);
if s <> lbBindings.Items[i] then begin
lbBindings.Items[i] := s;
end;
end;
end else begin
lbBindings.Items.Clear;
for i := 0 to FHandles.Count-1 do begin
lbBindings.Items.Add(GetDisplayString(FHandles[i]));
end;
end;
finally
lbBindings.Items.EndUpdate;
if Assigned(FCurrentHandle) then begin
lbBindings.ItemIndex := FCurrentHandle.Index;
end else begin
lbBindings.ItemIndex := IndyMin(selected, lbBindings.Items.Count-1);
end;
end;
finally
FInUpdateRoutine := False;
end;
end;
function TIdDsnPropEdBindingVCL.Execute: Boolean;
begin
Result := ShowModal = mrOk;
end;
constructor TIdDsnPropEdBindingVCL.Create;
begin
Create(nil);
end;
end.
|
unit fmuFiscalMemory;
interface
uses
// VCL
ExtCtrls, StdCtrls, Controls, Classes, SysUtils, Buttons, Graphics,
// This
untPages, untUtil, untDriver;
type
{ TfmFiscalMemory }
TfmFiscalMemory = class(TPage)
grpRecordsSum: TGroupBox;
lblSumm1: TLabel;
lblSumm3: TLabel;
lblSumm2: TLabel;
lblSumm4: TLabel;
edtSumm1: TEdit;
edtSumm3: TEdit;
edtSumm2: TEdit;
edtSumm4: TEdit;
btnGetFMRecordsSum: TBitBtn;
cbFMType: TComboBox;
lblType: TLabel;
grpLastFMRecord: TGroupBox;
lblFMType: TLabel;
edtFMType: TEdit;
lblFMDate: TLabel;
edtFMDate: TEdit;
btnGetLastFMRecordDate: TBitBtn;
grpInitFM: TGroupBox;
btnInitFM: TButton;
procedure btnGetFMRecordsSumClick(Sender: TObject);
procedure btnGetLastFMRecordDateClick(Sender: TObject);
procedure btnInitFMClick(Sender: TObject);
end;
implementation
{$R *.DFM}
{ TfmFiscalMemory }
procedure TfmFiscalMemory.btnGetFMRecordsSumClick(Sender: TObject);
begin
EnableButtons(False);
try
Driver.TypeOfSumOfEntriesFM := Boolean(cbFMType.ItemIndex);
if Driver.GetFMRecordsSum = 0 then
begin
edtSumm1.Text := CurrToStr(Driver.Summ1);
edtSumm2.Text := CurrToStr(Driver.Summ2);
edtSumm3.Text := CurrToStr(Driver.Summ3);
edtSumm4.Text := CurrToStr(Driver.Summ4);
end else
begin
edtSumm1.Clear;
edtSumm2.Clear;
edtSumm3.Clear;
edtSumm4.Clear;
end;
finally
EnableButtons(True);
end;
end;
procedure TfmFiscalMemory.btnGetLastFMRecordDateClick(Sender: TObject);
begin
EnableButtons(False);
try
if Driver.GetLastFMRecordDate = 0 then
begin
if Driver.TypeOfLastEntryFM then edtFMType.Text := 'Смен. итог'
else edtFMType.Text := 'Фискал.';
edtFMDate.Text := DateToStr(Driver.Date);
end
else begin
edtFMType.Clear;
edtFMDate.Clear;
end;
finally
EnableButtons(True);
end;
end;
procedure TfmFiscalMemory.btnInitFMClick(Sender: TObject);
begin
EnableButtons(False);
try
Driver.InitFM;
finally
EnableButtons(True);
end;
end;
end.
|
{ *********************************************************************************** }
{ * CryptoLib Library * }
{ * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * }
{ * Github Repository <https://github.com/Xor-el> * }
{ * Distributed under the MIT software license, see the accompanying file LICENSE * }
{ * or visit http://www.opensource.org/licenses/mit-license.php. * }
{ * Acknowledgements: * }
{ * * }
{ * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * }
{ * development of this library * }
{ * ******************************************************************************* * }
(* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *)
unit ClpIAsn1TaggedObject;
{$I ..\Include\CryptoLib.inc}
interface
uses
ClpIProxiedInterface;
type
IAsn1TaggedObject = interface(IAsn1Object)
['{2EBA68BE-CEC6-4030-BB9C-E8310C9B7D5F}']
function GetTagNo: Int32;
function Getexplicitly: Boolean;
function Getobj: IAsn1Encodable;
property tagNo: Int32 read GetTagNo;
property explicitly: Boolean read Getexplicitly;
property obj: IAsn1Encodable read Getobj;
function isExplicit(): Boolean;
function IsEmpty(): Boolean;
function GetObject(): IAsn1Object;
function GetObjectParser(tag: Int32; isExplicit: Boolean): IAsn1Convertible;
function ToString(): String;
end;
implementation
end.
|
unit aeBoundingVolume;
interface
uses types, windows, aeMaths, aeRenderable, aeConst, aetypes;
// AE_BOUNDINGVOLUME_TYPE_UNINITILIZED means that we have an abstract, not good!
type
TaeBoundingVolumeType = (AE_BOUNDINGVOLUME_TYPE_UNINITILIZED, AE_BOUNDINGVOLUME_TYPE_OBB);
type
TaeBoundingVolume = class(TaeRenderable)
public
constructor Create;
function distanceFromCenter(otherBV: TaeBoundingVolume): Single;
/// <remarks>
/// calculates bounding Volume from triangle data.
/// </remarks>
/// <returns>
/// returns true if successful.
/// </returns>
function calculateBoundingVolume(vio: TaeVertexIndexBuffer; avarageCenter: boolean = false): boolean; virtual; abstract;
function collideWith(otherBV: TaeBoundingVolume; var transformMatrix: TaeMatrix44): boolean; virtual; abstract;
function Intersect(ray: TaeRay3; transformMatrix: TaeMatrix44): boolean; virtual; abstract;
procedure clear; virtual; abstract;
function getCenter: TPoint3D;
function getType: TaeBoundingVolumeType;
protected
_type: TaeBoundingVolumeType;
_center: TPoint3D;
end;
implementation
{ TaeBoundingVolume }
constructor TaeBoundingVolume.Create;
begin
self._type := AE_BOUNDINGVOLUME_TYPE_UNINITILIZED;
end;
function TaeBoundingVolume.distanceFromCenter(otherBV: TaeBoundingVolume): Single;
begin
Result := self._center.Distance(otherBV.getCenter);
end;
function TaeBoundingVolume.getCenter: TPoint3D;
begin
Result := self._center;
end;
function TaeBoundingVolume.getType: TaeBoundingVolumeType;
begin
Result := self._type;
end;
end.
|
unit K395658761;
{* [Requestlink:395658761] }
// Модуль: "w:\archi\source\projects\Archi\Tests\K395658761.pas"
// Стереотип: "TestCase"
// Элемент модели: "K395658761" MUID: (506A965C0032)
// Имя типа: "TK395658761"
{$Include w:\archi\source\projects\Archi\arDefine.inc}
interface
{$If Defined(nsTest) AND Defined(InsiderTest)}
uses
l3IntfUses
{$If NOT Defined(NoScripts)}
, ArchiInsiderTest
{$IfEnd} // NOT Defined(NoScripts)
;
type
TK395658761 = class({$If NOT Defined(NoScripts)}
TArchiInsiderTest
{$IfEnd} // NOT Defined(NoScripts)
)
{* [Requestlink:395658761] }
protected
function GetFolder: AnsiString; override;
{* Папка в которую входит тест }
function GetModelElementGUID: AnsiString; override;
{* Идентификатор элемента модели, который описывает тест }
end;//TK395658761
{$IfEnd} // Defined(nsTest) AND Defined(InsiderTest)
implementation
{$If Defined(nsTest) AND Defined(InsiderTest)}
uses
l3ImplUses
, TestFrameWork
//#UC START# *506A965C0032impl_uses*
//#UC END# *506A965C0032impl_uses*
;
{$If NOT Defined(NoScripts)}
function TK395658761.GetFolder: AnsiString;
{* Папка в которую входит тест }
begin
Result := 'TableTools';
end;//TK395658761.GetFolder
function TK395658761.GetModelElementGUID: AnsiString;
{* Идентификатор элемента модели, который описывает тест }
begin
Result := '506A965C0032';
end;//TK395658761.GetModelElementGUID
initialization
TestFramework.RegisterTest(TK395658761.Suite);
{$IfEnd} // NOT Defined(NoScripts)
{$IfEnd} // Defined(nsTest) AND Defined(InsiderTest)
end.
|
inherited dmConfiguracaoLayouts: TdmConfiguracaoLayouts
OldCreateOrder = True
inherited qryManutencao: TIBCQuery
SQLInsert.Strings = (
'INSERT INTO CONFIGLAYOUT'
' (ITEMIDLAYOUT, CAMPO, POSINICIAL, TAMANHO, DESCRICAO, VALOR_DE' +
'FAULT, TRATAMENTO, ORDEM, IDLINHA, CAMPOREF, DT_ALTERACAO, OPERA' +
'DOR)'
'VALUES'
' (:ITEMIDLAYOUT, :CAMPO, :POSINICIAL, :TAMANHO, :DESCRICAO, :VA' +
'LOR_DEFAULT, :TRATAMENTO, :ORDEM, :IDLINHA, :CAMPOREF, :DT_ALTER' +
'ACAO, :OPERADOR)')
SQLDelete.Strings = (
'DELETE FROM CONFIGLAYOUT'
'WHERE'
' ITEMIDLAYOUT = :Old_ITEMIDLAYOUT AND CAMPO = :Old_CAMPO')
SQLUpdate.Strings = (
'UPDATE CONFIGLAYOUT'
'SET'
' ITEMIDLAYOUT = :ITEMIDLAYOUT, CAMPO = :CAMPO, POSINICIAL = :PO' +
'SINICIAL, TAMANHO = :TAMANHO, DESCRICAO = :DESCRICAO, VALOR_DEFA' +
'ULT = :VALOR_DEFAULT, TRATAMENTO = :TRATAMENTO, ORDEM = :ORDEM, ' +
'IDLINHA = :IDLINHA, CAMPOREF = :CAMPOREF, DT_ALTERACAO = :DT_ALT' +
'ERACAO, OPERADOR = :OPERADOR'
'WHERE'
' ITEMIDLAYOUT = :Old_ITEMIDLAYOUT AND CAMPO = :Old_CAMPO')
SQLRefresh.Strings = (
'SELECT ITEMIDLAYOUT, CAMPO, POSINICIAL, TAMANHO, DESCRICAO, VALO' +
'R_DEFAULT, TRATAMENTO, ORDEM, IDLINHA, CAMPOREF, DT_ALTERACAO, O' +
'PERADOR FROM CONFIGLAYOUT'
'WHERE'
' ITEMIDLAYOUT = :Old_ITEMIDLAYOUT AND CAMPO = :Old_CAMPO')
SQLLock.Strings = (
'SELECT NULL FROM CONFIGLAYOUT'
'WHERE'
'ITEMIDLAYOUT = :Old_ITEMIDLAYOUT AND CAMPO = :Old_CAMPO'
'FOR UPDATE WITH LOCK')
SQL.Strings = (
'SELECT'
' ITEMIDLAYOUT, '
' CAMPO, '
' POSINICIAL, '
' TAMANHO, '
' DESCRICAO, '
' VALOR_DEFAULT, '
' TRATAMENTO, '
' ORDEM, '
' IDLINHA, '
' CAMPOREF, '
' DT_ALTERACAO, '
' OPERADOR'
'FROM CONFIGLAYOUT')
object qryManutencaoITEMIDLAYOUT: TIntegerField
FieldName = 'ITEMIDLAYOUT'
Required = True
end
object qryManutencaoCAMPO: TStringField
FieldName = 'CAMPO'
Required = True
Size = 30
end
object qryManutencaoPOSINICIAL: TIntegerField
FieldName = 'POSINICIAL'
end
object qryManutencaoTAMANHO: TIntegerField
FieldName = 'TAMANHO'
end
object qryManutencaoDESCRICAO: TStringField
FieldName = 'DESCRICAO'
Size = 30
end
object qryManutencaoVALOR_DEFAULT: TStringField
FieldName = 'VALOR_DEFAULT'
Size = 30
end
object qryManutencaoTRATAMENTO: TIntegerField
FieldName = 'TRATAMENTO'
end
object qryManutencaoORDEM: TIntegerField
FieldName = 'ORDEM'
end
object qryManutencaoIDLINHA: TStringField
FieldName = 'IDLINHA'
Size = 10
end
object qryManutencaoCAMPOREF: TStringField
FieldName = 'CAMPOREF'
Size = 30
end
object qryManutencaoOPERADOR: TStringField
FieldName = 'OPERADOR'
end
object qryManutencaoDT_ALTERACAO: TDateTimeField
FieldName = 'DT_ALTERACAO'
end
end
inherited qryLocalizacao: TIBCQuery
SQL.Strings = (
'SELECT'
' ITEMIDLAYOUT, '
' CAMPO, '
' POSINICIAL, '
' TAMANHO, '
' DESCRICAO, '
' VALOR_DEFAULT, '
' TRATAMENTO, '
' ORDEM, '
' IDLINHA, '
' CAMPOREF, '
' DT_ALTERACAO, '
' OPERADOR'
'FROM CONFIGLAYOUT')
object qryLocalizacaoITEMIDLAYOUT: TIntegerField
FieldName = 'ITEMIDLAYOUT'
Required = True
end
object qryLocalizacaoCAMPO: TStringField
FieldName = 'CAMPO'
Required = True
Size = 30
end
object qryLocalizacaoPOSINICIAL: TIntegerField
FieldName = 'POSINICIAL'
end
object qryLocalizacaoTAMANHO: TIntegerField
FieldName = 'TAMANHO'
end
object qryLocalizacaoDESCRICAO: TStringField
FieldName = 'DESCRICAO'
Size = 30
end
object qryLocalizacaoVALOR_DEFAULT: TStringField
FieldName = 'VALOR_DEFAULT'
Size = 30
end
object qryLocalizacaoTRATAMENTO: TIntegerField
FieldName = 'TRATAMENTO'
end
object qryLocalizacaoORDEM: TIntegerField
FieldName = 'ORDEM'
end
object qryLocalizacaoIDLINHA: TStringField
FieldName = 'IDLINHA'
Size = 10
end
object qryLocalizacaoCAMPOREF: TStringField
FieldName = 'CAMPOREF'
Size = 30
end
object qryLocalizacaoDT_ALTERACAO: TDateTimeField
FieldName = 'DT_ALTERACAO'
end
object qryLocalizacaoOPERADOR: TStringField
FieldName = 'OPERADOR'
end
end
end
|
program binaryHandling(output);
const
MIN = 1;
MAX = 5;
type
bit = 0 .. 1;
bitString = array [MIN .. MAX] of bit;
var
b : bitString;
procedure printBits(var b : bitString);
var i : integer;
begin
for i := MIN to MAX do
write(b[i]);
writeln;
end;
function to_decimal(b : bitString) : integer;
var i, n : integer;
begin
i := 0; n := i;
while i < MAX do begin
n := n * 2 + b[MAX - i];
i := i + 1
end;
to_decimal := n
end;
procedure to_binary(n : integer; var b : bitString);
var i : integer;
begin
i := 0;
while n > 0 do begin
i := i + 1;
b[i] := n mod 2;
n := n div 2
end;
end;
begin
b[1] := 1; b[2] := 1; b[3] := 0; b[4] := 0; b[5] := 1;
printBits(b);
writeln(to_decimal(b));
to_binary(7, b);
printBits(b);
end. |
unit MdiChilds.FmPluginInstaller;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, MdiChilds.CustomDialog, JvComponentBase, JvDragDrop, Vcl.ComCtrls, JvExComCtrls, JvComCtrls, JvCheckTreeView,
Vcl.StdCtrls, Vcl.ExtCtrls, FWZipReader, System.ImageList, Vcl.ImgList, cxGraphics, MdiChilds.ProgressForm, ActionHandler, JvBaseDlg,
JvSelectDirectory, JvChangeNotify;
type
TFmPluginInstaller = class(TFmProcess)
tvPlugins: TJvCheckTreeView;
JvDragDrop: TJvDragDrop;
ilTree: TcxImageList;
JvSelectDirectory: TJvSelectDirectory;
JvChangeNotify: TJvChangeNotify;
procedure JvDragDropDrop(Sender: TObject; Pos: TPoint; Value: TStrings);
procedure tvPluginsNodeCheckedChange(Sender: TObject; Node: TJvTreeNode);
procedure tvPluginsDeletion(Sender: TObject; Node: TTreeNode);
procedure FormShow(Sender: TObject);
procedure JvChangeNotifyChangeNotify(Sender: TObject; Dir: string; Actions: TJvChangeActions);
private
ChangeItem: TJvChangeItem;
procedure LoadPlugin(Node: TTreeNode; FileName: string);
procedure AddTreeItem(Node: TTreeNode; ZipItem: TFWZipReaderItem);
protected
procedure DoOk(Sender: TObject; ProgressForm: TFmProgress; var ShowMessage: Boolean); override;
public
constructor Create(AOwner: TComponent); override;
procedure UpdateTree;
procedure AddPlugin(AFileName: string);
end;
TPluginInstallerActionHandler = class(TAbstractActionHandler)
public
procedure ExecuteAction(UserData: Pointer = nil); override;
end;
var
FmPluginInstaller: TFmPluginInstaller;
implementation
{$R *.dfm}
procedure TFmPluginInstaller.AddPlugin(AFileName: string);
var
Node: TTreeNode;
begin
Node := tvPlugins.Items.AddChild(nil, AFileName);
Node.ImageIndex := 0;
Node.SelectedIndex := 0;
TJvTreeNode(Node).Checked := True;
LoadPlugin(Node, AFileName);
end;
procedure TFmPluginInstaller.AddTreeItem(Node: TTreeNode; ZipItem: TFWZipReaderItem);
var
aNode: TTreeNode;
Stream: TMemoryStream;
begin
Stream := TMemoryStream.Create;
try
ZipItem.ExtractToStream(Stream, '');
aNode := tvPlugins.Items.AddChildObject(Node, ZipItem.FileName, Stream);
aNode.ImageIndex := 1;
aNode.SelectedIndex := 1;
TJvTreeNode(aNode).Checked := True;
except
Self.MessageBoxError('Не удалось прочитать содержимое: ' + ZipItem.FileName);
end;
end;
constructor TFmPluginInstaller.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
ChangeItem := JvChangeNotify.Notifications.Add;
end;
procedure TFmPluginInstaller.DoOk(Sender: TObject; ProgressForm: TFmProgress; var ShowMessage: Boolean);
var
Node: TTreeNode;
Stream: TMemoryStream;
begin
for Node in tvPlugins.Items do
begin
if TJvTreeNode(Node).Checked and (Node.Data <> nil) then
begin
Stream := TMemoryStream(Node.Data);
Stream.SaveToFile(ExtractFilePath(Application.ExeName) + Node.Text);
end;
end;
ShowMessage := True;
end;
procedure TFmPluginInstaller.FormShow(Sender: TObject);
begin
inherited;
JvChangeNotify.Notifications[0].Directory := GetEnvironmentVariable('USERPROFILE') + '\Downloads\';
JvChangeNotify.Active := True;
UpdateTree;
end;
procedure TFmPluginInstaller.JvChangeNotifyChangeNotify(Sender: TObject; Dir: string; Actions: TJvChangeActions);
begin
UpdateTree;
end;
procedure TFmPluginInstaller.JvDragDropDrop(Sender: TObject; Pos: TPoint; Value: TStrings);
var
I: Integer;
begin
tvPlugins.Items.Clear;
for I := 0 to Value.Count - 1 do
begin
if AnsiUpperCase(ExtractFileExt(Value[I])) = '.GCOMP' then
begin
AddPlugin(Value[I]);
end;
end;
end;
procedure TFmPluginInstaller.LoadPlugin(Node: TTreeNode; FileName: string);
var
ZipReader: TFWZipReader;
I: Integer;
begin
ZipReader := TFWZipReader.Create;
try
ZipReader.LoadFromFile(FileName);
for I := 0 to ZipReader.Count - 1 do
begin
TJvTreeNode(Node).Checked := True;
if not ZipReader.Item[I].IsFolder then
AddTreeItem(Node, ZipReader.Item[I]);
end;
finally
ZipReader.Free;
end;
end;
procedure TFmPluginInstaller.tvPluginsDeletion(Sender: TObject; Node: TTreeNode);
begin
if Node.Data <> nil then
begin
TMemoryStream(Node.Data).Free;
Node.Data := nil;
end;
end;
procedure TFmPluginInstaller.tvPluginsNodeCheckedChange(Sender: TObject; Node: TJvTreeNode);
var
Child: TTreeNode;
begin
Child := Node.getFirstChild;
while Child <> nil do
begin
TJvTreeNode(Child).Checked := Node.Checked;
Child := Node.GetNextChild(Child);
end;
end;
procedure TFmPluginInstaller.UpdateTree;
var
SR: TSearchRec;
begin
tvPlugins.Items.Clear;
tvPlugins.Items.BeginUpdate;
if FindFirst(Self.ChangeItem.Directory + '*.gcomp', faAnyFile, SR) = 0 then
begin
repeat
AddPlugin(ChangeItem.Directory + SR.Name);
until FindNext(SR) <> 0;
FindClose(SR);
end;
tvPlugins.Items.EndUpdate;
end;
{ TPluginInstallerActionHandler }
procedure TPluginInstallerActionHandler.ExecuteAction;
begin
TFmPluginInstaller.Create(Application).Show;
end;
begin
ActionHandlerManager.RegisterActionHandler('Установка дополнительных обработок', hkDefault, TPluginInstallerActionHandler);
end.
|
unit TestBaseJsonUnmarshalUnit;
interface
uses
TestFramework, Classes, SysUtils;
type
TTestBaseJsonUnmarshal = class abstract(TTestCase)
protected
procedure SaveTestDataToFile(s: String);
function EtalonFilename(TestName: String): String;
end;
implementation
{ TTestOptimizationParametersToJson }
uses MarshalUnMarshalUnit, GenericParametersUnit;
function TTestBaseJsonUnmarshal.EtalonFilename(TestName: String): String;
begin
Result := '..\..\Etalons\' + TestName + '.json';
end;
procedure TTestBaseJsonUnmarshal.SaveTestDataToFile(s: String);
var
st: TStringList;
begin
st := TStringList.Create;
try
st.Text := s;
st.SaveToFile('TestData.txt');
finally
FreeAndNil(st);
end;
end;
end. |
unit PaletteIO;
interface
uses
Palettes;
procedure JascLoadFromFile( const Filename : string; var LogPalette );
procedure JascSaveToFile( const Filename : string; const LogPalette );
implementation
uses
SysUtils, GDI;
procedure JascLoadFromFile( const Filename : string; var LogPalette );
var
LogPal : T256LogPalette absolute LogPalette;
var
JascFile : text;
Id : string;
Indx : integer;
begin
LogPal.Version := LogPaletteVersion;
LogPal.NumberOfEntries := 0;
AssignFile( JascFile, Filename );
reset( JascFile );
try
readln( JascFile, Id ); // Read JASC id
if UpperCase( Id ) = 'JASC-PAL'
then
begin
readln; // Read JASC version
readln( JascFile, LogPal.NumberOfEntries );
for Indx := 0 to LogPal.NumberOfEntries - 1 do
with LogPal.Entries[Indx] do
readln( JascFile, peRed, peGreen, peBlue );
end;
finally
CloseFile( JascFile );
end;
end;
procedure JascSaveToFile( const Filename : string; const LogPalette );
var
LogPal : T256LogPalette absolute LogPalette;
var
JascFile : text;
Indx : integer;
begin
AssignFile( JascFile, Filename );
rewrite( JascFile );
try
writeln( JascFile, 'JASC-PAL' ); // Write JASC id
writeln( JascFile, '0100' ); // Write JASC version
writeln( JascFile, LogPal.NumberOfEntries );
for Indx := 0 to LogPal.NumberOfEntries - 1 do
with LogPal.Entries[Indx] do
writeln( JascFile, peRed, peGreen, peBlue );
finally
CloseFile( JascFile );
end;
end;
end.
(*
The Jasc palette file format is not the same as the Microsoft PAL format.
Paint Shop Pro uses the Jasc palette file format (extension ".PAL") for saving 16 and 256 color
palette files. The file type was created as a text file so that you can edit or create palettes
with a text editor, such as Notepad. The file structure is as follows:
Header: JASC-PAL
Version: 0100
Number of Colors: 16 or 256
Palette Data: Made up of Red, Green and Blue color components. Color components are values from
0 to 255. RGB values must be separated by one space. Each RGB series must be on a separate line.
Example
The following is Window's default colors in the Jasc PAL file format:
JASC-PAL
0100
16
0 0 0
0 0 191
0 191 0
0 191 191
191 0 0
191 0 191
191 191 0
192 192 192
128 128 128
0 0 255
0 255 0
0 255 255
255 0 0
255 0 255
255 255 0
255 255 255
*)
|
unit MainForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Menus, ExtCtrls, StdCtrls, ComCtrls, ImgList, Registry,
xLngManager,
FR_View, FR_Desgn, FR_Class, FR_Rich, FR_ChBox, FR_Cross, FR_RRect, FR_BarC, FR_Shape, FR_Chart,
cxControls, cxContainer, cxTreeView, cxLookAndFeelPainters, cxButtons, cxEdit,
cxDropDownEdit, cxImageComboBox, cxGroupBox, cxTextEdit, cxMaskEdit;
const
langMax = 2;
langNames: array [0 .. langMax] of String = ('English', 'Русский', 'Українська');
langFolders: array [0 .. langMax] of String = ('ENG', 'RUS', 'UKR');
regRepEdit: String = '\SOFTWARE\OPERATOR\REPEDIT\';
type
TfrmMainForm = class(TForm)
Panel1: TPanel;
pmDocTree: TPopupMenu;
miEdit1: TMenuItem;
miCopyEdit1: TMenuItem;
SaveDialog1: TSaveDialog;
langMan: TxLngManager;
frRichObject1: TfrRichObject;
frChartObject1: TfrChartObject;
frShapeObject1: TfrShapeObject;
frBarCodeObject1: TfrBarCodeObject;
frRoundRectObject1: TfrRoundRectObject;
frCrossObject1: TfrCrossObject;
frCheckBoxObject1: TfrCheckBoxObject;
miRevert: TMenuItem;
miRestoreOrig: TMenuItem;
cxGroupBox1: TcxGroupBox;
docTreeView: TcxTreeView;
cbLangName: TcxImageComboBox;
butLoad: TcxButton;
butClose: TcxButton;
OpenDialog1: TOpenDialog;
ImageList1: TImageList;
procedure switchLang;
procedure InitRes;
procedure docTreeViewClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure cbLangNameChange(Sender: TObject);
procedure docTreeViewDblClick(Sender: TObject);
procedure miCopyEdit1Click(Sender: TObject);
function getCustomReportsReg: TRegKeyInfo;
procedure FormResize(Sender: TObject);
procedure pmDocTreePopup(Sender: TObject);
procedure miRevertClick(Sender: TObject);
procedure miRestoreOrigClick(Sender: TObject);
procedure butCloseClick(Sender: TObject);
procedure butLoadClick(Sender: TObject);
private
function getSelRepPath(inMenu: Boolean = False): String;
procedure restoreOldrep(from: Integer);
procedure makeLangTree(lang: Cardinal);
end;
var
frmMainForm: TfrmMainForm;
frDoc: TfrReport;
RepPath: String;
regCustomReps: String;
selNode: TTreeNode;
//========================================================================
//========================================================================
//========================================================================
implementation
{$IFDEF UDEBUG}
var
DEBUG_unit_ID: Integer; Debugging: Boolean; DEBUG_group_ID: String = '';
{$ENDIF}
{$R *.dfm}
//========================================================================
function getErrStr: String;
begin
Result := SysErrorMessage(GetLastError);
end;
//========================================================================
function TfrmMainForm.getSelRepPath(inMenu: Boolean = False): String;
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMainForm.getSelRepPath') else _udebug := nil;{$ENDIF}
Result := '';
if inMenu then begin // avoid fucking strange shit with selection clearing before the popup item executing
if selNode.Data = nil then begin {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} Exit; end;
Result := String(selNode.Data^)
end
else if docTreeView.Selected.Data = nil
then begin {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} Exit; end
else Result := String(docTreeView.Selected.Data^);
Result := RepPath + langFolders[cbLangName.ItemIndex] + '\' + Result;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//========================================================================
procedure TfrmMainForm.switchLang;
var
s: String;
{$IFDEF UDEBUG}_udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMainForm.switchLang') else _udebug := nil;{$ENDIF}
try
langMan.Active := False;
langMan.Active := True;
langMan.ActiveLngDesc := langFolders[cbLangName.ItemIndex];
except
ShowMessage('Unable to load language resource file! Exitting.');
raise;
end;
s := 'FR_' + langFolders[cbLangName.ItemIndex] + '.DLL';
try
//frLocale := TfrLocale.Create;
frLocale.LoadDll(s);
except
on e: Exception do ShowMessage('cannot localize FastReports engine as: ' + s);
end;
with langMan do begin // localizing
miEdit1.Caption := GetRS('menus', 'miEdit');
miCopyEdit1.Caption := GetRS('menus', 'miCopyEdit');
miRevert.Caption := GetRS('menus', 'miRevert');
miRestoreOrig.Caption := GetRS('menus', 'miRestoreOrig');
butClose.Caption := GetRS('common', 'butClose');
butLoad.Caption := GetRS('common', 'butLoad');
end;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//========================================================================
procedure TfrmMainForm.InitRes;
//{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
//{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMainForm.InitRes') else _udebug := nil;{$ENDIF}
langMan.CfgFile := ExtractFilePath(ParamStr(0)) + 'RE_LNG\lng.ini';
//{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//========================================================================
procedure TfrmMainForm.makeLangTree(lang: Cardinal);
var
i,l: Cardinal;
nodes: array [0..9] of TTreeNode; // 9 level nesting should be good guess ;)
rki: TRegKeyInfo;
procedure addChild(fname, descr: String);
var s: ^String;
begin
if fname = '' then Exit;
new(s);
s^ := fname;
nodes[l + 1] := docTreeView.Items.AddChildObject(nodes[l], descr, s );
end;
procedure addSibling(descr: String);
begin
nodes[l] := docTreeView.Items.AddObject(nodes[l], descr, nil );
end;
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMainForm.makeLangTree') else _udebug := nil;{$ENDIF}
docTreeView.Items.BeginUpdate;
docTreeView.Items.Clear;
rki := getCustomReportsReg;
l := 0; nodes[0] := nil;
case lang of
0: begin // en
addSibling('Main slips');
//addChild('Waybill_Invoice.frf', '????Memorandum');
addChild('ReturnOut.frf', 'Return to supplier');
addChild('Waybill_Mov.frf', 'Goods movement slip');
addChild('Waybill_In.frf', 'Goods receipt slip');
addChild('Waybill_Out.frf', 'Goods dispatch slip');
addSibling('Invoices');
addChild('WaybillAcc_Out.frf', 'Invoice');
addSibling('Orders');
addChild('Order_Out.frf', 'Client''''s order');
addChild('Order_In.frf', 'Order to supplier');
addSibling('Miscellaneous documents');
addChild('WarrantyDoc.frf', 'Warranty slip');
addChild('PriceLabel.frf', 'Price tags');
addChild('PriceLabelBC.frf', 'Price tags w barcodes');
addChild('Rep_DocRegistry.frf', 'Documents registry');
addSibling('Warehouse/point of sales');
addChild('Waybill_Rest.frf', 'Initial stock balance');
addChild('Inv.frf', 'Inventory');
addSibling('Reports on goods');
addChild('WriteOff.frf', 'Write off');
addChild('Rep1.frf', 'Short income and sales report');
addChild('Rep25.frf', 'Detailed goods income report');
addChild('RepMatRest.frf', 'Goods remains report');
addChild('grpmove.frf', 'Goods category movement report');
addChild('matmove.frf', 'Single product movement report');
addChild('Rep10.frf', 'Turnover register');
addChild('Rep10_1.frf', 'Turnover register for goods category');
addChild('RepMatSelRank.frf', 'Sales rating');
addChild('RepMatMinRest.frf', 'Minimal goods remains report');
addChild('RepMatTurnPeriod.frf', 'Product turnover (w/o sums)');
addChild('RepMatTurnPeriod2.frf', 'Product turnover');
addChild('RepMatSelSvc.frf', 'Short service sales summary');
addSibling('Financial reports');
addChild('RepMatSelPr.frf', 'Report on profitable sales');
addChild('DynSel.frf', 'Sales dynamics');
addChild('RepExpenses.frf', 'Expenses report');
addChild('ReplPRvsEx.frf', 'Financial results summary');
addChild('Rep21.frf', 'Short financial results report');
addChild('RepMoney.frf', 'Funds turnover report');
addSibling('Business partners');
addChild('Rep3.frf', 'Sales by clients / Income by suppliers');
addChild('Rep3_1.frf', 'Same as above with emphasize on profit');
addChild('Kreditors.frf', 'Creditors list');
addChild('Debitors.frf', 'Debtors list');
addChild('RepKAAllBOnly.frf', 'Business partner balance report');
addChild('RepKAAll.frf', 'Report on business partner');
addSibling('Contracts');
addChild('Rep24.frf', 'Short report on contract');
addSibling('Internal reports');
addChild('RepPersons.frf', 'Employees performance report');
if rki.NumSubKeys > 0 then addSibling('* Ваши отчёты *');
end; // english
//-------------------------------------------------------------------------
// русский
1: begin
addSibling('Накладные');
addChild('Waybill_Invoice.frf', 'Счёт-фактура');
addChild('ReturnOut.frf', 'Возвратная накладная');
addChild('Waybill_Mov.frf', 'Накладная перемещения');
addChild('Waybill_In.frf', 'Приходная накладная');
addChild('Waybill_Out.frf', 'Расходная накладная');
addSibling('Счета');
addChild('WaybillAcc_Out.frf', 'Счёт на предоплату');
addSibling('Заказы');
addChild('Order_Out.frf', 'Заказ от клиента');
addChild('Order_In.frf', 'Заказ поставщику');
addSibling('Документы');
addChild('WarrantyDoc.frf', 'Гарантийный документ');
addChild('PriceLabel.frf', 'Ценники');
addChild('PriceLabelBC.frf', 'Ценники со штрих-кодом');
addChild('Rep_DocRegistry.frf', 'Реестр документов');
addSibling('Склад');
addChild('Waybill_Rest.frf', 'Акт ввода остатков товара');
addChild('Inv.frf', 'Акт инвентаризации');
addSibling('Товарные отчёты');
addChild('WriteOff.frf', 'Акт списания');
addChild('Rep1.frf', 'Краткий отчёт о приходе и продажах товаров');
addChild('Rep25.frf', 'Развернутый отчет о приходе');
addChild('RepMatRest.frf', 'Ведомость материальных остатков');
addChild('grpmove.frf', 'Отчёт о движении группы товара');
addChild('matmove.frf', 'Отчёт о движении товара');
addChild('Rep10.frf', 'Оборотная ведомость');
addChild('Rep10_1.frf', 'Оборотная ведомость по группам товаров');
addChild('RepMatSelRank.frf', 'Рейтинг продаж');
addChild('RepMatMinRest.frf', 'Отчёт о минимальных остатках');
addChild('RepMatTurnPeriod.frf', 'Оборотная ведомость товара (без сумм)');
addChild('RepMatTurnPeriod2.frf', 'Оборотная ведомость товара');
addChild('RepMatSelSvc.frf', 'Краткий отчёт о продажах услуг');
addSibling('Финансовые отчёты');
addChild('RepMatSelPr.frf', 'Отчёт о продажах с прибылью');
addChild('DynSel.frf', 'Динамика продаж');
addChild('RepExpenses.frf', 'Отчёт о затратах');
addChild('ReplPRvsEx.frf', 'Отчёт о финансовом результате');
addChild('Rep21.frf', 'Краткий отчёт о финансовом результате');
addChild('RepMoney.frf', 'Отчёт об оборотах денежных средств');
addSibling('Отчёты по контрагентам');
addChild('Rep3.frf', 'Отчёт о продажах по клиентам/приходе по поставщикам');
addChild('Rep3_1.frf', '--"-- с показом прибыли');
addChild('Kreditors.frf', 'Список кредиторов (мы должны)');
addChild('Debitors.frf', 'Список дебеторов (нам должны)');
addChild('RepKAAllBOnly.frf', 'Баланс по контрагенту');
addChild('RepKAAll.frf', 'Отчёт по контрагенту');
addSibling('Отчёты по договорам');
addChild('Rep24.frf', 'Краткий отчёт по договору');
addSibling('Служебные отчёты');
addChild('RepPersons.frf', 'Отчёт о работе служащих');
if rki.NumSubKeys > 0 then addSibling('* Ваши отчёты *');
end; // russian
//-------------------------------------------------------------------------
// ukrainian
2: begin
addSibling('Накладні');
addChild('ReturnOut.frf', 'Повернення');
addChild('Waybill_Mov.frf', 'Переміщення');
addChild('Waybill_In.frf', 'Прибуткова');
addChild('Waybill_Out.frf', 'Видаткова');
addSibling('Рахунки');
addChild('WaybillAcc_Out.frf', 'Передоплата');
addSibling('Замовлення');
addChild('Order_Out.frf', 'Від клієнту');
addChild('Order_In.frf', 'Постачальнику');
addSibling('Документи');
addChild('WarrantyDoc.frf', 'Гарантійний документ');
addChild('PriceLabel.frf', 'Цiнники');
addChild('PriceLabelBC.frf', 'Цiнники зi штрих-кодом');
addChild('Rep_DocRegistry.frf', 'Реєстр документiв');
addSibling('Складскi звiти');
addChild('Rep1.frf', 'Скорочений звiт про прибуток товарiв');
addChild('Rep25.frf', 'Розгорнутий звiт про прибуток товарiв');
addChild('Rep1.frf', 'Скорочений звiт про продаж товарiв');
addChild('RepMatRest.frf', 'Вiдомiсть матерiальних залишкiв');
addChild('grpmove.frf', 'Звiт про рух групи товару');
addChild('matmove.frf', 'Звiт про рух товару');
addChild('Rep10.frf', 'Оборотна вiдомiсть');
addChild('Rep10_1.frf', 'Оборотна вiдомiсть по группах');
addChild('RepMatSelRank.frf', 'Рейтинг продажу');
addChild('RepMatMinRest.frf', 'Звiт про мiнiмальнi залишки');
addChild('RepMatTurnPeriod.frf', 'Оборотна вiдомiсть товару (без сум)');
addChild('RepMatTurnPeriod2.frf', 'Оборотна вiдомiсть товару');
addChild('RepMatSelSvc.frf', 'Скорочений звiт про продаж послуг');
addSibling('Фiнансовi звiти');
addChild('RepMatSelPr.frf', 'Звiт про продаж з прибутком');
addChild('DynSel.frf', 'Динамiка продажу');
addChild('RepExpenses.frf', 'Звiт про затрати');
addChild('ReplPRvsEx.frf', 'Звiт про фiнансовий результат');
addChild('Rep21.frf', 'Скорочений звiт про фiнансовий результат');
addChild('REpMoney.frf', 'Звiт про обiг грошових засобiв');
addSibling('Звiти по контрагентам');
addChild('Rep3.frf', 'Звiт про продаж по клiєнтам/по постачальникам');
addChild('Rep3_1.frf', '--"-- з показом прибутку');
addChild('Kreditors.frf', 'Список кредиторiв (ми заборгували)');
addChild('Debitors.frf', 'Список дебеторiв (нам заборгували)');
addChild('RepKAAllBOnly.frf', 'Баланс по контрагенту');
addChild('RepKAAll.frf', 'Звiт по контрагенту');
addSibling('Звiти по договорах');
addChild('Rep24.frf', 'Скорочений звiт за договором');
addSibling('Службовi звiти');
addChild('RepPersons.frf', 'Звiт про роботу службовцiв');
if rki.NumSubKeys > 0 then addSibling('* Ваші звіти *');
end; // ukrainian
end; //case
// adding custom reports here ------------------------------------------------
if rki.NumSubKeys > 0 then
with TRegistry.Create do begin
RootKey := HKEY_LOCAL_MACHINE;
for i := 1 to rki.NumSubKeys do begin
OpenKey(regCustomReps + IntToStr(i), False);
addChild(ReadString('File'), ReadString('Name'));
CloseKey;
end;
Free;
end;
docTreeView.Items.EndUpdate;
docTreeView.FullExpand;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//========================================================================
procedure TfrmMainForm.FormCreate(Sender: TObject);
var
i: Cardinal;
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMainForm.FormCreate') else _udebug := nil;{$ENDIF}
cxGRoupBox1.Caption := ' Copyright © Irystyle, 2003-' + IntToStr(CurrentYear) + ' ';
InitRes;
regCustomReps := regRepEdit + 'CUSTOMREP';
frDoc := TfrReport.Create(nil);
cbLangName.Tag := 0;
cbLangName.Properties.Items.Clear;
cbLangName.Properties.BeginUpdate;
for i := 0 to High(Langnames) do begin
cbLangName.Properties.Items.Add;
cbLangName.Properties.Items[i].Description := Langnames[i];
cbLangName.Properties.Items[i].Value := i;
end;
cbLangName.Properties.EndUpdate;
with TRegistry.Create do begin
RootKey := HKEY_CURRENT_USER;
if OpenKey(regRepEdit + 'lang', False) then begin // last lang used
cbLangName.ItemIndex := ReadInteger('lang');
CloseKey;
end
else cbLangName.ItemIndex := 0;
cbLangName.Tag := 1;
cbLangNameChange(Sender);
if not OpenKey('\SOFTWARE\OPERATOR\SKLAD', False) then begin
ShowMessage(langMan.GetRs('errors', 'noMainApp'));
Halt;
end;
RepPath := ReadString('ClientPath');
if RepPath = '' then begin
ShowMessage(langMan.GetRs('errors', 'noMainApp'));
Halt;
end;
RepPath := RepPath + '\Reports\';
CloseKey;
if OpenKey(regRepEdit + 'Form', False) then begin // last mainform shape
frmMainForm.Width := ReadInteger('Width');
frmMainForm.Height := ReadInteger('Height');
CloseKey;
end;
Free;
end;
if ParamCount > 0
then
try
frDoc.LoadFromFile(ParamStr(1));
frDoc.DesignReport;
except
on e: Exception do Application.MessageBox(PChar(langMan.GetRS('errors', 'errorTitle')), PChar(langMan.GetRS('errors', 'loadreport') + ': ' + e.Message));
end;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//========================================================================
procedure TfrmMainForm.docTreeViewClick(Sender: TObject);
(*
var
s: String;
m: tmodalresult;
{$IFDEF UDEBUG}_udebug: Tdebug;{$ENDIF}
*)
begin
(*{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMainForm.docTreeViewClick') else _udebug := nil;{$ENDIF}
frDoc.Clear;
with docTreeView do begin
if Selected.Data = nil then Exit;
if not frDoc.LoadFromFile(getSelRepPath) then Exit;
frDoc.MDIPreview := False;
frDoc.ModalPreview := False;
m := frDoc.DesignReport;
if m = mrOK then exit;
frDoc.ShowReport;
end;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
*)
end;
//========================================================================
procedure TfrmMainForm.docTreeViewDblClick(Sender: TObject);
var
s: AnsiString;
m: tmodalresult;
{$IFDEF UDEBUG}_udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMainForm.docTreeViewDblClick') else _udebug := nil;{$ENDIF}
frDoc.Clear;
with docTreeView do begin
if Selected.Data = nil then begin {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} Exit; end;
s := getSelRepPath;
if not FileExists(s + '.orig') then begin
if LongBool(0) = CopyFile(Pchar(s), PChar(s + '.orig'), False)
then Application.MessageBox(PChar(s + langMan.GetRS('errors', 'saveorig')), PChar(getErrStr));
end;
if FileExists(s + '.bak') then DeleteFile(s + '.bak');
if LongBool(0) = CopyFile(PChar(s), PChar(s + '.bak'), False)
then Application.MessageBox(PChar(s + langMan.GetRS('errors', 'savebak')), PChar(getErrStr));
if not frDoc.LoadFromFile(s) then begin {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} Exit; end;
{frDoc.MDIPreview := False;
frDoc.ModalPreview := False;
}
m := frDoc.DesignReport;
if m = mrOK then begin {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} exit; end;
end;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//========================================================================
procedure TfrmMainForm.cbLangNameChange(Sender: TObject);
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
if (cbLangName.Tag = 0) or (cbLangName.ItemIndex = -1) then Exit;
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMainForm.cbLangNameChange') else _udebug := nil;{$ENDIF}
with TRegistry.Create do begin
RootKey := HKEY_LOCAL_MACHINE;
OpenKey(regRepEdit + 'lang', True);
WriteInteger('lang', cbLangName.ItemIndex);
CloseKey;
Free;
end;
makeLangTree(cbLangName.ItemIndex);
switchLang;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//========================================================================
function TfrmMainForm.getCustomReportsReg: TRegKeyInfo;
var
rki: TRegKeyInfo;
{$IFDEF UDEBUG}_udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMainForm.getCustomReportsReg') else _udebug := nil;{$ENDIF}
with TRegistry.Create do begin
RootKey := HKEY_LOCAL_MACHINE;
OpenKey(regCustomReps, True);
GetKeyInfo(rki);
Result := rki;
CloseKey;
Free;
end;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//========================================================================
procedure TfrmMainForm.miCopyEdit1Click(Sender: TObject);
var
s, rname: String;
//rki: TRegKeyInfo;
i: Cardinal;
{$IFDEF UDEBUG}_udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMainForm.miCopyEdit1Click') else _udebug := nil;{$ENDIF}
with docTreeView do begin
if Selected.HasChildren then begin {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} Exit; end;
s := String(Selected.Data^);
end;
SaveDialog1.InitialDir := RepPath + langFolders[cbLangName.ItemIndex];
if (not saveDialog1.Execute) or (LongBool(0) = CopyFile(PChar(s), PChar(SaveDialog1.FileName), False))
then begin
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
Exit;
end;
s := SaveDialog1.FileName;
repeat
rname := InputBox(langMan.GetRS('common', 'GetRepNameCap'), langMan.GetRS('common', 'GetRepNamePrompt'), s);
until rname <> '';
with TRegistry.Create do begin
RootKey := HKEY_LOCAL_MACHINE;
i := 1;
while OpenKey(regCustomReps + IntToStr(i), False) do begin // search for free name
inc(i); CloseKey;
end;
OpenKey(regCustomReps + IntToStr(i), True);
WriteString('File', s);
WriteString('Name', rname);
CloseKey;
Free;
end;
frDoc.Title := s;
frDoc.LoadFromFile(RepPath + langFolders[cbLangName.ItemIndex] + s);
frDoc.DesignReport;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//========================================================================
procedure TfrmMainForm.FormResize(Sender: TObject);
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMainForm.FormResize') else _udebug := nil;{$ENDIF}
with TRegistry.Create do begin
RootKey := HKEY_LOCAL_MACHINE;
if OpenKey(regRepEdit + 'Form', True) then begin
WriteInteger('Width', frmMainForm.Width);
WriteInteger('Height', frmMainForm.Height);
CloseKey;
end;
Free;
end;
Realign;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//========================================================================
procedure TfrmMainForm.pmDocTreePopup(Sender: TObject);
var
s: String;
i: Integer;
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMainForm.pmDocTreePopup') else _udebug := nil;{$ENDIF}
with docTreeView do begin
selNode := Selected;
if Selected.Data = nil then begin
for i := 0 to pmDocTree.Items.Count-1 do
pmDocTree.Items[i].Enabled := False;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
Exit;
end;
s := getSelRepPath;
for i := 0 to pmDocTree.Items.Count-1 do
pmDocTree.Items[i].Enabled := pmDocTree.Items[i].Tag = 0;
miRestoreOrig.Enabled := FileExists(s + '.orig');
miRevert.Enabled := FileExists(s + '.bak');
end;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//========================================================================
procedure TfrmMainForm.restoreOldrep(from: Integer);
var s,ext: String;
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMainForm.restoreOldrep') else _udebug := nil;{$ENDIF}
if from = 0 then ext := '.bak'
else ext := '.orig';
s := getSelRepPath(True);
if LongBool(0) = CopyFile(PChar(s + ext), PChar(s), False) then begin
Application.MessageBox(PChar(s + langMan.GetRS('errors', 'CopyFile')), PChar(getErrStr));
begin {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} Exit; end;
end;
DeleteFile(s + ext);
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//========================================================================
procedure TfrmMainForm.miRevertClick(Sender: TObject);
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMainForm.miRevertClick') else _udebug := nil;{$ENDIF}
if IDYes = Application.MessageBox(PChar(langMan.GetRS('common', 'wantRevert')), PChar(selNode.Text), MB_YESNO)
then restoreOldRep(0);
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//========================================================================
procedure TfrmMainForm.miRestoreOrigClick(Sender: TObject);
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMainForm.miRestoreOrigClick') else _udebug := nil;{$ENDIF}
if IDYes = Application.MessageBox(PChar(langMan.GetRS('common', 'wantRestOrig')), PChar(selNode.Text), MB_YESNO)
then restoreOldRep(1);
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//========================================================================
procedure TfrmMainForm.butCloseClick(Sender: TObject);
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMainForm.butCloseClick') else _udebug := nil;{$ENDIF}
Application.Terminate;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//========================================================================
procedure TfrmMainForm.butLoadClick(Sender: TObject);
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMainForm.butLoadClick') else _udebug := nil;{$ENDIF}
with OpenDialog1.Create(nil) do
if Execute then begin
try
frDoc.LoadFromFile(FileName);
except
Application.MessageBox(PChar(langMan.GetRS('errors', 'errorTitle')), PChar(langMan.GetRS('errors', 'loadreport')));
Free;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
Exit;
end;
end;
frDoc.DesignReport;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//========================================================================
initialization
{$IFDEF UDEBUG}
Debugging := False;
DEBUG_unit_ID := debugRegisterUnit('MainForm', @Debugging, DEBUG_group_ID);
{$ENDIF}
//========================================================================
finalization
//{$IFDEF UDEBUG}debugUnregisterUnit(DEBUG_unit_ID);{$ENDIF}
end.
|
unit enRememberPassword;
(*-----------------------------------------------------------------------------
Название: enRememberPassword
Автор: mmorozov
Назначение: Форма для отсылки пользователю забытого пароля.
Версия: $Id: enRememberPassword.pas,v 1.24 2013/08/14 14:10:32 kostitsin Exp $
История:
$Log: enRememberPassword.pas,v $
Revision 1.24 2013/08/14 14:10:32 kostitsin
[$377169452] - LoginForm
Revision 1.23 2013/04/24 09:35:55 lulin
- портируем.
Revision 1.22 2009/08/25 14:54:50 lulin
{RequestLink:159367405}.
Revision 1.21 2009/08/25 14:13:02 lulin
{RequestLink:159367405}.
Revision 1.20 2008/07/07 14:26:52 lulin
- подготавливаемся к переименованию.
Revision 1.19 2008/05/15 20:15:13 lulin
- тотальная чистка.
Revision 1.18 2008/05/15 18:16:17 lulin
- вычищаем ненужное.
Revision 1.17 2008/05/13 16:24:13 lulin
- изменения в рамках <K>: 90441490.
Revision 1.16 2007/06/26 14:53:03 mmorozov
- hint fix;
Revision 1.15 2007/04/05 13:42:42 lulin
- избавляемся от лишних преобразований строк.
Revision 1.14 2007/03/28 19:42:53 lulin
- ЭлПаковский редактор переводим на строки с кодировкой.
Revision 1.13 2007/03/13 14:51:24 lulin
- избавляемся от чужой строчки ввода.
Revision 1.12 2007/02/07 12:45:01 lulin
- переводим на строки с кодировкой.
Revision 1.11 2006/12/06 08:00:29 lulin
- везде используем одни и те же метки.
Revision 1.10 2005/03/24 13:39:25 mmorozov
new: использование функций модуля nsVerifyValue;
Revision 1.9 2005/03/21 16:48:10 dinishev
Новый модуль nsLoginUtils
Revision 1.8 2004/11/24 11:06:03 am
change: override функции IsRealInstance для нормальной работы с большими шрифтами
Revision 1.7 2004/11/17 13:45:02 am
change: перевёл форму на vcm'ные рельсы
Revision 1.6 2004/10/25 09:43:54 mmorozov
no message
Revision 1.5 2004/10/25 08:40:06 mmorozov
new: add cvs log;
-----------------------------------------------------------------------------*)
interface
{$Include nsDefine.inc}
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, {enLogin}Login_Form, StdCtrls, ElXPThemedControl, ElBtnCtl, ElPopBtn,
vcmEntityForm, vtLabel, absdrop, treedrop,
nscCombobox, OvcBase, afwControl, afwCustomCommonControl, l3Interfaces,
evEditorWindow, evMultiSelectEditorWindow, evCustomEditor,
evEditorWithOperations, evMemo, evCustomEdit, elCustomEdit,
elCustomButtonEdit, ctButtonEdit, ctAbstractEdit,
PrimRememberPassword_Form, nevControl, evCustomEditorWindowModelPart,
evCustomMemo, EditableBox, FakeBox, afwControlPrim, afwBaseControl,
afwCustomCommonControlPrim
;
type
TnsRememberPasswordForm = class;
TnsSendAction = function(aSender: TnsRememberPasswordForm): TModalResult of object;
TnsRememberPasswordForm = class(TvcmEntityFormRef)
EMailLabel: TvtLabel;
HintLabel: TvtLabel;
btnCancel: TElPopupButton;
btnSend: TElPopupButton;
edEmail: TnscEdit;
procedure EMailEditChange(Sender: TObject);
procedure btnSendClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
f_SendAction: TnsSendAction;
function GetEMail: Il3CString;
procedure DoSend;
protected
procedure CreateParams(var aParams: TCreateParams);
override;
{-}
public
{$IfDef l3HackedVCL}
function IsRealInstance: Boolean;
override;
{-}
{$EndIf l3HackedVCL}
public
property EMail: Il3CString
read GetEMail;
{-}
property SendAction: TnsSendAction
read f_SendAction
write f_SendAction;
{-}
end;//TnsRememberPasswordForm
var
nsRememberPasswordForm: TnsRememberPasswordForm;
implementation
uses
l3String,
nsVerifyValue
;
{$R *.dfm}
function TnsRememberPasswordForm.GetEMail: Il3CString;
begin
result := edEmail.Text;
end;
procedure TnsRememberPasswordForm.EMailEditChange(Sender: TObject);
begin
btnSend.Enabled := nsEmailVerify.Verify(edEmail.Text);
if btnSend.Enabled then
edEmail.Font.Color := clWindowText
else
edEmail.Font.Color := clRed;
end;
procedure TnsRememberPasswordForm.DoSend;
begin
if Assigned(SendAction) then
ModalResult := SendAction(self);
end;
procedure TnsRememberPasswordForm.btnSendClick(Sender: TObject);
begin
DoSend;
end;
procedure TnsRememberPasswordForm.FormCreate(Sender: TObject);
begin
ActiveControl := edEmail;
end;
procedure TnsRememberPasswordForm.CreateParams(var aParams: TCreateParams);
begin
inherited;
with aParams do
begin
ExStyle := ExStyle or WS_EX_APPWINDOW and not(WS_EX_TOOLWINDOW);
WndParent := GetDesktopWindow;
end;
end;
{$IfDef l3HackedVCL}
function TnsRememberPasswordForm.IsRealInstance: Boolean;
begin
Result := True;
end;
{$EndIf l3HackedVCL}
end.
|
unit PrimTasksPanelMenu_Module;
// Модуль: "w:\common\components\gui\Garant\VCM\View\TasksPanel\PrimTasksPanelMenu_Module.pas"
// Стереотип: "VCMFormsPack"
// Элемент модели: "PrimTasksPanelMenu" MUID: (4C8DD8C602D3)
// Имя типа: "TPrimTasksPanelMenuModule"
{$Include w:\common\components\gui\sdoDefine.inc}
interface
{$If NOT Defined(NoVCM)}
uses
l3IntfUses
, vcmPopupMenuPrim
, Classes
, vcmBase
, vcmExternalInterfaces
, vcmModule
;
type
TPrimTasksPanelMenuModule = {abstract} class(TvcmModule)
private
f_PopupMenu: TvcmPopupMenuPrim;
private
procedure opCustomizeExecute(const aParams: IvcmExecuteParamsPrim);
{* Настройка... }
protected
function pm_GetPopupMenu: TvcmPopupMenuPrim;
procedure Cleanup; override;
{* Функция очистки полей объекта. }
procedure Loaded; override;
class procedure GetEntityForms(aList: TvcmClassList); override;
public
constructor Create(AOwner: TComponent); override;
protected
property PopupMenu: TvcmPopupMenuPrim
read pm_GetPopupMenu;
end;//TPrimTasksPanelMenuModule
{$IfEnd} // NOT Defined(NoVCM)
implementation
{$If NOT Defined(NoVCM)}
uses
l3ImplUses
, vcmModuleContractImplementation
, VCMCustomization_Customization_Contracts
{$If NOT Defined(NoVCL)}
, Menus
{$IfEnd} // NOT Defined(NoVCL)
, vcmTaskPanelInterfaces
, vcmInterfaces
, SysUtils
, vcmMenus
{$If NOT Defined(NoVCL)}
, Forms
{$IfEnd} // NOT Defined(NoVCL)
, l3Base
, CustomizeTasksPanel_Form
//#UC START# *4C8DD8C602D3impl_uses*
//#UC END# *4C8DD8C602D3impl_uses*
;
type
TTaskPanelServiceImpl = {final} class(TvcmModuleContractImplementation, ITaskPanelService)
public
procedure CustomizePanel(const aPanel: IvcmCustOps);
{* Настроить панель иструментов }
function TasksPanelPopupMenu: TPopupMenu;
class function Instance: TTaskPanelServiceImpl;
{* Метод получения экземпляра синглетона TTaskPanelServiceImpl }
class function Exists: Boolean;
{* Проверяет создан экземпляр синглетона или нет }
end;//TTaskPanelServiceImpl
var g_TTaskPanelServiceImpl: TTaskPanelServiceImpl = nil;
{* Экземпляр синглетона TTaskPanelServiceImpl }
var g_dmTasksPanelMenu: TPrimTasksPanelMenuModule = nil;
procedure TTaskPanelServiceImplFree;
{* Метод освобождения экземпляра синглетона TTaskPanelServiceImpl }
begin
l3Free(g_TTaskPanelServiceImpl);
end;//TTaskPanelServiceImplFree
procedure TTaskPanelServiceImpl.CustomizePanel(const aPanel: IvcmCustOps);
{* Настроить панель иструментов }
var
__WasEnter : Boolean;
//#UC START# *4C8E59B80380_4C8DD8C602D3_var*
//#UC END# *4C8E59B80380_4C8DD8C602D3_var*
begin
__WasEnter := vcmEnterFactory;
try
//#UC START# *4C8E59B80380_4C8DD8C602D3_impl*
(TCustomizeTasksPanelForm.Make(aPanel, vcmMakeParams, vcm_ztAny).
VCLWinControl As TCustomForm).ShowModal;
//#UC END# *4C8E59B80380_4C8DD8C602D3_impl*
finally
if __WasEnter then
vcmLeaveFactory;
end;//try..finally
end;//TTaskPanelServiceImpl.CustomizePanel
function TTaskPanelServiceImpl.TasksPanelPopupMenu: TPopupMenu;
var
__WasEnter : Boolean;
//#UC START# *4C8F777E02AD_4C8DD8C602D3_var*
//#UC END# *4C8F777E02AD_4C8DD8C602D3_var*
begin
__WasEnter := vcmEnterFactory;
try
//#UC START# *4C8F777E02AD_4C8DD8C602D3_impl*
Result := g_dmTasksPanelMenu.PopupMenu;
//#UC END# *4C8F777E02AD_4C8DD8C602D3_impl*
finally
if __WasEnter then
vcmLeaveFactory;
end;//try..finally
end;//TTaskPanelServiceImpl.TasksPanelPopupMenu
class function TTaskPanelServiceImpl.Instance: TTaskPanelServiceImpl;
{* Метод получения экземпляра синглетона TTaskPanelServiceImpl }
begin
if (g_TTaskPanelServiceImpl = nil) then
begin
l3System.AddExitProc(TTaskPanelServiceImplFree);
g_TTaskPanelServiceImpl := Create;
end;
Result := g_TTaskPanelServiceImpl;
end;//TTaskPanelServiceImpl.Instance
class function TTaskPanelServiceImpl.Exists: Boolean;
{* Проверяет создан экземпляр синглетона или нет }
begin
Result := g_TTaskPanelServiceImpl <> nil;
end;//TTaskPanelServiceImpl.Exists
function TPrimTasksPanelMenuModule.pm_GetPopupMenu: TvcmPopupMenuPrim;
//#UC START# *4C8F78BC0331_4C8DD8C602D3get_var*
//#UC END# *4C8F78BC0331_4C8DD8C602D3get_var*
begin
//#UC START# *4C8F78BC0331_4C8DD8C602D3get_impl*
if not Assigned(f_PopupMenu) then
begin
f_PopupMenu := TvcmPopupMenuPrim.Create(Self);
// Это нужно чтобы был найден группирующий элемент
f_PopupMenu.Items.Caption := vcmStr(ModuleDef.ModuleDef.Caption);
// Контекстные операции модуля
vcmMakeModuleMenu(f_PopupMenu.Items,
ModuleDef.ModuleDef,
[{vcm_ooShowInContextMenu}],
False);
end;//if not Assigned(f_PopupMenu) then
Result := f_PopupMenu;
//#UC END# *4C8F78BC0331_4C8DD8C602D3get_impl*
end;//TPrimTasksPanelMenuModule.pm_GetPopupMenu
procedure TPrimTasksPanelMenuModule.opCustomizeExecute(const aParams: IvcmExecuteParamsPrim);
{* Настройка... }
//#UC START# *4C8DD91901C8_4C8DD8C602D3exec_var*
var
l_MainForm: IvcmMainForm;
//#UC END# *4C8DD91901C8_4C8DD8C602D3exec_var*
begin
//#UC START# *4C8DD91901C8_4C8DD8C602D3exec_impl*
if Supports((aParams As IvcmExecuteParams).Container.NativeMainForm, IvcmMainForm, l_MainForm) then
TTaskPanelService.Instance.CustomizePanel(l_MainForm.TasksPanel)
else
Assert(False);
//#UC END# *4C8DD91901C8_4C8DD8C602D3exec_impl*
end;//TPrimTasksPanelMenuModule.opCustomizeExecute
procedure TPrimTasksPanelMenuModule.Cleanup;
{* Функция очистки полей объекта. }
//#UC START# *479731C50290_4C8DD8C602D3_var*
//#UC END# *479731C50290_4C8DD8C602D3_var*
begin
//#UC START# *479731C50290_4C8DD8C602D3_impl*
g_dmTasksPanelMenu := nil;
inherited;
//#UC END# *479731C50290_4C8DD8C602D3_impl*
end;//TPrimTasksPanelMenuModule.Cleanup
constructor TPrimTasksPanelMenuModule.Create(AOwner: TComponent);
//#UC START# *47D1602000C6_4C8DD8C602D3_var*
//#UC END# *47D1602000C6_4C8DD8C602D3_var*
begin
//#UC START# *47D1602000C6_4C8DD8C602D3_impl*
inherited;
//Name := 'vcm_dmTasksPanelMenu';
Assert(not Assigned(g_dmTasksPanelMenu));
g_dmTasksPanelMenu := Self;
//#UC END# *47D1602000C6_4C8DD8C602D3_impl*
end;//TPrimTasksPanelMenuModule.Create
procedure TPrimTasksPanelMenuModule.Loaded;
begin
inherited;
PublishOp('opCustomize', opCustomizeExecute, nil);
ShowInToolbar('opCustomize', False);
end;//TPrimTasksPanelMenuModule.Loaded
class procedure TPrimTasksPanelMenuModule.GetEntityForms(aList: TvcmClassList);
begin
inherited;
aList.Add(TCustomizeTasksPanelForm);
end;//TPrimTasksPanelMenuModule.GetEntityForms
initialization
TTaskPanelService.Instance.Alien := TTaskPanelServiceImpl.Instance;
{* Регистрация TTaskPanelServiceImpl }
{$IfEnd} // NOT Defined(NoVCM)
end.
|
unit uWorkSpace;
interface
uses
uWorkSpaceIntf, uEditorBase, Classes, Graphics, StdCtrls, Dialogs, uEditorIntf;
type
TWorkSpace = class(TInterfacedObject, IWorkSpaceIntf)
private
// 该类作为编辑器的代理。
FEditor: TEditorBase;
FIndex: Integer;
protected
// 获取索引
function GetIndex: Integer;
// 设置激活
procedure SetActive;
procedure OnSave(); virtual; abstract;
public
constructor Create(ParentControl: TComponent; Index: Integer; FileName: string);
function Close(): Integer;
function GetFileName: string;
function GetSaved: Boolean;
function Save: Boolean;
function SaveAs: Boolean;
function GetSelectText: String;
function CanUndo: Boolean;
procedure Undo;
function CanRedo: Boolean;
procedure Redo;
function CanCopy: Boolean;
procedure Copy;
function CanCut: Boolean;
procedure Cut;
function CanPaster: Boolean;
procedure Paster;
function CanDeleteSelection: Boolean;
procedure DelectSelection;
procedure SetFont(Font: TFont);
function FindNext(Text: String; Option: TFindOptions): Boolean;
function Replace(FindText, ReplaceText: String; Option: TFindOptions): Integer;
function GetWordCount: TWordCount;
function GetWordWarp: Boolean; // 是否分行
procedure SetWordWarp(bWordWarp: Boolean);
procedure SelectAll;
end;
implementation
uses
uGlobalObject;
{ TWorkSpace }
function TWorkSpace.CanCopy: Boolean;
begin
Result := FEditor.CanCopy;
end;
function TWorkSpace.CanCut: Boolean;
begin
Result := FEditor.CanCut;
end;
function TWorkSpace.CanDeleteSelection: Boolean;
begin
Result := FEditor.CanDeleteSelection;
end;
function TWorkSpace.CanPaster: Boolean;
begin
Result := FEditor.CanPaster;
end;
function TWorkSpace.CanRedo: Boolean;
begin
Result := FEditor.CanRedo;
end;
function TWorkSpace.CanUndo: Boolean;
begin
Result := FEditor.CanUndo;
end;
function TWorkSpace.Close: Integer;
begin
// 判断工作区是否被修改
if FEditor.GetSaved then
FEditor.Save;
end;
procedure TWorkSpace.Copy;
begin
FEditor.Copy;
end;
constructor TWorkSpace.Create(ParentControl: TComponent; Index: Integer;
FileName: string);
begin
{由于 FEditor 还没有组件,所以没有办法使用该类来创建FEditor对象
为了可以创建不同的 编辑器组件 对象,需要使用一个 构建器 类}
FEditorCtor.CreateAnEditor(FEditor, ParentControl);
if Assigned(FEditor) then
begin
FEditor.LoadFormFile(FileName);
FIndex := Index;
end;
end;
procedure TWorkSpace.Cut;
begin
FEditor.Cut;
end;
procedure TWorkSpace.DelectSelection;
begin
FEditor.DelectSelection;
end;
function TWorkSpace.FindNext(Text: String; Option: TFindOptions): Boolean;
begin
FEditor.FindNext(Text, Option);
end;
function TWorkSpace.GetFileName: string;
begin
Result := FEditor.GetFileName;
end;
function TWorkSpace.GetIndex: Integer;
begin
Result := FIndex;
end;
function TWorkSpace.GetSaved: Boolean;
begin
Result := FEditor.GetSaved;
end;
function TWorkSpace.GetSelectText: String;
begin
Result := FEditor.GetSelectText;
end;
function TWorkSpace.GetWordCount: TWordCount;
begin
Result := FEditor.GetWordCount;
end;
function TWorkSpace.GetWordWarp: Boolean;
begin
Result := FEditor.GetWordWarp;
end;
procedure TWorkSpace.Paster;
begin
FEditor.Paster;
end;
procedure TWorkSpace.Redo;
begin
FEditor.Redo;
end;
function TWorkSpace.Replace(FindText, ReplaceText: String;
Option: TFindOptions): Integer;
begin
FEditor.Replace(FindText, ReplaceText, Option);
end;
function TWorkSpace.Save: Boolean;
begin
FEditor.Save;
OnSave();
end;
function TWorkSpace.SaveAs: Boolean;
begin
FEditor.Save;
OnSave();
end;
procedure TWorkSpace.SelectAll;
begin
FEditor.SelectAll;
end;
procedure TWorkSpace.SetActive;
begin
end;
procedure TWorkSpace.SetFont(Font: TFont);
begin
FEditor.SetFont(Font);
end;
procedure TWorkSpace.SetWordWarp(bWordWarp: Boolean);
begin
FEditor.SetWordWarp(bWordWarp);
end;
procedure TWorkSpace.Undo;
begin
FEditor.Undo;
end;
end.
|
unit TestUnmarshalAvoidanceZoneUnit;
interface
uses
TestFramework, SysUtils,
TestBaseJsonUnmarshalUnit,
System.Generics.Collections,
IAvoidanceZoneProviderUnit;
type
TTestUnmarshalAvoidanceZone = class(TTestBaseJsonUnmarshal)
private
procedure CheckEquals(Etalon: IAvoidanceZoneProvider; TestName: String); overload;
published
procedure RealAvoidanceZone();
end;
implementation
uses
Classes, System.JSON,
AvoidanceZoneUnit, MarshalUnMarshalUnit,
RealAvoidanceZoneProviderUnit;
procedure TTestUnmarshalAvoidanceZone.CheckEquals(
Etalon: IAvoidanceZoneProvider; TestName: String);
var
ActualList: TStringList;
Actual: TAvoidanceZoneList;
JsonFilename: String;
AvoidanceZones: TAvoidanceZoneList;
JsonValue: TJSONValue;
SortedAvoidanceZone1, SortedAvoidanceZone2: TAvoidanceZoneArray;
i: integer;
begin
JsonFilename := EtalonFilename(TestName);
ActualList := TStringList.Create;
try
ActualList.LoadFromFile(JsonFilename);
JsonValue := TJSONObject.ParseJSONValue(ActualList.Text);
try
AvoidanceZones := Etalon.AvoidanceZones;
Actual := TMarshalUnMarshal.FromJson(
AvoidanceZones.ClassType, JsonValue) as TAvoidanceZoneList;
try
CheckEquals(AvoidanceZones.Count, Actual.Count);
SortedAvoidanceZone1 := AvoidanceZoneUnit.SortAvoidanceZones(AvoidanceZones.ToArray);
SortedAvoidanceZone2 := AvoidanceZoneUnit.SortAvoidanceZones(Actual.ToArray);
for i := 0 to Length(SortedAvoidanceZone1) - 1 do
CheckTrue(SortedAvoidanceZone1[i].Equals(SortedAvoidanceZone2[i]));
finally
FreeAndNil(Actual);
FreeAndNil(AvoidanceZones);
end;
finally
FreeAndNil(JsonValue);
end;
finally
FreeAndNil(ActualList);
end;
Etalon := nil;
end;
procedure TTestUnmarshalAvoidanceZone.RealAvoidanceZone;
begin
CheckEquals(
TRealAvoidanceZoneProvider.Create,
'AvoidanceZoneFromJson');
end;
initialization
// Register any test cases with the test runner
RegisterTest('JSON\Unmarshal\', TTestUnmarshalAvoidanceZone.Suite);
end.
|
// 为了兼容Lazarus与Delphi对于资源窗口数据中图片读取的处理
// 比如在Delphi中TPngImage是没有Size标识的,但Lazarus中一定有
// 于是只能进行修改,统一都有图片Size标识,但在Delphi读取时经过判断后跳过相关的
unit uImages;
interface
uses
System.Classes,
System.SysUtils,
Vcl.Graphics,
Vcl.Imaging.pngimage,
Vcl.Imaging.GIFImg,
Vcl.Imaging.GIFConsts;
type
TPngImage = class(Vcl.Imaging.pngimage.TPngImage)
protected
procedure ReadData(Stream: TStream); override;
procedure WriteData(Stream: TStream); override;
end;
TGIFImage = class(Vcl.Imaging.GIFImg.TGIFImage)
protected
procedure ReadData(Stream: TStream); override;
procedure WriteData(Stream: TStream); override;
end;
// 与lazarus保持一致
TPortableNetworkGraphic = class(TPngImage)
end;
implementation
{ TPngImage }
procedure TPngImage.ReadData(Stream: TStream);
const
PngHeader: Array[0..7] of AnsiChar = (#137, #80, #78, #71, #13, #10, #26, #10);
var
LHeader: array[0..7] of AnsiChar;
begin
Stream.Read(LHeader[0], 8);
if CompareMem(@PngHeader[0], @LHeader[0], 8) then
Stream.Position := Stream.Position - 8
else
Stream.Position := Stream.Position - 4;
inherited;
end;
procedure TPngImage.WriteData(Stream: TStream);
var
Size: Longint;
LMem: TMemoryStream;
begin
LMem := TMemoryStream.Create;
try
SaveToStream(LMem);
Size := LMem.Size;
Stream.Write(Size, Sizeof(Size));
if Size > 0 then
Stream.Write(LMem.Memory^, Size);
finally
LMem.Free;
end;
end;
{ TGIFImage }
procedure TGIFImage.ReadData(Stream: TStream);
const
GifHeader: array[0..2] of Byte = ($47, $49, $46);
var
LHeader: array[0..2] of Byte;
begin
Stream.Read(LHeader[0], 3);
if CompareMem(@GifHeader[0], @LHeader[0], 3) then
Stream.Position := Stream.Position - 3
else
Stream.Position := Stream.Position + 1;
inherited;
end;
procedure TGIFImage.WriteData(Stream: TStream);
var
Size: Longint;
LMem: TMemoryStream;
begin
LMem := TMemoryStream.Create;
try
SaveToStream(LMem);
Size := LMem.Size;
Stream.Write(Size, Sizeof(Size));
if Size > 0 then
Stream.Write(LMem.Memory^, Size);
finally
LMem.Free;
end;
end;
initialization
TPicture.UnregisterGraphicClass(Vcl.Imaging.pngimage.TPngImage);
TPicture.UnregisterGraphicClass(Vcl.Imaging.GIFImg.TGIFImage);
// 重新注册
TPicture.RegisterFileFormat('PNG', 'Portable Network Graphics', TPortableNetworkGraphic);
TPicture.RegisterFileFormat('PNG', 'Portable Network Graphics', TPngImage);
TPicture.RegisterFileFormat('GIF', sGIFImageFile, TGIFImage);
finalization
end.
|
unit FastMM4DataCollector;
{$I FastMM4Options.inc}
interface
type
TStaticCollector = record
strict private const
CDefaultPromoteGen1_sec = 1; // promote every second
CDefaultPromoteGen1Count = 1; // promote allocations with Count > 1
CGeneration1Size = 1024;
CGeneration2Size = 256;
CCollectedDataSize = CGeneration2Size;
CMaxPointers = 11; // same as in FastMM4
public type
TPointers = record
Pointers: array [1..CMaxPointers] of pointer;
Count : integer;
class operator Equal(const a, b: TPointers): boolean;
end;
TDataInfo = record
Data : TPointers;
Count: integer;
end;
TCollectedData = array [1..CCollectedDataSize] of TDataInfo;
TGenerationOverflowCount = record
Generation1: integer;
Generation2: integer;
end;
strict private type
PDataInfo = ^TDataInfo;
TGenerationPlaceholder = array [1..1] of TDataInfo;
PGenerationPlaceholder = ^TGenerationPlaceholder;
TGenerationInfo = record
Data : PGenerationPlaceholder;
Size : integer;
Last : integer;
NextGeneration : integer;
PromoteEvery_sec: integer;
PromoteCountOver: integer;
OverflowCount : integer;
LastCheck_ms : int64;
end;
var
FGeneration1 : array [1..CGeneration1Size] of TDataInfo;
FGeneration2 : array [1..CGeneration2Size] of TDataInfo;
FGenerationInfo: array [0..2] of TGenerationInfo; //gen0 is used for merging
FLocked : boolean;
FPadding : array [1..3] of byte;
function GetGen1_PromoteCountOver: integer;
function GetGen1_PromoteEvery_sec: integer;
function GetOverflowCount: TGenerationOverflowCount;
procedure Lock;
function Now_ms: int64; inline;
procedure SetGen1_PromoteCountOver(const value: integer);
procedure SetGen1_PromoteEvery_sec(const value: integer);
private
procedure AddToGeneration(generation: integer; const aData: TPointers;
count: integer = 1);
procedure CheckPromoteGeneration(generation: integer); inline;
function FindInGeneration(generation: integer; const aData: TPointers): integer; inline;
function FindInsertionPoint(generation, count: integer): integer; inline;
procedure FlushAllGenerations;
function InsertIntoGeneration(generation: integer; const dataInfo: TDataInfo): boolean;
procedure PromoteGeneration(oldGen, newGen: integer);
procedure ResortGeneration(generation, idxData: integer);
public
procedure Initialize;
procedure Add(const pointers: pointer; count: integer);
procedure GetData(var data: TCollectedData; var count: integer);
procedure Merge(var mergedData: TCollectedData; var mergedCount: integer;
const newData: TCollectedData; newCount: integer);
property Gen1_PromoteCountOver: integer read GetGen1_PromoteCountOver
write SetGen1_PromoteCountOver;
property OverflowCount: TGenerationOverflowCount read GetOverflowCount;
property Gen1_PromoteEvery_sec: integer read GetGen1_PromoteEvery_sec write
SetGen1_PromoteEvery_sec;
end;
PStaticCollector = ^TStaticCollector;
implementation
uses
Winapi.Windows; //used in Now_ms
{$RANGECHECKS OFF}
// Copied from FastMM4.pas
function LockCmpxchg(CompareVal, NewVal: Byte; AAddress: PByte): Byte;
asm
{$if SizeOf(Pointer) = 4}
{On entry:
al = CompareVal,
dl = NewVal,
ecx = AAddress}
{$ifndef LINUX}
lock cmpxchg [ecx], dl
{$else}
{Workaround for Kylix compiler bug}
db $F0, $0F, $B0, $11
{$endif}
{$else}
{On entry:
cl = CompareVal
dl = NewVal
r8 = AAddress}
.noframe
mov rax, rcx
lock cmpxchg [r8], dl
{$ifend}
end;
{ TStaticCollector.TPointers }
class operator TStaticCollector.TPointers.Equal(const a, b: TPointers): boolean;
var
i: integer;
begin
Result := a.Count = b.Count;
if Result then
for i := 1 to a.Count do
if a.Pointers[i] <> b.Pointers[i] then
Exit(false);
end;
{ TStaticCollector }
procedure TStaticCollector.Add(const pointers: pointer; count: integer);
var
ptrData: TPointers;
begin
Lock;
ptrData.Count := CMaxPointers;
if count < CMaxPointers then
ptrData.Count := count;
Move(pointers^, ptrData.Pointers[1], ptrData.Count * SizeOf(pointer));
AddToGeneration(1, ptrData);
FLocked := false;
end;
procedure TStaticCollector.AddToGeneration(generation: integer; const aData: TPointers;
count: integer = 1);
var
dataInfo: TDataInfo;
idxData : integer;
begin
CheckPromoteGeneration(generation);
with FGenerationInfo[generation] do begin
idxData := FindInGeneration(generation, aData);
if idxData >= 1 then begin
Data^[idxData].Count := Data^[idxData].Count + count;
ResortGeneration(generation, idxData);
end
else begin
dataInfo.Data := aData;
dataInfo.Count := count;
InsertIntoGeneration(generation, dataInfo);
end;
end;
end; { TStaticCollector.AddToGeneration }
procedure TStaticCollector.CheckPromoteGeneration(generation: integer);
begin
with FGenerationInfo[generation] do begin
if NextGeneration > 0 then begin
if LastCheck_ms = 0 then
LastCheck_ms := Now_ms
else if ((Now_ms - LastCheck_ms) div 1000) >= PromoteEvery_sec then begin
PromoteGeneration(generation, NextGeneration);
LastCheck_ms := Now_ms;
end;
end;
end;
end;
function TStaticCollector.FindInGeneration(generation: integer; const aData: TPointers):
integer;
begin
with FGenerationInfo[generation] do begin
for Result := 1 to Last do
if Data^[Result].Data = aData then
Exit;
end;
Result := 0;
end;
function TStaticCollector.FindInsertionPoint(generation, count: integer): integer;
var
insert: integer;
begin
with FGenerationInfo[generation] do begin
for insert := Last downto 1 do begin
if Data^[insert].Count > count then
Exit(insert+1);
end;
Result := 1;
end;
end;
procedure TStaticCollector.FlushAllGenerations;
var
generation: integer;
nextGen : integer;
begin
generation := 1;
while generation <> 0 do begin
nextGen := FGenerationInfo[generation].NextGeneration;
if nextGen > 0 then
PromoteGeneration(generation, nextGen);
generation := nextGen;
end;
end;
procedure TStaticCollector.GetData(var data: TCollectedData; var count: integer);
begin
Lock;
FlushAllGenerations;
Assert(Length(data) = Length(FGeneration2));
count := FGenerationInfo[2].Last;
Move(FGeneration2[1], data[1], count * SizeOf(data[1]));
FLocked := false;
end;
function TStaticCollector.GetGen1_PromoteCountOver: integer;
begin
Result := FGenerationInfo[1].PromoteCountOver;
end;
function TStaticCollector.GetGen1_PromoteEvery_sec: integer;
begin
Result := FGenerationInfo[1].PromoteEvery_sec;
end;
function TStaticCollector.GetOverflowCount: TGenerationOverflowCount;
begin
Result.Generation1 := FGenerationInfo[1].OverflowCount;
Result.Generation2 := FGenerationInfo[2].OverflowCount;
end;
procedure TStaticCollector.Initialize;
begin
Assert(SizeOf(TStaticCollector) mod SizeOf(pointer) = 0);
with FGenerationInfo[1] do begin
Data := @FGeneration1;
Size := CGeneration1Size;
Last := 0;
NextGeneration := 2;
PromoteEvery_sec := CDefaultPromoteGen1_sec;
PromoteCountOver := CDefaultPromoteGen1Count;
LastCheck_ms := 0;
end;
with FGenerationInfo[2] do begin
Data := @FGeneration2;
Size := CGeneration2Size;
NextGeneration := 0;
end;
end;
function TStaticCollector.InsertIntoGeneration(generation: integer; const dataInfo:
TDataInfo): boolean;
var
idx: integer;
begin
// We already know that this element does not exist in the generation.
Result := true;
with FGenerationInfo[generation] do begin
idx := FindInsertionPoint(generation, dataInfo.Count);
if idx > Last then begin
if Last = Size then begin
Inc(OverflowCount);
Result := false;
end
else begin
Inc(Last);
Data^[Last] := dataInfo;
end;
end
else begin
if Last < Size then begin
Move(Data^[idx], Data^[idx+1], (Last-idx+1) * SizeOf(Data^[idx]));
Inc(Last);
end
else begin
if Last > idx then
Move(Data^[idx], Data^[idx+1], (Last-idx) * SizeOf(Data^[idx]));
Inc(OverflowCount);
end;
Data^[idx] := dataInfo;
end;
end;
end;
procedure TStaticCollector.Lock;
begin
{$ifndef AssumeMultiThreaded}
if IsMultiThread then
{$endif}
begin
while LockCmpxchg(0, 1, @FLocked) <> 0 do
begin
{$ifdef NeverSleepOnThreadContention}
{$ifdef UseSwitchToThread}
SwitchToThread;
{$endif}
{$else}
Sleep(0);
if LockCmpxchg(0, 1, @FLocked) = 0 then
Break;
Sleep(1);
{$endif}
end;
end;
end;
procedure TStaticCollector.Merge(var mergedData: TCollectedData;
var mergedCount: integer; const newData: TCollectedData; newCount: integer);
var
iNew: integer;
begin
// Merges two sorted arrays.
FGenerationInfo[0].Data := @mergedData;
FGenerationInfo[0].Last := mergedCount;
FGenerationInfo[0].Size := CCollectedDataSize;
FGenerationInfo[0].NextGeneration := 0;
for iNew := 1 to newCount do
AddToGeneration(0, newData[iNew].Data, newData[iNew].Count);
mergedCount := FGenerationInfo[0].Last;
end;
function TStaticCollector.Now_ms: int64;
var
st: TSystemTime;
begin
// We cannot use SysUtils as that gets memory allocator called before FastMM is initialized.
GetSystemTime(st);
SystemTimeToFileTime(st, TFileTime(Result));
Result := Result div 10000;
end;
procedure TStaticCollector.PromoteGeneration(oldGen, newGen: integer);
var
canInsert : boolean;
idxNew : integer;
idxOld : integer;
newGenData: PGenerationPlaceholder;
pOldData : PDataInfo;
begin
canInsert := true;
newGenData := FGenerationInfo[newGen].Data;
with FGenerationInfo[oldGen] do begin
for idxOld := 1 to Last do begin
pOldData := @Data^[idxOld];
if pOldData^.Count <= PromoteCountOver then
break; //for idxOld
idxNew := FindInGeneration(newGen, pOldData^.Data);
if idxNew > 0 then begin
newGenData^[idxNew].Count := newGenData^[idxNew].Count + pOldData^.Count;
ResortGeneration(newGen, idxNew);
end
else if canInsert then
canInsert := InsertIntoGeneration(newGen, pOldData^)
else with FGenerationInfo[newGen] do
Inc(OverflowCount);
end; //for idxOld
Last := 0;
end;
end;
procedure TStaticCollector.ResortGeneration(generation, idxData: integer);
var
dataInfo: TDataInfo;
idx : integer;
begin
// Data^[idxData].Count was just updated, resort the generation.
with FGenerationInfo[generation] do begin
idx := FindInsertionPoint(generation, Data^[idxData].Count);
if idx < idxData then begin
dataInfo := Data^[idxData];
Move(Data^[idx], Data^[idx+1], (idxData-idx) * SizeOf(Data^[idx]));
Data^[idx] := dataInfo;
end;
end;
end;
procedure TStaticCollector.SetGen1_PromoteCountOver(const value: integer);
begin
FGenerationInfo[1].PromoteCountOver := value;
end;
procedure TStaticCollector.SetGen1_PromoteEvery_sec(const value: integer);
begin
FGenerationInfo[1].PromoteEvery_sec := value;
end;
end.
|
unit Sorting;
{=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=]
Copyright (c) 2013, Jarl K. <Slacky> Holta || http://github.com/WarPie
All rights reserved.
For more info see: Copyright.txt
[=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=}
{$mode objfpc}{$H+}
{$inline on}
(*
Modified version of Quicksort to get better best-case performance.
> The closer the array is to beeing already sorted, the faster it gets.
> Does not matter much if the array is reversed or not.
> Fallback to ShellSort to avoid a bad worst-case scenario.
How does it work?
1. Based on a sligtly modified Quicksort.
2. Recursively partitions the array at the middle (See step 4)...
3. If the partition Left to Right is less then a cirtain criteria InsertionSort is used.
> If not insertion:
4. Pivot is selected as a Median of 5: Left - MidLeft - Mid - MidRight - Right.
5. If all items from "Left up to pivot" and "Right down to pivot" is (close to) sorted
then we run InsertionSort on the "partition", and exit. If not then we continue
doing a regular quicksort. This check is then continued ~6 times in each partioning.
6. If the recursion depth goes bellow a given limit then we fall back to ShellSort to avoid
worst-case scenario in Quicksort: O(n^2).
-------
My testes show that it can be ~30x faster then QuickSort..
>> Much more whenever quicksort goes O(n^2) - Rare/Depending on pivot selection.
*)
interface
uses
CoreTypes, SysUtils;
procedure InsSortTIA(var Arr:TIntArray; Left, Right:Integer); Inline;
procedure InsSortTEA(var Arr:TExtArray; Left, Right:Integer); Inline;
procedure InsSortTDA(var Arr:TDoubleArray; Left, Right:Integer); Inline;
procedure InsSortTFA(var Arr:TFloatArray; Left, Right:Integer); Inline;
procedure InsSortTPA(var Arr:TPointArray; Weight:TIntArray; Left, Right:Integer); Inline;
procedure ShellSortTIA(var Arr: TIntArray);
procedure ShellSortTEA(var Arr: TExtArray);
procedure ShellSortTDA(var Arr: TDoubleArray);
procedure ShellSortTFA(var Arr: TFloatArray);
procedure ShellSortTPA(var Arr: TPointArray; Weight:TIntArray);
procedure SortTBA(var Arr: CoreTypes.TByteArray);
procedure SortTIA(var Arr: TIntArray);
procedure SortTEA(var Arr: TExtArray);
procedure SortTDA(var Arr: TDoubleArray);
procedure SortTFA(var Arr: TFloatArray);
procedure SortTPA(var Arr: TPointArray);
procedure SortTPAFrom(var Arr: TPointArray; const From:TPoint);
procedure SortTPAbyRow(var Arr: TPointArray);
procedure SortTPAbyColumn(var Arr: TPointArray);
procedure SortTPAByY(var Arr: TPointArray);
procedure SortTPAByX(var Arr: TPointArray);
procedure SortTSA(var Arr: TStringArray; CaseInsesitive:Boolean=False);
procedure SortTSANatural(var Arr: TStringArray);
procedure SortATPAByLength(var Arr:T2DPointArray);
procedure SortATPAByMean(var Arr:T2DPointArray);
procedure SortATPAByFirst(var Arr:T2DPointArray);
procedure SortATPAByIndex(var Arr:T2DPointArray; index:Int32);
procedure SortATBAByLength(var Arr:T2DByteArray);
procedure SortATBAByMean(var Arr:T2DByteArray);
procedure SortATBAByFirst(var Arr:T2DByteArray);
procedure SortATBAByIndex(var Arr:T2DByteArray; index:Int32);
procedure SortATIAByLength(var Arr:T2DIntArray);
procedure SortATIAByMean(var Arr:T2DIntArray);
procedure SortATIAByFirst(var Arr:T2DIntArray);
procedure SortATIAByIndex(var Arr:T2DIntArray; index:Int32);
procedure SortATEAByLength(var Arr:T2DExtArray);
procedure SortATEAByMean(var Arr:T2DExtArray);
procedure SortATEAByFirst(var Arr:T2DExtArray);
procedure SortATEAByIndex(var Arr:T2DExtArray; index:Int32);
//-----------------------------------------------------------------------||
implementation
uses
PointTools, Numeric, CoreMisc, Math;
{$I Sorting/SortingBase.pas}
{$I Sorting/TPASort.pas}
{$I Sorting/TBASort.pas}
{$I Sorting/TIASort.pas}
{$I Sorting/TEASort.pas}
{$I Sorting/TFASort.pas}
{$I Sorting/TDASort.pas}
{$I Sorting/TSASort.pas}
{$I Sorting/ATPASort.pas}
{$I Sorting/ATBASort.pas}
{$I Sorting/ATIASort.pas}
{$I Sorting/ATEASort.pas}
end.
|
{$I ok_sklad.inc}
unit WBMovSetPT;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, ExtCtrls, StdCtrls, cxButtons,
ssFormStorage, ActnList, ssBaseSkinForm, ssBevel, ImgList, ssSpeedButton,
ssPanel, ssGradientPanel, ssBaseDlg, xButton,
cxControls, cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxDropDownEdit,
ssDBLookupCombo, DB, DBClient, ssClientDataSet, ClientData, ssBaseIntfDlg,ssBaseConst;
type
TfrmWBMovSetPT = class(TfrmBaseIntfDlg)
FormStorage: TssFormStorage;
panMain: TPanel;
btnLock: TssSpeedButton;
btnHelp: TssSpeedButton;
aLock: TAction;
aHelp: TAction;
btnSendErrMessage: TssSpeedButton;
aSendErrMessage: TAction;
bvlBox: TssBevel;
cdsPriceTypes: TssClientDataSet;
dsPriceTypes: TDataSource;
lPriceType: TssBevel;
lcbPriceTypes: TssDBLookupCombo;
aAddPT: TAction;
btnAddPT: TssSpeedButton;
procedure ActionListUpdate(Action: TBasicAction; var Handled: Boolean);
procedure aLockExecute(Sender: TObject);
procedure aHelpExecute(Sender: TObject);
procedure aAddPTExecute(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure aSendErrMessageExecute(Sender: TObject);
private
FOnDate: TDateTime;
procedure WMRefresh(var M: TMessage); message WM_REFRESH;
protected
FParentName: string;
FID: integer;
FSubID: integer;
FGrpID: integer;
procedure SetID(const Value: integer); virtual; abstract;
procedure SetParentName(const Value: string); virtual;
procedure SetOnDate(const Value: TDateTime); virtual;
procedure SetSubID(const Value: integer); virtual;
procedure DoCreate; override;
procedure SetGrpID(const Value: integer); virtual;
public
MainHandle: HWND;
SourceID: integer;
IsPattern: Boolean;
property GrpID: integer read FGrpID write SetGrpID;
property ParentNameEx: string read FParentName write SetParentName;
property ID: integer read FID write SetID;
property SubID: integer read FSubID write SetSubID;
property OnDate: TDateTime read FOnDate write SetOnDate;
procedure SetCaptions; virtual;
procedure DoHelp; virtual;
procedure DoCustom(AParam: Integer); virtual;
end;
// TBaseDlgClass = class of TBaseDlg;
var
frmWBMovSetPT: TfrmWBMovSetPT;
implementation
uses prConst, prFun, Menus,prTypes, ssFun, Udebug;
var DEBUG_unit_ID: Integer; Debugging: Boolean; DEBUG_group_ID: String = '';
{$R *.dfm}
{ TBaseDlg }
procedure TfrmWBMovSetPT.WMRefresh(var M: TMessage);
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmWBMovSetPT.WMRefresh') else _udebug := nil;{$ENDIF}
case TRefType(M.LParam) of
rtPriceTypes: begin
DSRefresh(cdsPriceTypes, 'ptypeid', M.WParam);
lcbPriceTypes.KeyValue := M.WParam;
end;//rtPriceTypes
end;//case
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
procedure TfrmWBMovSetPT.SetOnDate(const Value: TDateTime);
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmWBMovSetPT.SetOnDate') else _udebug := nil;{$ENDIF}
FOnDate := Value;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
procedure TfrmWBMovSetPT.SetSubID(const Value: integer);
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmWBMovSetPT.SetSubID') else _udebug := nil;{$ENDIF}
FSubID := Value;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
procedure TfrmWBMovSetPT.SetParentName(const Value: string);
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmWBMovSetPT.SetParentName') else _udebug := nil;{$ENDIF}
FParentName := Value;
SetCaptions;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
procedure TfrmWBMovSetPT.SetCaptions;
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmWBMovSetPT.SetCaptions') else _udebug := nil;{$ENDIF}
inherited;
btnLock.Hint := LangMan.GetRS('Common', 'Lock');
btnHelp.Hint := LangMan.GetRS('Common', 'Help');
aOK.Caption := LangMan.GetRS('Common', 'OK');
aCancel.Caption := LangMan.GetRS('Common', 'Cancel');
aApply.Caption := LangMan.GetRS('Common', 'Apply');
aAddPT.Hint:=LangMan.GetRS('fmWaybill','RefPT');
lPriceType.Caption:=LangMan.GetRS('fmMaterials','PriceType')+':';
aAddPT.ShortCut:=TextToShortCut('Ctrl+Ins');
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
procedure TfrmWBMovSetPT.DoCreate;
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmWBMovSetPT.DoCreate') else _udebug := nil;{$ENDIF}
inherited;
FormStorage.IniFileName:=PrRegKey;
FormStorage.IniSection:=Self.Name;
FormStorage.Active:=True;
//SetStyle(Self, IStyle);
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
procedure TfrmWBMovSetPT.ActionListUpdate(Action: TBasicAction; var Handled: Boolean);
//{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
(*{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmWBMovSetPT.ActionListUpdate') else _udebug := nil;{$ENDIF}
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
*)
end;
procedure TfrmWBMovSetPT.SetGrpID(const Value: integer);
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmWBMovSetPT.SetGrpID') else _udebug := nil;{$ENDIF}
FGrpID := Value;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
procedure TfrmWBMovSetPT.aLockExecute(Sender: TObject);
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmWBMovSetPT.aLockExecute') else _udebug := nil;{$ENDIF}
LockScreen;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
procedure TfrmWBMovSetPT.aHelpExecute(Sender: TObject);
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmWBMovSetPT.aHelpExecute') else _udebug := nil;{$ENDIF}
DoHelp;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
procedure TfrmWBMovSetPT.DoHelp;
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmWBMovSetPT.DoHelp') else _udebug := nil;{$ENDIF}
Application.HelpJump(ParentNameEx);
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
procedure TfrmWBMovSetPT.DoCustom(AParam: Integer);
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmWBMovSetPT.DoCustom') else _udebug := nil;{$ENDIF}
{}
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
procedure TfrmWBMovSetPT.aAddPTExecute(Sender: TObject);
var aid: Integer;
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmWBMovSetPT.aAddPTExecute') else _udebug := nil;{$ENDIF}
try aid := lcbPriceTypes.KeyValue; except aid := 0; end;
lcbPriceTypes.SetFocus;
ShowModalRef(Self, rtPriceTypes, vtPriceTypes, 'TfmPriceTypes', Self.OnDate, aid);
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
procedure TfrmWBMovSetPT.FormCreate(Sender: TObject);
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmWBMovSetPT.FormCreate') else _udebug := nil;{$ENDIF}
inherited;
SetCaptions;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
procedure TfrmWBMovSetPT.aSendErrMessageExecute(Sender: TObject);
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmWBMovSetPT.aSendErrMessageExecute') else _udebug := nil;{$ENDIF}
SendMsg;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
initialization
{$IFDEF UDEBUG}Debugging := False;
DEBUG_unit_ID := debugRegisterUnit('WBMovSetPT', @Debugging, DEBUG_group_ID);{$ENDIF}
finalization
//{$IFDEF UDEBUG}debugUnregisterUnit(DEBUG_unit_ID);{$ENDIF}
end.
|
unit RegularPolygon;
interface
uses
System.SysUtils, System.Classes, System.Types, System.Math,
FMX.Types, FMX.Controls, FMX.Objects, FMX.Graphics;
type
TRegularPolygon = class(TShape)
private
FNumberOfSides: Integer;
FPath: TPathData;
procedure SetNumberOfSides(const Value: Integer);
{ Private-Deklarationen }
protected
{ Protected-Deklarationen }
procedure CreatePath;
procedure Paint; override;
public
{ Public-Deklarationen }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function PointInObject(X, Y: Single): Boolean; override;
published
{ Published-Deklarationen }
property NumberOfSides: Integer read FNumberOfSides write SetNumberOfSides;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('Samples', [TRegularPolygon]);
end;
{ TRegularPolygon }
constructor TRegularPolygon.Create(AOwner: TComponent);
begin
inherited;
FNumberOfSides := 3;
FPath := TPathData.Create;
end;
procedure TRegularPolygon.CreatePath;
procedure GoToAVertex(n: Integer; Angle, CircumRadius: Double;
IsLineTo: Boolean = True);
var
NewLocation: TPointF;
begin
NewLocation.X := Width / 2 + Cos(n * Angle) * CircumRadius;
NewLocation.Y := Height / 2 - Sin(n * Angle) * CircumRadius;
if IsLineTo then
FPath.LineTo(NewLocation)
else
FPath.MoveTo(NewLocation);
end;
var
i: Integer;
Angle, CircumRadius: Double;
begin
Angle := 2 * PI / FNumberOfSides;
CircumRadius := Min(ShapeRect.Width / 2, ShapeRect.Height / 2);
// Create a new Path
FPath.Clear;
// MoveTo the first point
GoToAVertex(0, Angle, CircumRadius, False);
// LineTo each Vertex
for i := 1 to FNumberOfSides do
GoToAVertex(i, Angle, CircumRadius);
FPath.ClosePath;
end;
destructor TRegularPolygon.Destroy;
begin
FreeAndNil(FPath);
inherited;
end;
procedure TRegularPolygon.Paint;
begin
CreatePath;
Canvas.FillPath(FPath, AbsoluteOpacity);
Canvas.DrawPath(FPath, AbsoluteOpacity);
end;
function TRegularPolygon.PointInObject(X, Y: Single): Boolean;
begin
CreatePath;
Result := Canvas.PtInPath(AbsoluteToLocal(PointF(X, Y)), FPath);
end;
procedure TRegularPolygon.SetNumberOfSides(const Value: Integer);
begin
if (FNumberOfSides <> Value) and (Value >= 3) then
begin
FNumberOfSides := Value;
Repaint;
end;
end;
end.
|
unit l3PrimString;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Библиотека "L3"
// Автор: Люлин А.В.
// Модуль: "w:/common/components/rtl/Garant/L3/l3PrimString.pas"
// Начат: 05.02.2008 16:57
// Родные Delphi интерфейсы (.pas)
// Generated from UML model, root element: <<SimpleClass::Class>> Shared Delphi Low Level::L3::l3CoreObjects::Tl3PrimString
//
//
// Все права принадлежат ООО НПП "Гарант-Сервис".
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ! Полностью генерируется с модели. Править руками - нельзя. !
{$Include ..\L3\l3Define.inc}
interface
uses
l3Interfaces,
l3Types,
l3DataContainerWithoutIUnknown
;
type
Tl3PrimString = {abstract} class(Tl3DataContainerWithoutIUnknown)
protected
// property methods
function pm_GetAsString: AnsiString;
procedure pm_SetAsString(const aValue: AnsiString);
function pm_GetAsWStr: Tl3WString;
procedure pm_SetAsWStr(const aValue: Tl3WString);
function pm_GetStringID: Integer; virtual;
procedure pm_SetStringID(aValue: Integer); virtual;
function pm_GetLinkedObject: TObject; virtual;
procedure pm_SetLinkedObject(aValue: TObject); virtual;
protected
// overridden protected methods
function GetEmpty: Boolean; override;
protected
// protected methods
function GetAsPCharLen: Tl3WString; virtual;
procedure DoSetAsPCharLen(const Value: Tl3PCharLen); virtual;
public
// public methods
procedure Clear; virtual;
{* Функция очистки объекта. Для перекрытия в потомках. }
procedure AssignString(aStr: Tl3PrimString); virtual;
{* Присвает другую строку данной. }
function Clone(anOwner: TObject = nil): Pointer; virtual;
{* Создайт копию строки. }
public
// public properties
property AsString: AnsiString
read pm_GetAsString
write pm_SetAsString;
{* свойство для преобразования к строкам Delphi и обратно. }
property AsWStr: Tl3WString
read pm_GetAsWStr
write pm_SetAsWStr;
property StringID: Integer
read pm_GetStringID
write pm_SetStringID;
{* Идентификатор. }
property LinkedObject: TObject
read pm_GetLinkedObject
write pm_SetLinkedObject;
{* Объект, привязанный к строке. }
end;//Tl3PrimString
implementation
uses
l3String
;
// start class Tl3PrimString
function Tl3PrimString.pm_GetAsString: AnsiString;
//#UC START# *47A869930282_47A8693601A1get_var*
var
l_S : Tl3WString;
//#UC END# *47A869930282_47A8693601A1get_var*
begin
//#UC START# *47A869930282_47A8693601A1get_impl*
if (Self = nil) then
Result := ''
else
begin
l_S := GetAsPCharLen;
if (l_S.SCodePage = CP_Unicode) then
Result := l3PCharLen2String(l_S, CP_ANSI)
else
Result := l3PCharLen2String(l_S, l_S.SCodePage);
end;//Self = nil
//#UC END# *47A869930282_47A8693601A1get_impl*
end;//Tl3PrimString.pm_GetAsString
procedure Tl3PrimString.pm_SetAsString(const aValue: AnsiString);
//#UC START# *47A869930282_47A8693601A1set_var*
//#UC END# *47A869930282_47A8693601A1set_var*
begin
//#UC START# *47A869930282_47A8693601A1set_impl*
if (Self <> nil) then
begin
if (aValue = '') then
Clear
else
AsWStr := l3PCharLen(aValue, AsWStr.SCodePage);
end;//Self <> nil
//#UC END# *47A869930282_47A8693601A1set_impl*
end;//Tl3PrimString.pm_SetAsString
function Tl3PrimString.pm_GetAsWStr: Tl3WString;
//#UC START# *47A869A600BF_47A8693601A1get_var*
//#UC END# *47A869A600BF_47A8693601A1get_var*
begin
//#UC START# *47A869A600BF_47A8693601A1get_impl*
if (Self = nil) then
l3AssignNil(Result)
else
Result := GetAsPCharLen;
//#UC END# *47A869A600BF_47A8693601A1get_impl*
end;//Tl3PrimString.pm_GetAsWStr
procedure Tl3PrimString.pm_SetAsWStr(const aValue: Tl3WString);
//#UC START# *47A869A600BF_47A8693601A1set_var*
//#UC END# *47A869A600BF_47A8693601A1set_var*
begin
//#UC START# *47A869A600BF_47A8693601A1set_impl*
if (Self <> nil) then
DoSetAsPCharLen(Tl3PCharLen(aValue));
//#UC END# *47A869A600BF_47A8693601A1set_impl*
end;//Tl3PrimString.pm_SetAsWStr
function Tl3PrimString.pm_GetStringID: Integer;
//#UC START# *47BC3BFD017F_47A8693601A1get_var*
//#UC END# *47BC3BFD017F_47A8693601A1get_var*
begin
//#UC START# *47BC3BFD017F_47A8693601A1get_impl*
Result := 0;
//#UC END# *47BC3BFD017F_47A8693601A1get_impl*
end;//Tl3PrimString.pm_GetStringID
procedure Tl3PrimString.pm_SetStringID(aValue: Integer);
//#UC START# *47BC3BFD017F_47A8693601A1set_var*
//#UC END# *47BC3BFD017F_47A8693601A1set_var*
begin
//#UC START# *47BC3BFD017F_47A8693601A1set_impl*
//#UC END# *47BC3BFD017F_47A8693601A1set_impl*
end;//Tl3PrimString.pm_SetStringID
function Tl3PrimString.pm_GetLinkedObject: TObject;
//#UC START# *47BC3CCE00A6_47A8693601A1get_var*
//#UC END# *47BC3CCE00A6_47A8693601A1get_var*
begin
//#UC START# *47BC3CCE00A6_47A8693601A1get_impl*
Result := nil;
//#UC END# *47BC3CCE00A6_47A8693601A1get_impl*
end;//Tl3PrimString.pm_GetLinkedObject
procedure Tl3PrimString.pm_SetLinkedObject(aValue: TObject);
//#UC START# *47BC3CCE00A6_47A8693601A1set_var*
//#UC END# *47BC3CCE00A6_47A8693601A1set_var*
begin
//#UC START# *47BC3CCE00A6_47A8693601A1set_impl*
//#UC END# *47BC3CCE00A6_47A8693601A1set_impl*
end;//Tl3PrimString.pm_SetLinkedObject
function Tl3PrimString.GetAsPCharLen: Tl3WString;
//#UC START# *47A869BB02DE_47A8693601A1_var*
//#UC END# *47A869BB02DE_47A8693601A1_var*
begin
//#UC START# *47A869BB02DE_47A8693601A1_impl*
l3AssignNil(Result);
//#UC END# *47A869BB02DE_47A8693601A1_impl*
end;//Tl3PrimString.GetAsPCharLen
procedure Tl3PrimString.DoSetAsPCharLen(const Value: Tl3PCharLen);
//#UC START# *47A869D10074_47A8693601A1_var*
//#UC END# *47A869D10074_47A8693601A1_var*
begin
//#UC START# *47A869D10074_47A8693601A1_impl*
Assert(false);
//#UC END# *47A869D10074_47A8693601A1_impl*
end;//Tl3PrimString.DoSetAsPCharLen
procedure Tl3PrimString.Clear;
//#UC START# *47BC02A50131_47A8693601A1_var*
//#UC END# *47BC02A50131_47A8693601A1_var*
begin
//#UC START# *47BC02A50131_47A8693601A1_impl*
// - ничего не делаем
//#UC END# *47BC02A50131_47A8693601A1_impl*
end;//Tl3PrimString.Clear
procedure Tl3PrimString.AssignString(aStr: Tl3PrimString);
//#UC START# *47BC3C950296_47A8693601A1_var*
//#UC END# *47BC3C950296_47A8693601A1_var*
begin
//#UC START# *47BC3C950296_47A8693601A1_impl*
StringID := aStr.StringID;
AsWStr := aStr.AsWStr;
LinkedObject := aStr.LinkedObject;
//#UC END# *47BC3C950296_47A8693601A1_impl*
end;//Tl3PrimString.AssignString
function Tl3PrimString.Clone(anOwner: TObject = nil): Pointer;
//#UC START# *47BC3FC40111_47A8693601A1_var*
type
Rl3PrimString = class of Tl3PrimString;
//#UC END# *47BC3FC40111_47A8693601A1_var*
begin
//#UC START# *47BC3FC40111_47A8693601A1_impl*
Result := Rl3PrimString(ClassType).Create;
if (anOwner <> nil) then
Tl3PrimString(Result).DoSetOwner(anOwner);
Tl3PrimString(Result).AssignString(Self);
//#UC END# *47BC3FC40111_47A8693601A1_impl*
end;//Tl3PrimString.Clone
function Tl3PrimString.GetEmpty: Boolean;
//#UC START# *4A54E03B009A_47A8693601A1_var*
//#UC END# *4A54E03B009A_47A8693601A1_var*
begin
//#UC START# *4A54E03B009A_47A8693601A1_impl*
Result := l3IsNil(AsWStr);
//#UC END# *4A54E03B009A_47A8693601A1_impl*
end;//Tl3PrimString.GetEmpty
end. |
{ *********************************************************************************** }
{ * CryptoLib Library * }
{ * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * }
{ * Github Repository <https://github.com/Xor-el> * }
{ * Distributed under the MIT software license, see the accompanying file LICENSE * }
{ * or visit http://www.opensource.org/licenses/mit-license.php. * }
{ * Acknowledgements: * }
{ * * }
{ * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * }
{ * development of this library * }
{ * ******************************************************************************* * }
(* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *)
unit ClpGlvTypeBParameters;
{$I ..\..\..\Include\CryptoLib.inc}
interface
uses
ClpBigInteger,
ClpIGlvTypeBParameters,
ClpCryptoLibTypes;
type
TGlvTypeBParameters = class sealed(TInterfacedObject, IGlvTypeBParameters)
strict private
function GetBeta: TBigInteger; inline;
function GetBits: Int32; inline;
function GetG1: TBigInteger; inline;
function GetG2: TBigInteger; inline;
function GetLambda: TBigInteger; inline;
function GetV1: TCryptoLibGenericArray<TBigInteger>; inline;
function GetV2: TCryptoLibGenericArray<TBigInteger>; inline;
strict protected
Fm_beta, Fm_lambda: TBigInteger;
Fm_v1, Fm_v2: TCryptoLibGenericArray<TBigInteger>;
Fm_g1, Fm_g2: TBigInteger;
Fm_bits: Int32;
public
constructor Create(const beta, lambda: TBigInteger;
const v1, v2: TCryptoLibGenericArray<TBigInteger>;
const g1, g2: TBigInteger; bits: Int32);
destructor Destroy; override;
property beta: TBigInteger read GetBeta;
property lambda: TBigInteger read GetLambda;
property v1: TCryptoLibGenericArray<TBigInteger> read GetV1;
property v2: TCryptoLibGenericArray<TBigInteger> read GetV2;
property g1: TBigInteger read GetG1;
property g2: TBigInteger read GetG2;
property bits: Int32 read GetBits;
end;
implementation
{ TGlvTypeBParameters }
constructor TGlvTypeBParameters.Create(const beta, lambda: TBigInteger;
const v1, v2: TCryptoLibGenericArray<TBigInteger>; const g1, g2: TBigInteger;
bits: Int32);
begin
Fm_beta := beta;
Fm_lambda := lambda;
Fm_v1 := v1;
Fm_v2 := v2;
Fm_g1 := g1;
Fm_g2 := g2;
Fm_bits := bits;
end;
destructor TGlvTypeBParameters.Destroy;
begin
inherited Destroy;
end;
function TGlvTypeBParameters.GetBeta: TBigInteger;
begin
Result := Fm_beta;
end;
function TGlvTypeBParameters.GetBits: Int32;
begin
Result := Fm_bits;
end;
function TGlvTypeBParameters.GetG1: TBigInteger;
begin
Result := Fm_g1;
end;
function TGlvTypeBParameters.GetG2: TBigInteger;
begin
Result := Fm_g2;
end;
function TGlvTypeBParameters.GetLambda: TBigInteger;
begin
Result := Fm_lambda;
end;
function TGlvTypeBParameters.GetV1: TCryptoLibGenericArray<TBigInteger>;
begin
Result := Fm_v1;
end;
function TGlvTypeBParameters.GetV2: TCryptoLibGenericArray<TBigInteger>;
begin
Result := Fm_v2;
end;
end.
|
{$MODE OBJFPC}
{$DEFINE RELEASE}
{$R-,Q-,S-,I-}
{$OPTIMIZATION LEVEL2}
{$INLINE ON}
program Marksman;
const
InputFile = 'ARCHER.INP';
OutputFile = 'ARCHER.OUT';
maxN = 2000;
maxC = 2000;
infty = High(QWord);
type
TCoord = SmallInt;
TCode = QWord;
TVector = record
x, y, z: Integer;
end;
TPoint = TVector;
var
p: array[1..maxN] of TPoint;
k: array[1..maxN] of TVector;
n: Integer;
res: Integer;
procedure Enter;
var
f: TextFile;
i: Integer;
begin
AssignFile(f, InputFile); Reset(f);
try
ReadLn(f, n);
for i := 1 to n do
with p[i] do ReadLn(f, x, y, z);
finally
CloseFile(f);
end;
end;
procedure GetVector(const a, b: TPoint; var v: TVector); inline;
var
d: TCoord;
begin
with v do
begin
x := b.x - a.x;
y := b.y - a.y;
z := b.z - a.z;
if z < 0 then
begin
x := -x; y := -y; z := -z;
end;
end;
end;
function Vector0(const v: TVector): Boolean; inline;
begin
Result := (v.x = 0) and (v.y = 0) and (v.z = 0);
end;
function Less(const u, v: TVector): Boolean; inline;
var
u0, v0: Boolean;
begin
u0 := Vector0(u); v0 := Vector0(v);
if u0 or v0 then
Exit(u0 and not v0);
//ux / uz < vx / vz hoac ux / uz = vx/vz va uy / uz < vy / vz
Result := (u.x * v.z < u.z * v.x) or
(u.x * v.z = u.z * v.x) and (u.y * v.z < u.z * v.y);
end;
function Equal(const u, v: TVector): Boolean; inline;
begin
Result := (u.x * v.z = u.z * v.x) and (u.y * v.z = u.z * v.y);
end;
procedure ShellSort(nv: Integer);
var
i, j, step: Integer;
temp: TVector;
begin
step := nv div 2;
while step <> 0 do
begin
for i := step + 1 to nv do
begin
temp := k[i]; j := i - step;
while (j > 0) and Less(temp, k[j]) do
begin
k[j + step] := k[j]; Dec(j, step);
end;
k[j + step] := temp;
end;
if step = 2 then step := 1
else step := step * 10 div 22;
end;
end;
procedure Solve;
var
i, j: Integer;
s, t: Integer;
nv0: Integer;
begin
res := 0;
for i := n downto 2 do
begin
if i < res then Break;
for j := i - 1 downto 1 do
GetVector(p[i], p[j], k[j]);
ShellSort(i - 1);
s := 1;
while (s < i) and Vector0(k[s]) do Inc(s); //Dem so vector 0
nv0 := s - 1;
if nv0 > res then res := nv0;
while s < i do
begin
t := s + 1;
while (t < i) and Equal(k[t], k[s]) do Inc(t);
if (t - s + nv0 > res) and (k[s].z <> 0) then
res := t - s + nv0;
s := t;
end;
end;
Inc(res);
end;
procedure PrintResult;
var
f: TextFile;
begin
AssignFile(f, OutputFile); Rewrite(f);
try
WriteLn(f, res);
finally
CloseFile(f);
end;
end;
begin
Enter;
Solve;
PrintResult;
end.
7
2 1 1
3 2 2
4 3 3
0 0 4
0 1 4
0 2 4
0 3 4
|
{####################################################################################}
{ }
{ DATA AUTOR Descrição }
{----------- ------------------ ----------------------------------------------------}
{ 22/06/2017 guilherme.chiarini Criação de arquivo }
{####################################################################################}
unit uobjProdutos;
interface
uses System.Classes, FireDAC.Comp.Client, uDataModule, system.SysUtils, Global;
type
TProduto = class
private
FID: integer;
FDescricao: string;
FChUnidade: Integer;
FValor: Extended;
FAtivo: string;
public
constructor Create(AOwner: TComponent);
function GravarProduto: Boolean;
function AlterarProduto: Boolean;
function ExcluirProduto: Boolean;
function Pesquisar(AChProduto: integer): TProduto;
property chave: integer read FID write FID;
property Descricao: string read FDescricao write FDescricao;
property unidade: integer read FChUnidade write FChUnidade;
property Valor: Extended read FValor write FValor;
property Ativo: string read FAtivo write FAtivo;
published
end;
implementation
{ TProduto }
function TProduto.AlterarProduto: Boolean;
var queryProduto: TFDQuery;
begin
queryProduto := TFDQuery.Create(nil);
try
queryProduto.Connection := DM.CONEXAO;
queryProduto.Close;
queryProduto.SQL.Clear;
queryProduto.SQL.Add('update cad_produto ' );
queryProduto.SQL.Add(' set tdescricao = :descricao, ');
queryProduto.SQL.Add(' nchunidade = :unidade, ');
queryProduto.SQL.Add(' nvalor = :valor, ');
queryProduto.SQL.Add(' lativo = :ativo ');
queryProduto.SQL.Add(' where chave = :id ');
queryProduto.ParamByName('id').AsInteger := chave;
queryProduto.ParamByName('descricao').AsString := Descricao;
queryProduto.ParamByName('unidade').AsInteger := unidade;
queryProduto.ParamByName('valor').AsFloat := Valor;
queryProduto.ParamByName('ativo').AsString := Ativo;
try
queryProduto.ExecSQL;
AlterarProduto := True;
except
AlterarProduto := False;
end;
finally
FreeAndNil(queryProduto);
end;
end;
constructor TProduto.Create(AOwner: TComponent);
begin
//
end;
function TProduto.ExcluirProduto: Boolean;
var queryProduto: TFDQuery;
begin
queryProduto := TFDQuery.Create(nil);
try
queryProduto.Connection := DM.CONEXAO;
queryProduto.Close;
queryProduto.SQL.Clear;
queryProduto.SQL.Add('delete from cad_produto ');
queryProduto.SQL.Add(' where chave = :id');
queryProduto.ParamByName('id').AsInteger := chave;
try
queryProduto.ExecSQL;
ExcluirProduto := True;
except
ExcluirProduto := False;
end;
finally
FreeAndNil(queryProduto);
end;
end;
function TProduto.GravarProduto: Boolean;
var queryProduto: TFDQuery;
begin
queryProduto := TFDQuery.Create(nil);
try
queryProduto.Connection := DM.CONEXAO;
queryProduto.Close;
queryProduto.SQL.Clear;
queryProduto.SQL.Add('insert into cad_produto ' );
queryProduto.SQL.Add(' (chave, ' );
queryProduto.SQL.Add(' tdescricao, ' );
queryProduto.SQL.Add(' nchunidade, ' );
queryProduto.SQL.Add(' nvalor, ' );
queryProduto.SQL.Add(' lativo) ' );
queryProduto.SQL.Add(' values(:chave, ' );
queryProduto.SQL.Add(' :descricao, ' );
queryProduto.SQL.Add(' :unidade, ' );
queryProduto.SQL.Add(' :valor, ' );
queryProduto.SQL.Add(' :ativo) ' );
queryProduto.ParamByName('chave').AsInteger := Global.verificar_gen('cad_produto');
queryProduto.ParamByName('descricao').AsString := Descricao;
queryProduto.ParamByName('unidade').AsInteger := unidade;
queryProduto.ParamByName('valor').AsFloat := Valor;
queryProduto.ParamByName('ativo').AsString := Ativo;
try
queryProduto.ExecSQL;
GravarProduto := True;
except
GravarProduto := False;
end;
finally
FreeAndNil(queryProduto);
end;
end;
function TProduto.Pesquisar(AChProduto: integer): TProduto;
var queryPesquisar: TFDQuery;
begin
queryPesquisar := TFDQuery.Create(nil);
try
queryPesquisar.Connection := DM.CONEXAO;
queryPesquisar.Close;
queryPesquisar.SQL.Clear;
queryPesquisar.SQL.Add('select * from cad_produto WHERE chave = :id ');
queryPesquisar.ParamByName('id').AsInteger := AChProduto;
queryPesquisar.Open;
if not queryPesquisar.IsEmpty then
begin
chave := queryPesquisar.FieldByName('chave').AsInteger;
Descricao := queryPesquisar.FieldByName('tdescricao').AsString;
unidade := queryPesquisar.FieldByName('nchunidade').AsInteger;
Valor := queryPesquisar.FieldByName('nvalor').AsFloat;
Ativo := queryPesquisar.FieldByName('lativo').AsString;
end
else
begin
chave := 0;
end;
finally
FreeAndNil(queryPesquisar);
end;
end;
end.
|
{> P2ada test - mathematical stuff }
program NPTest6;
{ Mandelbrot set in text-mode. Standard Pascal with "Double" type }
{ G. de Montmollin 2003 }
procedure Mandelbrot_ASCII(mx,my: Integer);
procedure Plot_area_absolute( ar,br,ai,bi: Double; itmax: Integer );
const ncol=6;
type Complex = record r,i: Double; end;
var
x,y: Integer;
col_table: array[0..ncol] of Char;
p, area: Complex;
function Check_in_set( c: Complex ): Integer;
var
z: Complex;
tmp: Double;
count: Integer;
begin
z.r:= 0.0;
z.i:= 0.0;
count:= 0;
repeat
tmp:= Sqr(z.r) - Sqr(z.i) + c.r;
z.i:= 2.0 * z.r * z.i + c.i;
z.r:= tmp;
count:= count + 1;
until (count > itmax) or ((Sqr(z.r) + Sqr(z.i)) > 4.0);
Check_in_set:= count
end;
begin
col_table[0]:= '#';
col_table[1]:= '%';
col_table[2]:= 'o';
col_table[3]:= '*';
col_table[4]:= ':';
col_table[5]:= '.';
col_table[6]:= ' ';
area.r:= br - ar;
area.i:= bi - ai;
for y:= 0 to my-1 do begin
for x:= 0 to mx-1 do begin
p.r:= ar + area.r * (x) / (mx); { <--- Add Long_Float(...) }
p.i:= ai + area.i * (y) / (my);
Write( col_table[(Check_in_set( p ) * ncol) div itmax] )
end;
WriteLn
end;
for x:= 0 to mx-9 do Write('-');
Write('[Return]');
ReadLn
end;
procedure Plot_area( ar,lr,ai,li: Double; itmax: Integer );
begin
Plot_area_absolute( ar,ar+lr,ai,ai+li, itmax )
end;
begin
Plot_area_absolute( -2.2, 1.0, -1.25, 1.25, 20 );
Plot_area_absolute( -1.0, 1.0, -1.25, 0.0, 20 );
Plot_area_absolute( -0.5, 0.4, -1.20, -0.6, 30 );
Plot_area(
-1.2029564421301, 0.0351555010544,
-0.3096782894352, 0.0116621445959, 150);
Plot_area(
-0.6318405970938, 0.1392759537664,
-0.7106447090334, 0.1356552208384, 200);
Plot_area(
-0.5228527433221, 0.0016623236276,
-0.5988152788281, 0.0011269551612, 300);
Plot_area(
-1.2963558632663, 0.0000120813111,
0.4418487504284, 0.0000057144987, 29);
end;
procedure The_Matrix;
const matmax = 20;
type Matrix = array[1..matmax,1..matmax] of Double;
var M1,M2,M3: Matrix;
i,j: Integer;
procedure TransposeAB( var A,B: Matrix );
var i,j: Integer;
begin
for i := 1 to matmax do
for j := 1 to matmax do
B[j,i]:= A[i,j]
end;
begin
for i := 1 to matmax do
for j := 1 to matmax do
if i > j then
M1[i,j]:= (i*j) { <- You need to write Long_Float(i*j) }
else
M1[i,j]:= 0.0;
TransposeAB(M1,M2);
TransposeAB(M2,M3);
for i := 1 to matmax do
for j := 1 to matmax do
if M1[i,j] <> M3[i,j] then WriteLn('Transpose failed!')
end;
begin
Mandelbrot_ASCII(78,24);
The_Matrix;
end.
|
unit UpdateAvoidanceZoneUnit;
interface
uses SysUtils, BaseExampleUnit;
type
TUpdateAvoidanceZone = class(TBaseExample)
public
procedure Execute(TerritoryId: String);
end;
implementation
uses AvoidanceZoneUnit, TerritoryContourUnit;
procedure TUpdateAvoidanceZone.Execute(TerritoryId: String);
var
ErrorString: String;
AvoidanceZone: TAvoidanceZone;
Territory: TTerritoryContour;
NewAvoidanceZone: TAvoidanceZone;
TerritoryName, TerritoryColor: String;
begin
TerritoryName := 'Test Territory Updated';
TerritoryColor := 'ff00ff';
Territory := TTerritoryContour.MakeCircleContour(
38.4132225905681, -78.501953234, 3000);
AvoidanceZone := TAvoidanceZone.Create(TerritoryName, TerritoryColor, Territory);
try
AvoidanceZone.TerritoryId := TerritoryId;
NewAvoidanceZone := Route4MeManager.AvoidanceZone.Update(AvoidanceZone, ErrorString);
try
WriteLn('');
if (NewAvoidanceZone <> nil) then
begin
WriteLn('UpdateAvoidanceZone executed successfully');
WriteLn(Format('Territory ID: %s', [NewAvoidanceZone.TerritoryId.Value]));
end
else
WriteLn(Format('UpdateAvoidanceZone error: "%s"', [ErrorString]));
finally
FreeAndNil(NewAvoidanceZone);
end;
finally
FreeAndNil(AvoidanceZone);
end;
end;
end.
|
unit Col;
interface
uses
Classes;
const
NoIndex = -1;
type
TRelationshipKind = (rkUse, rkBelonguer);
type
CCollection = class of TCollection;
PCollection = ^TCollection;
TCollection =
class
public
constructor Create( aLimit, aDelta : integer; aRelKind : TRelationshipKind );
destructor Destroy; override;
public
procedure Insert ( Item : TObject ); virtual;
procedure Delete ( Item : TObject ); virtual;
procedure Extract( Item : TObject ); virtual;
procedure AtInsert ( Index : integer; Item : TObject ); virtual;
procedure AtDelete ( Index : integer ); virtual;
procedure AtExtract( Index : integer ); virtual;
function IndexOf( Item : TObject ) : integer; virtual;
procedure InsertColl( Coll : TCollection );
procedure DeleteAll; virtual;
procedure ExtractAll; virtual;
protected
function GetItem( index : integer ) : TObject; virtual;
procedure SetItem( index : integer; Item : TObject ); virtual;
function GetCount : integer; virtual;
public
procedure Sort( Compare : TListSortCompare ); virtual;
public
property Items[index : integer] : TObject read GetItem write SetItem; default;
property Count : integer read GetCount;
private
fList : TList;
fRelKind : TRelationshipKind;
end;
implementation
{ TCollection }
constructor TCollection.Create( aLimit, aDelta : integer; aRelKind : TRelationshipKind );
begin
inherited Create;
fList := TList.Create;
fRelKind := aRelKind;
end;
destructor TCollection.Destroy;
var
i : integer;
begin
if fRelKind = rkBelonguer
then
for i := 0 to pred(fList.Count) do
Items[i].Free;
fList.Free;
inherited Destroy;
end;
procedure TCollection.Insert( Item : TObject );
begin
AtInsert( fList.Count, Item );
end;
procedure TCollection.Delete( Item : TObject );
var
Idx : integer;
begin
Idx := IndexOf( Item );
if Idx >= 0
then AtDelete( Idx );
end;
procedure TCollection.Extract( Item : TObject );
var
Idx : integer;
begin
Idx := IndexOf( Item );
if Idx >= 0
then AtExtract( Idx );
end;
procedure TCollection.AtInsert( Index : integer; Item : TObject );
begin
if fList.Capacity = fList.Count
then fList.Expand;
if Index < fList.Count
then fList.Insert( Index, Item )
else fList.Add( Item );
end;
procedure TCollection.AtDelete( Index : integer );
begin
if fRelKind = rkBelonguer
then TObject(fList[Index]).Free;
fList.Delete( Index );
fList.Pack;
end;
procedure TCollection.AtExtract( Index : integer );
begin
fList.Delete( Index );
fList.Pack;
end;
function TCollection.IndexOf( Item : TObject ) : integer;
begin
result := fList.IndexOf( Item );
end;
procedure TCollection.InsertColl( Coll : TCollection );
var
i : integer;
begin
for i := 0 to pred(Coll.Count) do
Insert( Coll[i] );
end;
procedure TCollection.DeleteAll;
begin
if fRelKind = rkBelonguer
then
while fList.Count > 0 do
AtDelete( 0 )
else fList.Clear;
end;
procedure TCollection.ExtractAll;
begin
fList.Clear;
end;
procedure TCollection.Sort( Compare : TListSortCompare );
begin
fList.Sort( Compare );
end;
function TCollection.GetItem( index : integer ) : TObject;
begin
result := fList.Items[index]
end;
procedure TCollection.SetItem( index : integer; Item : TObject );
begin
fList.Items[index] := Item;
end;
function TCollection.GetCount : integer;
begin
result := fList.Count;
end;
end.
|
{
Clever Internet Suite
Copyright (C) 2014 Clever Components
All Rights Reserved
www.CleverComponents.com
}
unit clDkimKey;
interface
{$I clVer.inc}
uses
{$IFNDEF DELPHIXE2}
Classes, SysUtils, Contnrs,
{$ELSE}
System.Classes, System.SysUtils, System.Contnrs,
{$ENDIF}
clConfig;
type
TclDkimKeyFlag = (ddfTestingDomain, ddfCheckUserIdentityDomain);
TclDkimKeyFlags = set of TclDkimKeyFlag;
TclDkimKeyServiceType = (ddsAll, ddsEmail);
TclDkimKeyServiceTypes = set of TclDkimKeyServiceType;
TclDkimKey = class
private
FVersion: string;
FAcceptableHashAlgorithms: TStrings;
FKeyType: string;
FNotes: string;
FPublicKey: string;
FServiceType: TclDkimKeyServiceTypes;
FFlags: TclDkimKeyFlags;
procedure ParseAcceptableHashAlgorithms(const ASource: string);
function ParseNotes(const ASource: string): string;
function ParseServiceType(const ASource: string): TclDkimKeyServiceTypes;
function ParseFlags(const ASource: string): TclDkimKeyFlags;
function GetAcceptableHashAlgorithms: string;
function GetNotes: string;
function GetServiceType: string;
function GetFlags: string;
procedure SetAcceptableHashAlgorithms(const Value: TStrings);
public
constructor Create;
destructor Destroy; override;
procedure Parse(const ATxt: string); virtual;
function Build: string; virtual;
procedure Clear; virtual;
property Version: string read FVersion write FVersion;
property AcceptableHashAlgorithms: TStrings read FAcceptableHashAlgorithms write SetAcceptableHashAlgorithms;
property KeyType: string read FKeyType write FKeyType;
property Notes: string read FNotes write FNotes;
property PublicKey: string read FPublicKey write FPublicKey;
property ServiceType: TclDkimKeyServiceTypes read FServiceType write FServiceType;
property Flags: TclDkimKeyFlags read FFlags write FFlags;
end;
TclDkimKeyList = class
private
FList: TObjectList;
function GetCount: Integer;
function GetItem(Index: Integer): TclDkimKey;
public
constructor Create;
destructor Destroy; override;
function Add(AItem: TclDkimKey): TclDkimKey;
procedure Delete(Index: Integer);
procedure Clear;
property Items[Index: Integer]: TclDkimKey read GetItem; default;
property Count: Integer read GetCount;
end;
implementation
uses
clUtils, clDkimUtils, clEncoder;
const
cDkimKeyServiceTypes: array[TclDkimKeyServiceType] of string = ('*', 'email');
cDkimKeyFlags: array[TclDkimKeyFlag] of string = ('y', 's');
{ TclDkimDnsRecord }
function TclDkimKey.GetAcceptableHashAlgorithms: string;
var
i: Integer;
begin
Result := '';
for i := 0 to AcceptableHashAlgorithms.Count - 1 do
begin
Result := Result + AcceptableHashAlgorithms[i] + ':';
end;
if (Length(Result) > 0) then
begin
System.Delete(Result, Length(Result), 1);
end;
end;
function TclDkimKey.GetNotes: string;
begin
Result := TclDkimQuotedPrintableEncoder.Encode(Notes);
end;
function TclDkimKey.GetServiceType: string;
var
k: TclDkimKeyServiceType;
begin
Result := '';
for k := Low(TclDkimKeyServiceType) to High(TclDkimKeyServiceType) do
begin
if (k in ServiceType) then
begin
Result := Result + cDkimKeyServiceTypes[k] + ':';
end;
end;
if (Length(Result) > 0) then
begin
System.Delete(Result, Length(Result), 1);
end;
end;
function TclDkimKey.GetFlags: string;
var
k: TclDkimKeyFlag;
begin
Result := '';
for k := Low(TclDkimKeyFlag) to High(TclDkimKeyFlag) do
begin
if (k in Flags) then
begin
Result := Result + cDkimKeyFlags[k] + ':';
end;
end;
if (Length(Result) > 0) then
begin
System.Delete(Result, Length(Result), 1);
end;
end;
function TclDkimKey.Build: string;
const
dkimKey = 'key';
var
fieldList: TclDkimHeaderFieldList;
src: TStrings;
begin
fieldList := nil;
src := nil;
try
fieldList := TclDkimHeaderFieldList.Create();
src := TStringList.Create();
fieldList.Parse(0, src);
fieldList.AddEmptyField(dkimKey);
fieldList.AddFieldItem(dkimKey, 'v', Version);
fieldList.AddFieldItem(dkimKey, 'h', GetAcceptableHashAlgorithms());
fieldList.AddFieldItem(dkimKey, 'k', KeyType);
fieldList.AddFieldItem(dkimKey, 'n', GetNotes());
fieldList.AddFieldItem(dkimKey, 's', GetServiceType());
fieldList.AddFieldItem(dkimKey, 't', GetFlags());
if (PublicKey = '') then
begin
fieldList.AddEmptyFieldItem(dkimKey, 'p');
end else
begin
fieldList.AddFieldItem(dkimKey, 'p', PublicKey);
end;
Result := fieldList.GetFieldValue(dkimKey);
finally
src.Free();
fieldList.Free();
end;
end;
procedure TclDkimKey.Clear;
begin
FVersion := '';
FAcceptableHashAlgorithms.Clear();
FKeyType := '';
FNotes := '';
FPublicKey := '';
FServiceType := [];
FFlags := [];
end;
constructor TclDkimKey.Create;
begin
inherited Create();
FAcceptableHashAlgorithms := TStringList.Create();
Clear();
end;
destructor TclDkimKey.Destroy;
begin
FAcceptableHashAlgorithms.Free();
inherited Destroy();
end;
procedure TclDkimKey.ParseAcceptableHashAlgorithms(const ASource: string);
begin
SplitText(Trim(ASource), AcceptableHashAlgorithms, ':');
end;
function TclDkimKey.ParseNotes(const ASource: string): string;
begin
Result := TclDkimQuotedPrintableEncoder.Decode(ASource);
end;
function TclDkimKey.ParseServiceType(const ASource: string): TclDkimKeyServiceTypes;
var
i: Integer;
k: TclDkimKeyServiceType;
list: TStrings;
begin
Result := [];
list := TStringList.Create();
try
SplitText(Trim(ASource), list, ':');
for i := 0 to list.Count - 1 do
begin
for k := Low(TclDkimKeyServiceType) to High(TclDkimKeyServiceType) do
begin
if (Trim(list[i]) = cDkimKeyServiceTypes[k]) then
begin
Result := Result + [k];
Break;
end;
end;
end;
finally
list.Free();
end;
end;
procedure TclDkimKey.SetAcceptableHashAlgorithms(const Value: TStrings);
begin
FAcceptableHashAlgorithms.Assign(Value);
end;
function TclDkimKey.ParseFlags(const ASource: string): TclDkimKeyFlags;
var
i: Integer;
k: TclDkimKeyFlag;
list: TStrings;
begin
Result := [];
list := TStringList.Create();
try
SplitText(Trim(ASource), list, ':');
for i := 0 to list.Count - 1 do
begin
for k := Low(TclDkimKeyFlag) to High(TclDkimKeyFlag) do
begin
if (Trim(list[i]) = cDkimKeyFlags[k]) then
begin
Result := Result + [k];
Break;
end;
end;
end;
finally
list.Free();
end;
end;
procedure TclDkimKey.Parse(const ATxt: string);
var
fieldList: TclDkimHeaderFieldList;
begin
fieldList := TclDkimHeaderFieldList.Create();
try
FVersion := Trim(fieldList.GetFieldValueItem(ATxt, 'v'));
ParseAcceptableHashAlgorithms(fieldList.GetFieldValueItem(ATxt, 'h'));
FKeyType := Trim(fieldList.GetFieldValueItem(ATxt, 'k'));
FNotes := ParseNotes(fieldList.GetFieldValueItem(ATxt, 'n'));
FPublicKey := Trim(fieldList.GetFieldValueItem(ATxt, 'p'));
FServiceType := ParseServiceType(fieldList.GetFieldValueItem(ATxt, 's'));
FFlags := ParseFlags(fieldList.GetFieldValueItem(ATxt, 't'));
finally
fieldList.Free();
end;
end;
{ TclDkimKeyList }
function TclDkimKeyList.Add(AItem: TclDkimKey): TclDkimKey;
begin
FList.Add(AItem);
Result := AItem;
end;
procedure TclDkimKeyList.Clear;
begin
FList.Clear();
end;
constructor TclDkimKeyList.Create;
begin
inherited Create();
FList := TObjectList.Create(True);
end;
procedure TclDkimKeyList.Delete(Index: Integer);
begin
FList.Delete(Index);
end;
destructor TclDkimKeyList.Destroy;
begin
FList.Free();
inherited Destroy();
end;
function TclDkimKeyList.GetCount: Integer;
begin
Result := FList.Count;
end;
function TclDkimKeyList.GetItem(Index: Integer): TclDkimKey;
begin
Result := TclDkimKey(FList[Index]);
end;
end.
|
program ex;
uses crt,Graph;
{описание абстрактного класса}
Type TChar=object
ch:char; {символ}
x,y:integer; {исходное положение}
constructor Init(ach:char; ax,ay:integer);
procedure Move(t:integer);
procedure Rel(t:integer); virtual;
end;
constructor TChar.Init(ach:char; ax,ay:integer);
begin
ch:=ach;
x:=ax;
y:=ay;
end;
procedure TChar.Rel(t:integer);
begin
End;
Procedure TChar.Move(t:integer);
begin
SetColor(GetBkColor);
OuttextXY(x,y,ch);
Rel(t); {вызываем переопределяемый метод изменения координат}
SetColor(ord(ch) mod 16);
OutTextXY(x,y,ch);
end;
{описание класса символа, перемещающегося по горизонтали}
Type TLineChar=object(TChar)
xn:integer; {точка отсчета координат по горизонтали}
constructor Init(ach:char; ax,ay:integer);
procedure Rel(t:integer); virtual;
end;
Constructor TLineChar.Init;
begin
inherited Init(ach,ax,ay); xn:=ax;
end;
procedure TLineChar.Rel;
begin
x:=(xn+t) mod GetMaxX;
end;
{описание класса символа, перемещающегося по вертикали}
Type TVLineChar=object(TChar)
yn:integer; {точка отсчета координат по вертикали}
constructor Init(ach:char; ax,ay:integer);
procedure Rel(t:integer); virtual;
end;
Constructor TVLineChar.Init;
begin
inherited Init(ach,ax,ay);
yn:=ay;
end;
procedure TVLineChar.Rel;
begin
y:=(yn+t) mod GetMaxY;
end;
{описание класса сивола, перемещающегося по окружности}
Type TCirChar=object(TChar)
xc,yx,r:integer; {параметры окружности}
t0:real; {исходное положение - начальный угол}
constructor Init(ach:char; axc,ayc,ar:integer; at0:real);
procedure Rel(t:integer); virtual;
end;
Constructor TCirChar.Init;
begin
inherited Init(ach,axc+round(ar*sin(at0)),ayc+round(ar*cos(at0)));
xc:=axc;
yc:=ayc;
r:=ar;
t0:=at0;
end;
procedure TCirChar.Rel;
begin
x:=xc+Round(r*sin(t0+t*t0.05));
y:=yx+Round(r*cos(t0+t*0.05));
end;
{объявление переменных}
var A:TLineChar;
B:TVLineChar;
C:TCirChar;
t:integer;
i:integer;
dr,md:integer;
{основная программа}
begin
dr:=detect;
InitGraph(dr,md,'E:\BP\BGI');
A.Init('a',0.25);
B.Init('b',100,0);
C.Init('c',GetMaxX div 2,GetMaxY div 2,80,0);
t:=0; {условное время движения}
while not KeyPressed and (t<1000) do
begin
A.Move(t); {перерисовываем символы}
B.Move(t);
C.Move(t);
t:=t+1; {увеличиваем условное время движения}
for i:=1 to 1000 do
Delay(1000); {фиксируем кадр}
end;
CloseGraph;
End.
|
unit m3DBActions;
{ Библиотека "M3" }
{ Автор: Люлин А.В. © }
{ Модуль: m3DBActions - }
{ Начат: 21.12.2007 11:19 }
{ $Id: m3DBActions.pas,v 1.3 2009/03/23 11:24:02 lulin Exp $ }
// $Log: m3DBActions.pas,v $
// Revision 1.3 2009/03/23 11:24:02 lulin
// - используем кошерный конструктор индекса потока документа.
//
// Revision 1.2 2008/05/08 14:04:19 fireton
// - перенос объектов в потоках из ветки
//
// Revision 1.1 2007/12/21 08:26:10 lulin
// - функции для построения оберток вынесены в отдельный модуль.
//
{$Include m3Define.inc}
interface
uses
m3DBInterfaces
;
function m3L2DocumentAction(Action: Pointer): Tm3DocumentAction;
{* - делает заглушку для локальной процедуры. }
procedure m3FreeDocumentAction(var Stub: Tm3DocumentAction);
{* - освобождает заглушку для локальной процедуры. }
function m3L2FilerAction(Action: Pointer): Tm3FilerAction;
{* - делает заглушку для локальной процедуры. }
procedure m3FreeFilerAction(var Stub: Tm3FilerAction);
{* - освобождает заглушку для локальной процедуры. }
function m3L2DBStreamAction(Action: Pointer): Tm3DBStreamAction;
{* - делает заглушку для локальной процедуры. }
procedure m3FreeDBStreamAction(var Stub: Tm3DBStreamAction);
{* - освобождает заглушку для локальной процедуры. }
function m3L2DBIndexAction(Action: Pointer): Tm3DBIndexAction;
{* - делает заглушку для локальной процедуры. }
procedure m3FreeDBIndexAction(var Stub: Tm3DBIndexAction);
{* - освобождает заглушку для локальной процедуры. }
implementation
uses
l3Base
;
function m3L2DocumentAction(Action: Pointer): Tm3DocumentAction;
{* - делает заглушку для локальной процедуры. }
register;
asm
jmp l3LocalStub
end;{asm}
procedure m3FreeDocumentAction(var Stub: Tm3DocumentAction);
{* - освобождает заглушку для локальной процедуры. }
register;
asm
jmp l3FreeLocalStub
end;{asm}
function m3L2FilerAction(Action: Pointer): Tm3FilerAction;
{* - делает заглушку для локальной процедуры. }
register;
asm
jmp l3LocalStub
end;{asm}
procedure m3FreeFilerAction(var Stub: Tm3FilerAction);
{* - освобождает заглушку для локальной процедуры. }
register;
asm
jmp l3FreeLocalStub
end;{asm}
function m3L2DBStreamAction(Action: Pointer): Tm3DBStreamAction;
{* - делает заглушку для локальной процедуры. }
register;
asm
jmp l3LocalStub
end;{asm}
procedure m3FreeDBStreamAction(var Stub: Tm3DBStreamAction);
{* - освобождает заглушку для локальной процедуры. }
register;
asm
jmp l3FreeLocalStub
end;{asm}
function m3L2DBIndexAction(Action: Pointer): Tm3DBIndexAction;
{* - делает заглушку для локальной процедуры. }
register;
asm
jmp l3LocalStub
end;{asm}
procedure m3FreeDBIndexAction(var Stub: Tm3DBIndexAction);
{* - освобождает заглушку для локальной процедуры. }
register;
asm
jmp l3FreeLocalStub
end;{asm}
end.
|
unit DirectionUnit;
interface
uses
REST.Json.Types, SysUtils, System.Generics.Collections, Generics.Defaults,
JSONNullableAttributeUnit,
DirectionLocationUnit, DirectionStepUnit, NullableBasicTypesUnit;
type
/// <summary>
/// A course or path on which something is moving or pointing
/// </summary>
/// <remarks>
/// https://github.com/route4me/json-schemas/blob/master/Direction.dtd
/// </remarks>
TDirection = class
private
[JSONName('location')]
[NullableObject(TDirectionLocation)]
FLocation: NullableObject;
[JSONName('steps')]
[NullableArray(TDirectionStep)]
FSteps: TDirectionStepArray;
function GetLocation: TDirectionLocation;
procedure SetLocation(const Value: TDirectionLocation);
public
constructor Create;
destructor Destroy; override;
function Equals(Obj: TObject): Boolean; override;
property Location: TDirectionLocation read GetLocation write SetLocation;
property Steps: TDirectionStepArray read FSteps;
end;
TDirectionArray = TArray<TDirection>;
function SortDirections(Directions: TDirectionArray): TDirectionArray;
implementation
function SortDirections(Directions: TDirectionArray): TDirectionArray;
begin
SetLength(Result, Length(Directions));
if Length(Directions) = 0 then
Exit;
TArray.Copy<TDirection>(Directions, Result, Length(Directions));
TArray.Sort<TDirection>(Result, TComparer<TDirection>.Construct(
function (const Direction1, Direction2: TDirection): Integer
begin
Result := Direction1.Location.CompareTo(Direction2.Location);
end));
end;
{ TDirection }
constructor TDirection.Create;
begin
FLocation := NullableObject.Null;
SetLength(FSteps, 0);
end;
destructor TDirection.Destroy;
var
i: integer;
begin
for i := Length(FSteps) - 1 downto 0 do
FreeAndNil(FSteps[i]);
FLocation.Free;
inherited;
end;
function TDirection.Equals(Obj: TObject): Boolean;
var
Other: TDirection;
i: integer;
SortedSteps1, SortedSteps2: TDirectionStepArray;
begin
Result := False;
if not (Obj is TDirection) then
Exit;
Other := TDirection(Obj);
if (FLocation.IsNull and Other.FLocation.IsNotNull) or
(FLocation.IsNotNull and Other.FLocation.IsNull) then
Exit;
if (Location <> nil) and (Location <> Other.Location) then
Exit;
if (Length(Steps) <> Length(Other.Steps)) then
Exit;
SortedSteps1 := DirectionStepUnit.SortDirectionSteps(Steps);
SortedSteps2 := DirectionStepUnit.SortDirectionSteps(Other.Steps);
for i := 0 to Length(SortedSteps1) - 1 do
if (not SortedSteps1[i].Equals(SortedSteps2[i])) then
Exit;
Result := True;
end;
function TDirection.GetLocation: TDirectionLocation;
begin
if FLocation.IsNull then
Result := nil
else
Result := FLocation.Value as TDirectionLocation;
end;
procedure TDirection.SetLocation(const Value: TDirectionLocation);
begin
FLocation := Value;
end;
end.
|
unit LUX.GPU.Vulkan.Pooler;
interface //#################################################################### ■
uses System.Generics.Collections,
vulkan_core,
LUX.GPU.Vulkan.Comman;
type //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【型】
TVkPoolers<TVkDevice_:class> = class;
TVkPooler<TVkDevice_:class> = class;
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【レコード】
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkPooler
TVkPooler<TVkDevice_:class> = class
private
type TVkPooler_ = TVkPooler<TVkDevice_>;
TVkCommans_ = TVkCommans<TVkPooler_>;
protected
_Device :TVkDevice_;
_Inform :VkCommandPoolCreateInfo;
_Handle :VkCommandPool;
_Commans :TVkCommans_;
///// アクセス
function GetHandle :VkCommandPool;
procedure SetHandle( const Handle_:VkCommandPool );
///// メソッド
procedure CreateHandle;
procedure DestroHandle;
public
constructor Create; overload;
constructor Create( const Device_:TVkDevice_ ); overload;
destructor Destroy; override;
///// プロパティ
property Device :TVkDevice_ read _Device ;
property Inform :VkCommandPoolCreateInfo read _Inform ;
property Handle :VkCommandPool read GetHandle write SetHandle;
property Commans :TVkCommans_ read _Commans ;
end;
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkPoolers
TVkPoolers<TVkDevice_:class> = class( TObjectList<TVkPooler<TVkDevice_>> )
private
type TVkPooler_ = TVkPooler<TVkDevice_>;
protected
_Device :TVkDevice_;
public
constructor Create( const Device_:TVkDevice_ );
destructor Destroy; override;
///// プロパティ
property Device :TVkDevice_ read _Device;
///// メソッド
function Add :TVkPooler_; overload;
end;
//const //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【定数】
//var //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【変数】
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【ルーチン】
implementation //############################################################### ■
uses LUX.GPU.Vulkan;
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【レコード】
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkPooler
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected
/////////////////////////////////////////////////////////////////////// アクセス
function TVkPooler<TVkDevice_>.GetHandle :VkCommandPool;
begin
if _Handle = 0 then CreateHandle;
Result := _Handle;
end;
procedure TVkPooler<TVkDevice_>.SetHandle( const Handle_:VkCommandPool );
begin
if _Handle <> 0 then DestroHandle;
_Handle := Handle_;
end;
/////////////////////////////////////////////////////////////////////// メソッド
procedure TVkPooler<TVkDevice_>.CreateHandle;
begin
Assert( vkCreateCommandPool( TVkDevice( _Device ).Handle, @_Inform, nil, @_Handle ) = VK_SUCCESS );
end;
procedure TVkPooler<TVkDevice_>.DestroHandle;
begin
vkDestroyCommandPool( TVkDevice( _Device ).Handle, _Handle, nil );
end;
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public
constructor TVkPooler<TVkDevice_>.Create;
begin
inherited;
_Handle := 0;
end;
constructor TVkPooler<TVkDevice_>.Create( const Device_:TVkDevice_ );
begin
Create;
_Device := Device_;
TVkDevice( _Device ).Poolers.Add( TVkPooler( Self ) );
with _Inform do
begin
sType := VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
pNext := nil;
queueFamilyIndex := TVkDevice( _Device ).FamilyG;
flags := Ord( VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT );
end;
_Commans := TVkCommans_.Create( Self );
end;
destructor TVkPooler<TVkDevice_>.Destroy;
begin
_Commans.Free;
Handle := 0;
inherited;
end;
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkPoolers
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public
constructor TVkPoolers<TVkDevice_>.Create( const Device_:TVkDevice_ );
begin
inherited Create;
_Device := Device_;
end;
destructor TVkPoolers<TVkDevice_>.Destroy;
begin
inherited;
end;
/////////////////////////////////////////////////////////////////////// メソッド
function TVkPoolers<TVkDevice_>.Add :TVkPooler_;
begin
Result := TVkPooler_.Create( _Device );
end;
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【ルーチン】
//############################################################################## □
initialization //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ 初期化
finalization //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ 最終化
end. //######################################################################### ■ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.