text stringlengths 14 6.51M |
|---|
unit UFrmCadastroCidade;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, UFrmCRUD, Menus, Buttons, StdCtrls, ExtCtrls
,UCidade
,UUTilitarios
,URegraCRUDEstado
,URegraCRUDCidade
;
type
TFrmCadastroCidade = class(TFrmCRUD)
gbInformacoes: TGroupBox;
lbCodigoPais: TLabel;
edNome: TLabeledEdit;
btnLocalizarEstado: TButton;
edEstado: TEdit;
stNomeEstado: TStaticText;
procedure btnLocalizarEstadoClick(Sender: TObject);
procedure edEstadoExit(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
protected
FCIDADE: TCIDADE;
FRegraCRUDCidade: TRegraCRUDCidade;
FregraCRUDEstado: TRegraCRUDEstado;
procedure Inicializa; override;
procedure Finaliza; override;
procedure PreencheEntidade; override;
procedure PreencheFormulario; override;
procedure PosicionaCursorPrimeiroCampo; override;
procedure HabilitaCampos(const ceTipoOperacaoUsuario: TTipoOperacaoUsuario); override;
end;
var
FrmCadastroCidade: TFrmCadastroCidade;
implementation
uses
UOpcaoPesquisa
, UEntidade
, UFrmPesquisa
, UEstado
, UDialogo
;
{$R *.dfm}
procedure TFrmCadastroCidade.btnLocalizarEstadoClick(Sender: TObject);
begin
edEstado.Text := TfrmPesquisa.MostrarPesquisa(TOpcaoPesquisa
.Create
.DefineVisao(VW_ESTADO)
.DefineNomeCampoRetorno(VW_ESTADO_ID)
.DefineNomePesquisa(STR_ESTADO)
.AdicionaFiltro(VW_ESTADO_NOME));
if Trim(edEstado.Text) <> EmptyStr then
edEstado.OnExit(btnLocalizarEstado);
end;
procedure TFrmCadastroCidade.edEstadoExit(Sender: TObject);
begin
stNomeEstado.Caption := EmptyStr;
if Trim(edEstado.Text) <> EmptyStr then
try
FregraCRUDEstado.ValidaExistencia(StrToIntDef(edEstado.Text, 0));
FCIDADE.ESTADO := TESTADO(
FregraCRUDEstado.Retorna(StrToIntDef(edEstado.Text, 0)));
stNomeEstado.Caption := FCIDADE.ESTADO.NOME;
except
on E: Exception do
begin
TDialogo.Excecao(E);
edEstado.SetFocus;
end;
end;
end;
procedure TFrmCadastroCidade.Finaliza;
begin
inherited;
FreeAndNil(FregraCRUDEstado);
end;
procedure TFrmCadastroCidade.HabilitaCampos(
const ceTipoOperacaoUsuario: TTipoOperacaoUsuario);
begin
inherited;
gbInformacoes.Enabled := FTipoOperacaoUsuario In [touInsercao, touAtualizacao];
end;
procedure TFrmCadastroCidade.Inicializa;
begin
inherited;
DefineEntidade(@FCIDADE, TCIDADE);
DefineRegraCRUD(@FRegraCRUDCidade, TRegraCRUDCidade);
AdicionaOpcaoPesquisa(TOpcaoPesquisa
.Create
.AdicionaFiltro(FLD_CIDADE_NOME)
.DefineNomeCampoRetorno(FLD_ENTIDADE_ID)
.DefineNomePesquisa(STR_CIDADE)
.DefineVisao(TBL_CIDADE));
FregraCRUDEstado := TRegraCRUDEstado.Create;
end;
procedure TFrmCadastroCidade.PosicionaCursorPrimeiroCampo;
begin
inherited;
edNome.SetFocus;
end;
procedure TFrmCadastroCidade.PreencheEntidade;
begin
inherited;
FCIDADE.NOME := edNome.Text;
end;
procedure TFrmCadastroCidade.PreencheFormulario;
begin
inherited;
edNome.Text := FCIDADE.NOME;
edEstado.Text := IntToStr(FCIDADE.ESTADO.ID);
stNomeEstado.Caption := FCIDADE.ESTADO.NOME;
end;
end.
|
unit Geo.Utils;
interface
uses
Geo.Calcs, Geo.Pos, clipper;
type
TGeoUtils = class
public
class function ExpandPolygonBy(var AZone: TGeoPosArray; const ARadius: Double): Boolean;
end;
implementation
class function TGeoUtils.ExpandPolygonBy(var AZone: TGeoPosArray; const ARadius: Double): Boolean;
var
i, l, k, z: Integer;
GeoPos, GeoPos2: TGeoPos;
CPos: TCartesianPos;
DZone: TPath;
RZones: TPaths;
begin
if ARadius <= 0 then
Exit(True);
Result := False;
try
l := Length(AZone);
SetLength(DZone, l);
for i := 0 to l - 1 do
begin
GeoPos2 := GeoPos;
GeoPos := AZone[i];
if i > 0 then
TGeoCalcs.CastGeoCoordinates2(GeoPos2, GeoPos);
CPos := GeoPos.ToCartesianPos(0);
DZone[i].X := Round(CPos.X);
DZone[i].Y := Round(CPos.Y);
end;
with TClipperOffset.Create() do
try
AddPath(DZone, jtSquare, etClosedPolygon);
Execute(RZones, ARadius);
finally
Free;
end;
if Length(RZones) > 0 then
begin
Result := True;
z := 0;
l := 0;
for k := 0 to Length(RZones) - 1 do
if Length(RZones[k]) > l then
begin
z := k;
l := Length(RZones[k]);
end;
l := Length(RZones[0]);
SetLength(AZone, l);
for i := 0 to l - 1 do
AZone[i] := TGeoPos.Create(TCartesianPos.Create(RZones[z][i].X, RZones[z][i].Y));
end;
finally
DZone := nil;
RZones := nil;
end;
end;
end.
|
unit EstoqueFactory.Controller;
interface
uses EstoqueFactory.Controller.interf, Produto.Controller.interf,
ImportarProduto.Controller.interf, Orcamento.Controller.interf,
ExportarOrcamento.Controller.interf;
type
TEstoqueFactory = class(TInterfacedObject, IEstoqueFactoryController)
private
public
constructor Create;
destructor Destroy; override;
class function New: IEstoqueFactoryController;
function Produto: IProdutoController;
function ImportarProduto: IImportarProdutoController;
function Orcamento: IOrcamentoController;
function ExportarOrcamento: IExportarOrcamento;
end;
implementation
{ TEstoqueFactory }
uses Produto.Controller, ImportarProduto.Controller, Orcamento.Controller,
ExportarOrcamento.Controller;
constructor TEstoqueFactory.Create;
begin
end;
destructor TEstoqueFactory.Destroy;
begin
inherited;
end;
function TEstoqueFactory.ExportarOrcamento: IExportarOrcamento;
begin
Result := TExportarOrcamento.New;
end;
function TEstoqueFactory.ImportarProduto: IImportarProdutoController;
begin
Result := TImportarProdutoController.New;
end;
class function TEstoqueFactory.New: IEstoqueFactoryController;
begin
Result := Self.Create;
end;
function TEstoqueFactory.Orcamento: IOrcamentoController;
begin
Result := TOrcamentoController.New;
end;
function TEstoqueFactory.Produto: IProdutoController;
begin
Result := TProdutoController.New;
end;
end.
|
{*******************************************************************************
Title: iTEC-SOFTWARE
Description: VO relational the table [RECEBIMENTO_CONTA]
The MIT License
Copyright: Copyright (C) 2010 www.itecsoftware.com.br
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, sub license, 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.
The author may be contacted at:
william@itecsoftware.com.br
@author William (william_mk@hotmail.com)
@version 1.0
*******************************************************************************}
unit RecebimentoContaVO;
interface
uses
VO, Atributos, Classes, Constantes, Generics.Collections, SysUtils,
RecebimentoContaParcelaVO, RecebimentoContaRecebimentoVO, CartaoRecebimentoVO;
type
[TEntity]
[TTable('RECEBIMENTO_CONTA')]
TRecebimentoContaVO = class(TVO)
private
FID: Integer;
FID_MOVIMENTO: Integer;
FID_PESSOA: Integer;
FID_AUTORIZOU_DESCONTO: Integer;
FLANCAMENTO: TDateTime;
FVALOR: Extended;
FTAXA_DESCONTO: Extended;
FDESCONTO: Extended;
FTOTAL: Extended;
FRECEBIDO: Extended;
FTROCO: Extended;
FSINCRONIZADO: String;
FPARCELAS: TObjectList<TRecebimentoContaParcelaVO>;
FRECEBIMENTOS: TObjectList<TRecebimentoContaRecebimentoVO>;
FCARTAORECEBIMENTOS: TObjectList<TCartaoRecebimentoVO>;
public
constructor Create; overload; override;
destructor Destroy; override;
[TId('ID')]
[TGeneratedValue(sAuto)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property Id: Integer read FID write FID;
[TColumn('ID_MOVIMENTO','Id Movimento',80,[ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property IdMovimento: Integer read FID_MOVIMENTO write FID_MOVIMENTO;
[TColumn('ID_PESSOA','Id Pessoa',80,[ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property IdPessoa: Integer read FID_PESSOA write FID_PESSOA;
[TColumn('ID_AUTORIZOU_DESCONTO','Id Autorizou Desconto',80,[ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property IdAutorizouDesconto: Integer read FID_AUTORIZOU_DESCONTO write FID_AUTORIZOU_DESCONTO;
[TColumn('LANCAMENTO','Lancamento',272,[ldGrid, ldLookup, ldCombobox], False)]
property Lancamento: TDateTime read FLANCAMENTO write FLANCAMENTO;
[TColumn('VALOR','Valor',128,[ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftFloatComSeparador, taRightJustify)]
property Valor: Extended read FVALOR write FVALOR;
[TColumn('TAXA_DESCONTO','Taxa Desconto',128,[ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftFloatComSeparador, taRightJustify)]
property TaxaDesconto: Extended read FTAXA_DESCONTO write FTAXA_DESCONTO;
[TColumn('DESCONTO','Desconto',128,[ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftFloatComSeparador, taRightJustify)]
property Desconto: Extended read FDESCONTO write FDESCONTO;
[TColumn('TOTAL','Total',128,[ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftFloatComSeparador, taRightJustify)]
property Total: Extended read FTOTAL write FTOTAL;
[TColumn('RECEBIDO','Recebido',128,[ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftFloatComSeparador, taRightJustify)]
property Recebido: Extended read FRECEBIDO write FRECEBIDO;
[TColumn('TROCO','Troco',128,[ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftFloatComSeparador, taRightJustify)]
property Troco: Extended read FTROCO write FTROCO;
[TColumn('SINCRONIZADO','Sincronizado',8,[ldGrid, ldLookup, ldCombobox], False)]
property Sincronizado: String read FSINCRONIZADO write FSINCRONIZADO;
[TManyValuedAssociation(False, 'ID_RECEBIMENTO_CONTA', 'ID','RECEBIMENTO_CONTA_PARCELA')]
property Parcelas: TObjectList<TRecebimentoContaParcelaVO> read FPARCELAS write FPARCELAS;
[TManyValuedAssociation(False, 'ID_RECEBIMENTO_CONTA', 'ID','RECEBIMENTO_CONTA_RECEBIMENTO')]
property Recebimentos: TObjectList<TRecebimentoContaRecebimentoVO> read FRECEBIMENTOS write FRECEBIMENTOS;
[TManyValuedAssociation(False, 'ID_RECEBIMENTO_CONTA', 'ID','CARTAO_RECEBIMENTO')]
property CartaoRecebimentos: TObjectList<TCartaoRecebimentoVO> read FCARTAORECEBIMENTOS write FCARTAORECEBIMENTOS;
end;
implementation
{ TRecebimentoContaVO }
constructor TRecebimentoContaVO.Create;
begin
inherited;
Parcelas:= TObjectList<TRecebimentoContaParcelaVO>.Create;
Recebimentos:= TObjectList<TRecebimentoContaRecebimentoVO>.Create;
CartaoRecebimentos:= TObjectList<TCartaoRecebimentoVO>.Create;
end;
destructor TRecebimentoContaVO.Destroy;
begin
Parcelas.Free;
Recebimentos.Free;
CartaoRecebimentos.Free;
inherited;
end;
end.
|
unit uFrmPessoaHistoryTypeResult;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, PAIDETODOS, siComp, siLangRT, StdCtrls, LblEffct, ExtCtrls,
ADODB;
type
TFrmPessoaHistoryTypeResult = class(TFrmParent)
btnSave: TButton;
Label1: TLabel;
edtResult: TEdit;
lbHasBairro: TLabel;
Label2: TLabel;
pnlMenuHighlight: TPanel;
CD: TColorDialog;
cmdInsResult: TADOCommand;
procedure pnlMenuHighlightClick(Sender: TObject);
procedure btnSaveClick(Sender: TObject);
private
FIDPessoaHistoryType : Integer;
function ValidateResult : Boolean;
procedure InsertResult;
public
function Start(IDPessoaHistoryType : Integer) : Boolean;
end;
implementation
uses uDM, uMsgBox, uMsgConstant;
{$R *.dfm}
{ TFrmPessoaHistoryTypeResult }
function TFrmPessoaHistoryTypeResult.Start(IDPessoaHistoryType : Integer): Boolean;
begin
FIDPessoaHistoryType := IDPessoaHistoryType;
ShowModal;
Result := True;
end;
procedure TFrmPessoaHistoryTypeResult.pnlMenuHighlightClick(
Sender: TObject);
begin
inherited;
CD.Color := TPanel(Sender).Color;
if CD.Execute then
TPanel(Sender).Color := CD.Color;
end;
procedure TFrmPessoaHistoryTypeResult.InsertResult;
begin
with cmdInsResult do
begin
Parameters.ParamByName('IDPessoaHistoryResult').Value := DM.GetNextID('Mnt_PessoaHistoryResult.IDPessoaHistoryResult');
Parameters.ParamByName('IDPessoaHistoryType').Value := FIDPessoaHistoryType;
Parameters.ParamByName('PessoaHistoryResult').Value := edtResult.Text;
Parameters.ParamByName('ResultColor').Value := ColorToString(pnlMenuHighlight.Color);
Execute;
end;
end;
function TFrmPessoaHistoryTypeResult.ValidateResult: Boolean;
begin
Result := True;
if Trim(edtResult.Text) = '' then
begin
MsgBox(MSG_CRT_NOT_RESULT_TYPE, vbCritical + vbOkOnly);
Result := False;
Exit;
end;
end;
procedure TFrmPessoaHistoryTypeResult.btnSaveClick(Sender: TObject);
begin
inherited;
if ValidateResult then
begin
InsertResult;
Close;
end;
end;
end.
|
(*
The Computer Language Benchmarks Game
http://benchmarksgame.alioth.debian.org/
contributed by Vitaly Trifonof based on a contribution of Ales Katona
*reset*
*)
program BinaryTrees;
type
PNode = ^TNode;
TNode = record
l, r: PNode;
end;
function CreateNode(l2, r2: PNode): PNode; inline;
begin
CreateNode := GetMem(SizeOf(TNode));
CreateNode^.l:=l2;
CreateNode^.r:=r2;
end;
(* Destroy node and it subnodes in one procedure *)
procedure DestroyNode(ANode: PNode); inline;
var
LNode, RNode: PNode;
begin
LNode := ANode^.l;
if LNode <> nil then
begin
RNode := ANode^.r;
if LNode^.l <> nil then
begin
DestroyNode(LNode^.l);
DestroyNode(LNode^.r);
FreeMem(LNode, SizeOf(TNode));
DestroyNode(RNode^.l);
DestroyNode(RNode^.r);
FreeMem(RNode, SizeOf(TNode));
end
else
begin
DestroyNode(LNode);
DestroyNode(RNode);
end
end;
FreeMem(ANode, SizeOf(TNode));
end;
(* Left subnodes check in cycle, right recursive *)
function CheckNode(ANode: PNode): Longint; inline;
begin
CheckNode := 0;
while ANode^.l <> nil do
begin
CheckNode += 1 + CheckNode(ANode^.r);
ANode := ANode^.l
end;
CheckNode += 1;
end;
(*
Create node and it subnodes in one function
make(1,a)=(2I-1)=Ia make(2,Ia-1)=(2(2I-1)-1)=(4I-3)
make(2,Ia) =(2(2I-1)) =(4I-2)
make(1,b)=(2I)=Ib make(2,Ib-1)=(2(2I)-1) =(4I-1)
make(2,Ib) =(2(2I)) =(4I)
*)
function Make(d: Longint): PNode;
var
fi: Longint;
begin
case d of
0: Make:=CreateNode(nil, nil);
1: Make:=CreateNode(CreateNode(nil, nil), CreateNode(nil, nil));
else
d -= 2;
Make:=CreateNode(
CreateNode( Make(d),Make(d) ),
CreateNode( Make(d),Make(d) )
)
end
end;
const
mind = 4;
var
maxd : Longint = 10;
strd,
iter,
c, d, i : Longint;
tree, llt : PNode;
begin
if ParamCount = 1 then
Val(ParamStr(1), maxd);
if maxd < mind+2 then
maxd := mind + 2;
strd:=maxd + 1;
tree:=Make(strd);
Writeln('stretch tree of depth ', strd, #9' check: ', CheckNode(tree));
DestroyNode(tree);
llt:=Make(maxd);
d:=mind;
while d <= maxd do begin
iter:=1 shl (maxd - d + mind);
c:=0;
for i:=1 to Iter do begin
tree:=Make(d);
c:=c + CheckNode(tree);
DestroyNode(tree);
end;
Writeln(Iter, #9' trees of depth ', d, #9' check: ', c);
Inc(d, 2);
end;
Writeln('long lived tree of depth ', maxd, #9' check: ', CheckNode(llt));
DestroyNode(llt);
end. |
//
// VXScene Component Library, based on GLScene http://glscene.sourceforge.net
//
{
A plane simulating animated water
The Original Code is part of Cosmos4D
http://users.hol.gr/~sternas/
Sternas Stefanos 2003
}
unit VXS.WaterPlane;
interface
{$I VXScene.inc}
uses
System.Classes,
FMX.Objects,
FMX.Types,
FMX.Graphics,
VXS.OpenGL,
VXS.VectorGeometry,
VXS.Scene,
VXS.VectorLists,
VXS.CrossPlatform,
VXS.PersistentClasses,
VXS.BaseClasses,
VXS.Context,
VXS.RenderContextInfo,
VXS.VectorTypes;
type
TVXWaterPlaneOption = (wpoTextured);
TVXWaterPlaneOptions = set of TVXWaterPlaneOption;
const
cDefaultWaterPlaneOptions = [wpoTextured];
type
TVXWaterPlane = class(TVXSceneObject)
private
FLocks: packed array of ByteBool;
FPositions, FVelocity: packed array of Single;
FPlaneQuadIndices: TPersistentObjectList;
FPlaneQuadTexCoords: TTexPointList;
FPlaneQuadVertices: TAffineVectorList;
FPlaneQuadNormals: TAffineVectorList;
FActive: Boolean;
FRainTimeInterval: Integer;
FRainForce: Single;
FViscosity: Single;
FElastic: Single;
FResolution: Integer;
FSimulationFrequency, FTimeToNextUpdate: Single;
FTimeToNextRainDrop: Single;
FMaximumCatchupIterations: Integer;
FLastIterationStepTime: Single;
FMask: TImage;
FOptions: TVXWaterPlaneOptions;
protected
procedure SetElastic(const value: Single);
procedure SetResolution(const value: Integer);
procedure SetRainTimeInterval(const val: Integer);
procedure SetViscosity(const val: Single);
procedure SetRainForce(const val: Single);
procedure SetSimulationFrequency(const val: Single);
procedure SetMask(val: TImage);
procedure SetOptions(const val: TVXWaterPlaneOptions);
procedure DoMaskChanged(Sender: TObject);
procedure InitResolution;
procedure IterComputeVelocity;
procedure IterComputePositions;
procedure IterComputeNormals;
procedure Iterate;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure DoProgress(const progressTime: TVXProgressTimes); override;
procedure BuildList(var rci: TVXRenderContextInfo); override;
procedure Assign(Source: TPersistent); override;
function AxisAlignedDimensionsUnscaled: TVector; override;
procedure CreateRippleAtGridPos(X, Y: Integer);
procedure CreateRippleAtWorldPos(const X, Y, z: Single); overload;
procedure CreateRippleAtWorldPos(const pos: TVector); overload;
procedure CreateRippleRandom;
procedure Reset;
{ CPU time (in seconds) taken by the last iteration step. }
property LastIterationStepTime: Single read FLastIterationStepTime;
published
property Active: Boolean read FActive write FActive default True;
{ Delay between raindrops in milliseconds (0 = no rain) }
property RainTimeInterval: Integer read FRainTimeInterval
write SetRainTimeInterval default 500;
property RainForce: Single read FRainForce write SetRainForce;
property Viscosity: Single read FViscosity write SetViscosity;
property Elastic: Single read FElastic write SetElastic;
property Resolution: Integer read FResolution write SetResolution
default 64;
property Options: TVXWaterPlaneOptions read FOptions write SetOptions
default cDefaultWaterPlaneOptions;
{ A picture whose pixels determine what part of the waterplane is active.
Pixels with a green/gray component beyond 128 are active, the others
are not (in short, white = active, black = inactive).
The picture will automatically be stretched to match the resolution. }
property Mask: TImage read FMask write SetMask;
{ Maximum frequency (in Hz) at which simulation iterations happen. }
property SimulationFrequency: Single read FSimulationFrequency
write SetSimulationFrequency;
{ Maximum number of simulation iterations during catchups.
Catchups happen when for a reason or another, the DoProgress doesn't
happen as fast SimulationFrequency. }
property MaximumCatchupIterations: Integer read FMaximumCatchupIterations
write FMaximumCatchupIterations default 1;
end;
// -------------------------------------------------------------
implementation
// -------------------------------------------------------------
constructor TVXWaterPlane.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
ObjectStyle := ObjectStyle + [osDirectDraw];
FElastic := 10;
FActive := True;
FRainTimeInterval := 500;
FRainForce := 5000;
FViscosity := 0.99;
FSimulationFrequency := 100; // 100 Hz
FMaximumCatchupIterations := 1;
FOptions := cDefaultWaterPlaneOptions;
FPlaneQuadIndices := TPersistentObjectList.Create;
FPlaneQuadTexCoords := TTexPointList.Create;
FPlaneQuadVertices := TAffineVectorList.Create;
FPlaneQuadNormals := TAffineVectorList.Create;
FMask := TImage.Create(AOwner);
FMask.Bitmap.OnChange := DoMaskChanged;
SetResolution(64);
end;
destructor TVXWaterPlane.Destroy;
begin
FMask.Free;
FPlaneQuadNormals.Free;
FPlaneQuadVertices.Free;
FPlaneQuadTexCoords.Free;
FPlaneQuadIndices.CleanFree;
inherited;
end;
procedure TVXWaterPlane.DoProgress(const progressTime: TVXProgressTimes);
var
i: Integer;
begin
inherited;
if Active and Visible then
begin
// new raindrops
if FRainTimeInterval > 0 then
begin
FTimeToNextRainDrop := FTimeToNextRainDrop - progressTime.deltaTime;
i := FMaximumCatchupIterations;
while FTimeToNextRainDrop <= 0 do
begin
CreateRippleRandom;
FTimeToNextRainDrop := FTimeToNextRainDrop + FRainTimeInterval * 0.001;
Dec(i);
if i < 0 then
begin
if FTimeToNextRainDrop < 0 then
FTimeToNextRainDrop := FRainTimeInterval * 0.001;
Break;
end;
end;
end;
// iterate simulation
FTimeToNextUpdate := FTimeToNextUpdate - progressTime.deltaTime;
if FTimeToNextUpdate <= 0 then
begin
i := FMaximumCatchupIterations;
while FTimeToNextUpdate <= 0 do
begin
Iterate;
FTimeToNextUpdate := FTimeToNextUpdate + 1 / FSimulationFrequency;
Dec(i);
if i < 0 then
begin
if FTimeToNextUpdate < 0 then
FTimeToNextUpdate := 1 / FSimulationFrequency;
Break;
end;
end;
StructureChanged;
end;
end;
end;
procedure TVXWaterPlane.CreateRippleAtGridPos(X, Y: Integer);
begin
if (X > 0) and (Y > 0) and (X < Resolution - 1) and (Y < Resolution - 1) then
FVelocity[X + Y * Resolution] := FRainForce;
end;
procedure TVXWaterPlane.CreateRippleAtWorldPos(const X, Y, z: Single);
var
vv: TVector;
begin
vv := AbsoluteToLocal(PointMake(X, Y, z));
CreateRippleAtGridPos(Round((vv.X + 0.5) * Resolution),
Round((vv.z + 0.5) * Resolution));
end;
procedure TVXWaterPlane.CreateRippleAtWorldPos(const pos: TVector);
var
vv: TVector;
begin
vv := AbsoluteToLocal(PointMake(pos));
CreateRippleAtGridPos(Round((vv.X + 0.5) * Resolution),
Round((vv.z + 0.5) * Resolution));
end;
procedure TVXWaterPlane.CreateRippleRandom;
begin
CreateRippleAtGridPos(Random(Resolution - 3) + 2, Random(Resolution - 3) + 2);
end;
procedure TVXWaterPlane.InitResolution;
var
i, j: Integer;
v: TAffineVector;
resSqr: Integer;
invResol: Single;
begin
resSqr := FResolution * FResolution;
FPlaneQuadIndices.Capacity := resSqr * 2;
FPlaneQuadTexCoords.Clear;
FPlaneQuadTexCoords.Capacity := resSqr;
FPlaneQuadVertices.Clear;
FPlaneQuadVertices.Capacity := resSqr;
invResol := 1 / Resolution;
for j := 0 to Resolution - 1 do
begin
for i := 0 to Resolution - 1 do
begin
FPlaneQuadTexCoords.Add(i * invResol, j * invResol);
FPlaneQuadVertices.Add((i - Resolution * 0.5) * invResol, 0,
(j - Resolution * 0.5) * invResol);
end;
end;
FPlaneQuadNormals.Count := resSqr;
v.X := 0;
v.Y := 2048;
v.z := 0;
for i := 0 to FPlaneQuadNormals.Count - 1 do
FPlaneQuadNormals.List[i] := v;
SetLength(FPositions, resSqr);
SetLength(FVelocity, resSqr);
SetLength(FLocks, resSqr);
Reset;
Iterate;
StructureChanged;
end;
procedure TVXWaterPlane.Reset;
var
i, j, ij, resSqr: Integer;
maskBmp: TBitmap;
scanLine: PIntegerArray;
il: TIntegerList;
locked: Boolean;
begin
resSqr := FResolution * FResolution;
for i := 0 to resSqr - 1 do
begin
FPositions[i] := 0;
FVelocity[i] := 0;
FLocks[i] := False;
end;
if FMask.Width > 0 then
begin
maskBmp := TBitmap.Create;
try
{ TODO : E2129 Cannot assign to a read-only property }
(* maskBmp.PixelFormat:= TPixelFormat.RGBA32F; //in VCL glpf32bit; *)
maskBmp.Width := Resolution;
maskBmp.Height := Resolution;
{ TODO : E2003 Undeclared identifier: 'StretchDraw' }
(* maskBmp.Canvas.StretchDraw(Rect(0, 0, Resolution, Resolution), FMask.Graphic); *)
for j := 0 to Resolution - 1 do
begin
scanLine := BitmapScanLine(maskBmp, Resolution - 1 - j);
// maskBmp.ScanLine[Resolution-1-j];
for i := 0 to Resolution - 1 do
FLocks[i + j * Resolution] := (((scanLine[i] shr 8) and $FF) < 128);
end;
finally
maskBmp.Free;
end;
end;
FPlaneQuadIndices.Clean;
for j := 0 to Resolution - 2 do
begin
il := TIntegerList.Create;
for i := 0 to Resolution - 1 do
begin
ij := i + j * Resolution;
if (il.Count and 2) <> 0 then
locked := False
else
begin
locked := FLocks[ij] and FLocks[ij + Resolution];
if locked and (i < Resolution - 1) then
locked := FLocks[ij + 1] and FLocks[ij + Resolution + 1];
end;
if not locked then
il.Add(ij, ij + Resolution)
else if il.Count > 0 then
begin
FPlaneQuadIndices.Add(il);
il := TIntegerList.Create;
end;
end;
if il.Count > 0 then
FPlaneQuadIndices.Add(il)
else
il.Free;
end;
end;
procedure TVXWaterPlane.IterComputeVelocity;
var
i, j, ij: Integer;
f1, f2: Single;
posList, velList: PSingleArray;
lockList: PByteArray;
begin
f1 := 0.05;
f2 := 0.01 * FElastic;
posList := @FPositions[0];
velList := @FVelocity[0];
lockList := @FLocks[0];
for i := 1 to Resolution - 2 do
begin
ij := i * Resolution;
for j := 1 to Resolution - 2 do
begin
Inc(ij);
if lockList[ij] <> 0 then
continue;
velList[ij] := velList[ij] + f2 *
(posList[ij] - f1 * (4 * (posList[ij - 1] + posList[ij + 1] +
posList[ij - Resolution] + posList[ij + Resolution]) +
posList[ij - 1 - Resolution] + posList[ij + 1 - Resolution] +
posList[ij - 1 + Resolution] + posList[ij + 1 + Resolution]));
end;
end;
end;
procedure TVXWaterPlane.IterComputePositions;
const
cVelocityIntegrationCoeff: Single = 0.02;
cHeightFactor: Single = 1E-4;
var
ij: Integer;
f: Single;
coeff: Single;
posList, velList: PSingleArray;
lockList: PByteArray;
begin
// Calculate the new ripple positions and update vertex coordinates
coeff := cVelocityIntegrationCoeff * Resolution;
f := cHeightFactor / Resolution;
posList := @FPositions[0];
velList := @FVelocity[0];
lockList := @FLocks[0];
for ij := 0 to Resolution * Resolution - 1 do
begin
if lockList[ij] = 0 then
begin
posList[ij] := posList[ij] - coeff * velList[ij];
velList[ij] := velList[ij] * FViscosity;
FPlaneQuadVertices.List[ij].Y := posList[ij] * f;
end;
end;
end;
procedure TVXWaterPlane.IterComputeNormals;
var
i, j, ij: Integer;
pv: PAffineVector;
posList: PSingleArray;
normList: PAffineVectorArray;
begin
// Calculate the new vertex normals (not normalized, the hardware will handle that)
posList := @FPositions[0];
normList := FPlaneQuadNormals.List;
for i := 1 to Resolution - 2 do
begin
ij := i * Resolution;
for j := 1 to Resolution - 2 do
begin
Inc(ij);
pv := @normList[ij];
pv.X := posList[ij + 1] - posList[ij - 1];
pv.z := posList[ij + Resolution] - posList[ij - Resolution];
end;
end;
end;
procedure TVXWaterPlane.Iterate;
var
t: Int64;
begin
if Visible then
begin
t := StartPrecisionTimer;
IterComputeVelocity;
IterComputePositions;
IterComputeNormals;
FLastIterationStepTime := StopPrecisionTimer(t);
end;
end;
procedure TVXWaterPlane.BuildList(var rci: TVXRenderContextInfo);
var
i: Integer;
il: TIntegerList;
begin
glPushClientAttrib(GL_CLIENT_VERTEX_ARRAY_BIT);
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3, GL_FLOAT, 0, FPlaneQuadVertices.List);
glEnableClientState(GL_NORMAL_ARRAY);
glNormalPointer(GL_FLOAT, 0, FPlaneQuadNormals.List);
if wpoTextured in Options then
begin
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glTexCoordPointer(2, GL_FLOAT, 0, FPlaneQuadTexCoords.List);
end
else
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
if GL_EXT_compiled_vertex_array then
glLockArraysEXT(0, FPlaneQuadVertices.Count);
for i := 0 to FPlaneQuadIndices.Count - 1 do
begin
il := TIntegerList(FPlaneQuadIndices[i]);
glDrawElements(GL_QUAD_STRIP, il.Count, GL_UNSIGNED_INT, il.List);
end;
if GL_EXT_compiled_vertex_array then
glUnlockArraysEXT;
glPopClientAttrib;
end;
procedure TVXWaterPlane.Assign(Source: TPersistent);
begin
if Assigned(Source) and (Source is TVXWaterPlane) then
begin
Active := TVXWaterPlane(Source).Active;
RainTimeInterval := TVXWaterPlane(Source).RainTimeInterval;
RainForce := TVXWaterPlane(Source).RainForce;
Viscosity := TVXWaterPlane(Source).Viscosity;
end;
inherited Assign(Source);
end;
function TVXWaterPlane.AxisAlignedDimensionsUnscaled: TVector;
begin
Result.X := 0.5 * Abs(Resolution);
Result.Y := 0;
Result.z := 0.5 * Abs(FResolution);
end;
procedure TVXWaterPlane.SetElastic(const value: Single);
begin
FElastic := value;
end;
procedure TVXWaterPlane.SetResolution(const value: Integer);
begin
if value <> FResolution then
begin
FResolution := value;
if FResolution < 16 then
FResolution := 16;
InitResolution;
end;
end;
procedure TVXWaterPlane.SetRainTimeInterval(Const val: Integer);
begin
if (val >= 0) and (val <= 1000000) then
FRainTimeInterval := val;
end;
Procedure TVXWaterPlane.SetViscosity(const val: Single);
begin
if (val >= 0) and (val <= 1) then
FViscosity := val;
end;
procedure TVXWaterPlane.SetRainForce(const val: Single);
begin
if (val >= 0) and (val <= 1000000) then
FRainForce := val;
end;
procedure TVXWaterPlane.SetSimulationFrequency(const val: Single);
begin
if FSimulationFrequency <> val then
begin
FSimulationFrequency := val;
if FSimulationFrequency < 1 then
FSimulationFrequency := 1;
FTimeToNextUpdate := 0;
end;
end;
procedure TVXWaterPlane.SetMask(val: TImage);
begin
FMask.Assign(val);
end;
procedure TVXWaterPlane.DoMaskChanged(Sender: TObject);
begin
Reset;
StructureChanged;
end;
procedure TVXWaterPlane.SetOptions(const val: TVXWaterPlaneOptions);
begin
if FOptions <> val then
begin
FOptions := val;
StructureChanged;
end;
end;
// -------------------------------------------------------------
initialization
// -------------------------------------------------------------
RegisterClasses([TVXWaterPlane]);
end.
|
Unit USrv;
interface
uses Windows, Classes, Graphics, Controls, Messages, Dialogs,
SysUtils;
const WM_GETIMAGE = WM_USER + $0429;
function BitmapToRegion(Bitmap: TBitmap): HRGN;
function CopyToBitmap(Control: TControl; Bitmap: TBitmap; Anyway: boolean): boolean;
procedure CopyParentImage(Control: TControl; Dest: TCanvas);
procedure RestoreImage(DestDC: HDC; SrcBitmap: TBitmap; r: TRect;
dwROP: dword); overload;
procedure RestoreImage(DestDC: HDC; SrcBitmap: TBitmap; l, t, w, h: integer;
dwROP: dword); overload;
procedure AjustBitmap(const M: TBitmap; S, C: TColor);
procedure FadeBitmap(const M: TBitmap; C: TColor; D: byte);
function IncColor(C: TColor; D: integer): TColor;
implementation
function BitmapToRegion(Bitmap: TBitmap): HRGN;
var
X, Y: Integer;
XStart: Integer;
TransC: TColor;
R: HRGN;
begin
Result := 0;
with Bitmap do begin
TransC := Canvas.Pixels[0, 0];
for Y := 0 to Height - 1 do begin
X := 0;
while X < Width do begin
while (X < Width) and (Canvas.Pixels[X, Y] = TransC) do Inc(X);
if X >= Width then Break;
XStart := X;
while (X < Width) and (Canvas.Pixels[X, Y] <> TransC) do Inc(X);
R := CreateRectRgn(XStart, Y, X, Y + 1);
if Result = 0 then Result := R
else begin
CombineRgn(Result, Result, R, RGN_OR);
DeleteObject(R);
end;
end;
end;
end;
end;
function CopyToBitmap;
var x, y: integer;
begin
Result := False;
if Control = nil then exit;
x := BitMap.Width - 2;
y := BitMap.Height - 2;
if (Anyway) or
(x + 2 <> Control.Width) or
(y + 2 <> Control.Height) or
(BitMap.Canvas.Pixels[x, y] = $FFFFFF) or
(BitMap.Canvas.Pixels[x, y] = $000000) then begin
BitMap.Width := Control.Width;
BitMap.Height := Control.Height;
CopyParentImage(Control, BitMap.Canvas);
Result := True;
end;
end;
type
TParentControl = class(TWinControl);
procedure CopyParentImage(Control: TControl; Dest: TCanvas);
var
I, Count, X, Y, SaveIndex: Integer;
DC: HDC;
R, SelfR, CtlR: TRect;
begin
if (Control = nil) or (Control.Parent = nil) then Exit;
Count := Control.Parent.ControlCount;
DC := Dest.Handle;
with Control.Parent do ControlState := ControlState + [csPaintCopy];
try
with Control do begin
SelfR := Bounds(Left, Top, Width, Height);
X := -Left; Y := -Top;
end;
{ Copy parent control image }
SaveIndex := SaveDC(DC);
try
if TParentControl(Control.Parent).Perform(
WM_GETIMAGE, DC, integer(@SelfR)) <> $29041961 then begin
SetViewportOrgEx(DC, X, Y, nil);
IntersectClipRect(DC, 0, 0, Control.Parent.ClientWidth,
Control.Parent.ClientHeight);
with TParentControl(Control.Parent) do begin
Perform(WM_ERASEBKGND, DC, 0);
PaintWindow(DC);
end;
end;
finally
RestoreDC(DC, SaveIndex);
end;
{ Copy images of graphic controls }
for I := 0 to Count - 1 do begin
if Control.Parent.Controls[I] = Control then continue
else if (Control.Parent.Controls[I] <> nil) and
(Control.Parent.Controls[I] is TGraphicControl) then
begin
with TGraphicControl(Control.Parent.Controls[I]) do begin
CtlR := Bounds(Left, Top, Width, Height);
if Bool(IntersectRect(R, SelfR, CtlR)) and Visible then begin
ControlState := ControlState + [csPaintCopy];
SaveIndex := SaveDC(DC);
try
if Perform(
WM_GETIMAGE, DC, integer(@SelfR)) <> $29041961 then begin
{ SaveIndex := SaveDC(DC);}
SetViewportOrgEx(DC, Left + X, Top + Y, nil);
IntersectClipRect(DC, 0, 0, Width, Height);
Perform(WM_PAINT, DC, 0);
end;
finally
RestoreDC(DC, SaveIndex);
ControlState := ControlState - [csPaintCopy];
end;
end;
end;
end;
end;
finally
with Control.Parent do ControlState := ControlState - [csPaintCopy];
end;
end;
procedure RestoreImage(DestDC: HDC; SrcBitmap: TBitmap; r: TRect;
dwROP: dword); overload;
begin
RestoreImage(DestDC, SrcBitmap, r.Left, r.Top,
r.Right - r.Left, r.Bottom - r.Top, dwROP);
end;
procedure RestoreImage(DestDC: HDC; SrcBitmap: TBitmap; l, t, w, h: integer;
dwROP: dword); overload;
var x, y: integer;
begin
x := l + w div 2;
y := t + h div 2;
if (SrcBitmap.Canvas.Pixels[x, y] <> $FFFFFF) and
(SrcBitMap.Canvas.Pixels[x, y] <> $000000) then begin
x := l;
y := t;
if y + h > SrcBitMap.Height then begin
y := SrcBitMap.Height - h;
end;
bitblt(DestDC, l, t, w, h,
SrcBitMap.Canvas.Handle, x, y, dwROP);
end;
end;
procedure SplitColor(C: TColor; var r, g, b: integer);
begin
b := (c and $FF0000) shr 16;
g := (c and $00FF00) shr 08;
r := (c and $0000FF) shr 00;
end;
procedure AjustBitmap;
var i, j: integer;
t: TBitmap;
r,
g,
b,
r2,
g2,
b2: integer;
p: PRGBTriple;
function CalcColor(c1, c2, c3: integer): integer;
begin
if c1 = c3 then begin
Result := c2;
exit;
end;
if c1 = 0 then begin
Result := 0;
exit;
end;
{ Result := 255 * c1 div c3 - c1 * (255 - c1) * (255 - c2) div c3 div (255 - c3);
exit;}
Result := c1 * c2 div c3;
if c2 = 0 then Result := c1 * 150 div 255;
if Result > 255 then Result := 255;
if Result < 50 then Result := Result + 50;
{ exit;
a := trunc(x1 * 3);
a := c1 * (255 - c1) * c2 * (255 - c2) div c3 div (255 - c3);
a := 255 * 255 - 4 * a;
try
x1 := Trunc((255 - sqrt(a)) / 2);
x2 := Trunc((255 + sqrt(a)) / 2);
if x1 > x2 then Result := Trunc(x1)
else Result := Trunc(x2);
except
Result := 0;
end;}
end;
begin
if s = c then exit;
if m.Width = 0 then exit;
if m.Height = 0 then exit;
t := TBitmap.Create;
m.PixelFormat := pf24bit;
t.Assign(m);
SplitColor(ColorToRGB(s), r, g, b);
if r = 0 then r := 1;
if g = 0 then g := 1;
if b = 0 then b := 1;
SplitColor(ColorToRGB(c), r2, g2, b2);
for j := 0 to t.Height - 1 do begin
p := t.scanline[j];
for i := 0 to t.Width - 1 do begin
p.rgbtRed := CalcColor(p.rgbtRed, r2, r);
p.rgbtGreen := CalcColor(p.rgbtGreen, g2, g);
p.rgbtBlue := CalcColor(p.rgbtBlue, b2, b);
inc(p);
end;
end;
m.Assign(t);
t.Free;
end;
procedure FadeBitmap;
var i, j: integer;
t: TBitmap;
r,
g,
b: integer;
p: PRGBTriple;
function CalcColor(o: byte; c: byte; b: byte): byte;
var d: byte;
begin
Result := c;
if o > c then begin
d := $FF - c;
if d > b then d := b;
Result := c + c * d div 255;
end else
if o < c then begin
d := c;
if d > b then d := b;
Result := c - c * d div 255;
end;
end;
begin
if m.Width = 0 then exit;
if m.Height = 0 then exit;
t := TBitmap.Create;
m.PixelFormat := pf24bit;
t.Assign(m);
SplitColor(ColorToRGB(c), r, g, b);
if r = 0 then r := 1;
if g = 0 then g := 1;
if b = 0 then b := 1;
for j := 0 to t.Height - 1 do begin
p := t.scanline[j];
for i := 0 to t.Width - 1 do begin
p.rgbtRed := CalcColor(p.rgbtRed, r, d);
p.rgbtGreen := CalcColor(p.rgbtGreen, g, d);
p.rgbtBlue := CalcColor(p.rgbtBlue, b, d);
inc(p);
end;
end;
m.Assign(t);
t.Free;
end;
function IncColor;
var T: TColor;
P: PRGBTriple;
begin
T := ColorToRGB(C);
p := @T;
if D > 0 then begin
if p.rgbtBlue < 255 - D then p.rgbtBlue := p.rgbtBlue + D else p.rgbtBlue := 255;
if p.rgbtRed < 255 - D then p.rgbtRed := p.rgbtRed + D else p.rgbtRed := 255;
if p.rgbtGreen < 255 - D then p.rgbtGreen := p.rgbtGreen + D else p.rgbtGreen := 255;
end else begin
if p.rgbtBlue > D then p.rgbtBlue := p.rgbtBlue - D else p.rgbtBlue := 000;
if p.rgbtRed > D then p.rgbtRed := p.rgbtRed - D else p.rgbtRed := 000;
if p.rgbtGreen > D then p.rgbtGreen := p.rgbtGreen - D else p.rgbtGreen := 000;
end;
Result := T;
end;
end.
|
unit CatTarifGridAdd;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLabel, cxCurrencyEdit, cxControls, cxContainer, cxEdit,
cxTextEdit, cxLookAndFeelPainters, ActnList, StdCtrls, cxButtons,
cxMaskEdit, cxDropDownEdit, cxCalendar, uFControl, uLabeledFControl,
uCharControl, uFloatControl, cxCheckBox, BaseTypes, uIntControl, DB,
FIBDataSet, pFIBDataSet, Math;
type
TfrmCatTarifGridAdd = class(TForm)
CatNote: TcxTextEdit;
lblNote: TcxLabel;
btnOk: TcxButton;
btnCancel: TcxButton;
ActList: TActionList;
ActOk: TAction;
ActCancel: TAction;
lblKoeff: TcxLabel;
lblCategory: TcxLabel;
CatKoeff: TcxCurrencyEdit;
CategoryEdit: TcxTextEdit;
DataSet: TpFIBDataSet;
MinValueEdit: TcxCurrencyEdit;
SumEdit: TcxCurrencyEdit;
cxLabel1: TcxLabel;
cxLabel2: TcxLabel;
procedure ActOkExecute(Sender: TObject);
procedure ActCancelExecute(Sender: TObject);
procedure CategoryEditKeyPress(Sender: TObject; var Key: Char);
procedure CatKoeffPropertiesChange(Sender: TObject);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
FirstRate:Double;
ActDate:TDate;
IdTarifGrid:Integer;
IdCategoryGrid:Variant;
ModeEdit:String;
public
{ Public declarations }
constructor Create(AOwner:TComponent; EditMode:Boolean;
Id_Tarif:Variant; ActualDate:TDate;
RateValue, SumStav:Double;
IdCategory:Variant);
function GetMinCategory(DateValue:TDate):Double;
function IsExistsCategory(NumCat:Integer):Boolean;
end;
var
frmCatTarifGridAdd: TfrmCatTarifGridAdd;
implementation
uses TarifGridMain;
{$R *.dfm}
constructor TfrmCatTarifGridAdd.Create(AOwner:TComponent; EditMode:Boolean;
Id_Tarif:Variant; ActualDate:TDate;
RateValue, SumStav:Double;
IdCategory:Variant);
begin
inherited Create(AOwner);
IdCategoryGrid:=IdCategory;
ModeEdit:='T';
if EditMode=False then
begin
try
DataSet.Close;
DataSet.SQLs.SelectSQL.Clear;
DataSet.SQLs.SelectSQL.Text:='select max(num_category) '+
'from up_category_tarif_grid '+
'where id_tarif_grid=:id_tarif_grid';
DataSet.ParamByName('id_tarif_grid').Value:=Id_Tarif;
DataSet.Open;
CategoryEdit.Text:=IntToStr(DataSet['max']+1);
ModeEdit:='F';
except on E:Exception
do begin
CategoryEdit.Text:='1';
end;
end;
CatKoeff.Value:=1;
end;
IdTarifGrid:=Id_Tarif;
MinValueEdit.Value:=SumStav;
FirstRate:=RateValue;
ActDate:=ActualDate;
end;
function TfrmCatTarifGridAdd.IsExistsCategory(NumCat:Integer):Boolean;
begin
try
Result:=False;
DataSet.Close;
DataSet.SQLs.SelectSQL.Clear;
DataSet.SQLs.SelectSQL.Text:='select can_add '+
'from up_check_can_add_category(:id_tarif_grid, :num_category, :edit_mode, :id_category_grid)';
DataSet.ParamByName('id_tarif_grid').AsInteger:=IdTarifGrid;
DataSet.ParamByName('num_category').AsInteger:=NumCat;
DataSet.ParamByName('edit_mode').AsString:=ModeEdit;
DataSet.ParamByName('id_category_grid').Value:=IdCategoryGrid;
DataSet.Open;
DataSet.FetchAll;
if DataSet['can_add']='T' then Result:=True;
except on E:Exception
do begin
Result:=False;
end;
end;
end;
function TfrmCatTarifGridAdd.GetMinCategory(DateValue:TDate):Double;
begin
try
DataSet.Close;
DataSet.SQLs.SelectSQL.Clear;
DataSet.SQLs.SelectSQL.Text:='select min_value '+
'from get_min_category(:act_date)';
DataSet.ParamByName('act_date').Value:=DateValue;
DataSet.Open;
Result:=DataSet['min_value'];
except on E:Exception
do begin
Result:=0;
end;
end;
end;
procedure TfrmCatTarifGridAdd.ActOkExecute(Sender: TObject);
begin
If CategoryEdit.Text='' then
begin
agMessageDlg('Увага', 'Треба ввести розряд!', mtInformation, [mbOK]);
Exit;
end;
If (VarIsNull(CatKoeff.Value)) then
begin
agMessageDlg('Увага', 'Треба ввести коефіцієнт!', mtInformation, [mbOK]);
Exit;
end;
if IsExistsCategory(StrToInt(CategoryEdit.Text))=False then
begin
agMessageDlg('Увага', 'Такий розряд вже існує!', mtInformation, [mbOK]);
Exit;
end;
ModalResult:=mrOk;
end;
procedure TfrmCatTarifGridAdd.ActCancelExecute(Sender: TObject);
begin
ModalResult:=mrCancel;
end;
procedure TfrmCatTarifGridAdd.CategoryEditKeyPress(Sender: TObject;
var Key: Char);
begin
if (key in ['0'..'9']) or (key=#8) then CategoryEdit.Properties.ReadOnly:=False
else CategoryEdit.Properties.ReadOnly:=True;
end;
procedure TfrmCatTarifGridAdd.CatKoeffPropertiesChange(Sender: TObject);
var CurValue, MinValue:Double;
begin
try
CurValue:=StrToFloat(CatKoeff.Text);
except
CurValue:=0;
end;
MinValue:=GetMinCategory(ActDate);
SumEdit.Value:=SimpleRoundTo(CurValue*MinValueEdit.Value, -2);
end;
procedure TfrmCatTarifGridAdd.FormShow(Sender: TObject);
begin
if CategoryEdit.Text='1' then
begin
CatKoeff.Text:='1';
CatKoeff.Enabled:=False;
CategoryEdit.Enabled:=False;
end;
if CategoryEdit.Enabled=False Then CatNote.SetFocus;
end;
end.
|
unit LessEqOpTest;
interface
uses
DUnitX.TestFramework,
uIntXLibTypes,
uIntX;
type
[TestFixture]
TLessEqOpTest = class(TObject)
public
[Test]
procedure Simple();
[Test]
procedure SimpleFail();
[Test]
procedure Big();
[Test]
procedure BigFail();
[Test]
procedure EqualValues();
end;
implementation
[Test]
procedure TLessEqOpTest.Simple();
var
int1, int2: TIntX;
begin
int1 := TIntX.Create(7);
int2 := TIntX.Create(8);
Assert.IsTrue(int1 <= int2);
end;
[Test]
procedure TLessEqOpTest.SimpleFail();
var
int1: TIntX;
begin
int1 := TIntX.Create(8);
Assert.IsFalse(int1 <= 7);
end;
[Test]
procedure TLessEqOpTest.Big();
var
temp1, temp2: TIntXLibUInt32Array;
int1, int2: TIntX;
begin
SetLength(temp1, 2);
temp1[0] := 1;
temp1[1] := 2;
SetLength(temp2, 3);
temp2[0] := 1;
temp2[1] := 2;
temp2[2] := 3;
int1 := TIntX.Create(temp1, False);
int2 := TIntX.Create(temp2, True);
Assert.IsTrue(int2 <= int1);
end;
[Test]
procedure TLessEqOpTest.BigFail();
var
temp1, temp2: TIntXLibUInt32Array;
int1, int2: TIntX;
begin
SetLength(temp1, 2);
temp1[0] := 1;
temp1[1] := 2;
SetLength(temp2, 3);
temp2[0] := 1;
temp2[1] := 2;
temp2[2] := 3;
int1 := TIntX.Create(temp1, False);
int2 := TIntX.Create(temp2, True);
Assert.IsFalse(int1 <= int2);
end;
[Test]
procedure TLessEqOpTest.EqualValues();
var
temp1, temp2: TIntXLibUInt32Array;
int1, int2: TIntX;
begin
SetLength(temp1, 3);
temp1[0] := 1;
temp1[1] := 2;
temp1[2] := 3;
SetLength(temp2, 3);
temp2[0] := 1;
temp2[1] := 2;
temp2[2] := 3;
int1 := TIntX.Create(temp1, True);
int2 := TIntX.Create(temp2, True);
Assert.IsTrue(int1 <= int2);
end;
initialization
TDUnitX.RegisterTestFixture(TLessEqOpTest);
end.
|
unit sp_cust_rate_acc_FORM_ADD;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Mask, BaseTypes, SYS_OPTIONS, cxControls, cxContainer,
cxEdit, cxTextEdit, cxMaskEdit, cxButtonEdit, cxLookAndFeelPainters,
cxButtons, Variants, ExtCtrls, dogLoaderUnit, cxLabel, cxDropDownEdit,
cxCalendar, cxGroupBox, cxMemo;
type
TFsp_cust_rate_acc_ADD = class(TForm)
Label2: TLabel;
LabelBANK: TLabel;
Label4: TLabel;
BankEdit: TcxButtonEdit;
TypeAccountEdit: TcxButtonEdit;
AccountEdit: TcxTextEdit;
OKButton1: TcxButton;
OKButton2: TcxButton;
CancelButton: TcxButton;
Bevel1: TBevel;
MFOEdit: TcxTextEdit;
Label1: TLabel;
CityEdit: TcxTextEdit;
Label3: TLabel;
cxGroupBox1: TcxGroupBox;
DateBegEdit: TcxDateEdit;
cxLabel1: TcxLabel;
cxLabel2: TcxLabel;
DateEndEdit: TcxDateEdit;
NoteMemo: TcxMemo;
cxLabel3: TcxLabel;
procedure CancelButtonClick(Sender: TObject);
procedure Edit1KeyPress(Sender: TObject; var Key: Char);
procedure OKButton1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure OKButton2Click(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure TypeAccountEditButtonClick(Sender: TObject;
AbsoluteIndex: Integer);
procedure BankEditButtonClick(Sender: TObject; AbsoluteIndex: Integer);
procedure CustomerEditKeyPress(Sender: TObject; var Key: Char);
procedure MFOEditExit(Sender: TObject);
procedure MFOEditKeyPress(Sender: TObject; var Key: Char);
procedure MFOEditPropertiesChange(Sender: TObject);
procedure BankEditPropertiesChange(Sender: TObject);
procedure CityEditPropertiesChange(Sender: TObject);
public
Action : TSpravAction;
MResult : string;
id_bank : integer;
id_type_account : integer;
bank_mfo : string;
bankFinded : boolean;
is_bank_account : boolean;
is_val_account : Boolean;
is_no_acc : Boolean;
BankChanged : boolean;
SkipChecks : boolean;
procedure CheckBank;
function CheckNulls : boolean;
procedure FindBank;
end;
implementation
uses Resources_unitb, GlobalSPR, sp_customer_FORM, FIBQuery,
LangUnit;
{$R *.DFM}
function TFsp_cust_rate_acc_ADD.CheckNulls : boolean;
var
r : integer;
frm : TFsp_customer;
begin
Result := false;
if SkipChecks then exit;
if MFOEdit.Text = '' then begin
ShowMessage('Уведіть МФО.');
Result := true;
exit;
end;
if BankEdit.Text = '' then begin
ShowMessage('Укажіть найменування банку.');
Result := true;
exit;
end;
if CityEdit.Text = '' then begin
ShowMessage('Укажіть місто банку.');
Result := true;
exit;
end;
if AccountEdit.Text = '' then begin
MessageBox(handle,PChar(CUSTOMER_MUST_ACCOUNT),PChar(CUSTOMER_MESSAGE_WARNING), MB_OK or MB_ICONWARNING);
Result := true;
exit;
end;
if TypeAccountEdit.Text = '' then begin
MessageBox(handle,PChar(CUSTOMER_MUST_TYPE_ACC),PChar(CUSTOMER_MESSAGE_WARNING), MB_OK or MB_ICONWARNING);
Result := true;
exit;
end;
try
// Проверка исключена 2020-01-06 в свзи с изменением длины счета и внедрением iBAN
// if is_bank_account then if not CheckAccount(AccountEdit.Text, bank_mfo) then begin
// ShowMessage('Уведено невірний рахунок.');
// Result := true;
// exit;
// end;
except
Result := true;
exit;
end;
if DateBegEdit.Text = '' then
begin
ShowMessage('Укажіть дату початку.');
Result := true;
exit;
end;
if DateEndEdit.Text = '' then
begin
ShowMessage('Укажіть дату закінчення.');
Result := true;
exit;
end;
if TFsp_customer(Owner).FormStyle = fsNormal then begin
if (not is_bank_account) and (not is_val_account) then begin
r := MessageDlg('Увага', 'Довідник запущений у режимі відображення тільки банківських рахунків. Уведений рахунок не буде відображений. Продовжити?', mtConfirmation, [mbYes, mbNo]);
if r = mrNo then begin
Result := true;
exit;
end;
end;
end;
frm := TFsp_customer(Owner);
frm.Query.Close;
if Action = saAdd then frm.Query.SQL.Text := 'select * from PROC_PUB_SP_CUST_ACC_DUB(''' + AccountEdit.Text + ''', ' + IntToStr(id_type_account) + ', ' + IntToStr(id_bank) + ', -1, ' + QuotedStr(DateBegEdit.Text) + ', ' + QuotedStr(DateEndEdit.Text) + ' )'
else frm.Query.SQL.Text := 'select * from PROC_PUB_SP_CUST_ACC_DUB(''' + AccountEdit.Text + ''', ' + IntToStr(id_type_account) + ', ' + IntToStr(id_bank) + ', ' + FloatToStr(frm.AccountDataSet.FBN('ID_RATE_ACCOUNT').asCurrency) + ', ' + QuotedStr(DateBegEdit.Text) + ', ' + QuotedStr(DateEndEdit.Text) +')';
// ShowMessage(frm.Query.SQL.Text);
frm.Query.ExecQuery;
if frm.Query.RecordCount <> 0 then begin
if MessageDlg('Увага', 'Дані реквізити вже існують. Записати?', mtConfirmation, [mbYes, mbNo]) = mrYes then begin
// TFsp_customer(Owner).LocateCustomer(frm.Query['ID_CUSTOMER'].AsInteger);
// TFsp_customer(Owner).LocateAccount(frm.Query['ID_RATE_ACCOUNT'].AsInteger);
// frm.Query.Close;
// Result := true;
//
end else begin
frm.Query.Close;
Result := true;
exit;
end;
end;
frm.Query.Close;
end;
procedure TFsp_cust_rate_acc_ADD.CancelButtonClick(Sender: TObject);
begin
Close;
end;
procedure TFsp_cust_rate_acc_ADD.Edit1KeyPress(Sender: TObject;
var Key: Char);
begin
if Key = #13 then OKButton1.SetFocus;
end;
procedure TFsp_cust_rate_acc_ADD.OKButton1Click(Sender: TObject);
begin
CheckBank;
if is_no_acc then
begin
MResult := 'ok1';
Close;
Exit;
end;
if SkipChecks then begin
ModalResult := mrOk;
exit;
end;
if CheckNulls then exit;
mResult := 'ok1';
Close;
end;
procedure TFsp_cust_rate_acc_ADD.FormCreate(Sender: TObject);
var
yy, mm, dd : word;
begin
LangPackApply(Self);
if Action = saAdd then begin
id_type_account := SYS_DEF_ID_TYPE_ACCOUNT;
TypeAccountEdit.Text := SYS_DEF_NAME_TYPE_ACCOUNT;
is_bank_account := true;
decodedate(now, yy, mm, dd);
dd := 1;
if mm <> 1 then mm := mm - 1 else
begin
mm := 12;
yy := yy - 1;
end;
DateBegEdit.Date := EncodeDate(yy, mm, dd);
DateEndEdit.Date := SYS_MAX_TIMESTAMP;
end;
bankFinded := false;
{ LabelBANK.Caption:=CUSTOMER_BANK_CONST;
Label4.Caption:=CUSTOMER_ACC_TYPE_CONST;
Label2.Caption:=CUSTOMER_ACC_CONST;
CancelButton.Caption:=CUSTOMER_CANCEL_BUT_CONST;}
mResult := 'cancel';
end;
procedure TFsp_cust_rate_acc_ADD.OKButton2Click(Sender: TObject);
begin
CheckBank;
if is_no_acc then
begin
MResult := 'ok2';
Close;
Exit;
end;
if CheckNulls then exit;
mResult := 'ok2';
Close;
end;
procedure TFsp_cust_rate_acc_ADD.FormShow(Sender: TObject);
begin
if Action = saAdd then begin
id_bank := -1;
id_type_account := SYS_ID_TYPE_ACCOUNT;
TypeAccountEdit.Text := SYS_NAME_TYPE_ACCOUNT;
is_bank_account := true;
CityEdit.Text := SYS_CITY;
end;
if AccountEdit.Visible then AccountEdit.SetFocus;
end;
procedure TFsp_cust_rate_acc_ADD.TypeAccountEditButtonClick(
Sender: TObject; AbsoluteIndex: Integer);
var id:Variant;
begin
id:=GlobalSPR.GetIniAcc(self.Owner,TFsp_customer(self.Owner).WorkDatabase.Handle,fsnormal,TFsp_customer(self.Owner).ActualDate);
if VarArrayDimCount(id)>0
then begin
if id[0]<>NULL
then begin
id_type_account :=id[0];
TypeAccountEdit.Text:=id[1];
is_bank_account := id[2] = 1;
is_val_account := id[3] = 1;
is_no_acc := id[4] = 1;
OKButton1.Enabled := is_bank_account or is_val_account or is_no_acc;
end;
end;
end;
procedure TFsp_cust_rate_acc_ADD.BankEditButtonClick(Sender: TObject;
AbsoluteIndex: Integer);
var id:Variant;
begin
id:=GlobalSPR.GetBanks(self,TFsp_customer(self.Owner).Workdatabase.Handle,fsNormal,TFsp_customer(self.Owner).ActualDate);
if VarArrayDimCount(id)>0
then begin
if id[0]<>NULL
then begin
id_bank :=id[0];
BankEdit.Text:=id[1];
bank_mfo := id[2];
CityEdit.Text := id[3];
MFOEdit.Text := bank_mfo;
bankFinded := true;
end;
end;
end;
procedure TFsp_cust_rate_acc_ADD.CustomerEditKeyPress(Sender: TObject;
var Key: Char);
begin
if Key = #13 then begin
Key := #0;
AccountEdit.SetFocus;
end;
end;
procedure TFsp_cust_rate_acc_ADD.FindBank;
var
frm : TFsp_customer;
begin
if Action = saView then exit;
bankFinded := false;
id_bank := -1;
bankChanged := false;
// BankEdit.Text := '';
// CityEdit.Text := 'Донецьк';
if MFOEdit.Text = '' then exit;
frm := TFsp_customer(Owner);
frm.Query.Close;
frm.Query.SQL.Text := 'select * from PROC_PUB_SP_BANK_GET_BY_MFO(''' + MFOEdit.Text + ''', ' + IntToStr(SYS_CURRENT_DEPARTMENT) + ')';
frm.Query.ExecQuery;
if frm.Query.RecordCount = 0 then begin
frm.Query.Close;
exit;
end;
id_bank := frm.Query.FieldbyName('ID_BANK').AsInteger;
BankEdit.Text := frm.Query.FieldbyName('NAME_BANK').AsString;
CityEdit.Text := frm.Query.FieldbyName('CITY').AsString;
bankFinded := true;
frm.Query.Close;
end;
procedure TFsp_cust_rate_acc_ADD.MFOEditExit(Sender: TObject);
begin
FindBank;
end;
procedure TFsp_cust_rate_acc_ADD.MFOEditKeyPress(Sender: TObject;
var Key: Char);
begin
if Key = #13 then begin
FindBank;
BankEdit.SetFocus;
end;
end;
procedure TFsp_cust_rate_acc_ADD.MFOEditPropertiesChange(Sender: TObject);
begin
bank_mfo := MFOEdit.Text;
end;
procedure TFsp_cust_rate_acc_ADD.BankEditPropertiesChange(Sender: TObject);
begin
if bankFinded then bankChanged := true else bankChanged := false;
end;
procedure TFsp_cust_rate_acc_ADD.CityEditPropertiesChange(Sender: TObject);
begin
if Sender = CityEdit then if bankFinded then BankChanged := true;
end;
procedure TFsp_cust_rate_acc_ADD.CheckBank;
var
frm : TFsp_customer;
begin
if not bankFinded then begin
if MessageDlg('Увага', 'Уведений банк із МФО = "' + MFOEdit.Text + '" не знайдений у довіднику банків. Додати?', mtConfirmation, [mbYes, mbNo]) = mrYes then begin
frm := TFsp_customer(Owner);
frm.StoredProc2.Transaction.StartTransaction;
frm.StoredProc2.ExecProcedure('PUB_SP_BANK_ADD', [MFOEdit.Text, BankEdit.Text, CityEdit.Text, SYS_ID_USER, GetCompName, GetIPAddress]);
id_bank := frm.StoredProc2.ParamByName('P_ID_BANK').AsInteger;
frm.StoredProc2.Transaction.Commit;
// frm.SelectAll_S;
bankFinded := true;
end else exit;
end else if BankChanged and (id_bank > 0)then begin
if MessageDlg('Увага', 'Вы изменили существующий банк. Применить изменения?', mtConfirmation, [mbYes, mbNo]) = mrYes then begin
frm := TFsp_customer(Owner);
frm.StoredProc2.Transaction.StartTransaction;
frm.StoredProc2.ExecProcedure('PUB_SP_SP_BANK_MOD', [id_bank, MFOEdit.Text, BankEdit.Text, CityEdit.Text, SYS_ID_USER, GetCompName, GetIPAddress]);
// id_bank := frm.StoredProc.ParamByName('ID_BANK').AsInteger;
frm.StoredProc2.Transaction.Commit;
// frm.SelectAll_S;
bankFinded := true;
bankchanged := false;
end else exit;
end;
end;
end.
|
unit ThItemFactory;
interface
uses
System.Classes,
ThItem, ThTypes;
type
TThItemClasses = class(TObject)
private
FList: TList;
public
constructor Create;
destructor Destroy; override;
procedure AddItem(ID: Integer; ItemClass: TThItemClass);
function GetItemClass(ID: Integer): TThItemClass;
end;
TThItemFactory = class(TObject)
private
FItemClasses: TThItemClasses;
public
constructor Create;
destructor Destroy; override;
procedure AddItem(ID: Integer; ItemClass: TThItemClass);
function Get(AID: Integer; AItemData: IThItemData = nil): TThItem;
end;
procedure RegisterItem(ID: Integer; ItemClass: TThItemClass);
function ItemFactory: TThItemFactory;
implementation
var
_Factory: TThItemFactory;
procedure RegisterItem(ID: Integer; ItemClass: TThItemClass);
begin
if not Assigned(_Factory) then
_Factory := TThItemFactory.Create;
_Factory.AddItem(ID, ItemClass);
end;
function ItemFactory: TThItemFactory;
begin
Assert(Assigned(_Factory), 'Not assigned item factory object.');
Result := _Factory;
end;
type
TThItemClassData = class(TObject)
private
FID: Integer;
FItemClass: TThItemClass;
public
constructor Create(ID: Integer; ItemClass: TThItemClass);
property ID: Integer read FID;
property ItemClass: TThItemClass read FItemClass;
end;
{ TThItemData }
constructor TThItemClassData.Create(ID: Integer; ItemClass: TThItemClass);
begin
FID := ID;
FItemClass := ItemClass;
end;
{ TThItems }
constructor TThItemClasses.Create;
begin
FList := TList.Create;
end;
destructor TThItemClasses.Destroy;
var
I: Integer;
begin
for I := 0 to FList.Count - 1 do
TObject(FList[I]).Free;
FList.Free;
inherited;
end;
function TThItemClasses.GetItemClass(ID: Integer): TThItemClass;
var
I: Integer;
begin
Result := nil;
for I := 0 to FList.Count - 1 do
if TThItemClassData(FList[I]).ID = ID then
begin
Result := TThItemClassData(FList[I]).ItemClass;
Exit;
end;
end;
procedure TThItemClasses.AddItem(ID: Integer; ItemClass: TThItemClass);
begin
FList.Add(TThItemClassData.Create(ID, ItemClass));
end;
{ TThItemFactory }
constructor TThItemFactory.Create;
begin
FItemClasses := TThItemClasses.Create;
end;
destructor TThItemFactory.Destroy;
begin
FItemClasses.Free;
inherited;
end;
procedure TThItemFactory.AddItem(ID: Integer; ItemClass: TThItemClass);
begin
FItemClasses.AddItem(ID, ItemClass);
end;
function TThItemFactory.Get(AID: Integer; AItemData: IThItemData): TThItem;
var
ItemClass: TThItemClass;
begin
Result := nil;
ItemClass := FItemClasses.GetItemClass(AID);
if Assigned(ItemClass) then
begin
Result := ItemClass.Create(nil);
Result.SetItemData(AItemData);
end;
end;
initialization
finalization
if Assigned(_Factory) then
_Factory.Free;
end.
|
unit Invoice.Controller.TabForm.Default;
interface
uses Invoice.Controller.Interfaces, Vcl.ComCtrls, Vcl.ActnList, System.Classes, Vcl.Forms;
type
TControllerTabFormDefault = class(TInterfacedObject, iControllerTabFormDefault)
public
constructor Create;
destructor Destroy; Override;
class function New: iControllerTabFormDefault;
function CreateTab(aAction: TAction; aPageControl: TPageControl): TTabSheet;
procedure ShowForm(aTabSheet: TTabSheet; NameForm: String);
end;
implementation
uses Vcl.Controls;
{ TControllerTabForm }
constructor TControllerTabFormDefault.Create;
begin
//
end;
function TControllerTabFormDefault.CreateTab(aAction: TAction; aPageControl: TPageControl): TTabSheet;
var
aTabSheet: TTabSheet;
TabName: String;
begin
Result:= nil;
//
TabName := 'Tab' + aAction.Name;
//
aTabSheet := aPageControl.FindComponent(TabName) as TTabSheet;
//
if not Assigned(aTabSheet) then
begin
aTabSheet := TTabSheet.Create(aPageControl);
aTabSheet.Name := TabName;
aTabSheet.Caption := aAction.Caption;
aTabSheet.PageControl := aPageControl;
aTabSheet.ImageIndex := 0;
aTabSheet.Hint := '';
end;
//
aPageControl.ActivePage := aTabSheet;
//
Result:= aTabSheet;
end;
procedure TControllerTabFormDefault.ShowForm(aTabSheet: TTabSheet; NameForm: String);
var
NewForm: TFormClass;
aForm: TForm;
begin
if (aTabSheet.Hint = '') and (NameForm <> '') then
begin
NewForm := TFormClass(FindClass('T' + NameForm));
//
aForm := NewForm.Create(Application);
aForm.Parent := aTabSheet;
aForm.BorderStyle := bsNone;
aForm.Align := alClient;
aForm.Visible := True;
//
aTabSheet.Hint := NameForm;
end;
end;
destructor TControllerTabFormDefault.Destroy;
begin
inherited;
end;
class function TControllerTabFormDefault.New: iControllerTabFormDefault;
begin
Result := Self.Create;
end;
end.
|
unit tExecuteTask;
interface
uses
SysUtils, Classes, ShellAPI, OoMisc, uPOSServerTypes, uDMThread, ActiveX;
type
TThreadExecuteTask = class(TThread)
private
{ Private declarations }
fRunning : Boolean;
fIDStore: Integer;
FLocalSetting: TLocalSetting;
FServerConnection: TServerConnection;
FDMThread: TDMThread;
FOnNeedWriteIniBool: TOnNeedWriteIniBool;
FOnNeedWriteIniDateTime: TOnNeedWriteIniDateTime;
FOnNeedWriteIniInteger: TOnNeedWriteIniInteger;
FOnNeedWriteIniString: TOnNeedWriteIniString;
FForceSynchronization: Boolean;
FSynchronizationType: Integer;
FCashRegInfolist: TStringList;
FOnPOSServerStatusEvent : TPOSServerStatusEvent;
FPOSServerStepCompleted: TPOSServerStepCompleted;
FPOSServerCompleted: TPOSServerCompleted;
FOnSaveNextSchedule: TOnSaveNextSchedule;
function StopVPN:Boolean;
protected
property DMThread: TDMThread read FDMThread write FDMThread;
procedure ExecuteJobs;
procedure Execute; override;
public
property Running : Boolean read fRunning;
property IDStore : Integer read FIDStore write FIDStore;
property ServerConnection: TServerConnection read FServerConnection write FServerConnection;
property LocalSetting: TLocalSetting read FLocalSetting write FLocalSetting;
property ForceSynchronization : Boolean read FForceSynchronization write FForceSynchronization;
property CashRegInfolist: TStringList read FCashRegInfolist write FCashRegInfolist;
property SynchronizationType: Integer read FSynchronizationType write FSynchronizationType;
property OnNeedWriteIniBool: TOnNeedWriteIniBool read FOnNeedWriteIniBool write FOnNeedWriteIniBool;
property OnNeedWriteIniDateTime: TOnNeedWriteIniDateTime read FOnNeedWriteIniDateTime write FOnNeedWriteIniDateTime;
property OnNeedWriteIniString: TOnNeedWriteIniString read FOnNeedWriteIniString write FOnNeedWriteIniString;
property OnNeedWriteIniInteger: TOnNeedWriteIniInteger read FOnNeedWriteIniInteger write FOnNeedWriteIniInteger;
property OnPOSServerStatusEvent: TPOSServerStatusEvent read FOnPOSServerStatusEvent write FOnPOSServerStatusEvent;
property OnPOSServerStepCompleted: TPOSServerStepCompleted read FPOSServerStepCompleted write FPOSServerStepCompleted;
property OnPOSServerCompleted: TPOSServerCompleted read FPOSServerCompleted write FPOSServerCompleted;
property OnSaveNextSchedule: TOnSaveNextSchedule read FOnSaveNextSchedule write FOnSaveNextSchedule;
procedure WriteIniBool(ASection, AKey: String; AValue: Boolean);
procedure WriteIniDateTime(ASection, AKey: String; AValue: TDateTime);
procedure WriteIniInteger(ASection, AKey: String; AValue: Integer);
procedure WriteIniString(ASection, AKey, AValue: String);
procedure FreeDMThread;
end;
implementation
uses uMainConf;
{ TThreadExecuteTask }
function TThreadExecuteTask.StopVPN:Boolean;
begin
Result := False;
if ((FrmMain.fNetworkCon.NetworkCon1 <> '') and (FrmMain.VPN1.ConnectState = csRasConnected)) and
(FrmMain.fNetworkCon.StopVPN1) then
FrmMain.VPN1.Hangup;
if ((FrmMain.fNetworkCon.NetworkCon2 <> '') and (FrmMain.VPN2.ConnectState = csRasConnected)) and
(FrmMain.fNetworkCon.StopVPN2) then
FrmMain.VPN2.Hangup;
end;
procedure TThreadExecuteTask.ExecuteJobs;
begin
CoInitialize(nil);
FDMThread := TDMThread.Create(nil);
try
FDMThread.Thread := Self;
FDMThread.IDStore := FIDStore;
FDMThread.ServerConnection := FServerConnection;
FDMThread.LocalSetting := FLocalSetting;
FDMThread.ForceSynchronization := FForceSynchronization;
FDMThread.CashRegInfolist := FCashRegInfolist;
FDMThread.SynchronizationType := FSynchronizationType;
FDMThread.Execute;
finally
FDMThread.Free;
end;
end;
procedure TThreadExecuteTask.Execute;
begin
{ Place thread code here }
FRunning := True;
try
if (not Terminated) then
ExecuteJobs;
finally
FRunning := False;
end;
end;
procedure TThreadExecuteTask.WriteIniBool(ASection, AKey: String; AValue: Boolean);
begin
if Assigned(FOnNeedWriteIniBool) then
FOnNeedWriteIniBool(ASection, AKey, AValue);
end;
procedure TThreadExecuteTask.WriteIniDateTime(ASection, AKey: String; AValue: TDateTime);
begin
if Assigned(FOnNeedWriteIniDateTime) then
FOnNeedWriteIniDateTime(ASection, AKey, AValue);
end;
procedure TThreadExecuteTask.WriteIniString(ASection, AKey: String; AValue: String);
begin
if Assigned(FOnNeedWriteIniString) then
FOnNeedWriteIniString(ASection, AKey, AValue);
end;
procedure TThreadExecuteTask.WriteIniInteger(ASection, AKey: String; AValue: Integer);
begin
if Assigned(FOnNeedWriteIniInteger) then
FOnNeedWriteIniInteger(ASection, AKey, AValue);
end;
procedure TThreadExecuteTask.FreeDMThread;
begin
if FDMThread <> nil then
FDMThread.Free;
end;
end.
|
unit Stitch;
{ SuperStitch function }
interface
uses
SysUtils, WinTypes, WinProcs, Classes, Dialogs,
M_Global, M_Util, M_MapUt, M_mapfun, M_editor, G_Util;
TYPE TStitchRequest = class(TObject)
sc, wl : Integer;
sc0, wl0 : Integer;
XOffs : Real;
YOffs : Real;
end;
CONST
STITCH_DIR_RIGHT = 0;
STITCH_DIR_LEFT = 1;
VAR
STITCH_REQUESTS : TStringList;
STITCH_TEXTURE : String[13];
STITCH_TXSIZEX,
STITCH_TXSIZEY : Real;
STITCH_DIR : Integer;
procedure SuperStitch(sc, wl, tex, dir : Integer);
procedure SuperStitchAWall;
implementation
{WARNING, although tex is in the parameters, no full support is added to
start stitching on a TOP or BOT textures.
Anyway, it is *NOT* necessary, because there is always a
non adjoined wall in the vicinity...}
procedure SuperStitch(sc, wl, tex, dir : Integer);
var s, w : Integer;
TheSector : TSector;
TheWall : TWall;
TheSReq : TStitchRequest;
OffsX,
OffsY : Real;
begin
{first set all the wall marks to zero, we'll use this to mark
when a wall already has been stitched so no wall is done more than once}
for s := 0 to MAP_SEC.Count - 1 do
begin
TheSector := TSector(MAP_SEC.Objects[s]);
for w := 0 to TheSector.Wl.Count - 1 do
begin
TheWall := TWall(TheSector.Wl.Objects[w]);
TheWall.Mark := 0;
end;
end;
STITCH_REQUESTS := TStringList.Create;
STITCH_DIR := dir; {0 = right; 1 = left}
TheSector := TSector(MAP_SEC.Objects[sc]);
TheWall := TWall(TheSector.Wl.Objects[wl]);
case tex of
0 : {MID}
begin
STITCH_TEXTURE := TheWall.Mid.Name;
OffsX := TheWall.Mid.f1;
OffsY := TheWall.Mid.f2;
end;
1 : {TOP}
begin
STITCH_TEXTURE := TheWall.Top.Name;
OffsX := TheWall.Top.f1;
OffsY := TheWall.Top.f2;
end;
2 : {BOT}
begin
STITCH_TEXTURE := TheWall.Bot.Name;
OffsX := TheWall.Bot.f1;
OffsY := TheWall.Bot.f2;
end;
end;
(*
{get the texture dimensions for offsets normalizing}
{search for texture first in project dir}
if FileExists(LEVELPath + '\' + STITCH_TEXTURE) then
begin
STITCH_TXSIZEX := 0;
STITCH_TXSIZEY := 0;
end
else
begin
{else, search in textures.gob}
if IsResourceInGOB(TEXTURESgob, STITCH_TEXTURE, dummy1, dummy2) then
begin
STITCH_TXSIZEX := 0;
STITCH_TXSIZEY := 0;
end
else
begin
ShowMessage('Texture not found !');
end;
end;
*)
{create a special request for the first wall}
TheSReq := TStitchRequest.Create;
TheSreq.sc := sc;
TheSreq.wl := wl;
TheSreq.sc0 := -1;
TheSreq.wl0 := -1;
if STITCH_DIR = 0 then
TheSreq.XOffs := OffsX
else
TheSreq.XOffs := OffsX - GetWLLen(sc, wl);
TheSReq.YOffs := OffsY;
STITCH_REQUESTS.AddObject('1', TheSReq);
while STITCH_REQUESTS.Count <> 0 do SuperStitchAWall;
STITCH_REQUESTS.Free;
MODIFIED := TRUE;
DO_Fill_WallEditor;
end;
procedure SuperStitchAWall;
var s, w, v : Integer;
TheSector : TSector;
TheSector0 : TSector;
TOPSector : TSector;
TheWall : TWall;
TheWall0 : TWall;
NewWall : TWall;
NewWall2 : TWall;
NewWall3 : TWall;
NewSector2 : TSector;
TheSReq : TStitchRequest;
NewSReq : TStitchRequest;
lvx, rvx,
wallnum : Integer;
curxofs,
curyofs : Real;
wllen,
wlhei : Real;
oldmidx,
oldtopx,
oldbotx : Real;
TheSector2 : TSector;
begin
TheSReq := TStitchRequest(STITCH_REQUESTS.Objects[0]);
TheSector := TSector(MAP_SEC.Objects[TheSReq.sc]);
TheWall := TWall(TheSector.Wl.Objects[TheSReq.wl]);
wllen := GetWLLen(TheSReq.sc, TheSReq.wl);
wlhei := GetWLHei(TheSReq.sc, TheSReq.wl);
{don't do anything if the wall was already handled}
if TheWall.Mark <> 0 then
begin
STITCH_REQUESTS.Delete(0);
exit;
end;
{don't do anything if there is a multisel and the wall is not in it}
if WL_MULTIS.Count <> 0 then
if WL_MULTIS.IndexOf(Format('%4d%4d', [TheSReq.sc, TheSReq.wl])) = -1 then
begin
STITCH_REQUESTS.Delete(0);
exit;
end;
{do the actual stitching, unless it is the first wall}
if (TheSReq.sc0 <> -1) then
begin
TheSector0 := TSector(MAP_SEC.Objects[TheSReq.sc0]);
TheWall0 := TWall(TheSector0.Wl.Objects[TheSReq.wl0]);
{save the original offsets to restore the SIGN relative position later}
oldmidx := TheWall.Mid.f1;
oldtopx := TheWall.Top.f1;
oldbotx := TheWall.Bot.f1;
curyofs := TheSReq.YOffs + TheSector.Floor_Alt - TheSector0.Floor_Alt;
{!!! normalize offset if possible (ie make a "mod" texture size) !!!}
if STITCH_DIR = STITCH_DIR_RIGHT then
begin
{handle horizontal stitching}
curxofs := TheSReq.Xoffs + wllen;
{!!! normalize offset if possible (ie make a "mod" texture size) !!!}
if TheWall.Mid.Name = STITCH_TEXTURE then TheWall.Mid.f1 := TheSReq.Xoffs;
if TheWall.Adjoin <> -1 then
begin
if TheWall.Top.Name = STITCH_TEXTURE then TheWall.Top.f1 := TheSReq.Xoffs;
if TheWall.Bot.Name = STITCH_TEXTURE then TheWall.Bot.f1 := TheSReq.Xoffs;
end;
{handle vertical stitching}
if TheWall.Mid.Name = STITCH_TEXTURE then
TheWall.Mid.f2 := curyofs;
if TheWall.Adjoin <> -1 then
begin
if TheWall.Bot.Name = STITCH_TEXTURE then
TheWall.Bot.f2 := curyofs;
if TheWall.Top.Name = STITCH_TEXTURE then
begin
TOPSector := TSector(MAP_SEC.Objects[TheWall.Adjoin]);
TheWall.Top.f2 := TheSReq.YOffs + TOPSector.Ceili_Alt - TheSector.Floor_Alt;
end;
end;
end
else
begin
{handle horizontal stitching}
curxofs := TheSReq.Xoffs - wllen;
{!!! normalize offset if possible (ie make a "mod" texture size) !!!}
if TheWall.Mid.Name = STITCH_TEXTURE then TheWall.Mid.f1 := curxofs;
if TheWall.Adjoin <> -1 then
begin
if TheWall.Top.Name = STITCH_TEXTURE then TheWall.Top.f1 := curxofs;
if TheWall.Bot.Name = STITCH_TEXTURE then TheWall.Bot.f1 := curxofs;
end;
{handle vertical stitching}
if TheWall.Mid.Name = STITCH_TEXTURE then
TheWall.Mid.f2 := curyofs;
if TheWall.Adjoin <> -1 then
begin
if TheWall.Bot.Name = STITCH_TEXTURE then
TheWall.Bot.f2 := curyofs;
if TheWall.Top.Name = STITCH_TEXTURE then
begin
TOPSector := TSector(MAP_SEC.Objects[TheWall.Adjoin]);
TheWall.Top.f2 := TheSReq.YOffs + TOPSector.Ceili_Alt - TheSector.Floor_Alt;
end;
end;
end;
{keep the relative position of the SIGN}
if (TheWall.Sign.Name <> '') then
begin
if TheWall.Adjoin = - 1 then
begin
if TheWall.Mid.Name = STITCH_TEXTURE then
TheWall.Sign.f1 := TheWall.Sign.f1 + TheWall.Mid.f1 - oldmidx;
end
else
begin
TheSector2 := TSector(MAP_SEC.Objects[TheWall.Adjoin]);
if TheSector2.Floor_Alt > TheSector.Floor_Alt then
begin
{there is a bot tx, so the SIGN is on the bot tx !}
if TheWall.Bot.Name = STITCH_TEXTURE then
TheWall.Sign.f1 := TheWall.Sign.f1 + TheWall.Bot.f1 - oldbotx;
end
else
if TheSector2.Ceili_Alt < TheSector.Ceili_Alt then
begin
{there is no bot tx, but well a top tx,
so the SIGN is on the top tx !}
if TheWall.Top.Name = STITCH_TEXTURE then
TheWall.Sign.f1 := TheWall.Sign.f1 + TheWall.Top.f1 - oldtopx;
end
end;
end;
end
else
begin
curxofs := TheSReq.Xoffs + wllen;
curyofs := TheSReq.YOffs;
{!!! normalize offset if possible (ie make a "mod" texture size) !!!}
end;
TheWall.Mark := 1;
{find possible other walls to add to STITCH_REQUESTS
There are only two possibilities :
1) the next/prev wall in the sector
2) if the next/prev wall has an adjoin, the next/prev of this adjoin}
if STITCH_DIR = STITCH_DIR_RIGHT then
begin
rvx := TheWall.right_vx;
if GetWLfromLeftVX(TheSReq.sc, rvx, WallNum) then
begin
NewWall := TWall(TheSector.Wl.Objects[WallNum]);
if (NewWall.Mid.Name = STITCH_TEXTURE) or
(NewWall.Top.Name = STITCH_TEXTURE) or
(NewWall.Bot.Name = STITCH_TEXTURE) then
if NewWall.Mark = 0 then
begin
{request TheSReq.sc, wallnum}
NewSReq := TStitchRequest.Create;
NewSReq.sc := TheSReq.sc;
NewSReq.wl := wallnum;
NewSReq.sc0 := TheSReq.sc;
NewSReq.wl0 := TheSReq.wl;
NewSReq.XOffs := curxofs;
NewSReq.YOffs := curyofs;
STITCH_REQUESTS.AddObject('R', NewSReq);
end;
if NewWall.Adjoin <> - 1 then
begin
NewSector2 := TSector(MAP_SEC.Objects[NewWall.Adjoin]);
NewWall2 := TWall(NewSector2.Wl.Objects[NewWall.Mirror]);
rvx := NewWall2.right_vx;
if GetWLfromLeftVX(NewWall.Adjoin, rvx, WallNum) then
begin
NewWall3 := TWall(NewSector2.Wl.Objects[WallNum]);
if (NewWall3.Mid.Name = STITCH_TEXTURE) or
(NewWall3.Top.Name = STITCH_TEXTURE) or
(NewWall3.Bot.Name = STITCH_TEXTURE) then
if NewWall3.Mark = 0 then
begin
{request newall.adjoin, wallnum}
NewSReq := TStitchRequest.Create;
NewSReq.sc := newwall.adjoin;
NewSReq.wl := wallnum;
NewSReq.sc0 := TheSReq.sc;
NewSReq.wl0 := TheSReq.wl;
NewSReq.XOffs := curxofs;
NewSReq.YOffs := curyofs;
STITCH_REQUESTS.AddObject('R', NewSReq);
end;
end
else
begin
{there is a problem with that wall, stop everything}
STITCH_REQUESTS.Delete(0);
exit;
end;
end;
end
else
begin
{there is a problem with that wall, stop everything}
STITCH_REQUESTS.Delete(0);
exit;
end;
end
else
begin
lvx := TheWall.left_vx;
if GetWLfromRightVX(TheSReq.sc, lvx, WallNum) then
begin
NewWall := TWall(TheSector.Wl.Objects[WallNum]);
if (NewWall.Mid.Name = STITCH_TEXTURE) or
(NewWall.Top.Name = STITCH_TEXTURE) or
(NewWall.Bot.Name = STITCH_TEXTURE) then
if NewWall.Mark = 0 then
begin
{request TheSReq.sc, wallnum}
NewSReq := TStitchRequest.Create;
NewSReq.sc := TheSReq.sc;
NewSReq.wl := wallnum;
NewSReq.sc0 := TheSReq.sc;
NewSReq.wl0 := TheSReq.wl;
NewSReq.XOffs := curxofs;
NewSReq.YOffs := curyofs;
STITCH_REQUESTS.AddObject('R', NewSReq);
end;
if NewWall.Adjoin <> - 1 then
begin
NewSector2 := TSector(MAP_SEC.Objects[NewWall.Adjoin]);
NewWall2 := TWall(NewSector2.Wl.Objects[NewWall.Mirror]);
lvx := NewWall2.left_vx;
if GetWLfromRightVX(NewWall.Adjoin, lvx, WallNum) then
begin
NewWall3 := TWall(NewSector2.Wl.Objects[WallNum]);
if (NewWall3.Mid.Name = STITCH_TEXTURE) or
(NewWall3.Top.Name = STITCH_TEXTURE) or
(NewWall3.Bot.Name = STITCH_TEXTURE) then
if NewWall3.Mark = 0 then
begin
{request newall.adjoin, wallnum}
NewSReq := TStitchRequest.Create;
NewSReq.sc := newwall.adjoin;
NewSReq.wl := wallnum;
NewSReq.sc0 := TheSReq.sc;
NewSReq.wl0 := TheSReq.wl;
NewSReq.XOffs := curxofs;
NewSReq.YOffs := curyofs;
STITCH_REQUESTS.AddObject('R', NewSReq);
end;
end
else
begin
{there is a problem with that wall, stop everything}
STITCH_REQUESTS.Delete(0);
exit;
end;
end;
end
else
begin
{there is a problem with that wall, stop everything}
STITCH_REQUESTS.Delete(0);
exit;
end;
end;
STITCH_REQUESTS.Delete(0);
end;
end.
|
unit URequisicaoEstoque;
interface
uses
UEntidade
,UTipoMovimentacao
,UStatus
,UEmpresaMatriz
,UProduto
,UDeposito
,UUsuario
,ULote
;
type
TREQUISICAOESTOQUE = class (TENTIDADE)
public
TIPO_MOVIMENTACAO : TTIPOMOVIMENTACAO;
DATA_EMISSAO : TDateTime;
DATA_ENTRADA : TDateTime;
DATA_CANCELAMENTO : TDateTime;
STATUS : TSTATUS;
EMPRESA : TEmpresa;
NUMERO_DOCUMENTO : integer;
PRODUTO : TPRODUTO;
QUANTIDADE : double;
CUSTO_UNITARIO : double;
DEPOSITO_ORIGEM : TDEPOSITO;
DEPOSITO_DESTINO : TDEPOSITO;
LOTE : TLOTE;
USUARIO : TUSUARIO;
DATA_INCLUSAO : TDateTime;
constructor Create; override;
destructor Destroy; override;
end;
const
TBL_REQUISICAO_ESTOQUE = 'REQUISICAO_ESTOQUE';
FLD_REQUISICAO_ESTOQUE_TIPO_MOVIMENTACAO = 'ID_TIPO_MOVIMENTACAO';
FLD_REQUISICAO_ESTOQUE_DATA_EMISSAO = 'DATA_EMISSAO';
FLD_REQUISICAO_ESTOQUE_DATA_ENTRADA = 'DATA_ENTRADA';
FLD_REQUISICAO_ESTOQUE_DATA_CANCELAMENTO = 'DATA_CANCELAMENTO';
FLD_REQUISICAO_ESTOQUE_STATUS = 'ID_STATUS';
FLD_REQUISICAO_ESTOQUE_EMPRESA = 'ID_EMPRESA';
FLD_REQUISICAO_ESTOQUE_NUMERO_DOCUMENTO = 'NUMERO_DOCUMENTO';
FLD_REQUISICAO_ESTOQUE_PRODUTO = 'ID_PRODUTO';
FLD_REQUISICAO_ESTOQUE_QUANTIDADE = 'QUANTIDADE';
FLD_REQUISICAO_ESTOQUE_CUSTO_UNITARIO = 'CUSTO_UNITARIO';
FLD_REQUISICAO_ESTOQUE_DEPOSITO_ORIGEM = 'ID_DEPOSITO_ORIGEM';
FLD_REQUISICAO_ESTOQUE_DEPOSITO_DESTINO = 'ID_DEPOSITO_DESTINO';
FLD_REQUISICAO_ESTOQUE_LOTE = 'ID_LOTE';
FLD_REQUISICAO_ESTOQUE_USUARIO = 'ID_USUARIO';
FLD_REQUISICAO_ESTOQUE_DATA_INCLUSAO = 'DATA_INCLUSAO';
VW_REQUISICAO_ESTOQUE = 'VW_REQUISICAO_ESTOQUE';
VW_REQUISICAO_ESTOQUE_CODIGO = 'CODIGO';
VW_REQUISICAO_ESTOQUE_TIPO_MOVIMENTACAO = 'TIPO DE MOVIMENTACAO';
VW_REQUISICAO_ESTOQUE_STATUS = 'STATUS';
VW_REQUISICAO_ESTOQUE_EMPRESA = 'EMPRESA';
VW_REQUISICAO_ESTOQUE_PRODUTO = 'PRODUTO';
VW_REQUISICAO_ESTOQUE_DEPOSITO_ORIGEM = 'DEPOSITO DE ORGIEM';
VW_REQUISICAO_ESTOQUE_DEPOSITO_DESTINO = 'DEPOSITO DE DESTINO';
VW_REQUISICAO_ESTOQUE_USUARIO = 'USUARIO';
VW_REQUISICAO_ESTOQUE_LOTE = 'LOTE';
resourcestring
STR_REQUISICAO_ESTOQUE = 'REQUISIÇÃO ESTOQUE';
implementation
uses
Sysutils
,Dialogs
;
{ TREQUISICAOESTOQUE }
constructor TREQUISICAOESTOQUE.Create;
begin
inherited;
TIPO_MOVIMENTACAO := TTIPOMOVIMENTACAO.Create;
STATUS := TSTATUS.Create;
EMPRESA := TEmpresa.Create;
PRODUTO := TPRODUTO.Create;
DEPOSITO_ORIGEM := TDEPOSITO.Create;
DEPOSITO_DESTINO := TDEPOSITO.Create;
USUARIO := TUSUARIO.Create;
LOTE := TLOTE.Create;
end;
destructor TREQUISICAOESTOQUE.Destroy;
begin
freeAndNil(TIPO_MOVIMENTACAO);
freeAndNil(STATUS);
freeAndNil(EMPRESA);
freeAndNil(PRODUTO);
freeAndNil(DEPOSITO_ORIGEM);
freeAndNil(DEPOSITO_DESTINO);
freeAndNil(USUARIO);
freeAndNil(LOTE);
inherited;
end;
end.
|
unit uImportFunc;
interface
uses
SysUtils, Classes, Variants, DB, ActiveX, ComObj, Excel8TLB, ComCtrls, ADODB,
AppEvnts, VirtualTable, StrUtils, Dialogs, ChooseOrg;
type
TPrimaryKey = record
Id, Inst: integer;
end;
{ TdmImportFunc }
TdmImportFunc = class(TDataModule)
private
{ Private declarations }
public
procedure MoveExcelToDataSet(APathToExcel: string; AStartDataRow: integer; ADataSet: TDataSet;
AFieldsExcel, AFieldsDataSet: array of Variant; AProgress: TProgressBar);
procedure MoveExcelToDataSetADO(APathToExcel: string; AStartDataRow: integer; ADataSet: TDataSet;
AFieldsExcel, AFieldsDataSet: array of Variant; AProgress: TProgressBar);
end;
TExeLink = class
public
class function GetOilLinkId(ATableName: string; AOutProgram: integer; AOutCode: string): integer;
class function GetOilLinkInst(ATableName: string; AOutProgram: integer; AOutCode: string): integer;
class function GetOilLinkKey(ATableName: string; AOutProgram: integer; AOutCode: string): TPrimaryKey;
class function GetOutLinkVal(ATableName: string; AOutProgram, AOilId, AOilInst: integer): string;
end;
TOilDataType = (odtNpGroup, odtNpType, odtAZS, odtOrg, odtOper);
{ TParseExcel }
{
Дано условие:
Необходимо динамически распознать согластно некторорых услови номер строки в Excel, и номер столбца
}
TParseExcelOrientation = (peoNone, peoHorizontal, peoVertical);
TParseExcelSource = (pesNone, pesExcel, pesBuffer);
TParseExcelListRecord = ^PParseExcelListRecord;
PParseExcelListRecord = record
List: TVirtualTable;
Orientation: TParseExcelOrientation;
Index: integer;
end;
TParseExcel = class
private
FBufferHorizontal, FBufferVertical: string;
FDistinctLists: TList;
FList: variant;
FOrientation: TParseExcelOrientation;
FSourceType: TParseExcelSource;
FDataSetHorizontal, FDataSetVertical: TVirtualTable;
FCountHorizontal, FCountVertical: integer;
FOffsetHorizontal, FOffsetVertical: integer;
FRangeHorizontal, FRangeVertical: string;
function GetOrientation: TParseExcelOrientation;
procedure SetList(const Value: variant);
function GetSourceType: TParseExcelSource;
function GetDistinctLists(AOrientation: TParseExcelOrientation;
AIndex: integer): TVirtualTable;
procedure SetBuffer(AOrientation: TParseExcelOrientation;
const Value: string);
function GetBuffer(AOrientation: TParseExcelOrientation): string;
function GetCount(AOrientation: TParseExcelOrientation): integer;
procedure ProcessBuffer(ABuffer: string; ATable: TVirtualTable; AOrientation: TParseExcelOrientation);
procedure SetDestBuffer(var ADestBuffer:string; const AValue: string);
function FindTablePosition(ATable: TVirtualTable;
AOrientation: TParseExcelOrientation; ALocateValues: array of variant;
AUseAlias: boolean): integer;
function GetTable(AOrientation: TParseExcelOrientation): TVirtualTable;
function GetOffset(AOrientation: TParseExcelOrientation): integer;
procedure SetOffset(AOrientation: TParseExcelOrientation;
const Value: integer);
function GetRange(AOrientation: TParseExcelOrientation): string;
procedure SetRange(AOrientation: TParseExcelOrientation;
const AValue: string);
public
constructor Create;
destructor Destroy; override;
// Плюс такого метода передачи данных - быстродействие
// Минус - при копировании их Excel в Excel не должно быть скрытых строк и столбцов
property Buffer[AOrientation: TParseExcelOrientation]: string read GetBuffer write SetBuffer;
property Count[AOrientation: TParseExcelOrientation]: integer read GetCount;
property DistinctLists[AOrientation: TParseExcelOrientation; AIndex: integer]: TVirtualTable{'VALUE', 'ALIAS'} read GetDistinctLists;
function FindPosition(AOrientation: TParseExcelOrientation; ALocateValues: array of variant; AUseAlias: boolean = true): integer;
property List: variant read FList write SetList;
property Offset[AOrientation: TParseExcelOrientation]: integer read GetOffset write SetOffset;
property Orientation: TParseExcelOrientation read GetOrientation write FOrientation;
property Range[AOrientation: TParseExcelOrientation]: string read GetRange write SetRange;
property SourceType: TParseExcelSource read GetSourceType;
property Table[AOrientation: TParseExcelOrientation]: TVirtualTable read GetTable;
end;
{TDefineUnits}
TDefineResult = class
FId, FInst: integer;
private
function GetAsInteger: integer;
function GetAsPrimaryKey: TPrimaryKey;
procedure SetAsPrimaryKey(const Value: TPrimaryKey);
public
constructor Create(AId: integer; AInst: integer = 0); overload;
constructor Create(APk: TPrimaryKey); overload;
property AsPrimaryKey: TPrimaryKey read GetAsPrimaryKey write SetAsPrimaryKey;
property AsInteger: integer read GetAsInteger write FId;
end;
TDefineUnit = class
private
FDefined: boolean;
FInst: integer;
FResult: TDefineResult;
FText: string;
FUserMode: boolean;
function GetResult: TDefineResult;
private
function Define: boolean;
protected
function DoDefine: boolean; virtual; abstract;
public
constructor Create(AText: string; AInst: integer = 0; AUserMode: boolean = True);
property Defined: boolean read FDefined;
property Result: TDefineResult read GetResult;
property UserMode: boolean read FUserMode default True;
end;
TDefineResultSave = ^PDefineResultSave;
PDefineResultSave = packed record
Text: string[255];
Id, Inst: integer;
end;
ENoDataFound = class(Exception);
TDefineUnitClass = class of TDefineUnit;
TStoreDefineUnit = class
private
FDefineUnitClass: TDefineUnitClass;
FResultList: TList;
FUserMode: boolean;
FDataType: TOilDataType;
public
constructor Create(ADefineUnitClass: TDefineUnitClass); overload;
constructor Create(ADataType: TOilDataType); overload;
destructor Destroy; override;
function GetLink(AText: string; AExeLinkProgram: integer = 0; AInst: integer = 0): TDefineResult;
procedure LoadFromFile(AFilePath: string);
procedure SaveToFile(AFilePath: string);
procedure SetLink(AText: string; AInst: integer; ADefineResult: TDefineResult);
property UserMode: boolean read FUserMode write FUserMode default True;
end;
TDefineAZS = class(TDefineUnit)
protected
function DoDefine: boolean; override;
end;
// Не реализованы
TDefineNpGroup = class(TDefineUnit)
function DoDefine: boolean; override;
end;
TDefineNpType = class(TDefineUnit)
function DoDefine: boolean; override;
end;
TDefineOrg = class(TDefineUnit)
function DoDefine: boolean; override;
end;
TDefineOper = class(TDefineUnit)
function DoDefine: boolean; override;
end;
const
DefineClassArray: array[low(TOilDataType)..high(TOilDataType)] of TDefineUnitClass =
(TDefineNpGroup, TDefineNpType, TDefineAZS, TDefineOrg, TDefineOper);
DefineTableArray: array[low(TOilDataType)..high(TOilDataType)] of string =
('OIL_NP_GROUP', 'OIL_NP_TYPE', 'OIL_ORG', 'OIL_ORG', 'OIL_OPER_TYPE');
DefineKeyCountArray: array[low(TOilDataType)..high(TOilDataType)] of word =
(1, 1, 2, 2, 1);
DefineParseExcelOrientation: array[low(TParseExcelOrientation)..high(TParseExcelOrientation)] of string =
('нет', 'горизонталь', 'вертикаль');
var
ImportFunc: TdmImportFunc;
implementation
uses ExFunc, UDbFunc;
{$R *.dfm}
{ TdmImportFunc }
type
TFieldLink = record
DataSetName: string;
ExcelName: string;
ColumnNumbExcel: integer;
end;
procedure TdmImportFunc.MoveExcelToDataSet(APathToExcel: string; AStartDataRow: integer; ADataSet: TDataSet;
AFieldsExcel, AFieldsDataSet: array of Variant; AProgress: TProgressBar);
var
Unknown: iUnknown;
MsExcel, List: Variant;
Eof: boolean;
Row, MinRow, MaxRow, Column, i: integer;
FieldLinksArray: array of TFieldLink;
IsFound: boolean;
//R: Variant;
begin
// Основная проблема данного метода - это скорость.
try
if Succeeded(GetActiveObject(ProgIDToClassID('Excel.Application'), nil, Unknown)) then
MsExcel := GetActiveOleObject('Excel.Application')
else
MsExcel := CreateOleObject('Excel.Application');
try
MsExcel.Workbooks.Add(APathToExcel);
List := MsExcel.ActiveWorkBook.ActiveSheet;
// запретить перерисовку экрана
MsExcel.ScreenUpdating := False;
{ // отменить автоматическую калькуляцию формул
//MsExcel.Calculation[0] := xlManual;
// отменить проверку автоматическую ошибок в ячейках (для XP и выше)
MsExcel.ErrorCheckingOptions.BackgroundChecking := False;
MsExcel.ErrorCheckingOptions.NumberAsText := False;
MsExcel.ErrorCheckingOptions.InconsistentFormula := False;}
SetLength(FieldLinksArray, high(AFieldsExcel)+1);
// Определение расположения колонок
for i := low(AFieldsExcel) to high(AFieldsExcel) do
begin
IsFound := False;
for Column := 1 to 255 do
begin
if List.Cells[AStartDataRow - 1, ExcelNumberToColumn(Column)].Value = AFieldsExcel[i] then
begin
FieldLinksArray[i].ColumnNumbExcel := Column;
FieldLinksArray[i].DataSetName := AFieldsDataSet[i];
FieldLinksArray[i].ExcelName := AFieldsExcel[i];
IsFound := True;
break;
end;
end;
if not IsFound then
raise Exception.CreateFmt('Не удалось найти колонку "%s"',[AFieldsExcel[i]]);
end;
// AProgress.AddProgress();
// Определение конца данных
Row := AStartDataRow;
MinRow := AStartDataRow;
MaxRow := AStartDataRow + 1000;
while VarAsType(List.Cells[MaxRow,1].Value, varString) <> '' do
begin
MinRow := MaxRow;
MaxRow := MaxRow + 1000;
end;
IsFound := False;
while not IsFound do
begin
Row := MinRow + (MaxRow - MinRow) div 2;
if VarAsType(List.Cells[Row,1].Value, varString) = '' then
MaxRow := Row
else
MinRow := Row;
IsFound := (MaxRow - MinRow) = 1;
end;
if AProgress <> nil then
begin
AProgress.Max := MaxRow;
AProgress.Step := 1;
end;
// Определение начала данных
Eof := False;
Row := AStartDataRow;
ADataSet.Open;
while not Eof do
begin
if VarAsType(List.Cells[Row,1].Value, varString) = '' then
begin
Eof := true;
continue;
end;
if AProgress <> nil then
AProgress.StepIt;
ADataSet.Append;
for i := low(FieldLinksArray) to high(FieldLinksArray) do
ADataSet.FieldByName(FieldLinksArray[i].DataSetName).Value := List.Cells[Row,FieldLinksArray[i].ColumnNumbExcel];
ADataSet.Post;
inc(Row);
end;
finally
MsExcel := UnAssigned;
end;
except on e:Exception do
Raise Exception.Create('ImportFunc.MoveExcelToDataSet: '+e.Message);
end;
end;
procedure TdmImportFunc.MoveExcelToDataSetADO(APathToExcel: string; AStartDataRow: integer; ADataSet: TDataSet;
AFieldsExcel, AFieldsDataSet: array of Variant; AProgress: TProgressBar);
const
ConStr =
'Provider=Microsoft.Jet.OLEDB.4.0;' +
'Data Source=%s;' +
'Extended Properties="Excel 8.0;HDR=Yes;";';
{var
i: integer;}
begin
{
http://support.microsoft.com/kb/194124/EN-US/
http://www.sql.ru/forum/actualthread.aspx?bid=1&tid=153285&pg=3
try
XLConn.ConnectionString := Format(ConStr, [ExpandFileName(APathToExcel)]);
XLConn.Open;
XLDataSet.Connection := XLConn;
XLDataSet.CommandText :=
'select * from [Sheet1$]';
XLDataSet.Open;
XLDataSet.First;
if AProgress <> nil then
begin
AProgress.Max := XLDataSet.RecordCount;
AProgress.Step := 1;
end;
ADataSet.Open;
while not XLDataSet.Eof do
begin
ADataSet.Append;
for i := low(AFieldsExcel) to high(AFieldsExcel) do
ADataSet.FieldByName(AFieldsDataSet[i]).AsString := XLDataSet.FieldByName(AFieldsExcel[i]).AsString;
ADataSet.Post;
if AProgress <> nil then
AProgress.StepIt;
XLDataSet.Next;
end;
XLDataSet.Close;
XLConn.Close;
except on e:Exception do
Raise Exception.Create('ImportFunc.MoveExcelToDataSet: '+e.Message);
end; }
end;
{ TParseExcel }
constructor TParseExcel.Create;
begin
FOrientation := peoNone;
FSourceType := pesNone;
FDistinctLists := TList.Create;
FDataSetHorizontal := TVirtualTable.Create(nil);
FDataSetVertical := TVirtualTable.Create(nil);
end;
destructor TParseExcel.Destroy;
begin
FDistinctLists.Free;
FDataSetHorizontal.Free;
FDataSetVertical.Free;
end;
function TParseExcel.FindTablePosition(ATable: TVirtualTable;
AOrientation: TParseExcelOrientation; ALocateValues: array of variant;
AUseAlias: boolean): integer;
var
i: integer;
msg: string;
function GetValueFromAlias(AValue: string):string;
begin
if AUseAlias then
begin
DistinctLists[AOrientation, i].Filtered := False;
DistinctLists[AOrientation, i].Filter := Format('ALIAS=''%s''', [AValue]);
DistinctLists[AOrientation, i].Filtered := True;
try
If DistinctLists[AOrientation, i].IsEmpty then
raise ENoDataFound.CreateFmt('Алиас "%s" не найден', [AValue])
else
Result := DistinctLists[AOrientation, i].FieldByName('VALUE').AsString
finally
DistinctLists[AOrientation, i].Filtered := False;
end;
end
else
Result := AValue;
end;
begin
try
Result := -1;
ATable.Filtered := False;
ATable.Filter := '1=1';
for i := 0 to high(ALocateValues) do
ATable.Filter := ATable.Filter + Format(' AND %s=''%s''', ['F'+IntToStr(i), GetValueFromAlias(ALocateValues[i])]);
ATable.Filtered := True;
try
if ATable.IsEmpty then
raise ENoDataFound.CreateFmt('Позиция не найдена! Согластно фильтру "%s"', [ATable.Filter])
else
Result := ATable.FieldByName('POSITION').AsInteger;
finally
ATable.Filtered := False;
end;
except on E:ENoDataFound do
begin
msg := '';
for i := 0 to high(ALocateValues) do
msg := msg + ALocateValues[i] + ',';
raise ENoDataFound.CreateFmt('Произошла ошибка. На наборе (%s), ориентация выбора "%s".'+#13#10+e.Message,
[msg, DefineParseExcelOrientation[AOrientation]]);
end;
end;
end;
function TParseExcel.FindPosition(AOrientation: TParseExcelOrientation;
ALocateValues: array of variant; AUseAlias: boolean): integer;
begin
case AOrientation of
peoHorizontal:
Result := FindTablePosition(FDataSetHorizontal, AOrientation, ALocateValues, AUseAlias);
peoVertical:
Result := FindTablePosition(FDataSetVertical, AOrientation, ALocateValues, AUseAlias);
else
raise Exception.Create('FindPosition: AOrientation = peoNone');
end;
Result := Result + Offset[AOrientation] + 1;
end;
function TParseExcel.GetDistinctLists(AOrientation: TParseExcelOrientation;
AIndex: integer): TVirtualTable;
var
i: integer;
ListRecord: TParseExcelListRecord;
begin
Result := nil;
for i := 0 to FDistinctLists.Count - 1 do
begin
ListRecord := FDistinctLists.Items[i];
if (ListRecord.Orientation = AOrientation) and (ListRecord.Index = AIndex) then
begin
Result := ListRecord.List;
break;
end;
end;
end;
function TParseExcel.GetOrientation: TParseExcelOrientation;
begin
if FOrientation = peoNone then
raise Exception.Create('Не установленна направленность!');
Result := FOrientation;
end;
function TParseExcel.GetSourceType: TParseExcelSource;
begin
if FSourceType = pesNone then
raise Exception.Create('Не установлен испочник данных!');
Result := FSourceType;
end;
procedure TParseExcel.ProcessBuffer(ABuffer: string; ATable: TVirtualTable;
AOrientation: TParseExcelOrientation);
var
Columns, Row: TStringList;
i, j: integer;
procedure InitTables;
var
j, i: integer;
ListRecord: TParseExcelListRecord;
begin
// Инициализируем список полей
ATable.DeleteFields;
ATable.AddField('POSITION', ftInteger);
// Удаляем все нашей ориентации
i := 0;
while i < FDistinctLists.Count do
begin
ListRecord := FDistinctLists.Items[i];
if (ListRecord.Orientation = AOrientation) then
FDistinctLists.Delete(i)
else
inc(i);
end;
for j := 0 to Count[AOrientation] - 1 do
begin
new(ListRecord);
ListRecord.List := TVirtualTable.Create(nil);
ListRecord.List.AddField('VALUE',ftString, 256);
ListRecord.List.AddField('ALIAS',ftString, 256);
ListRecord.List.Open;
ListRecord.Orientation := AOrientation;
ListRecord.Index := j;
FDistinctLists.Add(ListRecord);
ATable.AddField('F'+IntToStr(j), ftString, 100);
end;
end;
begin
Columns := TStringList.Create;
Row := TStringList.Create;
try
Columns.Text := ABuffer;
case AOrientation of
peoVertical:
begin
if Row.Count > 100 then
raise Exception.Create('Превышено максимально допустимое значение таблицы!');
// Определяем количество колонок
Row.Text := AnsiReplaceStr(Columns[0],#9,#10);
FCountVertical := Row.Count;
InitTables;
ATable.Open;
for i := 0 to Columns.Count - 1 do
begin
Row.Text := AnsiReplaceStr(Columns[i],#9,#10);
ATable.Append;
ATable.FieldByName('POSITION').AsInteger := i;
for j := 0 to Row.Count - 1 do
begin
// Формируем списки уникальных значений
DistinctLists[AOrientation, j].Filtered := False;
if Row[j] = '' then
DistinctLists[AOrientation, j].Filter := 'VALUE = NULL'
else
DistinctLists[AOrientation, j].Filter := Format('VALUE = %s', [QuotedStr(Row[j])]);
DistinctLists[AOrientation, j].Filtered := True;
if DistinctLists[AOrientation, j].IsEmpty then
begin
DistinctLists[AOrientation, j].Append;
DistinctLists[AOrientation, j].FieldByName('VALUE').AsString := Row[j];
DistinctLists[AOrientation, j].Post;
end;
DistinctLists[AOrientation, j].Filtered := False;
// Формируем структуру с позициями значений
ATable.FieldByName('F'+IntToStr(j)).AsString := Row[j];
end;
ATable.Post;
end;
end;
peoHorizontal:
begin
Row.Text := AnsiReplaceStr(Columns[0],#9,#10);
if Columns.Count > 100 then
raise Exception.Create('Превышено максимально допустимое значение таблицы!');
// Определяем количество колонок
FCountHorizontal := Columns.Count;
InitTables;
ATable.Open;
Row.Text := AnsiReplaceStr(Columns[0],#9,#10);
for i := 0 to Row.Count - 1 do
begin
ATable.Append;
ATable.FieldByName('POSITION').AsInteger := i;
for j := 0 to Columns.Count - 1 do
begin
Row.Text := AnsiReplaceStr(Columns[j],#9,#10);
// Формируем списки уникальных значений
DistinctLists[AOrientation, j].Filtered := False;
if Row[j] = '' then
DistinctLists[AOrientation, j].Filter := 'VALUE = NULL'
else
DistinctLists[AOrientation, j].Filter := Format('VALUE = %s', [QuotedStr(Row[i])]);
DistinctLists[AOrientation, j].Filtered := True;
if DistinctLists[AOrientation, j].IsEmpty then
begin
DistinctLists[AOrientation, j].Append;
DistinctLists[AOrientation, j].FieldByName('VALUE').AsString := Row[i];
DistinctLists[AOrientation, j].Post;
end;
DistinctLists[AOrientation, j].Filtered := False;
ATable.FieldByName('F'+IntToStr(j)).AsString := Row[i];
end;
ATable.Post;
end;
end;
end;//case
finally
Columns.Free;
Row.Free;
end;
end;
procedure TParseExcel.SetDestBuffer(var ADestBuffer:string; const AValue: string);
begin
FSourceType := pesBuffer;
ADestBuffer := AValue;
end;
procedure TParseExcel.SetList(const Value: variant);
begin
if FSourceType = pesNone then
begin
FSourceType := pesExcel;
FList := Value;
end
else if SourceType = pesBuffer then
raise Exception.Create('Нельзя повторно установить источник данных');
end;
procedure TParseExcel.SetBuffer(AOrientation: TParseExcelOrientation;
const Value: string);
begin
case AOrientation of
peoHorizontal:
begin
SetDestBuffer(FBufferHorizontal, Value);
ProcessBuffer(FBufferHorizontal, FDataSetHorizontal, AOrientation);
end;
peoVertical:
begin
SetDestBuffer(FBufferVertical, Value);
ProcessBuffer(FBufferVertical, FDataSetVertical, AOrientation);
end;
end;
end;
function TParseExcel.GetBuffer(
AOrientation: TParseExcelOrientation): string;
begin
case AOrientation of
peoHorizontal:
Result := FBufferHorizontal;
peoVertical:
Result := FBufferVertical;
end;
end;
function TParseExcel.GetCount(
AOrientation: TParseExcelOrientation): integer;
begin
case AOrientation of
peoHorizontal:
Result := FCountHorizontal;
peoVertical:
Result := FCountVertical;
else
Result := 0;
end;
end;
function TParseExcel.GetTable(
AOrientation: TParseExcelOrientation): TVirtualTable;
begin
case AOrientation of
peoHorizontal:
Result := FDataSetHorizontal;
peoVertical:
Result := FDataSetVertical;
else
Result := nil;
end;
end;
function TParseExcel.GetOffset(
AOrientation: TParseExcelOrientation): integer;
begin
case AOrientation of
peoHorizontal:
Result := FOffsetHorizontal;
peoVertical:
Result := FOffsetVertical;
else
Result := 0;
end;
end;
procedure TParseExcel.SetOffset(AOrientation: TParseExcelOrientation;
const Value: integer);
begin
case AOrientation of
peoHorizontal:
FOffsetHorizontal := Value;
peoVertical:
FOffsetVertical := Value;
end;
end;
function TParseExcel.GetRange(
AOrientation: TParseExcelOrientation): string;
begin
case AOrientation of
peoHorizontal: Result := FRangeHorizontal;
peoVertical: Result := FRangeVertical;
end;
end;
procedure TParseExcel.SetRange(AOrientation: TParseExcelOrientation;
const AValue: string);
// Передаеться строка вида "A1:B2"
var
minrow, mincol,
maxrow, maxcol,
row, col: integer;
buff, str: string;
function GetVal(AStr: string; AIsNumbers: boolean): string;
var
i: integer;
begin
Result := '';
for i := 1 to length(AStr) do
if AStr[i] in ['0'..'9'] then
begin
if AIsNumbers then
Result := Result+AStr[i];
end
else if not AIsNumbers then
Result := Result+AStr[i];
end;
begin
// Разбираем строку
minrow := StrToInt(GetVal(copy(AValue,1,pos(':',AValue)-1),true));
mincol := ExcelColumnToNumber(GetVal(copy(AValue,1,pos(':',AValue)-1),false));
maxrow := StrToInt(GetVal(copy(AValue,pos(':',AValue)+1,length(AValue)),true));
maxcol := ExcelColumnToNumber(GetVal(copy(AValue,pos(':',AValue)+1,length(AValue)),false));
buff := '';
// Формируем буфер
for row := minrow to maxrow do
begin
str := '';
for col := mincol to maxcol do
try
str := str + FList.Cells[row, col].Text + #9;
except on E:Exception do
raise Exception.CreateFmt('SetRange: Ошибка при считывании %s(%d)%d'+#13#10+e.Message,[ExcelNumberToColumn(col), col, row]);
end;
//Delete(str, length(str), 1);
buff := buff + str + #13#10;
end;
Buffer[AOrientation] := buff;
case AOrientation of
peoHorizontal: FRangeHorizontal := AValue;
peoVertical: FRangeVertical := AValue;
end;
end;
{ TExeLink }
class function TExeLink.GetOilLinkId(ATableName: string; AOutProgram: integer;
AOutCode: string): integer;
begin
Result := nvl(GetSqlValueParSimple('select ov.GetOilLinkId(:ATableName, :AOutProgram, :AOutCode) from dual',
['ATableName', ATableName,
'AOutProgram',AOutProgram,
'AOutCode',AOutCode]),-1);
if Result = -1 then
raise ENoDataFound.Create('GetOilLinkId: Соответствие не найдено!');
end;
class function TExeLink.GetOilLinkInst(ATableName: string; AOutProgram: integer;
AOutCode: string): integer;
begin
Result := nvl(GetSqlValueParSimple('select ov.GetOilLinkInst(:ATableName, :AOutProgram, :AOutCode) from dual',
['ATableName', ATableName,
'AOutProgram',AOutProgram,
'AOutCode',AOutCode]),-1);
if Result = -1 then
raise ENoDataFound.Create('GetOilLinkId: Соответствие не найдено!');
end;
class function TExeLink.GetOilLinkKey(ATableName: string; AOutProgram: integer;
AOutCode: string): TPrimaryKey;
begin
Result.Id := GetOilLinkId(ATableName, AOutProgram, AOutCode);
try
Result.Inst := GetOilLinkInst(ATableName, AOutProgram, AOutCode);
except on e:ENoDataFound do
Result.Inst := 0;
end;
end;
class function TExeLink.GetOutLinkVal(ATableName: string; AOutProgram, AOilId,
AOilInst: integer): string;
begin
Result := nvl(GetSqlValueParSimple('select ov.GetOutLinkVal(:ATableName, :AOutProgram, :AOilId, :AOilInst) from dual',
['ATableName', ATableName,
'AOutProgram',AOutProgram,
'AOilId',AOilId,
'AOilInst',AOilInst]),-1);
end;
{ TDefineResult }
constructor TDefineResult.Create(AId, AInst: integer);
begin
FId := AId;
FInst := AInst;
end;
constructor TDefineResult.Create(APk: TPrimaryKey);
begin
Create(APk.Id, APk.Inst);
end;
function TDefineResult.GetAsInteger: integer;
begin
Result := FId;
end;
function TDefineResult.GetAsPrimaryKey: TPrimaryKey;
begin
Result.id := FId;
Result.inst := FInst;
end;
procedure TDefineResult.SetAsPrimaryKey(const Value: TPrimaryKey);
begin
FId := Value.id;
FInst := Value.inst;
end;
{ TDefineUnit }
constructor TDefineUnit.Create(AText: string; AInst: integer = 0; AUserMode: boolean = True);
begin
if AInst = 0 then
FInst := StrToInt(ReadOilVar('INST'))
else
FInst := AInst;
FText := AText;
FDefined := False;
FUserMode := AUserMode;
Define;
end;
function TDefineUnit.Define: boolean;
begin
Result := DoDefine;
FDefined := Result;
end;
function TDefineUnit.GetResult: TDefineResult;
begin
if FDefined then
Result := FResult
else
raise ENoDataFound.CreateFmt('Значение не определено для "%s"',[FText]);
end;
{ TStoreDefineUnit }
constructor TStoreDefineUnit.Create(ADefineUnitClass: TDefineUnitClass);
var
i: TOilDataType;
begin
FDefineUnitClass := ADefineUnitClass;
for i := low(DefineClassArray) to high(DefineClassArray) do
begin
if DefineClassArray[i] = ADefineUnitClass then
begin
FDataType := i;
break;
end;
end;
FResultList := TList.Create;
FUserMode := True;
end;
constructor TStoreDefineUnit.Create(ADataType: TOilDataType);
begin
Create(DefineClassArray[ADataType]);
FDataType := ADataType;
end;
destructor TStoreDefineUnit.Destroy;
begin
FResultList.Free;
end;
function TStoreDefineUnit.GetLink(AText: string; AExeLinkProgram, AInst: integer): TDefineResult;
var
i: integer;
Rec: TDefineResultSave;
IsFound: boolean;
Res: TDefineResult;
du: TDefineUnit;
begin
Res := TDefineResult.Create(0, 0);
// Проверяем кеш
IsFound := False;
for i := 0 to FResultList.Count - 1 do
begin
Rec := FResultList[i];
if Rec.Text = AText then
begin
Result := TDefineResult.Create(Rec.Id, Rec.Inst);
Exit;
end;
end;
// Ищем в EXE_LINK
if AExeLinkProgram <> 0 then
begin
try
if DefineKeyCountArray[FDataType] = 2 then
begin
With TExeLink.GetOilLinkKey(DefineTableArray[FDataType], AExeLinkProgram, AText) do
begin
Res := TDefineResult.Create(Id, Inst);
IsFound := True;
end
end
else if DefineKeyCountArray[FDataType] = 1 then
begin
Res := TDefineResult.Create(TExeLink.GetOilLinkId(DefineTableArray[FDataType], AExeLinkProgram, AText), 0);
IsFound := True;
end;
except on e:ENoDataFound do;
end;
end;
// Ищем соответствие по-горячому "правильными" методами
if not IsFound then
begin
du := FDefineUnitClass.Create(AText, AInst, UserMode);
try
if du.Defined then
begin
Res := TDefineResult.Create(du.Result.AsPrimaryKey);
IsFound := True;
end;
finally
du.Free;
end;
end;
// Сохраняем
if IsFound then
begin
Result := Res;
new(Rec);
Rec.Text := AText;
Rec.Id := Result.AsPrimaryKey.Id;
Rec.Inst := Result.AsPrimaryKey.Inst;
FResultList.Add(Rec);
end
else
raise ENoDataFound.CreateFmt('GetLink: Не найдено соответствие для "%s"', [AText]);
end;
procedure TStoreDefineUnit.LoadFromFile(AFilePath: string);
var
F: file of PDefineResultSave;
Rec: TDefineResultSave;
begin
FResultList.Clear;
AssignFile(F, AFilePath);
Reset(F);
while not Eof(F) do
begin
New(Rec);
Read(F, Rec^);
FResultList.Add(Rec);
end;
CloseFile(F);
end;
procedure TStoreDefineUnit.SaveToFile(AFilePath: string);
var
F: file of PDefineResultSave;
i: integer;
Rec: TDefineResultSave;
begin
AssignFile(F, AFilePath);
Rewrite(F);
for i := 0 to FResultList.Count - 1 do
begin
Rec := FResultList[i];
Write(F, Rec^);
end;
CloseFile(F);
end;
procedure TStoreDefineUnit.SetLink(AText: string; AInst: integer;
ADefineResult: TDefineResult);
var
Rec: TDefineResultSave;
IsFound: boolean;
i: integer;
begin
IsFound := False;
for i := 0 to FResultList.Count - 1 do
begin
Rec := FResultList[i];
if Rec.Text = AText then
begin
IsFound := True;
Rec.Id := ADefineResult.AsPrimaryKey.Id;
Rec.Inst := ADefineResult.AsPrimaryKey.Inst;
Break;
end;
end;
if not IsFound then
begin
new(Rec);
Rec.Text := AText;
Rec.Id := ADefineResult.AsPrimaryKey.Id;
Rec.Inst := ADefineResult.AsPrimaryKey.Inst;
FResultList.Add(Rec);
end;
end;
{ TDefineAZS }
function TDefineAZS.DoDefine: boolean;
var
vNum, AZSName: string;
i, Id: integer;
begin
Result := False;
// Поиск АЗС по номеру в тексте
try
AZSName := FText;
vNum := '';
// Ищем цифры в названии
While (Length(AZSName) <> 0) and not (AZSName[1] in ['0'..'9']) do
Delete(AZSName,1,1);
// Если цыфры не найдены - выходим
if AZSName <> '' then
if AZSName[1] in ['0'..'9'] then
begin
// Вырезаем цыфры
for i := 1 to Length(AZSName) do
begin
if AZSName[i] in ['0'..'9'] then
vNum := vNum + AZSName[i]
else if vNum <> '' then
// если номер уже определен, и пошли другие символы, то выходим из цикла
break;
end;
// Определяем код АЗС по номеру
Id := nvl(GetSqlValueParSimple('select id from v_oil_azs where azs_num = :azs_num and par = :par and par_inst = :par_inst',
['azs_num', StrToInt(vNum),
'par', FInst,
'par_inst', FInst]),-1);
if Id <> -1 then
begin
FResult := TDefineResult.Create(Id, Id);
Result := True;
end;
end;
except on e: Exception do
// ShowMessage(format('Не удалось извлечь номер из строки %s',[FText]));
end;
// Даем пользователю возможность выбора
if not Result and UserMode then
begin
ShowMessage('Сделайте выбор АЗС для значения '+FText);
if ChooseOrg.CaptureOrg(2, FInst, FInst, 'yyy', Id, Id, AZSName) then
begin
Result := True;
FResult := TDefineResult.Create(Id, Id);
end;
end;
end;
{ TDefineOrg }
function TDefineOrg.DoDefine: boolean;
begin
Result := False;
end;
{ TDefineNpType }
function TDefineNpType.DoDefine: boolean;
begin
Result := False;
end;
{ TDefineNpGroup }
function TDefineNpGroup.DoDefine: boolean;
begin
Result := False;
end;
{ TDefineOper }
function TDefineOper.DoDefine: boolean;
begin
Result := False;
end;
initialization
ImportFunc := TdmImportFunc.Create(nil);
finalization
ImportFunc.Free;
end.
|
unit ImageRGBAData;
interface
uses Windows, Graphics, Abstract2DImageData, RGBASingleDataSet;
type
T2DImageRGBAData = class (TAbstract2DImageData)
private
// Gets
function GetData(_x, _y, _c: integer):single;
// Sets
procedure SetData(_x, _y, _c: integer; _value: single);
protected
// Constructors and Destructors
procedure Initialize; override;
// Gets
function GetBitmapPixelColor(_Position: longword):longword; override;
function GetRPixelColor(_Position: longword):byte; override;
function GetGPixelColor(_Position: longword):byte; override;
function GetBPixelColor(_Position: longword):byte; override;
function GetAPixelColor(_Position: longword):byte; override;
function GetRedPixelColor(_x,_y: integer):single; override;
function GetGreenPixelColor(_x,_y: integer):single; override;
function GetBluePixelColor(_x,_y: integer):single; override;
function GetAlphaPixelColor(_x,_y: integer):single; override;
// Sets
procedure SetBitmapPixelColor(_Position, _Color: longword); override;
procedure SetRGBAPixelColor(_Position: integer; _r, _g, _b, _a: byte); override;
procedure SetRedPixelColor(_x,_y: integer; _value:single); override;
procedure SetGreenPixelColor(_x,_y: integer; _value:single); override;
procedure SetBluePixelColor(_x,_y: integer; _value:single); override;
procedure SetAlphaPixelColor(_x,_y: integer; _value:single); override;
public
// Misc
procedure ScaleBy(_Value: single); override;
procedure Invert; override;
// properties
property Data[_x,_y,_c:integer]:single read GetData write SetData; default;
end;
implementation
// Constructors and Destructors
procedure T2DImageRGBAData.Initialize;
begin
FData := TRGBASingleDataSet.Create;
end;
// Gets
function T2DImageRGBAData.GetData(_x, _y, _c: integer):single;
begin
if (_x >= 0) and (_x < FXSize) and (_y >= 0) and (_y < FYSize) and (_c >= 0) and (_c <= 2) then
begin
case (_c) of
0: Result := (FData as TRGBASingleDataSet).Red[(_y * FXSize) + _x];
1: Result := (FData as TRGBASingleDataSet).Green[(_y * FXSize) + _x];
2: Result := (FData as TRGBASingleDataSet).Blue[(_y * FXSize) + _x];
else
begin
Result := (FData as TRGBASingleDataSet).Alpha[(_y * FXSize) + _x];
end;
end;
end
else
begin
Result := -99999;
end;
end;
function T2DImageRGBAData.GetBitmapPixelColor(_Position: longword):longword;
begin
Result := RGB(Round((FData as TRGBASingleDataSet).Blue[_Position]) and $FF,Round((FData as TRGBASingleDataSet).Green[_Position]) and $FF,Round((FData as TRGBASingleDataSet).Red[_Position]) and $FF);
end;
function T2DImageRGBAData.GetRPixelColor(_Position: longword):byte;
begin
Result := Round((FData as TRGBASingleDataSet).Red[_Position]) and $FF;
end;
function T2DImageRGBAData.GetGPixelColor(_Position: longword):byte;
begin
Result := Round((FData as TRGBASingleDataSet).Green[_Position]) and $FF;
end;
function T2DImageRGBAData.GetBPixelColor(_Position: longword):byte;
begin
Result := Round((FData as TRGBASingleDataSet).Blue[_Position]) and $FF;
end;
function T2DImageRGBAData.GetAPixelColor(_Position: longword):byte;
begin
Result := Round((FData as TRGBASingleDataSet).Alpha[_Position]) and $FF;
end;
function T2DImageRGBAData.GetRedPixelColor(_x,_y: integer):single;
begin
Result := (FData as TRGBASingleDataSet).Red[(_y * FXSize) + _x];
end;
function T2DImageRGBAData.GetGreenPixelColor(_x,_y: integer):single;
begin
Result := (FData as TRGBASingleDataSet).Green[(_y * FXSize) + _x];
end;
function T2DImageRGBAData.GetBluePixelColor(_x,_y: integer):single;
begin
Result := (FData as TRGBASingleDataSet).Blue[(_y * FXSize) + _x];
end;
function T2DImageRGBAData.GetAlphaPixelColor(_x,_y: integer):single;
begin
Result := (FData as TRGBASingleDataSet).Alpha[(_y * FXSize) + _x];
end;
// Sets
procedure T2DImageRGBAData.SetBitmapPixelColor(_Position, _Color: longword);
begin
(FData as TRGBASingleDataSet).Red[_Position] := GetRValue(_Color);
(FData as TRGBASingleDataSet).Green[_Position] := GetGValue(_Color);
(FData as TRGBASingleDataSet).Blue[_Position] := GetBValue(_Color);
end;
procedure T2DImageRGBAData.SetRGBAPixelColor(_Position: integer; _r, _g, _b, _a: byte);
begin
(FData as TRGBASingleDataSet).Red[_Position] := _r;
(FData as TRGBASingleDataSet).Green[_Position] := _g;
(FData as TRGBASingleDataSet).Blue[_Position] := _b;
(FData as TRGBASingleDataSet).Alpha[_Position] := _a;
end;
procedure T2DImageRGBAData.SetRedPixelColor(_x,_y: integer; _value:single);
begin
(FData as TRGBASingleDataSet).Red[(_y * FXSize) + _x] := _value;
end;
procedure T2DImageRGBAData.SetGreenPixelColor(_x,_y: integer; _value:single);
begin
(FData as TRGBASingleDataSet).Green[(_y * FXSize) + _x] := _value;
end;
procedure T2DImageRGBAData.SetBluePixelColor(_x,_y: integer; _value:single);
begin
(FData as TRGBASingleDataSet).Blue[(_y * FXSize) + _x] := _value;
end;
procedure T2DImageRGBAData.SetAlphaPixelColor(_x,_y: integer; _value:single);
begin
(FData as TRGBASingleDataSet).Alpha[(_y * FXSize) + _x] := _value;
end;
procedure T2DImageRGBAData.SetData(_x, _y, _c: integer; _value: single);
begin
if (_x >= 0) and (_x < FXSize) and (_y >= 0) and (_y < FYSize) and (_c >= 0) and (_c <= 2) then
begin
case (_c) of
0: (FData as TRGBASingleDataSet).Red[(_y * FXSize) + _x] := _value;
1: (FData as TRGBASingleDataSet).Green[(_y * FXSize) + _x] := _value;
2: (FData as TRGBASingleDataSet).Blue[(_y * FXSize) + _x] := _value;
3: (FData as TRGBASingleDataSet).Alpha[(_y * FXSize) + _x] := _value;
end;
end;
end;
// Misc
procedure T2DImageRGBAData.ScaleBy(_Value: single);
var
x,maxx: integer;
begin
maxx := (FXSize * FYSize) - 1;
for x := 0 to maxx do
begin
(FData as TRGBASingleDataSet).Red[x] := (FData as TRGBASingleDataSet).Red[x] * _Value;
(FData as TRGBASingleDataSet).Green[x] := (FData as TRGBASingleDataSet).Green[x] * _Value;
(FData as TRGBASingleDataSet).Blue[x] := (FData as TRGBASingleDataSet).Blue[x] * _Value;
(FData as TRGBASingleDataSet).Alpha[x] := (FData as TRGBASingleDataSet).Alpha[x] * _Value;
end;
end;
procedure T2DImageRGBAData.Invert;
var
x,maxx: integer;
begin
maxx := (FXSize * FYSize) - 1;
for x := 0 to maxx do
begin
(FData as TRGBASingleDataSet).Red[x] := 1 - (FData as TRGBASingleDataSet).Red[x];
(FData as TRGBASingleDataSet).Green[x] := 1 - (FData as TRGBASingleDataSet).Green[x];
(FData as TRGBASingleDataSet).Blue[x] := 1 - (FData as TRGBASingleDataSet).Blue[x];
(FData as TRGBASingleDataSet).Alpha[x] := 1 - (FData as TRGBASingleDataSet).Alpha[x];
end;
end;
end.
|
unit OrcamentoOperacaoAlterar.Controller;
interface
uses Orcamento.Controller.interf, Orcamento.Model.interf,
OrcamentoItens.Model.interf, Generics.Collections, TESTORCAMENTOITENS.Entidade.Model,
TESTORCAMENTO.Entidade.Model, System.SysUtils, ormbr.factory.interfaces,
OrcamentoFornecedores.Model.Interf, TESTORCAMENTOFORNECEDORES.Entidade.Model;
type
TOrcamentoOperacaoAlterarController = class(TInterfacedObject,
IOrcamentoOperacaoAlterarController)
private
FConexao: IDBConnection;
FOrcamentoModel: IOrcamentoModel;
FOrcamentoItensModel: IOrcamentoItensModel;
FOrcamentoFornecedoresModel: IOrcamentoFornecedoresModel;
FRegistro: TTESTORCAMENTO;
FDescricao: string;
FLista: TList<TOrcamentoItens>;
FListaFornecedores: TList<TOrcamentoFornecedores>;
procedure removerItensOrcamento;
procedure removerFornecedoresOrcamento;
procedure gravarCapaOrcamento;
procedure gravarItensOrcamento;
procedure gravarFornecedoresOrcamento;
public
constructor Create;
destructor Destroy; override;
class function New: IOrcamentoOperacaoAlterarController;
function orcamentoModel(AValue: IOrcamentoModel)
: IOrcamentoOperacaoAlterarController;
function orcamentoItensModel(AValue: IOrcamentoItensModel)
: IOrcamentoOperacaoAlterarController;
function orcamentoFornecedoresModel(AValue: IOrcamentoFornecedoresModel)
: IOrcamentoOperacaoAlterarController;
function orcamentoSelecionado(AValue: TTESTORCAMENTO): IOrcamentoOperacaoAlterarController;
function descricao(AValue: string): IOrcamentoOperacaoAlterarController;
function itens(AValue: TList<TOrcamentoItens>)
: IOrcamentoOperacaoAlterarController;
function fornecedores(AValue: TList<TOrcamentoFornecedores>)
: IOrcamentoOperacaoAlterarController;
procedure finalizar;
end;
implementation
{ TOrcamentoOperacaoAlterarController }
uses FacadeController;
constructor TOrcamentoOperacaoAlterarController.Create;
begin
FConexao := TFacadeController.New.ConexaoController.conexaoAtual;
end;
function TOrcamentoOperacaoAlterarController.descricao(
AValue: string): IOrcamentoOperacaoAlterarController;
begin
Result := self;
FDescricao := AValue;
end;
destructor TOrcamentoOperacaoAlterarController.Destroy;
begin
inherited;
end;
procedure TOrcamentoOperacaoAlterarController.finalizar;
begin
{1} gravarCapaOrcamento;
{2} removerItensOrcamento;
{3} removerFornecedoresOrcamento;
{4} gravarItensOrcamento;
{5} gravarFornecedoresOrcamento;
end;
function TOrcamentoOperacaoAlterarController.fornecedores(
AValue: TList<TOrcamentoFornecedores>): IOrcamentoOperacaoAlterarController;
begin
Result := Self;
FListaFornecedores := AValue;
end;
procedure TOrcamentoOperacaoAlterarController.gravarCapaOrcamento;
begin
FOrcamentoModel.DAO.Modify(FRegistro);
FRegistro.DESCRICAO := FDescricao;
FOrcamentoModel.DAO.Update(FRegistro);
end;
procedure TOrcamentoOperacaoAlterarController.gravarFornecedoresOrcamento;
var
I: Integer;
begin
for I := 0 to Pred(FListaFornecedores.Count) do
begin
FOrcamentoFornecedoresModel.Entidade(TTESTORCAMENTOFORNECEDORES.Create);
FOrcamentoFornecedoresModel.Entidade.IDORCAMENTO := FRegistro.CODIGO;
FOrcamentoFornecedoresModel.Entidade.IDFORNECEDOR := FListaFornecedores[I].codigo;
FOrcamentoFornecedoresModel.DAO.Insert(FOrcamentoFornecedoresModel.Entidade);
end;
end;
procedure TOrcamentoOperacaoAlterarController.gravarItensOrcamento;
var
I: Integer;
begin
for I := 0 to Pred(FLista.Count) do
begin
FOrcamentoItensModel.Entidade(TTESTORCAMENTOITENS.Create);
FOrcamentoItensModel.Entidade.IDORCAMENTO := FRegistro.CODIGO;
FOrcamentoItensModel.Entidade.IDPRODUTO := FLista[I].codigo;
FOrcamentoItensModel.Entidade.QTDE := FLista[I].qtde;
FOrcamentoItensModel.DAO.Insert(FOrcamentoItensModel.Entidade);
end;
end;
function TOrcamentoOperacaoAlterarController.itens(
AValue: TList<TOrcamentoItens>): IOrcamentoOperacaoAlterarController;
begin
Result := Self;
FLista := AValue;
end;
class function TOrcamentoOperacaoAlterarController.New
: IOrcamentoOperacaoAlterarController;
begin
Result := Self.Create;
end;
function TOrcamentoOperacaoAlterarController.orcamentoFornecedoresModel(
AValue: IOrcamentoFornecedoresModel): IOrcamentoOperacaoAlterarController;
begin
Result := Self;
FOrcamentoFornecedoresModel := AValue;
end;
function TOrcamentoOperacaoAlterarController.orcamentoItensModel(
AValue: IOrcamentoItensModel): IOrcamentoOperacaoAlterarController;
begin
Result := self;
FOrcamentoItensModel := AValue;
end;
function TOrcamentoOperacaoAlterarController.orcamentoModel(
AValue: IOrcamentoModel): IOrcamentoOperacaoAlterarController;
begin
Result := self;
FOrcamentoModel := AValue;
end;
function TOrcamentoOperacaoAlterarController.orcamentoSelecionado(
AValue: TTESTORCAMENTO): IOrcamentoOperacaoAlterarController;
begin
Result := Self;
FRegistro := AValue;
end;
procedure TOrcamentoOperacaoAlterarController.removerFornecedoresOrcamento;
begin
FConexao
.ExecuteDirect(
Format('Delete from TEstOrcamentoFornecedores Where IdOrcamento = %s',
[QuotedStr(FRegistro.CODIGO)]
));
end;
procedure TOrcamentoOperacaoAlterarController.removerItensOrcamento;
begin
FConexao
.ExecuteDirect(
Format('Delete from TEstOrcamentoItens Where IdOrcamento = %s',
[QuotedStr(FRegistro.CODIGO)]
));
end;
end.
|
unit Odontologia.Modelo.Pais;
interface
uses
Data.DB,
SimpleDAO,
SimpleInterface,
SimpleQueryRestDW,
Odontologia.Modelo.Pais.Interfaces,
Odontologia.Modelo.Entidades.Pais,
Odontologia.Modelo.Conexion.RestDW,
System.SysUtils;
type
TModelPais = class (TInterfacedOBject, iModelPais)
private
FEntidade : TDPAIS;
FDAO : iSimpleDao<TDPAIS>;
FDataSource : TDataSource;
public
constructor Create;
destructor Destroy; override;
class function New : iModelPais;
function Entidad : TDPAIS;
function DAO : iSimpleDAO<TDPAIS>;
function DataSource (aDataSource : TDataSource) : iModelPais;
end;
implementation
{ TModelPais }
constructor TModelPais.Create;
begin
FEntidade := TDPAIS.Create;
FDAO := TSimpleDAO<TDPAIS>
.New(TSimpleQueryRestDW<TDPAIS>
.New(ModelConexion.RESTDWDataBase1));
end;
function TModelPais.DAO: iSimpleDAO<TDPAIS>;
begin
Result := FDAO;
end;
function TModelPais.DataSource(aDataSource: TDataSource): iModelPais;
begin
Result := Self;
FDataSource := aDataSource;
FDAO.DataSource(FDataSource);
end;
destructor TModelPais.Destroy;
begin
FreeAndNil(FEntidade);
inherited;
end;
function TModelPais.Entidad: TDPAIS;
begin
Result := FEntidade;
end;
class function TModelPais.New: iModelPais;
begin
Result := Self.Create;
end;
end.
|
//---------------------------------------------------------------------------
// This software is Copyright (c) 2015 Embarcadero Technologies, Inc.
// You may only use this software if you are an authorized licensee
// of an Embarcadero developer tools product.
// This software is considered a Redistributable as defined under
// the software license agreement that comes with the Embarcadero Products
// and is subject to that software license agreement.
//---------------------------------------------------------------------------
unit Breakable;
interface
uses
Box2D.Common, Box2D.Collision, Box2D.Dynamics, Test;
type
TBreakable = class(TTest)
protected
m_body1: b2BodyWrapper;
m_velocity: b2Vec2;
m_angularVelocity: float32;
m_shape1: b2PolygonShapeWrapper;
m_shape2: b2PolygonShapeWrapper;
m_piece1: Pb2Fixture;
m_piece2: Pb2Fixture;
m_broke: Boolean;
m_break: Boolean;
public
constructor Create;
destructor Destroy; override;
class function CreateTest: TTest; static;
procedure Break;
procedure Step(settings: PSettings); override;
procedure Keyboard(key: Integer); override;
procedure PostSolve(contact: b2ContactHandle; impulse: Pb2ContactImpulse); override; cdecl;
end;
implementation
uses
System.Math,
DebugDraw;
procedure TBreakable.Break;
var
body1: b2BodyWrapper;
body2: b2BodyWrapper;
center: b2Vec2;
center1: b2Vec2;
center2: b2Vec2;
velocity1: b2Vec2;
velocity2: b2Vec2;
bd: b2BodyDef;
begin
// Create two bodies from one.
body1 := m_piece1.GetBody;
center := body1.GetWorldCenter^;
body1.DestroyFixture(m_piece2);
m_piece2 := nil;
bd := b2BodyDef.Create;
bd.&type := b2_dynamicBody;
bd.position := body1.GetPosition^;
bd.angle := body1.GetAngle;
body2 := m_world.CreateBody(@bd);
m_piece2 := body2.CreateFixture(m_shape2, 1.0);
// Compute consistent velocities for new bodies based on
// cached velocity.
center1 := body1.GetWorldCenter^;
center2 := body2.GetWorldCenter^;
velocity1 := m_velocity + b2Cross(m_angularVelocity, center1 - center);
velocity2 := m_velocity + b2Cross(m_angularVelocity, center2 - center);
body1.SetAngularVelocity(m_angularVelocity);
body1.SetLinearVelocity(velocity1);
body2.SetAngularVelocity(m_angularVelocity);
body2.SetLinearVelocity(velocity2);
end;
constructor TBreakable.Create;
var
bd: b2BodyDef;
ground: b2BodyWrapper;
shape: b2EdgeShapeWrapper;
begin
inherited;
// Ground body
bd := b2BodyDef.Create;
ground := m_world.CreateBody(@bd);
shape := b2EdgeShapeWrapper.Create;
shape.&Set(b2Vec2.Create(-40.0, 0.0), b2Vec2.Create(40.0, 0.0));
ground.CreateFixture(shape, 0.0);
shape.Destroy;
// Breakable dynamic body
bd := b2BodyDef.Create;
bd.&type := b2_dynamicBody;
bd.position.&Set(0.0, 40.0);
bd.angle := 0.25 * pi;
m_body1 := m_world.CreateBody(@bd);
m_shape1 := b2PolygonShapeWrapper.Create;
m_shape1.SetAsBox(0.5, 0.5, b2Vec2.Create(-0.5, 0.0), 0.0);
m_piece1 := m_body1.CreateFixture(m_shape1, 1.0);
m_shape2 := b2PolygonShapeWrapper.Create;
m_shape2.SetAsBox(0.5, 0.5, b2Vec2.Create(0.5, 0.0), 0.0);
m_piece2 := m_body1.CreateFixture(m_shape2, 1.0);
m_break := false;
m_broke := false;
end;
class function TBreakable.CreateTest: TTest;
begin
Result := TBreakable.Create;
end;
destructor TBreakable.Destroy;
begin
m_shape1.Destroy;
m_shape2.Destroy;
inherited;
end;
procedure TBreakable.Keyboard(key: Integer);
begin
inherited;
end;
procedure TBreakable.PostSolve(contact: b2ContactHandle; impulse: Pb2ContactImpulse);
var
maxImpulse: float32;
count: Integer;
LContact: b2ContactWrapper;
I: Integer;
begin
// The body already broke.
if m_broke then
Exit;
// Should the body break?
LContact := contact;
count := LContact.GetManifold.pointCount;
maxImpulse := 0.0;
for I := 0 to count -1 do
begin
maxImpulse := Max(maxImpulse, impulse.normalImpulses[I]);
end;
if maxImpulse > 40.0 then
begin
// Flag the body for breaking.
m_break := true;
end;
end;
procedure TBreakable.Step(settings: PSettings);
begin
if (m_break) then
begin
Break;
m_broke := true;
m_break := false;
end;
// Cache velocities to improve movement on breakage.
if (m_broke = false) then
begin
m_velocity := m_body1.GetLinearVelocity^;
m_angularVelocity := m_body1.GetAngularVelocity;
end;
inherited Step(settings);
end;
initialization
RegisterTest(TestEntry.Create('Breakable', @TBreakable.CreateTest));
end.
|
{*********************************************************************************************}
{ }
{ XML Data Binding }
{ }
{ Generated on: 11-7-2013 13:10:26 }
{ Generated from: Z:\pg\Documents\pgdemos\FMWeather\src\sample_data\CountryCities.xml }
{ Settings stored in: Z:\pg\Documents\pgdemos\FMWeather\src\sample_data\CountryCities.xdb }
{ }
{*********************************************************************************************}
unit xmlbinding_countrycities;
interface
uses xmldom, XMLDoc, XMLIntf;
type
{ Forward Decls }
IXMLNewDataSetType = interface;
IXMLTableType = interface;
{ IXMLNewDataSetType }
IXMLNewDataSetType = interface(IXMLNodeCollection)
['{61100614-21E5-4B6E-B2A0-42114ABDA229}']
{ Property Accessors }
function Get_Table(Index: Integer): IXMLTableType;
{ Methods & Properties }
function Add: IXMLTableType;
function Insert(const Index: Integer): IXMLTableType;
property Table[Index: Integer]: IXMLTableType read Get_Table; default;
end;
{ IXMLTableType }
IXMLTableType = interface(IXMLNode)
['{1591411A-F784-4342-83AC-D88558534005}']
{ Property Accessors }
function Get_Country: UnicodeString;
function Get_City: UnicodeString;
procedure Set_Country(Value: UnicodeString);
procedure Set_City(Value: UnicodeString);
{ Methods & Properties }
property Country: UnicodeString read Get_Country write Set_Country;
property City: UnicodeString read Get_City write Set_City;
end;
{ Forward Decls }
TXMLNewDataSetType = class;
TXMLTableType = class;
{ TXMLNewDataSetType }
TXMLNewDataSetType = class(TXMLNodeCollection, IXMLNewDataSetType)
protected
{ IXMLNewDataSetType }
function Get_Table(Index: Integer): IXMLTableType;
function Add: IXMLTableType;
function Insert(const Index: Integer): IXMLTableType;
public
procedure AfterConstruction; override;
end;
{ TXMLTableType }
TXMLTableType = class(TXMLNode, IXMLTableType)
protected
{ IXMLTableType }
function Get_Country: UnicodeString;
function Get_City: UnicodeString;
procedure Set_Country(Value: UnicodeString);
procedure Set_City(Value: UnicodeString);
end;
{ Global Functions }
function GetNewDataSet(Doc: IXMLDocument): IXMLNewDataSetType;
function LoadNewDataSet(const FileName: string): IXMLNewDataSetType;
function NewNewDataSet: IXMLNewDataSetType;
const
TargetNamespace = '';
implementation
{ Global Functions }
function GetNewDataSet(Doc: IXMLDocument): IXMLNewDataSetType;
begin
Result := Doc.GetDocBinding('NewDataSet', TXMLNewDataSetType, TargetNamespace) as IXMLNewDataSetType;
end;
function LoadNewDataSet(const FileName: string): IXMLNewDataSetType;
begin
Result := LoadXMLDocument(FileName).GetDocBinding('NewDataSet', TXMLNewDataSetType, TargetNamespace) as IXMLNewDataSetType;
end;
function NewNewDataSet: IXMLNewDataSetType;
begin
Result := NewXMLDocument.GetDocBinding('NewDataSet', TXMLNewDataSetType, TargetNamespace) as IXMLNewDataSetType;
end;
{ TXMLNewDataSetType }
procedure TXMLNewDataSetType.AfterConstruction;
begin
RegisterChildNode('Table', TXMLTableType);
ItemTag := 'Table';
ItemInterface := IXMLTableType;
inherited;
end;
function TXMLNewDataSetType.Get_Table(Index: Integer): IXMLTableType;
begin
Result := List[Index] as IXMLTableType;
end;
function TXMLNewDataSetType.Add: IXMLTableType;
begin
Result := AddItem(-1) as IXMLTableType;
end;
function TXMLNewDataSetType.Insert(const Index: Integer): IXMLTableType;
begin
Result := AddItem(Index) as IXMLTableType;
end;
{ TXMLTableType }
function TXMLTableType.Get_Country: UnicodeString;
begin
Result := ChildNodes['Country'].Text;
end;
procedure TXMLTableType.Set_Country(Value: UnicodeString);
begin
ChildNodes['Country'].NodeValue := Value;
end;
function TXMLTableType.Get_City: UnicodeString;
begin
Result := ChildNodes['City'].Text;
end;
procedure TXMLTableType.Set_City(Value: UnicodeString);
begin
ChildNodes['City'].NodeValue := Value;
end;
end. |
unit Datapar.Conexao.DBExpress;
interface
uses
Data.DB, Datapar.Conexao, Data.FMTBcd, Data.SqlExpr, Data.DBXOracle;
type
TExpressQuery = class(TDataparQuery)
strict private
FConnection : TSQLConnection;
FQuery: TSQLQuery;
public
constructor create(AProvider: TDataparProvider);
function executaSql(ACommand: TDataparCommand): TDataSet; override;
end;
implementation
{ TFireQuery }
constructor TExpressQuery.create(AProvider: TDataparProvider);
begin
if FConnection = nil then
begin
FConnection := TSQLConnection.Create(Nil);
FConnection.DriverName := AProvider.DriverName;
FConnection.Params.Values['DriverName'] := AProvider.DriverName;
FConnection.Params.Values['DataBase'] := AProvider.Host;
FConnection.Params.Values['User_Name'] := AProvider.User;
FConnection.Params.Values['Password'] := AProvider.Password;
end;
FConnection.Connected := True;
end;
function TExpressQuery.executaSql(ACommand: TDataparCommand): TDataSet;
begin
FQuery:= TSQLQuery.Create(Nil);
FQuery.SQLConnection := FConnection;
FQuery.SQL.Add(ACommand.SQL);
FQuery.Active := True;
Result := FQuery;
end;
end.
|
//
// VXScene Component Library, based on GLScene http://glscene.sourceforge.net
//
{
A PFX whose particles are lines
}
unit VXS.LinePFX;
interface
{$I VXScene.inc}
uses
System.Classes,
System.SysUtils,
VXS.OpenGL,
VXS.PersistentClasses,
VXS.VectorGeometry,
VXS.ParticleFX,
VXS.Texture,
VXS.Color,
VXS.RenderContextInfo,
VXS.Context,
VXS.VectorTypes;
type
{ Linear particle. }
TVXLineParticle = class (TVXParticle)
private
FDirection : TAffineVector;
FLength : Single;
protected
public
procedure WriteToFiler(writer : TVirtualWriter); override;
procedure ReadFromFiler(reader : TVirtualReader); override;
{ Direction of the line. }
property Direction : TAffineVector read FDirection write FDirection;
{ Length of the line }
property Length : Single read FLength write FLength;
end;
{ Polygonal particles FX manager.
The particles of this manager are made of N-face regular polygon with
a core and edge color. No texturing is available.
If you render large particles and don't have T&L acceleration, consider
using TVXPointLightPFXManager. }
TVXLinePFXManager = class (TVXLifeColoredPFXManager)
private
Fvx, Fvy : TAffineVector; // NOT persistent
FNvx, FNvy : TAffineVector; // NOT persistent
FDefaultLength : Single;
protected
function StoreDefaultLength : Boolean;
function TexturingMode : Cardinal; override;
procedure InitializeRendering(var rci: TVXRenderContextInfo); override;
procedure BeginParticles(var rci: TVXRenderContextInfo); override;
procedure RenderParticle(var rci: TVXRenderContextInfo; aParticle : TVXParticle); override;
procedure EndParticles(var rci: TVXRenderContextInfo); override;
procedure FinalizeRendering(var rci: TVXRenderContextInfo); override;
public
constructor Create(aOwner : TComponent); override;
destructor Destroy; override;
class function ParticlesClass : TVXParticleClass; override;
function CreateParticle : TVXParticle; override;
published
property DefaultLength : Single read FDefaultLength write FDefaultLength stored StoreDefaultLength;
property ParticleSize;
property ColorInner;
property ColorOuter;
property LifeColors;
end;
// ------------------------------------------------------------------
implementation
// ------------------------------------------------------------------
// ------------------
// ------------------ TVXLinePFXManager ------------------
// ------------------
constructor TVXLinePFXManager.Create(aOwner : TComponent);
begin
inherited;
FDefaultLength:=1;
end;
destructor TVXLinePFXManager.Destroy;
begin
inherited Destroy;
end;
class function TVXLinePFXManager.ParticlesClass : TVXParticleClass;
begin
Result:=TVXLineParticle;
end;
function TVXLinePFXManager.CreateParticle : TVXParticle;
begin
Result:=inherited CreateParticle;
TVXLineParticle(Result).FLength:=DefaultLength;
end;
function TVXLinePFXManager.TexturingMode : Cardinal;
begin
Result:=0;
end;
procedure TVXLinePFXManager.InitializeRendering(var rci: TVXRenderContextInfo);
var
i : Integer;
matrix : TMatrix;
begin
inherited;
glGetFloatv(GL_MODELVIEW_MATRIX, @matrix);
for i:=0 to 2 do begin
Fvx.V[i]:=matrix.V[i].X;
Fvy.V[i]:=matrix.V[i].Y;
end;
FNvx:=VectorNormalize(Fvx);
FNvy:=VectorNormalize(Fvy);
end;
procedure TVXLinePFXManager.BeginParticles(var rci: TVXRenderContextInfo);
begin
ApplyBlendingMode(rci);
end;
procedure TVXLinePFXManager.RenderParticle(var rci: TVXRenderContextInfo; aParticle : TVXParticle);
var
lifeTime, sizeScale, fx, fy, f : Single;
inner, outer : TColorVector;
pos, dir, start, stop, dv : TAffineVector;
begin
lifeTime:=CurrentTime-aParticle.CreationTime;
ComputeColors(lifeTime, inner, outer);
if ComputeSizeScale(lifeTime, sizeScale) then
sizeScale:=sizeScale*ParticleSize
else sizeScale:=ParticleSize;
pos:=aParticle.Position;
with TVXLineParticle(aParticle) do begin
dir:=VectorNormalize(aParticle.Velocity);
f:=Length*0.5;
end;
start:=VectorCombine(pos, dir, 1, f);
stop:=VectorCombine(pos, dir, 1, -f);
fx:=VectorDotProduct(dir, FNvy)*sizeScale;
fy:=-VectorDotProduct(dir, FNvx)*sizeScale;
dv:=VectorCombine(Fvx, Fvy, fx, fy);
glBegin(GL_TRIANGLE_FAN);
glColor4fv(@inner);
glVertex3fv(@start);
glColor4fv(@outer);
glVertex3f(start.X+dv.X, start.Y+dv.Y, start.Z+dv.Z);
glVertex3f(stop.X+dv.X, stop.Y+dv.Y, stop.Z+dv.Z);
glColor4fv(@inner);
glVertex3fv(@stop);
glColor4fv(@outer);
glVertex3f(stop.X-dv.X, stop.Y-dv.Y, stop.Z-dv.Z);
glVertex3f(start.X-dv.X, start.Y-dv.Y, start.Z-dv.Z);
glEnd;
end;
procedure TVXLinePFXManager.EndParticles(var rci: TVXRenderContextInfo);
begin
UnapplyBlendingMode(rci);
end;
procedure TVXLinePFXManager.FinalizeRendering(var rci: TVXRenderContextInfo);
begin
inherited;
end;
function TVXLinePFXManager.StoreDefaultLength : Boolean;
begin
Result:=(FDefaultLength<>1);
end;
// ------------------
// ------------------ TVXLineParticle ------------------
// ------------------
procedure TVXLineParticle.WriteToFiler(writer : TVirtualWriter);
begin
inherited WriteToFiler(writer);
with writer do begin
WriteInteger(0); // Archive Version 0
Write(FDirection, SizeOf(FDirection));
WriteFloat(FLength);
end;
end;
procedure TVXLineParticle.ReadFromFiler(reader : TVirtualReader);
var
archiveVersion : integer;
begin
inherited ReadFromFiler(reader);
archiveVersion:=reader.ReadInteger;
if archiveVersion=0 then with reader do begin
Read(FDirection, SizeOf(FDirection));
FLength:=ReadFloat;
end else RaiseFilerException(archiveVersion);
end;
// ------------------------------------------------------------------
initialization
// ------------------------------------------------------------------
// class registrations
RegisterClasses([TVXLineParticle, TVXLinePFXManager]);
end.
|
unit Unit1;
interface
uses
Winapi.Windows,
Winapi.Messages,
System.SysUtils,
System.Variants,
System.Classes,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
GLCadencer,
GLTexture,
GLWin32Viewer,
GLScene,
GLObjects,
GLMaterial,
GLFileTGA,
GLCoordinates,
GLTeapot,
GLCrossPlatform,
GLBaseClasses;
type
TForm1 = class(TForm)
GLScene: TGLScene;
GLSceneViewer: TGLSceneViewer;
GLMaterialLibrary: TGLMaterialLibrary;
GLCadencer: TGLCadencer;
gloCamera: TGLCamera;
gloFog: TGLDummyCube;
gloFogZ2: TGLPlane;
gloFogY3: TGLPlane;
gloFogZ1: TGLPlane;
gloFogY1: TGLPlane;
gloFogX3: TGLPlane;
gloFogY2: TGLPlane;
gloFogZ3: TGLPlane;
gloFogX2: TGLPlane;
gloFogX1: TGLPlane;
gloLight: TGLLightSource;
gloTeapot: TGLTeapot;
procedure FormCreate(Sender: TObject);
procedure GLCadencerProgress(Sender: TObject; const deltaTime,
newTime: Double);
private
public
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
var
i : integer;
NewMat : TGLLibMaterial;
begin
randomize;
with GLMaterialLibrary.Materials do
begin
for i:=1 to 5 do
begin
NewMat := Add;
NewMat.Name := 'cloud' + inttostr(i);
NewMat.Material.Texture.Image.LoadFromFile('textures\cloud' + inttostr(i) + '.tga');
NewMat.Material.MaterialOptions := [moNoLighting];
NewMat.Material.Texture.Enabled := True;
NewMat.Material.Texture.TextureMode := tmReplace;
NewMat.Material.BlendingMode := bmTransparency;
end;
end;
with gloFog do
begin
for i:=0 to 8 do
begin
TGLPlane(Children[i]).Material.MaterialLibrary := GLMaterialLibrary;
TGLPlane(Children[i]).Material.LibMaterialName := 'cloud' + inttostr(random(4)+1);
end;
end;
end;
procedure TForm1.GLCadencerProgress(Sender: TObject; const deltaTime,
newTime: Double);
begin
gloFog.Turn(10*deltaTime);
gloTeaPot.Position.Y := Sin(newTime) * 5;
end;
end.
|
unit ufrmDialogSubGroup;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, ufrmMasterDialog, System.Actions,
Vcl.ActnList, ufraFooterDialog3Button, Vcl.ExtCtrls, uInterface, uModBarang,
cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer,
cxEdit, Vcl.StdCtrls, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxLookupEdit,
cxDBLookupEdit, cxDBExtLookupComboBox, uModSuplier;
type
TfrmDialogSubGroup = class(TfrmMasterDialog, ICRUDAble)
lbDivision: TLabel;
cxLookupMerGroup: TcxExtLookupComboBox;
edtCode: TEdit;
lbKode: TLabel;
lbNama: TLabel;
edtName: TEdit;
procedure actDeleteExecute(Sender: TObject);
procedure actSaveExecute(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
FModSubGroup: TModSubGroup;
function GetModSubGroup: TModSubGroup;
function ValidateData: Boolean;
{ Private declarations }
public
procedure LoadData(AID: String);
procedure SaveData;
property ModSubGroup: TModSubGroup read GetModSubGroup write FModSubGroup;
{ Public declarations }
end;
var
frmDialogSubGroup: TfrmDialogSubGroup;
implementation
uses
uAppUtils, uConstanta, uDMClient, uDXUtils;
{$R *.dfm}
procedure TfrmDialogSubGroup.actDeleteExecute(Sender: TObject);
begin
inherited;
if not TAppUtils.Confirm(CONF_VALIDATE_FOR_DELETE) then exit;
Try
DMCLient.CrudClient.DeleteFromDB(ModSubGroup);
TAppUtils.Information(CONF_DELETE_SUCCESSFULLY);
Self.ModalResult := mrOk;
Self.Close;
except
TAppUtils.Error(ER_DELETE_FAILED);
raise;
End;
end;
procedure TfrmDialogSubGroup.actSaveExecute(Sender: TObject);
begin
inherited;
if not ValidateData then exit;
SaveData;
Self.ModalResult := mrOk;
end;
procedure TfrmDialogSubGroup.FormCreate(Sender: TObject);
begin
inherited;
cxLookupMerGroup.LoadFromDS(
DMClient.DSProviderClient.MerchandiseGroup_GetDSLookup,
'REF$MERCHANDISE_GRUP_ID','MERCHANGRUP_NAME' ,
['REF$MERCHANDISE_GRUP_ID','REF$MERCHANDISE_ID'], Self);
Self.AssignKeyDownEvent;
end;
function TfrmDialogSubGroup.GetModSubGroup: TModSubGroup;
begin
if not Assigned(FModSubGroup) then
FModSubGroup := TModSubGroup.Create;
Result := FModSubGroup;
end;
procedure TfrmDialogSubGroup.LoadData(AID: String);
begin
if Assigned(FModSubGroup) then FreeAndNil(FModSubGroup);
FModSubGroup := DMClient.CrudClient.Retrieve(TModSubGroup.ClassName, aID) as TModSubGroup;
edtCode.Text := ModSubGroup.SUBGRUP_CODE;
edtName.Text := ModSubGroup.SUBGRUP_NAME;
cxLookupMerGroup.EditValue := ModSubGroup.MerchandiseGroup.ID;
end;
procedure TfrmDialogSubGroup.SaveData;
begin
ModSubGroup.SUBGRUP_CODE := edtCode.Text;
ModSubGroup.SUBGRUP_NAME := edtName.Text;
ModSubGroup.MerchandiseGroup := TModMerchandiseGroup.CreateID(cxLookupMerGroup.EditValue);
Try
ModSubGroup.ID := DMClient.CrudClient.SaveToDBID(ModSubGroup);
TAppUtils.Information(CONF_ADD_SUCCESSFULLY);
except
TAppUtils.Error(ER_INSERT_FAILED);
raise;
End;
end;
function TfrmDialogSubGroup.ValidateData: Boolean;
begin
Result := False;
if VarIsNull(cxLookupMerGroup.EditValue) then
begin
TAppUtils.Error('Merchandise Group wajib dipilih');
exit;
end;
if edtCode.Text = '' then
begin
TAppUtils.Error('Kode tidak boleh kosong');
exit;
end;
if edtName.Text = '' then
begin
TAppUtils.Error('Nama tidak boleh kosong');
exit;
end;
Result := True;
end;
end.
|
program HowToUseRadioButton;
uses
SwinGame, sgTypes, sgUserInterface;
procedure Main();
var
cp : Panel;
begin
OpenGraphicsWindow('How To Radio Button ', 400, 150);
LoadDefaultColors();
cp := LoadPanel('radioPanel.txt');
ShowPanel(cp);
PanelSetDraggable(cp, false);
repeat // The game loop...
ProcessEvents();
ClearScreen(ColorWhite);
DrawInterface();
UpdateInterface();
RefreshScreen();
until WindowCloseRequested();
ReleaseAllResources();
end;
begin
Main();
end. |
unit AsConvertOpTest;
{$mode objfpc}{$H+}
interface
uses
fpcunit,
testregistry,
uIntXLibTypes,
uIntX;
type
{ TTestAsConvertOp }
TTestAsConvertOp = class(TTestCase)
published
procedure AsInteger();
procedure AsUInt32();
procedure AsInt64();
procedure AsUInt64();
private
procedure ProcIntegerOne();
procedure ProcIntegerTwo();
procedure ProcIntegerThree();
procedure ProcIntegerFour();
procedure ProcIntegerFive();
procedure ProcUInt32One();
procedure ProcUInt32Two();
procedure ProcUInt32Three();
procedure ProcInt64One();
procedure ProcInt64Two();
procedure ProcInt64Three();
procedure ProcInt64Four();
procedure ProcUInt64One();
procedure ProcUInt64Two();
procedure ProcUInt64Three();
end;
implementation
{ TTestAsConvertOp }
procedure TTestAsConvertOp.AsInteger;
var
n: integer;
IntX: TIntX;
begin
AssertException(EOverflowException, @ProcIntegerOne);
n := 1234567890;
IntX := n;
AssertEquals(n, integer(IntX));
n := -n;
IntX := n;
AssertEquals(n, integer(IntX));
n := 0;
IntX := n;
AssertEquals(n, integer(IntX));
AssertException(EOverflowException, @ProcIntegerTwo);
AssertException(EOverflowException, @ProcIntegerThree);
AssertException(EOverflowException, @ProcIntegerFour);
AssertException(EOverflowException, @ProcIntegerFive);
end;
procedure TTestAsConvertOp.AsUInt32;
var
IntX: TIntX;
n: UInt32;
begin
n := 1234567890;
IntX := n;
AssertEquals(n, UInt32(IntX));
n := 0;
IntX := n;
AssertEquals(n, UInt32(IntX));
AssertException(EOverflowException, @ProcUInt32One);
AssertException(EOverflowException, @ProcUInt32Two);
AssertException(EOverflowException, @ProcUInt32Three);
end;
procedure TTestAsConvertOp.AsInt64;
var
IntX: TIntX;
n: int64;
ni: integer;
begin
n := 1234567890123456789;
IntX := n;
AssertEquals(n, int64(IntX));
n := -n;
IntX := n;
AssertEquals(n, int64(IntX));
n := 0;
IntX := n;
AssertEquals(n, int64(IntX));
ni := 1234567890;
n := ni;
IntX := ni;
AssertEquals(n, int64(IntX));
AssertException(EOverflowException, @ProcInt64One);
AssertException(EOverflowException, @ProcInt64Two);
AssertException(EOverflowException, @ProcInt64Three);
AssertException(EOverflowException, @ProcInt64Four);
end;
procedure TTestAsConvertOp.AsUInt64;
var
IntX: TIntX;
n: UInt64;
begin
n := 1234567890123456789;
IntX := n;
AssertTrue(n = UInt64(IntX));
n := 0;
IntX := n;
AssertTrue(n = UInt64(IntX));
AssertException(EOverflowException, @ProcUInt64One);
AssertException(EOverflowException, @ProcUInt64Two);
AssertException(EOverflowException, @ProcUInt64Three);
end;
procedure TTestAsConvertOp.ProcIntegerOne;
var
IntX: TIntX;
begin
IntX := TIntX.Create(High(UInt32));
IntX.AsInteger;
end;
procedure TTestAsConvertOp.ProcIntegerTwo;
var
temp: TIntXLibUInt32Array;
n: integer;
IntX: TIntX;
un: UInt32;
begin
n := 1234567890;
un := UInt32(n);
SetLength(temp, 3);
temp[0] := un;
temp[1] := un;
temp[2] := un;
IntX := TIntX.Create(temp, False);
IntX.AsInteger;
end;
procedure TTestAsConvertOp.ProcIntegerThree;
var
temp: TIntXLibUInt32Array;
n: integer;
IntX: TIntX;
un: UInt32;
begin
n := 1234567890;
un := UInt32(n);
SetLength(temp, 3);
temp[0] := un;
temp[1] := un;
temp[2] := un;
IntX := TIntX.Create(temp, True);
IntX.AsInteger;
end;
procedure TTestAsConvertOp.ProcIntegerFour;
var
IntX: TIntX;
begin
IntX := TIntX.Create(High(integer)) + 10;
IntX.AsInteger;
end;
procedure TTestAsConvertOp.ProcIntegerFive;
var
IntX: TIntX;
begin
IntX := TIntX.Create(Low(integer)) - 10;
IntX.AsInteger;
end;
procedure TTestAsConvertOp.ProcUInt32One;
var
temp: TIntXLibUInt32Array;
IntX: TIntX;
n: UInt32;
begin
n := 1234567890;
SetLength(temp, 3);
temp[0] := n;
temp[1] := n;
temp[2] := n;
IntX := TIntX.Create(temp, False);
IntX.AsUInt32;
end;
procedure TTestAsConvertOp.ProcUInt32Two;
var
IntX: TIntX;
begin
IntX := TIntX.Create(High(UInt32)) + 10;
IntX.AsUInt32;
end;
procedure TTestAsConvertOp.ProcUInt32Three;
var
IntX: TIntX;
begin
IntX := TIntX.Create(Low(UInt32)) - 10;
IntX.AsUInt32;
end;
procedure TTestAsConvertOp.ProcInt64One;
var
temp: TIntXLibUInt32Array;
IntX: TIntX;
un: UInt32;
begin
un := 1234567890;
SetLength(temp, 5);
temp[0] := un;
temp[1] := un;
temp[2] := un;
temp[3] := un;
temp[4] := un;
IntX := TIntX.Create(temp, False);
IntX.AsInt64;
end;
procedure TTestAsConvertOp.ProcInt64Two;
var
temp: TIntXLibUInt32Array;
IntX: TIntX;
un: UInt32;
begin
un := 1234567890;
SetLength(temp, 5);
temp[0] := un;
temp[1] := un;
temp[2] := un;
temp[3] := un;
temp[4] := un;
IntX := TIntX.Create(temp, True);
IntX.AsInt64;
end;
procedure TTestAsConvertOp.ProcInt64Three;
var
IntX: TIntX;
begin
IntX := TIntX.Create(High(int64)) + 10;
IntX.AsInt64;
end;
procedure TTestAsConvertOp.ProcInt64Four;
var
IntX: TIntX;
begin
IntX := TIntX.Create(Low(int64)) - 10;
IntX.AsInt64;
end;
procedure TTestAsConvertOp.ProcUInt64One;
var
temp: TIntXLibUInt32Array;
IntX: TIntX;
un: UInt32;
begin
un := 1234567890;
SetLength(temp, 5);
temp[0] := un;
temp[1] := un;
temp[2] := un;
temp[3] := un;
temp[4] := un;
IntX := TIntX.Create(temp, False);
IntX.AsUInt64;
end;
procedure TTestAsConvertOp.ProcUInt64Two;
var
IntX: TIntX;
begin
IntX := TIntX.Create(High(UInt64)) + 10;
IntX.AsUInt64;
end;
procedure TTestAsConvertOp.ProcUInt64Three;
var
IntX: TIntX;
begin
IntX := TIntX.Create(Low(UInt64)) - 10;
IntX.AsUInt64;
end;
initialization
RegisterTest(TTestAsConvertOp);
end.
|
namespace GlHelper;
{$GLOBALS ON}
interface
uses
rtl,
RemObjects.Elements.RTL;
{$IF ISLAND}
{$DEFINE FIXMATHERROR} // Use own implementation of Pow because error in RTL Island
{$ENDIF}
const
{ Default tolerance for comparing small floating-point values. }
SINGLE_TOLERANCE = 0.000001;
EPSILON: Single = 1E-40;
method Sqrt(const A: Single): Single; inline;
method InverseSqrt(const A: Single): Single; inline;
method ArcTan2(const Y, X: Single): Single; inline;
method Abs(const A: Single): Single; inline;
method Mix(const A, B, T: Single): Single; inline;
method Mix(const A, B: TVector2; const T: Single): TVector2; inline;
method Mix(const A, B: TVector3; const T: Single): TVector3; inline;
method Mix(const A, B, T: TVector3): TVector3; inline;
method Mix(const A, B: TVector4; const T: Single): TVector4; inline;
method Mix(const A, B, T: TVector4): TVector4; inline;
method SinCos(const ARadians: Single; out ASin, ACos: Single); inline;
method SinCos(const ARadians: TVector4; out ASin, ACos: TVector4); inline;
method Radians(const ADegrees: Single): Single; inline;
method EnsureRange(const A, AMin, AMax: Single): Single; inline;
implementation
method Sqrt(const A: Single): Single;
begin
{$IF FIXMATHERROR}
exit math.Exp(0.5 * Math.Log(A));
{$ELSE}
Result := Math.Sqrt(A);
{$ENDIF}
end;
method InverseSqrt(const A: Single): Single;
begin
Result := 1 / Sqrt(A)
end;
method ArcTan2(const Y, X: Single): Single;
begin
Result := Math.Atan2(Y, X);
end;
method Abs(const A: Single): Single;
begin
Result := Math.Abs(A);
end;
method Mix(const A, B, T: Single): Single;
begin
Result := A + (T * (B - A)); // Faster
end;
method Mix(const A, B: TVector2; const T: Single): TVector2;
begin
Result.Init(Mix(A.X, B.X, T), Mix(A.Y, B.Y, T));
end;
method Mix(const A, B: TVector3; const T: Single): TVector3;
begin
Result.Init(Mix(A.X, B.X, T), Mix(A.Y, B.Y, T), Mix(A.Z, B.Z, T));
end;
method Mix(const A, B, T: TVector3): TVector3;
begin
Result.Init(Mix(A.X, B.X, T.X), Mix(A.Y, B.Y, T.Y), Mix(A.Z, B.Z, T.Z));
end;
method Mix(const A, B: TVector4; const T: Single): TVector4;
begin
Result.Init(Mix(A.X, B.X, T), Mix(A.Y, B.Y, T), Mix(A.Z, B.Z, T), Mix(A.W, B.W, T));
end;
method Mix(const A, B, T: TVector4): TVector4;
begin
Result.Init(Mix(A.X, B.X, T.X), Mix(A.Y, B.Y, T.Y), Mix(A.Z, B.Z, T.Z), Mix(A.W, B.W, T.W));
end;
method SinCos(const ARadians: Single; out ASin, ACos: Single);
begin
ASin := Math.Sin(ARadians);
ACos := Math.Cos(ARadians);
end;
method SinCos(const ARadians: TVector4; out ASin, ACos: TVector4);
begin
SinCos(ARadians.X, out ASin.X, out ACos.X);
SinCos(ARadians.Y, out ASin.Y, out ACos.Y);
SinCos(ARadians.Z, out ASin.Z, out ACos.Z);
SinCos(ARadians.W, out ASin.W, out ACos.W);
end;
method Radians(const ADegrees: Single): Single;
begin
Result := ADegrees * (Consts.PI / 180);
end;
method EnsureRange(const A, AMin, AMax: Single): Single;
begin
Result := A;
if Result < AMin then
Result := AMin;
if Result > AMax then
Result := AMax;
end;
end. |
(***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is TurboPower Async Professional
*
* The Initial Developer of the Original Code is
* TurboPower Software
*
* Portions created by the Initial Developer are Copyright (C) 1991-2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** *)
{*********************************************************}
{* EXSAPIB0.PAS 4.06 *}
{*********************************************************}
{**********************Description************************}
{* Demonstrates how to create a simple voice telephony *}
{* application using SAPI *}
{*********************************************************}
unit ExSapiB0;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
OoMisc, AdSapiEn, StdCtrls, Gauges, AdPort, AdTapi, AdSapiPh;
type
TPhraseType = (ptHelp, ptDate, ptTime, ptQuit, ptUnknown);
TForm1 = class(TForm)
Gauge1: TGauge;
Label1: TLabel;
Label2: TLabel;
Button1: TButton;
Memo1: TMemo;
ApdSapiEngine1: TApdSapiEngine;
ApdSapiPhone1: TApdSapiPhone;
ApdComPort1: TApdComPort;
function AnalyzePhrase (Phrase : string) : TPhraseType;
procedure SaySomething (Something : string);
procedure FindPhoneEngines;
procedure Button1Click(Sender: TObject);
procedure ApdSapiEngine1VUMeter(Sender: TObject; Level: Integer);
procedure ApdSapiPhone1TapiConnect(Sender: TObject);
procedure ApdSapiEngine1PhraseFinish(Sender: TObject;
const Phrase: String);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
function TForm1.AnalyzePhrase (Phrase : string) : TPhraseType;
begin
Result := ptUnknown;
if Phrase = 'help' then
Result := ptHelp
else if (Phrase = 'close') or (Phrase = 'exit') or
(Phrase = 'goodbye') or (Phrase = 'end') or
(Phrase = 'bye') then
Result := ptQuit
else if (Phrase = 'what time is it') or (Phrase = 'time') then
Result := ptTime
else if (Phrase = 'what day is it') or (Phrase = 'day') then
Result := ptDate;
end;
procedure TForm1.SaySomething (Something : string);
begin
Memo1.Lines.Add ('--> ' + Something);
ApdSapiEngine1.Speak (Something);
end;
procedure TForm1.FindPhoneEngines;
procedure SetSSEngine;
var
i : Integer;
begin
for i := 0 to ApdSapiEngine1.SSVoices.Count - 1 do
if tfPhoneOptimized in ApdSapiEngine1.SSVoices.Features[i] then begin
ApdSapiEngine1.SSVoices.CurrentVoice := i;
Exit;
end;
raise Exception.Create ('No phone enabled speech synthesis engine was found');
end;
procedure SetSREngine;
var
i : Integer;
begin
for i := 0 to ApdSapiEngine1.SREngines.Count - 1 do
if sfPhoneOptimized in ApdSapiEngine1.SREngines.Features[i] then begin
ApdSapiEngine1.SREngines.CurrentEngine := i;
Exit;
end;
raise Exception.Create ('No phone enabled speech recognition engine was found');
end;
begin
SetSSEngine;
SetSREngine;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
with ApdSapiEngine1.WordList do begin
Clear;
Add ('close');
Add ('exit');
Add ('goodbye');
Add ('end');
Add ('bye');
Add ('what time is it');
Add ('time');
Add ('what day is it');
Add ('day');
Add ('help');
end;
FindPhoneEngines;
ApdSapiPhone1.AutoAnswer;
end;
procedure TForm1.ApdSapiEngine1VUMeter(Sender: TObject; Level: Integer);
begin
Gauge1.Progress := Level;
end;
procedure TForm1.ApdSapiPhone1TapiConnect(Sender: TObject);
begin
SaySomething ('Welcome to the speech recognition demo.');
SaySomething ('Say "Help" to get help');
ApdSapiEngine1.Listen;
end;
procedure TForm1.ApdSapiEngine1PhraseFinish(Sender: TObject;
const Phrase: String);
begin
Memo1.Lines.Add ('<-- ' + Phrase);
case AnalyzePhrase (Phrase) of
ptHelp :
begin
SaySomething ('You can say several things to this demo.');
SaySomething ('"Help" will give you help.');
SaySomething ('"What time is it?" will tell the current time.');
SaySomething ('"What day is it?" will tell the current day.');
SaySomething ('"Goodbye" will end this demo.');
end;
ptQuit :
begin
SaySomething ('Goodbye');
ApdSapiEngine1.WaitUntilDoneSpeaking;
ApdSapiPhone1.CancelCall;
ApdSapiPhone1.AutoAnswer;
end;
ptDate :
begin
SaySomething ('It is ' + FormatDateTime ('mmmm d, yyyy', Now) + '.');
end;
ptTime :
begin
SaySomething ('It is ' + FormatDateTime ('h:nam/pm', Now) + '.');
end;
ptUnknown :
begin
SaySomething ('I didn''t understand you.');
end;
end;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
if (not ApdSapiEngine1.IsSapi4Installed) then begin
ShowMessage ('SAPI 4 is not installed. AV will occur when answering');
end;
end;
end.
|
program _2;
type
TPtr=^Elem;
Elem=record
len:word;
inf:string;
link:TPtr;
end;
var f:text;
Top:TPtr;
procedure Pop(value:string);
var P:TPtr;
begin
new(P);
P^.inf:=value;
P^.len:=length(value);
p^.link:=Top;
Top:=P;
end;
procedure Push;
var P:TPtr;
begin
new(P);
P:=Top;
Top:=Top^.link;
Dispose(P);
end;
procedure CreateList(var f:text);
var s:string;
begin
assign(f,'2.txt');
reset(f);
while eof(f)=false do
begin
readln(f,s);
Pop(s);
end;
close(f);
end;
procedure SortList;
var PS,I:TPtr;
ind,Imax:word;
Max:word;
SMax:string;
begin
new(PS);
PS:=Top;
while PS^.link<>nil do
begin
Max:=PS^.len;
SMax:=PS^.inf;
ind:=0;
Imax:=0;
I:=PS^.link;
while I<>nil do
begin
inc(ind);
if I^.len>Max then
begin
Max:=I^.len;
SMax:=I^.inf;
Imax:=ind;
end;
I:=I^.link;
end;
I:=PS;
for ind:=1 to IMax do I:=I^.link;
I^.len:=PS^.len;
I^.inf:=PS^.inf;
PS^.len:=Max;
PS^.inf:=SMax;
PS:=PS^.link;
end;
end;
procedure CreateNewFile;
var g:text;
P:TPtr;
begin
assign(g,'newfile.txt');
rewrite(g);
P:=Top;
while P<>nil do
begin
writeln(g,P^.inf);
P:=P^.link;
end;
close(g);
end;
begin
CreateList(f);
SortList;
CreateNewFile;
while Top<>nil do Push;
end.
|
unit BCEditor.Editor.Utils;
interface
uses
System.Classes, BCEditor.Types;
function GetTextPosition(AChar, ALine: Integer): TBCEditorTextPosition;
function IsUTF8(Stream: TStream; out WithBOM: Boolean): Boolean;
implementation
uses
System.Math, System.SysUtils, BCEditor.Consts;
function GetTextPosition(AChar, ALine: Integer): TBCEditorTextPosition;
begin
with Result do
begin
Char := AChar;
Line := ALine;
end;
end;
// checks for a BOM in UTF-8 format or searches the first 4096 bytes for typical UTF-8 octet sequences
function IsUTF8(Stream: TStream; out WithBOM: Boolean): Boolean;
const
MinimumCountOfUTF8Strings = 1;
MaxBufferSize = $4000;
var
Buffer: array of Byte;
BufferSize, i, FoundUTF8Strings: Integer;
{ 3 trailing bytes are the maximum in valid UTF-8 streams,
so a count of 4 trailing bytes is enough to detect invalid UTF-8 streams }
function CountOfTrailingBytes: Integer;
begin
Result := 0;
Inc(i);
while (i < BufferSize) and (Result < 4) do
begin
if Buffer[i] in [$80 .. $BF] then
Inc(Result)
else
Break;
Inc(i);
end;
end;
begin
{ if Stream is nil, let Delphi raise the exception, by accessing Stream,
to signal an invalid result }
// start analysis at actual Stream.Position
BufferSize := Min(MaxBufferSize, Stream.Size - Stream.Position);
// if no special characteristics are found it is not UTF-8
Result := False;
WithBOM := False;
if BufferSize > 0 then
begin
SetLength(Buffer, BufferSize);
Stream.ReadBuffer(Buffer[0], BufferSize);
Stream.Seek(-BufferSize, soFromCurrent);
{ first search for BOM }
if (BufferSize >= Length(UTF8BOM)) and CompareMem(@Buffer[0], @UTF8BOM[0], Length(UTF8BOM)) then
begin
WithBOM := True;
Result := True;
Exit;
end;
{ If no BOM was found, check for leading/trailing byte sequences,
which are uncommon in usual non UTF-8 encoded text.
NOTE: There is no 100% save way to detect UTF-8 streams. The bigger
MinimumCountOfUTF8Strings, the lower is the probability of
a false positive. On the other hand, a big MinimumCountOfUTF8Strings
makes it unlikely to detect files with only little usage of non
US-ASCII chars, like usual in European languages. }
FoundUTF8Strings := 0;
i := 0;
while i < BufferSize do
begin
case Buffer[i] of
$00 .. $7F: // skip US-ASCII characters as they could belong to various charsets
;
$C2 .. $DF:
if CountOfTrailingBytes = 1 then
Inc(FoundUTF8Strings)
else
Break;
$E0:
begin
Inc(i);
if (i < BufferSize) and (Buffer[i] in [$A0 .. $BF]) and (CountOfTrailingBytes = 1) then
Inc(FoundUTF8Strings)
else
Break;
end;
$E1 .. $EC, $EE .. $EF:
if CountOfTrailingBytes = 2 then
Inc(FoundUTF8Strings)
else
Break;
$ED:
begin
Inc(i);
if (i < BufferSize) and (Buffer[i] in [$80 .. $9F]) and (CountOfTrailingBytes = 1) then
Inc(FoundUTF8Strings)
else
Break;
end;
$F0:
begin
Inc(i);
if (i < BufferSize) and (Buffer[i] in [$90 .. $BF]) and (CountOfTrailingBytes = 2) then
Inc(FoundUTF8Strings)
else
Break;
end;
$F1 .. $F3:
if CountOfTrailingBytes = 3 then
Inc(FoundUTF8Strings)
else
Break;
$F4:
begin
Inc(i);
if (i < BufferSize) and (Buffer[i] in [$80 .. $8F]) and (CountOfTrailingBytes = 2) then
Inc(FoundUTF8Strings)
else
Break;
end;
$C0, $C1, $F5 .. $FF: // invalid UTF-8 bytes
Break;
$80 .. $BF: // trailing bytes are consumed when handling leading bytes,
// any occurence of "orphaned" trailing bytes is invalid UTF-8
Break;
end;
if FoundUTF8Strings = MinimumCountOfUTF8Strings then
begin
Result := True;
Break;
end;
Inc(i);
end;
end;
end;
end.
|
unit M_flaged;
interface
uses WinTypes, WinProcs, Classes, Graphics, Forms, Controls, Buttons,
StdCtrls, IniFiles, M_Global, ExtCtrls;
type
TFlagEditor = class(TForm)
LBFlags: TListBox;
Panel1: TPanel;
Title: TPanel;
SBCommit: TSpeedButton;
SBRollback: TSpeedButton;
SBHelp: TSpeedButton;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure SBCommitClick(Sender: TObject);
procedure SBRollbackClick(Sender: TObject);
procedure SBHelpClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
FlagEditor: TFlagEditor;
implementation
{$R *.DFM}
procedure TFlagEditor.FormCreate(Sender: TObject);
begin
FlagEditor.Left := Ini.ReadInteger('WINDOWS', 'Flag Editor X', 72);
FlagEditor.Top := Ini.ReadInteger('WINDOWS', 'Flag Editor Y', 72);
{
FlagEditor.Width := Ini.ReadInteger('WINDOWS', 'Flag Editor W', 629);
FlagEditor.Height := Ini.ReadInteger('WINDOWS', 'Flag Editor H', 440);
}
end;
procedure TFlagEditor.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Ini.WriteInteger('WINDOWS', 'Flag Editor X', FlagEditor.Left);
Ini.WriteInteger('WINDOWS', 'Flag Editor Y', FlagEditor.Top);
{
Ini.WriteInteger('WINDOWS', 'Flag Editor W', FlagEditor.Width);
Ini.WriteInteger('WINDOWS', 'Flag Editor H', FlagEditor.Height);
}
end;
procedure TFlagEditor.FormKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Shift = [] then
Case Key of
VK_F1 : Application.HelpJump('wdfuse_help_secondary');
VK_F2,
VK_RETURN : FlagEditor.ModalResult := mrOk;
VK_ESCAPE : FlagEditor.ModalResult := mrCancel;
end;
end;
procedure TFlagEditor.SBCommitClick(Sender: TObject);
begin
FlagEditor.ModalResult := mrOk;
end;
procedure TFlagEditor.SBRollbackClick(Sender: TObject);
begin
FlagEditor.ModalResult := mrCancel;
end;
procedure TFlagEditor.SBHelpClick(Sender: TObject);
begin
Application.HelpJump('wdfuse_help_secondary');
end;
end.
|
unit AST.Delphi.System;
interface
{$i compilers.inc}
uses System.Classes,
System.SysUtils,
AST.Pascal.Parser,
AST.Delphi.Classes,
AST.Delphi.DataTypes,
AST.Delphi.Operators,
AST.Parser.Utils,
AST.Parser.Messages,
AST.Classes,
AST.Intf,
AST.Delphi.Errors,
AST.Delphi.Contexts,
AST.Delphi.Parser,
AST.Delphi.Intf;
// System
type
TSYSTEMUnit = class;
TIDBuiltInFunction = class(TIDProcedure)
protected
class function GetFunctionID: TBuiltInFunctionID; virtual; abstract;
class function CreateTMPExpr(const EContext: TEContext; const DataType: TIDType): TIDExpression;
public
constructor Create(Scope: TScope; const Name: string; ResultType: TIDType); reintroduce; virtual;
/////////////////////////////////////////////////////////////////////////////////////////
property FunctionID: TBuiltInFunctionID read GetFunctionID;
class function CreateDecl(SyUtit: TSYSTEMUnit; Scope: TScope): TIDBuiltInFunction; virtual; abstract;
end;
TIDBuiltInFunctionClass = class of TIDBuiltInFunction;
TIDSysRuntimeFunction = class(TIDBuiltInFunction)
protected
class function GetFunctionID: TBuiltInFunctionID; override;
public
function Process(var EContext: TEContext): TIDExpression; virtual;
end;
TSysFunctionContext = record
UN: TASTDelphiUnit;
Scope: TScope;
ParamsStr: string;
ArgsCount: Integer;
EContext: ^TEContext;
SContext: PSContext;
ERRORS: TASTDelphiErrors;
end;
TIDSysCompileFunction = class(TIDBuiltInFunction)
protected
class function GetFunctionID: TBuiltInFunctionID; override;
public
function Process(const Ctx: TSysFunctionContext): TIDExpression; virtual; abstract;
end;
TIDSysRuntimeFunctionClass = class of TIDSysRuntimeFunction;
// TIDSysCompileFunctionClass = class of TIDSysCompileFunction;
TSystemOperatos = record
public
// implicits
ImplicitVariantToAny,
ImplicitVariantFromAny,
ImplicitStringFromAny,
ImplicitCharToAnsiChar,
ImplicitCharToString,
ImplicitRangeFromAny,
ImplicitRangeToAny,
ImplicitStringToAnsiString,
ImplicitStringToGUID,
ImplicitStringToPChar,
ImplicitAnsiStringToString,
ImplicitPointerToAny,
ImplicitPointerFromAny,
ImplicitUntypedFromAny,
ImplicitClosureToTMethod,
ImplicitCharToAnsiString,
ImplicitAnsiStringFromAny,
ImplicitAnsiCharToAnsiString,
ImplicitAnsiCharToString,
ImplicitAnsiCharToWideChar,
ImplicitMetaClassToGUID,
ImplicitClassToClass,
ImplicitArrayToAny,
ImplicitArrayFromAny,
ImplicitSetFromAny,
ImplicitNullPtrToAny,
ImplicitTVarRecToAny,
ImplicitTVarRecFromAny,
ImplicitSysVarFromAny
: TIDOperator;
// explicits
ExplicitStringFromAny,
ExplicitAnsiStringFromAny,
ExplicitTProcFromAny,
ExplicitClassFromAny,
ExplicitClassOfToAny,
ExplicitClassOfFromAny,
ExplicitInterfaceFromAny,
ExplicitPointerToAny,
ExplicitPointerFromAny,
ExplicitRecordFromAny,
ExplicitEnumToAny,
ExplicitEnumFromAny,
ExplicitUntypedToAny,
ExplicitUntypedRefToAny,
ExplicitCharToAny,
ExplicitRangeFromAny,
ExplicitRecordToAny,
ExplicitStaticArrayToAny,
ExplicitDynArrayToAny,
ExplicitVariantToAny,
ExplicitVariantFromAny: TIDOperator;
// any cast
IsOrdinal: TIDOperator;
// in
Ordinal_In_Set: TIDOperator;
// add
StaticArray_Add: TIDOperator;
Ptr_IntDiv_Int: TIDOperator;
// Set Multiplay
Multiply_Set: TIDOperator;
Add_Set: TIDOperator;
Subtract_Set: TIDOperator;
// DynArray
Equal_DynArray: TIDOperator;
Equal_NullPtr: TIDOperator;
NotEqual_NullPtr: TIDOperator;
procedure Init(Scope: TScope);
end;
TSYSTEMUnit = class(TASTDelphiUnit, IASTDelphiSystemUnit)
type
TDataTypes = array[TDataTypeID] of TIDType;
const
SystemTypesCount = Ord(dtPointer) + 1;
private
var
fDecls: TDelphiSystemDeclarations;
fArrayType: TIDArray; // служебный тип для функций Length/SetLength
fDateTimeType: TIDType;
fDateType: TIDType;
fTimeType: TIDType;
fTypeIDType: TIDType;
fAsserProc: TIDProcedure;
fOpenString: TIDType;
fOperators: TSystemOperatos;
procedure AddImplicists;
procedure AddExplicists;
procedure AddNegOperators;
procedure AddAddOperators;
procedure AddSubOperators;
procedure AddMulOperators;
procedure AddDivOperators;
procedure AddIntDivOperators;
procedure AddModOperators;
procedure AddLogicalOperators;
procedure AddBitwiseOperators;
procedure AddCompareOperators;
procedure AddArithmeticOperators;
procedure AddTVarRecImplicitOperators;
procedure RegisterTypes;
procedure RegisterBuiltinFunctions;
procedure SystemFixup;
procedure InsertToScope(Declaration: TIDDeclaration); overload;
function RegisterType(const TypeName: string; TypeClass: TIDTypeClass; DataType: TDataTypeID): TIDType;
function RegisterTypeCustom(const TypeName: string; TypeClass: TIDTypeClass; DataType: TDataTypeID): TIDType;
function RegisterOrdinal(const TypeName: string; DataType: TDataTypeID; LowBound: Int64; HighBound: UInt64): TIDType;
function RegisterTypeAlias(const TypeName: string; OriginalType: TIDType): TIDAliasType;
function RegisterPointer(const TypeName: string; TargetType: TIDType): TIDPointer;
function RegisterConstInt(const Name: string; DataType: TIDType; Value: Int64): TIDIntConstant;
function RegisterConstStr(Scope: TScope; const Name: string; const Value: string ): TIDStringConstant;
function RegisterVariable(Scope: TScope; const Name: string; DataType: TIDType): TIDVariable;
function RegisterBuiltin(const BuiltinClass: TIDBuiltInFunctionClass): TIDBuiltInFunction; overload;
function GetSystemDeclarations: PDelphiSystemDeclarations; override;
private
function GetTypeByID(ID: TDataTypeID): TIDType;
procedure SearchSystemTypes;
procedure AddStandardExplicitsTo(const Sources: array of TDataTypeID; Dest: TIDType); overload;
public
////////////////////////////////////////////////////////////////////////////////////////////////////
constructor Create(const Project: IASTProject; const FileName: string; const Source: string); override;
function Compile(ACompileIntfOnly: Boolean; RunPostCompile: Boolean = True): TCompilerResult; override;
function CompileIntfOnly: TCompilerResult; override;
////////////////////////////////////////////////////////////////////////////////////////////////////
property DataTypes[ID: TDataTypeID]: TIDType read GetTypeByID;
property SystemDeclarations: PDelphiSystemDeclarations read GetSystemDeclarations;
property _Int8: TIDType read fDecls._Int8 write fDecls._Int8;
property _Int16: TIDType read fDecls._Int16 write fDecls._Int16;
property _Int32: TIDType read fDecls._Int32 write fDecls._Int32;
property _Int64: TIDType read fDecls._Int64 write fDecls._Int64;
property _UInt8: TIDType read fDecls._UInt8 write fDecls._UInt8;
property _UInt16: TIDType read fDecls._UInt16 write fDecls._UInt16;
property _UInt32: TIDType read fDecls._UInt32 write fDecls._UInt32;
property _UInt64: TIDType read fDecls._UInt64 write fDecls._UInt64;
property _NativeInt: TIDType read fDecls._NativeInt write fDecls._NativeInt;
property _NativeUInt: TIDType read fDecls._NativeUInt write fDecls._NativeUInt;
property _Float32: TIDType read fDecls._Float32 write fDecls._Float32;
property _Float64: TIDType read fDecls._Float64 write fDecls._Float64;
property _Float80: TIDType read fDecls._Float80 write fDecls._Float80;
property _Currency: TIDType read fDecls._Currency write fDecls._Currency;
property _Comp: TIDType read fDecls._Comp write fDecls._Comp;
property _Boolean: TIDType read fDecls._Boolean write fDecls._Boolean;
property _AnsiChar: TIDType read fDecls._AnsiChar write fDecls._AnsiChar;
property _WideChar: TIDType read fDecls._WideChar write fDecls._WideChar;
property _AnsiString: TIDType read fDecls._AnsiString write fDecls._AnsiString;
property _UnicodeString: TIDType read fDecls._UnicodeString write fDecls._UnicodeString;
property _ShortString: TIDType read fDecls._ShortString write fDecls._ShortString;
property _WideString: TIDType read fDecls._WideString write fDecls._WideString;
property _Variant: TIDType read fDecls._Variant write fDecls._Variant;
property _NilPointer: TIDType read fDecls._NullPtrType;
property _TGuid: TIDStructure read fDecls._GuidType;
property _True: TIDBooleanConstant read fDecls._True;
property _False: TIDBooleanConstant read fDecls._False;
property _TrueExpression: TIDExpression read fDecls._TrueExpression;
property _FalseExpression: TIDExpression read fDecls._FalseExpression;
property _ZeroConstant: TIDIntConstant read fDecls._ZeroConstant;
property _ZeroIntExpression: TIDExpression read fDecls._ZeroIntExpression;
property _ZeroFloatExpression: TIDExpression read fDecls._ZeroFloatExpression;
property _OneConstant: TIDIntConstant read fDecls._OneConstant;
property _OneExpression: TIDExpression read fDecls._OneExpression;
property _NullPtrConstant: TIDIntConstant read fDecls._NullPtrConstant;
property _NullPtrExpression: TIDExpression read fDecls._NullPtrExpression;
property _EmptyStrExpression: TIDExpression read fDecls._EmptyStrExpression;
property _Pointer: TIDPointer read fDecls._PointerType;
property _UntypedReference: TIDUntypedRef read fDecls._UntypedReference;
property _Untyped: TIDType read fDecls._Untyped;
property _TObject: TIDClass read fDecls._TObject;
property _Exception: TIDClass read fDecls._Exception;
property _EAssert: TIDClass read fDecls._EAssertClass;
property _TTypeKind: TIDEnum read fDecls._TTypeKind;
property _DateTime: TIDType read fDateTimeType;
property _Date: TIDType read fDateType;
property _Time: TIDType read fTimeType;
property _AssertProc: TIDProcedure read fAsserProc;
property _TypeID: TIDType read fTypeIDType;
property _DeprecatedDefaultStr: TIDStringConstant read fDecls._DeprecatedDefaultStr;
property _OrdinalType: TIDType read fDecls._OrdinalType;
property _PAnsiChar: TIDType read fDecls._PAnsiChar;
property _PWideChar: TIDType read fDecls._PWideChar;
property _AnyArrayType: TIDArray read fArrayType;
property _MetaType: TIDType read fDecls._MetaType;
property _Void: TIDType read fDecls._Void;
property _ResStringRecord: TIDType read fDecls._ResStringRecord;
property Operators: TSystemOperatos read fOperators;
end;
TDlphDeclarationHelper = class helper for TIDDeclaration
private
function GetSysUnit: TSYSTEMUnit;
public
property SYSUnit: TSYSTEMUnit read GetSysUnit;
end;
implementation
uses AST.Parser.Errors,
AST.Delphi.SysFunctions,
AST.Delphi.SysOperators,
AST.Targets,
AST.Lexer;
{ TDlphDeclarationHelper }
function TDlphDeclarationHelper.GetSysUnit: TSYSTEMUnit;
begin
if Module is TSYSTEMUnit then
Result := TSYSTEMUnit(Module)
else
Result := TASTDelphiUnit(Module).SysUnit as TSYSTEMUnit;
end;
{ TIDBuiltInFunction }
constructor TIDBuiltInFunction.Create(Scope: TScope; const Name: string; ResultType: TIDType);
begin
inherited CreateAsSystem(Scope, Name);
ItemType := itMacroFunction;
Self.DataType := ResultType;
end;
class function TIDBuiltInFunction.CreateTMPExpr(const EContext: TEContext; const DataType: TIDType): TIDExpression;
var
Decl: TIDVariable;
begin
Decl := EContext.SContext.Proc.GetTMPVar(DataType);
Result := TIDExpression.Create(Decl);
end;
{ TIDSysRuntimeFunction }
class function TIDSysRuntimeFunction.GetFunctionID: TBuiltInFunctionID;
begin
Result := bf_sysrtfunction;
end;
function TIDSysRuntimeFunction.Process(var EContext: TEContext): TIDExpression;
begin
AbortWorkInternal('Method "Process" must be override');
Result := nil;
end;
{ TIDSysCompileFunction }
class function TIDSysCompileFunction.GetFunctionID: TBuiltInFunctionID;
begin
Result := bf_sysctfunction;
end;
procedure AddUnarOperator(Op: TOperatorID; Source, Destination: TIDType); inline;
begin
Source.OverloadUnarOperator(Op, Destination);
end;
procedure AddBinarOperator(Op: TOperatorID; Left, Right, Result: TIDType); overload; inline;
begin
Left.OverloadBinarOperator2(Op, Right, Result);
end;
procedure AddBinarOperator(Op: TOperatorID; Left: TIDType; const Rights: array of TIDType; Result: TIDType); overload;
var
i: Integer;
Right: TIDType;
begin
for i := 0 to Length(Rights) - 1 do begin
Right := Rights[i];
AddBinarOperator(Op, Left, Right, Result);
end;
end;
{ TSYSTEMUnit }
procedure TSYSTEMUnit.AddImplicists;
procedure AddBaseImplicits(DataType: TIDType);
var
i: TDataTypeID;
begin
for i := dtInt8 to dtComp do
DataType.OverloadImplicitTo(DataTypes[i]);
DataType.OverloadImplicitTo(_Variant, Operators.ImplicitVariantFromAny);
end;
var
i: TDataTypeID;
begin
// signed:
AddBaseImplicits(_Int8);
AddBaseImplicits(_Int16);
AddBaseImplicits(_Int32);
AddBaseImplicits(_Int64);
AddBaseImplicits(_UInt8);
AddBaseImplicits(_UInt16);
AddBaseImplicits(_UInt32);
AddBaseImplicits(_UInt64);
AddBaseImplicits(_NativeInt);
AddBaseImplicits(_NativeUInt);
// Variant
for i := dtInt8 to dtVariant do
_Variant.OverloadImplicitTo(DataTypes[i], Operators.ImplicitVariantToAny);
_Variant.OverloadExplicitToAny(Operators.ExplicitVariantToAny);
_Variant.OverloadExplicitFromAny(Operators.ExplicitVariantFromAny);
// float32
with _Float32 do begin
OverloadImplicitTo(_Float32);
OverloadImplicitTo(_Float64);
OverloadImplicitTo(_Float80);
OverloadImplicitTo(_Currency);
OverloadImplicitTo(_Comp);
OverloadImplicitTo(_Variant, Operators.ImplicitVariantFromAny);
end;
// Float64
with _Float64 do begin
OverloadImplicitTo(_Float32);
OverloadImplicitTo(_Float64);
OverloadImplicitTo(_Float80);
OverloadImplicitTo(_Currency);
OverloadImplicitTo(_Comp);
OverloadImplicitTo(_Variant, Operators.ImplicitVariantFromAny);
end;
// Float80
with _Float80 do begin
OverloadImplicitTo(_Float32);
OverloadImplicitTo(_Float64);
OverloadImplicitTo(_Currency);
OverloadImplicitTo(_Comp);
OverloadImplicitTo(_Variant, Operators.ImplicitVariantFromAny);
end;
// Currency
with _Currency do begin
OverloadImplicitTo(_Float32);
OverloadImplicitTo(_Float64);
OverloadImplicitTo(_Float80);
OverloadImplicitTo(_Comp);
OverloadImplicitTo(_Variant, Operators.ImplicitVariantFromAny);
end;
with _Comp do begin
OverloadImplicitTo(_Float32);
OverloadImplicitTo(_Float64);
OverloadImplicitTo(_Float80);
OverloadImplicitTo(_Currency);
OverloadImplicitTo(_Variant, Operators.ImplicitVariantFromAny);
end;
// UnicodeString
_UnicodeString.OverloadImplicitTo(_Variant, Operators.ImplicitVariantFromAny);
_UnicodeString.OverloadImplicitTo(_AnsiString, Operators.ImplicitStringToAnsiString);
_UnicodeString.OverloadImplicitTo(_TGuid, Operators.ImplicitStringToGUID);
_UnicodeString.OverloadImplicitTo(_PWideChar, Operators.ImplicitStringToPChar);
_UnicodeString.OverloadImplicitTo(_PAnsiChar, Operators.ImplicitStringToPChar);
_UnicodeString.OverloadImplicitTo(_WideString);
_UnicodeString.OverloadImplicitFrom(_PWideChar);
_UnicodeString.OverloadImplicitFromAny(Operators.ImplicitStringFromAny);
// ShortString
_ShortString.OverloadImplicitTo(_AnsiString);
_ShortString.OverloadImplicitTo(_Variant, Operators.ImplicitVariantFromAny);
_ShortString.OverloadImplicitTo(_PWideChar, Operators.ImplicitStringToPChar);
_ShortString.OverloadImplicitTo(_PAnsiChar, Operators.ImplicitStringToPChar);
_ShortString.OverloadImplicitTo(_UnicodeString, Operators.ImplicitAnsiStringToString);
_ShortString.OverloadImplicitTo(_TGuid, Operators.ImplicitStringToGUID);
_ShortString.OverloadImplicitFrom(_PAnsiChar);
// AnsiString
_AnsiString.OverloadImplicitTo(_Variant, Operators.ImplicitVariantFromAny);
_AnsiString.OverloadImplicitTo(_PWideChar, Operators.ImplicitStringToPChar);
_AnsiString.OverloadImplicitTo(_PAnsiChar, Operators.ImplicitStringToPChar);
_AnsiString.OverloadImplicitTo(_UnicodeString, Operators.ImplicitAnsiStringToString);
_AnsiString.OverloadImplicitTo(_TGuid, Operators.ImplicitStringToGUID);
_AnsiString.OverloadImplicitTo(_ShortString);
_AnsiString.OverloadImplicitTo(_WideString);
_AnsiString.OverloadImplicitFrom(_PAnsiChar);
_AnsiString.OverloadImplicitFromAny(Operators.ImplicitAnsiStringFromAny);
// WideString
_WideString.OverloadImplicitTo(_Variant, Operators.ImplicitVariantFromAny);
_WideString.OverloadImplicitTo(_PWideChar, Operators.ImplicitStringToPChar);
_WideString.OverloadImplicitTo(_PAnsiChar, Operators.ImplicitStringToPChar);
_WideString.OverloadImplicitTo(_AnsiString);
_WideString.OverloadImplicitTo(_ShortString);
_WideString.OverloadImplicitTo(_UnicodeString);
_WideString.OverloadImplicitFromAny(Operators.ImplicitStringFromAny);
_WideString.OverloadExplicitFromAny(Operators.ExplicitStringFromAny);
// WideChar
_WideChar.OverloadImplicitTo(_WideChar);
_WideChar.OverloadImplicitTo(_PWideChar);
_WideChar.OverloadImplicitTo(_UnicodeString, Operators.ImplicitCharToString);
_WideChar.OverloadImplicitTo(_AnsiString, Operators.ImplicitCharToAnsiString);
_WideChar.OverloadImplicitTo(_AnsiChar, Operators.ImplicitCharToAnsiChar);
_WideChar.OverloadImplicitTo(_Variant, Operators.ImplicitVariantFromAny);
_WideChar.OverloadImplicitTo(_WideString);
// AnsiChar
_AnsiChar.OverloadImplicitTo(_AnsiChar);
_AnsiChar.OverloadImplicitTo(_PAnsiChar);
_AnsiChar.OverloadImplicitTo(_AnsiString, Operators.ImplicitAnsiCharToAnsiString);
_AnsiChar.OverloadImplicitTo(_UnicodeString, Operators.ImplicitAnsiCharToString);
_AnsiChar.OverloadImplicitTo(_WideChar, Operators.ImplicitAnsiCharToWideChar);
_AnsiChar.OverloadImplicitTo(_Variant, Operators.ImplicitVariantFromAny);
_MetaType.OverloadImplicitTo(_TGuid, Operators.ImplicitMetaClassToGUID);
// Boolean
_Boolean.OverloadImplicitTo(_Boolean);
_Boolean.OverloadImplicitTo(_Variant, Operators.ImplicitVariantFromAny);
end;
procedure TSYSTEMUnit.AddStandardExplicitsTo(const Sources: array of TDataTypeID; Dest: TIDType);
var
i: Integer;
begin
for i := 0 to Length(Sources) - 1 do
DataTypes[Sources[i]].OverloadExplicitTo(Dest);
end;
procedure TSYSTEMUnit.AddExplicists;
procedure AddBaseExplicits(DataType: TIDType);
var
i: TDataTypeID;
begin
for i := dtInt8 to dtFloat64 do
DataType.OverloadExplicitTo(DataTypes[i]);
end;
procedure AddExplicits(DataType: TIDType; LB, HB: TDataTypeID);
var
i: TDataTypeID;
begin
for i := LB to HB do
DataType.OverloadExplicitTo(DataTypes[i]);
end;
begin
AddBaseExplicits(_Int8);
AddBaseExplicits(_Int16);
AddBaseExplicits(_Int32);
AddBaseExplicits(_Int64);
AddBaseExplicits(_UInt8);
AddBaseExplicits(_UInt16);
AddBaseExplicits(_UInt32);
AddBaseExplicits(_UInt64);
AddBaseExplicits(_NativeInt);
AddBaseExplicits(_NativeUInt);
AddBaseExplicits(_Variant);
AddBaseExplicits(_Boolean);
AddBaseExplicits(_WideChar);
AddBaseExplicits(_AnsiChar);
AddExplicits(_Float32, dtFloat32, dtFloat64);
AddExplicits(_Float64, dtFloat32, dtFloat64);
AddExplicits(_Float32, dtInt8, dtNativeUInt);
AddExplicits(_Float64, dtInt8, dtNativeUInt);
// String
_UnicodeString.OverloadExplicitTo(_Pointer);
_UnicodeString.OverloadExplicitTo(_NativeInt);
_UnicodeString.OverloadExplicitTo(_NativeUInt);
_UnicodeString.OverloadExplicitTo(_PWideChar);
_UnicodeString.OverloadExplicitTo(_WideString);
_UnicodeString.OverloadExplicitTo(_AnsiString);
_UnicodeString.OverloadExplicitTo(_ShortString);
_UnicodeString.OverloadExplicitFromAny(Operators.ExplicitStringFromAny);
// AnsiString
_AnsiString.OverloadExplicitTo(_Pointer);
_AnsiString.OverloadExplicitTo(_NativeInt);
_AnsiString.OverloadExplicitTo(_NativeUInt);
_AnsiString.OverloadExplicitTo(_PAnsiChar);
_AnsiString.OverloadExplicitTo(_ShortString);
_AnsiString.OverloadExplicitTo(_WideString);
_AnsiString.OverloadExplicitFromAny(Operators.ExplicitAnsiStringFromAny);
// WideString
_WideString.OverloadExplicitTo(_UnicodeString);
_WideString.OverloadExplicitTo(_Pointer);
_WideString.OverloadExplicitTo(_NativeInt);
_WideString.OverloadExplicitTo(_NativeUInt);
// AnsiChar
_AnsiChar.OverloadExplicitTo(_WideChar);
// ShortString
_ShortString.OverloadExplicitTo(_AnsiString);
_ShortString.OverloadExplicitTo(_UnicodeString);
// WideChar
_WideChar.OverloadExplicitTo(_UnicodeString);
_WideChar.OverloadExplicitToAny(Operators.ExplicitCharToAny);
_PWideChar.OverloadExplicitTo(_UnicodeString);
_UntypedReference.OverloadExplicitTo(_ShortString);
AddStandardExplicitsTo([dtInt8, dtInt16, dtInt32, dtInt64, dtUInt8, dtUInt16, dtUInt32, dtUInt64, dtNativeInt, dtNativeUInt, dtBoolean], _WideChar);
AddStandardExplicitsTo([dtInt8, dtInt16, dtInt32, dtInt64, dtUInt8, dtUInt16, dtUInt32, dtUInt64, dtNativeInt, dtNativeUInt, dtBoolean], _AnsiChar);
end;
procedure TSYSTEMUnit.AddIntDivOperators;
begin
AddBinarOperator(opIntDiv, _Int8, [_Int8, _UInt8, _Int16, _UInt16, _Int32, _UInt32, _Int64, _UInt64], _Int8);
AddBinarOperator(opIntDiv, _UInt8, [_Int8, _UInt8, _Int16, _UInt16, _Int32, _UInt32, _Int64, _UInt64], _UInt8);
AddBinarOperator(opIntDiv, _Int16, [_Int8, _UInt8, _Int16, _UInt16, _Int32, _UInt32, _Int64, _UInt64], _Int16);
AddBinarOperator(opIntDiv, _UInt16, [_Int8, _UInt8, _Int16, _UInt16, _Int32, _UInt32, _Int64, _UInt64], _UInt16);
AddBinarOperator(opIntDiv, _Int32, [_Int8, _UInt8, _Int16, _UInt16, _Int32, _UInt32, _Int64, _UInt64], _Int32);
AddBinarOperator(opIntDiv, _UInt32, [_Int8, _UInt8, _Int16, _UInt16, _Int32, _UInt32, _Int64, _UInt64], _UInt32);
AddBinarOperator(opIntDiv, _Int64, [_Int8, _UInt8, _Int16, _UInt16, _Int32, _UInt32, _Int64, _UInt64], _Int64);
AddBinarOperator(opIntDiv, _UInt64, [_Int8, _UInt8, _Int16, _UInt16, _Int32, _UInt32, _Int64, _UInt64], _UInt64);
AddBinarOperator(opIntDiv, _NativeInt, [_Int8, _UInt8, _Int16, _UInt16, _Int32, _UInt32, _Int64, _UInt64], _NativeInt);
AddBinarOperator(opIntDiv, _NativeUInt, [_Int8, _UInt8, _Int16, _UInt16, _Int32, _UInt32, _Int64, _UInt64], _NativeUInt);
end;
procedure TSYSTEMUnit.AddLogicalOperators;
begin
AddUnarOperator(opNot, _Boolean, _Boolean);
AddBinarOperator(opAnd, _Boolean, _Boolean, _Boolean);
AddBinarOperator(opOr, _Boolean, _Boolean, _Boolean);
AddBinarOperator(opXor, _Boolean, _Boolean, _Boolean);
end;
procedure TSYSTEMUnit.AddModOperators;
begin
AddBinarOperator(opModDiv, _Int8, [_Int8, _UInt8], _Int8);
AddBinarOperator(opModDiv, _UInt8, _UInt8, _UInt8);
AddBinarOperator(opModDiv, _Int16, [_Int8, _UInt8, _Int16, _UInt16], _Int16);
AddBinarOperator(opModDiv, _UInt16, [_UInt8, _UInt16], _UInt16);
AddBinarOperator(opModDiv, _Int32, [_Int8, _UInt8, _Int16, _UInt16, _Int32, _UInt32], _Int32);
AddBinarOperator(opModDiv, _UInt32, [_UInt8, _UInt16, _UInt32], _UInt32);
AddBinarOperator(opModDiv, _Int64, [_Int8, _UInt8, _Int16, _UInt16, _Int32, _UInt32, _Int64, _UInt64], _Int64);
AddBinarOperator(opModDiv, _UInt64, [_UInt8, _UInt16, _UInt32, _UInt64], _UInt64);
end;
procedure TSYSTEMUnit.AddMulOperators;
begin
AddBinarOperator(opMultiply, _Int8, [_Int8, _UInt8, _Int16, _UInt16], _Int32);
AddBinarOperator(opMultiply, _UInt8, [_Int8, _Int16], _Int32);
AddBinarOperator(opMultiply, _UInt8, [_UInt8, _UInt16], _UInt32);
AddBinarOperator(opMultiply, _Int16, [_Int8, _UInt8, _Int16, _UInt16, _Int32, _UInt32], _Int32);
AddBinarOperator(opMultiply, _Int16, [_Int64, _UInt64], _Int64);
AddBinarOperator(opMultiply, _UInt16, [_UInt8, _UInt16, _UInt32], _UInt32);
AddBinarOperator(opMultiply, _UInt16, [_Int8, _Int16, _Int32], _Int32);
AddBinarOperator(opMultiply, _Int32, [_Int8, _UInt8, _Int16, _UInt16, _Int32, _UInt32], _Int32);
AddBinarOperator(opMultiply, _UInt32, [_UInt8, _UInt16, _UInt32], _UInt32);
AddBinarOperator(opMultiply, _Int64, [_Int8, _UInt8, _Int16, _UInt16, _Int32, _UInt32, _Int64, _UInt64], _Int64);
AddBinarOperator(opMultiply, _UInt64, [_UInt8, _UInt16, _UInt32, _UInt64], _UInt64);
AddBinarOperator(opMultiply, _NativeInt, _NativeInt, _NativeInt);
AddBinarOperator(opMultiply, _NativeUInt, _NativeUInt, _NativeUInt);
// int * float
AddBinarOperator(opMultiply, _Float32, [_Int8, _UInt8, _Int16, _UInt16, _Int32, _UInt32, _Int64, _UInt64, _Float32, _Float64], _Float64);
AddBinarOperator(opMultiply, _Float64, [_Int8, _UInt8, _Int16, _UInt16, _Int32, _UInt32, _Int64, _UInt64, _Float32, _Float64], _Float64);
AddBinarOperator(opMultiply, _Float80, [_Int8, _UInt8, _Int16, _UInt16, _Int32, _UInt32, _Int64, _UInt64, _Float32, _Float64], _Float80);
// variant
AddBinarOperator(opMultiply, _Variant, _Variant, _Variant);
end;
procedure TSYSTEMUnit.AddNegOperators;
begin
AddUnarOperator(opNegative, _Int8, _Int8);
AddUnarOperator(opNegative, _UInt8, _Int8);
AddUnarOperator(opNegative, _Int16, _Int16);
AddUnarOperator(opNegative, _UInt16, _Int16);
AddUnarOperator(opNegative, _Int32, _Int32);
AddUnarOperator(opNegative, _UInt32, _Int32);
AddUnarOperator(opNegative, _Int64, _Int64);
AddUnarOperator(opNegative, _UInt64, _Int64);
AddUnarOperator(opNegative, _NativeInt, _NativeInt);
AddUnarOperator(opNegative, _NativeUInt, _NativeInt);
AddUnarOperator(opNegative, _Float32, _Float32);
AddUnarOperator(opNegative, _Float64, _Float64);
end;
procedure TSYSTEMUnit.AddSubOperators;
begin
// int - int
AddBinarOperator(opSubtract, _Int8, [_Int8, _UInt8], _Int8);
AddBinarOperator(opSubtract, _UInt8, _UInt8, _UInt8);
AddBinarOperator(opSubtract, _Int16, [_Int8, _UInt8, _Int16, _UInt16], _Int16);
AddBinarOperator(opSubtract, _UInt16, [_UInt8, _UInt16], _UInt16);
AddBinarOperator(opSubtract, _Int32, [_Int8, _UInt8, _Int16, _UInt16, _Int32, _UInt32], _Int32);
AddBinarOperator(opSubtract, _UInt32, [_UInt8, _UInt16, _UInt32], _UInt32);
AddBinarOperator(opSubtract, _NativeInt, [_Int8, _UInt8, _Int16, _UInt16, _Int32, _UInt32], _NativeInt);
AddBinarOperator(opSubtract, _NativeUInt, [_Int8, _UInt8, _Int16, _UInt16, _Int32, _UInt32], _NativeInt);
AddBinarOperator(opSubtract, _Int64, [_Int8, _UInt8, _Int16, _UInt16, _Int32, _UInt32, _Int64, _UInt64], _Int64);
AddBinarOperator(opSubtract, _UInt64, [_UInt8, _UInt16, _UInt32, _UInt64], _UInt64);
// int - float
AddBinarOperator(opSubtract, _Float32, [_Int8, _UInt8, _Int16, _UInt16, _Int32, _UInt32, _Int64, _UInt64, _Float32], _Float32);
AddBinarOperator(opSubtract, _Float64, [_Int8, _UInt8, _Int16, _UInt16, _Int32, _UInt32, _Int64, _UInt64, _Float32, _Float64], _Float64);
AddBinarOperator(opSubtract, _Float80, [_Int8, _UInt8, _Int16, _UInt16, _Int32, _UInt32, _Int64, _UInt64, _Float32, _Float64, _Float80, _Currency], _Float80);
AddBinarOperator(opSubtract, _Currency, [_Int8, _UInt8, _Int16, _UInt16, _Int32, _UInt32, _Int64, _UInt64, _Float32, _Float64, _Float80, _Currency], _Currency);
AddBinarOperator(opSubtract, _Variant, _Variant, _Variant);
end;
procedure TSYSTEMUnit.AddTVarRecImplicitOperators;
begin
fDecls._TVarRec.OverloadExplicitToAny(Operators.ImplicitTVarRecToAny);
fDecls._TVarRec.OverloadExplicitFromAny(Operators.ImplicitTVarRecFromAny);
end;
procedure TSYSTEMUnit.AddAddOperators;
begin
AddBinarOperator(opAdd, _Int8, [_Int8, _UInt8], _Int8);
AddBinarOperator(opAdd, _UInt8, _UInt8, _UInt8);
AddBinarOperator(opAdd, _Int16, [_Int8, _UInt8, _Int16, _UInt16], _Int16);
AddBinarOperator(opAdd, _UInt16, [_UInt8, _UInt16], _UInt16);
AddBinarOperator(opAdd, _Int32, [_Int8, _UInt8, _Int16, _UInt16, _Int32, _UInt32], _Int32);
AddBinarOperator(opAdd, _UInt32, [_UInt8, _UInt16, _UInt32], _UInt32);
AddBinarOperator(opAdd, _NativeInt, [_Int8, _UInt8, _Int16, _UInt16, _Int32, _UInt32], _NativeInt);
AddBinarOperator(opAdd, _NativeUInt, [_UInt8, _UInt16, _UInt32], _NativeUInt);
AddBinarOperator(opAdd, _Int64, [_Int8, _UInt8, _Int16, _UInt16, _Int32, _UInt32, _Int64, _UInt64], _Int64);
AddBinarOperator(opAdd, _UInt64, [_UInt8, _UInt16, _UInt32, _UInt64], _UInt64);
// int + float
AddBinarOperator(opAdd, _Float32, [_Int8, _UInt8, _Int16, _UInt16, _Int32, _UInt32, _Int64, _UInt64, _Float32], _Float32);
AddBinarOperator(opAdd, _Float64, [_Int8, _UInt8, _Int16, _UInt16, _Int32, _UInt32, _Int64, _UInt64, _Float32, _Float64], _Float64);
AddBinarOperator(opAdd, _Float80, [_Int8, _UInt8, _Int16, _UInt16, _Int32, _UInt32, _Int64, _UInt64, _Float32, _Float64, _Float80, _Currency], _Float80);
// strings
AddBinarOperator(opAdd, _UnicodeString, _UnicodeString, _UnicodeString);
AddBinarOperator(opAdd, _UnicodeString, _WideChar, _UnicodeString);
AddBinarOperator(opAdd, _UnicodeString, _PWideChar, _UnicodeString);
AddBinarOperator(opAdd, _PWideChar, _PWideChar, _UnicodeString);
AddBinarOperator(opAdd, _PWideChar, _WideChar, _UnicodeString);
AddBinarOperator(opAdd, _PWideChar, _UnicodeString, _UnicodeString);
AddBinarOperator(opAdd, _WideChar, _WideChar, _UnicodeString);
AddBinarOperator(opAdd, _WideChar, _PWideChar, _UnicodeString);
AddBinarOperator(opAdd, _WideChar, _UnicodeString, _UnicodeString);
AddBinarOperator(opAdd, _WideString, _WideString, _WideString);
AddBinarOperator(opAdd, _AnsiString, _AnsiString, _AnsiString);
AddBinarOperator(opAdd, _AnsiString, _AnsiChar, _AnsiString);
AddBinarOperator(opAdd, _AnsiString, _PAnsiChar, _AnsiString);
AddBinarOperator(opAdd, _AnsiChar, _AnsiChar, _AnsiString);
AddBinarOperator(opAdd, _AnsiChar, _PAnsiChar, _AnsiString);
AddBinarOperator(opAdd, _AnsiChar, _AnsiString, _AnsiString);
AddBinarOperator(opAdd, _Variant, _Variant, _Variant);
end;
procedure TSYSTEMUnit.AddDivOperators;
begin
AddBinarOperator(opDivide, _Int8, [_Int8, _UInt8, _Int16, _UInt16, _Int32, _UInt32, _Int64, _UInt64], _Float64);
AddBinarOperator(opDivide, _Int16, [_Int8, _UInt8, _Int16, _UInt16, _Int32, _UInt32, _Int64, _UInt64], _Float64);
AddBinarOperator(opDivide, _Int32, [_Int8, _UInt8, _Int16, _UInt16, _Int32, _UInt32, _Int64, _UInt64], _Float64);
AddBinarOperator(opDivide, _Int64, [_Int8, _UInt8, _Int16, _UInt16, _Int32, _UInt32, _Int64, _UInt64], _Float64);
AddBinarOperator(opDivide, _Float32, [_Int8, _UInt8, _Int16, _UInt16, _Int32, _UInt32, _Int64, _UInt64, _Float32, _Float64], _Float64);
AddBinarOperator(opDivide, _Float64, [_Int8, _UInt8, _Int16, _UInt16, _Int32, _UInt32, _Int64, _UInt64, _Float32, _Float64], _Float64);
AddBinarOperator(opDivide, _Variant, _Variant, _Variant);
end;
procedure TSYSTEMUnit.AddArithmeticOperators;
begin
AddNegOperators;
AddAddOperators;
AddSubOperators;
AddMulOperators;
AddDivOperators;
AddIntDivOperators;
AddModOperators;
end;
procedure TSYSTEMUnit.AddBitwiseOperators;
function GetMaxBitwiceOpType(DtLeft, DtRight: TIDType): TIDType;
begin
if DtLeft.DataTypeID in [dtInt8, dtUint8, dtInt16, dtUInt16, dtInt32, dtUint32] then
Result := _UInt32
else
Result := _Int64;
end;
procedure UnarOp(Op: TOperatorID);
var
i: TDataTypeID;
begin
for i := dtInt8 to dtNativeUInt do
AddUnarOperator(Op, DataTypes[i], DataTypes[i]);
end;
procedure BitwiseOp(Op: TOperatorID);
var
i, j: TDataTypeID;
begin
for i := dtInt8 to dtNativeUInt do
for j := dtInt8 to dtNativeUInt do
AddBinarOperator(Op, DataTypes[i], DataTypes[j], GetMaxBitwiceOpType(DataTypes[i], DataTypes[j]));
end;
begin
UnarOp(opNot);
BitwiseOp(opAnd);
BitwiseOp(opOr);
BitwiseOp(opXor);
BitwiseOp(opShiftLeft);
BitwiseOp(opShiftRight);
end;
procedure TSYSTEMUnit.AddCompareOperators;
procedure AD(Op: TOperatorID);
var
i, j: TDataTypeID;
begin
for i := dtInt8 to dtNativeUInt do
for j := dtInt8 to dtNativeUInt do
AddBinarOperator(Op, DataTypes[i], DataTypes[j], _Boolean);
for i := dtInt8 to dtUInt64 do begin
AddBinarOperator(Op, DataTypes[i], _Float32, _Boolean);
AddBinarOperator(Op, DataTypes[i], _Float64, _Boolean);
AddBinarOperator(Op, DataTypes[i], _Float64, _Boolean);
AddBinarOperator(Op, DataTypes[i], _Currency, _Boolean);
AddBinarOperator(Op, DataTypes[i], _Comp, _Boolean);
AddBinarOperator(Op, _Float32, DataTypes[i], _Boolean);
AddBinarOperator(Op, _Float64, DataTypes[i], _Boolean);
AddBinarOperator(Op, _Float80, DataTypes[i], _Boolean);
AddBinarOperator(Op, _Currency, DataTypes[i], _Boolean);
AddBinarOperator(Op, _Comp, DataTypes[i], _Boolean);
end;
AddBinarOperator(Op, _Float32, _Float32, _Boolean);
AddBinarOperator(Op, _Float32, _Float64, _Boolean);
AddBinarOperator(Op, _Float64, _Float32, _Boolean);
AddBinarOperator(Op, _Float64, _Float64, _Boolean);
AddBinarOperator(Op, _Float32, _Float80, _Boolean);
AddBinarOperator(Op, _Float64, _Float80, _Boolean);
AddBinarOperator(Op, _Float80, _Float80, _Boolean);
AddBinarOperator(Op, _Float32, _Currency, _Boolean);
AddBinarOperator(Op, _Float64, _Currency, _Boolean);
AddBinarOperator(Op, _Float80, _Currency, _Boolean);
AddBinarOperator(Op, _Boolean, _Boolean, _Boolean);
AddBinarOperator(Op, _Variant, _Variant, _Boolean);
end;
begin
AD(opEqual);
AD(opNotEqual);
AD(opLess);
AD(opLessOrEqual);
AD(opGreater);
AD(opGreaterOrEqual);
// Char
AddBinarOperator(opEqual, _WideChar, _WideChar, _Boolean);
AddBinarOperator(opNotEqual, _WideChar, _WideChar, _Boolean);
AddBinarOperator(opLess, _WideChar, _WideChar, _Boolean);
AddBinarOperator(opLessOrEqual, _WideChar, _WideChar, _Boolean);
AddBinarOperator(opGreater, _WideChar, _WideChar, _Boolean);
AddBinarOperator(opGreaterOrEqual, _WideChar, _WideChar, _Boolean);
// AnsiChar
AddBinarOperator(opEqual, _AnsiChar, _AnsiChar, _Boolean);
AddBinarOperator(opNotEqual, _AnsiChar, _AnsiChar, _Boolean);
AddBinarOperator(opLess, _AnsiChar, _AnsiChar, _Boolean);
AddBinarOperator(opLessOrEqual, _AnsiChar, _AnsiChar, _Boolean);
AddBinarOperator(opGreater, _AnsiChar, _AnsiChar, _Boolean);
AddBinarOperator(opGreaterOrEqual, _AnsiChar, _AnsiChar, _Boolean);
// ShortString
AddBinarOperator(opEqual, _ShortString, _ShortString, _Boolean);
AddBinarOperator(opNotEqual, _ShortString, _ShortString, _Boolean);
AddBinarOperator(opLess, _ShortString, _ShortString, _Boolean);
AddBinarOperator(opLessOrEqual, _ShortString, _ShortString, _Boolean);
AddBinarOperator(opGreater, _ShortString, _ShortString, _Boolean);
AddBinarOperator(opGreaterOrEqual, _ShortString, _ShortString, _Boolean);
// AnsiString
AddBinarOperator(opEqual, _AnsiString, _AnsiString, _Boolean);
AddBinarOperator(opNotEqual, _AnsiString, _AnsiString, _Boolean);
AddBinarOperator(opLess, _AnsiString, _AnsiString, _Boolean);
AddBinarOperator(opLessOrEqual, _AnsiString, _AnsiString, _Boolean);
AddBinarOperator(opGreater, _AnsiString, _AnsiString, _Boolean);
AddBinarOperator(opGreaterOrEqual, _AnsiString, _AnsiString, _Boolean);
// String
AddBinarOperator(opEqual, _UnicodeString, _UnicodeString, _Boolean);
AddBinarOperator(opNotEqual, _UnicodeString, _UnicodeString, _Boolean);
AddBinarOperator(opLess, _UnicodeString, _UnicodeString, _Boolean);
AddBinarOperator(opLessOrEqual, _UnicodeString, _UnicodeString, _Boolean);
AddBinarOperator(opGreater, _UnicodeString, _UnicodeString, _Boolean);
AddBinarOperator(opGreaterOrEqual, _UnicodeString, _UnicodeString, _Boolean);
// WideString
AddBinarOperator(opEqual, _WideString, _WideString, _Boolean);
AddBinarOperator(opNotEqual, _WideString, _WideString, _Boolean);
AddBinarOperator(opLess, _WideString, _WideString, _Boolean);
AddBinarOperator(opLessOrEqual, _WideString, _WideString, _Boolean);
AddBinarOperator(opGreater, _WideString, _WideString, _Boolean);
AddBinarOperator(opGreaterOrEqual, _WideString, _WideString, _Boolean);
end;
function TSYSTEMUnit.RegisterType(const TypeName: string; TypeClass: TIDTypeClass; DataType: TDataTypeID): TIDType;
begin
Result := TypeClass.CreateAsSystem(IntfScope, TypeName);
Result.Elementary := True;
Result.DataTypeID := DataType;
Result.ItemType := itType;
InsertToScope(Result);
AddType(Result);
end;
function TSYSTEMUnit.RegisterTypeCustom(const TypeName: string; TypeClass: TIDTypeClass;
DataType: TDataTypeID): TIDType;
begin
Result := TypeClass.CreateAsSystem(IntfScope, TypeName);
Result.Elementary := True;
Result.DataTypeID := DataType;
Result.ItemType := itType;
InsertToScope(Result);
AddType(Result);
end;
procedure TSYSTEMUnit.RegisterTypes;
begin
//===============================================================
_Int8 := RegisterOrdinal('ShortInt', dtInt8, MinInt8, MaxInt8);
_Int16 := RegisterOrdinal('SmallInt', dtInt16, MinInt16, MaxInt16);
_Int32 := RegisterOrdinal('Integer', dtInt32, MinInt32, MaxInt32);
_Int64 := RegisterOrdinal('Int64', dtInt64, MinInt64, MaxInt64);
_UInt8 := RegisterOrdinal('Byte', dtUInt8, 0, MaxUInt8);
_UInt16 := RegisterOrdinal('Word', dtUInt16, 0, MaxUInt16);
_UInt32 := RegisterOrdinal('Cardinal', dtUInt32, 0, MaxUInt32);
_UInt64 := RegisterOrdinal('UInt64', dtUInt64, 0, MaxUInt64);
_NativeInt := RegisterOrdinal('NativeInt', dtNativeInt, MinInt64, MaxInt64);
_NativeUInt := RegisterOrdinal('NativeUInt', dtNativeUInt, 0, MaxUInt64);
_Float32 := RegisterType('Single', TIDType, dtFloat32);
_Float64 := RegisterType('Double', TIDType, dtFloat64);
_Float80 := RegisterType('Extended', TIDType, dtFloat80);
_Currency := RegisterType('Currency', TIDType, dtCurrency);
fDecls._Comp := RegisterType('Comp', TIDType, dtComp);
//===============================================================
_Boolean := RegisterOrdinal('Boolean', dtBoolean, 0, 1);
_Boolean.OverloadExplicitFromAny(Operators.IsOrdinal);
_AnsiChar := RegisterOrdinal('AnsiChar', dtAnsiChar, 0, MaxUInt8);
_WideChar := RegisterOrdinal('Char', dtChar, 0, MaxUInt16);
//===============================================================
_ShortString := RegisterType('ShortString', TIDString, dtShortString);
TIDString(_ShortString).ElementDataType := _AnsiChar;
//===============================================================
_AnsiString := RegisterType('AnsiString', TIDString, dtAnsiString);
TIDString(_AnsiString).ElementDataType := _AnsiChar;
//===============================================================
_UnicodeString := RegisterType('String', TIDString, dtString);
TIDString(_UnicodeString).ElementDataType := _WideChar;
//===============================================================
_Variant := RegisterType('Variant', TIDVariant, dtVariant);
//===============================================================
_WideString := RegisterType('WideString', TIDString, dtWideString);
TIDString(_WideString).ElementDataType := _WideChar;
//===============================================================
fOpenString := RegisterTypeCustom('OpenString', TIDString, dtString);
TIDString(fOpenString).ElementDataType := _WideChar;
//===============================================================
// TObject ========================================================
{FTObject := TIDClass.CreateAsSystem(UnitInterface, 'TObject');
FTObject.NeedForward := True; // forward declaration
InsertToScope(FTObject);}
// TGUID ========================================================
fDecls._GuidType := TIDRecord.CreateAsSystem(IntfScope, 'TGUID');
fDecls._GuidType.NeedForward := True;
fDecls._GuidType.DataTypeID := dtGuid;
fDecls._GuidType.DataType := _MetaType;
InsertToScope(fDecls._GuidType);
AddType(fDecls._GuidType);
//===============================================================
FDateTimeType := TIDAliasType.CreateAliasAsSystem(IntfScope, 'DateTime', _Float64);
FDateType := TIDAliasType.CreateAliasAsSystem(IntfScope, 'Date', _Float64);
FTimeType := TIDAliasType.CreateAliasAsSystem(IntfScope, 'Time', _Float64);
InsertToScope(FDateTimeType);
InsertToScope(FDateType);
InsertToScope(FTimeType);
AddType(FDateTimeType);
AddType(FDateType);
AddType(FTimeType);
//===============================================================
fDecls._PointerType := RegisterPointer('Pointer', nil);
//===============================================================
// null ptr type (special type for "nil" constant)
fDecls._NullPtrType := TIDNullPointerType.CreateAsSystem(IntfScope, 'null ptr');
// fDecls._NullPtrType.AddBinarySysOperator(opEqual, fOperators.Equal_NullPtr);
// fDecls._NullPtrType.AddBinarySysOperator(opNotEqual, fOperators.NotEqual_NullPtr);
// null ptr type constant
fDecls._NullPtrConstant := TIDIntConstant.Create(IntfScope, Identifier('nil'), fDecls._NullPtrType, 0);
fDecls._NullPtrExpression := TIDExpression.Create(fDecls._NullPtrConstant);
IntfScope.InsertID(fDecls._NullPtrConstant);
fDecls._PointerType.CreateStandardOperators;
fDecls._NullPtrType.CreateStandardOperators;
// Untyped reference
fDecls._UntypedReference := TIDUntypedRef.CreateAsSystem(IntfScope, '$Untyped reference');
IntfScope.InsertID(fDecls._UntypedReference);
fDecls._UntypedReference.OverloadImplicitFromAny(Operators.ImplicitUntypedFromAny);
fDecls._UntypedReference.OverloadExplicitToAny(Operators.ExplicitUntypedRefToAny);
// Untyped
fDecls._Untyped := TIDOrdinal.CreateAsSystem(IntfScope, '$Untyped');
fDecls._Untyped.DataTypeID := dtNativeUInt;
IntfScope.InsertID(fDecls._Untyped);
fDecls._Untyped.OverloadExplicitToAny(Operators.ExplicitUntypedToAny);
// Delphi system aliases
RegisterTypeAlias('LongInt', _Int32);
RegisterTypeAlias('LongWord', _UInt32);
fDecls._Real := RegisterTypeAlias('Real', _Float64);
RegisterTypeAlias('_ShortString', _ShortString);
RegisterTypeAlias('UnicodeString', _UnicodeString);
RegisterTypeAlias('WideChar', _WideChar);
RegisterTypeAlias('ByteBool', _Boolean);
RegisterTypeAlias('WordBool', _Boolean);
RegisterTypeAlias('LongBool', _Boolean);
RegisterTypeAlias('OleVariant', _Variant);
// PAnsiChar
fDecls._PAnsiChar := RegisterType('PAnsiChar', TIDPointer, dtPAnsiChar);
TIDPointer(fDecls._PAnsiChar).ReferenceType := _AnsiChar;
fDecls._PAnsiChar.OverloadImplicitTo(_Variant);
fDecls._PAnsiChar.CreateStandardOperators;
// PWideChar
fDecls._PWideChar := RegisterType('PWideChar', TIDPointer, dtPWideChar);
TIDPointer(fDecls._PWideChar).ReferenceType := _WideChar;
fDecls._PWideChar.OverloadImplicitTo(_Variant);
fDecls._PWideChar.CreateStandardOperators;
_AnsiChar.DefaultReference := _PAnsiChar;
_WideChar.DefaultReference := _PWideChar;
RegisterTypeAlias('PChar', _PWideChar);
RegisterTypeAlias('Text', _Pointer);
fDecls._MaxIntConstant := RegisterConstInt('MaxInt', _Int32, MaxInt32);
fDecls._MaxIntExpression := TIDExpression.Create(fDecls._MaxIntConstant, 0);
// constant "True"
fDecls._True := TIDBooleanConstant.Create(IntfScope, Identifier('TRUE'), _Boolean, True);
fDecls._TrueExpression := TIDExpression.Create(fDecls._True);
IntfScope.InsertID(fDecls._True);
// constant "False"
fDecls._False := TIDBooleanConstant.Create(IntfScope, Identifier('FALSE'), _Boolean, False);
fDecls._FalseExpression := TIDExpression.Create(fDecls._False);
IntfScope.InsertID(fDecls._False);
// constant "0"
fDecls._ZeroConstant := TIDIntConstant.CreateAsAnonymous(IntfScope, _UInt8, 0);
fDecls._ZeroIntExpression := TIDExpression.Create(fDecls._ZeroConstant);
fDecls._ZeroFloatExpression := TIDExpression.Create(TIDFloatConstant.CreateAsAnonymous(IntfScope, _Float64, 0));
// constant "1"
fDecls._OneConstant := TIDIntConstant.CreateAsAnonymous(IntfScope, _UInt8, 1);
fDecls._OneExpression := TIDExpression.Create(fDecls._OneConstant);
// constant ""
fDecls._EmptyStrConstant := TIDStringConstant.CreateAsAnonymous(IntfScope, _UnicodeString, '');
fDecls._EmptyStrExpression := TIDExpression.Create(fDecls._EmptyStrConstant);
// constant "[]"
fDecls._EmptyArrayConstant := TIDDynArrayConstant.CreateAsAnonymous(IntfScope, _Void, []);
// constant for deprecated
fDecls._DeprecatedDefaultStr := TIDStringConstant.CreateAsSystem(IntfScope, 'The declaration is deprecated');
AddImplicists;
AddExplicists;
AddArithmeticOperators;
AddLogicalOperators;
AddBitwiseOperators;
AddCompareOperators;
end;
function TSYSTEMUnit.RegisterVariable(Scope: TScope; const Name: string; DataType: TIDType): TIDVariable;
begin
Result := TIDVariable.CreateAsSystem(Scope, Name);
Result.DataType := DataType;
InsertToScope(Scope, Result);
end;
procedure TSYSTEMUnit.SearchSystemTypes;
begin
// todo: use forward declaration instead
fDecls._TObject := GetPublicClass('TObject');
fDecls._ResStringRecord := GetPublicType('PResStringRec');
fDecls._TVarRec := GetPublicType('TVarRec');
fDecls._TTypeKind := GetPublicType('TTypeKind') as TIDEnum;
if Assigned(fDecls._TVarRec) then
AddTVarRecImplicitOperators;
end;
procedure TSYSTEMUnit.SystemFixup;
begin
if Package.Target = TWINX86_Target.TargetName then
begin
var coeffTypeType: TIDEnum := RegisterType('coeffType', TIDEnum, dtEnum) as TIDEnum;
coeffTypeType.Items := TScope.Create(stLocal, ImplScope);
var Item := TIDIntConstant.Create(coeffTypeType.Items, TIdentifier.Make('cHi'));
Item.DataType := coeffTypeType;
Item.Value := 0;
InsertToScope(coeffTypeType.Items, Item);
Item := TIDIntConstant.Create(coeffTypeType.Items, TIdentifier.Make('cLo'));
Item.DataType := coeffTypeType;
Item.Value := 1;
InsertToScope(coeffTypeType.Items, Item);
coeffTypeType.LowBound := 0;
coeffTypeType.HighBound := 1;
end;
end;
function TSYSTEMUnit.RegisterBuiltin(const BuiltinClass: TIDBuiltInFunctionClass): TIDBuiltInFunction;
begin
Result := BuiltinClass.CreateDecl(Self, Self.IntfScope);
InsertToScope(Self.IntfScope, Result);
end;
procedure TSYSTEMUnit.RegisterBuiltinFunctions;
begin
RegisterBuiltin(TSF_Abs);
RegisterBuiltin(TSF_Assert);
RegisterBuiltin(TSF_Assigned);
RegisterBuiltin(TSF_AtomicCmpExchange);
RegisterBuiltin(TSF_AtomicDecrement);
RegisterBuiltin(TSF_AtomicExchange);
RegisterBuiltin(TSF_AtomicIncrement);
RegisterBuiltin(TSF_Copy);
RegisterBuiltin(TSF_Chr);
RegisterBuiltin(TSF_Close);
RegisterBuiltin(TCT_Dec);
RegisterBuiltin(TSF_Dispose);
RegisterBuiltin(TSCTF_Defined);
RegisterBuiltin(TSCTF_Default);
RegisterBuiltin(TSCTF_IsManagedType);
RegisterBuiltin(TSCTF_IsConstValue);
RegisterBuiltin(TSCTF_TypeInfo);
RegisterBuiltin(TSCTF_TypeName);
RegisterBuiltin(TSCTF_GetTypeKind);
RegisterBuiltin(TSCTF_HasWeakRef);
RegisterBuiltin(TSCTF_Declared);
RegisterBuiltin(TCT_Break);
RegisterBuiltin(TCT_Continue);
RegisterBuiltin(TSF_Delete);
RegisterBuiltin(TSF_Exit);
RegisterBuiltin(TSF_Exclude);
RegisterBuiltin(TSF_FreeMem);
RegisterBuiltin(TSF_FillChar);
RegisterBuiltin(TSF_GetMem);
RegisterBuiltin(TSF_GetDir);
RegisterBuiltin(TSF_Halt);
RegisterBuiltin(TSF_HiBound);
RegisterBuiltin(TSF_HiByte);
RegisterBuiltin(TSF_LoByte);
RegisterBuiltin(TSF_Include);
RegisterBuiltin(TSF_Inc);
RegisterBuiltin(TSF_Insert);
RegisterBuiltin(TSF_LoBound);
RegisterBuiltin(TSF_Length);
RegisterBuiltin(TSF_New);
RegisterBuiltin(TSF_Now);
RegisterBuiltin(TSF_Ord);
RegisterBuiltin(TSF_Odd);
RegisterBuiltin(TSF_Pi);
RegisterBuiltin(TSF_Pred);
RegisterBuiltin(TSF_ReallocMem);
RegisterBuiltin(TSF_Round);
RegisterBuiltin(TSF_RunError);
RegisterBuiltin(TSF_Str);
RegisterBuiltin(TSF_Sqr);
RegisterBuiltin(TCT_SizeOf);
RegisterBuiltin(TSF_Succ);
RegisterBuiltin(TSF_SetLength);
RegisterBuiltin(TSF_SetString);
RegisterBuiltin(TSF_Swap);
RegisterBuiltin(TSF_Trunc);
RegisterBuiltin(TSF_Val);
RegisterBuiltin(TSF_ReturnAddress);
RegisterBuiltin(TSF_VarCast);
RegisterBuiltin(TSF_VarClear);
RegisterVariable(ImplScope, 'ReturnAddress', _Pointer);
RegisterConstStr(ImplScope, 'libmmodulename', '');
RegisterConstInt('CompilerVersion', _Int32, 35); // Delphi 11.x
// jsut for debug purpose
RegisterBuiltin(TSCTF_Console);
RegisterBuiltin(TSCTF_Scope);
end;
function TSYSTEMUnit.RegisterOrdinal(const TypeName: string; DataType: TDataTypeID; LowBound: Int64; HighBound: UInt64): TIDType;
begin
Result := RegisterType(TypeName, TIDOrdinal, DataType);
TIDOrdinal(Result).LowBound := LowBound;
TIDOrdinal(Result).HighBound := HighBound;
TIDOrdinal(Result).SignedBound := LowBound < 0;
end;
function TSYSTEMUnit.Compile(ACompileIntfOnly: Boolean; RunPostCompile: Boolean = True): TCompilerResult;
begin
Result := CompileInProgress;
try
RegisterBuiltinFunctions;
SystemFixup;
Result := inherited Compile(ACompileIntfOnly, {RunPostCompile:} False);
if Result = CompileSuccess then
begin
SearchSystemTypes;
fCompiled := CompileSuccess;
end;
except
on e: ECompilerStop do Exit;
on e: ECompilerSkip do Exit(CompileSkip);
on e: ECompilerAbort do PutMessage(ECompilerAbort(e).CompilerMessage^);
on e: Exception do PutMessage(cmtInteranlError, e.Message);
end;
end;
constructor TSYSTEMUnit.Create(const Project: IASTProject; const FileName: string; const Source: string);
begin
inherited Create(Project, FileName, Source);
fSysDecls := @fDecls;
{$IFDEF DEBUG}
SetUnitName('system');
{$ENDIF}
fOperators.Init(IntfScope);
fDecls._MetaType := TIDType.CreateAsSystem(IntfScope, 'MetaType');
fDecls._MetaType.DataTypeID := dtClass;
fDecls._Void := TIDType.CreateAsSystem(IntfScope, 'Void');
fDecls._Void.DataTypeID := TDataTypeID(dtUnknown);
fDecls._OrdinalType := TIDOrdinal.CreateAsSystem(IntfScope, 'ordinal');
RegisterTypes;
// fDecls._PointerType.CreateStandardOperators;
// fDecls._PAnsiChar.CreateStandardOperators;
// fDecls._PChar.CreateStandardOperators;
fArrayType := TIDArray.CreateAsSystem(IntfScope, 'array');
end;
function TSYSTEMUnit.GetTypeByID(ID: TDataTypeID): TIDType;
begin
Result := fDecls.DataTypes[ID];
end;
function TSYSTEMUnit.GetSystemDeclarations: PDelphiSystemDeclarations;
begin
Result := addr(fDecls);
end;
procedure TSYSTEMUnit.InsertToScope(Declaration: TIDDeclaration);
begin
if Assigned(IntfScope.InsertNode(Declaration.Name, Declaration)) then
raise Exception.CreateFmt('Unit SYSTEM: ' + sIdentifierRedeclaredFmt, [Declaration.Name]);
end;
function TSYSTEMUnit.CompileIntfOnly: TCompilerResult;
begin
Result := Compile({ACompileIntfOnly:} True);
end;
function TSYSTEMUnit.RegisterTypeAlias(const TypeName: string; OriginalType: TIDType): TIDAliasType;
begin
Result := TIDAliasType.CreateAliasAsSystem(IntfScope, TypeName, OriginalType);
Result.Elementary := True;
InsertToScope(Result);
AddType(Result);
end;
function TSYSTEMUnit.RegisterConstInt(const Name: string; DataType: TIDType; Value: Int64): TIDIntConstant;
begin
Result := TIDIntConstant.CreateAsSystem(IntfScope, Name);
Result.DataType := DataType;
Result.Value := Value;
InsertToScope(Result);
end;
function TSYSTEMUnit.RegisterConstStr(Scope: TScope; const Name, Value: string): TIDStringConstant;
begin
Result := TIDStringConstant.CreateAsSystem(Scope, Name);
Result.DataType := _UnicodeString;
Result.Value := Value;
InsertToScope(Result);
end;
function TSYSTEMUnit.RegisterPointer(const TypeName: string; TargetType: TIDType): TIDPointer;
begin
Result := TIDPointer.CreateAsSystem(IntfScope, TypeName);
Result.ReferenceType := TargetType;
InsertToScope(Result);
AddType(Result);
end;
{ TSystemOperatos }
procedure TSystemOperatos.Init(Scope: TScope);
begin
// implicit
ImplicitVariantToAny := TSysImplicitVariantToAny.CreateAsSystem(Scope);
ImplicitVariantFromAny := TSysImplicitVariantFromAny.CreateAsSystem(Scope);
ImplicitStringFromAny := TSysImplicitStringFromAny.CreateAsSystem(Scope);
ImplicitCharToAnsiChar := TSysImplicitCharToAnsiChar.CreateAsSystem(Scope);
ImplicitCharToString := TSysImplicitCharToString.CreateAsSystem(Scope);
ImplicitRangeFromAny := TSysImplicitRangeFromAny.CreateAsSystem(Scope);
ImplicitRangeToAny := TSysImplicitRangeToAny.CreateAsSystem(Scope);
ImplicitStringToAnsiString := TSysImplicitStringToAnsiString.CreateAsSystem(Scope);
ImplicitStringToGUID := TSysImplicitStringToGUID.CreateAsSystem(Scope);
ImplicitStringToPChar := TSysImplicitStringToPChar.CreateAsSystem(Scope);
ImplicitAnsiStringToString := TSysImplicitAnsiStringToString.CreateAsSystem(Scope);
ImplicitPointerToAny := TSysImplicitPointerToAny.CreateAsSystem(Scope);
ImplicitPointerFromAny := TSysImplicitPointerFromAny.CreateAsSystem(Scope);
ImplicitUntypedFromAny := TSysImplicitUntypedFromAny.CreateAsSystem(Scope);
ImplicitClosureToTMethod := TSysImplicitClosureToTMethod.CreateAsSystem(Scope);
ImplicitCharToAnsiString := TSysImplicitCharToAnsiString.CreateAsSystem(Scope);
ImplicitAnsiStringFromAny := TSysImplicitAnsiStringFromAny.CreateAsSystem(Scope);
ImplicitAnsiCharToAnsiString := TSysImplicitAnsiCharToAnsiString.CreateAsSystem(Scope);
ImplicitAnsiCharToString := TSysImplicitAnsiCharToString.CreateAsSystem(Scope);
ImplicitAnsiCharToWideChar := TSysImplicitAnsiCharToWideChar.CreateAsSystem(Scope);
ImplicitMetaClassToGUID := TSysImplicitMetaClassToGUID.CreateAsSystem(Scope);
ImplicitClassToClass := TSysImplicitClassToClass.CreateAsSystem(Scope);
ImplicitArrayToAny := TSysImplicitArrayToAny.CreateAsSystem(Scope);
ImplicitArrayFromAny := TSysImplicitArrayFromAny.CreateAsSystem(Scope);
ImplicitSetFromAny := TSysImplicitSetFromAny.CreateAsSystem(Scope);
ImplicitNullPtrToAny := TSysImplicitNullPtrToAny.CreateAsSystem(Scope);
ImplicitTVarRecToAny := TSysImplicitTVarRecToAny.CreateAsSystem(Scope);
ImplicitTVarRecFromAny := TSysImplicitTVarRecFromAny.CreateAsSystem(Scope);
ImplicitSysVarFromAny := TSysImplicitSysVarFromAny.CreateAsSystem(Scope);
// explicit
ExplicitStringFromAny := TSysExplicitStringFromAny.CreateAsSystem(Scope);
ExplicitAnsiStringFromAny := TSysExplicitAnsiStringFromAny.CreateAsSystem(Scope);
ExplicitTProcFromAny := TSysExplicitTProcFromAny.CreateAsSystem(Scope);
ExplicitClassFromAny := TSysExplicitClassFromAny.CreateAsSystem(Scope);
ExplicitClassOfToAny := TSysExplicitClassOfToAny.CreateAsSystem(Scope);
ExplicitClassOfFromAny := TSysExplicitClassOfFromAny.CreateAsSystem(Scope);
ExplicitInterfaceFromAny := TSysExplicitInterfaceFromAny.CreateAsSystem(Scope);
ExplicitPointerToAny := TSysExplictPointerToAny.CreateAsSystem(Scope);
ExplicitPointerFromAny := TSysExplictPointerFromAny.CreateAsSystem(Scope);
ExplicitRecordFromAny := TSysExplicitRecordFromAny.CreateAsSystem(Scope);
ExplicitEnumToAny := TSysExplicitEnumToAny.CreateAsSystem(Scope);
ExplicitEnumFromAny := TSysExplicitEnumFromAny.CreateAsSystem(Scope);
ExplicitUntypedToAny := TSysExplicitUntypedToAny.CreateAsSystem(Scope);
ExplicitUntypedRefToAny := TSysExplicitUntypedRefToAny.CreateAsSystem(Scope);
ExplicitCharToAny := TSysExplicitCharToAny.CreateAsSystem(Scope);
ExplicitRangeFromAny := TSysExplicitRangeFromAny.CreateAsSystem(Scope);
ExplicitRecordToAny := TSysExplicitRecordToAny.CreateAsSystem(Scope);
ExplicitStaticArrayToAny := TSysExplicitStaticArrayToAny.CreateAsSystem(Scope);
ExplicitDynArrayToAny := TSysExplicitDynArrayToAny.CreateAsSystem(Scope);
ExplicitVariantToAny := TSysExplicitVariantToAny.CreateAsSystem(Scope);
ExplicitVariantFromAny := TSysExplicitVariantFromAny.CreateAsSystem(Scope);
// any cast
IsOrdinal := TSysTypeCast_IsOrdinal.CreateAsSystem(Scope);
// in
Ordinal_In_Set := TSysOrdinalInSet.CreateAsSystem(Scope);
// add
StaticArray_Add := TSys_StaticArray_Add.CreateAsSystem(Scope);
Ptr_IntDiv_Int := TSys_Ptr_IntDiv_Int.CreateAsSystem(Scope);
Multiply_Set := TSys_Multiply_Set.CreateAsSystem(Scope);
Add_Set := TSys_Add_Set.CreateAsSystem(Scope);
Subtract_Set := TSys_Subtract_Set.CreateAsSystem(Scope);
Equal_DynArray := TSys_Equal_DynArray.CreateAsSystem(Scope);
Equal_NullPtr := TSys_Equal_NullPtr.CreateAsSystem(Scope);
NotEqual_NullPtr := TSys_NotEqual_NullPtr.CreateAsSystem(Scope);
end;
initialization
finalization
end.
|
namespace proholz.xsdparser;
interface
type
XsdListVisitor = public class(XsdAnnotatedElementsVisitor)
private
// *
// * The {@link XsdList} instance which owns this {@link XsdListVisitor} instance. This way this visitor instance can
// * perform changes in the {@link XsdList} object.
//
//
var owner: XsdList;
public
constructor(aowner: XsdList);
method visit(element: XsdSimpleType); override;
end;
implementation
constructor XsdListVisitor(aowner: XsdList);
begin
inherited constructor(aowner);
self.owner := aowner;
end;
method XsdListVisitor.visit(element: XsdSimpleType);
begin
inherited visit(element);
if assigned(owner.getItemType()) then begin
raise new ParsingException(XsdList.XSD_TAG + ' element: The element cannot have both the itemType attribute and a ' + XsdSimpleType.XSD_TAG + ' element as content at the same time.');
end;
owner.setSimpleType(element);
end;
end. |
namespace InterfacesSample.SampleClasses;
interface
uses
System,
System.Windows.Forms;
type
{ IVersionInfo interface
Notice how, in Oxygene, there's no need to declare setter and getter methods for
interface properties. Their implementation and names are deferred to the class
that implements this interface. }
IVersionInfo = interface
property Name: String read;
property MajVersion: Integer read;
property MinVersion: Integer read;
property Description: String read;
end;
{ VersionInfo class }
VersionInfo = class(IVersionInfo)
private
fControl: Control;
protected
method GetName: String;
public
constructor(aControl: Control; aMajVersion, aMinVersion: Integer; aDescription: String);
property Name: String read GetName;
{ The following Readonly properties can only be set inside a constructor }
property MajVersion: Integer; readonly;
property MinVersion: Integer; readonly;
property Description: String; readonly;
end;
{ SampleButton
Notice how the VersionInfo property is initialized inline and, trough the use
of the keyword "implements", provides an implementation for IVersionInfo to
the class SampleButton.
}
SampleButton = class(System.Windows.Forms.Button, IVersionInfo)
public
property VersionInfo: IVersionInfo := new VersionInfo(self, 1,0,'A button with VersionInfo'); implements IVersionInfo;
end;
{ SampleTextBox
See comment for SampleButton. Thanks to inline instantiation of properties
and the "implements" keyword, code-reuse and interface delegation is made
much simpler. }
SampleTextBox = class(System.Windows.Forms.TextBox, IVersionInfo)
public
property VersionInfo: IVersionInfo := new VersionInfo(self, 2,3,'A text box with VersionInfo'); implements IVersionInfo;
end;
implementation
constructor VersionInfo(aControl: Control; aMajVersion, aMinVersion: integer; aDescription: string);
begin
inherited constructor;
fControl := aControl;
MajVersion := aMajVersion;
MinVersion := aMinVersion;
Description := aDescription;
end;
method VersionInfo.GetName: string;
begin
{ Result is implicitly initialized to '' }
if assigned(fControl) then
result := fControl.Name
end;
end. |
//=============================================================================
// sgAnimations.pas
//=============================================================================
/// Animations in SwinGame can be used to move between cells in bitmaps and
/// sprites. Each Animation generates a number sequence that can then be used
/// when drawing bitmaps.
///
/// @module Animations
/// @static
unit sgAnimations;
//=============================================================================
interface
uses sgTypes;
//=============================================================================
//----------------------------------------------------------------------------
// Creating an AnimationScript
//----------------------------------------------------------------------------
/// Load animation details from a animation frames file.
///
/// @lib
/// @sn loadAnimationScriptFromFile:%s
///
/// @class AnimationScript
/// @constructor
/// @csn initFromFile:%s
function LoadAnimationScript(const filename: String) : AnimationScript;
/// Frees loaded animation frames data. Use this when you will no longer be
/// using the animation for any purpose, including within sprites.
///
/// @lib
///
/// @class AnimationScript
/// @dispose
procedure FreeAnimationScript(var scriptToFree: AnimationScript);
//----------------------------------------------------------------------------
// AnimationScript mapping routines
//----------------------------------------------------------------------------
/// The index of the animation within the animation template that has the supplied name.
///
/// @lib
/// @sn animationScript:%s indexOfAnimation:%s
///
/// @class AnimationScript
/// @method IndexOfAnimation
/// @csn indexOfAnimation:%s
///
/// @doc_details
function AnimationIndex(temp: AnimationScript; const name: String): Longint;
/// The name of the animation within the animation template at the specified index.
///
/// @lib AnimationScriptAnimationName
/// @sn animationScript:%s nameOfAnimation:%s
///
/// @class AnimationScript
/// @method NameOfAnimation
/// @csn nameOfAnimation:%s
///
/// @doc_details
function AnimationName(temp: AnimationScript; idx: Longint): String;
/// The name of the animation currently being played.
///
/// @lib
/// @sn nameOfAnimation:%s
///
/// @class Animation
/// @getter Name
///
/// @doc_details
function AnimationName(temp: Animation): String;
//----------------------------------------------------------------------------
// AnimationScript mapping routines
//----------------------------------------------------------------------------
/// Loads and returns a `AnimationScript`. The supplied ``filename`` is used to
/// locate the `AnimationScript` to load. The supplied ``name`` indicates the
/// name to use to refer to this in SwinGame. The `AnimationScript` can then be
/// retrieved by passing this ``name`` to the `AnimationScriptNamed` function.
///
/// @lib
/// @sn loadAnimationScriptNamed:%s fromFile:%s
///
/// @class AnimationScript
/// @constructor
/// @csn initWithName:%s fromFile:%s
function LoadAnimationScriptNamed(const name, filename: String): AnimationScript;
/// Determines if SwinGame has animation frames loaded for the supplied ``name``.
/// This checks against all loaded animation frames, those loaded without a name
/// are assigned the filename as a default.
///
/// @lib
///
/// @doc_details
function HasAnimationScript(const name: String): Boolean;
/// Returns the `AnimationScript` that has been loaded with the specified ``name``,
/// see `LoadAnimationScriptNamed`.
///
/// @lib
function AnimationScriptNamed(const name: String): AnimationScript;
/// Releases the SwinGame resources associated with the animation template of the
/// specified ``name``.
///
/// @lib
procedure ReleaseAnimationScript(const name: String);
/// Releases all of the animation templates that have been loaded.
///
/// @lib
procedure ReleaseAllAnimationScripts();
/// Returns the name of the Animation Script.
///
/// @lib
///
/// @class AnimationScript
/// @getter Name
function AnimationScriptName(script: AnimationScript): String;
/// Returns the number of Animations within an Animation Script.
///
/// @lib
///
/// @class AnimationScript
/// @getter AnimationCount
function AnimationCount(script: animationScript): Longint;
//----------------------------------------------------------------------------
// Creating an Animation
//----------------------------------------------------------------------------
/// Creates an animation from a `AnimationScript`. This may play a sound effect
/// if the animation is set to play a sound effect on its first frame.
///
/// @lib CreateAnimationNamed
/// @sn animationNamed:%s from:%s
///
/// @class Animation
/// @constructor
/// @csn initAsName:%s from:%s
function CreateAnimation(const identifier: String; script: AnimationScript): Animation; overload;
/// Creates an animation from a `AnimationScript`. If ``withSound`` is ``true``, this may
/// play a sound effect if the animation is set to play a sound effect on its first frame.
///
/// @lib CreateAnimationNamedWithSound
/// @sn animationNamed:%s from:%s withSound:%s
///
/// @class Animation
/// @constructor
/// @csn initAsName:%s from:%s withSound:%s
///
/// @doc_details
function CreateAnimation(const identifier: String; script: AnimationScript; withSound: Boolean): Animation; overload;
/// Creates an animation from an `AnimationScript`. If ``withSound`` is ``true``, this may
/// play a sound effect if the animation is set to play a sound effect on its first frame.
///
/// @lib
/// @sn animationAtIndex:%s from:%s withSound:%s
///
/// @class Animation
/// @constructor
/// @csn initAtIndex:%s from:%s withSound:%s
///
/// @doc_details
function CreateAnimation(identifier: Longint; script: AnimationScript; withSound: Boolean): Animation; overload;
/// Creates an animation from an `AnimationScript`. This may play a sound effect
/// if the animation is set to play a sound effect on its first frame.
///
/// @lib CreateAnimationWithSound
/// @sn animationAtIndex:%s from:%s
///
/// @class Animation
/// @constructor
/// @csn initAtIndex:%s from:%s
///
/// @doc_details
function CreateAnimation(identifier: Longint; script: AnimationScript): Animation; overload;
/// Disposes of the resources used in the animation.
///
/// @lib
///
/// @class Animation
/// @dispose
procedure FreeAnimation(var ani: Animation);
//----------------------------------------------------------------------------
// Drawing Animations
//----------------------------------------------------------------------------
/// Assign a new starting animation to the passed in animation from the `AnimationScript`.
/// This may play a sound if the first frame of the animation is linked to a sound effect.
///
/// @lib AssignAnimationNamed
/// @sn assignAnimationNamed:%s to:%s from:%s
///
/// @class Animation
/// @overload AssignAnimation AssignAnimationNamed
/// @csn assignAnimationNamed:%s from:%s
procedure AssignAnimation(anim: Animation; const name: String; script: AnimationScript); overload;
/// Assign a new starting animation to the passed in animation from the `AnimationScript`.
/// This may play a sound if the first frame of the animation is linked to a sound effect, and withSound is true.
///
/// @lib AssignAnimationNamedWithSound
/// @sn assignAnimationNamed:%s to:%s from:%s withSound:%s
///
/// @class Animation
/// @overload AssignAnimation AssignAnimationNamedWithSound
/// @csn assignAnimationNamed:%s from:%s withSound:%s
///
/// @doc_details
procedure AssignAnimation(anim: Animation; const name: String; script: AnimationScript; withSound: Boolean); overload;
/// Assign a new starting animation to the passed in animation from the `AnimationScript`.
/// This may play a sound if the first frame of the animation is linked to a sound effect.
///
/// @lib AssignAnimation
/// @sn assignAnimation:%s to:%s from:%s
///
/// @class Animation
/// @method AssignAnimation
/// @csn assignAnimation:%s from:%s
///
/// @doc_details
procedure AssignAnimation(anim: Animation; idx: Longint; script: AnimationScript); overload;
/// Assign a new starting animation to the passed in animation from the `AnimationScript`.
/// This may play a sound if the first frame of the animation is linked to a sound effect, and
/// ``withSound`` is ``true``.
///
/// @lib AssignAnimationWithSound
/// @sn assignAnimation:%s to:%s from:%s withSound:%s
///
/// @class Animation
/// @overload AssignAnimation AssignAnimationWithSound
/// @csn assignAnimation:%s from:%s withSound:%s
///
/// @doc_details
procedure AssignAnimation(anim: Animation; idx: Longint; script: AnimationScript; withSound: Boolean); overload;
//----------------------------------------------------------------------------
// Drawing Animations
//----------------------------------------------------------------------------
/// Uses the `Animation` information to draw a `Bitmap` at the specified
/// ``x``,``y`` location.
///
/// @lib
/// @sn drawAnimation:%s bitmap:%s x:%s y:%s
///
/// @class Animation
/// @method DrawBitmap
/// @csn drawBitmap:%s x:%s y:%s
procedure DrawAnimation(ani: Animation; bmp: Bitmap; x, y: Single); overload;
/// Uses the animation information to draw a bitmap at the specified
/// x,y location given the passed in options.
///
/// @lib DrawAnimationWithOptions
/// @sn drawAnimation:%s bitmap:%s atX:%s y:%s opts:%s
///
/// @class Animation
/// @overload DrawBitmap DrawBitmapWithOptions
/// @csn drawBitmap:%s atX:%s y:%s opts:%s
///
/// @doc_details
procedure DrawAnimation(ani: Animation; bmp: Bitmap; x, y: Single; const opts : DrawingOptions); overload;
/// Uses the animation information to draw a bitmap at the specified
/// point.
///
/// @lib DrawAnimationAtPoint
/// @sn drawAnimation:%s bitmap:%s pt:%s
///
/// @class Animation
/// @overload DrawBitmap DrawBitmapAtPt
/// @csn drawBitmap:%s pt:%s
///
/// @doc_details
procedure DrawAnimation(ani: Animation; bmp: Bitmap; const pt: Point2D); overload;
/// Uses the animation information to draw a bitmap at the specified
/// point given the passed in options.
///
/// @lib DrawAnimationAtPointWithOptions
/// @sn drawAnimation:%s bitmap:%s pt:%s opts:%s
///
/// @class Animation
/// @overload DrawBitmap DrawBitmapPtWithOptions
/// @csn drawBitmap:%s at:%s opts:%s
///
/// @doc_details
procedure DrawAnimation(ani: Animation; bmp: Bitmap; const pt: Point2D; const opts : DrawingOptions); overload;
//----------------------------------------------------------------------------
// Updating Animations
//----------------------------------------------------------------------------
/// Updates the animation, updating the time spent and possibly moving to a new
/// frame in the animation. This may play a sound effect if the new frame
/// triggers a sound.
///
/// @lib
/// @sn updateAnimation:%s
///
/// @class Animation
/// @method Update
/// @csn update
procedure UpdateAnimation(anim: Animation); overload;
/// Updates the animation a certain percentage and possibly moving to a new
/// frame in the animation. This may play a sound effect if the new frame
/// triggers a sound.
///
/// @lib UpdateAnimationPct
/// @sn updateAnimation:%s pct:%s
///
/// @class Animation
/// @overload Update UpdatePct
/// @csn updatePct:%s
///
/// @doc_details
procedure UpdateAnimation(anim: Animation; pct: Single); overload;
/// Updates the animation a certain percentage and possibly moving to a new
/// frame in the animation. This may play a sound effect if the new frame
/// triggers a sound and withSound is true.
///
/// @lib UpdateAnimationPctAndSound
/// @sn updateAnimation:%s pct:%s withSound:%s
///
/// @class Animation
/// @overload Update UpdatePctAndSound
/// @csn updatePct:%s withSound:%s
///
/// @doc_details
procedure UpdateAnimation(anim: Animation; pct: Single; withSound: Boolean); overload;
/// Restarts the animation. This may play a sound effect if the first frame
/// triggers a sound.
///
/// @lib RestartAnimation
///
/// @class Animation
/// @method Restart
procedure RestartAnimation(anim: Animation); overload;
/// Restarts the animation. This may play a sound effect if the first frame
/// triggers a sound and withSound is true.
///
/// @lib ResetAnimationWithSound
/// @sn resetAnimation:%s withSound:%s
///
/// @class Animation
/// @overload Reset ResetWithSound
/// @csn resetWithSound:%s
///
/// @doc_details
procedure RestartAnimation(anim: Animation; withSound: Boolean); overload;
//----------------------------------------------------------------------------
// Query Animation
//----------------------------------------------------------------------------
/// Indicates if an animation has ended. Animations with loops will never end.
///
/// @lib
///
/// @class Animation
/// @getter Ended
function AnimationEnded(anim: Animation): Boolean;
/// Returns the current cell (the part of the image or sprite) of this animation.
/// This can be used to animate an image or sprite.
///
/// @lib
///
/// @class Animation
/// @getter CurrentCell
///
/// @doc_details
function AnimationCurrentCell(anim: Animation): Longint;
/// Returns true if the animation entered a new frame on its last update.
/// This can be used to trigger actions on frames within an animation.
///
/// @lib
///
/// @class Animation
/// @getter EnteredFrame
///
/// @doc_details
function AnimationEnteredFrame(anim: Animation): Boolean;
/// Returns the amount of time spent in the current frame. When this exceeds
/// the frames duration the animation moves to the next frame.
///
/// @lib
///
/// @class Animation
/// @getter FrameTime
///
/// @doc_details
function AnimationFrameTime(anim: Animation): Single;
/// Returns the vector assigned to the current frame in the animation.
///
/// @lib
///
/// @class Animation
/// @getter Vector
///
/// @doc_details
function AnimationCurrentVector(anim: Animation): Vector;
//=============================================================================
implementation
uses
SysUtils, StrUtils, Classes,
stringhash, sgSharedUtils, sgNamedIndexCollection,
sgShared, sgResources, sgTrace, sgAudio, sgImages, sgGeometry, sgDrawingOptions, sgBackendTypes;
//=============================================================================
var
_Animations: TStringHash;
function DoLoadAnimationScript(const name, filename: String) : AnimationScript;
type
RowData = record
id,cell,dur,next: Longint;
snd: SoundEffect;
mvmt: Vector;
end;
IdData = record
name: String;
startId: Longint;
end;
var
a: AnimationScriptPtr;
rows: Array of RowData;
ids: Array of IdData;
input: Text; //the bundle file
line, id, data, path: String;
lineNo, maxId: Longint;
procedure AddRow(myRow: RowData);
var
j: Longint;
begin
// Check if beyond current range
if myRow.id > maxId then
begin
SetLength(rows, myRow.id + 1);
// Mark new rows as "empty"
for j := maxId + 1 to High(rows) do
begin
rows[j].id := -1;
rows[j].snd := nil;
rows[j].cell := -1;
rows[j].next := -1;
rows[j].mvmt := VectorTo(0,0);
end;
maxId := myRow.id;
end;
if rows[myRow.id].id <> -1 then
begin
RaiseException('Error at line ' + IntToStr(lineNo) + ' in animation ' + filename + '. A frame with id ' + IntToStr(myRow.id) + ' already exists.');
exit;
end
else
begin
// Success add the row.
rows[myRow.id] := myRow;
end;
end;
procedure AddID(myId: IdData);
var
j: Longint;
begin
// Check if name is already in ids
for j := 0 to High(ids) do
begin
if ids[j].name = myId.name then
begin
RaiseException('Error at line ' + IntToStr(lineNo) + ' in animation ' + filename + '. The id ' + myId.name + ' already exists.');
exit;
end;
end;
SetLength(ids, Length(ids) + 1);
ids[High(ids)] := myId;
end;
procedure ProcessFrame();
var
myRow: RowData;
begin
if CountDelimiter(data, ',') <> 3 then
begin
RaiseException('Error at line ' + IntToStr(lineNo) + ' in animation ' + filename + '. A frame must have 4 values separated as id,cell,dur,next');
exit;
end;
myRow.id := MyStrToInt(ExtractDelimited(1,data,[',']), false);
myRow.cell := MyStrToInt(ExtractDelimited(2,data,[',']), false);
myRow.dur := MyStrToInt(ExtractDelimited(3,data,[',']), false);
myRow.next := MyStrToInt(ExtractDelimited(4,data,[',']), true);
myRow.snd := nil;
myRow.mvmt := VectorTo(0,0);
AddRow(myRow);
end;
procedure ProcessMultiFrame();
var
id_range, cell_range: Array of Longint;
dur, next, j: Longint;
myRow: RowData;
begin
if CountDelimiterWithRanges(data, ',') <> 3 then
begin
RaiseException('Error at line ' + IntToStr(lineNo) + ' in animation ' + filename + '. A multi-frame must have 4 values separated as id-range,cell-range,dur,next');
exit;
end;
id_range := ProcessRange(ExtractDelimitedWithRanges(1, data));
cell_range := ProcessRange(ExtractDelimitedWithRanges(2, data));
if Length(id_range) <> Length(cell_range) then
begin
RaiseException('Error at line ' + IntToStr(lineNo) + ' in animation ' + filename + '. The range of cells and ids is not the same length.');
exit;
end;
dur := MyStrToInt(ExtractDelimitedWithRanges(3,data), false);
next := MyStrToInt(ExtractDelimitedWithRanges(4,data), true);
for j := Low(id_range) to High(id_range) do
begin
myRow.id := id_range[j];
myRow.cell := cell_range[j];
myRow.dur := dur;
myRow.snd := nil;
myRow.mvmt := VectorTo(0,0);
if j <> High(id_range) then
myRow.next := id_range[j + 1]
else
myRow.next := next;
AddRow(myRow);
end;
end;
procedure ProcessId();
var
myIdData: IdData;
begin
if CountDelimiterWithRanges(data, ',') <> 1 then
begin
RaiseException('Error at line ' + IntToStr(lineNo) + ' in animation ' + filename + '. A id must have 2 values separated as name,start-id');
exit;
end;
myIdData.name := ExtractDelimited(1,data,[',']);
myIdData.startId := MyStrToInt(ExtractDelimited(2,data,[',']), false);
AddID(myIdData);
end;
procedure ProcessSound();
var
id: Longint;
sndId, sndFile: String;
begin
if CountDelimiter(data, ',') <> 2 then
begin
RaiseWarning('Error at line ' + IntToStr(lineNo) + ' in animation ' + filename + '. A sound must have three parts frame #,sound name,sound file.');
exit;
end;
id := MyStrToInt(ExtractDelimited(1,data,[',']), true);
sndId := ExtractDelimited(2,data,[',']);
sndFile := ExtractDelimited(3,data,[',']);
if not HasSoundEffect(sndId) then
begin
if LoadSoundEffectNamed(sndId, sndFile) = nil then
begin
RaiseWarning('At line ' + IntToStr(lineNo) + ' in animation ' + filename + ': Cannot find ' + sndId + ' sound file ' + sndFile);
exit;
end;
end;
if WithinRange(Length(rows), id) then
rows[id].snd := SoundEffectNamed(sndId)
else
RaiseWarning('At line ' + IntToStr(lineNo) + ' in animation ' + filename + ': No frame with id ' + IntToStr(id) + ' for sound file ' + sndFile)
end;
procedure ProcessVector();
var
id_range: Array of Longint;
id, i: Longint;
xVal, yVal: String;
x, y: Single;
v: Vector;
begin
if CountDelimiter(data, ',') <> 2 then
begin
RaiseWarning('Error at line ' + IntToStr(lineNo) + ' in animation ' + filename + '. A vector must have three parts frame #s, x value, y value.');
exit;
end;
id_range := ProcessRange(ExtractDelimitedWithRanges(1, data));
xVal := ExtractDelimitedWithRanges(2,data);
yVal := ExtractDelimitedWithRanges(3,data);
if not TryStrToFloat(xVal, x) then
begin
RaiseWarning('Error at line ' + IntToStr(lineNo) + ' in animation ' + filename + '. X value must be a number.');
exit;
end;
if not TryStrToFloat(yVal, y) then
begin
RaiseWarning('Error at line ' + IntToStr(lineNo) + ' in animation ' + filename + '. Y value must be a number.');
exit;
end;
v := VectorTo(x, y);
// WriteLn('Vector ', PointToString(v) );
//
for i := Low(id_range) to High(id_range) do
begin
id := id_range[i];
if WithinRange(Length(rows), id) then
begin
rows[id].mvmt := v;
end;
end;
end;
procedure ProcessLine();
begin
// Split line into id and data
id := ExtractDelimited(1, line, [':']);
data := ExtractDelimited(2, line, [':']);
// Verify that id is a single char
if Length(id) <> 1 then
begin
RaiseWarning('Error at line ' + IntToStr(lineNo) + ' in animation ' + filename + '. Error with frame #: ' + id + '. This should be a single character.');
exit;
end;
// Process based on id
case LowerCase(id)[1] of // in all cases the data variable is read
'f': ProcessMultiFrame(); //test... or ProcessFrame();
'm': ProcessMultiFrame();
'i': ProcessId();
's': ProcessSound();
'v': ProcessVector();
else
begin
RaiseWarning('Error at line ' + IntToStr(lineNo) + ' in animation ' + filename + '. Error with id: ' + id + '. This should be one of f,m,i, s, or v.');
exit;
end;
end;
end;
procedure BuildFrameLists();
var
frames: Array of AnimationFrame;
j, nextIdx, addedIdx: Longint;
begin
SetLength(frames, Length(rows));
for j := 0 to High(frames) do
begin
// Allocte space for frames
New(frames[j]);
end;
// Link the frames together
for j := 0 to High(frames) do
begin
frames[j]^.index := j;
frames[j]^.cellIndex := rows[j].cell;
frames[j]^.sound := rows[j].snd;
frames[j]^.duration := rows[j].dur;
frames[j]^.movement := rows[j].mvmt;
//WriteLn(j, PointToString(frames[j]^.movement));
//WriteLn('Frame ', HexStr(frames[j]), ' Vector ', PointToString(frames[j]^.movement));
// Get the next id and then
nextIdx := rows[j].next;
if nextIdx = -1 then
begin
//The end of a list of frames = no next
frames[j]^.next := nil;
end
else if (nextIdx < 0) or (nextIdx > High(frames)) then
begin
FreeAnimationScript(result);
result := nil;
RaiseWarning('Error in animation ' + filename + '. Error with frame: ' + IntToStr(j) + '. Next is outside of available frames.');
exit;
end
else
frames[j]^.next := frames[nextIdx];
//WriteLn(j, ' = ', frames[j]^.cellIndex, ' -> ', nextIdx);
end;
//We have the data ready, now lets create the linked lists...
New(a);
a^.id := ANIMATION_SCRIPT_PTR;
a^.name := name; // name taken from parameter of DoLoadAnimationScript
a^.filename := filename; // filename also taken from parameter
a^.frames := frames; // The frames of this animation.
SetLength(a^.animations, Length(ids));
SetLength(a^.animObjs, 0);
a^.nextAnimIdx := 0;
InitNamedIndexCollection(a^.animationIds); //Setup the name <-> id mappings
for j := 0 to High(ids) do //Add in the animation starting indexes
begin
addedIdx := AddName(a^.animationIds, ids[j].name); //Allocate the index
a^.animations[addedIdx] := ids[j].startId; //Store the linked index
//WriteLn('load ids: ', addedIdx, ' - startid ', ids[j].startId)
end;
result := a;
end;
procedure MakeFalse(var visited: Array of Boolean);
var
i: Longint;
begin
for i := 0 to High(visited) do
begin
visited[i] := false;
end;
end;
function SumLoop(start: AnimationFrame): Single;
var
current: AnimationFrame;
begin
result := start^.duration;
current := start^.next;
while (current <> start) and (assigned(current)) do
begin
result := result + current^.duration;
current := current^.next;
end;
end;
// Animations with loops must have a duration > 0 for at least one frame
procedure CheckAnimationLoops();
var
i: Longint;
done: Boolean;
visited: Array of Boolean;
current: AnimationFrame;
begin
done := true;
// check for all positive
for i := 0 to High(a^.frames) do
begin
if a^.frames[i]^.duration = 0 then
begin
done := false;
break;
end;
end;
if done then exit;
SetLength(visited, Length(a^.frames));
// Check through each animation for a loop
for i := 0 to High(a^.animations) do
begin
MakeFalse(visited);
current := a^.frames[a^.animations[i]];
// Check for a loop
while current <> nil do
begin
if visited[current^.index] then
begin
if SumLoop(current) = 0 then
begin
FreeAnimationScript(result);
RaiseException('Error in animation ' + filename + '. Animation contains a loop with duration 0 starting at cell ' + IntToStr(current^.index));
exit;
end;
break;
end
else
current := current^.next;
end;
end;
end;
function VerifyVersion(): Boolean;
begin
result := false;
if EOF(input) then exit;
line := '';
while (Length(line) = 0) or (MidStr(line,1,2) = '//') do
begin
ReadLn(input, line);
line := Trim(line);
end;
//Verify that the line has the right version
if line <> 'SwinGame Animation #v1' then
begin
RaiseWarning('Error in animation ' + filename + '. Animation files must start with "SwinGame Animation #v1"');
exit;
end;
result := true;
end;
begin
{$IFDEF TRACE}
TraceEnter('sgAnimations', 'LoadAnimationScript');
{$ENDIF}
path := FilenameToResource(name, AnimationResource);
if not FileExists(path) then
begin
RaiseWarning('Unable to locate ' + name + ' animation file at ' + filename);
result := nil;
exit;
end;
lineNo := 0;
maxId := -1;
SetLength(rows, 0);
result := nil;
Assign(input, path);
Reset(input);
try
if not VerifyVersion() then
begin
RaiseWarning('Error loading animation script: ' + path);
exit
end;
while not EOF(input) do
begin
lineNo := lineNo + 1;
ReadLn(input, line);
line := Trim(line);
if Length(line) = 0 then continue; //skip empty lines
if MidStr(line,1,2) = '//' then continue; //skip lines starting with //
ProcessLine();
end;
BuildFrameLists();
CheckAnimationLoops();
finally
Close(input);
end;
{$IFDEF TRACE}
TraceExit('sgAnimations', 'LoadAnimationScript');
{$ENDIF}
end;
function LoadAnimationScript(const filename: String) : AnimationScript;
begin
result := LoadAnimationScriptNamed(filename, filename);
end;
function AnimationScriptName(script: AnimationScript): String;
var
a: AnimationScriptPtr;
begin
result := '';
a := ToAnimationScriptPtr(script);
if Assigned(a) then result := a^.name;
end;
procedure FreeAnimationScript(var scriptToFree: AnimationScript);
var
a: AnimationScriptPtr;
begin
a := ToAnimationScriptPtr(scriptToFree);
if Assigned(a) then
ReleaseAnimationScript(a^.name);
scriptToFree := nil;
end;
function LoadAnimationScriptNamed(const name, filename: String): AnimationScript;
var
obj: tResourceContainer;
frm: AnimationScript;
begin
{$IFDEF TRACE}
TraceEnter('sgAnimations', 'MapAnimationFrame', name + ' = ' + filename);
{$ENDIF}
// WriteLn('Loading Animation Script ', name, ' for ', filename);
if _Animations.containsKey(name) then
begin
// WriteLn(' Using existing... ', name, ' for ', filename);
result := AnimationScriptNamed(name);
exit;
end;
frm := DoLoadAnimationScript(filename, name);
if not assigned(frm) then
begin
result := nil;
exit;
end;
obj := tResourceContainer.Create(frm);
if not _Animations.setValue(name, obj) then
begin
RaiseException('** Leaking: Caused by loading AnimationScript resource twice, ' + name);
result := nil;
exit;
end;
result := frm;
{$IFDEF TRACE}
TraceExit('sgAnimations', 'MapAnimationFrame', HexStr(result));
{$ENDIF}
end;
function HasAnimationScript(const name: String): Boolean;
begin
{$IFDEF TRACE}
TraceEnter('sgAnimations', 'HasAnimationScript', name);
{$ENDIF}
result := _Animations.containsKey(name);
{$IFDEF TRACE}
TraceExit('sgAnimations', 'HasAnimationScript', BoolToStr(result, true));
{$ENDIF}
end;
function AnimationScriptNamed(const name: String): AnimationScript;
var
tmp : TObject;
begin
{$IFDEF TRACE}
TraceEnter('sgAnimations', 'AnimationScriptNamed', name);
{$ENDIF}
tmp := _Animations.values[name];
if assigned(tmp) then result := AnimationScript(tResourceContainer(tmp).Resource)
else
begin
result := nil;
RaiseWarning('Unable to locate AnimationScript named ' + name);
end;
{$IFDEF TRACE}
TraceExit('sgAnimations', 'AnimationScriptNamed', HexStr(result));
{$ENDIF}
end;
procedure DoFreeAnimationScript(var frm: AnimationScript);
var
i: Longint;
a: AnimationScriptPtr;
begin
a := ToAnimationScriptPtr(frm);
if not assigned(a) then exit;
FreeNamedIndexCollection(a^.animationIds);
// WriteLn(a^.nextAnimIdx);
// Must use downto as animations are removed from the array in FreeAnimation!
for i := a^.nextAnimIdx - 1 downto 0 do
begin
FreeAnimation(a^.animObjs[i]);
end;
for i := 0 to High(a^.frames) do
begin
Dispose(a^.frames[i]);
a^.frames[i] := nil;
end;
a^.id := NONE_PTR;
Dispose(a);
frm := nil;
end;
procedure ReleaseAnimationScript(const name: String);
var
frm: AnimationScript;
begin
{$IFDEF TRACE}
TraceEnter('sgAnimations', 'ReleaseAnimationScript', 'frm = ' + name);
{$ENDIF}
frm := AnimationScriptNamed(name);
if (assigned(frm)) then
begin
_Animations.remove(name).Free();
DoFreeAnimationScript(frm);
end;
{$IFDEF TRACE}
TraceExit('sgAnimations', 'ReleaseAnimationScript');
{$ENDIF}
end;
procedure ReleaseAllAnimationScripts();
begin
{$IFDEF TRACE}
TraceEnter('sgAnimations', 'ReleaseAllAnimationScripts', '');
{$ENDIF}
ReleaseAll(_Animations, @ReleaseAnimationScript);
{$IFDEF TRACE}
TraceExit('sgAnimations', 'ReleaseAllAnimationScripts');
{$ENDIF}
end;
function AnimationCount(script: animationScript): Longint;
var
a: AnimationScriptPtr;
begin
a := ToAnimationScriptPtr(script);
if Assigned(a) then
result := Length(a^.animations)
else
result := 0;
end;
function _AnimationEnded(anim: AnimationPtr): Boolean;
begin
if not Assigned(anim) then
result := true
else
result := not Assigned(anim^.currentFrame);
end;
function StartFrame(id: Longint; temp: AnimationScript) : AnimationFrame;
var
a: AnimationScriptPtr;
begin
a := ToAnimationScriptPtr(temp);
result := nil;
if a = nil then exit;
if (id < 0) or (id > High(a^.animations)) then exit;
result := a^.frames[id];
end;
//----------------------------------------------------------------------------
function StartFrame(const name: String; temp: AnimationScript) : AnimationFrame;
var
a: AnimationScriptPtr;
begin
a := ToAnimationScriptPtr(temp);
if Assigned(a) then
result := StartFrame(IndexOf(a^.animationIds, name), temp)
else
result := nil;
end;
procedure _AddAnimation(script: AnimationScriptPtr; ani: AnimationPtr);
begin
if Length(script^.animObjs) <= script^.nextAnimIdx then
SetLength(script^.animObjs, script^.nextAnimIdx + 1);
script^.animObjs[script^.nextAnimIdx] := ani;
ani^.script := script;
script^.nextAnimIdx += 1;
end;
procedure _RemoveAnimation(script: AnimationScriptPtr; ani: AnimationPtr);
var
i: Integer;
begin
for i := Low(script^.animObjs) to script^.nextAnimIdx - 1 do
begin
if script^.animObjs[i] = ani then
begin
script^.nextAnimIdx -= 1; // Move back one (will point to high first time...)
script^.animObjs[i] := script^.animObjs[script^.nextAnimIdx]; // Copy back old last place
script^.animObjs[script^.nextAnimIdx] := nil; // Just to make sure...
exit;
end;
end;
RaiseWarning('Could not remove animation! ' + HexStr(ani) + AnimationScriptName(script));
end;
procedure FreeAnimation(var ani: Animation);
var
toFree: AnimationPtr;
a: AnimationPtr;
begin
a := ToAnimationPtr(ani);
// WriteLn('Freeing Anim ', HexStr(ani));
if assigned(a) then
begin
toFree := a;
_RemoveAnimation(a^.script, a);
toFree^.id := NONE_PTR;
// WriteLn('Now Disposing Anim ', HexStr(ani), '=', HexStr(toFree));
Dispose(toFree); //ani may have been overridden by last call...
ani := nil;
end;
end;
procedure _AssignAnimation(anim: AnimationPtr; idx: Longint; script: AnimationScriptPtr; withSound: Boolean); forward;
function _CreateAnimation(identifier: Longint; script: AnimationScriptPtr; withSound: Boolean): Animation; overload;
var
aptr: AnimationPtr;
begin
result := nil;
if script = nil then exit;
if (identifier < 0) or (identifier > High(script^.animations)) then
begin
RaiseWarning('Unable to create animation number ' + IntToStr(identifier) + ' from script ' + script^.name);
exit;
end;
new(aptr);
aptr^.id := ANIMATION_PTR;
_AddAnimation(script, aptr);
result := aptr;
_AssignAnimation(aptr, identifier, script, withSound);
// WriteLn('Created ', HexStr(result));
end;
function _CreateAnimation(const identifier: String; script: AnimationScriptPtr; withSound: Boolean): Animation; overload;
var
idx: Integer;
begin
result := nil;
if script = nil then exit;
idx := IndexOf(script^.animationIds, identifier);
if (idx < 0) or (idx > High(script^.animations)) then
begin
RaiseWarning('Unable to create animation "' + identifier + '" from script ' + script^.name);
exit;
end;
result := _CreateAnimation(idx, script, withSound);
end;
function CreateAnimation(identifier: Longint; script: AnimationScript; withSound: Boolean): Animation; overload;
begin
result := _CreateAnimation(identifier, ToAnimationScriptPtr(script), withSound);
end;
function CreateAnimation(identifier: Longint; script: AnimationScript): Animation; overload;
begin
result := CreateAnimation(identifier, script, True);
end;
function CreateAnimation(const identifier: String; script: AnimationScript; withSound: Boolean): Animation; overload;
begin
result := _CreateAnimation(identifier, ToAnimationScriptPtr(script), withSound);
end;
function CreateAnimation(const identifier: String; script: AnimationScript): Animation; overload;
begin
result := CreateAnimation(identifier, script, True);
end;
procedure AssignAnimation(anim: Animation; const name: String; script: AnimationScript); overload;
begin
AssignAnimation(anim, name, script, true);
end;
procedure AssignAnimation(anim: Animation; const name: String; script: AnimationScript; withSound: Boolean); overload;
begin
AssignAnimation(anim, AnimationIndex(script, name), script, withSound);
end;
procedure AssignAnimation(anim: Animation; idx: Longint; script: AnimationScript); overload;
begin
AssignAnimation(anim, idx, script, true);
end;
procedure AssignAnimation(anim: Animation; idx: Longint; script: AnimationScript; withSound: Boolean); overload;
begin
_AssignAnimation(ToAnimationPtr(anim), idx, ToAnimationScriptPtr(script), withSound);
end;
procedure _AssignAnimation(anim: AnimationPtr; idx: Longint; script: AnimationScriptPtr; withSound: Boolean);
begin
if (not assigned(anim)) or (not assigned(script)) then exit;
if (idx < 0) or (idx > High(script^.animations)) then
begin
RaiseWarning('Assigning an animation frame that is not within range 0-' + IntToStr(High(script^.animations)) + '.');
exit;
end;
// Animation is being assigned to another script
if anim^.script <> script then
begin
_RemoveAnimation(anim^.script, anim); // remove from old script
_AddAnimation(script, anim); // add to new script
end;
anim^.firstFrame := script^.frames[script^.animations[idx]];
anim^.animationName := AnimationName(script, idx);
RestartAnimation(anim, withSound);
end;
procedure _UpdateAnimation(anim: AnimationPtr; pct: Single; withSound: Boolean); overload;
begin
{$IFDEF TRACE}
TraceEnter('sgAnimations', 'UpdateAnimation', '');
try
{$ENDIF}
if _AnimationEnded(anim) then exit;
anim^.frameTime := anim^.frameTime + pct;
anim^.enteredFrame := false;
if anim^.frameTime >= anim^.currentFrame^.duration then
begin
anim^.frameTime := anim^.frameTime - anim^.currentFrame^.duration; //reduce the time
anim^.lastFrame := anim^.currentFrame; //store last frame
anim^.currentFrame := anim^.currentFrame^.next; //get the next frame
//if assigned(anim^.currentFrame) then
//WriteLn('Frame ', HexStr(anim^.currentFrame), ' Vector ', PointToString(anim^.currentFrame^.movement));
if assigned(anim^.currentFrame) and assigned(anim^.currentFrame^.sound) and withSound then
begin
PlaySoundEffect(anim^.currentFrame^.sound);
end;
end;
{$IFDEF TRACE}
finally
TraceExit('sgAnimations', 'UpdateAnimation', '');
end;
{$ENDIF}
end;
procedure UpdateAnimation(anim: Animation; pct: Single; withSound: Boolean); overload;
begin
_UpdateAnimation(ToAnimationPtr(anim), pct, withSound);
end;
procedure UpdateAnimation(anim: Animation; pct: Single); overload;
begin
UpdateAnimation(anim, pct, True);
end;
procedure UpdateAnimation(anim: Animation); overload;
begin
UpdateAnimation(anim, 1, True);
end;
function AnimationEnded(anim: Animation): Boolean;
begin
result := _AnimationEnded(ToAnimationPtr(anim));
end;
procedure _RestartAnimation(anim: AnimationPtr; withSound: Boolean); overload;
begin
if not assigned(anim) then exit;
anim^.currentFrame := anim^.firstFrame;
anim^.lastFrame := anim^.firstFrame;
anim^.frameTime := 0;
anim^.enteredFrame := true;
if assigned(anim^.currentFrame) and assigned(anim^.currentFrame^.sound) and withSound then
PlaySoundEffect(anim^.currentFrame^.sound);
end;
procedure RestartAnimation(anim: Animation); overload;
begin
RestartAnimation(ToAnimationPtr(anim), true);
end;
procedure RestartAnimation(anim: Animation; withSound: Boolean); overload;
begin
_RestartAnimation(ToAnimationPtr(anim), withSound);
end;
function _AnimationCurrentCell(anim: AnimationPtr): Longint;
begin
if not assigned(anim) then
result := 0 //no animation - return the first frame
else if not _AnimationEnded(anim) then
result := anim^.currentFrame^.cellIndex
else if not assigned(anim^.lastFrame) then
result := -1
else //Use the last frame drawn.
result := anim^.lastFrame^.cellIndex;
end;
function AnimationCurrentCell(anim: Animation): Longint;
begin
result := _AnimationCurrentCell(ToAnimationPtr(anim));
end;
function _AnimationCurrentVector(anim: AnimationPtr): Vector;
begin
if not assigned(anim) then
result := VectorTo(0,0)
else if not AnimationEnded(anim) then
begin
result := anim^.currentFrame^.movement;
// WriteLn(PointToString(result));
end
else
result := VectorTo(0,0)
end;
function AnimationCurrentVector(anim: Animation): Vector;
begin
result := _AnimationCurrentVector(ToAnimationPtr(anim));
end;
function _AnimationEnteredFrame(anim: AnimationPtr): Boolean;
begin
if not Assigned(anim) then
result := false
else
result := anim^.enteredFrame;
end;
function AnimationEnteredFrame(anim: Animation): Boolean;
begin
result := _AnimationEnteredFrame(ToAnimationPtr(anim));
end;
function AnimationFrameTime(anim: Animation): Single;
var
a: AnimationPtr;
begin
a := ToAnimationPtr(anim);
if not Assigned(a) then
result := -1
else
result := a^.frameTime;
end;
procedure DrawAnimation(ani: Animation; bmp: Bitmap; x, y: Single; const opts: DrawingOptions); overload;
begin
{$IFDEF TRACE}
TraceEnter('sgAnimations', 'DrawAnimation', AnimationName(ani));
try
{$ENDIF}
DrawCell(bmp, AnimationCurrentCell(ani), x, y, opts);
{$IFDEF TRACE}
finally
TraceExit('sgAnimations', 'DrawAnimation', AnimationName(ani));
end;
{$ENDIF}
end;
procedure DrawAnimation(ani: Animation; bmp: Bitmap; const pt: Point2D; const opts: DrawingOptions); overload;
begin
DrawAnimation(ani, bmp, pt.x, pt.y, OptionDefaults());
end;
procedure DrawAnimation(ani: Animation; bmp: Bitmap; x, y: Single); overload;
begin
DrawAnimation(ani, bmp, x, y, OptionDefaults());
end;
procedure DrawAnimation(ani: Animation; bmp: Bitmap; const pt: Point2D); overload;
begin
DrawAnimation(ani, bmp, pt.x, pt.y, OptionDefaults());
end;
function AnimationIndex(temp: AnimationScript; const name: String): Longint;
var
a: AnimationScriptPtr;
begin
a := ToAnimationScriptPtr(temp);
if not assigned(a) then result := -1
else result := IndexOf(a^.animationIds, name);
end;
function AnimationName(temp: AnimationScript; idx: Longint): String;
var
a: AnimationScriptPtr;
begin
a := ToAnimationScriptPtr(temp);
if not assigned(a) then result := ''
else result := NameAt(a^.animationIds, idx);
end;
function AnimationName(temp: Animation): String;
var
a: AnimationPtr;
begin
a := ToAnimationPtr(temp);
if not assigned(a) then result := ''
else result := a^.animationName;
end;
//=============================================================================
initialization
begin
{$IFDEF TRACE}
TraceEnter('sgAnimations', 'Initialise', '');
{$ENDIF}
InitialiseSwinGame();
_Animations := TStringHash.Create(False, 1024);
{$IFDEF TRACE}
TraceExit('sgAnimations', 'Initialise');
{$ENDIF}
end;
finalization
begin
ReleaseAllAnimationScripts();
FreeAndNil(_Animations);
end;
//=============================================================================
end.
|
unit uDmPesquisa;
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.Phys.IB,
FireDAC.Phys.IBDef, FireDAC.VCLUI.Wait, FireDAC.Stan.Param, FireDAC.DatS,
FireDAC.DApt.Intf, FireDAC.DApt, FireDAC.Phys.IBBase, Data.DB,
FireDAC.Comp.DataSet, FireDAC.Comp.Client;
type
TdmPesquisa = class(TDataModule)
con: TFDConnection;
qry: TFDQuery;
FDPhysIBDriverLink1: TFDPhysIBDriverLink;
private
{ Private declarations }
public
class function ObterNomePeloId(const AID: Integer): String;
end;
implementation
{%CLASSGROUP 'Vcl.Controls.TControl'}
{$R *.dfm}
{ TdmPesquisa }
class function TdmPesquisa.ObterNomePeloId(const AID: Integer): String;
begin
var LDM: TdmPesquisa := TdmPesquisa.Create(nil);
try
LDM.qry.ParamByName('CUST_NO').AsInteger := AID;
LDM.qry.Open;
if LDM.qry.IsEmpty then
raise Exception.Create('Not found');
result := LDM.qry.FieldByName('CUSTOMER').AsString;
finally
LDM.Free;
end;
end;
end.
|
{*******************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ XML RTL Constants }
{ }
{ Copyright (c) 2002 Borland Software Corporation }
{ }
{ Русификация: 2002 Polaris Software }
{ http://polesoft.da.ru }
{*******************************************************}
unit XMLConst;
interface
resourcestring
{ xmldom.pas }
SDuplicateRegistration = '"%s" DOMImplementation уже зарегистрирован';
SNoMatchingDOMVendor = 'Нет подходящего DOM Vendor: "%s"';
SNoDOMNodeEx = 'Выбранный DOM Vendor не поддерживает это свойство или метод';
SDOMNotSupported = 'Свойство или метод "%s" не поддерживается DOM Vendor "%s"';
{ msxmldom.pas }
SNodeExpected = 'Узел не может быть пустым (null)';
SMSDOMNotInstalled = 'Microsoft MSXML не установлен';
{ oxmldom.pas }
{$IFDEF MSWINDOWS}
SErrorDownloadingURL = 'Ошибка загрузки URL: %s';
SUrlMonDllMissing = 'Не могу загрузить %s';
{$ENDIF}
SNotImplemented = 'Это свойство или метод не реализован в Open XML Parser';
{ xercesxmldom.pas }
SINDEX_SIZE_ERR = 'Неверное смещение в строке';
SDOMSTRING_SIZE_ERR = 'Неверный размер DOMString';
SHIERARCHY_REQUEST_ERR = 'Не могу вставить дочерний узел';
SWRONG_DOCUMENT_ERR = 'Узлом владеет другой документ';
SINVALID_CHARACTER_ERR = 'Неверный символ в имени';
SNO_DATA_ALLOWED_ERR = 'No data allowed'; // not used
SNO_MODIFICATION_ALLOWED_ERR = 'Изменения не допустимы (данные только для чтения)';
SNOT_FOUND_ERR = 'Узел не найден';
SNOT_SUPPORTED_ERR = 'Не поддерживается';
SINUSE_ATTRIBUTE_ERR = 'Атрибут уже связан с другим элементом';
SINVALID_STATE_ERR = 'Неверное состояние';
SSYNTAX_ERR = 'Неверный синтаксис';
SINVALID_MODIFICATION_ERR = 'Invalid modification'; // not used
SNAMESPACE_ERR = 'Неверный запрос namespace';
SINVALID_ACCESS_ERR = 'Invalid access'; // not used
SBadTransformArgs = 'TransformNode должен быть вызван, используя узел документа (не элемент документа) для источника и stylesheet.';
SErrorWritingFile = 'Ошибка создания файла "%s"';
SUnhandledXercesErr = 'Unhandled Xerces DOM ошибка (сообщение не доступно): %d';
SDOMError = 'Ошибка DOM: ';
{$IFDEF LINUX}
SErrorLoadingLib = 'Ошибка загрузки библиотеки "%s": "%s"';
{$ENDIF}
{ XMLDoc.pas }
SNotActive = 'Нет активного документа';
SNodeNotFound = 'Узел "%s" не найден';
SMissingNode = 'IDOMNode требуется';
SNoAttributes = 'Атрибуты не поддерживаются на этом типе узла';
SInvalidNodeType = 'Неверный тип узла';
SMismatchedRegItems = 'Несовпадающие параметры к RegisterChildNodes';
SNotSingleTextNode = 'Элемент не содержит единственный текстовый узел';
SNoDOMParseOptions = 'Реализация DOM не поддерживает IDOMParseOptions';
SNotOnHostedNode = 'Неверная операция на hosted узле';
SMissingItemTag = 'Свойство ItemTag не инициализировано';
SNodeReadOnly = 'Узел только для чтения';
SUnsupportedEncoding = 'Кодирование неподдерживаемого символа "%s", повторите с использованием LoadFromFile';
SNoRefresh = 'Refresh поддерживается только, если установлены свойства FileName или XML';
SMissingFileName = 'FileName не может быть пустым';
SLine = 'Line';
SUnknown = 'Неизвестно';
{ XMLSchema.pas }
SInvalidSchema = 'Неверный или неподдерживаемый документ XML Schema';
SNoLocalTypeName = 'Объявления локального типа не могут иметь имя. Элемент: %s';
SUnknownDataType = 'Неизвестный тип данных "%s"';
SInvalidValue = 'Неверное %s значение: "%s"';
SInvalidGroupDecl = 'Неверное group объявление в "%s"';
SMissingName = 'Потеряно имя типа';
SInvalidDerivation = 'Неверное решение комплексного типа: %s';
SNoNameOnRef = 'Имя не допускается на ref item';
SNoGlobalRef = 'Пункты глобальной схемы не могут содержать ref';
SNoRefPropSet = '%s не может быть установлено на ref item';
SSetGroupRefProp = 'Установить свойство GroupRef для cmGroupRef content model';
SNoContentModel = 'ContentModel не установлена';
SNoFacetsAllowed = 'Facets и Enumeration не допустимы на этом типе данных "%s"';
SNotBuiltInType = 'Неверное имя встроенного типа "%s"';
SBuiltInType = 'Встроенный тип';
{ XMLDataToSchema.pas }
SXMLDataTransDesc = 'Транслятор XMLData в XML Schema (.xml -> .xsd)';
{ XMLSchema99.pas }
S99TransDesc = 'Транслятор 1999 XML Schema (.xsd <-> .xsd)';
{ DTDSchema.pas }
SDTDTransDesc = 'Транслятор DTD в XML Schema (.dtd <-> .xsd)';
{ XDRSchema.pas }
SXDRTransDesc = 'Транслятор XDR в XML Schema (.xdr <-> .xsd)';
implementation
end.
|
unit Server.Controller;
interface
uses
System.Generics.Collections,
System.JSON,
Spring.Collections,
Common.Entities.Player,
Server.WIRL.Response,
Common.Entities.Card,
Common.Entities.Round,
Common.Entities.Bet,
Common.Entities.GameSituation,
Server.Entities.Game
;
type
IApiV1Controller = interface
['{43B8C3AB-4848-41EE-AAF9-30DE019D0059}']
function GetPlayers:TPlayers<TPlayer>;
function RegisterPlayer(const APlayer:TPlayers<TPlayer>):TBaseRESTResponse;
function DeletePlayer(const APlayerName:String):TBaseRESTResponse;
function GetGameSituation: TGameSituation<TPlayer>;
procedure NewGameInfo(const AMessage: String);
function GetAllCards:TCards;
function NewGame:TExtendedRESTResponse;
function GetPlayerCards(AGameID:String; APlayerName:String):TCards;
function GiveUp: TBaseRESTResponse;
function GetBets:TBets;
function NewBet(const AParam: TBet): TBaseRESTResponse;
function SetKing(ACard: TCardKey): TBaseRESTResponse;
function ChangeCards(ACards: TCards): TBaseRESTResponse;
function GetRound:TGameRound;
function NewRound: TBaseRESTResponse;
function Turn(AName:String; ACard:TCardKey): TBaseRESTResponse;
end;
TApiV1Controller = class(TInterfacedObject, IApiV1Controller)
public
function GetPlayers:TPlayers<TPlayer>;
function RegisterPlayer(const APlayer:TPlayers<TPlayer>):TBaseRESTResponse;
function DeletePlayer(const APlayerName:String):TBaseRESTResponse;
function GetAllCards:TCards;
function NewGame:TExtendedRESTResponse;
function GetGame:TGame;
function GetGameSituation: TGameSituation<TPlayer>;
procedure NewGameInfo(const AMessage: String);
function GiveUp: TBaseRESTResponse;
function GetPlayerCards(AGameID:String; APlayerName:String):TCards;
function GetBets:TBets;
function NewBet(const AParam: TBet): TBaseRESTResponse;
function SetKing(ACard: TCardKey): TBaseRESTResponse;
function ChangeCards(ACards: TCards): TBaseRESTResponse;
function GetRound:TGameRound;
function NewRound: TBaseRESTResponse;
function Turn(AName:String; ACard:TCardKey): TBaseRESTResponse;
end;
implementation
uses
System.SysUtils
, Server.Repository
, Server.Register
;
{ TApiV1Controller }
function TApiV1Controller.GetAllCards: TCards;
begin
Result := GetContainer.Resolve<IRepository>.GetAllCards;
end;
function TApiV1Controller.GetBets: TBets;
begin
Result := GetContainer.Resolve<IRepository>.GetBets;
end;
function TApiV1Controller.GetPlayerCards(AGameID: String; APlayerName: String): TCards;
var g:TGame;
pc:TPlayerCards;
begin
g:=GetGame;
if Assigned(g) then begin
pc:=g.FindPlayer(APlayerName);
if Assigned(pc) then
Result:=pc.Cards
else
raise Exception.Create('Player='+APlayerName+' not found');
end
else
raise Exception.Create('Game ID='+AGameid+' not found');
end;
function TApiV1Controller.GetPlayers: TPlayers<TPlayer>;
begin
Result := GetContainer.Resolve<IRepository>.GetPlayers;
end;
function TApiV1Controller.GetRound: TGameRound;
begin
Result:=GetContainer.Resolve<IRepository>.GetRound;
end;
function TApiV1Controller.GiveUp: TBaseRESTResponse;
begin
Result:=GetContainer.Resolve<IRepository>.GiveUp;
end;
function TApiV1Controller.NewBet(const AParam: TBet): TBaseRESTResponse;
begin
Result:=GetContainer.Resolve<IRepository>.NewBet(AParam);
end;
function TApiV1Controller.NewGame: TExtendedRESTResponse;
begin
Result:=GetContainer.Resolve<IRepository>.NewGame;
end;
procedure TApiV1Controller.NewGameInfo(const AMessage: String);
begin
GetContainer.Resolve<IRepository>.NewGameInfo(AMessage);
end;
function TApiV1Controller.NewRound: TBaseRESTResponse;
begin
Result:=GetContainer.Resolve<IRepository>.NewRound;
end;
function TApiV1Controller.GetGame:TGame;
begin
Result:=GetContainer.Resolve<IRepository>.GetGame;
end;
function TApiV1Controller.GetGameSituation: TGameSituation<TPlayer>;
begin
Result:=GetContainer.Resolve<IRepository>.GetGameSituation;
end;
function TApiV1Controller.RegisterPlayer(const APlayer:TPlayers<TPlayer>):TBaseRESTResponse;
begin
Result:=GetContainer.Resolve<IRepository>.RegisterPlayer(APlayer);
end;
function TApiV1Controller.SetKing(ACard: TCardKey): TBaseRESTResponse;
begin
Result:=GetContainer.Resolve<IRepository>.SetKing(ACard);
end;
function TApiV1Controller.Turn(AName: String; ACard: TCardKey): TBaseRESTResponse;
begin
Result:=GetContainer.Resolve<IRepository>.Turn(AName, ACard);
end;
function TApiV1Controller.ChangeCards(ACards: TCards): TBaseRESTResponse;
begin
Result := GetContainer.Resolve<IRepository>.ChangeCards(ACards);
end;
function TApiV1Controller.DeletePlayer(const APlayerName:String):TBaseRESTResponse;
begin
Result:=GetContainer.Resolve<IRepository>.DeletePlayer(APlayerName);
end;
end.
|
unit OBJLoader;
interface
uses
Classes,
SysUtils,
StrUtils,
System.Math.Vectors,
Generics.Collections,
Shape,
Material,
Math,
Utils,
MTLLoader;
type
TOBJFile = class
public
v: TList<TVector>;
vn: TList<TVector>;
constructor Create();
end;
function Rebound(Stre: TDynStore; Shps: TList<Cardinal>): TBounds;
function SubDevide(Stre: TDynStore; DvOn: Word; const IMin, IMax: Cardinal;
Shps: TList<Cardinal>): Cardinal;
function LoadOBJ(Stre: TDynStore; fileName: string; const ofst: TVector): Cardinal;
implementation
{ TOBJFile }
constructor TOBJFile.Create;
begin
Self.v := TList<TVector>.Create;
Self.vn := TList<TVector>.Create;
end;
function Rebound(Stre: TDynStore; Shps: TList<Cardinal>): TBounds;
var
PMin: TVector;
PMax: TVector;
Indx: Cardinal;
Bnds: TBounds;
begin
// Initialize Min/Max values
PMin := TVector.Create(10000000, 10000000, 10000000);
PMax := TVector.Create(-10000000, -10000000, -10000000);
// Calc the bound
Indx := 0;
while Indx < Shps.Count do
begin
Bnds := Bound(Stre, Stre.Shps[Shps[Indx]]);
PMin.X := Min(PMin.X, Bnds.PMin.X);
PMin.Y := Min(PMin.Y, Bnds.PMin.Y);
PMin.W := Min(PMin.W, Bnds.PMin.W);
PMax.X := Max(PMax.X, Bnds.PMax.X);
PMax.Y := Max(PMax.Y, Bnds.PMax.Y);
PMax.W := Max(PMax.W, Bnds.PMax.W);
Indx := Indx + 1;
end;
Result := TBounds.Create(PMin, PMax);
end;
{ Subdeviding an OBJ }
function SubDevide(Stre: TDynStore; DvOn: Word; const IMin, IMax: Cardinal;
Shps: TList<Cardinal>): Cardinal;
var
PMdn, PMdx, PMin, PMax: TVector;
ShpL, ShpR: TList<Cardinal>;
IdxL, IdxR: Cardinal;
Indx: Cardinal;
Bnds: TBounds;
begin
// Base cases
if Shps.Count = 1 then
begin
Result := Shps[0];
Exit;
end;
if Shps.Count < 8 then
begin
Result := Stre.Shps.Add(AabbCreate(IMin, IMax, Shps.ToArray));
Exit;
end;
// Otherwise split on an axis (DvOn: 0 -> X, 1 -> Y, 2 -> Z)
PMin := Stre.VPos[IMin];
PMax := Stre.VPos[IMax];
PMdn := PMax;
case DvOn of
0:
PMdn.X := (PMin.X + PMax.X) * 0.5;
1:
PMdn.Y := (PMin.Y + PMax.Y) * 0.5;
2:
PMdn.W := (PMin.W + PMax.W) * 0.5;
end;
PMdx := PMin;
case DvOn of
0:
PMdx.X := (PMin.X + PMax.X) * 0.5;
1:
PMdx.Y := (PMin.Y + PMax.Y) * 0.5;
2:
PMdx.W := (PMin.W + PMax.W) * 0.5;
end;
// Divide over the two lists
ShpL := TList<Cardinal>.Create;
ShpR := TList<Cardinal>.Create;
Indx := 0;
while Indx < Shps.Count do
begin
Bnds := Bound(Stre, Stre.Shps[Shps[Indx]]);
if ((Bnds.PMax.X < PMdn.X) or (DvOn <> 0)) and
((Bnds.PMax.Y < PMdn.Y) or (DvOn <> 1)) and
((Bnds.PMax.W < PMdn.W) or (DvOn <> 2)) then
begin
ShpL.Add(Shps[Indx]);
end
else
begin
ShpR.Add(Shps[Indx]);
end;
Indx := Indx + 1;
end;
// Free memory of shps array
Shps.Destroy;
if ShpL.Count = 0 then
begin
Bnds := Rebound(Stre, ShpR);
Result := Stre.Shps.Add(AabbCreate(Stre.VPos.Add(Bnds.PMin), IMax, ShpR.ToArray));
Exit;
end
else if ShpR.Count = 0 then
begin
Result := Stre.Shps.Add(AabbCreate(IMin, Stre.VPos.Add(PMdn), ShpL.ToArray));
Exit;
end
else
begin
// Add new points to store & recurse
DvOn := (DvOn + 1) mod 3;
IdxL := SubDevide(Stre, DvOn, IMin, Stre.VPos.Add(PMdn), ShpL);
Bnds := Rebound(Stre, ShpR);
IdxR := SubDevide(Stre, DvOn, Stre.VPos.Add(Bnds.PMin), IMax, ShpR);
// Add sub-shapes to object
Result := Stre.Shps.Add(AabbCreate(IMin, IMax, [IdxL, IdxR]));
end;
end;
{ OBJ File Loader }
function ParsFIdx(ObjF: TOBJFile; p: string): TVector;
var
SepL: TStringList;
vIdx: Integer;
begin
SepL := TStringList.Create;
Split('/', p, SepL);
vIdx := StrToInt(SepL[0]) - 1;
Result := ObjF.v[vIdx];
end;
function ParsTria(Stre: TDynStore; ObjF: TOBJFile;
pos1, pos2, pos3: string; Mtrl: TMaterial): TShape;
var
IPs1, IPs2, IPs3: Cardinal;
begin
IPs1 := Stre.VPos.Add(ParsFIdx(ObjF, pos1));
IPs2 := Stre.VPos.Add(ParsFIdx(ObjF, pos2));
IPs3 := Stre.VPos.Add(ParsFIdx(ObjF, pos3));
Result := TriaCreate(IPs1, IPs2, IPs3, (Stre.VPos[IPs2] - Stre.VPos[IPs1])
.CrossProduct(Stre.VPos[IPs3] - Stre.VPos[IPs2]), Mtrl);
end;
function LoadOBJ(Stre: TDynStore; fileName: string; const ofst: TVector): Cardinal;
var
PMin, PMax: TVector;
Vec3: TVector;
TxtF: TextFile;
SepL: TStringList;
ObjF: TOBJFile;
Shps: TList<Cardinal>;
SIdx: Cardinal;
Line: string;
Mtls: TDictionary<string, TMaterial>;
CMtl: TMaterial;
begin
AssignFile(TxtF, fileName);
begin
try
Reset(TxtF);
except
raise Exception.Create('File not found: ' + fileName);
end;
end;
// Initialize Min/Max values
PMin := TVector.Create(10000000, 10000000, 10000000);
PMax := TVector.Create(-10000000, -10000000, -10000000);
// Initilize Objects
SepL := TStringList.Create;
Shps := TList<Cardinal>.Create;
ObjF := TOBJFile.Create;
CMtl := TMaterial.Create(TVector.Create(244, 244, 244), 0, 0, 0); // Default MTL
// Scan the file
while not Eof(TxtF) do
begin
Readln(TxtF, Line);
Split(' ', Line, SepL);
// Skip lines and polys larger than 4
if (SepL.Count > 6) then
Continue;
case IndexStr(SepL[0], ['v', 'vn', 'f', 'mtllib', 'usemtl']) of
0:
begin
Vec3 := ofst + ParsVec3(SepL[1], SepL[2], SepL[3]);
ObjF.v.Add(Vec3);
// BB scaling
PMin.X := Min(PMin.X, Vec3.X);
PMin.Y := Min(PMin.Y, Vec3.Y);
PMin.W := Min(PMin.W, Vec3.W);
PMax.X := Max(PMax.X, Vec3.X);
PMax.Y := Max(PMax.Y, Vec3.Y);
PMax.W := Max(PMax.W, Vec3.W);
end;
// 1: ObjF.vn.Add(ParsVec3(TVector.Zero, SepL[1], SepL[2], SepL[3]));
2:
begin
if SepL.Count < 3 then Continue;
if SepL[3] = '' then
Continue;
SIdx := Stre.Shps.Add(ParsTria(Stre, ObjF, SepL[1], SepL[2],
SepL[3], CMtl));
Shps.Add(SIdx);
// Parse 2nd triangle from a quad
if SepL.Count = 5 then
begin
if SepL[4] = '' then
Continue;
SIdx := Stre.Shps.Add(ParsTria(Stre, ObjF, SepL[3], SepL[4],
SepL[1], CMtl));
Shps.Add(SIdx);
end;
end;
3: begin // mtllib
Mtls := LoadMTL(Stre, 'C:\Repos\Delphi_RayTracer\' + SepL[1]);
end;
4: begin //usemtl
CMtl := Mtls[SepL[1]];
end;
end;
end;
Result := SubDevide(Stre, 0, Stre.VPos.Add(PMin), Stre.VPos.Add(PMax), Shps);
// Result := Stre.Shps.Add(AabbCreate(Stre.VPos.Add(PMin), Stre.VPos.Add(PMax), Shps.ToArray));
ObjF.Destroy;
CloseFile(TxtF);
end;
end.
|
(*
OpenSSL-compatible encrypt/decrypt routines can be used to protect non-TLS (wss://) websocket
connections using a shared secret key in a text-friendly manner.
v0.11, 2015-08-08, by Alexander Morris
added more notes and sample code, added time_strcmp() and a different random() function
added asHex (default) for GetHmacSha256Auth() and GetPBKDF2KeyHash()
v0.10, 2015-07-31, by Alexander Morris
Requirements: DCPCrypt2
References:
http://deusty.blogspot.com/2009/04/decrypting-openssl-aes-files-in-c.html
http://stackoverflow.com/questions/8313992/dcpcrypt-delphi-not-properly-encoding-rijndael
http://stackoverflow.com/questions/8806481/how-can-i-decrypt-something-with-pycrypto-that-was-encrypted-using-openssl
http://security.stackexchange.com/questions/20129/how-and-when-do-i-use-hmac
http://stackoverflow.com/questions/17533675/getting-the-128-most-significant-bits-from-a-hash
http://codahale.com/a-lesson-in-timing-attacks/
http://stackoverflow.com/questions/3946869/how-reliable-is-the-random-function-in-delphi
The secret key must somehow be preshared, for example, to access a desktop app from a mobile app.
Additionally, 2FA can be achieved once the mobile client has the key, since the key can be
further encrypted and locally stored on the mobile device with a unique password provided by the user.
Even if the mobile device is lost, the key remains secure as long as the secondary password is unknown.
Encryption is tricky and difficult to properly implement, so tread accordingly and be sure you
know what you are doing. As one example, look at the link above just on timing attacks. There are
also issues with weak random number generators.
If you want to implement a more comprehensive cypto library in Delphi, check out my libsodium.dll wrapper
( http://github.com/alexpmorris/libsodium-delphi ) which enables you to easily implement fast, highly
secure asymmmetric key exchange such as Curve25519, a state-of-the-art Diffie-Hellman elliptical-curve
function suitable for a wide variety of applications, as well as ChaCha20-Poly1305 encryption, which may
be more efficient especially with older mobile devices. For more on ChaCha20-Poly1305 and Curve25519, check out:
https://blog.cloudflare.com/do-the-chacha-better-mobile-performance-with-cryptography/
https://blog.cloudflare.com/a-relatively-easy-to-understand-primer-on-elliptic-curve-cryptography/
If you require more comprehensive security / encryption out of the box (especially for a standard
secure server implementation), including automatic key exchange, TLS1.2 sockets should probably be used
instead (ie. wss://) using a socket implementation such as DnTlsBox in IOCPengine:
https://bitbucket.org/voipobjects/iocpengine
in Delphi:
mySalt := CreateSalt(10);
myKeyHash := GetSha256KeyHash('mySecretKey',mySalt,100);
myKeyHash := GetPBKDF2KeyHash('mySecretKey',mySalt,1000,1); // <-- PBKDF2 can be used as an alternative
testStr :='encrypt me!';
EncryptOpenSSLAES256CBC(myKeyHash,testStr); // testStr is now encrypted
DecryptOpenSSLAES256CBC(myKeyHash,testStr); // testStr should again equal 'encrypt me!'
you should also authenticate the integrity of the encrypted message by including an HMAC+SHA256
signature along with the encrypted message:
authHash := Copy(GetHmacSha256Auth('mySecretKey',EncryptedMessage),1,32);
messages can be easily encrypted/decrypted from javascript using crypto-js:
<script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/sha256.js"></script>
<script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/aes.js"></script>
<script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/hmac-sha256.js"></script>
<script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/pbkdf2.js"></script>
<script language="javascript" type="text/javascript">
function hex2a(hex) {
var str = '';
for (var i = 0; i < hex.length; i += 2)
str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
return str;
}
// create a key/hash with a salt and xxx iterations
// ie. msgJson = {"typ":"auth","salt":"SOcYFih","iter":100};
if (msgJson.typ == "auth") {
for (var j=1;j<=msgJson.iter;j++) {
hash = CryptoJS.SHA256(hash+privateKey+msgJson.salt).toString();
}
//encrypt
var encryptedMsg = CryptoJS.AES.encrypt(msg,hash).toString();
encryptedMsg += CryptoJS.HmacSHA256(encryptedMsg,hash).toString().substr(0,32);
//decrypt
var hmacCheck = json.substr(encryptedMsg.length-32,32);
encryptedMsg = encryptedMsg.substr(0,encryptedMsg.length-32);
if (hmacCheck == CryptoJS.HmacSHA256(encryptedMsg,hash).toString().substr(0,32)) {
packet = hex2a(CryptoJS.AES.decrypt(encryptedMsg,hash).toString());
} else { packet = "cannotAuthenticatePacket"; }
</script>
WARNING: Using websocket deflate with encryption is useless. To use encryption + deflate,
you must deflate then encrypt. From javascript, you can use the following code:
<script src="https://cdnjs.cloudflare.com/ajax/libs/pako/0.2.7/pako.min.js"></script>
<script language="javascript" type="text/javascript">
var deflate = new pako.Deflate({ level: 8, windowBits: -15, memLevel:9, to: 'string'});
var inflate = new pako.Inflate({ windowBits: -15, to: 'string'});
//deflate
if (msgDeflate) {
deflate.push(msg, 2); //type 2 = Z_SYNC_FLUSH
msg = CryptoJS.enc.Latin1.parse(deflate.result.substr(0,deflate.result.length-4));
}
encryptedMsg = CryptoJS.AES.encrypt(msg,hash).toString();
encryptedMsg += CryptoJS.HmacSHA256(encryptedMsg,hash);
//inflate
if (packet.substr(0,10) == "U2FsdGVkX1") { //packet is encrypted
var hmacCheck = json.substr(packet.length-64,64);
packet = encryptedMsg.substr(0,packet.length-64);
if (hmacCheck == CryptoJS.HmacSHA256(packet,hash)) {
packet = hex2a(CryptoJS.AES.decrypt(packet,hash).toString());
if (msgDeflate) {
inflate.push(packet+"\x00\x00\xff\xff", 2); //type 2 = Z_SYNC_FLUSH
packet = inflate.result;
}
} else { packet = "cannotAuthenticatePacket"; }
}
</script>
*)
unit WebSocketCrypt;
interface
uses SysUtils, DCPcrypt2, DCPrijndael, DCPmd5, DCPbase64, DCPsha1, DCPsha256, DCPsha512, DCPauth, crandom;
//256-bit openssl-compatible AES format text-based packet encryption/decryption functions
// testStr :='encrypt me!';
// EncryptOpenSSLAES256CBC('hashOfMySecretKey',testStr); // testStr is now encrypted
// DecryptOpenSSLAES256CBC('hashOfMySecretKey',testStr); // testStr should again equal 'encrypt me!'
//
// messages can be easily encrypted/decrypted from javascript using crypto-js
procedure EncryptOpenSSLAES256CBC(const hashS: AnsiString; var msgS: AnsiString);
procedure DecryptOpenSSLAES256CBC(const hashS: AnsiString; var msgS: AnsiString);
//get len bytes worth of salt
function CreateSalt(const len: integer): AnsiString;
//create an SHA256 hash of mySecretKey using mySalt with iter iterations
function GetSha256KeyHash(const mySecretKey,mySalt: AnsiString; const iter: integer): AnsiString;
//create a 256-bit or 512-bit PBKDF2 hash of mySecretKey using mySalt with iter iterations
//shaMode=1 to use Sha1 for compatibility with CryptoJS.PBKDF2() - 256-bit output
//shaMode=2 to uses Sha256 as hash function - 256-bit output
//shaMode=3 to uses Sha512 as hash function - 512-bit output
function GetPBKDF2KeyHash(const mySecretKey,mySalt: AnsiString; const iter: integer; const shaMode: Byte; const asHex: Boolean = true): AnsiString;
//create an HMAC + SHA256 message authentication using mySecretKey
function GetHmacSha256Auth(const mySecretKey,myMessage: AnsiString; const asHex: Boolean = true): AnsiString;
//constant time string comparision in delphi to prevent timing attacks, based on XORing
function time_strcmp(const str1, str2: AnsiString): boolean;
implementation
procedure PKS7Padding(var rawS: AnsiString);
var i,padSize: integer;
begin
padSize := 16 - (length(rawS) mod 16);
for i := 1 to padSize do rawS:=rawS+chr(padSize);
end;
procedure EncryptOpenSSLAES256CBC(const hashS: AnsiString; var msgS: AnsiString);
//256-bit openssl-compatible AES format
var Cipher: TDCP_rijndael;
Hash: TDCP_md5;
key,key2,iv: array [0..31] of AnsiChar;
salt,tmpKeyS,pwdS: AnsiString;
rawS,tmpS: AnsiString;
i: integer;
begin
if (hashS = '') then exit;
try
tmpKeyS := ''; pwdS := '';
SetLength(salt,8);
CryptGenRandomBytes(@salt[1],8);
PKS7Padding(msgS);
pwdS := hashS;
Hash := TDCP_md5.Create(nil);
Hash.Init;
Hash.UpdateStr(pwdS+salt);
Hash.Final(key);
Hash.Init;
for i:=0 to 15 do tmpKeyS:=tmpKeyS+key[i];
Hash.UpdateStr(tmpKeyS+pwdS+salt);
Hash.Final(key2);
for i:=0 to 15 do begin tmpKeyS:=tmpKeyS+key2[i]; key[i+16]:=key2[i]; end;
Hash.Init;
Hash.UpdateStr(copy(tmpKeyS,17,16)+pwdS+salt);
Hash.Final(iv);
Hash.Free;
except exit end;
//writeln('slt=',StringToHex(salt));
//write('key='); for i:= 0 to 31 do write(lowercase(IntToHex(ord(key[i]),2))); writeln;
//write('iv ='); for i:= 0 to 15 do write(lowercase(IntToHex(ord(iv[i]),2))); writeln;
Cipher := TDCP_rijndael.Create(nil);
Cipher.Init(key,256,@iv);
try Cipher.EncryptCBC(msgS[1],msgS[1],length(msgS)); except end;
msgS := Base64EncodeStr('Salted__'+salt+msgS);
//writeln(msgS);
Cipher.Burn;
Cipher.Free;
end;
//http://deusty.blogspot.com/2009/04/decrypting-openssl-aes-files-in-c.html
//http://stackoverflow.com/questions/8313992/dcpcrypt-delphi-not-properly-encoding-rijndael
//http://stackoverflow.com/questions/8806481/how-can-i-decrypt-something-with-pycrypto-that-was-encrypted-using-openssl
procedure DecryptOpenSSLAES256CBC(const hashS: AnsiString; var msgS: AnsiString);
//256-bit openssl-compatible AES format
var Cipher: TDCP_rijndael;
Hash: TDCP_md5;
key,key2,iv: array [0..31] of AnsiChar;
salt,tmpKeyS,pwdS: AnsiString;
rawS,tmpS: AnsiString;
i,padLen: integer;
begin
if (hashS = '') then exit;
try
rawS := Base64DecodeStr(msgS);
salt := ''; tmpKeyS := ''; pwdS := '';
if (copy(rawS,1,8)='Salted__') then begin //openssl format
salt := copy(rawS,9,8);
delete(rawS,1,16);
end;
pwdS := hashS;
Hash := TDCP_md5.Create(nil);
Hash.Init;
Hash.UpdateStr(pwdS+salt);
Hash.Final(key);
Hash.Init;
for i:=0 to 15 do tmpKeyS:=tmpKeyS+key[i];
Hash.UpdateStr(tmpKeyS+pwdS+salt);
Hash.Final(key2);
for i:=0 to 15 do begin tmpKeyS:=tmpKeyS+key2[i]; key[i+16]:=key2[i]; end;
Hash.Init;
Hash.UpdateStr(copy(tmpKeyS,17,16)+pwdS+salt);
Hash.Final(iv);
Hash.Free;
except exit; end;
//writeln('slt=',StringToHex(salt));
//write('key='); for i:= 0 to 31 do write(lowercase(IntToHex(ord(key[i]),2))); writeln;
//write('iv ='); for i:= 0 to 15 do write(lowercase(IntToHex(ord(iv[i]),2))); writeln;
Cipher := TDCP_rijndael.Create(nil);
Cipher.Init(key,256,@iv);
try Cipher.DecryptCBC(rawS[1],rawS[1],length(rawS)); except end;
padLen := ord(copy(rawS,length(rawS),1)[1]);
if (padLen > 0) then delete(rawS,length(rawS)-padLen+1,padLen);
msgS := rawS;
// try msgS := Cipher.DecryptString(Base64EncodeStr(rawS)); except end;
Cipher.Burn;
Cipher.Free;
end;
//get len bytes worth of salt
function CreateSalt(const len: integer): AnsiString;
var ch: AnsiChar;
begin
result := '';
while (length(result)<len) do begin
//ch := chr(45+random(65));
CryptGenRandomBytes(@ch,1);
ch := AnsiChar(45+(Ord(ch) mod 65));
if (ch in ['0'..'9','A'..'Z','a'..'z','$','&','#','@','_','*','!','~','.','?',':',';','^','%']) then result:=result+ch;
end;
end;
//create an SHA256 hash of mySecretKey using mySalt with iter iterations
function GetSha256KeyHash(const mySecretKey,mySalt: AnsiString; const iter: integer): AnsiString;
var Hash: TDCP_sha256;
Digest: array[0..31] of byte; //256-bit sha256 digest (32 bytes)
tmpHashS: AnsiString;
i,j: integer;
begin
tmpHashS := '';
Hash := TDCP_sha256.Create(nil);
for i := 1 to iter do begin
Hash.Init;
Hash.UpdateStr(tmpHashS+mySecretKey+mySalt);
Hash.Final(Digest);
tmpHashS := ''; for j := 0 to 31 do begin tmpHashS := tmpHashS + lowercase(IntToHex(Digest[j],2)); end;
end;
Hash.Free;
result := tmpHashS;
end;
//create a 256-bit or 512-bit PBKDF2 hash of mySecretKey using mySalt with iter iterations
//shaMode=1 to use Sha1 for compatibility with CryptoJS.PBKDF2() - 256-bit output
//shaMode=2 to uses Sha256 as hash function - 256-bit output
//shaMode=3 to uses Sha512 as hash function - 512-bit output
function GetPBKDF2KeyHash(const mySecretKey,mySalt: AnsiString; const iter: integer; const shaMode: Byte; const asHex: Boolean = true): AnsiString;
var hash: TDCP_hashclass;
tmpHashS,hexVal: AnsiString;
i,useBytes: integer;
begin
useBytes := 32; // 256-bit output
if (shaMode <= 1) then hash := TDCP_sha1 else
if (shaMode = 2) then hash := TDCP_sha256 else begin
hash := TDCP_sha512;
useBytes := 64; // 512-bit output
end;
tmpHashS := PBKDF2(mySecretKey,mySalt,iter,useBytes{256 div 8},hash);
if asHex then begin
SetLength(result,useBytes*2{64});
i := 0;
while (i < useBytes{32}) do begin
hexVal := lowercase(IntToHex(ord(tmpHashS[i+1]),2));
Move(hexVal[1],Result[(i*2)+1],2);
i := i + 1;
end;
end else result := tmpHashS;
end;
//create an HMAC + SHA256 message authentication using mySecretKey
function GetHmacSha256Auth(const mySecretKey,myMessage: AnsiString; const asHex: Boolean = true): AnsiString;
var tmpHashS,hexVal: AnsiString;
i: integer;
begin
tmpHashS := CalcHMAC(myMessage, mySecretKey, TDCP_sha256);
result := '';
if asHex then begin
SetLength(result,64);
i := 0;
while (i < 32) do begin
hexVal := lowercase(IntToHex(ord(tmpHashS[i+1]),2));
Move(hexVal[1],Result[(i*2)+1],2);
i := i + 1;
end;
end else result := tmpHashS;
end;
//constant time string comparision in delphi to prevent timing attacks, based on XORing
//http://codahale.com/a-lesson-in-timing-attacks/
//http://codereview.stackexchange.com/questions/13512/constant-time-string-comparision-in-php-to-prevent-timing-attacks
function time_strcmp(const str1, str2: AnsiString): boolean;
var res: array of byte;
i,shortLen,sums: cardinal;
begin
result := false;
if (length(str1) < length(str2)) then shortLen := Length(str1) else shortLen := length(str2);
SetLength(res,shortLen);
for i := 0 to shortLen-1 do res[i] := ord(str1[i+1]) xor ord(str2[i+1]);
if Length(str1) <> length(str2) then exit;
sums := 0;
for i := shortLen-1 downto 0 do sums := sums + res[i];
if (sums = 0) then result := true;
end;
initialization
Randomize;
end.
|
//---------------------------------------------------------------------------
// Copyright 2014 The Open Source Electronic Health Record Alliance
//
// 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.
//---------------------------------------------------------------------------
{$Optimization off}
unit UTXlfMime;
interface
uses UnitTest, TestFrameWork, XlfMime,SysUtils, Windows, Registry, Dialogs, Classes, Forms, Controls,
StdCtrls;
implementation
type
UTXlfMimeTests=class(TTestCase)
private
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestMimeEncodedSize;
procedure TestMimeEncode;
procedure TestMimeEncodeString;
procedure TestMimeDecodeString;
end;
procedure UTXlfMimeTests.SetUp;
begin
end;
procedure UTXlfMimeTests.TearDown;
begin
end;
procedure UTXlfMimeTests.TestMimeEncodedSize;
var
test : integer;
blah : Cardinal;
begin
WriteLn(Output,'Start MimeEncodedSize');
test:=10;
blah := XlfMime.MimeEncodedSize(test);
CheckEquals(16,blah,'MimeFunction for value'+ IntToStr(test) +' hasnt returned correctly');
test:=15;
blah := XlfMime.MimeEncodedSize(test);
CheckEquals(20,blah,'MimeFunction for value'+ IntToStr(test) +' hasnt returned correctly');
test:=500;
blah := XlfMime.MimeEncodedSize(test);
CheckEquals(668,blah,'MimeFunction for value'+ IntToStr(test) +' hasnt returned correctly');
WriteLn(Output,'Stop MimeEncodedSize');
end;
procedure UTXlfMimeTests.TestMimeEncode;
var
hashVal: array of byte;
hashStr: string;
dwlen : Cardinal;
i : integer;
begin
WriteLn(Output,'Start MimeEncode');
dwlen :=10;
hashStr :='';
SetLength(hashVal,dwlen);
SetLength(hashStr, XlfMime.MimeEncodedSize(dwlen));
for i := 0 to dwLen - 1 do
begin
hashVal[i] :=i;
end;
XlfMime.MimeEncode(PChar(hashVal)^,dwlen, PChar(hashStr)^);
CheckEquals('AAECAwQFBgcICQ==',hashStr,'MimeEncode hasnt returned correctly1');
dwlen :=10;
hashStr :='';
SetLength(hashVal,dwlen);
SetLength(hashStr, XlfMime.MimeEncodedSize(dwlen));
for i := 0 to dwLen - 1 do hashVal[i] :=i*2;
XlfMime.MimeEncode(PChar(hashVal)^,dwlen, PChar(hashStr)^);
CheckEquals('AAIEBggKDA4QEg==',hashStr,'MimeEncode hasnt returned correctly2');
dwlen :=10;
hashStr :='';
SetLength(hashVal,dwlen);
SetLength(hashStr, XlfMime.MimeEncodedSize(dwlen));
for i := 0 to dwLen - 1 do hashVal[i] :=i*3;
XlfMime.MimeEncode(PChar(hashVal)^,dwlen, PChar(hashStr)^);
CheckEquals('AAMGCQwPEhUYGw==',hashStr,'MimeEncode hasnt returned correctly3');
dwlen :=15;
hashStr :='';
SetLength(hashVal,dwlen);
SetLength(hashStr, XlfMime.MimeEncodedSize(dwlen));
for i := 0 to dwlen-1 do hashVal[i] :=i;
XlfMime.MimeEncode(PChar(hashVal)^,dwlen, PChar(hashStr)^);
CheckEquals('AAECAwQFBgcICQoLDA0O',hashStr,'MimeEncode hasnt returned correctly4');
dwlen :=15;
hashStr :='';
SetLength(hashVal,dwlen);
SetLength(hashStr, XlfMime.MimeEncodedSize(dwlen));
for i := 0 to dwlen-1 do hashVal[i] :=(i+2)*12;
XlfMime.MimeEncode(PChar(hashVal)^,dwlen, PChar(hashStr)^);
CheckEquals('GCQwPEhUYGx4hJCcqLTA',hashStr,'MimeEncode hasnt returned correctly5');
dwlen :=100;
hashStr :='';
SetLength(hashVal,dwlen);
SetLength(hashStr, XlfMime.MimeEncodedSize(dwlen));
for i := 0 to dwlen-1 do hashVal[i] :=(i+2)*2;
XlfMime.MimeEncode(PChar(hashVal)^,dwlen, PChar(hashStr)^);
CheckEquals('BAYICgwOEBIUFhgaHB4gIiQmKCosLjAyNDY4Ojw+QEJERkhKTE5QUlRWWFpcXmBiZGZoamxucHJ0dnh6fH6AgoSGiIqMjpCSlJaYmpyeoKKkpqiqrK6wsrS2uLq8vsDCxMbIyg=='
,hashStr,'MimeEncode hasnt returned correctly6');
WriteLn(Output,'Stop MimeEncode');
end;
procedure UTXlfMimeTests.TestMimeEncodeString;
var
outstring:string;
const
test = 'blah';
begin
WriteLn(Output,'Start MimeEncodeString');
outstring := XlfMime.MimeEncodeString(test);
CheckEquals('YmxhaA==',outstring,'Mime Encode String didnt return correctly');
outstring := XlfMime.MimeEncodeString('This is a longer string');
CheckEquals('VGhpcyBpcyBhIGxvbmdlciBzdHJpbmc=',outstring,'Mime Encode String didnt return correctly');
WriteLn(Output,'Start MimeEncodeString');
end;
procedure UTXlfMimeTests.TestMimeDecodeString;
var
outstring:string;
begin
WriteLn(Output,'Start MimeEncodedSize');
outstring := XlfMime.MimeDecodeString('YmxhaA==');
CheckEquals('blah',outstring,'Mime Decode didt return correcly');
outstring := XlfMime.MimeDecodeString('VGhpcyBpcyBhIGxvbmdlciBzdHJpbmc=');
CheckEquals('This is a longer string',outstring,'Mime Decode didnt return correctly');
end;
begin
UnitTest.addSuite(UTXlfMimeTests.Suite);
end. |
unit savefilt;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
wwsavflt, Wwfltdlg, StdCtrls, Grids, Wwdbigrd, Wwdbgrid, DB, DBTables,
Wwtable, Wwdatsrc, selfilt, Menus;
type
TSaveFilterDemo = class(TForm)
wwFilterDialog1: TwwFilterDialog;
wwDataSource1: TwwDataSource;
wwTable1: TwwTable;
wwDBGrid1: TwwDBGrid;
MainMenu1: TMainMenu;
Filter1: TMenuItem;
Filter2: TMenuItem;
ClearFilter1: TMenuItem;
SaveFilter1: TMenuItem;
LoadFilter1: TMenuItem;
Exit1: TMenuItem;
Memo1: TMemo;
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure Button4Click(Sender: TObject);
procedure Filter2Click(Sender: TObject);
procedure ClearFilter1Click(Sender: TObject);
procedure SaveFilter1Click(Sender: TObject);
procedure Exit1Click(Sender: TObject);
procedure LoadFilter1Click(Sender: TObject);
private
procedure LoadFilter;
{ Private declarations }
public
wwSaveFilter1: TwwSaveFilter;
{ Public declarations }
end;
var
SaveFilterDemo: TSaveFilterDemo;
implementation
{$R *.DFM}
procedure TSaveFilterDemo.LoadFilter;
var FilterForm: TSelectSaveFilter;
currentFilterNames : TStrings;
i: integer;
begin
FilterForm := TSelectSaveFilter.create(Application);
if (not wwSaveFilter1.GetFilterNames(FilterForm.FiltersBox.Items)) then
begin
ShowMessage('You do not have any saved filters.');
FilterForm.Free;
exit;
end;
Screen.Cursor := crHourGlass;
if (FilterForm.ShowModal=mrOk) then
begin
{ Remove deleted filters from file}
currentFilterNames := TStringList.create;
wwSaveFilter1.GetFilterNames(currentFilterNames);
for i:=0 to currentFilterNames.Count-1 do
if (FilterForm.FiltersBox.Items.IndexOf(currentFilterNames.Strings[i])<0) then
wwSaveFilter1.DeleteFilter(currentFilterNames.Strings[i]);
currentFilterNames.free;
// Load selected filter
if (FilterForm.FiltersBox.ItemIndex <> -1) then
wwSaveFilter1.LoadFilter(FilterForm.FiltersBox.Items.Strings[FilterForm.FiltersBox.ItemIndex]);
end;
FilterForm.Free;
Screen.Cursor := crArrow;
end;
procedure TSaveFilterDemo.Button2Click(Sender: TObject);
begin
wwSaveFilter1.SaveFilter(InputBox('Filter Name', 'Name of Filter?',''));
end;
procedure TSaveFilterDemo.Button3Click(Sender: TObject);
begin
wwfilterdialog1.execute;
end;
procedure TSaveFilterDemo.FormShow(Sender: TObject);
begin
wwSaveFilter1:= TwwSaveFilter.create(Application);
wwSaveFilter1.Delimiter := '///';
wwSaveFilter1.FilePath := 'SaveFilt.txt';
wwSaveFilter1.wwFilterDialog := wwFilterDialog1;
Width:= (LongInt(Width) * PixelsPerInch) div 96;
Height:= (LongInt(Height) * PixelsPerInch) div 96;
end;
procedure TSaveFilterDemo.Button4Click(Sender: TObject);
begin
Close;
end;
procedure TSaveFilterDemo.Filter2Click(Sender: TObject);
begin
wwFilterDialog1.execute;
end;
procedure TSaveFilterDemo.ClearFilter1Click(Sender: TObject);
begin
wwFilterDialog1.ClearFilter;
wwFilterDialog1.ApplyFilter;
end;
procedure TSaveFilterDemo.SaveFilter1Click(Sender: TObject);
begin
wwSaveFilter1.SaveFilter(InputBox('Filter Name', 'Name of Filter?',''));
end;
procedure TSaveFilterDemo.Exit1Click(Sender: TObject);
begin
Close;
end;
procedure TSaveFilterDemo.LoadFilter1Click(Sender: TObject);
begin
LoadFilter;
end;
end.
|
{ ZADANIE 14
* Vytvorte funkciu, ktorá zistí ciferný súčet celého kladného čísla
* a použite ju v hlavnom programe.
* }
program FunkciaCifernySucet;
uses crt, sysutils;
var c: Longint; {globalne premenne - mozeme ich pouzivat v celom programe} {pouzijeme Longint namiesto integer-u aby sme mohli zadavat dlhzsie cisla}
{jednoduchsi variant funkcie s konvertovanim typov lokalnych premennych}
function cifernySucet(cislo: Longint): integer; {deklaracia funkcie: function nazovFunkcie(vstupnyParameter: typPremennej): vystupnyTypFunkcie;}
var retazec: String; {lokalne premenne - mozeme ich poucivat iba v tele funkcie}
i, sucet: integer;
begin
retazec := IntToStr(cislo);
sucet := 0;
for i := 1 to length(retazec) do
sucet := sucet + StrToInt(retazec[i]); {jednotlivo pripocitavame kazdu cifru}
cifernySucet := sucet; {na konci funkcie zadame jej vystupnu hodnotu: nazovFunkcie := nejakaHodnota;}
end;
function cifSucet2(cislo: Longint): integer; {zlozitejsi variant funkcie s matematickym vypoctom ciferneho suctu}
var sucet, delitel: Longint;
begin
sucet := 0;
delitel := 10;
while (cislo * 10 > delitel) do
begin
sucet := sucet + (cislo mod delitel div (delitel div 10));
cislo := cislo - (cislo mod delitel);
delitel := delitel * 10;
end;
cifSucet2 := sucet;
end;
begin
clrscr;
write('Zadaj cislo: ');
readln(c);
clrscr;
writeln('Ciferny sucet cisla ', c, ' je ', cifernySucet(c)); {volanie funkcie - nazovFunkcie(premenna)}
writeln('Vysledok z druhej funkcie: ', cifSucet2(c));
readln;
end.
|
{
Purpose: Generates bash tags for a selected plugin automatically
Games: FO3/FNV/FO4/TES4/TES5/SSE/Enderal
Author: fireundubh <fireundubh@gmail.com>
}
unit GenerateWryeBashTags;
const
scaleFactor = Screen.PixelsPerInch / 96;
var
kFile : IwbFile;
slBadTags : TStringList;
slDifferentTags : TStringList;
slExistingTags : TStringList;
slLog : TStringList;
slMasterPlugins : TStringList;
slSuggestedTags : TStringList;
sFileName : String;
sTag : String;
sScriptName : String;
sScriptVersion : String;
sScriptAuthor : String;
sScriptEmail : String;
optionAddTags : Integer;
optionOutputLog : Integer;
bQuickExit : Boolean;
function wbIsOblivion: Boolean;
begin
Result := wbGameMode = gmTES4;
end;
function wbIsSkyrim: Boolean;
begin
Result := (wbGameMode = gmTES5) or (wbGameMode = gmEnderal) or (wbGameMode = gmTES5VR) or (wbGameMode = gmSSE);
end;
function wbIsSkyrimSE: Boolean;
begin
Result := wbGameMode = gmSSE;
end;
function wbIsFallout3: Boolean;
begin
Result := wbGameMode = gmFO3;
end;
function wbIsFalloutNV: Boolean;
begin
Result := wbGameMode = gmFNV;
end;
function wbIsFallout4: Boolean;
begin
Result := (wbGameMode = gmFO4) or (wbGameMode = gmFO4VR);
end;
function wbIsFallout76: Boolean;
begin
Result := wbGameMode = gmFO76;
end;
procedure BuildMasterPluginsList(f: IwbFile; output: TStringList);
var
m: IwbFile;
i: Integer;
begin
output.Add(GetFileName(f));
for i := 0 to Pred(MasterCount(f)) do
begin
m := MasterByIndex(f, i);
output.Add(GetFileName(m));
BuildMasterPluginsList(m, output);
end;
end;
procedure LogInfo(s: String);
begin
AddMessage('[INFO] ' + s);
end;
procedure LogWarn(s: String);
begin
AddMessage('[WARN] ' + s);
end;
procedure LogError(s: String);
begin
AddMessage('[ERRO] ' + s);
end;
function Initialize: Integer;
var
kDescription : IInterface;
kHeader : IInterface;
sBashTags : String;
sDescription : String;
sMasterName : String;
r : IwbMainRecord;
i : Integer;
begin
sScriptName := 'GenerateWryeBashTags'; // working name
sScriptVersion := '1.6.3.0';
sScriptAuthor := 'fireundubh';
sScriptEmail := 'fireundubh@gmail.com';
// clear
ClearMessages();
// show script header
AddMessage(#10);
LogInfo(sScriptName + ' v' + sScriptVersion + ' by ' + sScriptAuthor + ' <' + sScriptEmail + '>');
AddMessage(#10);
optionAddTags := mrNo;
optionOutputLog := mrYes;
kFile := Configure(sScriptName + ' v' + sScriptVersion);
if not Assigned(kFile) then
exit;
sFileName := GetFileName(kFile);
// create list of log entries
slLog := TStringList.Create;
slLog.Sorted := False;
slLog.Duplicates := dupAccept;
// create list of tags
slSuggestedTags := TStringList.Create;
slSuggestedTags.Sorted := True;
slSuggestedTags.Duplicates := dupIgnore;
slSuggestedTags.Delimiter := ','; // separated by comma
slExistingTags := TStringList.Create; // existing tags
slDifferentTags := TStringList.Create; // different tags
slBadTags := TStringList.Create; // bad tags
if wbIsFallout3 then
LogInfo('Using game mode: Fallout 3');
if wbIsFalloutNV then
LogInfo('Using game mode: Fallout: New Vegas');
if wbIsFallout4 then
LogInfo('Using game mode: Fallout 4');
if wbIsFallout76 then
begin
LogError('Fallout 76 is not supported by CBash.');
exit;
end;
if wbIsOblivion then
LogInfo('Using game mode: Oblivion');
if wbIsSkyrim and not wbIsSkyrimSE then
LogInfo('Using game mode: Skyrim');
if wbIsSkyrimSE then
LogInfo('Using game mode: Skyrim Special Edition');
slMasterPlugins := TStringList.Create;
slMasterPlugins.Duplicates := dupIgnore;
slMasterPlugins.Sorted := True;
AddMessage(#10);
BuildMasterPluginsList(kFile, slMasterPlugins);
LogInfo('Processing... Please wait. This could take a while.');
for i := 0 to Pred(RecordCount(kFile)) do
ProcessRecord(RecordByIndex(kFile, i));
AddMessage(#10);
// exit conditions
if not Assigned(sFileName) then
exit;
// output file name
LogInfo(Uppercase(sFileName));
AddMessage(#10);
// output log
if optionOutputLog = mrYes then
for i := 0 to Pred(slLog.Count) do
LogInfo(slLog[i]);
if (optionOutputLog = mrYes) and (slLog.Count > 0) then
AddMessage(#10);
// if any suggested tags were generated
if slSuggestedTags.Count > 0 then
begin
kHeader := ElementBySignature(kFile, 'TES4');
// determine if the header record exists
if Assigned(kHeader) then
begin
kDescription := ElementBySignature(kHeader, 'SNAM');
sDescription := GetEditValue(kDescription);
// categorize tag list
sBashTags := RegExMatch('(?:[{]{2}BASH:).*?[}]{2}', sDescription);
if Length(sBashTags) > 0 then
begin
sBashTags := Trim(MidStr(sBashTags, 8, Length(sBashTags) - 9));
slExistingTags.CommaText := sBashTags;
end else
slExistingTags.CommaText := '';
slDifferentTags := Diff(slSuggestedTags, slExistingTags);
slBadTags := Diff(slExistingTags, slSuggestedTags);
slSuggestedTags.AddStrings(slDifferentTags);
// exit if existing and suggested tags are the same
if SameText(slExistingTags.CommaText, slSuggestedTags.CommaText) then
begin
LogInfo(FormatTags(slExistingTags, 'existing tag found:', 'existing tags found:', 'No existing tags found.'));
LogInfo(FormatTags(slSuggestedTags, 'suggested tag:', 'suggested tags:', 'No suggested tags.'));
LogWarn('No tags to add.' + #13#10);
exit;
end;
// exit if the header record doesn't exist
end else begin
LogError('Header record not found. Nothing to do. Exiting.' + #13#10);
exit;
end;
// write tags
if optionAddTags = mrYes then
begin
// if the description element doesn't exist, add the element
kDescription := ElementBySignature(kHeader, 'SNAM');
if not Assigned(kDescription) then
kDescription := Add(kHeader, 'SNAM', True);
if not SameText(slExistingTags.CommaText, slSuggestedTags.CommaText) then
begin
sDescription := GetEditValue(kDescription);
sDescription := Trim(RemoveFromEnd(sDescription, Format('{{BASH:%s}}', [slExistingTags.DelimitedText])));
SetEditValue(kDescription, sDescription + #13#10 + #13#10 + Format('{{BASH:%s}}', [slSuggestedTags.DelimitedText]));
end;
LogInfo(FormatTags(slBadTags, 'bad tag removed:', 'bad tags removed:', 'No bad tags found.'));
LogInfo(FormatTags(slDifferentTags, 'tag added to file header:', 'tags added to file header:', 'No tags added.'));
end;
// suggest tags only and output to log
if optionAddTags = mrNo then
begin
LogInfo(FormatTags(slExistingTags, 'existing tag found:', 'existing tags found:', 'No existing tags found.'));
LogInfo(FormatTags(slBadTags, 'bad tag found:', 'bad tags found:', 'No bad tags found.'));
LogInfo(FormatTags(slDifferentTags, 'suggested tag to add:', 'suggested tags to add:', 'No suggested tags to add.'));
LogInfo(FormatTags(slSuggestedTags, 'suggested tag overall:', 'suggested tags overall:', 'No suggested tags overall.'));
end;
end else
LogInfo('No tags are suggested for this plugin.');
AddMessage(#10);
end;
function ProcessRecord(e: IInterface): Integer;
var
o : IInterface;
sTag : String;
sSignature : String;
ConflictState : TConflictThis;
iFormID : Integer;
begin
// exit conditions
ConflictState := ConflictAllForMainRecord(e);
// get record signature
sSignature := Signature(e);
if (ConflictState = caUnknown)
or (ConflictState = caOnlyOne)
or (ConflictState = caNoConflict) then
exit;
// exit if the record should not be processed
if CompareText(sFileName, 'Dawnguard.esm') = 0 then
begin
iFormID := FileFormID(e);
if (iFormID = $00016BCF)
or (iFormID = $0001EE6D)
or (iFormID = $0001FA4C)
or (iFormID = $00039F67)
or (iFormID = $0006C3B6) then
exit;
end;
// get master record if record is an override
o := Master(e);
if not Assigned(o) then
exit;
// if record overrides several masters, then get the last one
o := HighestOverrideOrSelfInList(o, OverrideCount(o), slMasterPlugins);
// stop processing deleted records to avoid errors
if GetIsDeleted(e)
or GetIsDeleted(o) then
exit;
// -------------------------------------------------------------------------------
// GROUP: Supported tags exclusive to FNV
// -------------------------------------------------------------------------------
if wbIsFalloutNV then
if sSignature = 'WEAP' then
ProcessTag('WeaponMods', e, o);
// -------------------------------------------------------------------------------
// GROUP: Supported tags exclusive to TES4
// -------------------------------------------------------------------------------
if wbIsOblivion then
begin
if InDelimitedList(sSignature, 'CREA NPC_', ' ') then
begin
ProcessTag('Actors.Spells', e, o);
if sSignature = 'CREA' then
ProcessTag('Creatures.Blood', e, o);
end;
// TODO: Npc.EyesOnly - NOT IMPLEMENTED
// TODO: Npc.HairOnly - NOT IMPLEMENTED
// TODO: R.AddSpells - NOT IMPLEMENTED
if sSignature = 'RACE' then
begin
ProcessTag('R.ChangeSpells', e, o);
ProcessTag('R.Attributes-F', e, o);
ProcessTag('R.Attributes-M', e, o);
end;
if sSignature = 'ROAD' then
ProcessTag('Roads', e, o);
if sSignature = 'SPEL' then
ProcessTag('SpellStats', e, o);
end;
// -------------------------------------------------------------------------------
// GROUP: Supported tags exclusive to TES5 and SSE
// -------------------------------------------------------------------------------
if wbIsSkyrim then
begin
if sSignature = 'CELL' then
begin
ProcessTag('C.Location', e, o);
ProcessTag('C.LockList', e, o);
ProcessTag('C.Regions', e, o);
ProcessTag('C.SkyLighting', e, o);
end;
if InDelimitedList(sSignature, 'ACTI ALCH AMMO ARMO BOOK FLOR FURN INGR KEYM LCTN MGEF MISC NPC_ SCRL SLGM SPEL TACT WEAP', ' ') then
ProcessTag('Keywords', e, o);
end;
// -------------------------------------------------------------------------------
// GROUP: Supported tags exclusive to FO3 and FNV
// -------------------------------------------------------------------------------
if wbIsFallout3 or wbIsFalloutNV then
begin
sTag := 'Destructible';
if InDelimitedList(sSignature, 'ACTI ALCH AMMO BOOK CONT DOOR FURN IMOD KEYM MISC MSTT PROJ TACT TERM WEAP', ' ') then
ProcessTag(sTag, e, o);
// special handling for CREA and NPC_ record types
if InDelimitedList(sSignature, 'CREA NPC_', ' ') then
if not CompareFlags(sTag, e, o, 'ACBS\Template Flags', 'Use Model/Animation', False, False) then
ProcessTag(sTag, e, o);
end;
// -------------------------------------------------------------------------------
// GROUP: Supported tags exclusive to FO3, FNV, and TES4
// -------------------------------------------------------------------------------
if wbIsOblivion or wbIsFallout3 or wbIsFalloutNV then
begin
if InDelimitedList(sSignature, 'CREA NPC_', ' ') then
begin
sTag := 'Factions';
if wbIsOblivion then
ProcessTag(sTag, e, o)
else
if not CompareFlags(sTag, e, o, 'ACBS\Template Flags', 'Use Factions', False, False) then
ProcessTag(sTag, e, o);
end;
if sSignature = 'FACT' then
ProcessTag('Relations', e, o);
end;
// -------------------------------------------------------------------------------
// GROUP: Supported tags exclusive to FO3, FNV, TES5, and SSE
// -------------------------------------------------------------------------------
if not wbIsOblivion and not wbIsFallout4 then
begin
if InDelimitedList(sSignature, 'CREA NPC_', ' ') then
begin
sTag := 'Actors.ACBS';
if not CompareFlags(sTag, e, o, 'ACBS\Template Flags', 'Use Stats', False, False) then
ProcessTag(sTag, e, o);
sTag := 'Actors.AIData';
if not CompareFlags(sTag, e, o, 'ACBS\Template Flags', 'Use AI Data', False, False) then
ProcessTag(sTag, e, o);
sTag := 'Actors.AIPackages';
if not CompareFlags(sTag, e, o, 'ACBS\Template Flags', 'Use AI Packages', False, False) then
ProcessTag(sTag, e, o);
if sSignature = 'CREA' then
if not CompareFlags(sTag, e, o, 'ACBS\Template Flags', 'Use Model/Animation', False, False) then
ProcessTag('Actors.Anims', e, o);
if not CompareFlags(sTag, e, o, 'ACBS\Template Flags', 'Use Traits', False, False) then
begin
ProcessTag('Actors.CombatStyle', e, o);
ProcessTag('Actors.DeathItem', e, o);
end;
sTag := 'Actors.Skeleton';
if not CompareFlags(sTag, e, o, 'ACBS\Template Flags', 'Use Model/Animation', False, False) then
ProcessTag(sTag, e, o);
sTag := 'Actors.Stats';
if not CompareFlags(sTag, e, o, 'ACBS\Template Flags', 'Use Stats', False, False) then
ProcessTag(sTag, e, o);
// TODO: IIM - NOT IMPLEMENTED
// TODO: MustBeActiveIfImported - NOT IMPLEMENTED
if sSignature = 'NPC_' then
begin
sTag := 'NPC.Class';
if not CompareFlags(sTag, e, o, 'ACBS\Template Flags', 'Use Traits', False, False) then
ProcessTag(sTag, e, o);
sTag := 'NPC.Race';
if not CompareFlags(sTag, e, o, 'ACBS\Template Flags', 'Use Traits', False, False) then
ProcessTag(sTag, e, o);
sTag := 'NpcFaces';
if not CompareFlags(sTag, e, o, 'ACBS\Template Flags', 'Use Model/Animation', False, False) then
ProcessTag(sTag, e, o);
end;
sTag := 'Scripts';
if not CompareFlags(sTag, e, o, 'ACBS\Template Flags', 'Use Script', False, False) then
ProcessTag(sTag, e, o);
end;
if sSignature = 'CELL' then
begin
ProcessTag('C.Acoustic', e, o);
ProcessTag('C.Encounter', e, o);
ProcessTag('C.ImageSpace', e, o);
end;
if sSignature = 'RACE' then
begin
ProcessTag('Body-F', e, o);
ProcessTag('Body-M', e, o);
ProcessTag('Body-Size-F', e, o);
ProcessTag('Body-Size-M', e, o);
ProcessTag('Eyes', e, o);
ProcessTag('Hair', e, o);
ProcessTag('R.Description', e, o);
ProcessTag('R.Ears', e, o);
ProcessTag('R.Head', e, o);
ProcessTag('R.Mouth', e, o);
ProcessTag('R.Relations', e, o);
ProcessTag('R.Skills', e, o);
ProcessTag('R.Teeth', e, o);
ProcessTag('Voice-F', e, o);
ProcessTag('Voice-M', e, o);
end;
// TODO: ScriptContents - SHOULD NOT BE IMPLEMENTED
// -- According to the Wrye Bash Readme: "Should not be used. Can cause serious issues."
if InDelimitedList(sSignature, 'ACTI ALCH ARMO CONT DOOR FLOR FURN INGR KEYM LIGH LVLC MISC QUST WEAP', ' ') then
ProcessTag('Scripts', e, o);
end;
// -------------------------------------------------------------------------------
// GROUP: Supported tags exclusive to FO3, FNV, TES4, TES5, and SSE
// -------------------------------------------------------------------------------
if not wbIsFallout4 then
begin
if sSignature = 'CELL' then
begin
ProcessTag('C.Climate', e, o);
ProcessTag('C.Light', e, o);
ProcessTag('C.Music', e, o);
ProcessTag('C.Name', e, o);
ProcessTag('C.Owner', e, o);
ProcessTag('C.RecordFlags', e, o);
ProcessTag('C.Water', e, o);
end;
// TODO: Deactivate - NOT IMPLEMENTED
// TAG: Delev, Relev
if InDelimitedList(sSignature, 'LVLC LVLI LVLN LVSP', ' ') then
ProcessDelevRelevTags(e, o);
// TODO: Filter - NOT IMPLEMENTED
if InDelimitedList(sSignature, 'ACTI ALCH AMMO APPA ARMO BOOK BSGN CLAS CLOT DOOR FLOR FURN INGR KEYM LIGH MGEF MISC SGST SLGM WEAP', ' ') then
begin
ProcessTag('Graphics', e, o);
ProcessTag('Names', e, o);
ProcessTag('Stats', e, o);
if InDelimitedList(sSignature, 'ACTI DOOR LIGH MGEF', ' ') then
ProcessTag('Sound', e, o);
end;
if InDelimitedList(sSignature, 'CREA EFSH GRAS LSCR LTEX REGN STAT TREE', ' ') then
ProcessTag('Graphics', e, o);
if sSignature = 'CONT' then
begin
ProcessTag('Invent', e, o);
ProcessTag('Names', e, o);
ProcessTag('Sound', e, o);
end;
if InDelimitedList(sSignature, 'DIAL ENCH EYES FACT HAIR QUST RACE SPEL WRLD', ' ') then
ProcessTag('Names', e, o);
// TODO: NoMerge - NOT IMPLEMENTED
if (sSignature = 'WTHR') then
ProcessTag('Sound', e, o);
// special handling for CREA and NPC_
if InDelimitedList(sSignature, 'CREA NPC_', ' ') then
begin
if wbIsOblivion then
begin
ProcessTag('Invent', e, o);
ProcessTag('Names', e, o);
if sSignature = 'CREA' then
ProcessTag('Sound', e, o);
end;
if not wbIsOblivion then
begin
sTag := 'Invent';
if not CompareFlags(sTag, e, o, 'ACBS\Template Flags', 'Use Inventory', False, False) then
ProcessTag(sTag, e, o);
// special handling for CREA and NPC_ record types
sTag := 'Names';
if not CompareFlags(sTag, e, o, 'ACBS\Template Flags', 'Use Base Data', False, False) then
ProcessTag(sTag, e, o);
// special handling for CREA record type
sTag := 'Sound';
if sSignature = 'CREA' then
if not CompareFlags(sTag, e, o, 'ACBS\Template Flags', 'Use Model/Animation', False, False) then
ProcessTag(sTag, e, o);
end;
end;
end;
// ObjectBounds
sTag := 'ObjectBounds';
if wbIsFallout3 then
if InDelimitedList(sSignature, 'ACTI ADDN ALCH AMMO ARMA ARMO ASPC BOOK COBJ CONT CREA DOOR EXPL FURN GRAS IDLM INGR KEYM LIGH LVLC LVLI LVLN MISC MSTT NOTE NPC_ PROJ PWAT SCOL SOUN STAT TACT TERM TREE TXST WEAP', ' ') then
ProcessTag(sTag, e, o);
if wbIsFalloutNV then
if InDelimitedList(sSignature, 'ACTI ADDN ALCH AMMO ARMA ARMO ASPC BOOK CCRD CHIP CMNY COBJ CONT CREA DOOR EXPL FURN GRAS IDLM IMOD INGR KEYM LIGH LVLC LVLI LVLN MISC MSTT NOTE NPC_ PROJ PWAT SCOL SOUN STAT TACT TERM TREE TXST WEAP', ' ') then
ProcessTag(sTag, e, o);
if wbIsSkyrim then
if InDelimitedList(sSignature, 'ACTI ADDN ALCH AMMO APPA ARMO ARTO ASPC BOOK CONT DOOR DUAL ENCH EXPL FLOR FURN GRAS HAZD IDLM INGR KEYM LIGH LVLI LVLN LVSP MISC MSTT NPC_ PROJ SCRL SLGM SOUN SPEL STAT TACT TREE TXST WEAP', ' ') then
ProcessTag(sTag, e, o);
if wbIsFallout4 then
if InDelimitedList(sSignature, 'LVLI LVLN', ' ') then
ProcessTag(sTag, e, o);
// Text
if not wbIsFallout4 then
begin
sTag := 'Text';
if wbIsOblivion then
if InDelimitedList(sSignature, 'BOOK BSGN CLAS LSCR MGEF SKIL', ' ') then
ProcessTag(sTag, e, o);
if wbIsFallout3 then
if InDelimitedList(sSignature, 'AVIF BOOK CLAS LSCR MESG MGEF NOTE PERK TERM', ' ') then
ProcessTag(sTag, e, o);
if wbIsFalloutNV then
if InDelimitedList(sSignature, 'AVIF BOOK CHAL CLAS IMOD LSCR MESG MGEF NOTE PERK TERM', ' ') then
ProcessTag(sTag, e, o);
if wbIsSkyrim then
if InDelimitedList(sSignature, 'ALCH AMMO APPA ARMO AVIF BOOK CLAS LSCR MESG MGEF SCRL SHOU SPEL WEAP', ' ') then
ProcessTag(sTag, e, o);
end;
end;
function Finalize: Integer;
begin
if not Assigned(kFile) then
begin
LogInfo('Script execution was aborted.' + #13#10);
exit;
end;
slLog.Free;
slSuggestedTags.Free;
slExistingTags.Free;
slDifferentTags.Free;
slBadTags.Free;
slMasterPlugins.Free;
end;
function StrToBool(s: String): Boolean;
begin
if (s <> '0') and (s <> '1') then
Result := nil
else
if (s = '1') then
Result := True
else
Result := False;
end;
function InDelimitedList(asNeedle: String; asHaystack: String; asDelimiter: String): Boolean;
var
a: TStringDynArray;
i: Integer;
begin
Result := False;
a := SplitString(asHaystack, asDelimiter);
for i := 0 to Pred(Length(a)) do
if SameText(asNeedle, a[i]) then
begin
Result := True;
break;
end;
end;
function RegExMatch(asPattern: String; asSubject: String): String;
var
re: TPerlRegEx;
begin
Result := nil;
re := TPerlRegEx.Create;
try
re.RegEx := asPattern;
re.Options := [];
re.Subject := asSubject;
if re.Match then
Result := re.MatchedText;
finally
re.Free;
end;
end;
function RemoveFromEnd(asSource: String; asSubstring: String): String;
begin
Result := asSource;
if EndsText(asSource, asSubstring) then
Result := Copy(asSource, 1, Length(asSource) - Length(asSubstring));
end;
function SortKeyEx(const akElement : IInterface) : string;
var
kElement: IInterface;
i: Integer;
begin
Result := GetEditValue(akElement);
for i := 0 to Pred(ElementCount(akElement)) do
begin
kElement := ElementByIndex(akElement, i);
if SameText(Name(kElement), 'unknown') or SameText(Name(kElement), 'unused') then
continue;
if Result <> '' then
Result := Result + ' ' + SortKeyEx(kElement)
else
Result := SortKeyEx(kElement);
end;
end;
function CompareAssignment(asTag: String; e, m: IInterface): Boolean;
var
bAssignedE : Boolean;
bAssignedM : Boolean;
begin
if TagExists(asTag) then
exit;
Result := False;
bAssignedE := Assigned(e);
bAssignedM := Assigned(m);
if (not bAssignedE and not bAssignedM)
or (bAssignedE and bAssignedM) then
exit;
if bAssignedE <> bAssignedM then
begin
if optionOutputLog = mrYes then
AddLogEntry(asTag, 'Assigned', e, m);
AddTag(asTag);
Result := True;
end;
end;
function CompareElementCount(asTag: String; e, m: IInterface): Boolean;
var
iCountE : Integer;
iCountM : Integer;
begin
if TagExists(asTag) then
exit;
Result := False;
iCountE := ElementCount(e);
iCountM := ElementCount(m);
if iCountE = iCountM then
exit;
if iCountE <> iCountM then
begin
if optionOutputLog = mrYes then
AddLogEntry(asTag, 'ElementCount', e, m);
AddTag(asTag);
Result := True;
end;
end;
function CompareEditValue(asTag: String; e, m: IInterface): Boolean;
var
sValueE : String;
sValueM : String;
begin
if TagExists(asTag) then
exit;
Result := False;
sValueE := GetEditValue(e);
sValueM := GetEditValue(m);
if SameText(sValueE, sValueM) then
exit;
if not SameText(sValueE, sValueM) then
begin
if optionOutputLog = mrYes then
AddLogEntry(asTag, 'GetEditValue', e, m);
AddTag(asTag);
Result := True;
end;
end;
function CompareFlags(asTag: String; e, m: IInterface; asPath, asFlagName: String; bAddTag, bOperation: Boolean): Boolean;
var
x : IInterface;
y : IInterface;
a : IInterface;
b : IInterface;
sa : String;
sb : String;
sTestName : String;
bResult : Boolean;
begin
if TagExists(asTag) then
exit;
Result := False;
// flags arrays
x := ElementByPath(e, asPath);
y := ElementByPath(m, asPath);
// individual flags
a := ElementByName(x, asFlagName);
b := ElementByName(y, asFlagName);
// individual flag edit values
sa := GetEditValue(a);
sb := GetEditValue(b);
if bOperation then
bResult := not SameText(sa, sb) // only used for Behave Like Exterior, Use Sky Lighting, and Has Water
else
bResult := StrToBool(sa) or StrToBool(sb);
if bAddTag and bResult then
begin
if bOperation then
sTestName := 'CompareFlags:NOT'
else
sTestName := 'CompareFlags:OR';
if optionOutputLog = mrYes then
AddLogEntry(asTag, sTestName, x, y);
AddTag(asTag);
end;
Result := bResult;
end;
function CompareKeys(asTag: String; e, m: IInterface): Boolean;
var
bResult : Boolean;
sKeyE : String;
sKeyM : String;
ConflictState : TConflictThis;
begin
if TagExists(asTag) then
exit;
Result := False;
ConflictState := ConflictAllForMainRecord(ContainingMainRecord(e));
if (ConflictState = caUnknown)
or (ConflictState = caOnlyOne)
or (ConflictState = caNoConflict) then
exit;
sKeyE := SortKeyEx(e);
sKeyM := SortKeyEx(m);
// empty check
if (IsEmptyKey(sKeyE) and IsEmptyKey(sKeyM))
or SameText(sKeyE, sKeyM) then
exit;
// case sensitive comparison
if not SameText(sKeyE, sKeyM) then
begin
if optionOutputLog = mrYes then
AddLogEntry(asTag, 'CompareKeys', e, m);
AddTag(asTag);
Result := True;
end;
end;
function CompareNativeValues(asTag: String; e, m: IInterface; asPath: String): Boolean;
var
x : IInterface;
y : IInterface;
begin
if TagExists(asTag) then
exit;
Result := False;
x := ElementByPath(e, asPath);
y := ElementByPath(m, asPath);
if GetNativeValue(x) = GetNativeValue(y) then
exit;
if GetNativeValue(x) <> GetNativeValue(y) then
begin
if optionOutputLog = mrYes then
AddLogEntry(asTag, 'CompareNativeValues', e, m);
AddTag(asTag);
Result := True;
end;
end;
function HighestOverrideOrSelfInList(akMainRecord: IInterface; aiMaxLoadOrder: Integer; aslMasterPlugins: TStringList): IInterface;
var
kMaster : IwbMainRecord;
kFile : IwbFile;
sFileName : String;
i : Integer;
begin
Result := akMainRecord;
kMaster := MasterOrSelf(akMainRecord);
for i := Pred(OverrideCount(akMainRecord)) downto 0 do
begin
kFile := GetFile(OverrideByIndex(kMaster, i));
sFileName := GetFileName(kFile);
// skip plugins that aren't masters because we don't care about them
if aslMasterPlugins.IndexOf(sFileName) = -1 then
continue;
if GetLoadOrder(kFile) <= aiMaxLoadOrder then
begin
Result := OverrideByIndex(kMaster, i);
exit;
end;
end;
end;
function SortedArrayElementByValue(e: IInterface; sPath, sValue: String): IInterface;
var
i: Integer;
kEntry: IInterface;
begin
Result := nil;
for i := 0 to ElementCount(e) - 1 do
begin
kEntry := ElementByIndex(e, i);
if SameText(GetElementEditValues(kEntry, sPath), sValue) then
begin
Result := kEntry;
exit;
end;
end;
end;
function Diff(lsList1, lsList2: TStringList): TStringList;
var
i : Integer;
tmp : TStringList;
begin
tmp := TStringList.Create;
for i := 0 to lsList1.Count - 1 do
if lsList2.IndexOf(lsList1[i]) < 0 then
tmp.Add(lsList1[i]);
Result := tmp;
end;
// TODO: speed this up!
function IsEmptyKey(asSortKey: String): Boolean;
var
i : Integer;
begin
Result := True;
for i := 1 to Length(asSortKey) do
if asSortKey[i] = '1' then
begin
Result := False;
exit;
end;
end;
function FormatTags(aslTags: TStringList; asSingular, asPlural, asNull: String): String;
var
iTagCount : Integer;
sTagCount : String;
begin
iTagCount := aslTags.Count;
sTagCount := IntToStr(iTagCount);
if iTagCount = 1 then
Result := sTagCount + ' ' + asSingular + #13#10#32#32#32#32#32#32
else
if iTagCount > 1 then
Result := sTagCount + ' ' + asPlural + #13#10#32#32#32#32#32#32;
if iTagCount > 0 then
Result := Result + Format(' {{BASH:%s}}', [aslTags.DelimitedText])
else
Result := asNull;
end;
function TagExists(asTag: String): Boolean;
begin
Result := (slSuggestedTags.IndexOf(asTag) <> -1);
end;
procedure AddTag(asTag: String);
begin
if not TagExists(asTag) then
slSuggestedTags.Add(asTag);
end;
procedure Evaluate(asTag: String; e, m: IInterface);
begin
// exit if the tag already exists
if TagExists(asTag) then
exit;
// Suggest tag if one element exists while the other does not
if CompareAssignment(asTag, e, m) then
exit;
// exit if the first element does not exist
if not Assigned(e) then
exit;
// suggest tag if the two elements are different
if CompareElementCount(asTag, e, m) then
exit;
// suggest tag if the edit values of the two elements are different
if CompareEditValue(asTag, e, m) then
exit;
// compare any number of elements with CompareKeys
if CompareKeys(asTag, e, m) then
exit;
end;
procedure EvaluateByPath(asTag: String; e, m: IInterface; asPath: String);
var
x : IInterface;
y : IInterface;
begin
x := ElementByPath(e, asPath);
y := ElementByPath(m, asPath);
Evaluate(asTag, x, y);
end;
procedure ProcessTag(asTag: String; e, m: IInterface);
var
x : IInterface;
y : IInterface;
a : IInterface;
b : IInterface;
j : IInterface;
k : IInterface;
sElement : String;
sSignature : String;
begin
if TagExists(asTag) then
exit;
sSignature := Signature(e);
// Bookmark: Actors.ACBS
if asTag = 'Actors.ACBS' then
begin
// assign ACBS elements
sElement := 'ACBS';
x := ElementBySignature(e, sElement);
y := ElementBySignature(m, sElement);
// evaluate Flags if the Use Base Data flag is not set
sElement := 'Flags';
a := ElementByName(x, sElement);
b := ElementByName(y, sElement);
if wbIsOblivion then
if CompareKeys(asTag, a, b) then
exit;
if not wbIsOblivion then
if not CompareFlags(asTag, x, y, 'Template Flags', 'Use Base Data', False, False) then
if CompareKeys(asTag, a, b) then
exit;
// evaluate properties
EvaluateByPath(asTag, x, y, 'Fatigue');
EvaluateByPath(asTag, x, y, 'Level');
EvaluateByPath(asTag, x, y, 'Calc min');
EvaluateByPath(asTag, x, y, 'Calc max');
EvaluateByPath(asTag, x, y, 'Speed Multiplier');
EvaluateByPath(asTag, e, m, 'DATA\Base Health');
// evaluate Barter Gold if the Use AI Data flag is not set
sElement := 'Barter gold';
if wbIsOblivion then
EvaluateByPath(asTag, x, y, sElement)
else
if not CompareFlags(asTag, x, y, 'Template Flags', 'Use AI Data', False, False) then
EvaluateByPath(asTag, x, y, sElement);
end;
// Bookmark: Actors.AIData
if asTag = 'Actors.AIData' then
begin
// assign AIDT elements
sElement := 'AIDT';
x := ElementBySignature(e, sElement);
y := ElementBySignature(m, sElement);
// evaluate AIDT properties
EvaluateByPath(asTag, x, y, 'Aggression');
EvaluateByPath(asTag, x, y, 'Confidence');
EvaluateByPath(asTag, x, y, 'Energy level');
EvaluateByPath(asTag, x, y, 'Responsibility');
EvaluateByPath(asTag, x, y, 'Teaches');
EvaluateByPath(asTag, x, y, 'Maximum training level');
// check flags for Buys/Sells and Services
if CompareNativeValues(asTag, x, y, 'Buys/Sells and Services') then
exit;
end;
// Bookmark: Actors.AIPackages
if asTag = 'Actors.AIPackages' then
EvaluateByPath(asTag, e, m, 'Packages');
// Bookmark: Actors.Anims
if asTag = 'Actors.Anims' then
EvaluateByPath(asTag, e, m, 'KFFZ');
// Bookmark: Actors.CombatStyle
if asTag = 'Actors.CombatStyle' then
EvaluateByPath(asTag, e, m, 'ZNAM');
// Bookmark: Actors.DeathItem
if asTag = 'Actors.DeathItem' then
EvaluateByPath(asTag, e, m, 'INAM');
// Bookmark: Actors.Skeleton
if asTag = 'Actors.Skeleton' then
begin
// assign Model elements
sElement := 'Model';
x := ElementByName(e, sElement);
y := ElementByName(m, sElement);
// exit if the Model property does not exist in the control record
if not Assigned(x) then
exit;
// evaluate properties
EvaluateByPath(asTag, x, y, 'MODL');
EvaluateByPath(asTag, x, y, 'MODB');
EvaluateByPath(asTag, x, y, 'MODT');
end;
// Bookmark: Actors.Spells
if asTag = 'Actors.Spells' then
EvaluateByPath(asTag, e, m, 'Spells');
// Bookmark: Actors.Stats
if asTag = 'Actors.Stats' then
begin
// assign DATA elements
sElement := 'DATA';
x := ElementBySignature(e, sElement);
y := ElementBySignature(m, sElement);
// evaluate CREA properties
if sSignature = 'CREA' then
begin
EvaluateByPath(asTag, x, y, 'Health');
EvaluateByPath(asTag, x, y, 'Combat Skill');
EvaluateByPath(asTag, x, y, 'Magic Skill');
EvaluateByPath(asTag, x, y, 'Stealth Skill');
EvaluateByPath(asTag, x, y, 'Attributes');
end;
// evaluate NPC_ properties
if sSignature = 'NPC_' then
begin
EvaluateByPath(asTag, x, y, 'Base Health');
EvaluateByPath(asTag, x, y, 'Attributes');
EvaluateByPath(asTag, e, m, 'DNAM\Skill Values');
EvaluateByPath(asTag, e, m, 'DNAM\Skill Offsets');
end;
end;
// Bookmark: Body-F
if asTag = 'Body-F' then
EvaluateByPath(asTag, e, m, 'Body Data\Female Body Data\Parts');
// Bookmark: Body-M
if asTag = 'Body-M' then
EvaluateByPath(asTag, e, m, 'Body Data\Male Body Data\Parts');
// Bookmark: Body-Size-F
if asTag = 'Body-Size-F' then
begin
EvaluateByPath(asTag, e, m, 'DATA\Female Height');
EvaluateByPath(asTag, e, m, 'DATA\Female Weight');
end;
// Bookmark: Body-Size-M
if asTag = 'Body-Size-M' then
begin
EvaluateByPath(asTag, e, m, 'DATA\Male Height');
EvaluateByPath(asTag, e, m, 'DATA\Male Weight');
end;
// Bookmark: C.Acoustic
if asTag = 'C.Acoustic' then
EvaluateByPath(asTag, e, m, 'XCAS');
// Bookmark: C.Climate
if asTag = 'C.Climate' then
begin
// add tag if the Behave Like Exterior flag is set ine one record but not the other
if CompareFlags(asTag, e, m, 'DATA', 'Behave Like Exterior', True, True) then
exit;
// evaluate additional property
EvaluateByPath(asTag, e, m, 'XCCM');
end;
// Bookmark: C.Encounter
if asTag = 'C.Encounter' then
EvaluateByPath(asTag, e, m, 'XEZN');
// Bookmark: C.ImageSpace
if asTag = 'C.ImageSpace' then
EvaluateByPath(asTag, e, m, 'XCIM');
// Bookmark: C.Light
if asTag = 'C.Light' then
EvaluateByPath(asTag, e, m, 'XCLL');
// Bookmark: C.Location
if asTag = 'C.Location' then
EvaluateByPath(asTag, e, m, 'XLCN');
// Bookmark: C.LockList
if asTag = 'C.LockList' then
EvaluateByPath(asTag, e, m, 'XILL');
// Bookmark: C.Music
if asTag = 'C.Music' then
EvaluateByPath(asTag, e, m, 'XCMO');
// Bookmark: FULL (C.Name, Names, SpellStats)
if (asTag = 'C.Name') or (asTag = 'Names') or (asTag = 'SpellStats') then
EvaluateByPath(asTag, e, m, 'FULL');
// Bookmark: C.Owner
if asTag = 'C.Owner' then
EvaluateByPath(asTag, e, m, 'Ownership');
// Bookmark: C.RecordFlags
if asTag = 'C.RecordFlags' then
begin
// store Record Flags elements
sElement := 'Record Header\Record Flags';
x := ElementByPath(e, sElement);
y := ElementByPath(m, sElement);
// compare Record Flags elements
if CompareKeys(asTag, x, y) then
exit;
end;
// Bookmark: C.Regions
if asTag = 'C.Regions' then
EvaluateByPath(asTag, e, m, 'XCLR');
// Bookmark: C.SkyLighting
if asTag = 'C.SkyLighting' then
// add tag if the Behave Like Exterior flag is set ine one record but not the other
if CompareFlags(asTag, e, m, 'DATA', 'Use Sky Lighting', True, True) then
exit;
// Bookmark: C.Water
if asTag = 'C.Water' then
begin
// add tag if Has Water flag is set in one record but not the other
if CompareFlags(asTag, e, m, 'DATA', 'Has Water', True, True) then
exit;
// exit if Is Interior Cell is set in either record
if CompareFlags(asTag, e, m, 'DATA', 'Is Interior Cell', False, False) then
exit;
// evaluate properties
EvaluateByPath(asTag, e, m, 'XCLW');
EvaluateByPath(asTag, e, m, 'XCWT');
end;
// Bookmark: Creatures.Blood
if asTag = 'Creatures.Blood' then
begin
EvaluateByPath(asTag, e, m, 'NAM0');
EvaluateByPath(asTag, e, m, 'NAM1');
end;
// Bookmark: Destructible
if asTag = 'Destructible' then
begin
// assign Destructable elements
sElement := 'Destructable';
x := ElementByName(e, sElement);
y := ElementByName(m, sElement);
if CompareAssignment(asTag, x, y) then
exit;
sElement := 'DEST';
a := ElementBySignature(x, sElement);
b := ElementBySignature(y, sElement);
// evaluate Destructable properties
EvaluateByPath(asTag, a, b, 'Health');
EvaluateByPath(asTag, a, b, 'Count');
EvaluateByPath(asTag, x, y, 'Stages');
// assign Destructable flags
if not wbIsSkyrim then
begin
sElement := 'Flags';
j := ElementByName(a, sElement);
k := ElementByName(b, sElement);
if Assigned(j) or Assigned(k) then
begin
// add tag if Destructable flags exist in one record
if CompareAssignment(asTag, j, k) then
exit;
// evaluate Destructable flags
if CompareKeys(asTag, j, k) then
exit;
end;
end;
end;
// Bookmark: Eyes
if asTag = 'Eyes' then
EvaluateByPath(asTag, e, m, 'ENAM');
// Bookmark: Factions
if asTag = 'Factions' then
begin
// assign Factions properties
x := ElementByName(e, asTag);
y := ElementByName(m, asTag);
// add tag if the Factions properties differ
if CompareAssignment(asTag, x, y) then
exit;
// exit if the Factions property in the control record does not exist
if not Assigned(x) then
exit;
// evaluate Factions properties
if CompareKeys(asTag, x, y) then
exit;
end;
// Bookmark: Graphics
if asTag = 'Graphics' then
begin
// evaluate Icon and Model properties
if InDelimitedList(sSignature, 'ALCH AMMO APPA BOOK INGR KEYM LIGH MGEF MISC SGST SLGM TREE WEAP', ' ') then
begin
EvaluateByPath(asTag, e, m, 'Icon');
EvaluateByPath(asTag, e, m, 'Model');
end;
// evaluate Icon properties
if InDelimitedList(sSignature, 'BSGN CLAS LSCR LTEX REGN', ' ') then
EvaluateByPath(asTag, e, m, 'Icon');
// evaluate Model properties
if InDelimitedList(sSignature, 'ACTI DOOR FLOR FURN GRAS STAT', ' ') then
EvaluateByPath(asTag, e, m, 'Model');
// evaluate ARMO properties
if sSignature = 'ARMO' then
begin
// Shared
EvaluateByPath(asTag, e, m, 'Male world model');
EvaluateByPath(asTag, e, m, 'Female world model');
// ARMO - Oblivion
if wbIsOblivion then
begin
// evaluate Icon properties
EvaluateByPath(asTag, e, m, 'Icon');
EvaluateByPath(asTag, e, m, 'Icon 2 (female)');
// assign First Person Flags elements
sElement := 'BODT\First Person Flags';
x := ElementByPath(e, sElement);
if not Assigned(x) then
exit;
y := ElementByPath(m, sElement);
// evaluate First Person Flags
if CompareKeys(asTag, x, y) then
exit;
// assign General Flags elements
sElement := 'BODT\General Flags';
x := ElementByPath(e, sElement);
if not Assigned(x) then
exit;
y := ElementByPath(m, sElement);
// evaluate General Flags
if CompareKeys(asTag, x, y) then
exit;
end;
// ARMO - FO3, FNV
if wbIsFallout3 or wbIsFalloutNV then
begin
// evaluate Icon properties
EvaluateByPath(asTag, e, m, 'ICON');
EvaluateByPath(asTag, e, m, 'ICO2');
// assign First Person Flags elements
sElement := 'BMDT\Biped Flags';
x := ElementByPath(e, sElement);
if not Assigned(x) then
exit;
y := ElementByPath(m, sElement);
// evaluate First Person Flags
if CompareKeys(asTag, x, y) then
exit;
// assign General Flags elements
sElement := 'BMDT\General Flags';
x := ElementByPath(e, sElement);
if not Assigned(x) then
exit;
y := ElementByPath(m, sElement);
// evaluate General Flags
if CompareKeys(asTag, x, y) then
exit;
end;
// ARMO - TES5
if wbIsSkyrim then
begin
// evaluate Icon properties
EvaluateByPath(asTag, e, m, 'Icon');
EvaluateByPath(asTag, e, m, 'Icon 2 (female)');
// evaluate Biped Model properties
EvaluateByPath(asTag, e, m, 'Male world model');
EvaluateByPath(asTag, e, m, 'Female world model');
// assign First Person Flags elements
sElement := 'BOD2\First Person Flags';
x := ElementByPath(e, sElement);
if not Assigned(x) then
exit;
y := ElementByPath(m, sElement);
// evaluate First Person Flags
if CompareKeys(asTag, x, y) then
exit;
// assign General Flags elements
sElement := 'BOD2\General Flags';
x := ElementByPath(e, sElement);
if not Assigned(x) then
exit;
y := ElementByPath(m, sElement);
// evaluate General Flags
if CompareKeys(asTag, x, y) then
exit;
end;
end;
// evaluate CREA properties
if sSignature = 'CREA' then
begin
EvaluateByPath(asTag, e, m, 'NIFZ');
EvaluateByPath(asTag, e, m, 'NIFT');
end;
// evaluate EFSH properties
if sSignature = 'EFSH' then
begin
// evaluate Record Flags
sElement := 'Record Header\Record Flags';
x := ElementByPath(e, sElement);
y := ElementByPath(m, sElement);
if CompareKeys(asTag, x, y) then
exit;
// evaluate Icon properties
EvaluateByPath(asTag, e, m, 'ICON');
EvaluateByPath(asTag, e, m, 'ICO2');
// evaluate other properties
EvaluateByPath(asTag, e, m, 'NAM7');
if wbIsSkyrim then
begin
EvaluateByPath(asTag, e, m, 'NAM8');
EvaluateByPath(asTag, e, m, 'NAM9');
end;
EvaluateByPath(asTag, e, m, 'DATA');
end;
// evaluate MGEF properties
if wbIsSkyrim then
if sSignature = 'MGEF' then
begin
EvaluateByPath(asTag, e, m, 'Magic Effect Data\DATA\Casting Light');
EvaluateByPath(asTag, e, m, 'Magic Effect Data\DATA\Hit Shader');
EvaluateByPath(asTag, e, m, 'Magic Effect Data\DATA\Enchant Shader');
end;
// evaluate Material property
if sSignature = 'STAT' then
EvaluateByPath(asTag, e, m, 'DNAM\Material');
end;
// Bookmark: Hair
if asTag = 'Hair' then
EvaluateByPath(asTag, e, m, 'HNAM');
// Bookmark: Invent
if asTag = 'Invent' then
begin
// assign Items properties
sElement := 'Items';
x := ElementByName(e, sElement);
y := ElementByName(m, sElement);
// add tag if Items properties exist in one record but not the other
if CompareAssignment(asTag, x, y) then
exit;
// exit if Items property does not exist in control record
if not Assigned(x) then
exit;
// Items are sorted, so we don't need to compare by individual item
// SortKey combines all the items data
if CompareKeys(asTag, x, y) then
exit;
end;
// Bookmark: Keywords
if asTag = 'Keywords' then
begin
x := ElementBySignature(e, 'KWDA');
y := ElementBySignature(m, 'KWDA');
if CompareAssignment(asTag, x, y) then
exit;
if CompareElementCount(asTag, x, y) then
exit;
x := ElementBySignature(e, 'KSIZ');
y := ElementBySignature(m, 'KSIZ');
if CompareAssignment(asTag, x, y) then
exit;
if CompareEditValue(asTag, x, y) then
exit;
end;
// Bookmark: NPC.Class
if asTag = 'NPC.Class' then
EvaluateByPath(asTag, e, m, 'CNAM');
// Bookmark: NPC.Race
if asTag = 'NPC.Race' then
EvaluateByPath(asTag, e, m, 'RNAM');
// Bookmark: NpcFaces
if asTag = 'NpcFaces' then
begin
EvaluateByPath(asTag, e, m, 'HNAM');
EvaluateByPath(asTag, e, m, 'LNAM');
EvaluateByPath(asTag, e, m, 'ENAM');
EvaluateByPath(asTag, e, m, 'HCLR');
EvaluateByPath(asTag, e, m, 'FaceGen Data');
end;
// Bookmark: ObjectBounds
if asTag = 'ObjectBounds' then
EvaluateByPath(asTag, e, m, 'OBND');
// Bookmark: R.Attributes-F
if asTag = 'R.Attributes-F' then
EvaluateByPath(asTag, e, m, 'ATTR\Female');
// Bookmark: R.Attributes-M
if asTag = 'R.Attributes-M' then
EvaluateByPath(asTag, e, m, 'ATTR\Male');
// Bookmark: R.ChangeSpells
if asTag = 'R.ChangeSpells' then
EvaluateByPath(asTag, e, m, 'Spells');
// Bookmark: R.Description
if asTag = 'R.Description' then
EvaluateByPath(asTag, e, m, 'DESC');
// Bookmark: R.Ears
if asTag = 'R.Ears' then
begin
EvaluateByPath(asTag, e, m, 'Head Data\Male Head Data\Parts\[1]');
EvaluateByPath(asTag, e, m, 'Head Data\Female Head Data\Parts\[1]');
end;
// Bookmark: R.Head
if asTag = 'R.Head' then
begin
EvaluateByPath(asTag, e, m, 'Head Data\Male Head Data\Parts\[0]');
EvaluateByPath(asTag, e, m, 'Head Data\Female Head Data\Parts\[0]');
EvaluateByPath(asTag, e, m, 'FaceGen Data');
end;
// Bookmark: R.Mouth
if asTag = 'R.Mouth' then
begin
EvaluateByPath(asTag, e, m, 'Head Data\Male Head Data\Parts\[2]');
EvaluateByPath(asTag, e, m, 'Head Data\Female Head Data\Parts\[2]');
end;
// Bookmark: R.Relations
if asTag = 'R.Relations' then
EvaluateByPath(asTag, e, m, 'Relations');
// Bookmark: R.Skills
if asTag = 'R.Skills' then
EvaluateByPath(asTag, e, m, 'DATA\Skill Boosts');
// Bookmark: R.Teeth
if asTag = 'R.Teeth' then
begin
EvaluateByPath(asTag, e, m, 'Head Data\Male Head Data\Parts\[3]');
EvaluateByPath(asTag, e, m, 'Head Data\Female Head Data\Parts\[3]');
// FO3
if wbIsFallout3 then
begin
EvaluateByPath(asTag, e, m, 'Head Data\Male Head Data\Parts\[4]');
EvaluateByPath(asTag, e, m, 'Head Data\Female Head Data\Parts\[4]');
end;
end;
// Bookmark: Relations
if asTag = 'Relations' then
EvaluateByPath(asTag, e, m, 'Relations');
// Bookmark: Roads
if asTag = 'Roads' then
EvaluateByPath(asTag, e, m, 'PGRP');
// Bookmark: Scripts
if asTag = 'Scripts' then
EvaluateByPath(asTag, e, m, 'SCRI');
// Bookmark: Sound
if asTag = 'Sound' then
begin
// Activators, Containers, Doors, and Lights
if (sSignature = 'ACTI')
or (sSignature = 'CONT')
or (sSignature = 'DOOR')
or (sSignature = 'LIGH') then
begin
EvaluateByPath(asTag, e, m, 'SNAM');
// Activators
if sSignature = 'ACTI' then
EvaluateByPath(asTag, e, m, 'VNAM');
// Containers
if sSignature = 'CONT' then
begin
EvaluateByPath(asTag, e, m, 'QNAM');
if not wbIsSkyrim and not wbIsFallout3 then
EvaluateByPath(asTag, e, m, 'RNAM'); // FO3, TESV, and SSE don't have this element
end;
// Doors
if sSignature = 'DOOR' then
begin
EvaluateByPath(asTag, e, m, 'ANAM');
EvaluateByPath(asTag, e, m, 'BNAM');
end;
end;
// Creatures
if sSignature = 'CREA' then
begin
EvaluateByPath(asTag, e, m, 'WNAM');
EvaluateByPath(asTag, e, m, 'CSCR');
EvaluateByPath(asTag, e, m, 'Sound Types');
end;
// Magic Effects
if sSignature = 'MGEF' then
begin
// TES5, SSE
if wbIsSkyrim then
EvaluateByPath(asTag, e, m, 'SNDD');
// FO3, FNV, TES4
if not wbIsSkyrim then
begin
EvaluateByPath(asTag, e, m, 'DATA\Effect sound');
EvaluateByPath(asTag, e, m, 'DATA\Bolt sound');
EvaluateByPath(asTag, e, m, 'DATA\Hit sound');
EvaluateByPath(asTag, e, m, 'DATA\Area sound');
end;
end;
// Weather
if sSignature = 'WTHR' then
EvaluateByPath(asTag, e, m, 'Sounds');
end;
// Bookmark: SpellStats
if asTag = 'SpellStats' then
EvaluateByPath(asTag, e, m, 'SPIT');
// Bookmark: Stats
if asTag = 'Stats' then
begin
if InDelimitedList(sSignature, 'ALCH AMMO APPA ARMO BOOK CLOT INGR KEYM LIGH MISC SGST SLGM WEAP', ' ') then
begin
EvaluateByPath(asTag, e, m, 'EDID');
EvaluateByPath(asTag, e, m, 'DATA');
if InDelimitedList(sSignature, 'ARMO WEAP', ' ') then
EvaluateByPath(asTag, e, m, 'DNAM');
if sSignature = 'WEAP' then
EvaluateByPath(asTag, e, m, 'CRDT');
end;
if sSignature = 'ARMA' then
EvaluateByPath(asTag, e, m, 'DNAM');
end;
// Bookmark: Text
if asTag = 'Text' then
begin
if InDelimitedList(sSignature, 'ALCH AMMO APPA ARMO AVIF BOOK BSGN CHAL CLAS IMOD LSCR MESG MGEF PERK SCRL SHOU SKIL SPEL TERM WEAP', ' ') then
EvaluateByPath(asTag, e, m, 'DESC');
if not wbIsOblivion then begin
if sSignature = 'BOOK' then
EvaluateByPath(asTag, e, m, 'CNAM');
if sSignature = 'MGEF' then
EvaluateByPath(asTag, e, m, 'DNAM');
if sSignature = 'NOTE' then
EvaluateByPath(asTag, e, m, 'TNAM');
end;
end;
// Bookmark: Voice-F
if asTag = 'Voice-F' then
EvaluateByPath(asTag, e, m, 'VTCK\Voice #1 (Female)');
// Bookmark: Voice-M
if asTag = 'Voice-M' then
EvaluateByPath(asTag, e, m, 'VTCK\Voice #0 (Male)');
// Bookmark: WeaponMods
if asTag = 'WeaponMods' then
EvaluateByPath(asTag, e, m, 'Weapon Mods');
end;
// Bookmark: Delev, Relev
procedure ProcessDelevRelevTags(e, m: IInterface);
var
kEntries : IInterface;
kEntriesMaster : IInterface;
kEntry : IInterface;
kEntryMaster : IInterface;
kCOED : IInterface; // extra data
kCOEDMaster : IInterface; // extra data
sElement : String;
sSortKey : String;
sSortKeyMaster : String;
sTag : String;
i : Integer;
j : Integer;
begin
// nothing to do if already tagged
if TagExists('Delev') and TagExists('Relev') then
exit;
// get Leveled List Entries
sElement := 'Leveled List Entries';
kEntries := ElementByName(e, sElement);
kEntriesMaster := ElementByName(m, sElement);
if not Assigned(kEntries)
or not Assigned(kEntriesMaster) then
exit;
// initalize count matched on reference entries
j := 0;
// iterate through all entries
for i := 0 to Pred(ElementCount(kEntries)) do
begin
sElement := 'LVLO\Reference';
kEntry := ElementByIndex(kEntries, i);
kEntryMaster := SortedArrayElementByValue(kEntriesMaster, sElement, GetElementEditValues(kEntry, sElement));
if Assigned(kEntryMaster) then
begin
Inc(j);
sTag := 'Relev';
if not TagExists(sTag) then
begin
if CompareNativeValues(sTag, kEntry, kEntryMaster, 'LVLO\Level')
or CompareNativeValues(sTag, kEntry, kEntryMaster, 'LVLO\Count') then
exit;
// Relev check for changed level, count, extra data
if not wbIsOblivion then
begin
sElement := 'COED';
kCOED := ElementBySignature(kEntry, sElement);
kCOEDMaster := ElementBySignature(kEntryMaster, sElement);
sSortKey := SortKeyEx(kCOED);
sSortKeyMaster := SortKeyEx(kCOEDMaster);
if not SameText(sSortKey, sSortKeyMaster) then
begin
if optionOutputLog = mrYes then
AddLogEntry(sTag, 'Assigned', sSortKey, sSortKeyMaster);
AddTag(sTag);
exit;
end;
end;
end;
end;
end;
// if number of matched entries less than in master list
sTag := 'Delev';
if not TagExists(sTag) then
if j < ElementCount(kEntriesMaster) then
begin
if optionOutputLog = mrYes then
AddLogEntry(sTag, 'ElementCount', kEntries, kEntriesMaster);
AddTag(sTag);
exit;
end;
end;
function AddLogEntry(asTag: String; asTestName: String; e, m: IInterface): String;
var
sPrefix : String;
sString : String;
begin
if optionOutputLog = mrNo then
exit;
sPrefix := '(' + asTestName + ' Test)' + ' ' + asTag + ': ';
slLog.Add(sPrefix + PathName(m));
slLog.Add(sPrefix + PathName(e));
end;
function FileByName(asFileName: String): IwbFile;
var
kFile : IwbFile;
i : Integer;
begin
Result := nil;
for i := 0 to Pred(FileCount) do
begin
kFile := FileByIndex(i);
if asFileName = GetFileName(kFile) then
begin
Result := kFile;
exit;
end;
end;
end;
procedure EscKeyHandler(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
if Key = 27 then
Sender.Close;
end;
procedure chkAddTagsClick(Sender: TObject);
begin
if optionAddTags = mrYes then
optionAddTags := mrNo
else
optionAddTags := mrYes;
end;
procedure chkLoggingClick(Sender: TObject);
begin
if optionOutputLog = mrYes then
optionOutputLog := mrNo
else
optionOutputLog := mrYes;
end;
function Configure(asCaption: String): IwbFile;
var
frm : TForm;
lblPlugins : TLabel;
chkAddTags : TCheckBox;
chkLogging : TCheckBox;
cbbPlugins : TComboBox;
btnCancel : TButton;
btnOk : TButton;
i : Integer;
kFile : IwbFile;
begin
Result := nil;
frm := TForm.Create(TForm(frmMain));
try
frm.Caption := asCaption;
frm.BorderStyle := bsToolWindow;
frm.ClientWidth := 234 * scaleFactor;
frm.ClientHeight := 154 * scaleFactor;
frm.Position := poScreenCenter;
frm.KeyPreview := True;
frm.OnKeyDown := EscKeyHandler;
lblPlugins := TLabel.Create(frm);
lblPlugins.Parent := frm;
lblPlugins.Left := 16 * scaleFactor;
lblPlugins.Top := 64 * scaleFactor;
lblPlugins.Width := 200 * scaleFactor;
lblPlugins.Height := 16 * scaleFactor;
lblPlugins.Caption := 'Select file to analyze:';
lblPlugins.AutoSize := False;
chkAddTags := TCheckBox.Create(frm);
chkAddTags.Parent := frm;
chkAddTags.Left := 16 * scaleFactor;
chkAddTags.Top := 16 * scaleFactor;
chkAddTags.Width := 185 * scaleFactor;
chkAddTags.Height := 16 * scaleFactor;
chkAddTags.Caption := 'Write suggested tags to header';
chkAddTags.Checked := False;
chkAddTags.OnClick := chkAddTagsClick;
chkAddTags.TabOrder := 0;
chkLogging := TCheckBox.Create(frm);
chkLogging.Parent := frm;
chkLogging.Left := 16 * scaleFactor;
chkLogging.Top := 39 * scaleFactor;
chkLogging.Width := 185 * scaleFactor;
chkLogging.Height := 16 * scaleFactor;
chkLogging.Caption := 'Log test results to Messages tab';
chkLogging.Checked := True;
chkLogging.OnClick := chkLoggingClick;
chkLogging.TabOrder := 1;
cbbPlugins := TComboBox.Create(frm);
cbbPlugins.Parent := frm;
cbbPlugins.Left := 16 * scaleFactor;
cbbPlugins.Top := 85 * scaleFactor;
cbbPlugins.Width := 200 * scaleFactor;
cbbPlugins.Height := 21 * scaleFactor;
cbbPlugins.Style := csDropDownList;
cbbPlugins.DoubleBuffered := True;
cbbPlugins.TabOrder := 2;
for i := 0 to Pred(FileCount) do
begin
kFile := FileByIndex(i);
if IsEditable(kFile) then
cbbPlugins.Items.Add(GetFileName(kFile));
end;
cbbPlugins.ItemIndex := Pred(cbbPlugins.Items.Count);
btnOk := TButton.Create(frm);
btnOk.Parent := frm;
btnOk.Left := 62 * scaleFactor;
btnOk.Top := 120 * scaleFactor;
btnOk.Width := 75 * scaleFactor;
btnOk.Height := 25 * scaleFactor;
btnOk.Caption := 'Run';
btnOk.Default := True;
btnOk.ModalResult := mrOk;
btnOk.TabOrder := 3;
btnCancel := TButton.Create(frm);
btnCancel.Parent := frm;
btnCancel.Left := 143 * scaleFactor;
btnCancel.Top := 120 * scaleFactor;
btnCancel.Width := 75 * scaleFactor;
btnCancel.Height := 25 * scaleFactor;
btnCancel.Caption := 'Abort';
btnCancel.ModalResult := mrAbort;
btnCancel.TabOrder := 4;
if frm.ShowModal = mrOk then
Result := FileByName(cbbPlugins.Text);
finally
frm.Free;
end;
end;
end.
|
unit MTLLoader;
interface
uses Classes,
SysUtils,
StrUtils,
System.Math.Vectors,
Generics.Collections,
Shape,
Material,
Math,
Utils;
function LoadMTL(Stre: TDynStore; fileName: string) : TDictionary<string, TMaterial>;
implementation
function LoadMTL(Stre: TDynStore; fileName: string) : TDictionary<string, TMaterial>;
var
TxtF: TextFile;
SepL: TStringList;
SIdx: Cardinal;
Line: string;
CMnm: string;
CMtl: TMaterial;
begin
AssignFile(TxtF, fileName);
begin
try
Reset(TxtF);
except
raise Exception.Create('File not found: ' + fileName);
end;
end;
// Initilize Objects
SepL := TStringList.Create;
CMnm := '';
// Scan the file
while not Eof(TxtF) do
begin
Readln(TxtF, Line);
Split(' ', Line, SepL);
Result := TDictionary<string,TMaterial>.Create;
case IndexStr(SepL[0], ['newmtl', 'Kd', 'reflectiveness', 'opaqueness', 'refractive']) of
0:
begin
if CMnm <> '' then
begin
Result.Add(CMnm, CMtl);
end;
CMtl := TMaterial.Create(TVector.Zero, 0, 0, 0);
CMnm := SepL[1];
end;
1:
begin
CMtl.color := 255 * ParsVec3(SepL[1], SepL[2], SepL[3]);
end;
2:
begin
CMtl.reflective := StrToFloat(SepL[1]);
end;
3:
begin
CMtl.opaqueness := StrToFloat(SepL[1]);
end;
4:
begin
CMtl.refractive := StrToFloat(SepL[1]);
end;
end;
end;
if CMnm <> '' then
begin
Result.Add(CMnm, CMtl);
end;
CloseFile(TxtF);
end;
end.
|
unit uList64;
interface
uses
Generics.Collections,
SysUtils;
type
TList64 = class(TList<Int64>)
private
function GetMaxStatDateTime: TDateTime;
function GetMaxStatInt64: Int64;
function GetMaxStatInteger: Integer;
function GetMaxStatBoolean: Boolean;
function GetHasVarValues: Boolean;
public
function Add(Item: TDateTime): Integer; overload;
function Add(Item: Integer): Integer; overload;
function Add(Item: Boolean): Integer; overload;
property MaxStatInt64: Int64 read GetMaxStatInt64;
property MaxStatInteger: Integer read GetMaxStatInteger;
property MaxStatDateTime: TDateTime read GetMaxStatDateTime;
property MaxStatBoolean: Boolean read GetMaxStatBoolean;
property HasVarValues: Boolean read GetHasVarValues;
end;
implementation
{ TList64 }
function TList64.Add(Item: TDateTime): Integer;
var
Value: Int64;
begin
System.Move(Item, Value, SizeOf(TDateTime));
Result := Add(Value);
end;
function TList64.Add(Item: Integer): Integer;
var
Value: Int64;
begin
Value := Item;
Result := Add(Value);
end;
function TList64.Add(Item: Boolean): Integer;
var
Value: Int64;
begin
if Item then
Value := 1
else
Value := 0;
Result := Add(Value);
end;
function TList64.GetHasVarValues: Boolean;
var
FirstValue: Int64;
I: Integer;
begin
Result := False;
if Count = 0 then
Exit;
FirstValue := Self[0];
for I := 1 to Count - 1 do
if FirstValue <> Self[I] then
begin
Result := True;
Break;
end;
end;
function TList64.GetMaxStatInt64: Int64;
type
TDateStat = record
Value: Int64;
Count: Integer;
end;
TCompareArray = array of TDateStat;
var
I: Integer;
Stat: TCompareArray;
MaxC, MaxN: Integer;
procedure AddStat(Value: Int64);
var
J: Integer;
C: Integer;
begin
for J := 0 to Length(Stat) - 1 do
if Stat[J].Value = Value then
begin
Stat[J].Count := Stat[J].Count + 1;
Exit;
end;
C := Length(Stat);
SetLength(Stat, C + 1);
Stat[C].Value := Value;
Stat[C].Count := 1;
end;
begin
Result := 0;
if Count = 0 then
Exit;
SetLength(Stat, 0);
for I := 0 to Count - 1 do
AddStat(Self[I]);
MaxC := Stat[0].Count;
MaxN := 0;
for I := 0 to Length(Stat) - 1 do
if MaxC < Stat[I].Count then
begin
MaxC := Stat[I].Count;
MaxN := I;
end;
Result := Stat[MaxN].Value;
end;
function TList64.GetMaxStatDateTime: TDateTime;
var
MaxValue: Int64;
begin
MaxValue := MaxStatInt64;
System.Move(MaxValue, Result, SizeOf(TDateTime));
end;
function TList64.GetMaxStatInteger: Integer;
begin
Result := Integer(MaxStatInt64);
end;
function TList64.GetMaxStatBoolean: Boolean;
begin
Result := MaxStatInt64 <> 0;
end;
end.
|
Function SoNumero(Texto : String) : String;
//
// Filtra todos os numeros de uma string
//
var
Ind : Integer;
TmpRet : String;
begin
TmpRet := '';
for Ind := 1 to Length(Texto) do
begin
if IsDigit(Copy(Texto,Ind,1)) then
begin
TmpRet := TmpRet + Copy(Texto, Ind, 1);
end;
end;
Result := TmpRet;
end;
|
unit ibSHDataVCLTreeEditors;
interface
uses
Windows, Classes, Controls, Types, Messages, StdCtrls, DB, SysUtils,
Graphics, Buttons, ExtCtrls, DBCtrls, StrUtils, DBGridEh,
VirtualTrees, Forms,
SHDesignIntf, SHOptionsIntf, ibSHDesignIntf, ibSHDriverIntf,TntStdCtrls;
type
PTreeRec = ^TTreeRec;
TTreeRec = record
FieldNo: Integer;
Nullable: Boolean;
Computed: Boolean;
DefaultExpression: string;
CheckConstraint: string;
DataSource: TDataSource;
Field: TField;
DataType: string;
FieldDescription: string;
ImageIndex: Integer;
NodeHeight: Integer;
IsPicture: Boolean;
IsMultiLine: Boolean;
Component: TSHComponent;
FKFields: string;
ReferenceTable: string;
ReferenceFields: string;
end;
ISHTreeEditor = interface
['{088E9377-7BAD-438F-A145-85E8323C6829}']
function GetEditor: TWinControl; stdcall;
end;
TDataVCLFieldEditLink = class(TInterfacedObject, IVTEditLink, ISHTreeEditor)
private
FEdit: TWinControl; // One of the property editor classes.
// FEditButton: TEditButtonControlEh;
FTree: TVirtualStringTree; // A back reference to the tree calling.
FNode: PVirtualNode; // The node being edited.
FColumn: Integer; // The column of the node being edited.
protected
procedure EditKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure DoOnSetNULL(Sender: TObject);
public
destructor Destroy; override;
{ IVTEditLink }
function BeginEdit: Boolean; stdcall;
function CancelEdit: Boolean; stdcall;
function EndEdit: Boolean; stdcall;
function GetBounds: TRect; stdcall;
function PrepareEdit(Tree: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex): Boolean; stdcall;
procedure ProcessMessage(var Message: TMessage); stdcall;
procedure SetBounds(R: TRect); stdcall;
{ ISHTreeEditor }
function GetEditor: TWinControl; stdcall;
end;
TibSHEditForeignKeyPicker = class;
TibSHEditForeignKeyPickerForm = class(TCustomForm)
private
FTopPanel: TPanel;
FBottomPanel: TPanel;
FBtnOk: TButton;
FBtnCancel: TButton;
FDBGrid: TDBGridEh;
function GetEditForeignKeyPicker: TibSHEditForeignKeyPicker;
procedure WMActivate (var Message: TWMActivate); message WM_ACTIVATE;
protected
procedure Resize; override;
procedure CreateParams(var Params: TCreateParams); override;
procedure DoOnFormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property EditForeignKeyPicker: TibSHEditForeignKeyPicker
read GetEditForeignKeyPicker;
end;
TibSHEditForeignKeyPicker = class(TCustomPanel)
private
FEditButton: TSpeedButton;
FInputEdit: TEdit;
FReferenceTable: string;
FFields: TStrings;
FReferenceFields: TStrings;
FDataIntf: IibSHData;
FForm: TibSHEditForeignKeyPickerForm;
FDataSource: TDataSource;
FDRVDataset: TSHComponent;
FFieldName: string;
FSHCLDatabase: IibSHDatabase;
procedure SetFields(const Value: TStrings);
procedure SetReferenceFields(const Value: TStrings);
procedure SetReferenceTable(const Value: string);
procedure SetDataIntf(const Value: IibSHData);
procedure SetFormPos;
procedure WMWindowPosChanged(var Message: TWMWindowPosChanged); message WM_WINDOWPOSCHANGED;
procedure CreateDRV;
procedure FreeDRV;
function GetDRVDataset: IibSHDRVDataset;
protected
procedure Resize; override;
procedure VisibleChanging; override;
procedure ApplyGridFormatOptions(ADBGrid: TDBGridEh);
procedure DropDownGridPanel(Sender: TObject);
procedure DoOnOk(Sender: TObject);
procedure DoOnCancel(Sender: TObject);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property DataIntf: IibSHData read FDataIntf write SetDataIntf;
property DRVDataset: IibSHDRVDataset read GetDRVDataset;
property FieldName: string read FFieldName write FFieldName;
property Fields: TStrings read FFields write SetFields;
property InputEdit: TEdit read FInputEdit;
property ReferenceFields: TStrings read FReferenceFields write SetReferenceFields;
property ReferenceTable: string read FReferenceTable
write SetReferenceTable;
property SHCLDatabase: IibSHDatabase read FSHCLDatabase write FSHCLDatabase;
end;
implementation
uses ComCtrls;
{ TDataVCLFieldEditLink }
destructor TDataVCLFieldEditLink.Destroy;
begin
inherited;
end;
procedure TDataVCLFieldEditLink.EditKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
case Key of
VK_RETURN,
VK_DOWN,
VK_UP:
begin
if (Shift = []) and (not (FEdit is TMemo)) then
begin
// Forward the keypress to the tree. It will asynchronously change the focused node.
PostMessage(FTree.Handle, WM_KEYDOWN, Key, 0);
Key := 0;
end;
end;
end;
end;
procedure TDataVCLFieldEditLink.DoOnSetNULL(Sender: TObject);
var
Data: PTreeRec;
vTree: TVirtualStringTree;
vNode: PVirtualNode;
begin
if Assigned(FTree) and Assigned(FNode) then
begin
vTree := FTree;
vNode := FNode;
Data := FTree.GetNodeData(FNode);
Data.DataSource.DataSet.Edit;
Data.Field.Clear;
vTree.InvalidateNode(vNode);
end;
end;
function TDataVCLFieldEditLink.BeginEdit: Boolean;
begin
Result := True;
FEdit.Show;
FEdit.SetFocus;
end;
function TDataVCLFieldEditLink.CancelEdit: Boolean;
begin
Result := True;
FEdit.Hide;
// if FColumn = 1 then
// FTree.InvalidateNode(FNode);
end;
function TDataVCLFieldEditLink.EndEdit: Boolean;
var
Data: PTreeRec;
// Buffer: array[0..1024] of Char;
// S: WideString;
ResultDate: TDateTime;
ResultText: WideString;
IsTextResult: Boolean;
IsResult: Boolean;
vPriorValue: Variant;
vDataCustomForm: IibSHDataCustomForm;
function FormatErrorMessage(const E: string): string;
const
SignalStr = ':' + sLineBreak;
var
I: Integer;
begin
I := Pos(SignalStr, E);
Result := E;
if I > 0 then
Delete(Result, 1, I + Length(SignalStr) - 1);
Result := AnsiReplaceText(Result, SignalStr, '');
if Pos('can''t format message', Result) > 0 then
begin
I := Pos('not found', Result);
Result := Copy(Result, I + Length('not found.'), MaxInt);
end;
end;
begin
Result := True;
IsResult := False;
IsTextResult := True;
ResultDate := Now;
case FColumn of
{
1:
begin
Data := FTree.GetNodeData(FNode);
with FEdit as TCheckBox do
begin
if Assigned(Data) and Assigned(Data.Field) then
begin
if (Checked <> Data.Field.IsNull) and (not Data.Field.ReadOnly) then
begin
if Checked then
begin
if not (Data.Field.DataSet.State in [dsEdit, dsInsert]) then
Data.Field.DataSet.Edit;
Data.Field.Clear;
end;
end;
end;
end;
end;
}
5:
begin
Data := FTree.GetNodeData(FNode);
if Assigned(Data) and Assigned(Data.Field) then
begin
if FEdit is TDateTimePicker then
begin
IsTextResult := False;
IsResult := True;
ResultDate := TDateTimePicker(FEdit).DateTime;
end
else
// if FEdit is TEdit then
if FEdit is TTntEdit then
begin
ResultText := TTntEdit(FEdit).Text;
IsResult := True;
end
else
if FEdit is TMemo then
begin
ResultText := TMemo(FEdit).Lines.Text;
IsResult := True;
end
else
if FEdit is TibSHEditForeignKeyPicker then
begin
ResultText := TibSHEditForeignKeyPicker(FEdit).InputEdit.Text;
IsResult := True;
end;
end;
end;
end;
FEdit.Hide;
FTree.SetFocus;
if IsResult then
begin
if Data.Field.DataSet.Active then
begin
if IsTextResult then
begin
if Data.Field is TWideStringField then
IsResult := TWideStringField(Data.Field).Value<>ResultText
else
IsResult := Data.Field.AsString <> ResultText
end
else
IsResult := Data.Field.AsDateTime <> ResultDate;
if IsResult then
begin
Data.Field.DataSet.Edit;
vPriorValue := Data.Field.Value;
try
if IsTextResult then
begin
if Data.Field is TWideStringField then
TWideStringField(Data.Field).Value:= ResultText
else
Data.Field.AsString := ResultText
end
else
Data.Field.AsDateTime := ResultDate;
except
on E: Exception do
begin
Data.Field.Value := vPriorValue;
if Data.Component.GetComponentFormIntf(IibSHDataCustomForm, vDataCustomForm) then
vDataCustomForm.AddToResultEdit(FormatErrorMessage(E.Message))
else
raise;
end;
end;
end;
end;
end;
end;
function TDataVCLFieldEditLink.GetBounds: TRect;
begin
Result := FEdit.BoundsRect;
end;
function TDataVCLFieldEditLink.PrepareEdit(Tree: TBaseVirtualTree;
Node: PVirtualNode; Column: TColumnIndex): Boolean;
var
Data: PTreeRec;
begin
Result := True;
FTree := Tree as TVirtualStringTree;
FNode := Node;
FColumn := Column;
// determine what edit type actually is needed
FEdit.Free;
FEdit := nil;
Data := FTree.GetNodeData(Node);
case FColumn of
5:
begin
if Data.Field.IsBlob then
begin
if Data.IsPicture then
Result := False
else
begin
FEdit := TMemo.Create(nil);
with FEdit as TMemo do
begin
TabStop := True;
WantTabs := True;
Visible := False;
Parent := Tree;
Lines.Text := Data.Field.AsString;
OnKeyDown := EditKeyDown;
end;
end;
end
else
begin
if Data.Field.DataType in [ftDate, ftDateTime, ftTimeStamp] then
begin
FEdit := TDateTimePicker.Create(nil);
with FEdit as TDateTimePicker do
begin
TabStop := True;
Visible := False;
Parent := Tree;
CalColors.MonthBackColor := clWindow;
CalColors.TextColor := clBlack;
CalColors.TitleBackColor := clBtnShadow;
CalColors.TitleTextColor := clBlack;
CalColors.TrailingTextColor := clBtnFace;
DateTime := Data.Field.AsDateTime;
OnKeyDown := EditKeyDown;
end;
end
else
begin
if Length(Data.ReferenceTable) > 0 then
begin
FEdit := TibSHEditForeignKeyPicker.Create(nil);
with FEdit as TibSHEditForeignKeyPicker do
begin
InputEdit.TabStop := True;
Parent := Tree;
Visible := False;
InputEdit.Text := Data.Field.AsString;
InputEdit.OnKeyDown := EditKeyDown;
if Supports(Data.Component, IibSHData) and
Supports(Data.Component, IibSHDatabase) then
begin
SHCLDatabase := Data.Component as IibSHDatabase;
DataIntf := Data.Component as IibSHData;
ReferenceTable := Data.ReferenceTable;
Fields.Text := Data.FKFields;
ReferenceFields.Text := Data.ReferenceFields;
FieldName := Data.Field.FieldName;
end;
end;
//Data.DBTable.GetConstraint().
end
else
begin
{ TODO -oBuzz -cУникода суппорт : Вот тута добавить уникодную срань для редактирования дерева }
FEdit := TTntEdit.Create(nil);
with FEdit as TTntEdit do
begin
TabStop := True;
Visible := False;
Parent := Tree;
if Data.Field is TWideStringField then
Text := TWideStringField(Data.Field).Value
else
Text := Data.Field.AsString;
OnKeyDown := EditKeyDown;
end;
{ FEdit := TEdit.Create(nil);
with FEdit as TEdit do
begin
TabStop := True;
Visible := False;
Parent := Tree;
Text := Data.Field.AsString;
OnKeyDown := EditKeyDown;
end;}
end;
end;
end;
end;
6:
begin
FEdit := TButton.Create(nil);
with FEdit as TButton do
begin
TabStop := True;
Visible := False;
Parent := Tree;
Caption := 'SET NULL';
Height := 21;
OnKeyDown := EditKeyDown;
OnClick := DoOnSetNULL;
{
if (not Data.Field.ReadOnly) then
begin
FEdit.Perform(WM_LBUTTONDOWN, MK_LBUTTON, 1 shl 16 + 1);
FEdit.Perform(WM_LBUTTONUP, MK_LBUTTON, 1 shl 16 + 1);
end;
}
end;
{
FEdit := TCheckBox.Create(nil);
with FEdit as TCheckBox do
begin
TabStop := True;
Visible := False;
Parent := Tree;
Checked := Data.Field.IsNull;
OnKeyDown := EditKeyDown;
if (not Data.Field.ReadOnly) then
begin
FEdit.Perform(WM_LBUTTONDOWN, MK_LBUTTON, 1 shl 16 + 1);
FEdit.Perform(WM_LBUTTONUP, MK_LBUTTON, 1 shl 16 + 1);
if not (Data.DataSource.DataSet.State in [dsEdit, dsInsert]) then
Data.DataSource.DataSet.Edit;
if Checked then
Data.Field.Clear;
end;
FTree.InvalidateNode(FNode);
end;
}
end;
else
Result := False;
end;
end;
procedure TDataVCLFieldEditLink.ProcessMessage(var Message: TMessage);
begin
FEdit.WindowProc(Message);
end;
procedure TDataVCLFieldEditLink.SetBounds(R: TRect);
var
Dummy: Integer;
// NewRect: TRect;
begin
// Since we don't want to activate grid extensions in the tree (this would influence how the selection is drawn)
// we have to set the edit's width explicitly to the width of the column.
FTree.Header.Columns.GetColumnBounds(FColumn, Dummy, R.Right);
case FColumn of
{
0, 3:;
1:
begin
NewRect := R;
NewRect.Bottom := NewRect.Top + 20;
NewRect.Left := R.Left + ((R.Right - R.Left) div 2) - 6;
FEdit.BoundsRect := NewRect;
end;
}
5, 6:
begin
//FEdit.BoundsRect := R;
// FEdit.BoundsRect.Top := R.
R.Bottom := R.Top + (FEdit.BoundsRect.Bottom - FEdit.BoundsRect.Top);
FEdit.BoundsRect := R;
end;
end;
end;
function TDataVCLFieldEditLink.GetEditor: TWinControl;
begin
Result := FEdit;
end;
{ TibSHEditForeignKeyPickerForm }
constructor TibSHEditForeignKeyPickerForm.Create(AOwner: TComponent);
function CreatePanel(AOwner: TWinControl): TPanel;
begin
Result := TPanel.Create(AOwner);
with Result do
begin
Parent := AOwner;
BorderStyle := bsNone;
BevelInner := bvNone;
BevelOuter := bvNone;
Caption := EmptyStr;
end;
end;
begin
CreateNew(AOwner);
Width := 300;
Height := 250;
FTopPanel := CreatePanel(Self);
with FTopPanel do
begin
Align := alTop;
Height := 24;
end;
with TDBNavigator.Create(FTopPanel) do
begin
Parent := FTopPanel;
Flat := True;
Align := alLeft;
DataSource := EditForeignKeyPicker.FDataSource;
Top := 1;
Left := 1;
VisibleButtons := [nbFirst, nbPrior, nbNext, nbLast];
Width := Width div 2;
end;
FDBGrid := TDBGridEh.Create(Self);
with FDBGrid do
begin
Parent := Self;
Align := alClient;
DataSource := EditForeignKeyPicker.FDataSource;
Flat := True;
ReadOnly := True;
OnDblClick := EditForeignKeyPicker.DoOnOk;
end;
FBottomPanel := CreatePanel(Self);
with FBottomPanel do
begin
Align := alBottom;
Height := 26;
end;
FBtnOk := TButton.Create(FBottomPanel);
with FBtnOk do
begin
Parent := FBottomPanel;
Width := 60;
Height := 22;
Caption := 'Ok';
OnClick := EditForeignKeyPicker.DoOnOk;
Default := True;
Top := 2;
Left := FBottomPanel.Width - 124;
ModalResult := mrOk;
end;
FBtnCancel := TButton.Create(FBottomPanel);
with FBtnCancel do
begin
Parent := FBottomPanel;
Width := 60;
Height := 22;
Caption := 'Cancel';
OnClick := EditForeignKeyPicker.DoOnCancel;
Top := 2;
Left := FBottomPanel.Width - 62;
ModalResult := mrCancel;
end;
KeyPreview := True;
OnKeyDown := DoOnFormKeyDown;
end;
destructor TibSHEditForeignKeyPickerForm.Destroy;
begin
inherited Destroy;
end;
function TibSHEditForeignKeyPickerForm.GetEditForeignKeyPicker: TibSHEditForeignKeyPicker;
begin
Result := TibSHEditForeignKeyPicker(Owner);
end;
procedure TibSHEditForeignKeyPickerForm.WMActivate(
var Message: TWMActivate);
begin
if csDesigning in ComponentState then begin
inherited;
Exit;
end;
if Application.MainForm.HandleAllocated then
SendMessage(Application.MainForm.Handle, WM_NCACTIVATE, Ord(Message.Active <> WA_INACTIVE), 0);
end;
procedure TibSHEditForeignKeyPickerForm.Resize;
begin
inherited Resize;
FBtnOk.Top := 2;
FBtnOk.Left := FBottomPanel.Width - 124;
FBtnCancel.Top := 2;
FBtnCancel.Left := FBottomPanel.Width - 62;
end;
procedure TibSHEditForeignKeyPickerForm.CreateParams(
var Params: TCreateParams);
const
CS_DROPSHADOW = $20000;
begin
inherited;
with Params do
begin
Style := WS_POPUP;
ExStyle := WS_EX_TOOLWINDOW;
if ((Win32Platform and VER_PLATFORM_WIN32_NT) <> 0)
and (Win32MajorVersion > 4)
and (Win32MinorVersion > 0) {Windows XP} then
Params.WindowClass.style := Params.WindowClass.style or CS_DROPSHADOW;
Style := Style or WS_THICKFRAME
end;
end;
procedure TibSHEditForeignKeyPickerForm.DoOnFormKeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
case Key of
VK_RETURN: FBtnOk.Click;
VK_ESCAPE: FBtnCancel.Click;
end;
end;
{ TibSHEditForeignKeyPicker }
constructor TibSHEditForeignKeyPicker.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Caption := EmptyStr;
BorderStyle := bsNone;
BevelInner := bvNone;
// BevelOuter := bvNone;
BevelOuter := bvLowered;
FEditButton := TSpeedButton.Create(Self);
FEditButton.Parent := Self;
FEditButton.Align := alRight;
FEditButton.Caption := 'FK';
FEditButton.OnClick := DropDownGridPanel;
FInputEdit := TEdit.Create(Self);
FInputEdit.Parent := Self;
Height := FInputEdit.Height;
FInputEdit.Width := Width - Height;
FEditButton.Width := Height;
FFields := TStringList.Create;
FReferenceFields := TStringList.Create;
FDataSource := TDataSource.Create(Self);
FForm := TibSHEditForeignKeyPickerForm.Create(Self);
FForm.BorderStyle := bsNone;
FForm.Visible := False;
end;
destructor TibSHEditForeignKeyPicker.Destroy;
begin
FreeDRV;
FFields.Free;
FReferenceFields.Free;
inherited Destroy;
end;
procedure TibSHEditForeignKeyPicker.SetFields(const Value: TStrings);
begin
FFields.Assign(Value);
end;
procedure TibSHEditForeignKeyPicker.SetReferenceFields(
const Value: TStrings);
begin
FReferenceFields.Assign(Value);
end;
procedure TibSHEditForeignKeyPicker.SetReferenceTable(const Value: string);
begin
FReferenceTable := Value;
if Assigned(DataIntf) then
begin
if DRVDataset.Active then
DRVDataset.Close;
DRVDataset.SelectSQL.Text := Format('SELECT * FROM %s', [FReferenceTable]);
end;
end;
procedure TibSHEditForeignKeyPicker.SetDataIntf(const Value: IibSHData);
begin
FDataIntf := Value;
if Assigned(FDataIntf) then
begin
CreateDRV;
FDataSource.DataSet := DRVDataset.Dataset;
end
else
FreeDRV;
end;
procedure TibSHEditForeignKeyPicker.SetFormPos;
var
vLeftTop: TPoint;
begin
vLeftTop := ClientToScreen(Point(0, Height));
if vLeftTop.X + FForm.Width > Screen.Width then
FForm.Left := vLeftTop.X + FInputEdit.Width - FForm.Width
else
FForm.Left := vLeftTop.X;
if vLeftTop.Y + FForm.Height > Screen.Height then
FForm.Top := vLeftTop.Y - FInputEdit.Height - FForm.Height
else
FForm.Top := vLeftTop.Y;
end;
procedure TibSHEditForeignKeyPicker.WMWindowPosChanged(
var Message: TWMWindowPosChanged);
begin
inherited;
SetFormPos;
end;
procedure TibSHEditForeignKeyPicker.CreateDRV;
var
vDesigner: ISHDesigner;
vComponentClass: TSHComponentClass;
begin
if SHSupports(ISHDesigner, vDesigner) and Assigned(SHCLDatabase) then
begin
vComponentClass := vDesigner.GetComponent(SHCLDatabase.BTCLServer.DRVNormalize(IibSHDRVDataset));
if Assigned(vComponentClass) then
begin
FDRVDataset := vComponentClass.Create(Self);
DRVDataset.Database := DataIntf.Transaction.Database;
DRVDataset.ReadTransaction := DataIntf.Transaction;
end;
end;
end;
procedure TibSHEditForeignKeyPicker.FreeDRV;
begin
end;
function TibSHEditForeignKeyPicker.GetDRVDataset: IibSHDRVDataset;
begin
Supports(FDRVDataset, IibSHDRVDataset, Result);
end;
procedure TibSHEditForeignKeyPicker.Resize;
begin
inherited Resize;
FInputEdit.Left := 0;
FInputEdit.Top := 0;
FInputEdit.Width := Width - Height;
FInputEdit.Height := Height;
FEditButton.Width := Height;
end;
procedure TibSHEditForeignKeyPicker.VisibleChanging;
begin
if Visible then
FForm.Hide;
inherited VisibleChanging;
end;
procedure TibSHEditForeignKeyPicker.ApplyGridFormatOptions(
ADBGrid: TDBGridEh);
var
I: Integer;
vGridFormatOptions: ISHDBGridFormatOptions;
vDesigner: ISHDesigner;
procedure DoFitDisplayWidths;
var
J, dw, tw, MAX_COLUMN_WIDTH: Integer;
TM: TTextMetric;
begin
if Assigned(vGridFormatOptions) then
MAX_COLUMN_WIDTH := vGridFormatOptions.DisplayFormats.StringFieldWidth
else
MAX_COLUMN_WIDTH := 100;
GetTextMetrics(ADBGrid.Canvas.Handle, TM);
for J := 0 to Pred(ADBGrid.Columns.Count) do
begin
dw := ADBGrid.Columns[J].Field.DisplayWidth * (ADBGrid.Canvas.TextWidth('0') - TM.tmOverhang) + TM.tmOverhang + 4;
if dw > MAX_COLUMN_WIDTH then
dw := MAX_COLUMN_WIDTH;
tw := ADBGrid.Canvas.TextWidth(ADBGrid.Columns[J].Title.Caption + 'W');
if dw < tw then
dw := tw;
ADBGrid.Columns[J].Width := dw;
end;
end;
begin
if SHSupports(ISHDesigner, vDesigner) and
Supports(vDesigner.GetDemon(ISHDBGridFormatOptions), ISHDBGridFormatOptions, vGridFormatOptions) and
Assigned(ADBGrid) and
Assigned(ADBGrid.DataSource) and
Assigned(ADBGrid.DataSource.DataSet) and
(ADBGrid.DataSource.DataSet.FieldCount > 0) then
begin
for I := 0 to Pred(ADBGrid.Columns.Count) do
begin
if Assigned(SHCLDatabase) and
SHCLDatabase.DatabaseAliasOptions.DML.UseDB_KEY and
(not SHCLDatabase.DatabaseAliasOptions.DML.ShowDB_KEY) and
(ADBGrid.Columns[I].FieldName = 'DB_KEY') then
ADBGrid.Columns[I].Visible := False;
ADBGrid.Columns[I].ToolTips := True;
if ADBGrid.Columns[I].Field is TIntegerField then
begin
TIntegerField(ADBGrid.Columns[I].Field).DisplayFormat := vGridFormatOptions.DisplayFormats.IntegerField;
TIntegerField(ADBGrid.Columns[I].Field).EditFormat := vGridFormatOptions.EditFormats.IntegerField;
end;
if ADBGrid.Columns[I].Field is TFloatField then
begin
TFloatField(ADBGrid.Columns[I].Field).DisplayFormat := vGridFormatOptions.DisplayFormats.FloatField;
TFloatField(ADBGrid.Columns[I].Field).EditFormat := vGridFormatOptions.EditFormats.FloatField;
end;
// Шо за дубляж кода???
if ADBGrid.Columns[I].Field is TDateTimeField then
TDateTimeField(ADBGrid.Columns[I].Field).DisplayFormat := vGridFormatOptions.DisplayFormats.DateTimeField;
if ADBGrid.Columns[I].Field is TDateField then
TDateField(ADBGrid.Columns[I].Field).DisplayFormat := vGridFormatOptions.DisplayFormats.DateField;
if ADBGrid.Columns[I].Field is TTimeField then
TTimeField(ADBGrid.Columns[I].Field).DisplayFormat := vGridFormatOptions.DisplayFormats.TimeField;
end;
end;
end;
procedure TibSHEditForeignKeyPicker.DropDownGridPanel(Sender: TObject);
var
I: Integer;
S: string;
vIndex: Integer;
vDesigner: ISHDesigner;
vFormater: IibSHDataCustomForm;
begin
try
if Assigned(DRVDataset) then
begin
DRVDataset.Open;
vIndex := Fields.IndexOf(FieldName);
if vIndex > -1 then
begin
S := ReferenceFields[vIndex];
for I := 0 to Pred(FForm.FDBGrid.Columns.Count) do
if FForm.FDBGrid.Columns[I].FieldName = S then
begin
FForm.FDBGrid.Columns[I].Title.Font.Style :=
FForm.FDBGrid.Columns[I].Title.Font.Style + [fsBold];
Break;
end;
end;
SetFormPos;
if SHSupports(ISHDesigner, vDesigner) and
Supports(vDesigner.CurrentComponentForm, IibSHDataCustomForm, vFormater) then
vFormater.SetDBGridOptions(FForm.FDBGrid);
ApplyGridFormatOptions(FForm.FDBGrid);
FForm.Show;
end;
except
FForm.Hide;
end;
end;
procedure TibSHEditForeignKeyPicker.DoOnOk(Sender: TObject);
var
I: Integer;
begin
FForm.Hide;
DataIntf.Dataset.Dataset.Edit;
for I := 0 to Pred(Fields.Count) do
begin
DataIntf.Dataset.Dataset.FieldByName(Fields[I]).Value :=
DRVDataset.Dataset.FieldByName(ReferenceFields[I]).Value;
if AnsiSameText(Fields[I], FFieldName) then
InputEdit.Text := DataIntf.Dataset.Dataset.FieldByName(Fields[I]).AsString;
end;
end;
procedure TibSHEditForeignKeyPicker.DoOnCancel(Sender: TObject);
begin
FForm.Hide;
end;
end.
|
unit abFunctions;
interface
uses Windows, WinInet, ShFolder;
//String Functions
function IntToStr(I: Integer): String;
function StrToInt(S: String): Integer;
function LowerCase(S: String): String;
function MatchStrings(Str1, Str2: String): Boolean;
function LeftStr(const AText: AnsiString; const ACount: Integer): AnsiString; overload;
function RightStr(const AText: AnsiString; const ACount: Integer): AnsiString; overload;
function TrimEx(S: String): String;
function Split(Input: String; Deliminator: String; Index: Integer): String;
function ReplaceString(S, OldPattern, NewPattern: String): String;
function WildcardCompare(WildS, IstS: String): Boolean;
//System Information Functions
function GetProcessorName(): String;
function GetTotalRAM(): String;
function GetVideoCard(): String;
function GetUptime(): String;
function GetAppDataPath(): String;
function GetWinVersion(): String;
function GetWinLang(): String;
//Bot Functions
function Download(const fileURL, FileName: String): Boolean;
function CheckAuthHost(AuthHost, RawData: String): Boolean;
procedure DeleteSelf(MyPath: String);
function FileExists(FileName: String): Boolean;
procedure ExecuteFile(Path: String);
//Registry Functions
procedure InsertRegValue(Root: HKey; Path, Value, Str: String);
function ReadRegValue(Root: HKey; Path, Value, Default: String): String;
procedure DeleteRegValue(Root: HKey; Path, Value: String);
implementation
//////////////////////////////////////////////////////////
//String Functions
//////////////////////////////////////////////////////////
function IntToStr(I: Integer): String;
begin
Str(i, Result);
end;
function StrToInt(S: String): Integer;
begin
Val(S, Result, Result);
end;
function LowerCase(S: String): String;
var
I: Integer;
begin
for I := 1 to Length(S) do S[I] := Char(CharLower(PChar(S[I])));
Result := S;
end;
function MatchStrings(Str1, Str2: String): Boolean;
begin
if LowerCase(Str1) = LowerCase(Str2) then Result := True else Result := False;
end;
function LeftStr(const AText: AnsiString; const ACount: Integer): AnsiString; overload;
begin
Result := Copy(AText, 1, ACount);
end;
function RightStr(const AText: AnsiString; const ACount: Integer): AnsiString; overload;
begin
Result := Copy(AText, Length(AText) - ACount + 1, Length(AText));
end;
function TrimEx(S: String): String;
var
I, Count: Integer;
begin
I := Length(S);
Count:= 1;
repeat
if Copy(S, Count, 1) <> #0 then Result := Result + Copy(S, Count, 1);
Inc(Count)
until Count = I;
end;
function Split(Input: String; Deliminator: String; Index: Integer): String;
var
StringLoop, StringCount: Integer;
Buffer: String;
begin
Buffer := '';
if Index < 1 then Exit;
StringCount := 0;
StringLoop := 1;
while (StringLoop <= Length(Input)) do
begin
if (Copy(Input, StringLoop, Length(Deliminator)) = Deliminator) then
begin
Inc(StringLoop, Length(Deliminator) - 1);
Inc(StringCount);
if StringCount = Index then
begin
Result := Buffer;
Exit;
end
else
begin
Buffer := '';
end;
end
else
begin
Buffer := Buffer + Copy(Input, StringLoop, 1);
end;
Inc(StringLoop, 1);
end;
Inc(StringCount);
if StringCount < Index then Buffer := '';
Result := Buffer;
end;
function ReplaceString(S, OldPattern, NewPattern: String): String;
var
SearchStr, Patt, NewStr: string;
Offset: Integer;
begin
SearchStr := S;
Patt := OldPattern;
NewStr := S;
Result := '';
while SearchStr <> '' do
begin
Offset := Pos(Patt, SearchStr);
if Offset = 0 then
begin
Result := Result + NewStr;
Break;
end;
Result := Result + Copy(NewStr, 1, Offset - 1) + NewPattern;
NewStr := Copy(NewStr, Offset + Length(OldPattern), MaxInt);
SearchStr := Copy(SearchStr, Offset + Length(Patt), MaxInt);
end;
end;
function WildcardCompare(WildS, IstS: String): Boolean;
var
I, J, L, P: Byte;
begin
I := 1;
J := 1;
while (I <= Length(WildS)) do
begin
if WildS[I] = '*' then
begin
if I = Length(WildS) then
begin
Result := True;
Exit
end
else
begin
L := I + 1;
while (l < length(WildS)) and (WildS[l+1] <> '*') do Inc (l);
P := Pos(Copy(WildS, I + 1, L - I), IstS);
if P > 0 then J := P - 1
else
begin
Result := False;
Exit;
end;
end;
end
else
if (WildS[I] <> '?') and ((Length(IstS) < I) or (WildS[I] <> IstS[J])) then
begin
Result := False;
Exit
end;
Inc(I);
Inc(J);
end;
Result := (J > Length(IstS));
end;
//////////////////////////////////////////////////////////
//System Information Functions
//////////////////////////////////////////////////////////
function GetProcessorName(): String;
const
Size: Integer = 2048;
var
Temp: HKEY;
Speed: Integer;
begin
RegOpenKeyEx(HKEY_LOCAL_MACHINE, 'HARDWARE\DESCRIPTION\System\CentralProcessor\0', 0, KEY_QUERY_VALUE, Temp);
RegQueryValueEx(Temp, '~MHz', nil, nil, @Speed, @Size);
RegCloseKey(Temp);
Result := ReadRegValue(HKEY_LOCAL_MACHINE, 'HARDWARE\DESCRIPTION\System\CentralProcessor\0', 'ProcessorNameString', 'Not Found') + ' - ' + IntToStr(Speed) + ' MHz';
end;
function GetTotalRAM(): String;
var
MemoryStatus: TMemoryStatus;
begin
MemoryStatus.dwLength := SizeOf(TMemoryStatus);
GlobalMemoryStatus(MemoryStatus);
Result := IntToStr(MemoryStatus.dwTotalPhys div 1048576) + 'MB';
end;
function GetVideoCard(): String;
var
Device: TDisplayDevice;
dwFlags, dwDevNum: DWORD;
Return: String;
begin
Return := 'Not Found';
Device.cb := sizeof(Device);
dwFlags := 0;
dwDevNum := 0;
EnumDisplayDevices(nil, dwDevNum, Device, dwFlags);
Return := Device.DeviceString;
Result := Return;
end;
function GetUptime(): String;
var
Total: Integer;
begin
Total := GetTickCount() div 1000;
Result := IntToStr(Total DIV 86400) + 'd ' + IntToStr((Total MOD 86400) DIV 3600) + 'h ' + IntToStr(((Total MOD 86400) MOD 3600) DIV 60) + 'm ' + IntToStr((((Total MOD 86400) MOD 3600) MOD 60) DIV 1) + 's';
end;
function GetAppDataPath() : String;
var
SHGetFolderPath :TSHGetFolderPath;
hFolderDLL : THandle;
var
Buf: array[0..256] of Char;
begin
hFolderDLL := LoadLibrary('SHFolder.dll');
try
SHGetFolderPath := nil;
if hFolderDLL <> 0 then @SHGetFolderPath := GetProcAddress(hFolderDLL, 'SHGetFolderPathA');
if Assigned(SHGetFolderPath) and (S_OK = SHGetFolderPath(0, CSIDL_APPDATA or CSIDL_FLAG_CREATE, 0, 0, Buf)) then
else
GetTempPath(Max_path, Buf);
finally
if hFolderDLL <> 0 then FreeLibrary(hFolderDLL);
Result := String(Buf) + '\';
end;
end;
function GetWinVersion(): String;
var
osVerInfo: TOSVersionInfo;
majorVersion, minorVersion: Integer;
begin
Result := 'Unknown';
osVerInfo.dwOSVersionInfoSize := SizeOf(TOSVersionInfo) ;
if GetVersionEx(osVerInfo) then
begin
minorVersion := osVerInfo.dwMinorVersion;
majorVersion := osVerInfo.dwMajorVersion;
case osVerInfo.dwPlatformId of VER_PLATFORM_WIN32_NT:
begin
if majorVersion <= 4 then Result := 'WinNT'
else if (majorVersion = 5) and (minorVersion = 0) then Result := 'Win2000'
else if (majorVersion = 5) and (minorVersion = 1) then Result := 'WinXP'
else if (majorVersion = 5) and (minorVersion = 2) then Result := 'Win2003'
else if (majorVersion = 6) then Result := 'WinVista';
end;
VER_PLATFORM_WIN32_WINDOWS:
begin
if (majorVersion = 4) and (minorVersion = 0) then Result := 'Win95'
else if (majorVersion = 4) and (minorVersion = 10) then
begin
if osVerInfo.szCSDVersion[1] = 'A' then Result := 'Win98SE'
else
Result := 'Win98';
end
else if (majorVersion = 4) and (minorVersion = 90) then Result := 'WinME' else Result := 'Unknown';
end;
end;
end;
end;
function GetWinLang(): String;
var
Buffer: PChar;
Size: Integer;
begin
Size := GetLocaleInfo(LOCALE_SYSTEM_DEFAULT, LOCALE_SABBREVCTRYNAME, nil, 0);
GetMem(Buffer, Size);
try
GetLocaleInfo(LOCALE_SYSTEM_DEFAULT, LOCALE_SABBREVCTRYNAME, Buffer, Size);
Result := String(Buffer);
finally
FreeMem(Buffer);
end;
end;
//////////////////////////////////////////////////////////
//Bot Functions
//////////////////////////////////////////////////////////
function Download(const fileURL, FileName: String): Boolean;
const BufferSize = 1024;
var
hSession, hURL: HInternet;
Buffer: array[1..BufferSize] of Byte;
BufferLen: DWord;
f: File;
begin
Result := False;
hSession := InternetOpen(PChar('explorer'), INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0);
try
hURL := InternetOpenURL(hSession, PChar(fileURL), nil, 0, 0, 0);
try
AssignFile(f, FileName);
Rewrite(f,1);
repeat
InternetReadFile(hURL, @Buffer, SizeOf(Buffer), BufferLen);
BlockWrite(f, Buffer, BufferLen)
until BufferLen = 0;
CloseFile(f);
Result := True;
finally
InternetCloseHandle(hURL)
end
finally
InternetCloseHandle(hSession)
end
end;
function CheckAuthHost(AuthHost, RawData: String): Boolean;
begin
Delete(RawData, 1, 1);
RawData := Copy(RawData, 1, Pos(' ', RawData));
if WildcardCompare(AuthHost, TrimEx(RawData)) then Result := True else Result := False;
end;
procedure DeleteSelf(MyPath: String);
var
BatchFile: TextFile;
begin
AssignFile(BatchFile, GetAppDataPath + '~SystemCache.bat');
ReWrite(BatchFile);
WriteLn(BatchFile, ':try');
WriteLn(BatchFile, 'del "' + MyPath + '"');
WriteLn(BatchFile, 'if exist "' + MyPath + '" goto try');
WriteLn(BatchFile, 'del "' + GetAppDataPath + '~SystemCache.bat"' );
CloseFile(BatchFile);
ExecuteFile(GetAppDataPath + '~SystemCache.bat');
end;
function FileExists(FileName: String): Boolean;
var
hFile: THandle;
lpFindFileData: TWin32FindData;
begin
Result := False;
hFile := FindFirstFile(PChar(FileName), lpFindFileData);
if hFile <> INVALID_HANDLE_VALUE then
begin
FindClose(hFile);
Result := True;
end;
end;
procedure ExecuteFile(Path: String);
var
PI: TProcessInformation;
SI: TStartupInfo;
begin
FillChar(SI, SizeOf(SI), $00);
SI.dwFlags := STARTF_USESHOWWINDOW;
SI.wShowWindow := SW_HIDE;
if CreateProcess(nil, PChar(Path), nil, nil, False, IDLE_PRIORITY_CLASS, nil, nil, SI, PI) then
begin
CloseHandle(PI.hThread);
CloseHandle(PI.hProcess);
end;
end;
//////////////////////////////////////////////////////////
//Registry Functions
//////////////////////////////////////////////////////////
procedure InsertRegValue(Root: HKey; Path, Value, Str: String);
var
Key: HKey;
Size: Cardinal;
begin
RegOpenKey(Root, PChar(Path), Key);
Size := Length(Str);
RegSetValueEx(Key, PChar(Value), 0, REG_SZ, @Str[1], Size);
RegCloseKey(Key);
end;
function ReadRegValue(Root: HKey; Path, Value, Default: String): String;
var
Key: HKey;
RegType: Integer;
DataSize: Integer;
begin
Result := Default;
if (RegOpenKeyEx(Root, PChar(Path), 0, KEY_ALL_ACCESS, Key) = ERROR_SUCCESS) then
begin
if RegQueryValueEx(Key, PChar(Value), nil, @RegType, nil, @DataSize) = ERROR_SUCCESS then
begin
SetLength(Result, Datasize);
RegQueryValueEx(Key, PChar(Value), nil, @RegType, PByte(PChar(Result)), @DataSize);
SetLength(Result, Datasize - 1);
end;
RegCloseKey(Key);
end;
end;
procedure DeleteRegValue(Root: HKey; Path, Value: String);
var
Key: HKey;
begin
RegOpenKey(ROOT, PChar(Path), Key);
RegDeleteValue(Key, PChar(Value));
RegCloseKey(Key);
end;
end.
|
unit Controller.Interfaces;
interface
uses
Vcl.Samples.Spin, Vcl.ComCtrls, Data.DB, Datasnap.DBClient;
type
TProgress = Vcl.ComCtrls.TProgressBar;
TDataset = Data.DB.TDataSet;
TClientDataSet = Datasnap.DBClient.TClientDataSet;
TFieldType = Data.DB.TFieldType;
IThreadController = interface
['{8D669FD9-9899-4721-866A-287FAC55D684}']
procedure ExecutarLaco(PMilisegundos: Integer; PProgresso: TProgress);
end;
IProjetoController = interface
['{358C90B4-58D3-42A2-A18B-FC65D6D28A83}']
function ObterTotal(PDataSet: TDataSet): Currency;
function ObterTotalDivisoes(PDataSet: TDataSet): Currency;
procedure RetornarDataSet(PDataSet: TDataSet);
end;
IFactoryController = interface
['{120737AA-3390-40F7-88D9-D8217B4730BD}']
function ThreadController: IThreadController;
function ProjetoController: IProjetoController;
end;
implementation
end. |
namespace PictureViewer;
interface
uses
System.IO,
System.Windows.Media.Imaging,
System.Collections.ObjectModel;
type
ImageFile = public class
private
fImage: BitmapFrame;
fUri: Uri;
fPath: String;
protected
public
constructor (aPath: String);
method ToString(): String; override;
property Path: String read fPath;
property Uri: Uri read fUri;
property Image: BitmapFrame read fImage;
end;
ImageList = public class(ObservableCollection<ImageFile>)
private
fDirectory: DirectoryInfo;
method get_Path: String;
method SetPath(value: String);
method SetDirectory(value: DirectoryInfo);
method Update();
public
constructor;
constructor(aPath: String);
constructor(aDirectory: DirectoryInfo);
property Directory: DirectoryInfo read fDirectory write SetDirectory;
property Path: String read get_Path write SetPath;
end;
implementation
constructor ImageFile(aPath: String);
begin
fPath := aPath;
fUri := new Uri(fPath);
fImage := BitmapFrame.Create(fUri);
end;
method ImageFile.ToString(): String;
begin
exit(Path);
end;
constructor ImageList();
begin
end;
constructor ImageList(aDirectory: DirectoryInfo);
begin
Directory := aDirectory;
end;
constructor ImageList(aPath: String);
begin
constructor(new DirectoryInfo(aPath));
end;
method ImageList.SetDirectory(value: DirectoryInfo);
begin
fDirectory := value;
Update();
end;
method ImageList.Update();
begin
for each f: FileInfo in fDirectory.GetFiles('*.jpg') do begin
&Add(new ImageFile(f.FullName));
end;
end;
method ImageList.SetPath(value: String);
begin
fDirectory := new DirectoryInfo(value);
Update();
end;
method ImageList.get_Path: String;
begin
exit(fDirectory.FullName);
end;
end. |
unit uRoleListfrm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uListFormBaseFrm, cxStyles, cxCustomData, cxGraphics, cxFilter,
cxData, cxDataStorage, cxEdit, DB, cxDBData, cxGridLevel, cxClasses,
cxControls, cxGridCustomView, cxGridCustomTableView, cxGridTableView,
cxGridDBTableView, cxGrid, jpeg, ExtCtrls, Buttons, DBClient,PermissionAgtFrm;
type
TFM_RoleListForm = class(TListFormBaseFrm)
Panel1: TPanel;
btn_NewRow: TSpeedButton;
btn_DelRow: TSpeedButton;
Image1: TImage;
Panel2: TPanel;
cxgridRole: TcxGridDBTableView;
cxGrid1Level1: TcxGridLevel;
cxGrid1: TcxGrid;
cdsRoleList: TClientDataSet;
dsRoleList: TDataSource;
spt_AgtPerm: TSpeedButton;
btn_Allocuser: TSpeedButton;
spt_Edit: TSpeedButton;
procedure btn_NewRowClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure btn_DelRowClick(Sender: TObject);
procedure btn_AllocuserClick(Sender: TObject);
procedure cxgridRoleDblClick(Sender: TObject);
procedure spt_EditClick(Sender: TObject);
procedure spt_AgtPermClick(Sender: TObject);
private
{ Private declarations }
procedure OpenDatalist;
public
{ Public declarations }
end;
var
FM_RoleListForm: TFM_RoleListForm;
implementation
uses uRoleEditFrm, FrmCliDM,Pub_Fun,uAllocUserfrm;
{$R *.dfm}
procedure TFM_RoleListForm.btn_NewRowClick(Sender: TObject);
begin
inherited;
if EditRolenfo_Frm('') then
begin
OpenDatalist;
end;
end;
procedure TFM_RoleListForm.FormShow(Sender: TObject);
var FilePath : string;
begin
FilePath := ExtractFilePath(paramstr(0))+'\Img\Tool_bk.jpg';
if not LoadImage(FilePath,Image1) then Gio.AddShow('图片路径不存在:'+FilePath);
inherited;
OpenDatalist;
end;
procedure TFM_RoleListForm.OpenDatalist;
var
strsql, strError :string ;
begin
inherited;
try
strsql :=' select FID,Fnumber as 角色编号,Fname_l2 as 角色名称,FDESCRIPTION_L2 as 备注 from t_Pm_Role ';
Clidm.Get_OpenSQL(CliDM.cdstemp,strsql,strError);
cdsRoleList.Data := CliDM.cdstemp.Data;
except
on e :Exception do
begin
ShowMsg(Handle, '查询数据出错!'+strError,[]);
Abort;
end;
end;
cxgridRole.ClearItems;
cxgridRole.DataController.CreateAllItems;
if cxgridRole.GetColumnByFieldName('FID')<>nil then
cxgridRole.GetColumnByFieldName('FID').Visible := False;
cxgridRole.GetColumnByFieldName('角色编号').Width := 150;
cxgridRole.GetColumnByFieldName('角色名称').Width := 200;
cxgridRole.GetColumnByFieldName('备注').Width := 300;
end;
procedure TFM_RoleListForm.btn_DelRowClick(Sender: TObject);
var
strsql, ErrMsg : string;
begin
inherited;
strsql := ' select 1 from t_Pm_Userroleorg where FRoleID='+quotedstr(cdsRoleList.fieldbyname('FID').AsString);
Clidm.Get_OpenSQL(CliDM.cdstemp,strsql,ErrMsg);
if CliDM.cdstemp.RecordCount>0 then
begin
ShowMsg(Handle, '用户已经分配了角色权限不允许删除',[]);
Abort;
end;
if ShowYesNo(Handle, '确定删除角色?',[]) = idYes then
begin
strsql :=' delete from t_Pm_Rolepermissionentry where fparentID='+quotedstr(cdsRoleList.fieldbyname('FID').AsString)+'; '+
' delete from t_Pm_Rolecustomerentry where fparentID='+quotedstr(cdsRoleList.fieldbyname('FID').AsString)+'; '+
' delete from t_Pm_Rolesupplierentry where fparentID='+quotedstr(cdsRoleList.fieldbyname('FID').AsString)+'; '+
' delete from t_Pm_Role where FID ='+quotedstr(cdsRoleList.fieldbyname('FID').AsString)+'; ';
CliDM.Get_ExecSQL(strsql,ErrMsg);
if ErrMsg='' then
begin
ShowMsg(Handle, '删除数据成功',[]);
end
else
ShowMsg(Handle, '删除数据失败',[]);
end;
end;
procedure TFM_RoleListForm.btn_AllocuserClick(Sender: TObject);
begin
inherited;
with TFM_AllocUserRole.Create(self) do
begin
strRoleName := cdsRoleList.fieldbyname('角色名称').AsString;
strRoleID := cdsRoleList.fieldbyname('FID').AsString;
Open_Bill('', cdsRoleList.fieldbyname('FID').AsString);
ShowModal;
end;
end;
procedure TFM_RoleListForm.cxgridRoleDblClick(Sender: TObject);
begin
inherited;
EditRolenfo_Frm(cdsRoleList.fieldbyname('FID').AsString);
end;
procedure TFM_RoleListForm.spt_EditClick(Sender: TObject);
begin
inherited;
EditRolenfo_Frm(cdsRoleList.fieldbyname('FID').AsString);
end;
procedure TFM_RoleListForm.spt_AgtPermClick(Sender: TObject);
begin
inherited;
if cdsRoleList.IsEmpty then Exit;
UserRolePermissionAgt(cdsRoleList.fieldbyname('FID').AsString,0,'角色权限分配>'+cdsRoleList.fieldbyname('角色编号').AsString+':'+cdsRoleList.fieldbyname('角色名称').AsString);
end;
end.
|
unit XED.CategoryEnum;
{$Z4}
interface
type
TXED_Category_Enum = (
XED_CATEGORY_INVALID,
XED_CATEGORY_3DNOW,
XED_CATEGORY_ADOX_ADCX,
XED_CATEGORY_AES,
XED_CATEGORY_AMX_TILE,
XED_CATEGORY_AVX,
XED_CATEGORY_AVX2,
XED_CATEGORY_AVX2GATHER,
XED_CATEGORY_AVX512,
XED_CATEGORY_AVX512_4FMAPS,
XED_CATEGORY_AVX512_4VNNIW,
XED_CATEGORY_AVX512_BITALG,
XED_CATEGORY_AVX512_VBMI,
XED_CATEGORY_AVX512_VP2INTERSECT,
XED_CATEGORY_BINARY,
XED_CATEGORY_BITBYTE,
XED_CATEGORY_BLEND,
XED_CATEGORY_BMI1,
XED_CATEGORY_BMI2,
XED_CATEGORY_BROADCAST,
XED_CATEGORY_CALL,
XED_CATEGORY_CET,
XED_CATEGORY_CLDEMOTE,
XED_CATEGORY_CLFLUSHOPT,
XED_CATEGORY_CLWB,
XED_CATEGORY_CLZERO,
XED_CATEGORY_CMOV,
XED_CATEGORY_COMPRESS,
XED_CATEGORY_COND_BR,
XED_CATEGORY_CONFLICT,
XED_CATEGORY_CONVERT,
XED_CATEGORY_DATAXFER,
XED_CATEGORY_DECIMAL,
XED_CATEGORY_ENQCMD,
XED_CATEGORY_EXPAND,
XED_CATEGORY_FCMOV,
XED_CATEGORY_FLAGOP,
XED_CATEGORY_FMA4,
XED_CATEGORY_FP16,
XED_CATEGORY_GATHER,
XED_CATEGORY_GFNI,
XED_CATEGORY_HRESET,
XED_CATEGORY_IFMA,
XED_CATEGORY_INTERRUPT,
XED_CATEGORY_IO,
XED_CATEGORY_IOSTRINGOP,
XED_CATEGORY_KEYLOCKER,
XED_CATEGORY_KEYLOCKER_WIDE,
XED_CATEGORY_KMASK,
XED_CATEGORY_LEGACY,
XED_CATEGORY_LOGICAL,
XED_CATEGORY_LOGICAL_FP,
XED_CATEGORY_LZCNT,
XED_CATEGORY_MISC,
XED_CATEGORY_MMX,
XED_CATEGORY_MOVDIR,
XED_CATEGORY_MPX,
XED_CATEGORY_NOP,
XED_CATEGORY_PCLMULQDQ,
XED_CATEGORY_PCONFIG,
XED_CATEGORY_PKU,
XED_CATEGORY_POP,
XED_CATEGORY_PREFETCH,
XED_CATEGORY_PREFETCHWT1,
XED_CATEGORY_PTWRITE,
XED_CATEGORY_PUSH,
XED_CATEGORY_RDPID,
XED_CATEGORY_RDPRU,
XED_CATEGORY_RDRAND,
XED_CATEGORY_RDSEED,
XED_CATEGORY_RDWRFSGS,
XED_CATEGORY_RET,
XED_CATEGORY_ROTATE,
XED_CATEGORY_SCATTER,
XED_CATEGORY_SEGOP,
XED_CATEGORY_SEMAPHORE,
XED_CATEGORY_SERIALIZE,
XED_CATEGORY_SETCC,
XED_CATEGORY_SGX,
XED_CATEGORY_SHA,
XED_CATEGORY_SHIFT,
XED_CATEGORY_SMAP,
XED_CATEGORY_SSE,
XED_CATEGORY_STRINGOP,
XED_CATEGORY_STTNI,
XED_CATEGORY_SYSCALL,
XED_CATEGORY_SYSRET,
XED_CATEGORY_SYSTEM,
XED_CATEGORY_TBM,
XED_CATEGORY_TSX_LDTRK,
XED_CATEGORY_UINTR,
XED_CATEGORY_UNCOND_BR,
XED_CATEGORY_VAES,
XED_CATEGORY_VBMI2,
XED_CATEGORY_VEX,
XED_CATEGORY_VFMA,
XED_CATEGORY_VIA_PADLOCK,
XED_CATEGORY_VPCLMULQDQ,
XED_CATEGORY_VTX,
XED_CATEGORY_WAITPKG,
XED_CATEGORY_WIDENOP,
XED_CATEGORY_X87_ALU,
XED_CATEGORY_XOP,
XED_CATEGORY_XSAVE,
XED_CATEGORY_XSAVEOPT,
XED_CATEGORY_LAST);
/// This converts strings to #xed_category_enum_t types.
/// @param s A C-string.
/// @return #xed_category_enum_t
/// @ingroup ENUM
function str2xed_category_enum_t(s: PAnsiChar): TXED_Category_Enum; cdecl; external 'xed.dll';
/// This converts strings to #xed_category_enum_t types.
/// @param p An enumeration element of type xed_category_enum_t.
/// @return string
/// @ingroup ENUM
function xed_category_enum_t2str(const p: TXED_Category_Enum): PAnsiChar; cdecl; external 'xed.dll';
/// Returns the last element of the enumeration
/// @return xed_category_enum_t The last element of the enumeration.
/// @ingroup ENUM
function xed_category_enum_t_last:TXED_Category_Enum;cdecl; external 'xed.dll';
implementation
end.
|
// ************************************************************************
// ***************************** CEF4Delphi *******************************
// ************************************************************************
//
// CEF4Delphi is based on DCEF3 which uses CEF3 to embed a chromium-based
// browser in Delphi applications.
//
// The original license of DCEF3 still applies to CEF4Delphi.
//
// For more information about CEF4Delphi visit :
// https://www.briskbard.com/index.php?lang=en&pageid=cef
//
// Copyright © 2017 Salvador Díaz Fau. All rights reserved.
//
// ************************************************************************
// ************ vvvv Original license and comments below vvvv *************
// ************************************************************************
(*
* Delphi Chromium Embedded 3
*
* Usage allowed under the restrictions of the Lesser GNU General Public License
* or alternatively the restrictions of the Mozilla Public License 1.1
*
* 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.
*
* Unit owner : Henri Gourvest <hgourvest@gmail.com>
* Web site : http://www.progdigy.com
* Repository : http://code.google.com/p/delphichromiumembedded/
* Group : http://groups.google.com/group/delphichromiumembedded
*
* Embarcadero Technologies, Inc is not permitted to use or redistribute
* this source code without explicit permission.
*
*)
unit uCEFBinaryValue;
{$IFNDEF CPUX64}
{$ALIGN ON}
{$MINENUMSIZE 4}
{$ENDIF}
{$I cef.inc}
interface
uses
uCEFBaseRefCounted, uCEFInterfaces, uCEFTypes;
type
TCefBinaryValueRef = class(TCefBaseRefCountedRef, ICefBinaryValue)
protected
function IsValid: Boolean;
function IsOwned: Boolean;
function IsSame(const that: ICefBinaryValue): Boolean;
function IsEqual(const that: ICefBinaryValue): Boolean;
function Copy: ICefBinaryValue;
function GetSize: NativeUInt;
function GetData(buffer: Pointer; bufferSize, dataOffset: NativeUInt): NativeUInt;
public
class function UnWrap(data: Pointer): ICefBinaryValue;
class function New(const data: Pointer; dataSize: NativeUInt): ICefBinaryValue;
end;
TCefBinaryValueOwn = class(TCefBaseRefCountedOwn, ICefBinaryValue)
protected
function IsValid: Boolean;
function IsOwned: Boolean;
function IsSame(const that: ICefBinaryValue): Boolean;
function IsEqual(const that: ICefBinaryValue): Boolean;
function Copy: ICefBinaryValue;
function GetSize: NativeUInt;
function GetData(buffer: Pointer; bufferSize, dataOffset: NativeUInt): NativeUInt;
public
constructor Create;
end;
implementation
uses
uCEFMiscFunctions, uCEFLibFunctions;
// **********************************************
// ********** TCefBinaryValueRef **************
// **********************************************
function TCefBinaryValueRef.Copy: ICefBinaryValue;
begin
Result := UnWrap(PCefBinaryValue(FData).copy(PCefBinaryValue(FData)));
end;
function TCefBinaryValueRef.GetData(buffer: Pointer; bufferSize,
dataOffset: NativeUInt): NativeUInt;
begin
Result := PCefBinaryValue(FData).get_data(PCefBinaryValue(FData), buffer, bufferSize, dataOffset);
end;
function TCefBinaryValueRef.GetSize: NativeUInt;
begin
Result := PCefBinaryValue(FData).get_size(PCefBinaryValue(FData));
end;
function TCefBinaryValueRef.IsEqual(const that: ICefBinaryValue): Boolean;
begin
Result := PCefBinaryValue(FData).is_equal(PCefBinaryValue(FData), CefGetData(that)) <> 0;
end;
function TCefBinaryValueRef.IsOwned: Boolean;
begin
Result := PCefBinaryValue(FData).is_owned(PCefBinaryValue(FData)) <> 0;
end;
function TCefBinaryValueRef.IsSame(const that: ICefBinaryValue): Boolean;
begin
Result := PCefBinaryValue(FData).is_same(PCefBinaryValue(FData), CefGetData(that)) <> 0;
end;
function TCefBinaryValueRef.IsValid: Boolean;
begin
Result := PCefBinaryValue(FData).is_valid(PCefBinaryValue(FData)) <> 0;
end;
class function TCefBinaryValueRef.New(const data: Pointer; dataSize: NativeUInt): ICefBinaryValue;
begin
Result := UnWrap(cef_binary_value_create(data, dataSize));
end;
class function TCefBinaryValueRef.UnWrap(data: Pointer): ICefBinaryValue;
begin
if data <> nil then
Result := Create(data) as ICefBinaryValue else
Result := nil;
end;
// **********************************************
// ********** TCefBinaryValueOwn **************
// **********************************************
function cef_binary_value_is_valid(self: PCefBinaryValue): Integer; stdcall;
begin
Result := Ord(TCefBinaryValueOwn(CefGetObject(self)).IsValid);
end;
function cef_binary_value_is_owned(self: PCefBinaryValue): Integer; stdcall;
begin
Result := Ord(TCefBinaryValueOwn(CefGetObject(self)).IsOwned);
end;
function cef_binary_value_is_same(self, that: PCefBinaryValue):Integer; stdcall;
begin
Result := Ord(TCefBinaryValueOwn(CefGetObject(self)).IsSame(TCefBinaryValueRef.UnWrap(that)));
end;
function cef_binary_value_is_equal(self, that: PCefBinaryValue): Integer; stdcall;
begin
Result := Ord(TCefBinaryValueOwn(CefGetObject(self)).IsEqual(TCefBinaryValueRef.UnWrap(that)));
end;
function cef_binary_value_copy(self: PCefBinaryValue): PCefBinaryValue; stdcall;
begin
Result := CefGetData(TCefBinaryValueOwn(CefGetObject(self)).Copy);
end;
function cef_binary_value_get_size(self: PCefBinaryValue): NativeUInt; stdcall;
begin
Result := TCefBinaryValueOwn(CefGetObject(self)).GetSize;
end;
function cef_binary_value_get_data(self: PCefBinaryValue; buffer: Pointer; buffer_size, data_offset: NativeUInt): NativeUInt; stdcall;
begin
Result := TCefBinaryValueOwn(CefGetObject(self)).GetData(buffer, buffer_size, data_offset);
end;
constructor TCefBinaryValueOwn.Create;
begin
inherited CreateData(SizeOf(TCefBinaryValue));
with PCefBinaryValue(FData)^ do
begin
is_valid := cef_binary_value_is_valid;
is_owned := cef_binary_value_is_owned;
is_same := cef_binary_value_is_same;
is_equal := cef_binary_value_is_equal;
copy := cef_binary_value_copy;
get_size := cef_binary_value_get_size;
get_data := cef_binary_value_get_data;
end;
end;
function TCefBinaryValueOwn.IsValid: Boolean;
begin
Result := False;
end;
function TCefBinaryValueOwn.IsOwned: Boolean;
begin
Result := False;
end;
function TCefBinaryValueOwn.IsSame(const that: ICefBinaryValue): Boolean;
begin
Result := False;
end;
function TCefBinaryValueOwn.IsEqual(const that: ICefBinaryValue): Boolean;
begin
Result := False;
end;
function TCefBinaryValueOwn.Copy: ICefBinaryValue;
begin
Result := nil;
end;
function TCefBinaryValueOwn.GetSize: NativeUInt;
begin
Result := 0;
end;
function TCefBinaryValueOwn.GetData(buffer: Pointer; bufferSize, dataOffset: NativeUInt): NativeUInt;
begin
Result := 0;
end;
end.
|
unit TpPersistComponent;
interface
uses
SysUtils, Classes;
type
TTpPersistComponent = class(TComponent)
public
procedure SaveToStream(inStream: TStream); virtual;
procedure SaveToFile(const inFilename: string); virtual;
function SaveToText: string; virtual;
procedure LoadFromStream(inStream: TStream); virtual;
procedure LoadFromFile(const inFilename: string); virtual;
procedure LoadFromText(inOptsText: string); virtual;
end;
implementation
{ TTpPersistComponent }
procedure TTpPersistComponent.SaveToStream(inStream: TStream);
var
ms: TMemoryStream;
begin
ms := TMemoryStream.Create;
try
ms.WriteComponent(Self);
ms.Position := 0;
ObjectBinaryToText(ms, inStream);
finally
ms.Free;
end;
end;
function TTpPersistComponent.SaveToText: string;
var
ss: TStringStream;
begin
ss := TStringStream.Create('');
try
SaveToStream(ss);
Result := ss.DataString;
finally
ss.Free;
end;
end;
procedure TTpPersistComponent.SaveToFile(const inFilename: string);
var
fs: TFileStream;
begin
fs := TFileStream.Create(inFilename, fmCreate);
try
SaveToStream(fs);
finally
fs.Free;
end;
end;
procedure TTpPersistComponent.LoadFromStream(inStream: TStream);
var
ms: TMemoryStream;
begin
ms := TMemoryStream.Create;
try
ObjectTextToBinary(inStream, ms);
ms.Position := 0;
ms.ReadComponent(Self);
finally
ms.Free;
end;
end;
procedure TTpPersistComponent.LoadFromText(inOptsText: string);
var
ss: TStringStream;
begin
ss := TStringStream.Create(inOptsText);
try
LoadFromStream(ss);
finally
ss.Free;
end;
end;
procedure TTpPersistComponent.LoadFromFile(const inFilename: string);
var
fs: TFileStream;
begin
if not FileExists(inFilename) then
exit;
fs := TFileStream.Create(inFilename, fmOpenRead);
try
LoadFromStream(fs);
finally
fs.Free;
end;
end;
end.
|
unit uObjStringList;
interface
uses classes;
type
TObjStringList = class(TStringList)
private
procedure AutoFreeObject(index:integer); virtual;
public
destructor Destroy; override;
procedure Clear; override;
end;
implementation
procedure TObjStringList.AutoFreeObject(index : integer );
begin
// make sure index is in range
if (Index >= 0) and (index < Count ) then
begin
// call destructor of object
if assigned(objects[index]) then
objects[index].free;
end;
end;
procedure TObjStringList.Clear;
var
i, iTot : integer;
begin
// remove the objects before clearing
iTot := count - 1;
for i := 0 to iTot do
AutoFreeObject(i);
inherited Clear;
end;
destructor TObjStringList.Destroy;
begin
Clear;
inherited Destroy;
end;
end.
|
unit PersDatesAcc;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData,
cxDataStorage, cxEdit, DB, cxDBData, cxCheckBox, dxBar, dxBarExtItems,
cxSplitter, cxLabel, cxContainer, cxTextEdit, cxMaskEdit, cxDBEdit,
ExtCtrls, cxGridLevel, cxGridCustomTableView, cxGridTableView,
cxGridDBTableView, cxClasses, cxControls, cxGridCustomView, cxGrid,
dxDockPanel, dxDockControl, cxMemo, ZcxLocateBar,
FIBQuery, pFIBQuery, ZProc, Dates, ZTypes, ZMessages,
pFIBStoredProc, FIBDatabase, pFIBDatabase, FIBDataSet, pFIBDataSet, IBase,
cxCheckListBox, cxGridBandedTableView, cxGridDBBandedTableView, Unit_ZGlobal_Consts,
dxStatusBar, ActnList, unit_NumericConsts,
PackageLoad, z_dmCommonStyles, cxDBLabel, pFIBProps,
cxGridCustomPopupMenu, cxGridPopupMenu, zWait, Menus;
type
TFZDateAcc = class(TForm)
DSource3: TDataSource;
DSource1: TDataSource;
DataBase: TpFIBDatabase;
DSet3: TpFIBDataSet;
DSet1: TpFIBDataSet;
ReadTransaction: TpFIBTransaction;
WriteTransaction: TpFIBTransaction;
StoredProc: TpFIBStoredProc;
Styles: TcxStyleRepository;
dxBarDockControl2: TdxBarDockControl;
GridTableViewStyleSheetDevExpress: TcxGridTableViewStyleSheet;
cxStyle1: TcxStyle;
cxStyle2: TcxStyle;
cxStyle3: TcxStyle;
cxStyle4: TcxStyle;
cxStyle5: TcxStyle;
cxStyle6: TcxStyle;
cxStyle7: TcxStyle;
cxStyle8: TcxStyle;
cxStyle9: TcxStyle;
cxStyle10: TcxStyle;
cxStyle11: TcxStyle;
cxStyle12: TcxStyle;
cxStyle13: TcxStyle;
cxStyle14: TcxStyle;
GridBandedTableViewStyleSheetDevExpress: TcxGridBandedTableViewStyleSheet;
cxStyle15: TcxStyle;
cxStyle16: TcxStyle;
cxStyle17: TcxStyle;
cxStyle18: TcxStyle;
cxStyle19: TcxStyle;
cxStyle20: TcxStyle;
cxStyle21: TcxStyle;
cxStyle22: TcxStyle;
cxStyle23: TcxStyle;
cxStyle24: TcxStyle;
cxStyle25: TcxStyle;
cxStyle26: TcxStyle;
cxStyle27: TcxStyle;
cxStyle28: TcxStyle;
cxStyle29: TcxStyle;
cxStyle30: TcxStyle;
DSet2: TpFIBDataSet;
DSource2: TDataSource;
dxStatusBar1: TdxStatusBar;
ActionList: TActionList;
ActionSystem: TAction;
DockSite: TdxDockSite;
dxLayoutDockSite1: TdxLayoutDockSite;
DockPanel2: TdxDockPanel;
Grid3: TcxGrid;
Grid3DBBandedTableView1: TcxGridDBBandedTableView;
Grid3ClVo: TcxGridDBBandedColumn;
Grid3ClVidOpl: TcxGridDBBandedColumn;
Grid3ClSumma: TcxGridDBBandedColumn;
Grid3ClP1: TcxGridDBBandedColumn;
Grid3ClDepartment: TcxGridDBBandedColumn;
Grid3ClSmeta: TcxGridDBBandedColumn;
Grid3ClKodSetup3: TcxGridDBBandedColumn;
Grid3ClReCount: TcxGridDBBandedColumn;
Grid3ClNDay: TcxGridDBBandedColumn;
Grid3ClClock: TcxGridDBBandedColumn;
Grid3ClStavkaPercent: TcxGridDBBandedColumn;
Grid3Level1: TcxGridLevel;
PanelGrid3DopData: TPanel;
DBMaskEditDepartment: TcxDBMaskEdit;
DBMaskEditSmeta: TcxDBMaskEdit;
LabelDepartment: TcxLabel;
LabelSmeta: TcxLabel;
DBMaskEditPost: TcxDBMaskEdit;
LabelPost: TcxLabel;
cxSplitter1: TcxSplitter;
DBMaskEditCategory: TcxDBMaskEdit;
LabelCategory: TcxLabel;
cxDBMaskEdit1: TcxDBMaskEdit;
procedure ExitBtnClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure Grid3ClP1GetDisplayText(Sender: TcxCustomGridTableItem;
ARecord: TcxCustomGridRecord; var AText: String);
procedure Grid3ClKodSetup3GetDisplayText(
Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
var AText: String);
procedure Grid3ClNDayGetDisplayText(
Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
var AText: String);
procedure Grid3ClClockGetDisplayText(
Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
var AText: String);
procedure Grid2ClKodSetupGetDisplayText(Sender: TcxCustomGridTableItem;
ARecord: TcxCustomGridRecord; var AText: String);
procedure DSet3AfterOpen(DataSet: TDataSet);
procedure Grid3DBBandedTableView1DataControllerSummaryFooterSummaryItemsSummary(
ASender: TcxDataSummaryItems; Arguments: TcxSummaryEventArguments;
var OutArguments: TcxSummaryEventOutArguments);
procedure RefreshBtnClick(Sender: TObject);
procedure dxStatusBar1Resize(Sender: TObject);
procedure PanelGrid3DopDataResize(Sender: TObject);
procedure ActionSystemExecute(Sender: TObject);
procedure Grid3DBBandedTableView1FocusedRecordChanged(
Sender: TcxCustomGridTableView; APrevFocusedRecord,
AFocusedRecord: TcxCustomGridRecord;
ANewItemRecordFocusingChanged: Boolean);
procedure dxBarButton1Click(Sender: TObject);
procedure Grid3DBBandedTableView1DataControllerSummaryDefaultGroupSummaryItemsSummary(
ASender: TcxDataSummaryItems; Arguments: TcxSummaryEventArguments;
var OutArguments: TcxSummaryEventOutArguments);
private
PMode:TZTypeData;
PLanguageIndex:byte;
pStyles:TStylesDM;
pWidth:integer;
public
constructor Create(AOwner : TComponent;DB:TISC_DB_HANDLE; id_anketa:int64; kod_setup:Integer; is_science:Integer);reintroduce;
end;
implementation
uses StrUtils, Math;
{$R *.dfm}
constructor TFZDateAcc.Create(AOwner : TComponent;DB:TISC_DB_HANDLE; id_anketa:int64; kod_setup:Integer; is_science:Integer);
var i:Byte;
wf:TForm;
begin
Inherited Create(AOwner);
try
wf:=ShowWaitForm(Application.MainForm);
//******************************************************************************
pWidth := PanelGrid3DopData.Width-DBMaskEditDepartment.Width;
PLanguageIndex:=LanguageIndex;
Caption := 'Розшифровка персоніфікації';
//******************************************************************************
//******************************************************************************
Grid3ClVo.Caption := GridClKodVidOpl_Caption[PLanguageIndex];
Grid3ClVidOpl.Caption := GridClNameVidopl_Caption[PLanguageIndex];
Grid3ClSumma.Caption := GridClSumma_Caption[PLanguageIndex];
Grid3ClP1.Caption := GridClP1_Caption[PLanguageIndex];
Grid3ClDepartment.Caption := GridClKodDepartment_Caption[PLanguageIndex];
Grid3ClSmeta.Caption := GridClKodSmeta_Caption[PLanguageIndex];
Grid3ClKodSetup3.Caption := GridClKodSetup_Caption[PLanguageIndex];
Grid3ClReCount.Caption := '';
Grid3ClNDay.Caption := GridClNday_Caption[PLanguageIndex];
Grid3ClClock.Caption := GridClClock_Caption[PLanguageIndex];
Grid3ClStavkaPercent.Caption := GridClStavkaPercent_Caption[PLanguageIndex];
//******************************************************************************
LabelDepartment.Caption := LabelDepartment_Caption[PLanguageIndex];
LabelSmeta.Caption := LabelSmeta_Caption[PLanguageIndex];
LabelPost.Caption := LabelPost_Caption[PLanguageIndex];
LabelCategory.Caption := LabelCategory_Caption[PLanguageIndex];
//******************************************************************************
Grid3DBBandedTableView1.DataController.Summary.FooterSummaryItems[1].Format := Itogo_Caption[PLanguageIndex]+':';
//******************************************************************************
PanelGrid3DopData.Color := Grid3DBBandedTableView1.Styles.Background.Color;
cxSplitter1.Color := Grid3DBBandedTableView1.Styles.Header.Color;
//******************************************************************************
for i:=0 to dxStatusBar1.Panels.Count-1 do
dxStatusBar1.Panels[i].Width := dxStatusBar1.Width div dxStatusBar1.Panels.Count;
dxStatusBar1.Panels[0].Text:= RefreshBtn_Hint[PLanguageIndex];
dxStatusBar1.Panels[1].Text:= LocateBtn_Hint[PLanguageIndex];
dxStatusBar1.Panels[2].Text:= LocateNextBtn_Hint[PLanguageIndex];
dxStatusBar1.Panels[3].Text:= FilterBtn_Hint[PLanguageIndex];
dxStatusBar1.Panels[4].Text:= PrintBtn_Hint[PLanguageIndex];
dxStatusBar1.Panels[5].Text:= ExitBtn_Hint[PLanguageIndex];
//******************************************************************************
DSet3.SQLs.SelectSQL.Text:='SELECT * FROM Z_PERSONIFICATION_ACC_S('+IntToStr(id_anketa)+') where kod_setup3='+IntTostr(kod_setup)+
' and is_science='+IntTostr(is_science)+' order by Kod_vidopl';
DataBase.Handle := DB;
DSet3.Open;
//******************************************************************************
pStyles := TStylesDM.Create(self);
Grid3DBBandedTableView1.Styles.StyleSheet := pStyles.GridBandedTableViewStyleSheetDevExpress;
finally
CloseWaitForm(wf);
end;
end;
procedure TFZDateAcc.ExitBtnClick(Sender: TObject);
begin
Close;
end;
procedure TFZDateAcc.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
if ReadTransaction.InTransaction then ReadTransaction.Commit;
if FormStyle=fsMDIChild then Action:=caFree;
end;
procedure TFZDateAcc.FormCreate(Sender: TObject);
begin
Grid3DBBandedTableView1.DataController.Summary.FooterSummaryItems[1].Format := Itogo_Caption[PLanguageIndex];
end;
procedure TFZDateAcc.Grid3ClP1GetDisplayText(
Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
var AText: String);
begin
if AText='False' then
AText:=GridClP1_Text_False[PLanguageIndex];
if AText='True' then
AText:=GridClP1_Text_True[PLanguageIndex];
end;
procedure TFZDateAcc.Grid3ClKodSetup3GetDisplayText(
Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
var AText: String);
begin
Atext:=KodSetupToPeriod(StrToInt(Atext),1);
end;
procedure TFZDateAcc.Grid3ClNDayGetDisplayText(
Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
var AText: String);
begin
if StrToInt(AText)=0 then AText:='';
end;
procedure TFZDateAcc.Grid3ClClockGetDisplayText(
Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
var AText: String);
begin
if (AText<>'') and (StrToFloat(AText)=0) then AText:='';
end;
procedure TFZDateAcc.Grid2ClKodSetupGetDisplayText(
Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
var AText: String);
begin
Atext:=KodSetupToPeriod(StrToInt(AText),0);
end;
procedure TFZDateAcc.DSet3AfterOpen(DataSet: TDataSet);
begin
Grid3DBBandedTableView1.ViewData.Expand(False);
end;
procedure TFZDateAcc.Grid3DBBandedTableView1DataControllerSummaryFooterSummaryItemsSummary(
ASender: TcxDataSummaryItems; Arguments: TcxSummaryEventArguments;
var OutArguments: TcxSummaryEventOutArguments);
var AItem: TcxGridTableSummaryItem;
begin
AItem := TcxGridTableSummaryItem(Arguments.SummaryItem);
if (AItem.Column = Grid3ClSumma) and
(AItem.Kind = skSum) and (AItem.Position = spFooter) then
begin
if (VarToStr(Grid3DBBandedTableView1.DataController.Values[Arguments.RecordIndex, Grid3ClP1.Index]) ='F')
then OutArguments.Value:=-OutArguments.Value;
end;
end;
procedure TFZDateAcc.RefreshBtnClick(Sender: TObject);
begin
DSet3.Close;
DSet2.Close;
DSet1.CloseOpen(True);
DSet2.Open;
DSet3.Open;
end;
procedure TFZDateAcc.dxStatusBar1Resize(Sender: TObject);
var i:byte;
begin
for i:=0 to dxStatusBar1.Panels.Count-1 do
dxStatusBar1.Panels[i].Width := dxStatusBar1.Width div dxStatusBar1.Panels.Count;
end;
procedure TFZDateAcc.PanelGrid3DopDataResize(Sender: TObject);
begin
DBMaskEditDepartment.Width:=PanelGrid3DopData.Width-pWidth;
DBMaskEditSmeta.Width:=PanelGrid3DopData.Width-pWidth;
DBMaskEditPost.Width:=PanelGrid3DopData.Width-pWidth;
DBMaskEditCategory.Width:=PanelGrid3DopData.Width-pWidth;
end;
procedure TFZDateAcc.ActionSystemExecute(Sender: TObject);
begin
ZShowMessage('System Data','ID_MAN = '+VarToStrDef(DSet2['ID_MAN'],'NULL')+#13+
'ID_GROUP_ACCOUNT = '+VarToStrDef(DSet2['ID_GROUP_ACCOUNT'],'NULL')+#13+
'KOD_SETUP_2 = '+VarToStrDef(DSet2['KOD_SETUP_2'],'NULL'),mtInformation,[mbOk]);
end;
procedure TFZDateAcc.Grid3DBBandedTableView1FocusedRecordChanged(
Sender: TcxCustomGridTableView; APrevFocusedRecord,
AFocusedRecord: TcxCustomGridRecord;
ANewItemRecordFocusingChanged: Boolean);
begin
if (AFocusedRecord=nil) or (AFocusedRecord.Expandable) then
begin
DBMaskEditDepartment.DataBinding.DataSource := nil;
DBMaskEditSmeta.DataBinding.DataSource := nil;
DBMaskEditPost.DataBinding.DataSource := nil;
DBMaskEditCategory.DataBinding.DataSource := nil;
end
else
begin
DBMaskEditDepartment.DataBinding.DataSource := DSource3;
DBMaskEditSmeta.DataBinding.DataSource := DSource3;
DBMaskEditPost.DataBinding.DataSource := DSource3;
DBMaskEditCategory.DataBinding.DataSource := DSource3;
end;
end;
procedure TFZDateAcc.dxBarButton1Click(Sender: TObject);
begin
Grid3Level1.GridView := GetTable(DSource2,'KOD_SETUP_2');
end;
procedure TFZDateAcc.Grid3DBBandedTableView1DataControllerSummaryDefaultGroupSummaryItemsSummary(
ASender: TcxDataSummaryItems; Arguments: TcxSummaryEventArguments;
var OutArguments: TcxSummaryEventOutArguments);
var AItem: TcxGridTableSummaryItem;
begin
AItem := TcxGridTableSummaryItem(Arguments.SummaryItem);
if (AItem.Column = Grid3ClSumma) and
(AItem.Kind = skSum) and (AItem.Position = spGroup) then
begin
if (AItem.Column.GroupIndex<Grid3ClP1.GroupIndex) and (VarToStr(Grid3DBBandedTableView1.DataController.Values[Arguments.RecordIndex, Grid3ClP1.Index]) ='F')
then OutArguments.Value:=-OutArguments.Value;
end;
end;
end.
|
unit uFileSystemSetFilePropertyOperation;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, LazUTF8,
uFileSourceSetFilePropertyOperation,
uFileSource,
uFileSourceOperationOptions,
uFileSourceOperationUI,
uFile,
uFileProperty,
uDescr;
type
{ TFileSystemSetFilePropertyOperation }
TFileSystemSetFilePropertyOperation = class(TFileSourceSetFilePropertyOperation)
private
FFullFilesTree: TFiles; // source files including all files/dirs in subdirectories
FStatistics: TFileSourceSetFilePropertyOperationStatistics; // local copy of statistics
FDescription: TDescription;
// Options.
FSymLinkOption: TFileSourceOperationOptionSymLink;
FFileExistsOption: TFileSourceOperationUIResponse;
FDirExistsOption: TFileSourceOperationUIResponse;
function RenameFile(aFile: TFile; NewName: String): TSetFilePropertyResult;
protected
function SetNewProperty(aFile: TFile; aTemplateProperty: TFileProperty): TSetFilePropertyResult; override;
public
constructor Create(aTargetFileSource: IFileSource;
var theTargetFiles: TFiles;
var theNewProperties: TFileProperties); override;
destructor Destroy; override;
procedure Initialize; override;
procedure MainExecute; override;
procedure Finalize; override;
end;
implementation
uses
uGlobs, uLng, DCDateTimeUtils, uFileSystemUtil,
DCOSUtils, DCStrUtils, DCBasicTypes, uAdministrator
{$IF DEFINED(UNIX)}
, BaseUnix, DCUnix
{$ENDIF}
;
constructor TFileSystemSetFilePropertyOperation.Create(aTargetFileSource: IFileSource;
var theTargetFiles: TFiles;
var theNewProperties: TFileProperties);
begin
FSymLinkOption := fsooslNone;
FFullFilesTree := nil;
inherited Create(aTargetFileSource, theTargetFiles, theNewProperties);
// Assign after calling inherited constructor.
FSupportedProperties := [fpName,
{$IF DEFINED(UNIX)}
// Set owner/group before MODE because it clears SUID bit.
fpOwner,
{$ENDIF}
fpAttributes,
fpModificationTime,
fpCreationTime,
fpLastAccessTime];
if gProcessComments then begin
FDescription := TDescription.Create(False);
end;
end;
destructor TFileSystemSetFilePropertyOperation.Destroy;
begin
inherited Destroy;
if Recursive then
begin
if Assigned(FFullFilesTree) then
FreeAndNil(FFullFilesTree);
end;
if Assigned(FDescription) then
begin
FDescription.SaveDescription;
FreeAndNil(FDescription);
end;
end;
procedure TFileSystemSetFilePropertyOperation.Initialize;
var
TotalBytes: Int64;
begin
// Get initialized statistics; then we change only what is needed.
FStatistics := RetrieveStatistics;
if not Recursive then
begin
FFullFilesTree := TargetFiles;
FStatistics.TotalFiles := FFullFilesTree.Count;
end
else
begin
FillAndCount(TargetFiles, True, False,
FFullFilesTree,
FStatistics.TotalFiles,
TotalBytes); // gets full list of files (recursive)
end;
end;
procedure TFileSystemSetFilePropertyOperation.MainExecute;
var
aFile: TFile;
aTemplateFile: TFile;
CurrentFileIndex: Integer;
begin
for CurrentFileIndex := 0 to FFullFilesTree.Count - 1 do
begin
aFile := FFullFilesTree[CurrentFileIndex];
FStatistics.CurrentFile := aFile.FullPath;
UpdateStatistics(FStatistics);
if Assigned(TemplateFiles) and (CurrentFileIndex < TemplateFiles.Count) then
aTemplateFile := TemplateFiles[CurrentFileIndex]
else
aTemplateFile := nil;
SetProperties(CurrentFileIndex, aFile, aTemplateFile);
with FStatistics do
begin
DoneFiles := DoneFiles + 1;
UpdateStatistics(FStatistics);
end;
CheckOperationState;
end;
end;
procedure TFileSystemSetFilePropertyOperation.Finalize;
begin
end;
function TFileSystemSetFilePropertyOperation.SetNewProperty(aFile: TFile;
aTemplateProperty: TFileProperty): TSetFilePropertyResult;
begin
Result := sfprSuccess;
try
case aTemplateProperty.GetID of
fpName:
if (aTemplateProperty as TFileNameProperty).Value <> aFile.Name then
begin
Result := RenameFile(
aFile,
(aTemplateProperty as TFileNameProperty).Value);
if (Result = sfprSuccess) and gProcessComments then
begin
FDescription.Rename(aFile.FullPath, (aTemplateProperty as TFileNameProperty).Value);
end;
end
else
Result := sfprSkipped;
fpAttributes:
if (aTemplateProperty as TFileAttributesProperty).Value <>
(aFile.Properties[fpAttributes] as TFileAttributesProperty).Value then
begin
if not FileSetAttrUAC(
aFile.FullPath,
(aTemplateProperty as TFileAttributesProperty).Value) then
begin
Result := sfprError;
end;
end
else
Result := sfprSkipped;
fpModificationTime:
if (aTemplateProperty as TFileModificationDateTimeProperty).Value <>
(aFile.Properties[fpModificationTime] as TFileModificationDateTimeProperty).Value then
begin
if not FileSetTimeUAC(
aFile.FullPath,
DateTimeToFileTime((aTemplateProperty as TFileModificationDateTimeProperty).Value),
0,
0) then
begin
Result := sfprError;
end;
end
else
Result := sfprSkipped;
fpCreationTime:
if (aTemplateProperty as TFileCreationDateTimeProperty).Value <>
(aFile.Properties[fpCreationTime] as TFileCreationDateTimeProperty).Value then
begin
if not FileSetTimeUAC(
aFile.FullPath,
0,
DateTimeToFileTime((aTemplateProperty as TFileCreationDateTimeProperty).Value),
0) then
begin
Result := sfprError;
end;
end
else
Result := sfprSkipped;
fpLastAccessTime:
if (aTemplateProperty as TFileLastAccessDateTimeProperty).Value <>
(aFile.Properties[fpLastAccessTime] as TFileLastAccessDateTimeProperty).Value then
begin
if not FileSetTimeUAC(
aFile.FullPath,
0,
0,
DateTimeToFileTime((aTemplateProperty as TFileLastAccessDateTimeProperty).Value)) then
begin
Result := sfprError;
end;
end
else
Result := sfprSkipped;
{$IF DEFINED(UNIX)}
fpOwner:
begin
if fplchown(aFile.FullPath, (aTemplateProperty as TFileOwnerProperty).Owner,
(aTemplateProperty as TFileOwnerProperty).Group) <> 0 then
begin
Result := sfprError;;
end;
end
{$ENDIF}
else
raise Exception.Create('Trying to set unsupported property');
end;
except
on e: EDateOutOfRange do
begin
if not gSkipFileOpError then
case AskQuestion(rsMsgLogError + Format(rsMsgErrDateNotSupported, [DateTimeToStr(e.DateTime)]), '',
[fsourSkip, fsourAbort],
fsourSkip, fsourAbort) of
fsourSkip:
Result := sfprSkipped;
fsourAbort:
RaiseAbortOperation;
end;
end;
on e: EConvertError do
begin
if not gSkipFileOpError then
case AskQuestion(rsMsgLogError + e.Message, '', [fsourSkip, fsourAbort],
fsourSkip, fsourAbort) of
fsourSkip:
Result := sfprSkipped;
fsourAbort:
RaiseAbortOperation;
end;
end;
end;
end;
function TFileSystemSetFilePropertyOperation.RenameFile(aFile: TFile; NewName: String): TSetFilePropertyResult;
var
OldName: String;
function AskIfOverwrite(Attrs: TFileAttrs): TFileSourceOperationUIResponse;
var
sQuestion: String;
begin
if DCOSUtils.FPS_ISDIR(Attrs) then
begin
if FDirExistsOption <> fsourInvalid then Exit(FDirExistsOption);
Result := AskQuestion(Format(rsMsgErrDirExists, [NewName]), '',
[fsourSkip, fsourSkipAll, fsourAbort], fsourSkip, fsourAbort);
if Result = fsourSkipAll then
begin
FDirExistsOption:= fsourSkip;
Result:= FDirExistsOption;
end;
end
else begin
if FFileExistsOption <> fsourInvalid then Exit(FFileExistsOption);
sQuestion:= FileExistsMessage(NewName, aFile.FullPath, aFile.Size, aFile.ModificationTime);
Result := AskQuestion(sQuestion, '',
[fsourOverwrite, fsourSkip, fsourAbort, fsourOverwriteAll,
fsourSkipAll], fsourOverwrite, fsourAbort);
case Result of
fsourOverwriteAll:
begin
Result:= fsourOverwrite;
FFileExistsOption:= Result;
end;
fsourSkipAll:
begin
Result:= fsourSkip;
FFileExistsOption:= Result;
end;
end;
end;
end;
var
{$IFDEF UNIX}
OldAttr, NewAttr: TFileAttributeData;
{$ELSE}
NewFileAttrs: TFileAttrs;
{$ENDIF}
begin
OldName:= aFile.FullPath;
if FileSource.GetPathType(NewName) <> ptAbsolute then
begin
NewName := ExtractFilePath(OldName) + TrimPath(NewName);
end;
if OldName = NewName then
Exit(sfprSkipped);
{$IFDEF UNIX}
// Check if target file exists.
if FileGetAttrUAC(NewName, NewAttr) then
begin
// Cannot overwrite file by directory and vice versa
if fpS_ISDIR(NewAttr.FindData.st_mode) <> aFile.IsDirectory then
Exit(sfprError);
// Special case when filenames differ only by case,
// see comments in mbRenameFile function for details
if (UTF8LowerCase(OldName) <> UTF8LowerCase(NewName)) then
OldAttr.FindData.st_ino:= not NewAttr.FindData.st_ino
else begin
if not FileGetAttrUAC(OldName, OldAttr) then
Exit(sfprError);
end;
// Check if source and target are the same files (same inode and same device).
if (OldAttr.FindData.st_ino = NewAttr.FindData.st_ino) and
(OldAttr.FindData.st_dev = NewAttr.FindData.st_dev) and
// Check number of links, if it is 1 then source and target names most
// probably differ only by case on a case-insensitive filesystem.
((NewAttr.FindData.st_nlink = 1) {$IFNDEF DARWIN}or fpS_ISDIR(NewAttr.FindData.st_mode){$ENDIF}) then
begin
// File names differ only by case on a case-insensitive filesystem.
end
else begin
case AskIfOverwrite(NewAttr.FindData.st_mode) of
fsourOverwrite: ; // continue
fsourSkip:
Exit(sfprSkipped);
fsourAbort:
RaiseAbortOperation;
end;
end;
end;
{$ELSE}
// Windows XP doesn't allow two filenames that differ only by case (even on NTFS).
if UTF8LowerCase(OldName) <> UTF8LowerCase(NewName) then
begin
NewFileAttrs := FileGetAttrUAC(NewName);
if NewFileAttrs <> faInvalidAttributes then // If target file exists.
begin
// Cannot overwrite file by directory and vice versa
if fpS_ISDIR(NewFileAttrs) <> aFile.IsDirectory then
Exit(sfprError);
case AskIfOverwrite(NewFileAttrs) of
fsourOverwrite: ; // continue
fsourSkip:
Exit(sfprSkipped);
fsourAbort:
RaiseAbortOperation;
end;
end;
end;
{$ENDIF}
if RenameFileUAC(OldName, NewName) then
Result := sfprSuccess
else
Result := sfprError;
end;
end.
|
{-------------------------------------------------------------------------------
Copyright 2012 Ethea S.r.l.
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 Kitto.Ext.Service;
interface
uses
Windows, Messages, SysUtils, Classes, SvcMgr,
Kitto.Ext.Application;
type
TKExtService = class(TService)
procedure ServiceStart(Sender: TService; var Started: Boolean);
procedure ServiceStop(Sender: TService; var Stopped: Boolean);
procedure ServiceShutdown(Sender: TService);
procedure ServiceCreate(Sender: TObject);
procedure ServiceAfterInstall(Sender: TService);
private
FThread: TKExtAppThread;
FServiceDescription: string;
function CreateThread: TKExtAppThread;
procedure StopAndFreeThread;
procedure SetDescription(const ADescription: string);
procedure Configure;
public
function GetServiceController: TServiceController; override;
end;
var
KExtService: TKExtService;
implementation
{$R *.dfm}
uses
Winapi.WinSvc,
EF.Localization, EF.Logger, Kitto.Config;
procedure ServiceController(CtrlCode: DWord); stdcall;
begin
KExtService.Controller(CtrlCode);
end;
{ TKExtService }
procedure TKExtService.SetDescription(const ADescription: string);
var
LSCManager: SC_HANDLE;
LService: SC_HANDLE;
LDescription: SERVICE_DESCRIPTION;
begin
LSCManager := OpenSCManager(nil, nil, SC_MANAGER_ALL_ACCESS);
if LSCManager <> 0 then
begin
LService := OpenService(LSCManager, PChar(Name), STANDARD_RIGHTS_REQUIRED or SERVICE_CHANGE_CONFIG);
if LService <> 0 then
begin
LDescription.lpDescription := PChar(ADescription);
ChangeServiceConfig2(LService, SERVICE_CONFIG_DESCRIPTION, @LDescription);
CloseServiceHandle(LService);
end;
CloseServiceHandle(LSCManager);
end;
end;
procedure TKExtService.ServiceCreate(Sender: TObject);
begin
Name := TKConfig.AppName;
DisplayName := FServiceDescription;
Configure;
end;
procedure TKExtService.ServiceShutdown(Sender: TService);
begin
TEFLogger.Instance.Log('Service shutdown.');
StopAndFreeThread;
end;
procedure TKExtService.Configure;
var
LConfig: TKConfig;
begin
LConfig := TKConfig.Create;
try
FServiceDescription := _(LConfig.AppTitle);
finally
FreeAndNil(LConfig);
end;
end;
procedure TKExtService.StopAndFreeThread;
begin
if Assigned(FThread) then
begin
FThread.Terminate;
FThread.WaitFor;
FreeAndNil(FThread);
end;
end;
function TKExtService.CreateThread: TKExtAppThread;
begin
Result := TKExtAppThread.Create(True);
Result.Configure;
end;
function TKExtService.GetServiceController: TServiceController;
begin
Result := ServiceController;
end;
procedure TKExtService.ServiceAfterInstall(Sender: TService);
begin
SetDescription(FServiceDescription);
end;
procedure TKExtService.ServiceStart(Sender: TService; var Started: Boolean);
begin
TEFLogger.Instance.Log('Service start. Creating thread...');
FThread := CreateThread;
TEFLogger.Instance.Log('Starting thread...');
FThread.Start;
end;
procedure TKExtService.ServiceStop(Sender: TService; var Stopped: Boolean);
begin
StopAndFreeThread;
end;
end.
|
// quadratic function solver
function Solve(a, b, c : Real; var x1, x2 : Real) : Boolean;
var d : Real;
begin
d := (b*b) - (4*a*c);
if d < 0 then Result := False
else
begin
x1 := (-1*b + sqrt(d)) / (2*a);
x2 := (-1*b - sqrt(d)) / (2*a);
Result := True;
end;
end;
// function tester
var a, b, c, x1, x2 : Real;
hasSolution : Boolean;
a := 1;
b := -5;//2;
c := 6;//4;
hasSolution := Solve(a, b, c, x1, x2);
if hasSolution = True then Writeln(x1:4:2, x2:4:2)
else Writeln('No Solution');
|
unit NosoTime;
{
Nosotime 1.2
December 12th, 2022
Noso Time Unit for time synchronization on Noso project.
Requires indy package. (To-do: remove this dependancy)
Changes:
- Random use of NTP servers.
- Async process limited to every 5 seconds.
- Block time related functions.
}
{$mode ObjFPC}{$H+}
interface
uses
Classes, SysUtils, IdSNTP, DateUtils, strutils;
Type
TThreadUpdateOffset = class(TThread)
private
Hosts: string;
protected
procedure Execute; override;
public
constructor Create(const CreatePaused: Boolean; const THosts:string);
end;
Function GetNetworkTimestamp(hostname:string):int64;
function TimestampToDate(timestamp:int64):String;
Function GetTimeOffset(NTPServers:String):int64;
Function UTCTime:Int64;
Function UTCTimeStr:String;
Procedure UpdateOffset(NTPServers:String);
function TimeSinceStamp(Lvalue:int64):string;
Function BlockAge():integer;
Function NextBlockTimeStamp():Int64;
Function IsBlockOpen():boolean;
Var
NosoT_TimeOffset : int64 = 0;
NosoT_LastServer : string = '';
NosoT_LastUpdate : int64 = 0;
IMPLEMENTATION
constructor TThreadUpdateOffset.Create(const CreatePaused: Boolean; const THosts:string);
begin
inherited Create(CreatePaused);
Hosts := THosts;
end;
procedure TThreadUpdateOffset.Execute;
Begin
GetTimeOffset(Hosts);
End;
{Returns the data from the specified NTP server [Hostname]}
Function GetNetworkTimestamp(hostname:string):int64;
var
NTPClient: TIdSNTP;
begin
result := 0;
NTPClient := TIdSNTP.Create(nil);
TRY
NTPClient.Host := hostname;
NTPClient.Active := True;
NTPClient.ReceiveTimeout:=500;
result := DateTimeToUnix(NTPClient.DateTime);
if result <0 then result := 0;
EXCEPT on E:Exception do
result := 0;
END; {TRY}
NTPClient.Free;
end;
{Returns a UNIX timestamp in a human readeable format}
function TimestampToDate(timestamp:int64):String;
begin
result := DateTimeToStr(UnixToDateTime(TimeStamp));
end;
{
Uses a random NTP server from the list provided to set the value of the local variables.
NTPservers string must use NosoCFG format: server1:server2:server3:....serverX:
If directly invoked, will block the main thread until finish. (not recommended except on app launchs)
}
Function GetTimeOffset(NTPServers:String):int64;
var
Counter : integer = 0;
ThisNTP : int64;
MyArray : array of string;
RanNumber : integer;
Begin
Result := 0;
NTPServers := StringReplace(NTPServers,':',' ',[rfReplaceAll, rfIgnoreCase]);
NTPServers := Trim(NTPServers);
MyArray := SplitString(NTPServers,' ');
Rannumber := Random(length(MyArray));
For Counter := 0 to length(MyArray)-1 do
begin
ThisNTP := GetNetworkTimestamp(MyArray[Rannumber]);
if ThisNTP>0 then
begin
Result := ThisNTP - DateTimeToUnix(Now);
NosoT_LastServer := MyArray[Rannumber];
NosoT_LastUpdate := UTCTime;
break;
end;
Inc(RanNumber);
If RanNumber >= length(MyArray)-1 then RanNumber := 0;
end;
NosoT_TimeOffset := Result;
End;
{Returns the UTC UNIX timestamp}
Function UTCTime:Int64;
Begin
Result := DateTimeToUnix(Now, False) +NosoT_TimeOffset;
End;
{Implemented for easy compatibility with nosowallet}
Function UTCTimeStr:String;
Begin
Result := InttoStr(DateTimeToUnix(Now, False) +NosoT_TimeOffset);
End;
{Implemented to allow an async update of the offset; can be called every 5 seconds max}
Procedure UpdateOffset(NTPServers:String);
const
LastRun : int64 = 0;
var
LThread : TThreadUpdateOffset;
Begin
if UTCTime <= LastRun+4 then exit;
LastRun := UTCTime;
LThread := TThreadUpdateOffset.Create(true,NTPservers);
LThread.FreeOnTerminate:=true;
LThread.Start;
End;
{Tool: returns a simple string with the time elapsed since the provided timestamp [LValue]}
function TimeSinceStamp(Lvalue:int64):string;
var
Elapsed : Int64 = 0;
Begin
Elapsed := UTCTime - Lvalue;
if Elapsed div 60 < 1 then result := '<1m'
else if Elapsed div 3600 < 1 then result := IntToStr(Elapsed div 60)+'m'
else if Elapsed div 86400 < 1 then result := IntToStr(Elapsed div 3600)+'h'
else if Elapsed div 2592000 < 1 then result := IntToStr(Elapsed div 86400)+'d'
else if Elapsed div 31536000 < 1 then result := IntToStr(Elapsed div 2592000)+'M'
else result := IntToStr(Elapsed div 31536000)+' Y';
end;
{Return the current block age}
Function BlockAge():integer;
Begin
Result := UTCtime mod 600;
End;
{Returns the expected timestamp for next block}
Function NextBlockTimeStamp():Int64;
var
currTime : int64;
Remains : int64;
Begin
CurrTime := UTCTime;
Remains := 600-(CurrTime mod 600);
Result := CurrTime+Remains;
End;
{Returns if the current block is in operation period}
Function IsBlockOpen():boolean;
Begin
result := true;
if ( (BlockAge<10) or (BlockAge>585) ) then result := false;
End;
END. // END UNIT
|
{: MainForm<p>
Main form of the ManuCAD program<p>
<b>History :</b><font size=-1><ul>
<li>13/02/03 - SJ - Added Block drawing
<li>10/02/03 - SJ - Added Arc & Circle drawing & color selection
<li>08/02/03 - DA - A new DXf is opened with the form
- SJ - Added Polyline drawing
<li>26/01/03 - DA - Implemented the SaveAs action
- SJ - Added line drawing
<li>18/01/03 - SJ - Added status bar
<li>11/01/03 - SJ - Added print comfirmation
<li>06/12/02 - SJ - Added toolbar
<li>03/10/02 - DA - Zoom is now a little more intelligent
<li>01/10/02 - DA - Added zooming and unzooming
<li>30/10/02 - DA - Added a ifdef for delphi7 uses
<li>13/10/02 - DA - Changes on LoadDXF
<li>2?/09/02 - DA - Unit creation
</ul></font>
}
unit MainForm;
interface
uses
Windows,
Winapi.Messages,
System.SysUtils,
System.UITypes,
System.Variants,
System.Classes,
System.Actions,
ToolWin,
ComCtrls,
Buttons,
Vcl.Graphics,
Vcl.Controls, Vcl.Forms,
Vcl.Dialogs, Vcl.ActnList, Vcl.ActnMan, Vcl.Menus,
StdCtrls, Vcl.XPStyleActnCtrls, Printers,
GLWin32Viewer, GLScene,
GLObjects,
// DXF
GLDXFVectorFile, GLBitmapFont, GLWindowsFont,
GLCadencer,
// Added for objects adding
TypesDXF,
GLVectorGeometry,
GLVectorTypes,
GLCoordinates,
GLCrossPlatform,
GLBaseClasses;
type
TForm1 = class(TForm)
GLScene: TGLScene;
MainMenu1: TMainMenu;
ActionManager1: TActionManager;
ActLoadDXF: TAction;
ActQuit: TAction;
Fichier1: TMenuItem;
ChargerDXF1: TMenuItem;
Quitter1: TMenuItem;
N1: TMenuItem;
OpenDXFDialog: TOpenDialog;
GLLightSource1: TGLLightSource;
GLCamera: TGLCamera;
Affichage1: TMenuItem;
Zoomer1: TMenuItem;
Dzoomer1: TMenuItem;
ActZoomer: TAction;
ActDezoomer: TAction;
ToolBar1: TToolBar;
MoveButton: TSpeedButton;
ZoomButton: TSpeedButton;
ZoomPButton: TSpeedButton;
ZoomMButton: TSpeedButton;
ActInit: TAction;
InitButton: TSpeedButton;
ActPrint: TAction;
Imprimer1: TMenuItem;
PrintDXFDialog: TPrintDialog;
SelectButton: TSpeedButton;
GLViewer: TGLSceneViewer;
Initialise1: TMenuItem;
StatusBar: TStatusBar;
SpeedButton4: TSpeedButton;
LineButton: TSpeedButton;
PolyLButton: TSpeedButton;
ArcButton: TSpeedButton;
ActSave: TAction;
ActSaveas: TAction;
Enregistrer1: TMenuItem;
Enregistrersous1: TMenuItem;
SaveDXFDialog: TSaveDialog;
CircleButton: TSpeedButton;
ColorDXFDialog: TColorDialog;
ColorButton: TSpeedButton;
BlockButton: TSpeedButton;
BlockComboBox: TComboBox;
RotateButton: TSpeedButton;
GLDummyCube1: TGLDummyCube;
procedure ActLoadDXFExecute(Sender: TObject);
procedure ActQuitExecute(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure ActZoomerExecute(Sender: TObject);
procedure ActDezoomerExecute(Sender: TObject);
procedure GLViewerMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure GLViewerMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure ActInitExecute(Sender: TObject);
procedure InitButtonClick(Sender: TObject);
procedure FormMouseWheel(Sender: TObject; Shift: TShiftState;
WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean);
procedure ActPrintExecute(Sender: TObject);
procedure Enregistrersous1Click(Sender: TObject);
procedure ToolBarButtonSelect(Sender: TObject);
procedure GLViewerMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure ActSaveExecute(Sender: TObject);
procedure ActSaveasExecute(Sender: TObject);
procedure ColorButtonClick(Sender: TObject);
private
{ Déclarations privées }
DXFFile : TGLDXFFile;
OldMousePosition : TPoint;
DownPosition : TPoint;
SelectedMode : Integer;
CurrentEntity : TDXFEntity;
DrawingClickNb : Integer;
CurrentColor : Integer;
procedure Select(XLeft,Yleft,XRight,YRight : integer);
public
{ Déclarations publiques }
end;
var
Form1: TForm1;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
implementation
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
{$R *.dfm}
uses
FileDXF,
ProgressForm,
// Added for objects adding
ObjectsDXF,
MathsDXF;
// ActDezoomerExecute
//
procedure TForm1.ActDezoomerExecute(Sender: TObject);
begin
GLCamera.SceneScale := GLCamera.SceneScale * 0.85;
if GLCamera.SceneScale < 0 then GLCamera.SceneScale := 0.001;
end;
// ActInitExecute
//
procedure TForm1.ActInitExecute(Sender: TObject);
begin
with GLCamera do begin
Position.SetPoint(0, 0, -10);
SceneScale := 1;
end;
BlockComboBox.Items.Clear;
end;
// ActLoadDXFExecute
//
procedure TForm1.ActLoadDXFExecute(Sender: TObject);
var
DXFFileStream : TFileStream;
begin
if OpenDXFDialog.Execute then begin
ActInit.Execute;
DXFFileStream := TFileStream.Create(OpenDXFDialog.FileName, fmOpenRead or fmShareDenyWrite);
Progress.Show;
DXFFile.OnProgress := Progress.UpdateProgress;
Enabled := False;
try
// read the DXF file
DXFFile.LoadFromStream(DXFFileStream);
GLScene.Objects.AddChild(DXFFile.DirectOpenGL);
// center the drawing
with DXFFile.DXF.Header do
GLCamera.Position.SetPoint(GLCamera.Position.X + ((ExtMin.X - ExtMax.X) / 2),
GLCamera.Position.Y - ((ExtMin.Y - ExtMax.Y) / 2),
GLCamera.Position.Z + ((ExtMin.Z - ExtMax.Z) / 2));
// show the name of the open file in title and status bar
Caption := 'ManuCAD - ' + OpenDXFDialog.FileName;
StatusBar.Panels.Items[0].Text := OpenDXFDialog.FileName;
// enable actions
Enregistrer1.Enabled := True;
Enregistrersous1.Enabled := True;
finally
DXFFileStream.Free;
Progress.Hide;
Enabled := True;
end;
end;
end;
// ActPrintExecute
//
procedure TForm1.ActPrintExecute(Sender: TObject);
var
Bit : TBitmap;
begin
if PrintDXFDialog.Execute then begin
Bit := GLViewer.Buffer.CreateSnapShot.Create32BitsBitmap;
with Printer do begin
BeginDoc;
Canvas.StretchDraw(Rect(0, 0, 5000, 5000), Bit);
EndDoc;
end;
FreeAndNil(Bit);
end;
end;
// ActQuitExecute
//
procedure TForm1.ActQuitExecute(Sender: TObject);
begin
if MessageDlg('Voulez vous vraiment quitter ?', mtConfirmation, [mbYes, mbNo], 0) = mrYes then begin
Close;
end;
end;
// ActZoomerExecute
//
procedure TForm1.ActZoomerExecute(Sender: TObject);
begin
GLCamera.SceneScale := GLCamera.SceneScale * 1.15;
end;
// ColorButtonClick
//
procedure TForm1.ColorButtonClick(Sender: TObject);
var
i : Integer;
begin
if ColorDXFDialog.Execute then
for i := 0 to Def_Cols do
if DXF_Layer_Colours[i] = ColorDXFDialog.Color then begin
CurrentColor := i;
Break;
end;
end;
// Enregistrersous1Click
//
procedure TForm1.Enregistrersous1Click(Sender: TObject);
var
DXFFileStream : TFileStream;
begin
if SaveDXFDialog.Execute then begin
DXFFileStream := TFileStream.Create(SaveDXFDialog.FileName,
fmCreate or fmOpenWrite or fmShareExclusive);
Progress.Show;
DXFFile.OnProgress := Progress.UpdateProgress;
Enabled := False;
try
DXFFile.DXF.SaveToStream(DXFFileStream);
finally
DXFFileStream.Free;
Progress.Hide;
Enabled := True;
end;
end;
end;
// FormCreate
//
procedure TForm1.FormCreate(Sender: TObject);
begin
// set the decimal separator as in the DXF Files
FormatSettings.DecimalSeparator := '.';
// sets the default mode
SelectedMode := 1;
// sets the default color
CurrentColor := 3;
// create the DXF file
DXFFile := TGLDXFFile.Create;
ActInit.Execute;
// read the DXF file
DXFFile.NewDXF;
GLScene.Objects.AddChild(DXFFile.DirectOpenGL);
// show the name of the open file in title and status bar
Caption := 'ManuCAD - Nouveau fichier';
StatusBar.Panels.Items[0].Text := 'Nouveau fichier';
// enable actions
Enregistrer1.Enabled := True;
Enregistrersous1.Enabled := True;
end;
// FormDestroy
//
procedure TForm1.FormDestroy(Sender: TObject);
begin
// destroy the DXF File
DXFFile.Free;
end;
// FormKeyDown
//
procedure TForm1.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
with GLCamera do begin
case Key of
VK_LEFT : Position.X := Position.X + 50/(37*SceneScale);
VK_RIGHT : Position.X := Position.X - 50/(37*SceneScale);
VK_UP : Position.Y := Position.Y + 50/(37*SceneScale);
VK_DOWN : Position.Y := Position.Y - 50/(37*SceneScale);
VK_ADD : ActZoomer.Execute;
VK_SUBTRACT : ActDezoomer.Execute;
end;
end;
end;
// FormMouseWheel
//
procedure TForm1.FormMouseWheel(Sender: TObject; Shift: TShiftState;
WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean);
begin
with GLCamera do begin
SceneScale := SceneScale + (WheelDelta/200)*SceneScale;
if SceneScale < 0 then SceneScale := 0.001;
end;
end;
// GLViewerMouseDown
//
procedure TForm1.GLViewerMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
OldMousePosition.X := X;
OldMousePosition.Y := Y;
DownPosition.X := X;
DownPosition.Y := Y;
end;
// GLViewerMouseMove
//
procedure TForm1.GLViewerMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
var
AVect, AVectResult : TVector4f;
ATempVect : TVector3f;
Line : TDXFLine;
Polyl : TDXFPolyline;
Ark : TDXFArc;
Circl : TDXFCircle;
begin
MakeVector(AVect, X, GLViewer.Height - Y, 0);
GLViewer.Buffer.ScreenVectorIntersectWithPlaneXY(AVect, 0, AVectResult);
with StatusBar.Panels do begin
Items[1].Text := 'X : ' + FormatFloat('0.0', -AVectResult.X);
Items[2].Text := 'Y : ' + FormatFloat('0.0', AVectResult.Y);
Items[3].Text := 'Z : ' + FormatFloat('0.0', AVectResult.Z);
end;
with GLCamera do begin
case SelectedMode of
1 : begin
// Move
if ssLeft in Shift then begin
Position.X := Position.X - (OldMousePosition.X - X)/(37*SceneScale);
Position.Y := Position.Y - (OldMousePosition.Y - Y)/(37*SceneScale);
end;
end;
2 : begin
// Select
end;
3 : begin
// Zoom
if ssLeft in Shift then begin
SceneScale := SceneScale + ((OldMousePosition.Y - Y)/100)*SceneScale;
if SceneScale < 0 then SceneScale := 0.001;
end;
end;
4 : begin
// Line
if DrawingClickNb = 1 then begin
Line := TDXFLine(CurrentEntity);
Line.EndPoint := AffineVectorMake(AVectResult);
Line.EndPoint.X := -AVectResult.X;
GLViewer.Refresh;
end;
end;
5 : begin
// PolyLine
if DrawingClickNb > 0 then begin
Polyl := TDXFPolyline(CurrentEntity);
with Polyl do begin
PointList[Length(PointList) - 1].Primary := AffineVectorMake(AVectResult);
PointList[Length(PointList) - 1].Primary.X := -AVectResult.X;
end;
GLViewer.Refresh;
end;
end;
6 : begin
// Arc
case DrawingClickNb of
1 : begin
Ark := TDXFArc(CurrentEntity);
ATempVect := AffineVectorMake(AVectResult);
ATempVect.X := -ATempVect.X;
Ark.Radius := VectorDistance(Ark.Primary, ATempVect);
GLViewer.Refresh;
end;
2 : begin
Ark := TDXFArc(CurrentEntity);
ATempVect := AffineVectorMake(AVectResult);
ATempVect.X := -ATempVect.X;
Ark.StartAngle := Angle(Ark.Primary, ATempVect);
GLViewer.Refresh;
end;
3 : begin
Ark := TDXFArc(CurrentEntity);
ATempVect := AffineVectorMake(AVectResult);
ATempVect.X := -ATempVect.X;
Ark.EndAngle := Angle(Ark.Primary, ATempVect);
GLViewer.Refresh;
end;
end;
end;
7 : begin
// Circle
if DrawingClickNb = 1 then begin
Circl := TDXFCircle(CurrentEntity);
ATempVect := AffineVectorMake(AVectResult);
ATempVect.X := -ATempVect.X;
Circl.Radius := VectorDistance(Circl.Primary, ATempVect);
GLViewer.Refresh;
end;
end;
9 : begin
// Rotation
GLCamera.TargetObject := DXFFile.DirectOpenGL;
GLCamera.MoveAroundTarget(OldMousePosition.Y - Y, OldMousePosition.X - X);
end;
end;
end;
OldMousePosition.X := X;
OldMousePosition.Y := Y;
end;
// GLViewerMouseUp
//
procedure TForm1.GLViewerMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
var
AVect, AVectResult : TVector4f;
ATempVect : TVector3f;
Line : TDXFLine;
Polyl : TDXFPolyline;
Ark : TDXFArc;
Circl : TDXFCircle;
Blk : TDXFInsert;
begin
MakeVector(AVect, X, GLViewer.Height - Y, 0);
GLViewer.Buffer.ScreenVectorIntersectWithPlaneXY(AVect, 0, AVectResult);
case SelectedMode of
2 : begin
// Select
Select(DownPosition.X, DownPosition.Y, X, Y)
end;
4 : begin
// Draw line
if Button = TMouseButton.mbLeft then begin
if DrawingClickNb = 0 then begin
Line := TDXFLine.Create(DXFFile.DXF.Layers);
Line.ColorNum := CurrentColor;
Line.Layer := DXFFile.DXF.Layers.Layer[0];
Line.Primary := AffineVectorMake(AVectResult);
Line.Primary.X := -AVectResult.X;
DXFFile.DXF.Entities.AddEntity(Line);
CurrentEntity := Line;
DrawingClickNb := 1;
end else begin
Line := TDXFLine(CurrentEntity);
Line.EndPoint := AffineVectorMake(AVectResult);
Line.EndPoint.X := -AVectResult.X;
GLViewer.Refresh;
DrawingClickNb := 0;
end;
end;
end;
5 : begin
// Draw polyline
if Button = TMouseButton.mbLeft then begin
if DrawingClickNb = 0 then begin
Polyl := TDXFPolyline.Create(DXFFile.DXF.Layers);
Polyl.ColorNum := CurrentColor;
Polyl.Layer := DXFFile.DXF.Layers.Layer[0];
SetAffineVector(Polyl.Primary, 0, 0, 0);
with Polyl do begin
SetLength(PointList, 2);
PointList[0] := TDXFVertex.Create(DXFFile.DXF.Layers);
PointList[0].Layer := DXFFile.DXF.Layers.Layer[0];
PointList[0].Primary := AffineVectorMake(AVectResult);
PointList[0].Primary.X := -AVectResult.X;
PointList[1] := TDXFVertex.Create(DXFFile.DXF.Layers);
PointList[1].Layer := DXFFile.DXF.Layers.Layer[0];
PointList[1].Primary := AffineVectorMake(AVectResult);
PointList[1].Primary.X := -AVectResult.X;
end;
DXFFile.DXF.Entities.AddEntity(Polyl);
CurrentEntity := Polyl;
end else begin
Polyl := TDXFPolyline(CurrentEntity);
with Polyl do begin
PointList[Length(PointList) - 1].Primary := AffineVectorMake(AVectResult);
PointList[Length(PointList) - 1].Primary.X := -AVectResult.X;
SetLength(PointList, Length(PointList) + 1);
PointList[Length(PointList) - 1] := TDXFVertex.Create(DXFFile.DXF.Layers);
PointList[Length(PointList) - 1].Layer := DXFFile.DXF.Layers.Layer[0];
PointList[Length(PointList) - 1].Primary := AffineVectorMake(AVectResult);
PointList[Length(PointList) - 1].Primary.X := -AVectResult.X;
end;
GLViewer.Refresh;
end;
inc(DrawingClickNb);
end else if Button = TMouseButton.mbRight then begin
Polyl := TDXFPolyline(CurrentEntity);
Polyl.PointList[Length(Polyl.PointList) - 1].Free;
SetLength(Polyl.PointList, Length(Polyl.PointList) - 1);
DrawingClickNb := 0;
GLViewer.Refresh;
end;
end;
6 : // Draw arc
if Button = TMouseButton.mbLeft then begin
case DrawingClickNb of
0 : begin
Ark := TDXFArc.Create(DXFFile.DXF.Layers);
Ark.ColorNum := CurrentColor;
Ark.Layer := DXFFile.DXF.Layers.Layer[0];
Ark.Primary := AffineVectorMake(AVectResult);
Ark.Primary.X := -AVectResult.X;
Ark.StartAngle := 0;
Ark.EndAngle := 360;
DXFFile.DXF.Entities.AddEntity(Ark);
CurrentEntity := Ark;
DrawingClickNb := 1;
end;
1 : begin
Ark := TDXFArc(CurrentEntity);
ATempVect := AffineVectorMake(AVectResult);
ATempVect.X := -ATempVect.X;
Ark.Radius := VectorDistance(Ark.Primary, ATempVect);
DrawingClickNb := 2;
GLViewer.Refresh;
end;
2 : begin
Ark := TDXFArc(CurrentEntity);
ATempVect := AffineVectorMake(AVectResult);
ATempVect.X := -ATempVect.X;
Ark.StartAngle := Angle(Ark.Primary, ATempVect);
DrawingClickNb := 3;
GLViewer.Refresh;
end;
3 : begin
Ark := TDXFArc(CurrentEntity);
ATempVect := AffineVectorMake(AVectResult);
ATempVect.X := -ATempVect.X;
Ark.EndAngle := Angle(Ark.Primary, ATempVect);
DrawingClickNb := 0;
GLViewer.Refresh;
end;
end;
end;
7 : // Draw arc
if Button = TMouseButton.mbLeft then begin
if DrawingClickNb = 0 then begin
Circl := TDXFCircle.Create(DXFFile.DXF.Layers);
Circl.ColorNum := CurrentColor;
Circl.Layer := DXFFile.DXF.Layers.Layer[0];
Circl.Primary := AffineVectorMake(AVectResult);
Circl.Primary.X := -AVectResult.X;
DXFFile.DXF.Entities.AddEntity(Circl);
CurrentEntity := Circl;
DrawingClickNb := 1;
end else begin
Circl := TDXFCircle(CurrentEntity);
ATempVect := AffineVectorMake(AVectResult);
ATempVect.X := -ATempVect.X;
Circl.Radius := VectorDistance(Circl.Primary, ATempVect);
DrawingClickNb := 0;
GLViewer.Refresh;
end;
end;
8 : // Draw Block
if Button = TMouseButton.mbLeft then begin
Blk := TDXFInsert.Create(DXFFile.DXF.Layers, DXFFile.DXF.Blocks);
Blk.ColorNum := CurrentColor;
blk.BlockName := BlockComboBox.Text;
Blk.Layer := DXFFile.DXF.Layers.Layer[0];
Blk.Primary := AffineVectorMake(AVectResult);
Blk.Primary.X := -AVectResult.X;
DXFFile.DXF.Entities.AddEntity(Blk);
// CurrentEntity := Blk;
GLViewer.Refresh;
end;
end;
end;
// InitButtonClick
//
procedure TForm1.InitButtonClick(Sender: TObject);
begin
ActInit.Execute;
end;
// Select
//
procedure TForm1.Select(XLeft, Yleft, XRight, YRight : integer);
var
AVect, AVectLeft, AVectRight : TVector4f;
i : Integer;
begin
MakeVector(AVect, XLeft, GLViewer.Height - YLeft, 0);
GLViewer.Buffer.ScreenVectorIntersectWithPlaneXY(AVect, 0, AVectLeft);
AVectLeft.X := -AVectLeft.X;
MakeVector(AVect, XRight, GLViewer.Height - YRight, 0);
GLViewer.Buffer.ScreenVectorIntersectWithPlaneXY(AVect, 0, AVectRight);
AVectRight.X := -AVectRight.X;
for i := 0 to DXFFile.DXF.Entities.Count-1 do begin
With DXFFile.DXF.Entities do begin
if (Entity[i] is TDXFPoint) then begin
if (TDXFPoint(Entity[i]).Primary.X > AVectLeft.X)
and (TDXFPoint(Entity[i]).Primary.Y < AVectLeft.Y)
and (TDXFPoint(Entity[i]).Primary.X < AVectRight.X)
and (TDXFPoint(Entity[i]).Primary.Y > AVectRight.Y)
then TDXFPoint(Entity[i]).ColorNum := 6;
end;
end;
end;
GLViewer.Refresh;
end;
// ToolBarButtonSelect
//
procedure TForm1.ToolBarButtonSelect(Sender: TObject);
var
i : Integer;
begin
SelectedMode := TComponent(Sender).Tag;
case SelectedMode of
8 : begin
for i := 0 to DXFFile.DXF.Blocks.Count - 1 do begin
BlockComboBox.Items.Append(DXFFile.DXF.Blocks.Block[i].BlockName);
end;
BlockComboBox.Visible := True;
end;
else begin
BlockComboBox.Visible := False;
GLCamera.TargetObject := nil;
end;
end;
end;
// ActSaveExecute
//
procedure TForm1.ActSaveExecute(Sender: TObject);
begin
//
end;
// ActSaveasExecute
//
procedure TForm1.ActSaveasExecute(Sender: TObject);
var
DXFFileStream : TFileStream;
begin
if SaveDXFDialog.Execute then begin
DXFFileStream := TFileStream.Create(SaveDXFDialog.FileName,
fmCreate or fmOpenWrite or fmShareExclusive);
Progress.Show;
DXFFile.OnProgress := Progress.UpdateProgress;
Enabled := False;
try
DXFFile.DXF.SaveToStream(DXFFileStream);
finally
DXFFileStream.Free;
Progress.Hide;
Enabled := True;
end;
end;
end;
end.
|
unit ProdutoOperacaoExcluir.Controller;
interface
uses Produto.Controller.interf, Produto.Model.interf,
TESTPRODUTO.Entidade.Model, System.SysUtils;
type
TProdutoOperacaoExcluirController = class(TInterfacedObject,
IProdutoOperacaoExcluirController)
private
FProdutoModel: IProdutoModel;
FRegistro: TTESTPRODUTO;
public
constructor Create;
destructor Destroy; override;
class function New: IProdutoOperacaoExcluirController;
function produtoModel(AValue: IProdutoModel)
: IProdutoOperacaoExcluirController;
function produtoSelecionado(AValue: TTESTPRODUTO)
: IProdutoOperacaoExcluirController;
procedure finalizar;
end;
implementation
{ TProdutoOperacaoExcluirController }
uses FacadeView, Tipos.Controller.interf;
procedure TProdutoOperacaoExcluirController.finalizar;
begin
if TFacadeView.New
.MensagensFactory
.exibirMensagem(tmConfirmacao)
.mensagem(Format('Deseja excluir o produto %s ?', [FRegistro.DESCRICAO.Value]))
.exibir then
begin
FProdutoModel.DAO.Delete(FRegistro);
end;
end;
constructor TProdutoOperacaoExcluirController.Create;
begin
end;
destructor TProdutoOperacaoExcluirController.Destroy;
begin
inherited;
end;
class function TProdutoOperacaoExcluirController.New
: IProdutoOperacaoExcluirController;
begin
Result := Self.Create;
end;
function TProdutoOperacaoExcluirController.produtoModel(AValue: IProdutoModel)
: IProdutoOperacaoExcluirController;
begin
Result := Self;
FProdutoModel := AValue;
end;
function TProdutoOperacaoExcluirController.produtoSelecionado
(AValue: TTESTPRODUTO): IProdutoOperacaoExcluirController;
begin
Result := Self;
FRegistro := AValue;
end;
end.
|
unit ufrmDialogAdjustmentCashier;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ufrmMasterDialog, ExtCtrls, StdCtrls, Mask,
System.Actions, Vcl.ActnList, ufraFooterDialog3Button, cxGraphics, cxControls,
cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, Vcl.ComCtrls,
dxCore, cxDateUtils, cxDropDownEdit, cxLookupEdit, cxDBLookupEdit,
cxDBExtLookupComboBox, cxCurrencyEdit, cxTextEdit, cxMaskEdit, cxCalendar;
type
TFormMode = (fmAdd, fmEdit);
TfrmDialogAdjustmentCashier = class(TfrmMasterDialog)
pnl1: TPanel;
pnl2: TPanel;
lbl1: TLabel;
dtTgl: TcxDateEdit;
lbl3: TLabel;
edtPOSCode: TEdit;
lbl2: TLabel;
edtShift: TEdit;
lbl4: TLabel;
edtCashierId: TEdit;
edtCashierName: TEdit;
lbl5: TLabel;
lbl6: TLabel;
curredtCash: TcxCurrencyEdit;
cbpCard: TcxExtLookupComboBox;
lbl7: TLabel;
lbl8: TLabel;
curredtCredit: TcxCurrencyEdit;
lbl9: TLabel;
curredtDeposit: TcxCurrencyEdit;
lbl10: TLabel;
curredtVoucher: TcxCurrencyEdit;
lbl11: TLabel;
curredtVoucherLain: TcxCurrencyEdit;
lbl12: TLabel;
edtNote: TEdit;
curredtDebit: TcxCurrencyEdit;
procedure FormDestroy(Sender: TObject);
procedure footerDialogMasterbtnSaveClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure curredtCashKeyPress(Sender: TObject; var Key: Char);
procedure cbpCardKeyPress(Sender: TObject; var Key: Char);
procedure curredtCreditKeyPress(Sender: TObject; var Key: Char);
procedure curredtDebitKeyPress(Sender: TObject; var Key: Char);
procedure curredtDepositKeyPress(Sender: TObject; var Key: Char);
procedure curredtVoucherKeyPress(Sender: TObject; var Key: Char);
procedure curredtVoucherLainKeyPress(Sender: TObject; var Key: Char);
procedure curredtDepositEnter(Sender: TObject);
procedure curredtDepositExit(Sender: TObject);
procedure cbpCardChange(Sender: TObject);
private
FIsProcessSuccessfull: boolean;
FFormMode: TFormMode;
FBeginningBalanceId: integer;
FStrCash,
FStrCredit,
FStrDebit,
FStrDeposit,
FStrGoroCoupon,
FStrOtherCoupon : string;
procedure ClrCcAtribut;
procedure SetFormMode(const Value: TFormMode);
procedure SetIsProcessSuccessfull(const Value: boolean);
procedure ParseDataComboBox();
procedure SetBeginningBalanceId(const Value: integer);
function SaveAdjustmentCashier: boolean;
procedure SaveValueCurrencyEdit(ACurrencyEdit: TcxCurrencyEdit);
procedure LoadValueCurrencyEdit( ACurrencyEdit: TcxCurrencyEdit);
procedure PrintSlip(aAdjID: integer; aUnitID: integer);
public
{ Public declarations }
published
property FormMode: TFormMode read FFormMode write SetFormMode;
property IsProcessSuccessfull: boolean read FIsProcessSuccessfull write SetIsProcessSuccessfull;
property BeginningBalanceId: integer read FBeginningBalanceId write SetBeginningBalanceId;
end;
var
frmDialogAdjustmentCashier: TfrmDialogAdjustmentCashier;
implementation
uses ufrmAdjustmentCashier, uTSCommonDlg, uRetnoUnit, udmReport, Math, DB;
{$R *.dfm}
procedure TfrmDialogAdjustmentCashier.FormDestroy(Sender: TObject);
begin
inherited;
frmDialogAdjustmentCashier := nil;
end;
procedure TfrmDialogAdjustmentCashier.SetFormMode(const Value: TFormMode);
begin
FFormMode := Value;
end;
procedure TfrmDialogAdjustmentCashier.SetIsProcessSuccessfull(
const Value: boolean);
begin
FIsProcessSuccessfull := Value;
end;
procedure TfrmDialogAdjustmentCashier.footerDialogMasterbtnSaveClick(
Sender: TObject);
begin
inherited;
if (curredtCash.Value = 0)
and (curredtCredit.Value = 0)
and (curredtDebit.Value = 0)
and (curredtDeposit.Value = 0)
and (curredtVoucher.Value = 0)
and (curredtVoucherLain.Value = 0) then
begin
CommonDlg.ShowError('You cannot save an empty data');
Exit;
end;
if (curredtCash.Value <> 0)
and ((curredtCredit.Value <> 0)
or (curredtDebit.Value <> 0)
or (curredtDeposit.Value <> 0)
or (curredtVoucher.Value <> 0)
or (curredtVoucherLain.Value <> 0)) then
begin
CommonDlg.ShowError('Gagal simpan , Harus isi salah satu Cash atau Card');
Exit;
end;
if (Floor(dtTgl.Date) <= Floor(GetLastEODDate(DialogUnit))) then
begin
CommonDlg.ShowError('Tanggal ' + FormatDateTime('DD MMM YYYY', dtTgl.Date) + ' Sudah EOD, Transaksi tidak bisa dilanjutkan..');
dtTgl.SetFocus;
Exit;
end;
if (SaveAdjustmentCashier) then
begin
IsProcessSuccessfull := true;
end;
end;
procedure TfrmDialogAdjustmentCashier.ParseDataComboBox;
var
data: TDataSet;
sCreditDebet: string;
begin
{with cbpCard do
begin
ClearGridData;
ColCount := 4;
RowCount := 3;
AddRow(['Id', 'CARD CODE.','CARD NAME','CREDIT/DEBET']);
if not assigned(CreditCard) then
CreditCard := TCreditCard.Create;
data := CreditCard.GetListDataCreditCard(dialogunit,1);
if (data.RecordCount > 0) then
begin
RowCount := data.RecordCount + 2;
while not data.Eof do
begin
if (data.FieldByName('CARD_IS_CREDIT').AsInteger = 1) then
sCreditDebet := 'CREDIT'
else
sCreditDebet := 'DEBIT';
AddRow([data.FieldByName('CARD_ID').AsString,data.FieldByName('CARD_CODE').AsString,
data.FieldByName('CARD_NAME').AsString,sCreditDebet]);
data.Next;
end;
end
else
begin
AddRow(['0',' ',' ',' '])
end;
FixedRows := 1;
SizeGridToData;
Text := '';
end;
}
end;
procedure TfrmDialogAdjustmentCashier.FormShow(Sender: TObject);
begin
inherited;
// parse info read only
dtTgl.Date := frmAdjustmentCashier.dtTgl.Date;
edtPOSCode.Text := frmAdjustmentCashier.edtPOSCode.Text;
edtShift.Text := frmAdjustmentCashier.edtShiftCode.Text;
edtCashierId.Text := frmAdjustmentCashier.edtCashierCode.Text;
edtCashierName.Text := frmAdjustmentCashier.edtCashierName.Text;
BeginningBalanceId := frmAdjustmentCashier.BeginningBalanceId;
FStrCash := '0'+FormatSettings.DecimalSeparator+'00';
FStrCredit := '0'+FormatSettings.DecimalSeparator+'00';
FStrDebit := '0'+FormatSettings.DecimalSeparator+'00';
FStrDeposit := '0'+FormatSettings.DecimalSeparator+'00';
FStrGoroCoupon := '0'+FormatSettings.DecimalSeparator+'00';
FStrOtherCoupon := '0'+FormatSettings.DecimalSeparator+'00';
curredtCash.Value := 0;
ClrCcAtribut;
ParseDataComboBox;
curredtCash.SetFocus;
curredtCash.SelectAll;
end;
procedure TfrmDialogAdjustmentCashier.curredtCashKeyPress(Sender: TObject;
var Key: Char);
begin
if (Key = Chr(VK_RETURN)) then
begin
cbpCard.SetFocus;
cbpCard.SelectAll;
end;
end;
procedure TfrmDialogAdjustmentCashier.cbpCardKeyPress(Sender: TObject;
var Key: Char);
begin
{if (Key = Chr(VK_RETURN)) then
begin
ClrCcAtribut;
if (trim(cbpCard.Text) <> '') and (UpperCase(Trim(cbpCard.Cells[3,cbpCard.Row])) = 'CREDIT') then
begin
curredtCredit.SetFocus;
curredtCredit.SelectAll;
curredtCredit.Properties.ReadOnly := False;
curredtDebit.Properties.ReadOnly := true;
end
else
begin
curredtDebit.SetFocus;
curredtDebit.SelectAll;
curredtDebit.Properties.ReadOnly := False;
curredtCredit.Properties.ReadOnly := true;
end;
end;
}
end;
procedure TfrmDialogAdjustmentCashier.curredtCreditKeyPress(
Sender: TObject; var Key: Char);
begin
if (Key = Chr(VK_RETURN)) then
begin
curredtDeposit.SetFocus;
curredtDeposit.SelectAll;
end;
end;
procedure TfrmDialogAdjustmentCashier.curredtDebitKeyPress(Sender: TObject;
var Key: Char);
begin
if (Key = Chr(VK_RETURN)) then
begin
curredtDeposit.SetFocus;
curredtDeposit.SelectAll;
end;
end;
procedure TfrmDialogAdjustmentCashier.curredtDepositKeyPress(
Sender: TObject; var Key: Char);
begin
if (Key = Chr(VK_RETURN)) then
begin
curredtVoucher.SetFocus;
curredtVoucher.SelectAll;
end;
end;
procedure TfrmDialogAdjustmentCashier.curredtVoucherKeyPress(
Sender: TObject; var Key: Char);
begin
if (Key = Chr(VK_RETURN)) then
begin
curredtVoucherLain.SetFocus;
curredtVoucherLain.SelectAll;
end;
end;
procedure TfrmDialogAdjustmentCashier.curredtVoucherLainKeyPress(
Sender: TObject; var Key: Char);
begin
if (Key = Chr(VK_RETURN)) then
begin
edtNote.SetFocus;
edtNote.SelectAll;
end;
end;
procedure TfrmDialogAdjustmentCashier.SetBeginningBalanceId(
const Value: integer);
begin
FBeginningBalanceId := Value;
end;
function TfrmDialogAdjustmentCashier.SaveAdjustmentCashier: boolean;
var
idCard : integer;
begin
{with TAdjustmentCashier.CreateWithUser(Self,FLoginId,dialogunit) do
begin
try
if (Trim(cbpCard.Text) <> '') then
idCard := strtoint(cbpCard.Cells[0,cbpCard.Row])
else
idCard := 0;
UpdateData(BeginningBalanceId,
idCard,
curredtCash.Value,
curredtCredit.Value,
curredtDebit.Value,
curredtDeposit.Value,
edtNote.Text,
curredtVoucher.Value,
0,dialogunit,
curredtVoucherLain.Value);
Result := SaveToDB;
if Result then
begin
cCommitTrans;
PrintSlip(ID, dialogunit);
Close;
end
else
begin
cRollbackTrans;
end;
finally
Free;
end;
end;
}
end;
procedure TfrmDialogAdjustmentCashier.curredtDepositEnter(Sender: TObject);
begin
inherited;
LoadValueCurrencyEdit(Sender as TcxCurrencyEdit);
end;
procedure TfrmDialogAdjustmentCashier.curredtDepositExit(Sender: TObject);
begin
inherited;
SaveValueCurrencyEdit(Sender as TcxCurrencyEdit);
end;
procedure TfrmDialogAdjustmentCashier.LoadValueCurrencyEdit(
ACurrencyEdit: TcxCurrencyEdit);
var
AStringLoader: string;
begin
if ACurrencyEdit = curredtCash then
AStringLoader := FStrCash
else if ACurrencyEdit = curredtCredit then
AStringLoader := FStrCredit
else if ACurrencyEdit = curredtDebit then
AStringLoader := FStrDebit
else if ACurrencyEdit = curredtDeposit then
AStringLoader := FStrDeposit
else if ACurrencyEdit = curredtVoucher then
AStringLoader := FStrGoroCoupon
else if ACurrencyEdit = curredtVoucherLain then
AStringLoader := FStrOtherCoupon;
ACurrencyEdit.SelectAll;
if StrToFloat(AStringLoader) <> 0 then
ACurrencyEdit.SelText := AStringLoader;
end;
procedure TfrmDialogAdjustmentCashier.SaveValueCurrencyEdit(
ACurrencyEdit: TcxCurrencyEdit);
var
AStringSaver: string;
begin
ACurrencyEdit.SelectAll;
AStringSaver := ACurrencyEdit.SelText;
ACurrencyEdit.Value := StrToCurr(AStringSaver);
if ACurrencyEdit = curredtCash then
FStrCash := AStringSaver
else if ACurrencyEdit = curredtCredit then
FStrCredit := AStringSaver
else if ACurrencyEdit = curredtDebit then
FStrDebit := AStringSaver
else if ACurrencyEdit = curredtDeposit then
FStrDeposit := AStringSaver
else if ACurrencyEdit = curredtVoucher then
FStrGoroCoupon := AStringSaver
else if ACurrencyEdit = curredtVoucherLain then
FStrOtherCoupon := AStringSaver;
end;
procedure TfrmDialogAdjustmentCashier.cbpCardChange(Sender: TObject);
begin
inherited;
// cbpCard.Text := cbpCard.Cells[2, cbpCard.Row];
end;
procedure TfrmDialogAdjustmentCashier.ClrCcAtribut;
begin
curredtCredit.Value := 0;
curredtDebit.Value := 0;
curredtDeposit.Value := 0;
curredtVoucher.Value := 0;
curredtVoucherLain.Value := 0;
edtNote.Clear;
end;
procedure TfrmDialogAdjustmentCashier.PrintSlip(aAdjID: integer; aUnitID:
integer);
var
sSQL : string;
begin
sSQL := 'SELECT '
+ QuotedStr(Trim(edtPOSCode.Text)) +' as PosCode, '
+ QuotedStr(Trim(edtShift.Text)) +' as Shift, '
+ QuotedStr(Trim(edtCashierId.Text)) +' as CId, '
+ QuotedStr(Trim(edtCashierName.Text)) +' as CNm, '
+ ' AC.ADJCASHIER_CASH_VALUE as Cash, AC.ADJCASHIER_CREDIT AS CREDIT,'
+ ' AC.ADJCASHIER_DEBIT AS DEBET, AC.ADJCASHIER_DEPOSIT_COUPON AS DEPOSIT,'
+ ' AC.ADJCASHIER_GORO_COUPON AS VGORO, AC.ADJCASHIER_OTHER_COUPON AS VOTHER,'
+ ' AC.ADJCASHIER_DESCRIPTION AS DESCR, CC.CARD_NAME'
+ ' FROM ADJUSTMENT_CASHIER AC'
+ ' LEFT join ref$credit_card cc on cc.card_id = AC.ADJCASHIER_CARD_ID'
+ ' AND CC.CARD_UNT_ID = AC.ADJCASHIER_CARD_UNT_ID'
+ ' WHERE ADJCASHIER_ID = '+ IntToStr(aAdjID)
+ ' AND ADJCASHIER_UNT_ID = '+ IntToStr(aUnitID);
// dmReportNew.EksekusiReport('frAdjCashier', sSQL,'',True);
end;
end.
|
unit ibSHTrigger;
interface
uses
SysUtils, Classes,
SHDesignIntf,
ibSHDesignIntf, ibSHDBObject;
type
TibBTTrigger = class(TibBTDBObject, IibSHTrigger)
private
FTableName: string;
FStatus: string;
FTypePrefix: string;
FTypeSuffix: string;
FPosition: Integer;
function GetTableName: string;
procedure SetTableName(Value: string);
function GetStatus: string;
procedure SetStatus(Value: string);
function GetTypePrefix: string;
procedure SetTypePrefix(Value: string);
function GetTypeSuffix: string;
procedure SetTypeSuffix(Value: string);
function GetPosition: Integer;
procedure SetPosition(Value: Integer);
public
constructor Create(AOwner: TComponent); override;
published
property Description;
property TableName: string read GetTableName {write SetTableName};
property Status: string read GetStatus {write SetStatus};
property TypePrefix: string read GetTypePrefix {write SetTypePrefix};
property TypeSuffix: string read GetTypeSuffix {write SetTypeSuffix};
property Position: Integer read GetPosition {write SetPosition};
end;
TibBTSystemGeneratedTrigger = class(TibBTTrigger, IibSHSystemGeneratedTrigger)
public
constructor Create(AOwner: TComponent); override;
end;
implementation
uses
ibSHConsts, ibSHSQLs;
{ TibBTTrigger }
constructor TibBTTrigger.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FStatus := Format('%s', [Statuses[0]]);
FTypePrefix := Format('%s', [TypePrefixes[0]]);
FTypeSuffix := Format('%s', [TypeSuffixesIB[0]]);
end;
function TibBTTrigger.GetTableName: string;
begin
Result := FTableName;
end;
procedure TibBTTrigger.SetTableName(Value: string);
begin
FTableName := Value;
end;
function TibBTTrigger.GetStatus: string;
begin
Result := FStatus;
end;
procedure TibBTTrigger.SetStatus(Value: string);
begin
FStatus := Value;
end;
function TibBTTrigger.GetTypePrefix: string;
begin
Result := FTypePrefix;
end;
procedure TibBTTrigger.SetTypePrefix(Value: string);
begin
FTypePrefix := Value;
end;
function TibBTTrigger.GetTypeSuffix: string;
begin
Result := FTypeSuffix;
end;
procedure TibBTTrigger.SetTypeSuffix(Value: string);
begin
FTypeSuffix := Value;
end;
function TibBTTrigger.GetPosition: Integer;
begin
Result := FPosition;
end;
procedure TibBTTrigger.SetPosition(Value: Integer);
begin
FPosition := Value;
end;
{ TibBTSystemGeneratedTrigger }
constructor TibBTSystemGeneratedTrigger.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
System := True;
end;
end.
|
program HowToCollideSpriteWithLines;
uses
SwinGame, sgTypes;
procedure Main();
var
leftLine, rightLine, topLine, bottomLine: LineSegment;
ball: Sprite;
begin
OpenGraphicsWindow('Bouncing Ball', 800, 600);
ClearScreen(ColorWhite);
LoadBitmapNamed('ball', 'ball_small.png');
leftLine := LineFrom(10, 10, 10, 590);
rightLine := LineFrom(790, 10, 790, 590);
topLine := LineFrom(10, 10, 790, 10);
bottomLine := LineFrom(10, 590, 790, 590);
ball := CreateSprite(BitmapNamed('ball'));
SpriteSetX(ball, 100);
SpriteSetY(ball, 500);
SpriteSetVelocity(ball, VectorTo(1, -0.6));
repeat
ProcessEvents();
ClearScreen(ColorWhite);
DrawLine(ColorRed, leftLine);
DrawLine(ColorRed, rightLine);
DrawLine(ColorRed, topLine);
DrawLine(ColorRed, bottomLine);
DrawSprite(ball);
UpdateSprite(ball);
if CircleLineCollision(ball, leftLine) then
CollideCircleLine(ball, leftLine);
if CircleLineCollision(ball, rightLine) then
CollideCircleLine(ball, rightLine);
if CircleLineCollision(ball, topLine) then
CollideCircleLine(ball, topLine);
if CircleLineCollision(ball, bottomLine) then
CollideCircleLine(ball, bottomLine);
RefreshScreen();
until WindowCloseRequested();
FreeSprite(ball);
ReleaseAllResources();
end;
begin
Main();
end. |
(* WS_ADT 23.04.2017 *)
(* Container for strings *)
(* Hidden data *)
UNIT WS_ADT;
INTERFACE
TYPE
(* "hiding" of tree data *)
TreePtr = POINTER;
PROCEDURE InitTree(VAR Tree: TreePtr);
FUNCTION IsEmpty(VAR Tree: TreePtr): BOOLEAN;
FUNCTION Contains(VAR Tree: TreePtr; s: STRING): BOOLEAN;
PROCEDURE Insert (VAR Tree: TreePtr; s : String);
PROCEDURE Remove(VAR Tree: TreePtr; s: STRING);
FUNCTION Union (s1,s2 : TreePtr) : TreePtr;
FUNCTION Intersection (s1,s2 : TreePtr) : TreePtr;
FUNCTION Difference (s1,s2 : TreePtr) : TreePtr;
FUNCTION Cardinality (s1: TreePtr) : INTEGER;
PROCEDURE DisposeWS(VAR Tree: TreePtr);
IMPLEMENTATION
TYPE
WordSet = ^WordSetRec;
WordSetRec = RECORD
data: STRING;
left, right: WordSet;
END;
(* Init tree *)
PROCEDURE InitTree(VAR Tree: TreePtr);
BEGIN
WordSet(Tree) := NIL;
END;
(* create a new WordSet
returns: WordSet *)
FUNCTION NewWordSet (data: STRING): WordSet;
VAR
n: WordSet;
BEGIN
New(n);
n^.data := data;
n^.left := NIL;
n^.right := NIL;
NewWordSet := n;
END;
(* Check if binsearchtree is empty *)
FUNCTION IsEmpty(VAR Tree: TreePtr): BOOLEAN;
BEGIN
IsEmpty := WordSet(Tree) = NIL;
END;
(* check if binsearchtree contains string
TypeCast to WordSet for rec. function *)
FUNCTION ContainsRec(VAR t: TreePtr; s: STRING): BOOLEAN;
BEGIN
IF t = NIL THEN BEGIN
ContainsRec := FALSE;
END
ELSE IF WordSet(t)^.data = s THEN
ContainsRec := TRUE
ELSE IF s < WordSet(t)^.data THEN BEGIN
ContainsRec := ContainsRec(WordSet(t)^.left, s);
END
ELSE BEGIN
ContainsRec := ContainsRec(WordSet(t)^.right, s);
END;
END;
(* check if binsearchtree contains string
TypeCast to WordSet for rec. function *)
FUNCTION Contains(VAR Tree: TreePtr; s: STRING): BOOLEAN;
BEGIN
Contains := ContainsRec(WordSet(Tree), s);
END;
(* Insert in binsearchtree
recursive *)
PROCEDURE InsertRec (VAR t: WordSet; n: WordSet);
BEGIN
IF t = NIL THEN BEGIN
t := n;
END
ELSE BEGIN
IF (n^.data = t^.data) THEN Exit
ELSE IF n^.data < t^.data THEN
InsertRec(t^.left, n)
ELSE
InsertRec(t^.right, n)
END;
END;
(* Insert a string in binsearchtree
TypeCast to WordSet for rec. function *)
PROCEDURE Insert (VAR Tree: TreePtr; s : String);
BEGIN
InsertRec(WordSet(Tree), NewWordSet(s));
END;
(* Remove a string from binsearchtree *)
PROCEDURE Remove(VAR Tree: TreePtr; s: STRING);
VAR
n, nPar: WordSet;
st: WordSet; (*subtree*)
succ, succPar: WordSet;
BEGIN
nPar := NIL;
n := WordSet(Tree);
WHILE (n <> NIL) AND (n^.data <> s) DO BEGIN
nPar := n;
IF s < n^.data THEN
n := n^.left
ELSE
n := n^.right;
END;
IF n <> NIL THEN BEGIN (* no right subtree *)
IF n^.right = NIL THEN BEGIN
st := n^.left;
END
ELSE BEGIN
IF n^.right^.left = NIL THEN BEGIN (* right subtree, but no left subtree *)
st := n^.right;
st^.left := n^.left;
END
ELSE BEGIN
(*common case*)
succPar := NIL;
succ := n^.right;
WHILE succ^.left <> NIL DO BEGIN
succPar := succ;
succ := succ^.left;
END;
succPar^.left := succ^.right;
st := succ;
st^.left := n^.left;
st^.right := n^.right;
END;
END;
(* insert the new sub-tree *)
IF nPar = NIL THEN
WordSet(Tree) := st
ELSE IF n^.data < nPar^.data THEN
nPar^.left := st
ELSE
nPar^.right := st;
Dispose(n);
END; (* n <> NIL *)
END;
(* copy a set
returns: WordSet*)
FUNCTION CopyWSet(ws : WordSet) : WordSet;
VAR
n : WordSet;
BEGIN
IF ws = NIL THEN CopyWSet := NIL
ELSE BEGIN
New(n);
n^.data := ws^.data;
n^.left := CopyWSet(ws^.left);
n^.right := CopyWSet(ws^.right);
CopyWSet := n;
END;
END;
(* inserts s1 into s2 and returns it
recursive *)
FUNCTION UnionRec (s1,s2 : WordSet) : WordSet;
VAR
result : WordSet;
BEGIN
result := s2;
IF s1 <> NIL THEN BEGIN
Insert(result, s1^.data);
UnionRec(s1^.left, result);
UnionRec(s1^.right, result);
END;
UnionRec := result;
END;
(* union, calls recursive function
TypeCast to WordSet for rec. function *)
FUNCTION Union (s1,s2 : TreePtr) : TreePtr;
BEGIN
Union := WordSet(UnionRec(WordSet(s1),WordSet(s2)));
END;
(* removes Nodes that are not present in s2
recursive *)
FUNCTION IntersectionRec (VAR s1,s2 : WordSet) : WordSet;
BEGIN
IF s1 <> NIL THEN BEGIN
(* words that are NOT in both *)
IF NOT Contains(s2 ,s1^.data) THEN BEGIN
Remove(s1, s1^.data);
s1 := IntersectionRec(s1,s2);
END
ELSE BEGIN
IntersectionRec(s1^.left, s2);
IntersectionRec(s1^.right, s2);
END;
END;
IntersectionRec := s1;
END;
(* intersection, calls recursive function
TypeCast to WordSet for rec. function *)
FUNCTION Intersection (s1,s2 : TreePtr) : TreePtr;
BEGIN
Intersection := WordSet(IntersectionRec(WordSet(s1),WordSet(s2)));
END;
(* removes Nodes that are present in s2
recursive *)
FUNCTION DifferenceRec (VAR s1,s2 : WordSet) : WordSet;
BEGIN
IF s1 <> NIL THEN BEGIN
IF Contains(s2 ,s1^.data) THEN BEGIN
Remove(s1, s1^.data);
s1 := DifferenceRec(s1,s2);
END
ELSE BEGIN
DifferenceRec(s1^.left, s2);
DifferenceRec(s1^.right, s2);
END;
END;
DifferenceRec := s1;
END;
(* difference, calls recursive function
TypeCast to WordSet for rec. function *)
FUNCTION Difference (s1,s2 : TreePtr) : TreePtr;
BEGIN
WordSet(Difference) := DifferenceRec(WordSet(s1),WordSet(s2));
END;
(* number of words in a WordSet
returns 0 if none are found *)
FUNCTION Cardinality (s1: TreePtr) : INTEGER;
BEGIN
(* 0 if nothing is found *)
Cardinality := 0;
IF s1 <> NIL THEN BEGIN
Cardinality := 1;
IF (WordSet(s1)^.left <> NIL) AND (WordSet(s1)^.right <> NIL) THEN BEGIN
Cardinality := Cardinality(WordSet(s1)^.left) + Cardinality(WordSet(s1)^.right) + 1;
END
ELSE
IF WordSet(s1)^.left <> NIL THEN Cardinality := Cardinality(WordSet(s1)^.left) + 1
ELSE IF WordSet(s1)^.right <> NIL THEN Cardinality := Cardinality(WordSet(s1)^.right) + 1;
END;
END;
(* Removes all the elements from the binary search tree *)
(* rooted at Tree, leaving the tree empty. *)
PROCEDURE DisposeWS(VAR Tree : TreePtr);
BEGIN
(* Base Case: If Tree is NIL, do nothing. *)
IF Tree <> NIL THEN BEGIN
(* Traverse the left subtree in postorder. *)
DisposeWS (WordSet(Tree)^.Left);
(* Traverse the right subtree in postorder. *)
DisposeWS (WordSet(Tree)^.Right);
(* Delete this leaf node from the tree. *)
Dispose (WordSet(Tree));
END
END;
BEGIN
END. |
{------------------------------------------------------------------------------
Miguel A. Risco Castillo TuELED v0.2
http://ue.accesus.com/uecontrols
The contents of this file are subject to the Mozilla Public License
Version 1.1 (the "License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.mozilla.org/MPL/MPL-1.1.html
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either expressed or implied. See the License for
the specific language governing rights and limitations under the License.
------------------------------------------------------------------------------}
unit ueled;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs,
LCLIntf, LCLType, Types, BGRABitmap, BGRABitmapTypes;
type
{ TuELED }
TLedType = (ledRound, ledSquare);
TuELED = class(TGraphicControl)
private
FColor: TColor;
FActive: Boolean;
FOnChange: TNotifyEvent;
FChanging:Boolean;
FBright : Boolean;
FReflection : Boolean;
FLedType : TLedType;
procedure DrawLED;
procedure DrawLedRound(const r: integer; const LColor: TColor);
procedure DrawLedSquare(const r: integer; const LColor: TColor);
procedure SetActive(AValue:Boolean);
protected
class procedure WSRegisterClass; override;
class function GetControlClassDefaultSize: TSize; override;
procedure Paint; override;
procedure Loaded; override;
procedure Resize; override;
procedure SetColor(AValue: TColor); override;
procedure SetBright(Avalue:Boolean); virtual;
procedure SetReflection(Avalue:Boolean); virtual;
procedure SetLedType(AValue:TLedType); virtual;
procedure DoChange; virtual;
public
Bitmap: TBGRABitmap;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure ReDraw;
published
property Active: boolean read FActive write SetActive;
property LedType: TLedType read FLedType write SetLedType;
property Bright: boolean read FBright write SetBright;
property Reflection: boolean read FReflection write SetReflection;
property Align;
property Anchors;
property BorderSpacing;
property Color: tcolor read FColor write SetColor default clDefault;
property Constraints;
property DragCursor;
property DragKind;
property DragMode;
property Enabled;
property ParentColor;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property Visible;
property OnChange: TNotifyEvent read FOnChange write FOnChange;
property OnChangeBounds;
property OnMouseEnter;
property OnMouseLeave;
property OnMouseWheel;
property OnMouseWheelDown;
property OnMouseWheelUp;
property OnPaint;
property OnClick;
property OnConstrainedResize;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDock;
property OnEndDrag;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnResize;
property OnStartDock;
property OnStartDrag;
end;
procedure Register;
function Darker(Color:TColor; Percent:Byte):TBGRAPixel;
implementation
constructor TuELED.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
ControlStyle := ControlStyle + [csReplicatable, csCaptureMouse, csClickEvents, csDoubleClicks];
Bitmap:=TBGRABitmap.Create(0,0);
with GetControlClassDefaultSize do SetInitialBounds(0, 0, CX, CY);
FChanging:=false;
FActive:=true;
FBright:=true;
FReflection:=true;
FColor:=clLime;
FLedType:=ledRound;
end;
destructor TuELED.Destroy;
begin
if Assigned(Bitmap) then
begin
Bitmap.Free;
Bitmap := nil;
end;
inherited Destroy;
end;
procedure TuELED.ReDraw;
begin
Paint;
end;
procedure TuELED.Paint;
procedure DrawFrame;
begin
with inherited Canvas do
begin
Pen.Color := clBlack;
Pen.Style := psDash;
MoveTo(0, 0);
LineTo(Self.Width-1, 0);
LineTo(Self.Width-1, Self.Height-1);
LineTo(0, Self.Height-1);
LineTo(0, 0);
end;
end;
begin
if csDesigning in ComponentState then DrawFrame;
if assigned(Bitmap) then
begin
Bitmap.Draw(inherited Canvas,0,0,false);
end;
end;
procedure TuELED.Loaded;
begin
inherited Loaded;
end;
procedure TuELED.Resize;
begin
inherited Resize;
DrawLED;
end;
procedure TuELED.SetColor(AValue: TColor);
begin
if FColor = AValue then exit;
FColor := AValue;
DrawLED;
inherited SetColor(AValue);
end;
procedure TuELED.SetBright(Avalue: Boolean);
begin
if FBright = AValue then exit;
FBright := AValue;
DrawLED;
end;
procedure TuELED.SetReflection(Avalue: Boolean);
begin
if FReflection = AValue then exit;
FReflection := AValue;
DrawLED;
end;
procedure TuELED.SetLedType(AValue: TLedType);
begin
if FLedType = AValue then exit;
FLedType := AValue;
DrawLED;
end;
procedure TuELED.DrawLED;
var r:integer;
begin
if (csLoading in ComponentState) or FChanging then exit;
FChanging := True;
Bitmap.SetSize(width,height);
Bitmap.Fill(BGRAPixelTransparent);
if Width < Height then r:=Width else r:=Height;
r:=r div 10;
Case FLedType of
ledSquare : DrawLedSquare(r+2, FColor);
else
DrawLedRound(r+3, FColor)
end;
FChanging := False;
Invalidate;
DoChange;
end;
procedure TuELED.DrawLedRound(const r: integer; const LColor: TColor);
var
mask: TBGRABitmap;
layer: TBGRABitmap;
begin
//Bright
if FActive and FBright then
begin
layer:=TBGRABitmap.Create(Width, Height);
layer.GradientFill(0,0,layer.Width,layer.Height,
ColorToBGRA(ColortoRGB(LColor),240),ColorToBGRA(ColortoRGB(LColor),0),
gtRadial,PointF(layer.Width/2,layer.Height/2),PointF(0,layer.Height/2),
dmSet);
Bitmap.PutImage(0,0,layer,dmDrawWithTransparency);
layer.free;
end;
// Solid Led
if FActive then
begin
layer:=TBGRABitmap.Create(Width-2*r, Height-2*r);
layer.GradientFill(0,0,layer.Width,layer.Height,
ColorToBGRA(ColortoRGB(LColor)),BGRA(0,0,0),
gtRadial,PointF(layer.Width/2,layer.Height*8/15),PointF(layer.Width*1.5,layer.Height*1.5),
dmSet);
mask := TBGRABitmap.Create(layer.Width,layer.Height,BGRABlack);
mask.FillEllipseAntialias((layer.Width-1)/2,(layer.Height-1)/2,layer.Width/2,layer.Height/2,BGRAWhite);
layer.ApplyMask(mask);
mask.Free;
Bitmap.PutImage(r,r,layer,dmDrawWithTransparency);
layer.free;
end else Bitmap.FillEllipseAntialias((Width-1)/2,(Height-1)/2,Width/2-r,Height/2-r, Darker(LColor,80));
//Reflexion
if FReflection then
begin
layer:=TBGRABitmap.Create((Width-1)-2*r, 5*(Height-2*r) div 8);
layer.GradientFill(0,0,layer.Width,layer.Height,
BGRA(255,255,255,128),BGRA(255,255,255,0),
gtLinear,PointF(layer.Width/2,0),PointF(layer.Width/2,layer.Height*6/10),
dmSet);
mask := TBGRABitmap.Create(layer.Width,layer.Height,BGRABlack);
mask.FillEllipseAntialias(layer.Width/2,layer.Height/2,(layer.Width/2)*(4/5),(layer.Height/2)*(9/10),BGRAWhite);
layer.ApplyMask(mask);
mask.Free;
Bitmap.PutImage(r,r,layer,dmDrawWithTransparency);
layer.free;
end;
end;
procedure TuELED.DrawLedSquare(const r: integer; const LColor: TColor);
var
mask: TBGRABitmap;
layer: TBGRABitmap;
begin
//Bright
if FActive and FBright then
begin
layer:=TBGRABitmap.Create(Width, Height);
layer.GradientFill(0,0,layer.Width,layer.Height,
ColorToBGRA(ColortoRGB(LColor),255),ColorToBGRA(ColortoRGB(LColor),0),
gtRadial,PointF(layer.Width/2,layer.Height/2),PointF(0,3*layer.Height/4),
dmSet);
Bitmap.PutImage(0,0,layer,dmDrawWithTransparency);
layer.free;
end;
// Solid Led
if FActive then
begin
layer:=TBGRABitmap.Create(Width-2*r, Height-2*r);
layer.GradientFill(0,0,layer.Width,layer.Height,
ColorToBGRA(ColortoRGB(LColor)),BGRA(0,0,0),
gtRadial,PointF(layer.Width/2,layer.Height/2),PointF(layer.Width*1.5,layer.Height*1.5),
dmSet);
mask := TBGRABitmap.Create(layer.Width,layer.Height,BGRABlack);
mask.FillRoundRectAntialias(0,0,layer.Width,layer.Height,r,r,BGRAWhite);
layer.ApplyMask(mask);
mask.Free;
Bitmap.PutImage(r,r,layer,dmDrawWithTransparency);
layer.free;
end else Bitmap.FillRoundRectAntialias(r,r,Width-r,Height-r,r,r, Darker(LColor,80));
//Reflexion
if FReflection then
begin
layer:=TBGRABitmap.Create((Width-1)-2*r, 5*(Height-2*r) div 8);
layer.GradientFill(0,0,layer.Width,layer.Height,
BGRA(255,255,255,160),BGRA(255,255,255,0),
gtLinear,PointF(layer.Width/2,0),PointF(layer.Width/2,layer.Height*6/10),
dmSet);
mask := TBGRABitmap.Create(layer.Width,layer.Height,BGRABlack);
mask.FillRoundRectAntialias(layer.Width*(1/20),layer.Height*(1/20),layer.Width*(19/20),layer.Height*(19/20),r,r,BGRAWhite);
layer.ApplyMask(mask);
mask.Free;
Bitmap.PutImage(r,r,layer,dmDrawWithTransparency);
layer.free;
end;
end;
procedure TuELED.SetActive(AValue: Boolean);
begin
if AValue <> FActive then
begin
FActive := AValue;
DrawLED;
end;
end;
class function TuELED.GetControlClassDefaultSize: TSize;
begin
Result.CX := 24;
Result.CY := 24;
end;
procedure TuELED.DoChange;
begin
if Assigned(FOnChange) then FOnChange(Self);
end;
class procedure TuELED.WSRegisterClass;
begin
inherited WSRegisterClass;
end;
function Darker(Color:TColor; Percent:Byte):TBGRAPixel;
begin
Result:=ColorToBGRA(ColorToRGB(Color));
With Result do
begin
red:=red-muldiv(red,Percent,100); //Percent% closer to black
green:=green-muldiv(green,Percent,100);
blue:=blue-muldiv(blue,Percent,100);
end;
end;
procedure Register;
begin
{$I ueled_icon.lrs}
RegisterComponents('uEControls', [TuELED]);
end;
end.
|
unit ibSHDDLHistoryActions;
interface
uses
SysUtils, Classes, Menus,
SHDesignIntf, ibSHDesignIntf;
type
TibSHDDLHistoryPaletteAction = class(TSHAction)
public
constructor Create(AOwner: TComponent); override;
function SupportComponent(const AClassIID: TGUID): Boolean; override;
procedure EventExecute(Sender: TObject); override;
procedure EventHint(var HintStr: String; var CanShow: Boolean); override;
procedure EventUpdate(Sender: TObject); override;
end;
TibSHDDLHistoryFormAction = class(TSHAction)
public
constructor Create(AOwner: TComponent); override;
function SupportComponent(const AClassIID: TGUID): Boolean; override;
procedure EventExecute(Sender: TObject); override;
procedure EventHint(var HintStr: String; var CanShow: Boolean); override;
procedure EventUpdate(Sender: TObject); override;
end;
TibSHDDLHistoryToolbarAction_ = class(TSHAction)
public
constructor Create(AOwner: TComponent); override;
function SupportComponent(const AClassIID: TGUID): Boolean; override;
procedure EventExecute(Sender: TObject); override;
procedure EventHint(var HintStr: String; var CanShow: Boolean); override;
procedure EventUpdate(Sender: TObject); override;
end;
TibSHDDLHistoryEditorAction = class(TSHAction)
public
constructor Create(AOwner: TComponent); override;
function SupportComponent(const AClassIID: TGUID): Boolean; override;
procedure EventExecute(Sender: TObject); override;
procedure EventHint(var HintStr: String; var CanShow: Boolean); override;
procedure EventUpdate(Sender: TObject); override;
end;
TibSHDDLHistoryToolbarAction_Run = class(TibSHDDLHistoryToolbarAction_)
end;
TibSHDDLHistoryToolbarAction_Pause = class(TibSHDDLHistoryToolbarAction_)
end;
TibSHDDLHistoryToolbarAction_Region = class(TibSHDDLHistoryToolbarAction_)
end;
TibSHDDLHistoryToolbarAction_Refresh = class(TibSHDDLHistoryToolbarAction_)
end;
TibSHDDLHistoryToolbarAction_Save = class(TibSHDDLHistoryToolbarAction_)
end;
TibSHDDLHistoryEditorAction_SendToSQLEditor = class(TibSHDDLHistoryEditorAction)
end;
TibSHDDLHistoryEditorAction_ShowDDLHistory = class(TibSHDDLHistoryEditorAction)
end;
implementation
uses
ibSHConsts,
ibSHDDLHistoryFrm;
{ TibSHDDLHistoryPaletteAction }
constructor TibSHDDLHistoryPaletteAction.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FCallType := actCallPalette;
Category := Format('%s', ['Tools']);
Caption := Format('%s', ['DDL History']);
ShortCut := TextToShortCut('Shift+Ctrl+F11');
end;
function TibSHDDLHistoryPaletteAction.SupportComponent(const AClassIID: TGUID): Boolean;
begin
Result := IsEqualGUID(IibSHBranch, AClassIID) or IsEqualGUID(IfbSHBranch, AClassIID);
end;
procedure TibSHDDLHistoryPaletteAction.EventExecute(Sender: TObject);
begin
Designer.CreateComponent(Designer.CurrentDatabase.InstanceIID, IibSHDDLHistory, EmptyStr);
end;
procedure TibSHDDLHistoryPaletteAction.EventHint(var HintStr: String; var CanShow: Boolean);
begin
end;
procedure TibSHDDLHistoryPaletteAction.EventUpdate(Sender: TObject);
begin
Enabled := Assigned(Designer.CurrentDatabase) and
// (Designer.CurrentDatabase as ISHRegistration).Connected and
SupportComponent(Designer.CurrentDatabase.BranchIID);
end;
{ TibSHDDLHistoryFormAction }
constructor TibSHDDLHistoryFormAction.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FCallType := actCallForm;
Caption := SCallDDLStatements;
SHRegisterComponentForm(IibSHDDLHistory, Caption, TibSHDDLHistoryForm);
end;
function TibSHDDLHistoryFormAction.SupportComponent(const AClassIID: TGUID): Boolean;
begin
Result := IsEqualGUID(AClassIID, IibSHDDLHistory);
end;
procedure TibSHDDLHistoryFormAction.EventExecute(Sender: TObject);
begin
Designer.ChangeNotification(Designer.CurrentComponent, Caption, opInsert);
end;
procedure TibSHDDLHistoryFormAction.EventHint(var HintStr: String; var CanShow: Boolean);
begin
end;
procedure TibSHDDLHistoryFormAction.EventUpdate(Sender: TObject);
begin
FDefault := Assigned(Designer.CurrentComponentForm) and
AnsiSameText(Designer.CurrentComponentForm.CallString, Caption);
end;
{ TibSHDDLHistoryToolbarAction_ }
constructor TibSHDDLHistoryToolbarAction_.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FCallType := actCallToolbar;
Caption := '-';
if Self is TibSHDDLHistoryToolbarAction_Run then Tag := 1;
if Self is TibSHDDLHistoryToolbarAction_Pause then Tag := 2;
if Self is TibSHDDLHistoryToolbarAction_Region then Tag := 3;
if Self is TibSHDDLHistoryToolbarAction_Refresh then Tag := 4;
if Self is TibSHDDLHistoryToolbarAction_Save then Tag := 5;
case Tag of
1:
begin
Caption := Format('%s', ['Run']);
ShortCut := TextToShortCut('Ctrl+Enter');
SecondaryShortCuts.Add('F9');
end;
2:
begin
Caption := Format('%s', ['Stop']);
ShortCut := TextToShortCut('Ctrl+BkSp');
end;
3: Caption := Format('%s', ['Tree']);
4:
begin
Caption := Format('%s', ['Refresh']);
ShortCut := TextToShortCut('F5');
end;
5:
begin
Caption := Format('%s', ['Save']);
ShortCut := TextToShortCut('Ctrl+S');
end;
end;
if Tag <> 0 then Hint := Caption;
AutoCheck := Tag = 3; // Tree
end;
function TibSHDDLHistoryToolbarAction_.SupportComponent(const AClassIID: TGUID): Boolean;
begin
Result := IsEqualGUID(AClassIID, IibSHDDLHistory);
end;
procedure TibSHDDLHistoryToolbarAction_.EventExecute(Sender: TObject);
begin
case Tag of
// Run
1: (Designer.CurrentComponentForm as ISHRunCommands).Run;
// Pause
2: (Designer.CurrentComponentForm as ISHRunCommands).Pause;
// Tree
3: (Designer.CurrentComponentForm as ISHRunCommands).ShowHideRegion(Checked);
// Refresh
4: (Designer.CurrentComponentForm as ISHRunCommands).Refresh;
// Save
5: (Designer.CurrentComponentForm as ISHFileCommands).Save;
end;
end;
procedure TibSHDDLHistoryToolbarAction_.EventHint(var HintStr: String; var CanShow: Boolean);
begin
end;
procedure TibSHDDLHistoryToolbarAction_.EventUpdate(Sender: TObject);
begin
if Assigned(Designer.CurrentComponentForm) and
AnsiSameText(Designer.CurrentComponentForm.CallString, SCallDDLStatements) then
begin
Visible := True;
case Tag of
// Separator
0: ;
// Run
1: Enabled := (Designer.CurrentComponentForm as ISHRunCommands).CanRun;
// Pause
2: Enabled := (Designer.CurrentComponentForm as ISHRunCommands).CanPause;
// Tree
3: Checked := (Designer.CurrentComponentForm as IibSHDDLHistoryForm).RegionVisible;
// Refresh
4: Enabled := (Designer.CurrentComponentForm as ISHRunCommands).CanRefresh;
// Save
5: Enabled := (Designer.CurrentComponentForm as ISHFileCommands).CanSave;
end;
end else
Visible := False;
end;
{ TibSHDDLHistoryEditorAction }
constructor TibSHDDLHistoryEditorAction.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FCallType := actCallEditor;
if Self is TibSHDDLHistoryEditorAction_SendToSQLEditor then Tag := 1;
if Self is TibSHDDLHistoryEditorAction_ShowDDLHistory then Tag := 2;
case Tag of
0: Caption := '-'; // separator
1: Caption := SSendToSQLEditor;
2: Caption := SShowDDLHistory;
end;
end;
function TibSHDDLHistoryEditorAction.SupportComponent(
const AClassIID: TGUID): Boolean;
begin
case Tag of
1: Result := IsEqualGUID(AClassIID, IibSHDDLHistory);
2: Result := IsEqualGUID(AClassIID, IibSHSQLEditor) or IsEqualGUID(AClassIID, IibSHSQLPlayer);
else
Result := False;
end;
end;
procedure TibSHDDLHistoryEditorAction.EventExecute(Sender: TObject);
var
vDDLHistoryForm: IibSHDDLHistoryForm;
SQLPlayer: IibSHSQLPlayer;
vComponent: TSHComponent;
vCurrentComponent: TSHComponent;
begin
if Assigned(Designer.CurrentComponentForm) then
case Tag of
1:
if Supports(Designer.CurrentComponentForm, IibSHDDLHistoryForm, vDDLHistoryForm) then
vDDLHistoryForm.SendToSQLEditor;
2:
begin
if (Assigned(Designer.CurrentComponent) and
Supports(Designer.CurrentComponent, IibSHSQLPlayer, SQLPlayer) and
Assigned(SQLPlayer.BTCLDatabase) and
SQLPlayer.BTCLDatabase.Connected) then
begin
vCurrentComponent := Designer.CurrentComponent;
vComponent := Designer.CreateComponent(SQLPlayer.BTCLDatabase.InstanceIID, IibSHDDLHistory, '');
Designer.JumpTo(vCurrentComponent.InstanceIID, IibSHDDLHistory, vComponent.Caption);
end
else
if Assigned(Designer.CurrentDatabase) then
begin
if Assigned(Designer.CurrentComponent) then
begin
Designer.CreateComponent(Designer.CurrentDatabase.InstanceIID, IibSHDDLHistory, '');
// vCurrentComponent := Designer.CurrentComponent;
// vComponent := Designer.CreateComponent(Designer.CurrentDatabase.InstanceIID, IibSHDDLHistory, '');
// Designer.JumpTo(vCurrentComponent.InstanceIID, IibSHDDLHistory, vComponent.Caption);
end;
end;
end;
end;
end;
procedure TibSHDDLHistoryEditorAction.EventHint(var HintStr: String;
var CanShow: Boolean);
begin
end;
procedure TibSHDDLHistoryEditorAction.EventUpdate(Sender: TObject);
var
vDDLHistoryForm: IibSHDDLHistoryForm;
SQLPlayer: IibSHSQLPlayer;
begin
if Assigned(Designer.CurrentComponentForm) then
case Tag of
1:
if Supports(Designer.CurrentComponentForm, IibSHDDLHistoryForm, vDDLHistoryForm) then
Enabled := vDDLHistoryForm.GetCanSendToSQLEditor;
2: Enabled := Assigned(Designer.CurrentDatabase) or
{Enabled :=} (Assigned(Designer.CurrentComponent) and
Supports(Designer.CurrentComponent, IibSHSQLPlayer, SQLPlayer) and
Assigned(SQLPlayer.BTCLDatabase) and
SQLPlayer.BTCLDatabase.Connected);
else
Enabled := False;
end;
end;
end.
|
unit UPais;
interface
type
TPais = class (TObject)
private
FIdPais: Integer;
FPais: String;
FSigla:String;
FDDI:String;
FDataCadastro:String;
FDataAlteracao:String;
protected
procedure setIdPais(vIdPais:Integer);
procedure setPais(vPais:String);
procedure setSigla(VSigla:String);
procedure setDDI(vDDI:String);
procedure setDataCadastro(vDtCad:String);
procedure setDataAlteracao(vDtAlt:String);
function getIdPais:Integer;
function getPais:String;
function getSigla:String;
function getDDI:String;
function getDataCadastro:String;
function getDataAlteracao:String;
public
constructor Create;
destructor Destroy;
//Property Metod
property IdPais: Integer read getIdPais write setIdPais;
property Pais: String read getPais write setPais;
property DDI: String read getDDI write setDDI;
property Sigla: String read getSigla write setsigla;
property DataCadastro: String read getDataCadastro write setDataCadastro;
property DataAlteracao: String read getDataAlteracao write setDataAlteracao;
end;
implementation
{ TPais }
{ TPais }
constructor TPais.Create;
begin
FIdPais:= 0;
FPais:='';
FSigla:='';
FDDI:='';
FDataCadastro:='';
FDataAlteracao:='';
end;
destructor TPais.Destroy;
begin
end;
function TPais.getDataAlteracao: String;
begin
result:= FDataCadastro;
end;
function TPais.getDataCadastro: String;
begin
result:= FDataCadastro;
end;
function TPais.getDDI: String;
begin
result:=FDDI;
end;
function TPais.getIdPais: Integer;
begin
result:= FIdPais;
end;
function TPais.getPais: String;
begin
result:=FPais;
end;
function TPais.getSigla: String;
begin
result:=FSigla;
end;
procedure TPais.setDataAlteracao(vDtAlt: String);
begin
FDataAlteracao:=vDtAlt;
end;
procedure TPais.setDataCadastro(vDtCad: String);
begin
FDataCadastro:=vDtCad;
end;
procedure TPais.setDDI(vDDI: String);
begin
FDDI:=vDDI;
end;
procedure TPais.setIdPais(vIdPais: Integer);
begin
FIdPais:=vIdPais;
end;
procedure TPais.setPais(vPais: String);
begin
FPais:=vPais;
end;
procedure TPais.setSigla(vSigla: String);
begin
FSigla:=vSigla;
end;
end.
|
{*******************************************************}
{ }
{ Iocomp OPC Classes }
{ }
{ Copyright (c) 1997,2002 Iocomp Software }
{ }
{*******************************************************}
{$I iInclude.inc}
{$ifdef iVCL}unit iOPCClasses;{$endif}
{$ifdef iCLX}unit QiOPCClasses;{$endif}
interface
uses
Windows, Forms, Classes, ComObj, ActiveX, SysUtils, iOPCTypes, iOPCFunctions{$IFDEF COMPILER_6_UP},Variants{$ENDIF};
type
TiOPCShutdownCallback = class(TInterfacedObject, IOPCShutdown)
private
FOnChange : TNotifyEvent;
public
function ShutdownRequest(szReason: POleStr): HResult; stdcall;
property OnChange : TNotifyEvent read FOnChange write FOnChange;
end;
TiOPCAdviseSink = class(TInterfacedObject, IAdviseSink)
private
FData : OleVariant;
FQuality : Word;
FTimeStamp : TDateTime;
FClientHandle : OPCHANDLE;
FOnChange : TNotifyEvent;
public
procedure OnDataChange(const formatetc: TFormatEtc; const stgmed: TStgMedium); stdcall;
procedure OnViewChange(dwAspect: Longint; lindex: Longint); stdcall;
procedure OnRename(const mk: IMoniker); stdcall;
procedure OnSave; stdcall;
procedure OnClose; stdcall;
property Data : OleVariant read FData;
property TimeStamp : TDateTime read FTimeStamp;
property Quality : Word read FQuality;
property OnChange : TNotifyEvent read FOnChange write FOnChange;
end;
TiOPCDataCallback = class(TInterfacedObject, IOPCDataCallback)
private
FOnWriteComplete2 : TNotifyEvent;
FOnDataChange2 : TNotifyEvent;
FOnReadComplete2 : TNotifyEvent;
FData : OleVariant;
FQuality : Word;
FTimeStamp : TDateTime;
public
function OnDataChange (dwTransid : DWORD;
hGroup : OPCHANDLE;
hrMasterquality : HResult;
hrMastererror : HResult;
dwCount : DWORD;
phClientItems : POPCHANDLEARRAY;
pvValues : POleVariantArray;
pwQualities : PWordArray;
pftTimeStamps : PFileTimeArray;
pErrors : PResultList ): HResult; stdcall;
function OnReadComplete (dwTransid : DWORD;
hGroup : OPCHANDLE;
hrMasterquality : HResult;
hrMastererror : HResult;
dwCount : DWORD;
phClientItems : POPCHANDLEARRAY;
pvValues : POleVariantArray;
pwQualities : PWordArray;
pftTimeStamps : PFileTimeArray;
pErrors : PResultList ): HResult; stdcall;
function OnWriteComplete (dwTransid : DWORD;
hGroup : OPCHANDLE;
hrMastererr : HResult;
dwCount : DWORD;
pClienthandles : POPCHANDLEARRAY;
pErrors : PResultList ): HResult; stdcall;
function OnCancelComplete(dwTransid : DWORD;
hGroup : OPCHANDLE ): HResult; stdcall;
property Data : OleVariant read FData;
property TimeStamp : TDateTime read FTimeStamp;
property Quality : Word read FQuality;
property OnDataChange2 : TNotifyEvent read FOnDataChange2 write FOnDataChange2;
property OnReadComplete2 : TNotifyEvent read FOnReadComplete2 write FOnReadComplete2;
property OnWriteComplete2 : TNotifyEvent read FOnWriteComplete2 write FOnWriteComplete2;
end;
implementation
//***********************************************************************************************************************************
{ TiOPCShutdownCallback }
//***********************************************************************************************************************************
function TiOPCShutdownCallback.ShutdownRequest(szReason: POleStr): HResult;
begin
Result := S_OK;
if Assigned(FOnChange) then FOnChange(Self);
end;
//***********************************************************************************************************************************
procedure TiOPCAdviseSink.OnDataChange(const formatetc: TFormatEtc; const stgmed: TStgMedium);
var
PGH : POPCGROUPHEADER;
PIHA1 : POPCITEMHEADER1ARRAY;
PIHA2 : POPCITEMHEADER2ARRAY;
PV : POleVariant;
I : Integer;
WithTime : Boolean;
FileTime : TFileTime;
SystemTime : TSystemTime;
ALength : Integer;
AWideString : WideString;
APointer : Pointer;
begin
if (formatetc.cfFormat <> OPCSTMFORMATDATA) and (formatetc.cfFormat <> OPCSTMFORMATDATATIME) then Exit;
WithTime := formatetc.cfFormat = OPCSTMFORMATDATATIME;
PGH := GlobalLock(stgmed.hGlobal);
try
if PGH <> nil then
begin
PIHA1 := Pointer(PChar(PGH) + SizeOf(OPCGROUPHEADER));
PIHA2 := Pointer(PIHA1);
if Succeeded(PGH.hrStatus) then
begin
for I := 0 to PGH.dwItemCount - 1 do
begin
if WithTime then
begin
PV := POleVariant(PChar(PGH) + PIHA1[I].dwValueOffset);
FileTime := PIHA1[I].ftTimeStampItem;
if (FileTime.dwLowDateTime <> 0) or (FileTime.dwHighDateTime <> 0) then
begin
FileTimeToLocalFileTime(FileTime, FileTime);
FileTimeToSystemTime(FileTime, SystemTime);
try
FTimeStamp := SystemTimeToDateTime(SystemTime);
except
FTimeStamp := Now;
end;
end
else FTimeStamp := 0;
end
else
begin
PV := POleVariant(PChar(PGH) + PIHA2[I].dwValueOffset);
FTimeStamp := 0;
end;
FClientHandle := PIHA1[I].hClient;
FQuality := (PIHA1[I].wQuality and OPC_QUALITY_MASK);
if VarType(PV^) = varOleStr then
begin
APointer := Pointer(PChar(PV) + SizeOf(OleVariant));
ALength := Integer(APointer^);
APointer := Pointer(PChar(APointer) + SizeOf(ALength));
SetString(AWideString, PChar(WideCharToString(APointer)), ALength div 2);
FData := AWideString;
end
else FData := PV^;
if Assigned(FOnChange) then FOnChange(Self);
end;
end;
end;
finally
GlobalUnlock(stgmed.hGlobal);
end;
end;
//***********************************************************************************************************************************
procedure TiOPCAdviseSink.OnViewChange(dwAspect: Longint; lindex: Longint);begin end;
procedure TiOPCAdviseSink.OnRename (const mk: IMoniker); begin end;
procedure TiOPCAdviseSink.OnSave; begin end;
procedure TiOPCAdviseSink.OnClose; begin end;
//***********************************************************************************************************************************
function TiOPCDataCallback.OnDataChange(dwTransid : DWORD;
hGroup : OPCHANDLE;
hrMasterquality : HResult;
hrMastererror : HResult;
dwCount : DWORD;
phClientItems : POPCHANDLEARRAY;
pvValues : POleVariantArray;
pwQualities : PWordArray;
pftTimeStamps : PFileTimeArray;
pErrors : PResultList): HResult;
var
// ClientItems : POPCHANDLEARRAY;
Values : POleVariantArray;
Qualities : PWORDARRAY;
Times : PFileTimeArray;
FileTime : TFileTime;
SystemTime : TSystemTime;
begin
Result := S_OK;
if dwCount <= 0 then Exit;
// ClientItems := POPCHANDLEARRAY(phClientItems);
Values := POleVariantArray(pvValues);
Qualities := PWORDARRAY(pwQualities);
Times := PFileTimeArray(pftTimeStamps);
FData := Values[0];
FQuality := Qualities[0];
if (FileTime.dwLowDateTime <> 0) or (FileTime.dwHighDateTime <> 0) then
begin
FileTime := Times[0];
FileTimeToLocalFileTime(FileTime, FileTime);
FileTimeToSystemTime(FileTime, SystemTime);
FTimeStamp := SystemTimeToDateTime(SystemTime);
end
else FTimeStamp := 0;
if Assigned(FOnDataChange2) then FOnDataChange2(Self);
end;
//***********************************************************************************************************************************
function TiOPCDataCallback.OnReadComplete(dwTransid : DWORD;
hGroup : OPCHANDLE;
hrMasterquality : HResult;
hrMastererror : HResult;
dwCount : DWORD;
phClientItems : POPCHANDLEARRAY;
pvValues : POleVariantArray;
pwQualities : PWordArray;
pftTimeStamps : PFileTimeArray;
pErrors : PResultList): HResult;
begin
Result := OnDataChange(dwTransid, hGroup, hrMasterquality, hrMastererror, dwCount, phClientItems, pvValues, pwQualities, pftTimeStamps, pErrors);
end;
//***********************************************************************************************************************************
function TiOPCDataCallback.OnWriteComplete(dwTransid: DWORD; hGroup: OPCHANDLE; hrMastererr: HResult; dwCount: DWORD; pClienthandles: POPCHANDLEARRAY; pErrors: PResultList): HResult;
begin
Result := S_OK;
end;
//***********************************************************************************************************************************
function TiOPCDataCallback.OnCancelComplete(dwTransid: DWORD; hGroup: OPCHANDLE): HResult;
begin
Result := S_OK;
end;
//***********************************************************************************************************************************
end.
|
{
----------------------------------------------------------------
File - STATUS_STRINGS.PAS
Copyright (c) 2003 Jungo Ltd. http://www.jungo.com
----------------------------------------------------------------
}
unit status_strings;
interface
uses
Windows, windrvr;
function Stat2Str(dwStatus : DWORD) : String;
implementation
function Stat2Str(dwStatus : DWORD) : String;
begin
if dwStatus=WD_STATUS_SUCCESS then begin Stat2Str:='Success'; Exit; end;
if dwStatus=WD_STATUS_INVALID_WD_HANDLE then begin Stat2Str:='Invalid WinDriver handle'; Exit; end;
if dwStatus=WD_WINDRIVER_STATUS_ERROR then begin Stat2Str:='Error'; Exit; end;
if dwStatus=WD_INVALID_HANDLE then begin Stat2Str:='Invalid handle'; Exit; end;
if dwStatus=WD_INVALID_PIPE_NUMBER then begin Stat2Str:='Invalid pipe number'; Exit; end;
if dwStatus=WD_READ_WRITE_CONFLICT then begin Stat2Str:='Conflict between read and write operations'; Exit; end;
if dwStatus=WD_ZERO_PACKET_SIZE then begin Stat2Str:='Packet size is zero'; Exit; end;
if dwStatus=WD_INSUFFICIENT_RESOURCES then begin Stat2Str:='Insufficient resources'; Exit; end;
if dwStatus=WD_UNKNOWN_PIPE_TYPE then begin Stat2Str:='Unknown pipe type'; Exit; end;
if dwStatus=WD_SYSTEM_INTERNAL_ERROR then begin Stat2Str:='Intenal system error'; Exit; end;
if dwStatus=WD_DATA_MISMATCH then begin Stat2Str:='Data mismatch'; Exit; end;
if dwStatus=WD_NO_LICENSE then begin Stat2Str:='No valid license'; Exit; end;
if dwStatus=WD_INVALID_PARAMETER then begin Stat2Str:='Invalid parameter'; Exit; end;
if dwStatus=WD_NOT_IMPLEMENTED then begin Stat2Str:='Function not implemented'; Exit; end;
if dwStatus=WD_KERPLUG_FAILURE then begin Stat2Str:='KernelPlugin failure'; Exit; end;
if dwStatus=WD_FAILED_ENABLING_INTERRUPT then begin Stat2Str:='Failed enabling interrupt'; Exit; end;
if dwStatus=WD_INTERRUPT_NOT_ENABLED then begin Stat2Str:='Interrupt not enabled'; Exit; end;
if dwStatus=WD_RESOURCE_OVERLAP then begin Stat2Str:='Resource overlap'; Exit; end;
if dwStatus=WD_DEVICE_NOT_FOUND then begin Stat2Str:='Device not found'; Exit; end;
if dwStatus=WD_WRONG_UNIQUE_ID then begin Stat2Str:='Wrong unique ID'; Exit; end;
if dwStatus=WD_OPERATION_ALREADY_DONE then begin Stat2Str:='Operation already done'; Exit; end;
if dwStatus=WD_INTERFACE_DESCRIPTOR_ERROR then begin Stat2Str:='Interface descriptor error'; Exit; end;
if dwStatus=WD_SET_CONFIGURATION_FAILED then begin Stat2Str:='Set configuration operation failed'; Exit; end;
if dwStatus=WD_CANT_OBTAIN_PDO then begin Stat2Str:='Cannot obtain PDO'; Exit; end;
if dwStatus=WD_TIME_OUT_EXPIRED then begin Stat2Str:='TimeOut expired'; Exit; end;
if dwStatus=WD_IRP_CANCELED then begin Stat2Str:='IRP operation cancelled'; Exit; end;
if dwStatus=WD_FAILED_USER_MAPPING then begin Stat2Str:='Failed to map in user space'; Exit; end;
if dwStatus=WD_FAILED_KERNEL_MAPPING then begin Stat2Str:='Failed to map in kernel space'; Exit; end;
if dwStatus=WD_NO_RESOURCES_ON_DEVICE then begin Stat2Str:='No resources on the device'; Exit; end;
if dwStatus=WD_NO_EVENTS then begin Stat2Str:='No events'; Exit; end;
if dwStatus=WD_USBD_STATUS_SUCCESS then begin Stat2Str:='USBD: Success'; Exit; end;
if dwStatus=WD_USBD_STATUS_PENDING then begin Stat2Str:='USBD: Operation pending'; Exit; end;
if dwStatus=WD_USBD_STATUS_ERROR then begin Stat2Str:='USBD: Error'; Exit; end;
if dwStatus=WD_USBD_STATUS_HALTED then begin Stat2Str:='USBD: Halted'; Exit; end;
if dwStatus=WD_USBD_STATUS_CRC then begin Stat2Str:='HC status: CRC'; Exit; end;
if dwStatus=WD_USBD_STATUS_BTSTUFF then begin Stat2Str:='HC status: Bit stuffing '; Exit; end;
if dwStatus=WD_USBD_STATUS_DATA_TOGGLE_MISMATCH then begin Stat2Str:='HC status: Data toggle mismatch'; Exit; end;
if dwStatus=WD_USBD_STATUS_STALL_PID then begin Stat2Str:='HC status: PID stall'; Exit; end;
if dwStatus=WD_USBD_STATUS_DEV_NOT_RESPONDING then begin Stat2Str:='HC status: Device not responding'; Exit; end;
if dwStatus=WD_USBD_STATUS_PID_CHECK_FAILURE then begin Stat2Str:='HC status: PID check failed'; Exit; end;
if dwStatus=WD_USBD_STATUS_UNEXPECTED_PID then begin Stat2Str:='HC status: Unexpected PID'; Exit; end;
if dwStatus=WD_USBD_STATUS_DATA_OVERRUN then begin Stat2Str:='HC status: Data overrun'; Exit; end;
if dwStatus=WD_USBD_STATUS_DATA_UNDERRUN then begin Stat2Str:='HC status: Data underrun'; Exit; end;
if dwStatus=WD_USBD_STATUS_RESERVED1 then begin Stat2Str:='HC status: Reserved1'; Exit; end;
if dwStatus=WD_USBD_STATUS_RESERVED2 then begin Stat2Str:='HC status: Reserved2'; Exit; end;
if dwStatus=WD_USBD_STATUS_BUFFER_OVERRUN then begin Stat2Str:='HC status: Buffer overrun'; Exit; end;
if dwStatus=WD_USBD_STATUS_BUFFER_UNDERRUN then begin Stat2Str:='HC status: Buffer Underrun'; Exit; end;
if dwStatus=WD_USBD_STATUS_NOT_ACCESSED then begin Stat2Str:='HC status: Not accessed'; Exit; end;
if dwStatus=WD_USBD_STATUS_FIFO then begin Stat2Str:='HC status: Fifo'; Exit; end;
if dwStatus=WD_USBD_STATUS_ENDPOINT_HALTED then begin Stat2Str:='HCD: Trasnfer submitted to stalled endpoint'; Exit; end;
if dwStatus=WD_USBD_STATUS_NO_MEMORY then begin Stat2Str:='USBD: Out of memory'; Exit; end;
if dwStatus=WD_USBD_STATUS_INVALID_URB_FUNCTION then begin Stat2Str:='USBD: Invalid URB function'; Exit; end;
if dwStatus=WD_USBD_STATUS_INVALID_PARAMETER then begin Stat2Str:='USBD: Invalid parameter'; Exit; end;
if dwStatus=WD_USBD_STATUS_ERROR_BUSY then begin Stat2Str:='USBD: Attempted to close enpoint/interface/configuration with outstanding transfer'; Exit; end;
if dwStatus=WD_USBD_STATUS_REQUEST_FAILED then begin Stat2Str:='USBD: URB request failed'; Exit; end;
if dwStatus=WD_USBD_STATUS_INVALID_PIPE_HANDLE then begin Stat2Str:='USBD: Invalid pipe handle'; Exit; end;
if dwStatus=WD_USBD_STATUS_NO_BANDWIDTH then begin Stat2Str:='USBD: Not enough bandwidth for endpoint'; Exit; end;
if dwStatus=WD_USBD_STATUS_INTERNAL_HC_ERROR then begin Stat2Str:='USBD: Host controller error'; Exit; end;
if dwStatus=WD_USBD_STATUS_ERROR_SHORT_TRANSFER then begin Stat2Str:='USBD: Trasnfer terminated with short packet'; Exit; end;
if dwStatus=WD_USBD_STATUS_BAD_START_FRAME then begin Stat2Str:='USBD: Start frame outside range'; Exit; end;
if dwStatus=WD_USBD_STATUS_ISOCH_REQUEST_FAILED then begin Stat2Str:='HCD: Isochronous transfer completed with error'; Exit; end;
if dwStatus=WD_USBD_STATUS_FRAME_CONTROL_OWNED then begin Stat2Str:='USBD: Frame length control already taken'; Exit; end;
if dwStatus=WD_USBD_STATUS_FRAME_CONTROL_NOT_OWNED then begin Stat2Str:='USBD: Attemped operation on frame length control not owned by caller'; Exit; end;
if dwStatus=WD_INCORRECT_VERSION then begin Stat2Str:='Incorrect version'; Exit; end;
if dwStatus=WD_TRY_AGAIN then begin Stat2Str:='Try again'; Exit; end;
if dwStatus=WD_WINDRIVER_NOT_FOUND then begin Stat2Str:='Failed open WinDriver'; Exit; end;
Stat2Str := 'Unrecognized error code'
end;
end.
|
unit uLockBox_TestCases;
interface
uses
Classes, TestFramework, uTPLb_Hash, uTPLb_CryptographicLibrary, uTPLb_Codec,
uTPLb_StreamCipher, uTPLb_HugeCardinal, uTPLb_MemoryStreamPool;
type
TEnvironment_TestCase = class( TTestCase)
published
procedure Test_Environment;
end;
implementation
uses
SysUtils, uTPLb_HashDsc, uTPLb_BinaryUtils, uTPLb_StreamUtils, uTPLb_ECB, uTPLb_BlockCipher,
uTPLb_Random, uTPLb_HugeCardinalUtils, uTPLb_IntegerUtils, uTPLb_SVN_Keywords,
Dialogs, uTPLb_PointerArithmetic;
{ TTestCaseFirst }
procedure InitUnit_TestCases;
begin
TestFramework.RegisterTest( TEnvironment_TestCase.Suite);
end;
procedure DoneUnit_TestCases;
begin
end;
function rcs_version_AsInteger: integer;
var
s, Pattern: string;
P, Code: integer;
begin
s := TestFramework.rcs_version;
// s like '$Revision: 27 $' or '$Revision: 41 $'
Pattern := '$Revision: ';
P := Pos( Pattern, s);
if P > 0 then
Delete( s, P, Length( Pattern));
Pattern := ' ';
P := Pos( Pattern, s);
if P > 0 then
SetLength( s, P-1);
Val( s, result, Code);
if (s = '') or (Code <> 0) then
result := -1 // Signifying unknown version
end;
function DelphiVersion_DisplayName: string;
begin
result := '';
{$ifdef VER210}
result := 'Delphi 2010';
{$endif}
{$ifdef VER200}
result := 'Delphi 2009';
{$endif}
{$ifdef VER190}
result := 'Delphi 2007 for .NET';
{$endif}
{$ifdef VER180}
{$ifdef VER185}
result := 'Delphi 2007';
{$else}
result := 'Delphi 2006';
{$endif}
{$endif}
{$ifdef VER170}
result := 'Delphi 2005';
{$endif}
{$ifdef VER160}
result := 'Delphi 8 for .NET';
{$endif}
{$ifdef VER150}
result := 'Delphi 7';
{$endif}
{$IF compilerversion < 15}
// Delphi 6 or earlier
result := 'Archaic version of Delphi (not supported).';
{$IFEND}
{$IF (compilerversion >= 22.0) and (compilerversion < 23.0)}
result := 'Delphi XE';
{$IFEND}
{$IF (compilerversion >= 23.0) and (compilerversion < 24.0)}
{$IFDEF WIN32}
result := 'Delphi XE2 32-bit';
{$ENDIF}
{$IFDEF WIN64}
result := 'Delphi XE2 64-bit';
{$ENDIF}
{$IFDEF OSX}
result := 'Delphi XE2 OSX (platform not supported yet)';
{$ENDIF}
{$IFEND}
{$IF (compilerversion >= 24.0) and (compilerversion < 25.0)}
{$IFDEF WIN32}
result := 'Delphi XE3 32-bit';
{$ENDIF}
{$IFDEF WIN64}
result := 'Delphi XE3 64-bit';
{$ENDIF}
{$IFEND}
{$IF (compilerversion >= 27.0) and (compilerversion < 28.0)}
{$IFDEF WIN32}
result := 'Delphi XE6 32-bit';
{$ENDIF}
{$IFDEF WIN64}
result := 'Delphi XE6 64-bit';
{$ENDIF}
{$IFEND}
{$IF compilerversion >= 28.0}
result := 'Unrecognised version of Delphi later than Delphi XE';
{$IFEND}
if result = '' then
result := 'Unrecognised version of Delphi';
end;
{ TEnvironment_TestCase }
procedure TEnvironment_TestCase.Test_Environment;
var
Ver: integer;
Announcement: string;
begin
Ver := rcs_version_AsInteger;
if System.RTLVersion >= 19.00 then
Check( (Ver >= 27) and (Ver <= 41),
'These unit tests were ONLY made for revisions 27 through to 41 of D-Unit.')
else
Check( Ver = 36,
'For D7 and D2007 these unit tests were ONLY made for revision 36 of D-Unit.');
// Nota bene: revision 41 is not compatible with Delphi 7.
Check( (System.RTLVersion = 15.00) or
(System.RTLVersion = 17.00) or
(System.RTLVersion = 18.00) or
(System.RTLVersion = 21.00) or
(System.RTLVersion = 23.00) or
(System.RTLVersion = 27.00),
'These unit tests were ONLY made for Delphi 7, Delphi 2005, Delphi 2007 for win32 ' +
'(Enterprise edition), Delphi 2010, Delphi XE2 win 32-bit and Delphi win XE 64-bit.');
if SizeOf( TrueNativeInt ) <> SizeOf( pointer) then
ShowMessageFmt( 'Integer = %d bytes'#13#10 +
'NativeInt = %d bytes'#13#10 +
'TrueNativeInt = %d bytes'#13#10 +
'Pointer = %d bytes'#13#10 +
'Compiler = %.2f bytes',
[SizeOf(Integer), SizeOf( NativeInt), SizeOf( TrueNativeInt), SizeOf( pointer), CompilerVersion]);
Check( (SizeOf( TrueNativeInt ) = SizeOf( pointer)) and
(SizeOf( TrueNativeUInt) = SizeOf( pointer)),
'uTPLb_PointerArithmetic Native Integer definitions wrong.');
Announcement := Format( 'You are running DUnit at SVN revision %d.', [Ver]);
Announcement := Announcement + #13#10;
Announcement := Announcement + Format( 'The SVN revision of the ' +
'uTPLb_SVN_Keywords unit of the TPLB3 run-time package is %d.'#13#10 +
'Check the TPLB3 project options for the run-time package library version.',
[TPLB3Runtime_SVN_Revision]);
Announcement := Announcement + #13#10;
Announcement := Announcement + Format( 'You are testing with compiler %s',
[DelphiVersion_DisplayName]);
ShowMessage( Announcement);
end;
initialization
InitUnit_TestCases;
finalization
DoneUnit_TestCases;
end.
|
unit GLOBAL;
interface {Opysannya dostupnoyi informatsiyi dlya yinshykh moduliv}
const
p = 2;
m = 10;
n = 10;
type
arr = array[1..p, 1..m, 1..n] of integer; {Zadannya korystuvats'koho typu "masyv"}
vector=array [1..n*m] of integer;
var A:arr; {Zminna typu masyv}
C:vector;
procedure ShowArray(const a: arr); {Protsedura vyvedennya masyvu na ekran}
procedure SortArray(var a: arr); {Protsedura vporyadkovannoho zapovnennya masyvu}
procedure UnSortArray(var a: arr); {Protsedura nevporyadkovannoho zapovnennya masyvu}
procedure BackSortArray(var a: arr); {Protsedura zapovnennya oberneno vporyadkovannoho masyvu}
procedure SortVect(var C: vector);
procedure UnSortVect(var C: vector);
procedure BackSortVect(var C: vector);
implementation
procedure ShowArray(const a: arr); {Protsedura vyvedennya masyvu na ekran}
var
i, j, k: word;
begin
for k := 1 to p do {Lichyl'nyky prokhodu po koordynatam masyvu}
begin
for i := 1 to m do
begin
for j := 1 to n do
write(a[k, i, j]:8); {Vyvedennya elementu na ekran}
writeln;
end;
writeln;
end;
end;
procedure UnSortArray(var a: arr); {Protsedura nevporyadkovannoho zapovnennya masyvu}
var
i, j, k: word; {Zminni kordynat}
begin
randomize;
for k := 1 to p do {Lichyl'nyky prokhodu po koordynatam masyvu}
for i := 1 to m do
for j := 1 to n do
a[k, i, j] := random(p * m * n); {Prysvoyennya komirtsi masyvu randomnoho znachennya}
end;
procedure SortArray(var a: arr); {Protsedura vporyadkovannoho zapovnennya masyvu}
var
i, j, k: word; {Zminni kordynat}
l: word; {Zminna, za dopomohoyu yakoyi bude zapovnyuvatysya masyv}
begin
l := 1;
for k := 1 to p do {Lichyl'nyky prokhodu po koordynatam masyvu}
for i := 1 to m do
for j := 1 to n do
begin
a[k, i, j] := l; {Prysvoyennya komirtsi masyvu znachennya l}
inc(l); {Pry kozhnomu prokhodi lichyl'nyka, zminna l bude zbil'shuvatysya na 1}
end;
end;
procedure BackSortArray(var a: arr); {Protsedura zapovnennya oberneno vporyadkovannoho masyvu}
var
i, j, k: word; {Zminni kordynat}
l: word; {Zminna, za dopomohoyu yakoyi bude zapovnyuvatysya masyv}
begin
l := p * m * n; {Zminniy l prysvoyuyet'sya znachennya kil'kosti elementiv masyvu}
for k := 1 to p do {Lichyl'nyky prokhodu po koordynatam masyvu}
for i := 1 to m do
for j := 1 to n do
begin
a[k, i, j] := l; {Prysvoyennya komirtsi masyvu znachennya l}
dec(l); {Pry kozhnomu prokhodi lichyl'nyka, zminna l bude zmen'shuvatysya na 1}
end;
end;
procedure SortVect(var C: vector);
var
i,j:integer;
begin
for i:=1 to (n*m) do
C[i]:=i;
end;
procedure UnSortVect(var C: vector);
var
i,j:integer;
begin
j:=n*m;
for i:=1 to (j) do
C[i]:=random(j);
end;
procedure BackSortVect(var C: vector);
var
i,j,g:integer;
begin
j:=n*m; g:=j;
for i:=1 to j do
begin
C[i]:=g;
dec(g);
end;
end;
end. |
unit Chapter09._05_Solution1;
{$mode objfpc}{$H+}
interface
uses
Classes,
SysUtils,
Math,
DeepStar.Utils;
/// 背包问题
/// 记忆化搜索
/// 时间复杂度: O(n * C) 其中n为物品个数; C为背包容积
/// 空间复杂度: O(n * C)
type
TSolution = class(TObject)
public
function knapsack01(const w, v: TArr_int; c: integer): integer;
end;
procedure Main;
implementation
procedure Main;
var
w, v: TArr_int;
begin
w := [1, 2, 3];
v := [6, 10, 12];
with TSolution.Create do
begin
WriteLn(knapsack01(w, v, 5));
Free;
end;
end;
{ TSolution }
function TSolution.knapsack01(const w, v: TArr_int; c: integer): integer;
var
memo: TArr2D_int;
// 用 [0...index]的物品,填充容积为c的背包的最大价值
function __bestValue__(index, c: integer): integer;
var
res: integer;
begin
if (c <= 0) or (index < 0) then
Exit(0);
if memo[index, c] <> -1 then
Exit(memo[index, c]);
res := __bestValue__(index - 1, c);
if c >= w[index] then
res := Max(res, v[index] + __bestValue__(index - 1, c - w[index]));
memo[index, c] := res;
Result := res;
end;
var
n, i: integer;
begin
Assert((Length(w) = Length(v)) and (c >= 0));
n := Length(w);
if (n = 0) or (c = 0) then
Exit(0);
SetLength(memo, n, c + 1);
for i := 0 to n - 1 do
TArrayUtils_int.FillArray(memo[i], -1);
Result := __bestValue__(n - 1, c);
end;
end.
|
{
Datamove - Conversor de Banco de Dados Firebird para Oracle
licensed under a APACHE 2.0
Projeto Particular desenvolvido por Artur Barth e Gilvano Piontkoski para realizar conversão de banco de dados
firebird para Oracle. Esse não é um projeto desenvolvido pela VIASOFT.
Toda e qualquer alteração deve ser submetida à
https://github.com/Arturbarth/Datamove
}
unit uThreadMoveDados;
interface
uses
System.Classes, Vcl.ComCtrls,
FireDAC.Stan.Intf, FireDAC.Stan.Option,
FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS,
FireDAC.Stan.Async, FireDAC.DApt, FireDAC.Comp.Client,
Data.DB, FireDAC.Comp.DataSet, FireDAC.UI.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Phys, FireDAC.Phys.Oracle,
FireDAC.Phys.FB, uConexoes, uParametrosConexao, uEnum, Vcl.StdCtrls,
uThreadMoveTabela, System.Generics.Collections;
type
TThreadMoveDados = class
private
FcMsg: String;
FeTpLog: tpLog;
FnTotalTabelas: Integer;
FnTabelaAtual: Integer;
FModelFirebird: TModelConexao;
FModelOracle: TModelConexao;
qryTabelas: TFDQuery;
procedure Logar(eTpLog: tpLog; cMsg: String);
procedure SyncLogar;
protected
//procedure Execute; override;
public
FmeLog: TMemo;
FmeErros: TMemo;
FConsulta: String;
ThreadCount: Integer;
oListaThreads : TList;
FpbStatus: TProgressBar;
FDConOracle: TFDConnection;
FDConFireBird: TFDConnection;
FParOracle, FParmFirebird: IParametrosConexao;
procedure CarregarTabelasSistema;
procedure ConfigurarConexoes;
procedure MoverTabela(cTabela: String; nLinhas: Integer);
procedure MoverTabelasSistema;
constructor Create; overload;
destructor Destroy; override;
end;
implementation
uses System.SysUtils, uLog, uMoveDados;
{ TThreadMoveDados }
{procedure TThreadMoveDados.Execute;
begin
ThreadCount := 0;
oListaThreads := TList.Create;
ConfigurarConexoes;
MoverTabelasSistema;
end;}
procedure TThreadMoveDados.MoverTabelasSistema;
var
cTabela: String;
begin
Logar(tplLog,' iniciar tabelas ');
qryTabelas.Connection := FDConFirebird;
FmeLog.Clear;
FmeErros.Clear;
CarregarTabelasSistema;
FnTotalTabelas := qryTabelas.RecordCount;
Logar(tplLog, ' : Iniciando cópia das tabelas PADRÕES do SISTEMA ::');
qryTabelas.First;
while (not qryTabelas.Eof) do
begin
try
FnTabelaAtual := qryTabelas.RecNo;
cTabela := Trim(qryTabelas.FieldByName('TABELA').AsString);
MoverTabela(cTabela, qryTabelas.FieldByName('LINHAS').AsInteger);
except
on e: Exception do
begin
Logar(tplErro,' : Erro: ' + cTabela + ' :: ' + e.message);
end;
end;
qryTabelas.next;
end;
end;
procedure TThreadMoveDados.MoverTabela(cTabela: String; nLinhas: Integer);
var
oThreadMoveTabelas: TThreadMoveTabelas;
i: Integer;
{dtini, dtfim, total: TDateTime;
oMove: TMoveDados;}
begin
Inc(ThreadCount);
oThreadMoveTabelas := TThreadMoveTabelas.Create;
oThreadMoveTabelas.FmeLog := FmeLog;
oThreadMoveTabelas.FmeErros := FmeErros;
oThreadMoveTabelas.FpbStatus := FpbStatus;
oThreadMoveTabelas.FTabela := cTabela;
oThreadMoveTabelas.FLinhas := nLinhas;
oThreadMoveTabelas.FParmFirebird := FParmFirebird;
oThreadMoveTabelas.FParOracle := FParOracle;
oThreadMoveTabelas.FDConOracle := FDConOracle;
oThreadMoveTabelas.FDConFireBird := FDConFireBird;
oThreadMoveTabelas.FnTotalTabelas := FnTotalTabelas;
oThreadMoveTabelas.FnTabelaAtual := FnTabelaAtual;
oThreadMoveTabelas.MoverTabela(cTabela, nLinhas);;
{oListaThreads.Add(oThreadMoveTabelas);
if ThreadCount >= 8 then
begin
while oListaThreads.Count > 8 do begin
for I := 0 to oListaThreads.Count-1 do
begin
if TThreadMoveTabelas(oListaThreads[i]).Finalizou then
begin
Dec(ThreadCount);
oListaThreads.Remove(oListaThreads[i]);
Break;
end;
end;
end;
{while not oThreadMoveTabelas.Finalizou do
Sleep(5);
end;?
{try
Logar(tplLog, ' : Inciando copia da tabela ' + cTabela + '('+ IntToStr(nLinhas) +' registros) - Tabela' + IntToStr(FnTabelaAtual) + ' de ' + IntToStr(FnTotalTabelas));
dtini := Now;
oMove := TMoveDados.Create(FDConFirebird, FDConOracle);
oMove.MoverDadosTabela(cTabela);
total := Now-dtini;
Logar(tplLog, ' : Finalizada copia da tabela ' + cTabela + ' com ' +
IntToStr(nLinhas) + ' registros ' +
' em ' + FormatDateTime('hh:mm:sssss', total));
finally
oMove.Free;
end;}
end;
procedure TThreadMoveDados.ConfigurarConexoes;
//var
// oParOracle, oParmFirebird: IParametrosConexao;
begin
// oParmFirebird := TParametrosConexao.New('127.0.0.1', '3050', 'E:\Bancos\INDIANAAGRI_MIGRA.FDB', 'VIASOFT', '153', 'FB');
try
Logar(tplLog, ' : Conectando Origem ::');
FModelFirebird := TModelConexao.Create(FParmFirebird);
FDConFirebird := FModelFirebird.GetConexao;
Logar(tplLog, ' : Conectado Origem ::');
except
on e:Exception do begin
Logar(tplLog, ' : Conectando Origem ::' + e.Message);
end;
end;
try
Logar(tplLog, ' : Conectando Destino ::');
// oParOracle := TParametrosConexao.New('127.0.0.1', '1521', 'LOCAL_ORCL', 'VIASOFT', 'VIASOFT', 'Ora');
FModelOracle := TModelConexao.Create(FParOracle);
FDConOracle := FModelOracle.GetConexao;
Logar(tplLog, ' : Conectado Destino ::');
except
on e:Exception do begin
Logar(tplLog, ' : Conectando Destino ::' + e.Message);
end;
end;
qryTabelas.Connection := FDConFirebird;
end;
constructor TThreadMoveDados.Create;
begin
inherited Create;
qryTabelas := TFDQuery.Create(nil);
end;
destructor TThreadMoveDados.Destroy;
begin
FModelFirebird.Free;
FModelOracle.Free;
qryTabelas.Free;
inherited;
end;
procedure TThreadMoveDados.CarregarTabelasSistema;
begin
try
Logar(tplLog,' Carregando tabelas ');
qryTabelas.Close;
qryTabelas.SQL.Text := FConsulta;
// qryTabelas.SQL.Text := 'SELECT * FROM MIGRATABELAS WHERE TABELA = ''PCLASFIS'''; //MIGRAR = '+ QuotedStr('S') +
// ' AND PERSONALIZADA <> ' + QuotedStr('S') + ' AND LINHAS > 0 AND MIGRADA <> ' + QuotedStr('S') +
// ' ORDER BY LINHAS DESC';
qryTabelas.Open;
qryTabelas.FetchAll;
except
on e: Exception do
begin
Logar(tplErro,' : Erro ao carregar lista de tabelas : ' + e.message);
end;
end;
end;
procedure TThreadMoveDados.Logar(eTpLog: tpLog; cMsg: String);
begin
FcMsg := cMsg;
FeTpLog := eTpLog;
SyncLogar;
//Synchronize(SyncLogar);
end;
procedure TThreadMoveDados.SyncLogar;
begin
TLog.New.Logar(FcMsg);
if (FeTpLog = tplLog) then
FmeLog.Lines.Add(FormatDateTime('yyyy-mm-dd hh:mm:sssss', now) + ' : ' + FcMsg)
else if (FeTpLog = tplErro) then
FmeErros.Lines.Add(FormatDateTime('yyyy-mm-dd hh:mm:sssss', now) + ' : ' + FcMsg);
//FpbStatus.Position := Round((FnTabelaAtual/FnTotalTabelas)*100);
end;
end.
{
Datamove - Conversor de Banco de Dados Firebird para Oracle
licensed under a APACHE 2.0
Projeto Particular desenvolvido por Artur Barth e Gilvano Piontkoski para realizar conversão de banco de dados
firebird para Oracle. Esse não é um projeto desenvolvido pela VIASOFT.
Toda e qualquer alteração deve ser submetida à
https://github.com/Arturbarth/Datamove
}
|
{ ****************************************************************************** }
{ * Low MemoryHook written by QQ 600585@qq.com * }
{ * https://zpascal.net * }
{ * https://github.com/PassByYou888/zAI * }
{ * https://github.com/PassByYou888/ZServer4D * }
{ * https://github.com/PassByYou888/PascalString * }
{ * https://github.com/PassByYou888/zRasterization * }
{ * https://github.com/PassByYou888/CoreCipher * }
{ * https://github.com/PassByYou888/zSound * }
{ * https://github.com/PassByYou888/zChinese * }
{ * https://github.com/PassByYou888/zExpression * }
{ * https://github.com/PassByYou888/zGameWare * }
{ * https://github.com/PassByYou888/zAnalysis * }
{ * https://github.com/PassByYou888/FFMPEG-Header * }
{ * https://github.com/PassByYou888/zTranslate * }
{ * https://github.com/PassByYou888/InfiniteIoT * }
{ * https://github.com/PassByYou888/FastMD5 * }
{ ****************************************************************************** }
(*
update history
2017-12-31
*)
unit MH;
{$INCLUDE zDefine.inc}
interface
uses CoreClasses, SyncObjs, ListEngine;
procedure BeginMemoryHook_1;
procedure EndMemoryHook_1;
function GetHookMemorySize_1: nativeUInt;
function GetHookPtrList_1: TPointerHashNativeUIntList;
procedure BeginMemoryHook_2;
procedure EndMemoryHook_2;
function GetHookMemorySize_2: nativeUInt;
function GetHookPtrList_2: TPointerHashNativeUIntList;
procedure BeginMemoryHook_3;
procedure EndMemoryHook_3;
function GetHookMemorySize_3: nativeUInt;
function GetHookPtrList_3: TPointerHashNativeUIntList;
implementation
uses MH_ZDB, MH_1, MH_2, MH_3, DoStatusIO, PascalStrings;
procedure BeginMemoryHook_1;
begin
MH_1.BeginMemoryHook($FFFF);
end;
procedure EndMemoryHook_1;
begin
MH_1.EndMemoryHook;
end;
function GetHookMemorySize_1: nativeUInt;
begin
Result := MH_1.GetHookMemorySize;
end;
function GetHookPtrList_1: TPointerHashNativeUIntList;
begin
Result := MH_1.GetHookPtrList;
end;
procedure BeginMemoryHook_2;
begin
MH_2.BeginMemoryHook($FFFF);
end;
procedure EndMemoryHook_2;
begin
MH_2.EndMemoryHook;
end;
function GetHookMemorySize_2: nativeUInt;
begin
Result := MH_2.GetHookMemorySize;
end;
function GetHookPtrList_2: TPointerHashNativeUIntList;
begin
Result := MH_2.GetHookPtrList;
end;
procedure BeginMemoryHook_3;
begin
MH_3.BeginMemoryHook($FFFF);
end;
procedure EndMemoryHook_3;
begin
MH_3.EndMemoryHook;
end;
function GetHookMemorySize_3: nativeUInt;
begin
Result := MH_3.GetHookMemorySize;
end;
function GetHookPtrList_3: TPointerHashNativeUIntList;
begin
Result := MH_3.GetHookPtrList;
end;
var
MHStatusCritical: TCriticalSection;
OriginDoStatusHook: TDoStatusCall;
procedure InternalDoStatus(Text: SystemString; const ID: Integer);
var
hook_state_bak: Boolean;
begin
hook_state_bak := GlobalMemoryHook.V;
GlobalMemoryHook.V := False;
MHStatusCritical.Acquire;
try
OriginDoStatusHook(Text, ID);
finally
MHStatusCritical.Release;
GlobalMemoryHook.V := hook_state_bak;
end;
end;
initialization
MHStatusCritical := TCriticalSection.Create;
OriginDoStatusHook := OnDoStatusHook;
OnDoStatusHook := {$IFDEF FPC}@{$ENDIF FPC}InternalDoStatus;
finalization
DisposeObject(MHStatusCritical);
OnDoStatusHook := OriginDoStatusHook;
end.
|
namespace MetalExample;
interface
uses
Metal,
MetalKit;
// Helper Class for load a Shader from Resources and setup the vertex and fragment functions
type
shaderLoader = class
private
_vertexfunc :MTLFunction;
_fragmentfunc :MTLFunction;
public
constructor(const device: MTLDevice) Shadername(const shadername: String) Vertexname(const vertexname: String) Fragmentname(const fragmentname: String);
property VertexFunc : MTLFunction read _vertexfunc;
property FragmentFunc : MTLFunction read _fragmentfunc;
end;
implementation
constructor shaderLoader(const device: MTLDevice) Shadername(const shadername: String) Vertexname(const vertexname: String) Fragmentname(const fragmentname: String);
begin
var lError : Error;
var SourceShader := Asset.getFullname(shadername); readonly;
// Try to Load the Shader Lib
var defaultLibrary : MTLLibrary := device.newLibraryWithFile(SourceShader) error(var lError);
// Load all the shader files with a .metal file extension in the project
// Will not work at moment in element because there is no precompile for the shaders like in xcode
// var defaultLibrary : MTLLibrary := _device.newDefaultLibrary;
if defaultLibrary = nil then
begin
NSLog("Failed to load the Shaderlib, error %@", lError);
exit nil;
end
else
begin
_vertexfunc := defaultLibrary.newFunctionWithName(vertexname);
if _vertexfunc = nil then
begin
NSLog("Failed to get the Vertex Function , error %@", lError);
exit nil;
end;
// Load the fragment function from the library
_fragmentfunc := defaultLibrary.newFunctionWithName(fragmentname);
if _fragmentfunc = nil then
begin
NSLog("Failed to get the Fragment Function , error %@", lError);
exit nil;
end;
end;
end;
end. |
unit RegistryCleaner_RegExceptions;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls;
type
TfmRegExceptionsAdd = class(TForm)
edExclusionString: TEdit;
gbExcludeFrom: TGroupBox;
rbKeyAddr: TRadioButton;
rbText: TRadioButton;
lbExclusionString: TLabel;
ShapeBottom: TShape;
btOK: TButton;
btCancel: TButton;
procedure btCancelClick(Sender: TObject);
procedure btOKClick(Sender: TObject);
procedure ApplyLang;
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
fmRegExceptionsAdd: TfmRegExceptionsAdd;
implementation
uses RegistryCleaner_Settings;
{$R *.dfm}
{ЧТЕНИЕ ЯЗЫКОВОЙ СТРОКИ ИЗ ОПРЕДЕЛЁННОГО ФАЙЛА}
function ReadLangStr(FileName, Section, Caption: PChar): PChar; external 'Functions.dll';
//=========================================================
{КНОПКА "ОТМЕНА"}
//---------------------------------------------------------
procedure TfmRegExceptionsAdd.btCancelClick(Sender: TObject);
begin
Close;
end;
//=========================================================
//=========================================================
{ПРИМЕНЕНИЕ ЯЗЫКА}
//---------------------------------------------------------
procedure TfmRegExceptionsAdd.ApplyLang;
begin
Caption := ReadLangStr('RegistryCleaner.lng', 'Registry Cleaner', 'fmRegExceptionsAdd');
lbExclusionString.Caption := ReadLangStr('RegistryCleaner.lng', 'Registry Cleaner', 'lbExclusionString');
gbExcludeFrom.Caption := ReadLangStr('RegistryCleaner.lng', 'Registry Cleaner', 'gbExcludeFrom');
rbKeyAddr.Caption := ReadLangStr('RegistryCleaner.lng', 'Registry Cleaner', 'RegKey');
rbText.Caption := ReadLangStr('RegistryCleaner.lng', 'Registry Cleaner', 'Parameter');
btCancel.Caption := ReadLangStr('WinTuning_Common.lng', 'Common', 'Cancel');
end;
//=========================================================
//=========================================================
{КНОПКА "OK"}
//---------------------------------------------------------
procedure TfmRegExceptionsAdd.btOKClick(Sender: TObject);
var
LstIndex: integer;
begin
fmSettings.GridRegException.AddRow;
LstIndex := fmSettings.GridRegException.RowCount - 1;
if rbKeyAddr.Checked then fmSettings.GridRegException.Cells[1, LstIndex] := ReadLangStr('RegistryCleaner.lng', 'Registry Cleaner', 'RegKey')
else fmSettings.GridRegException.Cells[1, LstIndex] := ReadLangStr('RegistryCleaner.lng', 'Registry Cleaner', 'Parameter');
fmSettings.GridRegException.Cells[2, LstIndex] := edExclusionString.Text;
fmSettings.GridRegException.AutoSizeColumns(True);
Close;
end;
//=========================================================
//=========================================================
{ПРИ СОЗДАНИИ ФОРМЫ}
//---------------------------------------------------------
procedure TfmRegExceptionsAdd.FormCreate(Sender: TObject);
begin
ApplyLang;
end;
//=========================================================
end.
|
unit uI2XThreadBase;
interface
uses
SysUtils,
Classes,
uI2XDLL,
uDWImage,
GR32,
uI2XConstants,
uFileDir,
uI2XTemplate,
uImage2XML,
uI2XPluginManager
;
type
TI2XThreadedImageJob = class(TThread)
private
FTaskIDFriendly : string;
FImageMemoryMapID : string;
FLastStatusMessage : string;
FLastDebugMessage : string;
FErrorNo : integer;
FErrorString: string;
FDebugLevel : TDebugLevel;
FDebugPath : string;
FDebugLog : string;
FReturnValue : integer;
FDWImage : TDWImage;
FTaskCount : integer;
FResultXML : string;
FTaskCompleted : integer;
FOnCancel : TOnCancelEvent;
FOnJobStart : TOnJobStartEvent;
FOnJobEnd : TOnJobEndEvent;
FOnReturnXML : TOnReturnXMLEvent;
FOnJobError : TOnJobErrorEvent;
FOnStatusChange : TOnStatusChangeEvent;
FOnDebugMessage : TOnStatusChangeEvent;
FEnableJobEvents : boolean;
FImageFileName : string;
//Global plugin manager, this is so we do not have to reload this everytime it runs..
// Remember that we cannot use this if we choose to run this class threaded!
// It is much easier to mess with threads when objects are created in thier own thread
FPluginManager : TI2XPluginManager;
function DefaultDebugPath: string;
function getImageFileName: string;
procedure setImageFileName(const Value: string);
protected
FCreatePluginMananger : boolean;
function getPluginManager(): TI2XPluginManager;
procedure setPluginManager(Value: TI2XPluginManager);
procedure OnStatusChange( StatusMessage : string );
procedure OnDebugMessage( DebugMessage : string );
procedure OnJobStart( TasksCount : integer );
procedure OnJobError( ErrorNo : integer; ErrorString: string );
procedure OnCancel();
procedure OnJobEnd( TasksCompleted : integer; ImageMemoryMapID : string );
procedure OnReturnXML( ResultXML : string );
procedure DoJobStart(); virtual;
procedure DoCancel(); virtual;
procedure DoJobEnd(); virtual;
procedure DoReturnXML(); virtual;
procedure DoJobError(); virtual;
procedure DoStatusChange(); virtual;
procedure DoDebugMessage(); virtual;
procedure OnJobStartNull( TasksCount : integer );
procedure OnJobEndNull( TasksCompleted : integer; ImageMemoryMapID : string );
procedure OnReturnXMLNull( ResultXML : string );
procedure OnJobErrorNull( ErrorNo : integer; ErrorString: string );
//procedure Execute; override;
public
property DWImage : TDWImage read FDWImage write FDWImage;
property ImageMemoryMapID : string read FImageMemoryMapID write FImageMemoryMapID;
//This does not always equal the file name bieng OCRed. This is the file name this is
// written to the Output XML
property ImageFileName : string read getImageFileName write setImageFileName;
property LastStatusMessage : string read FLastStatusMessage write FLastStatusMessage;
property LastDebugMessage : string read FLastDebugMessage write FLastDebugMessage;
property OnJobStartEvent : TOnJobStartEvent read FOnJobStart write FOnJobStart;
property OnJobEndEvent : TOnJobEndEvent read FOnJobEnd write FOnJobEnd;
property OnReturnXMLEvent : TOnReturnXMLEvent read FOnReturnXML write FOnReturnXML;
property OnJobErrorEvent : TOnJobErrorEvent read FOnJobError write FOnJobError;
property OnStatusChangeEvent : TOnStatusChangeEvent read FOnStatusChange write FOnStatusChange;
property OnDebugMessageEvent : TOnStatusChangeEvent read FOnDebugMessage write FOnDebugMessage;
property DebugLevel : TDebugLevel read FDebugLevel write FDebugLevel;
property DebugPath : string read FDebugPath write FDebugPath;
property TaskIDFriendly : string read FTaskIDFriendly write FTaskIDFriendly;
property EnableJobEvents : boolean read FEnableJobEvents write FEnableJobEvents;
property PluginManager : TI2XPluginManager read getPluginManager write setPluginManager;
property ResultXML : string read FResultXML write FResultXML;
constructor Create(); overload;
constructor Create( bmp32: TBitmap32 ); overload;
destructor Destroy; override;
end;
implementation
{ TI2XThreadedImageJob }
function TI2XThreadedImageJob.DefaultDebugPath : string;
var
filedir : CFileDir;
begin
try
filedir := CFileDir.Create;
Result := filedir.GetSystemTempDir + TEMP_DIR_QUAL;
finally
FreeAndNil( filedir );
end;
end;
constructor TI2XThreadedImageJob.Create;
begin
inherited Create(true);
FDWImage := TDWImage.Create;
DebugLevel := dbNone;
FDebugPath := DefaultDebugPath();
FTaskIDFriendly := IntToStr( self.ThreadID );
FEnableJobEvents := true;
FCreatePluginMananger := true;
FImageFileName := '';
end;
constructor TI2XThreadedImageJob.Create(bmp32: TBitmap32);
begin
inherited Create(true);
FDWImage := TDWImage.Create( bmp32 );
DebugLevel := dbNone;
FDebugPath := DefaultDebugPath();
FTaskIDFriendly := IntToStr( self.ThreadID );
FEnableJobEvents := true;
FCreatePluginMananger := true;
FImageFileName := '';
end;
destructor TI2XThreadedImageJob.Destroy;
begin
FreeAndNil( FDWImage );
inherited;
end;
procedure TI2XThreadedImageJob.DoCancel;
Begin
if ( Assigned(self.FOnCancel)) then begin
FOnCancel( self, self.FTaskIDFriendly );
end;
End;
procedure TI2XThreadedImageJob.DoDebugMessage;
begin
if ( Assigned( self.FOnDebugMessage )) then begin
FOnDebugMessage( self, self.FTaskIDFriendly, self.FLastDebugMessage );
end;
end;
procedure TI2XThreadedImageJob.DoJobEnd;
begin
if ( Assigned(self.FOnJobEnd)) then begin
FOnJobEnd( self, self.FTaskIDFriendly, self.FTaskCompleted, self.FImageMemoryMapID );
end;
end;
procedure TI2XThreadedImageJob.DoJobError;
begin
if ( Assigned( self.FOnJobError )) then begin
FOnJobError( self, self.FTaskIDFriendly, self.FErrorNo, self.FErrorString );
end;
end;
procedure TI2XThreadedImageJob.DoJobStart;
begin
if ( Assigned(self.FOnJobStart)) then begin
FOnJobStart( self, self.FTaskIDFriendly, self.FTaskCount );
end;
end;
procedure TI2XThreadedImageJob.DoReturnXML;
begin
if ( Assigned( self.FOnReturnXML )) then begin
FOnReturnXML( self, self.FTaskIDFriendly, self.FResultXML );
end;
end;
procedure TI2XThreadedImageJob.DoStatusChange;
begin
if ( Assigned( self.FOnStatusChange )) then begin
FOnStatusChange( self, self.FTaskIDFriendly, self.FLastStatusMessage );
end;
end;
function TI2XThreadedImageJob.getImageFileName: string;
begin
Result := self.FImageFileName;
end;
function TI2XThreadedImageJob.getPluginManager: TI2XPluginManager;
begin
Result := self.FPluginManager;
end;
procedure TI2XThreadedImageJob.OnCancel();
begin
self.Synchronize( self.DoCancel );
end;
procedure TI2XThreadedImageJob.OnDebugMessage(DebugMessage: string);
begin
self.FLastDebugMessage := DebugMessage;
self.Synchronize( self.DoDebugMessage );
end;
procedure TI2XThreadedImageJob.OnJobEnd(TasksCompleted : integer; ImageMemoryMapID : string );
begin
self.FTaskCompleted := TasksCompleted;
self.FImageMemoryMapID := ImageMemoryMapID;
self.Synchronize( self.DoJobEnd );
end;
procedure TI2XThreadedImageJob.OnJobEndNull(TasksCompleted: integer; ImageMemoryMapID : string );
begin
end;
procedure TI2XThreadedImageJob.OnJobError(ErrorNo: integer;
ErrorString: string);
begin
self.FErrorNo := ErrorNo;
self.FErrorString := ErrorString;
self.Synchronize( self.DoJobError );
end;
procedure TI2XThreadedImageJob.OnJobErrorNull(ErrorNo: integer;
ErrorString: string);
begin
end;
procedure TI2XThreadedImageJob.OnJobStart(TasksCount: integer);
begin
self.FTaskCount := TasksCount;
self.Synchronize( self.DoJobStart );
end;
procedure TI2XThreadedImageJob.OnJobStartNull(TasksCount: integer);
begin
end;
procedure TI2XThreadedImageJob.OnReturnXML( ResultXML: string);
begin
self.ResultXML := ResultXML;
self.Synchronize( self.DoReturnXML );
end;
procedure TI2XThreadedImageJob.OnReturnXMLNull( ResultXML: string);
begin
end;
procedure TI2XThreadedImageJob.OnStatusChange(StatusMessage: string);
begin
self.FLastStatusMessage := StatusMessage;
self.Synchronize( self.DoStatusChange );
end;
procedure TI2XThreadedImageJob.setImageFileName(const Value: string);
begin
FImageFileName := Value;
end;
procedure TI2XThreadedImageJob.setPluginManager(Value: TI2XPluginManager);
begin
if ( Value = nil ) then begin
self.FCreatePluginMananger := true;
self.FPluginManager := nil;
end else begin
self.FCreatePluginMananger := false;
self.FPluginManager := Value;
end;
end;
initialization
finalization
END.
|
unit uFrmPurchaseCalcFreight;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, PAIDETODOS, siComp, siLangRT, StdCtrls, LblEffct, ExtCtrls, DB,
DBClient, ADODB, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData,
cxEdit, cxDBData, cxGridLevel, cxClasses, cxControls, cxGridCustomView,
cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid,
Buttons, SuperEdit, SuperEditCurrency, uDMCalcTax;
type
TFrmPurchaseCalcFreight = class(TFrmParent)
btnOK: TButton;
pnlValues: TPanel;
cdsPurchaseItem: TClientDataSet;
cdsItemTaxes: TClientDataSet;
cdsPurchaseItemIDPurchaseItem: TIntegerField;
cdsPurchaseItemModel: TStringField;
cdsPurchaseItemDescription: TStringField;
cdsPurchaseItemCostPrice: TCurrencyField;
cdsPurchaseItemFreight: TCurrencyField;
cdsPurchaseItemOtherCost: TCurrencyField;
cdsPurchaseItemTaxes: TCurrencyField;
cdsPurchaseItemNewCostPrice: TCurrencyField;
cdsItemTaxesIDPurchaseItemTax: TIntegerField;
cdsItemTaxesTaxValue: TCurrencyField;
cdsItemTaxesDebit: TBooleanField;
quPurchaseItem: TADODataSet;
cdsPurchaseItemNewSalePrice: TCurrencyField;
cdsPurchaseItemNewMSRP: TCurrencyField;
quPurchaseItemIDPurchaseItem: TIntegerField;
quPurchaseItemCostPrice: TBCDField;
quPurchaseItemFreightCost: TBCDField;
quPurchaseItemOtherCost: TBCDField;
quPurchaseItemNewCostPrice: TBCDField;
quPurchaseItemNewSalePrice: TBCDField;
quPurchaseItemNewSuggRetail: TBCDField;
quPurchaseItemModel: TStringField;
quPurchaseItemDescription: TStringField;
grdPurchaseItem: TcxGrid;
grdPurchaseItemDB: TcxGridDBTableView;
grdPurchaseItemLevel: TcxGridLevel;
dsPurchaseItem: TDataSource;
grdPurchaseItemDBModel: TcxGridDBColumn;
grdPurchaseItemDBDescription: TcxGridDBColumn;
grdPurchaseItemDBCostPrice: TcxGridDBColumn;
grdPurchaseItemDBFreight: TcxGridDBColumn;
grdPurchaseItemDBOtherCost: TcxGridDBColumn;
grdPurchaseItemDBTaxes: TcxGridDBColumn;
grdPurchaseItemDBNewCostPrice: TcxGridDBColumn;
grdPurchaseItemDBNewSalePrice: TcxGridDBColumn;
grdPurchaseItemDBNewMSRP: TcxGridDBColumn;
quItemTax: TADODataSet;
quItemTaxIDPurchaseItemTax: TIntegerField;
quItemTaxTaxValue: TBCDField;
quItemTaxTaxPercentage: TBCDField;
quItemTaxTaxCategory: TStringField;
quItemTaxDebit: TBooleanField;
quItemTaxFormula: TStringField;
cdsItemTaxesFormula: TStringField;
lbFreight: TLabel;
edtFreight: TSuperEditCurrency;
lbOtherCost: TLabel;
edtOtherCost: TSuperEditCurrency;
btnApply: TBitBtn;
cdsPurchaseItemQty: TFloatField;
quPurchaseItemQty: TFloatField;
cdsItemTaxesIDPurchaseItem: TIntegerField;
quItemTaxIDTaxCategory: TIntegerField;
cdsItemTaxesIDTaxCategory: TIntegerField;
cdsItemTaxesTaxPercentage: TBCDField;
quItemTaxIDPurchaseItem: TIntegerField;
cmdUpdatePurchaseItem: TADOCommand;
cdmItemTax: TADOCommand;
quPurchaseItemIDModel: TIntegerField;
quPurchaseItemIDCategory: TIntegerField;
quPurchaseItemIDSubCategory: TIntegerField;
quPurchaseItemIDGroup: TIntegerField;
cdsPurchaseItemIDModel: TIntegerField;
cdsPurchaseItemIDCategory: TIntegerField;
cdsPurchaseItemIDSubCategory: TIntegerField;
cdsPurchaseItemIDGroup: TIntegerField;
lbDiscount: TLabel;
edtDiscount: TSuperEditCurrency;
quPurchaseItemDiscount: TBCDField;
cdsPurchaseItemDiscount: TCurrencyField;
grdPurchaseItemDBDiscount: TcxGridDBColumn;
grdPurchaseItemDBQty: TcxGridDBColumn;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btCloseClick(Sender: TObject);
procedure btnOKClick(Sender: TObject);
procedure edtFreightKeyPress(Sender: TObject; var Key: Char);
procedure btnApplyClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
private
DMCalcTax : TDMCalcTax;
FResult : Boolean;
FIDPurchase : Integer;
FPurchaseSubTotal : Currency;
FCalcSalePrice : Boolean;
procedure ApplyValues;
procedure OpenPurchaseItem;
procedure ClosePurchaseItem;
procedure BuildPurchaseItem;
procedure OpenItemTax;
procedure CloseItemTax;
function GetTotalItemTax(IDPurchaseItem : Integer): Currency;
function UpdateItemTax(IDItem : Integer; CostPrice, Freight, OtherCost, Discount : Currency) : Currency;
function CalcNewSalePrice(CostPrice : Currency; IDModel, IDCat, IDSubCat, IDGroup : Integer): Currency;
function CalcNewMSRP(CostPrice : Currency; IDCat, IDSubCat, IDGroup : Integer): Currency;
procedure SaveValues;
public
function Start(IDPurchase : Integer; PurchaseSubTotal : Currency) : Boolean;
end;
implementation
uses uDM, uCharFunctions, uNumericFunctions, uSystemConst, uMsgBox, uHandleError;
{$R *.dfm}
{ TFrmPurchaseCalcFreight }
function TFrmPurchaseCalcFreight.Start(IDPurchase : Integer;
PurchaseSubTotal : Currency): Boolean;
begin
FResult := False;
FIDPurchase := IDPurchase;
FPurchaseSubTotal := PurchaseSubTotal;
BuildPurchaseItem;
FCalcSalePrice := DM.fSystem.SrvParam[PARAM_CALC_MARGIN];
ShowModal;
Result := FResult;
end;
procedure TFrmPurchaseCalcFreight.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
inherited;
ClosePurchaseItem;
CloseItemTax;
FreeAndNil(DMCalcTax);
Action := caFree;
end;
procedure TFrmPurchaseCalcFreight.btCloseClick(Sender: TObject);
begin
inherited;
Close;
end;
procedure TFrmPurchaseCalcFreight.btnOKClick(Sender: TObject);
begin
inherited;
SaveValues;
FResult := True;
Close;
end;
procedure TFrmPurchaseCalcFreight.ClosePurchaseItem;
begin
with cdsPurchaseItem do
if Active then
Close;
end;
procedure TFrmPurchaseCalcFreight.OpenPurchaseItem;
begin
with cdsPurchaseItem do
if not Active then
begin
CreateDataSet;
Open;
end;
end;
procedure TFrmPurchaseCalcFreight.BuildPurchaseItem;
begin
with quPurchaseItem do
try
if Active then
Close;
Parameters.ParamByName('IDPurchase').Value := FIDPurchase;
Open;
if not IsEmpty then
begin
OpenPurchaseItem;
OpenItemTax;
while not EOF do
begin
cdsPurchaseItem.Append;
cdsPurchaseItem.FieldByName('IDPurchaseItem').AsInteger := FieldByName('IDPurchaseItem').AsInteger;
cdsPurchaseItem.FieldByName('IDModel').AsInteger := FieldByName('IDModel').AsInteger;
cdsPurchaseItem.FieldByName('IDCategory').AsInteger := FieldByName('IDCategory').AsInteger;
cdsPurchaseItem.FieldByName('IDSubCategory').AsInteger := FieldByName('IDSubCategory').AsInteger;
cdsPurchaseItem.FieldByName('IDGroup').AsInteger := FieldByName('IDGroup').AsInteger;
cdsPurchaseItem.FieldByName('Model').AsString := FieldByName('Model').AsString;
cdsPurchaseItem.FieldByName('Description').AsString := FieldByName('Description').AsString;
cdsPurchaseItem.FieldByName('CostPrice').AsCurrency := FieldByName('CostPrice').AsCurrency;
cdsPurchaseItem.FieldByName('Freight').AsCurrency := FieldByName('FreightCost').AsCurrency;
cdsPurchaseItem.FieldByName('OtherCost').AsCurrency := FieldByName('OtherCost').AsCurrency;
cdsPurchaseItem.FieldByName('Taxes').AsCurrency := GetTotalItemTax(FieldByName('IDPurchaseItem').AsInteger);
cdsPurchaseItem.FieldByName('NewCostPrice').AsCurrency := FieldByName('NewCostPrice').AsCurrency;
cdsPurchaseItem.FieldByName('NewSalePrice').AsCurrency := FieldByName('NewSalePrice').AsCurrency;
cdsPurchaseItem.FieldByName('NewMSRP').AsCurrency := FieldByName('NewSuggRetail').AsCurrency;
cdsPurchaseItem.FieldByName('Qty').AsFloat := FieldByName('Qty').AsFloat;
cdsPurchaseItem.FieldByName('Discount').AsCurrency := FieldByName('Discount').AsCurrency;
cdsPurchaseItem.Post;
Next;
end;
cdsPurchaseItem.First;
end;
finally
Close;
end;
end;
procedure TFrmPurchaseCalcFreight.CloseItemTax;
begin
with cdsItemTaxes do
if Active then
Close;
end;
function TFrmPurchaseCalcFreight.GetTotalItemTax(IDPurchaseItem: Integer): Currency;
begin
with quItemTax do
try
if Active then
Close;
Parameters.ParamByName('IDPurchaseItem').Value := IDPurchaseItem;
Open;
Result := 0;
if not IsEmpty then
while not EOF do
begin
Result := Result + FieldByName('TaxValue').AsCurrency;
cdsItemTaxes.Append;
cdsItemTaxes.FieldByName('IDPurchaseItemTax').AsInteger := FieldByName('IDPurchaseItemTax').AsInteger;
cdsItemTaxes.FieldByName('IDPurchaseItem').AsInteger := FieldByName('IDPurchaseItem').AsInteger;
cdsItemTaxes.FieldByName('IDTaxCategory').AsInteger := FieldByName('IDTaxCategory').AsInteger;
cdsItemTaxes.FieldByName('TaxPercentage').AsFloat := FieldByName('TaxPercentage').AsFloat;
cdsItemTaxes.FieldByName('TaxValue').AsCurrency := FieldByName('TaxValue').AsCurrency;
cdsItemTaxes.FieldByName('Debit').AsBoolean := FieldByName('Debit').AsBoolean;
cdsItemTaxes.FieldByName('Formula').AsString := FieldByName('Formula').AsString;
cdsItemTaxes.Post;
Next;
end;
finally
Close;
end;
end;
procedure TFrmPurchaseCalcFreight.OpenItemTax;
begin
with cdsItemTaxes do
if not Active then
begin
CreateDataSet;
Open;
end;
end;
procedure TFrmPurchaseCalcFreight.edtFreightKeyPress(Sender: TObject;
var Key: Char);
begin
inherited;
Key := ValidatePositiveCurrency(Key);
end;
procedure TFrmPurchaseCalcFreight.btnApplyClick(Sender: TObject);
begin
inherited;
ApplyValues;
end;
procedure TFrmPurchaseCalcFreight.ApplyValues;
var
Freight,
ItemFreight : Currency;
OtherCost,
ItemOtherCost : Currency;
Discount,
ItemDiscount,
ItemDiscountTotal : Currency;
NewCost : Currency;
NewSale,
NewMSRP : Currency;
begin
Freight := MyStrToMoney(edtFreight.Text);
OtherCost := MyStrToMoney(edtOtherCost.Text);
Discount := MyStrToMoney(edtDiscount.Text);
ItemFreight := 0;
ItemOtherCost := 0;
ItemDiscount := 0;
ItemDiscountTotal := 0;
with cdsPurchaseItem do
try
DisableControls;
First;
while not EOF do
begin
Edit;
if Freight = 0 then
FieldByName('Freight').AsCurrency := 0
else
begin
ItemFreight := MyRound(((Freight / FPurchaseSubTotal) * FieldByName('CostPrice').AsCurrency),2);
FieldByName('Freight').AsCurrency := ItemFreight;
end;
if OtherCost = 0 then
FieldByName('OtherCost').AsCurrency := 0
else
begin
ItemOtherCost := MyRound(((OtherCost / FPurchaseSubTotal) * FieldByName('CostPrice').AsCurrency),2);
FieldByName('OtherCost').AsCurrency := ItemOtherCost;
end;
//Calculo de desconto sobre os items
if Discount = 0 then
FieldByName('Discount').AsCurrency := 0
else
begin
ItemDiscount := MyRound(((Discount / FPurchaseSubTotal) * FieldByName('CostPrice').AsCurrency),2);
ItemDiscountTotal := ItemDiscountTotal + ItemDiscount;
//Ajustar o ultimo registro arredondando o desconto para bater com desconto total
if (RecNo = RecordCount) then
if (ItemDiscountTotal < Discount) then
ItemDiscount := ItemDiscount + ABS(ItemDiscountTotal - Discount)
else if (ItemDiscountTotal > Discount) then
ItemDiscount := ItemDiscount - ABS(ItemDiscountTotal - Discount);
FieldByName('Discount').AsCurrency := ItemDiscount;
end;
FieldByName('Taxes').AsCurrency := UpdateItemTax(FieldByName('IDPurchaseItem').AsInteger,
FieldByName('CostPrice').AsCurrency,
ItemFreight,
ItemOtherCost,
ItemDiscount);
NewCost := FieldByName('CostPrice').AsCurrency + ItemFreight + ItemOtherCost + FieldByName('Taxes').AsCurrency - ItemDiscount;
FieldByName('NewCostPrice').AsCurrency := MyRound(NewCost / FieldByName('Qty').AsFloat, 2);
if FCalcSalePrice then
begin
NewSale := CalcNewSalePrice(FieldByName('NewCostPrice').AsCurrency,
FieldByName('IDModel').AsInteger,
FieldByName('IDCategory').AsInteger,
FieldByName('IDSubCategory').AsInteger,
FieldByName('IDGroup').AsInteger);
if NewSale <> 0 then
FieldByName('NewSalePrice').AsCurrency := NewSale;
NewMSRP := CalcNewMSRP(FieldByName('NewCostPrice').AsCurrency,
FieldByName('IDCategory').AsInteger,
FieldByName('IDSubCategory').AsInteger,
FieldByName('IDGroup').AsInteger);
if NewMSRP <> 0 then
FieldByName('NewMSRP').AsCurrency := NewMSRP;
end;
Post;
Next;
end;
finally
First;
EnableControls;
end;
end;
function TFrmPurchaseCalcFreight.UpdateItemTax(IDItem : Integer; CostPrice, Freight,
OtherCost, Discount : Currency): Currency;
var
i: Integer;
TaxList: TList;
ItemTax: TItemTax;
begin
Result := 0;
with cdsItemTaxes do
try
Filtered := False;
Filter := 'IDPurchaseItem = ' + IntToStr(IDItem);
Filtered := True;
First;
TaxList := TList.Create;
while not EOF do
begin
ItemTax := TItemTax.Create;
ItemTax.IDPurchaseItemTax := FieldByName('IDPurchaseItemTax').AsInteger;
ItemTax.IDPurchaseItem := IDItem;
ItemTax.TaxPercentage := FieldByName('TaxPercentage').AsFloat;
ItemTax.TaxValue := FieldByName('TaxValue').AsCurrency;
ItemTax.IDTaxCategory := FieldByName('IDTaxCategory').AsInteger;
ItemTax.Debit := FieldByName('Debit').AsBoolean;
ItemTax.Formula := FieldByName('Formula').AsString;
ItemTax.Cost := CostPrice;
ItemTax.Freight := Freight;
ItemTax.Other := OtherCost;
ItemTax.Discount := Discount;
TaxList.Add(ItemTax);
Next;
end;
DMCalcTax.CalculateTaxList(TaxList);
for i := 0 to Pred(TaxList.Count) do
begin
if Locate('IDPurchaseItemTax', TItemTax(TaxList[i]).IDPurchaseItemTax, []) then
begin
ItemTax := TItemTax(TaxList[i]);
Result := Result + ItemTax.TaxValue;
Edit;
FieldByName('TaxValue').AsCurrency := MyRound(ItemTax.TaxValue, 2);
Post;
FreeAndNil(ItemTax);
end;
end;
finally
Filtered := False;
Filter := '';
TaxList.Clear;
FreeAndNil(TaxList);
end;
end;
function TFrmPurchaseCalcFreight.CalcNewMSRP(
CostPrice: Currency; IDCat, IDSubCat, IDGroup : Integer): Currency;
begin
Result := DM.FDMCalcPrice.CalcMSRPPrice(IDCat, IDSubCat, IDGroup, CostPrice);
if Result = CostPrice then
Result := 0;
end;
function TFrmPurchaseCalcFreight.CalcNewSalePrice(
CostPrice: Currency; IDModel, IDCat, IDSubCat, IDGroup : Integer): Currency;
begin
Result := DM.FDMCalcPrice.CalcSalePrice(IDModel, IDCat, IDSubCat, IDGroup, CostPrice);
if Result = CostPrice then
Result := 0;
end;
procedure TFrmPurchaseCalcFreight.FormCreate(Sender: TObject);
begin
inherited;
DMCalcTax := TDMCalcTax.Create(Self);
DMCalcTax.ADODBConnect := DM.ADODBConnect;
end;
procedure TFrmPurchaseCalcFreight.FormShow(Sender: TObject);
begin
inherited;
grdPurchaseItemDBNewSalePrice.Visible := FCalcSalePrice;
grdPurchaseItemDBNewMSRP.Visible := FCalcSalePrice;
end;
procedure TFrmPurchaseCalcFreight.SaveValues;
var
sSQL : String;
begin
try
DM.ADODBConnect.BeginTrans;
with cdsPurchaseItem do
try
DisableControls;
First;
while not EOF do
begin
cmdUpdatePurchaseItem.Parameters.ParamByName('IDPurchaseItem').Value := FieldByName('IDPurchaseItem').AsInteger;
cmdUpdatePurchaseItem.Parameters.ParamByName('FreightCost').Value := FieldByName('Freight').AsCurrency;
cmdUpdatePurchaseItem.Parameters.ParamByName('OtherCost').Value := FieldByName('OtherCost').AsCurrency;
cmdUpdatePurchaseItem.Parameters.ParamByName('NewCostPrice').Value := FieldByName('NewCostPrice').AsCurrency;
cmdUpdatePurchaseItem.Parameters.ParamByName('Discount').Value := FieldByName('Discount').AsCurrency;
if FCalcSalePrice then
begin
if FieldByName('NewSalePrice').AsCurrency <> 0 then
cmdUpdatePurchaseItem.Parameters.ParamByName('NewSalePrice').Value := FieldByName('NewSalePrice').AsCurrency;
if FieldByName('NewMSRP').AsCurrency <> 0 then
cmdUpdatePurchaseItem.Parameters.ParamByName('NewSuggRetail').Value := FieldByName('NewMSRP').AsCurrency;
end
else
begin
cmdUpdatePurchaseItem.Parameters.ParamByName('NewSalePrice').Value := NULL;
cmdUpdatePurchaseItem.Parameters.ParamByName('NewSuggRetail').Value := NULL;
end;
cmdUpdatePurchaseItem.Execute;
Next;
end;
finally
EnableControls;
end;
with cdsItemTaxes do
begin
First;
while not EOF do
begin
cdmItemTax.Parameters.ParamByName('TaxValue').Value := FieldByName('TaxValue').AsCurrency;
cdmItemTax.Parameters.ParamByName('IDPurchaseItemTax').Value := FieldByName('IDPurchaseItemTax').AsCurrency;
cdmItemTax.Execute;
Next;
end;
end;
DM.RunSQL('EXEC sp_Purchase_AtuPurchaseSubTotal ' + IntToStr(FIDPurchase) + ', ' + IntToStr(Byte(DM.fSystem.SrvParam[PARAM_TAX_IN_COSTPRICE])));
DM.ADODBConnect.CommitTrans;
except
on E: Exception do
begin
DM.ADODBConnect.RollbackTrans;
DM.SetError(CRITICAL_ERROR, 'TFrmPurchaseCalcFreight.SaveValues', E.Message);
MsgBox(E.Message, vbCritical + vbOKOnly);
end;
end;
end;
end.
|
unit Mail4Delphi.Default;
interface
uses Mail4Delphi.Intf, System.Classes, System.SysUtils, IdSMTP, IdSSLOpenSSL, IdMessage, IdText, IdAttachmentFile,
IdExplicitTLSClientServerBase, System.Variants;
type
TMail = class(TInterfacedObject, IMail)
private
FIdSSLIOHandlerSocket: TIdSSLIOHandlerSocketOpenSSL;
FIdSMTP: TIdSMTP;
FIdMessage: TIdMessage;
FIdText: TIdText;
FSSL: Boolean;
FAuth: Boolean;
FReceiptRecipient: Boolean;
function SetUpEmail: Boolean;
protected
property IdSSLIOHandlerSocket: TIdSSLIOHandlerSocketOpenSSL read FIdSSLIOHandlerSocket write FIdSSLIOHandlerSocket;
property IdSMTP: TIdSMTP read FIdSMTP write FIdSMTP;
property IdMessage: TIdMessage read FIdMessage write FIdMessage;
property IdText: TIdText read FIdText write FIdText;
property SetSSL: Boolean read FSSL write FSSL;
property SetAuth: Boolean read FAuth write FAuth;
property SetReceiptRecipient: Boolean read FReceiptRecipient write FReceiptRecipient;
public
function AddTo(const AMail: string; const AName: string = ''): IMail;
function AddFrom(const AMail: string; const AName: string = ''): IMail;
function AddSubject(const ASubject: string): IMail;
function AddReplyTo(const AMail: string; const AName: string = ''): IMail;
function AddCC(const AMail: string; const AName: string = ''): IMail;
function AddBCC(const AMail: string; const AName: string = ''): IMail;
function AddBody(const ABody: string): IMail;
function Host(const AHost: string): IMail;
function UserName(const AUserName: string): IMail;
function Password(const APassword: string): IMail;
function Port(const APort: Integer): IMail;
function ReceiptRecipient(const AValue: Boolean): IMail;
function AddAttachment(const AFile: string): IMail;
function Auth(const AValue: Boolean): IMail;
function SSL(const AValue: Boolean): IMail;
function Clear: IMail;
function SendMail: Boolean;
class function New: IMail;
constructor Create;
destructor Destroy; override;
end;
implementation
function TMail.AddFrom(const AMail: string; const AName: string = ''): IMail;
begin
if AMail.Trim.IsEmpty then
begin
raise Exception.Create('E-mail do remetente não informado!');
Exit;
end;
FIdMessage.From.Address := AMail;
if not AName.Trim.IsEmpty then
FIdMessage.From.Name := AName;
Result := Self;
end;
function TMail.AddBCC(const AMail: string; const AName: string = ''): IMail;
begin
if AMail.Trim.IsEmpty then
begin
raise Exception.Create('E-mail não informado para cópia oculta!');
Exit;
end;
FIdMessage.BccList.Add.Text := AName + ' ' + AMail;
Result := Self;
end;
function TMail.AddAttachment(const AFile: string): IMail;
var
LFile: TIdAttachmentFile;
begin
LFile := TIdAttachmentFile.Create(IdMessage.MessageParts, AFile);
LFile.ContentDescription := 'Arquivo Anexo: ' + ExtractFileName(AFile);
Result := Self;
end;
function TMail.Auth(const AValue: Boolean): IMail;
begin
FAuth := AValue;
Result := Self;
end;
function TMail.AddBody(const ABody: string): IMail;
begin
FIdText.Body.Add(ABody);
Result := Self;
end;
function TMail.Host(const AHost: string): IMail;
begin
if AHost.Trim.IsEmpty then
raise Exception.Create('Servidor não informado!');
FIdSMTP.Host := AHost;
Result := Self;
end;
function TMail.Password(const APassword: string): IMail;
begin
if APassword.Trim.IsEmpty then
raise Exception.Create('Senha não informado!');
FIdSMTP.Password := APassword;
Result := Self;
end;
function TMail.Port(const APort: Integer): IMail;
begin
if VarIsNull(APort) then
raise Exception.Create('Senha não informado!');
FIdSMTP.Port := APort;
Result := Self;
end;
function TMail.ReceiptRecipient(const AValue: Boolean): IMail;
begin
FReceiptRecipient := AValue;
Result := Self;
end;
function TMail.SSL(const AValue: Boolean): IMail;
begin
FSSL := AValue;
Result := Self;
end;
function TMail.AddCC(const AMail: string; const AName: string = ''): IMail;
begin
if AMail.Trim.IsEmpty then
begin
raise Exception.Create('E-mail não informado para cópia!');
Exit;
end;
FIdMessage.CCList.Add.Text := AName + ' ' + AMail;
Result := Self;
end;
function TMail.AddReplyTo(const AMail: string; const AName: string = ''): IMail;
begin
if AMail.Trim.IsEmpty then
begin
raise Exception.Create('E-mail para resposta não informado!');
Exit;
end;
FIdMessage.ReplyTo.Add.Text := AName + ' ' + AMail;
Result := Self;
end;
function TMail.AddSubject(const ASubject: string): IMail;
begin
if ASubject.Trim.IsEmpty then
raise Exception.Create('Assunto não informado!');
FIdMessage.Subject := ASubject;
Result := Self;
end;
function TMail.AddTo(const AMail: string; const AName: string = ''): IMail;
begin
if AMail.Trim.IsEmpty then
raise Exception.Create('E-mail do destinatário não informado!')
else
FIdMessage.Recipients.Add.Text := AName + ' ' + AMail;
Result := Self;
end;
function TMail.Clear: IMail;
begin
FIdMessage.Clear;
FIdText.Body.Clear;
Result := Self;
end;
constructor TMail.Create;
begin
FIdSSLIOHandlerSocket := TIdSSLIOHandlerSocketOpenSSL.Create(nil);
FIdSMTP := TIdSMTP.Create(nil);
FIdMessage := TIdMessage.Create(nil);
FIdMessage.Encoding := meMIME;
FIdMessage.ConvertPreamble := True;
FIdMessage.Priority := mpNormal;
FIdMessage.ContentType := 'multipart/mixed';
FIdMessage.CharSet := 'utf-8';
FIdMessage.Date := Now;
FIdText := TIdText.Create(IdMessage.MessageParts);
FIdText.ContentType := 'text/html; text/plain;';
FIdText.CharSet := 'utf-8';
FSSL := False;
FAuth := False;
FReceiptRecipient := False;
end;
destructor TMail.Destroy;
begin
FreeAndNil(FIdMessage);
FreeAndNil(FIdSSLIOHandlerSocket);
FreeAndNil(FIdSMTP);
end;
class function TMail.New: IMail;
begin
Result := TMail.Create;
end;
function TMail.SendMail: Boolean;
begin
if not SetUpEmail then
begin
raise Exception.Create('Dados incompletos!');
Exit(False);
end;
FIdSSLIOHandlerSocket.SSLOptions.Method := sslvTLSv1_2;
FIdSSLIOHandlerSocket.SSLOptions.Mode := sslmUnassigned;
FIdSMTP.IOHandler := IdSSLIOHandlerSocket;
FIdSMTP.UseTLS := utUseExplicitTLS;
if FSSL then
begin
FIdSSLIOHandlerSocket.SSLOptions.Mode := sslmClient;
FIdSMTP.UseTLS := utUseImplicitTLS;
end;
FIdSMTP.AuthType := satNone;
if FAuth then
FIdSMTP.AuthType := satDefault;
if FReceiptRecipient then
FIdMessage.ReceiptRecipient.Text := FIdMessage.From.Name + ' ' + FIdMessage.From.Address;
try
FIdSMTP.Connect;
FIdSMTP.Authenticate;
except
on E: Exception do
begin
raise Exception.Create('Erro na conexão ou autenticação: ' + E.Message);
Exit(False);
end;
end;
try
FIdSMTP.Send(IdMessage);
FIdSMTP.Disconnect;
UnLoadOpenSSLLibrary;
Result := True;
except
on E: Exception do
raise Exception.Create('Erro ao enviar a mensagem: ' + E.Message);
end;
end;
function TMail.SetUpEmail: Boolean;
begin
Result := False;
if not(FIdMessage.Recipients.Count < 1) then
if not(FIdSMTP.Host.Trim.IsEmpty) then
if not(FIdSMTP.UserName.Trim.IsEmpty) then
if not(FIdSMTP.Password.Trim.IsEmpty) then
Result := not(VarIsNull(FIdSMTP.Port));
end;
function TMail.UserName(const AUserName: string): IMail;
begin
if AUserName.Trim.IsEmpty then
raise Exception.Create('Usuário não informado!');
FIdSMTP.UserName := AUserName;
Result := Self;
end;
end.
|
{*******************************************************************************
Title: T2Ti ERP
Description: VO relacionado à tabela [PONTO_FECHAMENTO_JORNADA]
The MIT License
Copyright: Copyright (C) 2016 T2Ti.COM
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.
The author may be contacted at:
t2ti.com@gmail.com
@author Albert Eije (t2ti.com@gmail.com)
@version 2.0
*******************************************************************************}
unit PontoFechamentoJornadaVO;
{$mode objfpc}{$H+}
interface
uses
VO, Classes, SysUtils, FGL;
type
TPontoFechamentoJornadaVO = class(TVO)
private
FID: Integer;
FID_PONTO_CLASSIFICACAO_JORNADA: Integer;
FID_COLABORADOR: Integer;
FDATA_FECHAMENTO: TDateTime;
FDIA_SEMANA: String;
FCODIGO_HORARIO: String;
FCARGA_HORARIA_ESPERADA: String;
FCARGA_HORARIA_DIURNA: String;
FCARGA_HORARIA_NOTURNA: String;
FCARGA_HORARIA_TOTAL: String;
FENTRADA01: String;
FSAIDA01: String;
FENTRADA02: String;
FSAIDA02: String;
FENTRADA03: String;
FSAIDA03: String;
FENTRADA04: String;
FSAIDA04: String;
FENTRADA05: String;
FSAIDA05: String;
FHORA_INICIO_JORNADA: String;
FHORA_FIM_JORNADA: String;
FHORA_EXTRA01: String;
FPERCENTUAL_HORA_EXTRA01: Extended;
FMODALIDADE_HORA_EXTRA01: String;
FHORA_EXTRA02: String;
FPERCENTUAL_HORA_EXTRA02: Extended;
FMODALIDADE_HORA_EXTRA02: String;
FHORA_EXTRA03: String;
FPERCENTUAL_HORA_EXTRA03: Extended;
FMODALIDADE_HORA_EXTRA03: String;
FHORA_EXTRA04: String;
FPERCENTUAL_HORA_EXTRA04: Extended;
FMODALIDADE_HORA_EXTRA04: String;
FFALTA_ATRASO: String;
FCOMPENSAR: String;
FBANCO_HORAS: String;
FOBSERVACAO: String;
//Transientes
published
property Id: Integer read FID write FID;
property IdPontoClassificacaoJornada: Integer read FID_PONTO_CLASSIFICACAO_JORNADA write FID_PONTO_CLASSIFICACAO_JORNADA;
property IdColaborador: Integer read FID_COLABORADOR write FID_COLABORADOR;
property DataFechamento: TDateTime read FDATA_FECHAMENTO write FDATA_FECHAMENTO;
property DiaSemana: String read FDIA_SEMANA write FDIA_SEMANA;
property CodigoHorario: String read FCODIGO_HORARIO write FCODIGO_HORARIO;
property CargaHorariaEsperada: String read FCARGA_HORARIA_ESPERADA write FCARGA_HORARIA_ESPERADA;
property CargaHorariaDiurna: String read FCARGA_HORARIA_DIURNA write FCARGA_HORARIA_DIURNA;
property CargaHorariaNoturna: String read FCARGA_HORARIA_NOTURNA write FCARGA_HORARIA_NOTURNA;
property CargaHorariaTotal: String read FCARGA_HORARIA_TOTAL write FCARGA_HORARIA_TOTAL;
property Entrada01: String read FENTRADA01 write FENTRADA01;
property Saida01: String read FSAIDA01 write FSAIDA01;
property Entrada02: String read FENTRADA02 write FENTRADA02;
property Saida02: String read FSAIDA02 write FSAIDA02;
property Entrada03: String read FENTRADA03 write FENTRADA03;
property Saida03: String read FSAIDA03 write FSAIDA03;
property Entrada04: String read FENTRADA04 write FENTRADA04;
property Saida04: String read FSAIDA04 write FSAIDA04;
property Entrada05: String read FENTRADA05 write FENTRADA05;
property Saida05: String read FSAIDA05 write FSAIDA05;
property HoraInicioJornada: String read FHORA_INICIO_JORNADA write FHORA_INICIO_JORNADA;
property HoraFimJornada: String read FHORA_FIM_JORNADA write FHORA_FIM_JORNADA;
property HoraExtra01: String read FHORA_EXTRA01 write FHORA_EXTRA01;
property PercentualHoraExtra01: Extended read FPERCENTUAL_HORA_EXTRA01 write FPERCENTUAL_HORA_EXTRA01;
property ModalidadeHoraExtra01: String read FMODALIDADE_HORA_EXTRA01 write FMODALIDADE_HORA_EXTRA01;
property HoraExtra02: String read FHORA_EXTRA02 write FHORA_EXTRA02;
property PercentualHoraExtra02: Extended read FPERCENTUAL_HORA_EXTRA02 write FPERCENTUAL_HORA_EXTRA02;
property ModalidadeHoraExtra02: String read FMODALIDADE_HORA_EXTRA02 write FMODALIDADE_HORA_EXTRA02;
property HoraExtra03: String read FHORA_EXTRA03 write FHORA_EXTRA03;
property PercentualHoraExtra03: Extended read FPERCENTUAL_HORA_EXTRA03 write FPERCENTUAL_HORA_EXTRA03;
property ModalidadeHoraExtra03: String read FMODALIDADE_HORA_EXTRA03 write FMODALIDADE_HORA_EXTRA03;
property HoraExtra04: String read FHORA_EXTRA04 write FHORA_EXTRA04;
property PercentualHoraExtra04: Extended read FPERCENTUAL_HORA_EXTRA04 write FPERCENTUAL_HORA_EXTRA04;
property ModalidadeHoraExtra04: String read FMODALIDADE_HORA_EXTRA04 write FMODALIDADE_HORA_EXTRA04;
property FaltaAtraso: String read FFALTA_ATRASO write FFALTA_ATRASO;
property Compensar: String read FCOMPENSAR write FCOMPENSAR;
property BancoHoras: String read FBANCO_HORAS write FBANCO_HORAS;
property Observacao: String read FOBSERVACAO write FOBSERVACAO;
//Transientes
end;
TListaPontoFechamentoJornadaVO = specialize TFPGObjectList<TPontoFechamentoJornadaVO>;
implementation
initialization
Classes.RegisterClass(TPontoFechamentoJornadaVO);
finalization
Classes.UnRegisterClass(TPontoFechamentoJornadaVO);
end.
|
(*
* Main server source.
*
* Overview of DNS protocol: http://www.zytrax.com/books/dns/ch15/
*)
unit DNSServer;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, StrUtils,
syncobjs,
synautil,
blcksock,
synsock,
DNSProtocol;
type
(*
* Blocksocket settings
*)
TUDPBlockSocketAttributes = record
IpAddress: string;
Port: string;
end;
(*
* Server status codes
*)
TDNSServerStatus = (
dnssStop,
dnssNormal,
dnssError,
dnssFatal,
dnssFailBind
);
(*
* Servers main listener thread.
* This starts listening on the requested port and IP and
* responds to DNS requests that come in.
*)
TListenerThread = class(TThread)
private
// Socket that listens
ListenerSocket: TUDPBlockSocket;
RequestStream: TMemoryStream;
ResponseStream: TMemoryStream;
protected
// Main server loop
procedure Execute; override;
// Validate request before match making
function ValidateRequest( Request: TStream ): boolean;
// Log server messages
procedure LogMessage( message:string );
// Process request data
function ProcessRequest( Request: Tstream ): TMemoryStream;
public
// Socket attributes
Attributes: TUDPBlockSocketAttributes;
// Addresses for maching
AddressList: TStringList;
// Create thread
constructor Create( IpAddress, Port:string );
// Close thread
destructor Destroy; override;
end;
Var
Tmp: String;
ServerStatus: TDNSServerStatus;
implementation
(*
* Validate DNS request
*)
function TListenerThread.ValidateRequest( Request: TStream ): boolean;
begin
// Check size (Header is 12 bytes)
if Request.size < 12 then result := false;
// Do validation
result := true;
end;
(*
* Log DNS server messages
*)
procedure TListenerThread.LogMessage( message:string );
begin
Writeln(StdErr, message);
// TODO: Maybe make log tab for the UI
end;
(*
* Process incoming stream of data.
*
*)
function TListenerThread.ProcessRequest( Request: TStream ): TMemoryStream;
var
Header: TDNSRequestHeader;
Question: TDNSRequestQuestion;
Answer: TDNSRequestAnswer;
AnswerSize: Integer;
Qb: Char;
TmpStr: Ansistring;
begin
//
// Process request question
//
try
//LogMessage('Received '+intTostr(Request.size)+' bytes of data.');
// Parse header
Header := DNSProtocol.getRequestHeader(Request);
// Parse question
Question := DNSProtocol.getRequestQuestion(Request);
except
On E: Exception do
LogMessage('Unable to process request: ' + E.Message);
end;
//
// Search for match and process the response
//
try
Answer := DNSProtocol.getRequestAnswer(Header, Question, AddressList);
except
On E: Exception do
LogMessage('Unable to process response: ' + E.Message);
end;
// Put together the response
Result := TMemoryStream.Create();
// Write header
Result.Write(Answer.Header, SizeOf(Answer.Header));
//Result.Write(Answer.QName, Length(Answer.QName));
SetString(TmpStr, PAnsiChar(@Answer.Question.QName[0]), Length(Answer.Question.QName));
//Result.WriteAnsiString(TmpStr);
// write dynamic name part
for Qb in TmpStr do
Result.WriteByte(ord(Qb));
// write rest of the answer
Result.Write(Answer.Question.QType, SizeOf(Answer.Question.QType));
Result.Write(Answer.Question.QClass, SizeOf(Answer.Question.QClass));
Result.Write(Answer.QNamePtr, SizeOf(Answer.QNamePtr));
Result.Write(Answer.QType, SizeOf(Answer.QType));
Result.Write(Answer.QClass, SizeOf(Answer.QClass));
Result.Write(Answer.TTL, SizeOf(Answer.TTL));
Result.Write(Answer.RLength, SizeOf(Answer.RLength));
Result.Write(Answer.RData, SizeOf(Answer.RData))
{ //Result.Write(Answer.RData, Length(Answer.RData));
for c in Answer.RData do
Result.WriteByte(ord(c));
}
end;
(*
* Main server loop
* Listens on the connection
*)
procedure TListenerThread.Execute;
var
f : TFileStream;
begin
try
with ListenerSocket do
begin
// Create socket
CreateSocket;
// Socket family
Family := SF_IP4;
// Test for success
if LastError = 0 then LogMessage('Socket successfully initialized')
else Raise Exception.Create('An error initializing socket: '+GetErrorDescEx);
// Bind to IP and port
Bind(Attributes.IpAddress, Attributes.Port);
// Test for success
if LastError = 0 then LogMessage('Binded on port ' + Attributes.Port)
else Raise Exception.Create('Bind error: ' + GetErrorDescEx);
// Start listening and the main server loop
Listen;
RequestStream := TMemoryStream.Create;
ResponseStream := TMemoryStream.Create();
ServerStatus := dnssNormal;
while not Terminated do begin
if CanRead(10) then begin
// Fill the request stream.
RecvStreamRaw(RequestStream, 1000);
// Process and reply
if (ValidateRequest(RequestStream)) then begin
ResponseStream := ProcessRequest(RequestStream);
//ListenerSocket.SendMaxChunk := 100;
ResponseStream.seek(0, soBeginning);
SendStreamRaw(ResponseStream);
// Debug
//ResponseStream.seek(0, soBeginning);
//f := TFileStream.Create('response.txt', fmCreate, 777);
//f.CopyFrom(ResponseStream, ResponseStream.Size);
//f.Free;
end;
// Clear for next read
RequestStream.Clear;
end;
//sleep(100);
end;
end;
except
On E: Exception do begin
LogMessage('Server exception: ' + E.Message);
ServerStatus := dnssFatal;
Terminate;
end;
end;
end;
(*
* Start server
*)
constructor TListenerThread.Create( IpAddress, Port:string );
begin
try
FreeOnTerminate := True;
ListenerSocket := TUDPBlockSocket.Create;
// Setup Server
Attributes.IpAddress := IpAddress;
Attributes.Port := Port;
if ListenerSocket.LastError <> 0 then raise Exception.Create('Listener creation error: '+ListenerSocket.GetErrorDescEx)
else LogMessage('Server created');
// TODO: Start log stream
except
On E: Exception do
LogMessage('Server create exception:' + E.Message);
end;
inherited Create(True);
end;
(*
* Destroy server
*)
destructor TListenerThread.Destroy;
begin
try
ListenerSocket.Free;
if ListenerSocket.LastError = 0 then LogMessage('Server destroyed')
else raise Exception.Create('Listener deleting error: '+ListenerSocket.GetErrorDescEx);
RequestStream.Free;
ResponseStream.Free;
// Free memmory
// TODO:
except
On E: Exception do
LogMessage('Server exception: ' + E.Message);
end;
inherited;
end;
end.
|
namespace org.me.deviceinfo;
//Sample app by Brian Long (http://blong.com)
{
This example demonstrates querying an Android device for various metrics and data
}
interface
uses
java.util,
android.app,
android.content,
android.content.res,
android.os,
android.view,
android.util,
android.widget;
//Queries various data and metrics from the device
//This activity uses a number of rows with similar layout for the information
//In this case they are created dynamically and added to an empty parent,
//keeping a list of references to the TextViews inside.
//The layout is an OS-defined one.
type
InfoActivity = public class(Activity)
private
infoItems: ArrayList<TextView>;
const
OS_VERSION = 0;
DEVICE_MANUFACTURER = 1;
DEVICE_MODEL = 2;
DEVICE_BRAND = 3;
DEVICE_PRODUCT = 4;
DEVICE_HARDWARE = 5;
DEVICE_DISPLAY = 6;
DEVICE_CPU_ABI = 7;
DEVICE_BOOTLOADER = 8;
SCREEN_RESOLUTION = 9;
SCREEN_DENSITY = 10;
public
method onCreate(savedInstanceState: Bundle); override;
method onResume; override;
end;
implementation
method InfoActivity.onCreate(savedInstanceState: Bundle);
begin
inherited;
ContentView := R.layout.info;
var listView := LinearLayout(findViewById(R.id.list));
//Set up an array of string ids
var infoLabels: array of Integer := [R.string.os_version, R.string.device_manufacturer,
R.string.device_model, R.string.device_brand, R.string.device_product,
R.string.device_hardware, R.string.device_build_id, R.string.device_cpu_abi,
R.string.device_bootloader, R.string.screen_resolution, R.string.screen_density];
//Empty list of TextViews
infoItems := new ArrayList<TextView>();
//Now loop through the string id array, creating a pre-defined 2 item list
//view item for each one, setting the first item (TextView) to the string
//and adding the second item (TextView) to the listview
for I: Integer := 0 to infoLabels.length - 1 do
begin
var listItem := LayoutInflater.inflate(Android.R.layout.simple_list_item_2, nil);
var infoLabel := TextView(listItem.findViewById(Android.R.id.text1));
infoLabel.Text := String[infoLabels[I]];
infoItems.add(TextView(listItem.findViewById(Android.R.id.text2)));
listView.addView(listItem)
end
end;
//When activity displays, populate all the list items with data about the device
method InfoActivity.onResume;
begin
inherited;
//This is a use of a case expression (as opposed to a case statement)
var releaseName := case Build.VERSION.SDK_INT of
Build.VERSION_CODES.BASE: 'Android 1 aka Base, October 2008';
Build.VERSION_CODES.BASE_1_1: 'Android 1.1 aka Base 1 1, February 2009';
Build.VERSION_CODES.CUPCAKE: 'Android 1.5 aka Cupcake, May 2009';
Build.VERSION_CODES.DONUT: 'Android 1.6 aka Donut, September 2009';
Build.VERSION_CODES.ECLAIR: 'Android 2.0 aka Eclair, November 2009';
Build.VERSION_CODES.ECLAIR_0_1: 'Android 2.0.1 aka Eclair 0 1, December 2009';
Build.VERSION_CODES.ECLAIR_MR1: 'Android 2.1 aka Eclair MR 1, January 2010';
Build.VERSION_CODES.FROYO: 'Android 2.2 aka FroYo, June 2010';
Build.VERSION_CODES.GINGERBREAD: 'Android 2.3 aka GingerBread, November 2010';
Build.VERSION_CODES.GINGERBREAD_MR1: 'Android 2.3.3 aka GingerBread MR 1, February 2011';
Build.VERSION_CODES.HONEYCOMB: 'Android 3.0 aka Honeycomb, February 2011';
Build.VERSION_CODES.HONEYCOMB_MR1: 'Android 3.1 aka Honeycomb MR1, May 2011';
Build.VERSION_CODES.HONEYCOMB_MR2: 'Android 3.2 aka Honeycomb MR2, June 2011';
Build.VERSION_CODES.CUR_DEVELOPMENT: 'Current development build';
else 'Unknown version';
end;
var codeName := iif(Build.VERSION.CODENAME = 'REL', 'release build', 'codename ' + Build.VERSION.CODENAME);
infoItems[OS_VERSION].Text := WideString.format('Version %s build %s - %s%n%s', Build.VERSION.RELEASE, Build.VERSION.INCREMENTAL, codeName, releaseName);
infoItems[DEVICE_MANUFACTURER].Text := WideString.format('%s', Build.MANUFACTURER);
infoItems[DEVICE_MODEL].Text := WideString.format('%s', Build.MODEL);
infoItems[DEVICE_BRAND].Text := WideString.format('%s', Build.BRAND);
infoItems[DEVICE_PRODUCT].Text := WideString.format('%s', Build.PRODUCT);
infoItems[DEVICE_HARDWARE].Text := WideString.format('%s', Build.HARDWARE);
infoItems[DEVICE_DISPLAY].Text := WideString.format('%s', Build.DISPLAY);
infoItems[DEVICE_CPU_ABI].Text := WideString.format('%s', Build.CPU_ABI);
infoItems[DEVICE_BOOTLOADER].Text := WideString.format('%s', Build.BOOTLOADER);
var config := Resources.Configuration;
var screenSize := case config.screenLayout and Configuration.SCREENLAYOUT_SIZE_MASK of
Configuration.SCREENLAYOUT_SIZE_SMALL: 'small';
Configuration.SCREENLAYOUT_SIZE_NORMAL: 'normal';
Configuration.SCREENLAYOUT_SIZE_LARGE: 'large';
Configuration.SCREENLAYOUT_SIZE_XLARGE: 'extra large';
else 'undefined'
end + ' screen size';
var sizeName := '';
var dm := Resources.DisplayMetrics;
if dm.densityDpi = DisplayMetrics.DENSITY_LOW then begin
if (dm.widthPixels = 240) and (dm.heightPixels = 320) then sizeName := 'QVGA';
if (dm.widthPixels = 240) and (dm.heightPixels = 400) then sizeName := 'WQVGA400';
if (dm.widthPixels = 240) and (dm.heightPixels = 432) then sizeName := 'WQVGA432'
end
else if dm.densityDpi = DisplayMetrics.DENSITY_MEDIUM then begin
if (dm.widthPixels = 320) and (dm.heightPixels = 480) then sizeName := 'HVGA';
if (dm.widthPixels = 480) and (dm.heightPixels = 800) then sizeName := 'WVGA800';
if (dm.widthPixels = 480) and (dm.heightPixels = 854) then sizeName := 'WVGA854'
end
else if dm.densityDpi = DisplayMetrics.DENSITY_HIGH then begin
if (dm.widthPixels = 480) and (dm.heightPixels = 800) then sizeName := 'WVGA800';
if (dm.widthPixels = 480) and (dm.heightPixels = 854) then sizeName := 'WVGA854'
end
else if dm.densityDpi = DisplayMetrics.DENSITY_XHIGH then begin
if (dm.widthPixels = 1280) and (dm.heightPixels = 800) then sizeName := 'WXGA';
end;
var screenOrientation := case config.orientation of
Configuration.ORIENTATION_LANDSCAPE: 'Landscape';
Configuration.ORIENTATION_PORTRAIT: 'Portrait';
Configuration.ORIENTATION_SQUARE: 'Qquare';
end + ' orientation';
if sizeName <> '' then screenSize := sizeName + ' - ' + screenSize;
infoItems[SCREEN_RESOLUTION].Text := WideString.format('%s%n%s%n%d x %d px%n%.0f x %.0f ppi',
screenSize, screenOrientation, dm.widthPixels, dm.heightPixels, dm.xdpi, dm.ydpi);
var densityStr := case dm.densityDpi of
DisplayMetrics.DENSITY_LOW: 'low density - ldpi';
DisplayMetrics.DENSITY_MEDIUM: 'medium density - mdpi';
DisplayMetrics.DENSITY_HIGH: 'high-density - hdpi';
DisplayMetrics.DENSITY_XHIGH: 'extra-high-density aka xhdpi';
DisplayMetrics.DENSITY_TV: '720p TV';
else 'unknown density'
end;
infoItems[SCREEN_DENSITY].Text := WideString.format(
'Density - %d dpi - %s%nLogical density - %.2f (dip scaling factor)%nFont scaling factor - %.2f',
dm.densityDpi, densityStr, dm.density, dm.scaledDensity)
end;
end. |
//
// Generated by JavaToPas v1.5 20180804 - 083150
////////////////////////////////////////////////////////////////////////////////
unit android.icu.text.Normalizer;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes,
android.icu.text.Normalizer_QuickCheckResult;
type
JNormalizer = interface;
JNormalizerClass = interface(JObjectClass)
['{BE09D6F3-FBD4-45E7-BC16-C5E8A20A7397}']
function _GetCOMPARE_CODE_POINT_ORDER : Integer; cdecl; // A: $19
function _GetCOMPARE_IGNORE_CASE : Integer; cdecl; // A: $19
function _GetFOLD_CASE_DEFAULT : Integer; cdecl; // A: $19
function _GetFOLD_CASE_EXCLUDE_SPECIAL_I : Integer; cdecl; // A: $19
function _GetINPUT_IS_FCD : Integer; cdecl; // A: $19
function _GetMAYBE : JNormalizer_QuickCheckResult; cdecl; // A: $19
function _GetNO : JNormalizer_QuickCheckResult; cdecl; // A: $19
function _GetYES : JNormalizer_QuickCheckResult; cdecl; // A: $19
function compare(char32a : Integer; char32b : Integer; options : Integer) : Integer; cdecl; overload;// (III)I A: $9
function compare(char32a : Integer; str2 : JString; options : Integer) : Integer; cdecl; overload;// (ILjava/lang/String;I)I A: $9
function compare(s1 : JString; s2 : JString; options : Integer) : Integer; cdecl; overload;// (Ljava/lang/String;Ljava/lang/String;I)I A: $9
function compare(s1 : TJavaArray<Char>; s1Start : Integer; s1Limit : Integer; s2 : TJavaArray<Char>; s2Start : Integer; s2Limit : Integer; options : Integer) : Integer; cdecl; overload;// ([CII[CIII)I A: $9
function compare(s1 : TJavaArray<Char>; s2 : TJavaArray<Char>; options : Integer) : Integer; cdecl; overload;// ([C[CI)I A: $9
property COMPARE_CODE_POINT_ORDER : Integer read _GetCOMPARE_CODE_POINT_ORDER;// I A: $19
property COMPARE_IGNORE_CASE : Integer read _GetCOMPARE_IGNORE_CASE; // I A: $19
property FOLD_CASE_DEFAULT : Integer read _GetFOLD_CASE_DEFAULT; // I A: $19
property FOLD_CASE_EXCLUDE_SPECIAL_I : Integer read _GetFOLD_CASE_EXCLUDE_SPECIAL_I;// I A: $19
property INPUT_IS_FCD : Integer read _GetINPUT_IS_FCD; // I A: $19
property MAYBE : JNormalizer_QuickCheckResult read _GetMAYBE; // Landroid/icu/text/Normalizer$QuickCheckResult; A: $19
property NO : JNormalizer_QuickCheckResult read _GetNO; // Landroid/icu/text/Normalizer$QuickCheckResult; A: $19
property YES : JNormalizer_QuickCheckResult read _GetYES; // Landroid/icu/text/Normalizer$QuickCheckResult; A: $19
end;
[JavaSignature('android/icu/text/Normalizer$QuickCheckResult')]
JNormalizer = interface(JObject)
['{07351CB6-CAB9-4C0B-ABF7-56533DF70F1B}']
end;
TJNormalizer = class(TJavaGenericImport<JNormalizerClass, JNormalizer>)
end;
const
TJNormalizerCOMPARE_CODE_POINT_ORDER = 32768;
TJNormalizerCOMPARE_IGNORE_CASE = 65536;
TJNormalizerFOLD_CASE_DEFAULT = 0;
TJNormalizerFOLD_CASE_EXCLUDE_SPECIAL_I = 1;
TJNormalizerINPUT_IS_FCD = 131072;
implementation
end.
|
{..............................................................................}
{ Summary: MillExporter - MMSetupDlg }
{ Setup the default values for a milling machine to be used by MillExporter. }
{ }
{ Written by Marty Hauff }
{ Copyright (c) 2008 by Altium Limited }
{..............................................................................}
Var
MMSetupForm : TMMSetupForm;
TMMSetupForm_IniFileName : TPCBString;
MillModel : string;
{..............................................................................}
procedure TMMSetupForm.TEdit_PosReal_OnKeyPress(Sender: TObject; var Key: Char);
begin
case Key of
// BackSpace, '.', '0'..'9'
8, 46, 48..57 :
begin
if (Key = 46) and (Pos('.', Sender.Text) > 0) then
Key := 0;
end;
else
Key := 0;
end;
end;
procedure TMMSetupForm.TEdit_PosInt_OnKeyPress(Sender: TObject; var Key: Char);
begin
case Key of
// BackSpace, '0'..'9'
8, 48..57 : Key := Key;
else
Key := 0;
end;
end;
{..............................................................................}
{..............................................................................}
procedure TMMSetupForm_SetIniFilename (Filename: TPCBString);
var
IniFile : TIniFile;
begin
TMMSetupForm_IniFilename := Filename;
If (FileExists(TMMSetupForm_IniFilename) = false) then
begin //Create a default file
IniFile := TIniFile.Create(FileName);
IniFile.WriteString('EGX-350','Model','EGX-350');
IniFile.WriteString('EGX-350','Description','Desktop Engraver');
IniFile.WriteString('EGX-350','Manufacturer','Roland');
IniFile.WriteString('EGX-350','CommandSet','RML');
IniFile.WriteString('EGX-350','CutterDiameter','0.25');
IniFile.WriteString('EGX-350','MaxX','305');
IniFile.WriteString('EGX-350','MaxY','230');
IniFile.WriteString('EGX-350','MaxZ','40');
IniFile.WriteString('EGX-350','MinXYSpeed','0.1');
IniFile.WriteString('EGX-350','MaxXYSpeed','60');
IniFile.WriteString('EGX-350','MinZSpeed','0.1');
IniFile.WriteString('EGX-350','MaxZSpeed','30');
IniFile.WriteString('EGX-350','MinSpindleSpeed','5000');
IniFile.WriteString('EGX-350','MaxSpindleSpeed','20000');
IniFile.WriteString('EGX-350','XMargin','5');
IniFile.WriteString('EGX-350','YMargin','5');
IniFile.WriteString('MDX-15','Model','MDX-15');
IniFile.WriteString('MDX-15','Description','Desktop 3D Scanning and Milling Machine');
IniFile.WriteString('MDX-15','Manufacturer','Roland');
IniFile.WriteString('MDX-15','CommandSet','RML');
IniFile.WriteString('MDX-15','CutterDiameter','0.25');
IniFile.WriteString('MDX-15','MaxX','152.4');
IniFile.WriteString('MDX-15','MaxY','101.6');
IniFile.WriteString('MDX-15','MaxZ','60.5');
IniFile.WriteString('MDX-15','MinXYSpeed','0.1');
IniFile.WriteString('MDX-15','MaxXYSpeed','15');
IniFile.WriteString('MDX-15','MinZSpeed','0.1');
IniFile.WriteString('MDX-15','MaxZSpeed','15');
IniFile.WriteString('MDX-15','MinSpindleSpeed','6500');
IniFile.WriteString('MDX-15','MaxSpindleSpeed','6500');
IniFile.WriteString('MDX-15','XMargin','5');
IniFile.WriteString('MDX-15','YMargin','5');
IniFile.WriteString('MDX-20','Model','MDX-20');
IniFile.WriteString('MDX-20','Description','Desktop 3D Scanning and Milling Machine');
IniFile.WriteString('MDX-20','Manufacturer','Roland');
IniFile.WriteString('MDX-20','CommandSet','RML');
IniFile.WriteString('MDX-20','CutterDiameter','0.25');
IniFile.WriteString('MDX-20','MaxX','203.2');
IniFile.WriteString('MDX-20','MaxY','152.4');
IniFile.WriteString('MDX-20','MaxZ','60.5');
IniFile.WriteString('MDX-20','MinXYSpeed','0.1');
IniFile.WriteString('MDX-20','MaxXYSpeed','15');
IniFile.WriteString('MDX-20','MinZSpeed','0.1');
IniFile.WriteString('MDX-20','MaxZSpeed','15');
IniFile.WriteString('MDX-20','MinSpindleSpeed','6500');
IniFile.WriteString('MDX-20','MaxSpindleSpeed','6500');
IniFile.WriteString('MDX-20','XMargin','5');
IniFile.WriteString('MDX-20','YMargin','5');
IniFile.WriteString('MDX-40','Model','MDX-40');
IniFile.WriteString('MDX-40','Description','3D Milling Machine');
IniFile.WriteString('MDX-40','Manufacturer','Roland');
IniFile.WriteString('MDX-40','CommandSet','RML');
IniFile.WriteString('MDX-40','CutterDiameter','0.25');
IniFile.WriteString('MDX-40','MaxX','305');
IniFile.WriteString('MDX-40','MaxY','305');
IniFile.WriteString('MDX-40','MaxZ','105');
IniFile.WriteString('MDX-40','MinXYSpeed','0.1');
IniFile.WriteString('MDX-40','MaxXYSpeed','50');
IniFile.WriteString('MDX-40','MinZSpeed','0.1');
IniFile.WriteString('MDX-40','MaxZSpeed','30');
IniFile.WriteString('MDX-40','MinSpindleSpeed','4500');
IniFile.WriteString('MDX-40','MaxSpindleSpeed','15000');
IniFile.WriteString('MDX-40','XMargin','5');
IniFile.WriteString('MDX-40','YMargin','5');
IniFile.Free;
end;
end;
Procedure TMMSetupForm_ReadIniFileToForm(Name : string);
var
IniFile : TIniFile;
begin
IniFile := TIniFile.Create(TMMSetupForm_IniFilename);
MMSetupForm.Model.Text := IniFile.ReadString(Name,'Model','');
MMSetupForm.Manufacturer.Text := IniFile.ReadString(Name,'Manufacturer','');
MMSetupForm.CommandSet.Text := IniFile.ReadString(Name,'CommandSet','RML');
MMSetupForm.Description.Text := IniFile.ReadString(Name,'Description','');
MMSetupForm.CutterDiameter.Text := IniFile.ReadFloat(Name, 'CutterDiameter',0.25);
MMSetupForm.MaxX.Text := IniFile.ReadFloat(Name,'MaxX',100.0);
MMSetupForm.MaxY.Text := IniFile.ReadFloat(Name,'MaxY',100.0);
MMSetupForm.MaxZ.Text := IniFile.ReadFloat(Name,'MaxZ',10.0);
MMSetupForm.MinXYSpeed.Text := IniFile.ReadFloat(Name,'MinXYSpeed',0.1);
MMSetupForm.MaxXYSpeed.Text := IniFile.ReadFloat(Name,'MaxXYSpeed',10);
MMSetupForm.MinZSpeed.Text := IniFile.ReadFloat(Name,'MinZSpeed',0.1);
MMSetupForm.MaxZSpeed.Text := IniFile.ReadFloat(Name,'MaxZSpeed',10);
MMSetupForm.MinSpindleSpeed.Text := IniFile.ReadInteger(Name,'MinSpindleSpeed',1000);
MMSetupForm.MaxSpindleSpeed.Text := IniFile.ReadInteger(Name,'MaxSpindleSpeed',10000);
MMSetupForm.XMargin.Text := IniFile.ReadFloat(Name,'XMargin',5.0);
MMSetupForm.YMargin.Text := IniFile.ReadFloat(Name,'YMargin',5.0);
IniFile.Free;
End;
Procedure TMMSetupForm_WriteFormToIniFile(MillModel : string);
var
IniFile : TIniFile;
begin
IniFile := TIniFile.Create(TMMSetupForm_IniFilename);
IniFile.WriteString(MillModel,'Model',MMSetupForm.Model.Text);
IniFile.WriteString(MillModel,'CommandSet',MMSetupForm.CommandSet.Text);
IniFile.WriteString(MillModel,'Description',MMSetupForm.Description.Text);
IniFile.WriteFloat(MillModel,'CutterDiameter',MMSetupForm.CutterDiameter.Text);
IniFile.WriteFloat(MillModel,'MaxX',MMSetupForm.MaxX.Text);
IniFile.WriteFloat(MillModel,'MaxY',MMSetupForm.MaxY.Text);
IniFile.WriteFloat(MillModel,'MaxZ',MMSetupForm.MaxZ.Text);
IniFile.WriteFloat(MillModel,'MinXYSpeed',MMSetupForm.MinXYSpeed.Text);
IniFile.WriteFloat(MillModel,'MaxXYSpeed',MMSetupForm.MaxXYSpeed.Text);
IniFile.WriteFloat(MillModel,'MinZSpeed',MMSetupForm.MinZSpeed.Text);
IniFile.WriteFloat(MillModel,'MaxZSpeed',MMSetupForm.MaxZSpeed.Text);
IniFile.WriteInteger(MillModel,'MinSpindleSpeed',MMSetupForm.MinSpindleSpeed.Text);
IniFile.WriteInteger(MillModel,'MaxSpindleSpeed',MMSetupForm.MaxSpindleSpeed.Text);
IniFile.WriteFloat(MillModel, 'XMargin',MMSetupForm.XMargin.Text);
IniFile.WriteFloat(MillModel, 'YMargin',MMSetupForm.YMargin.Text);
IniFile.Free;
End;
{..............................................................................}
{..............................................................................}
procedure TMMSetupForm.SaveClick(Sender: TObject);
Var
RecordName : String;
idx : Integer;
begin
RecordName := MMSetupForm.MMName.Text;
if (RecordName[strlen(RecordName)] = '*') then
RecordName := Copy(RecordName, 1, strlen(RecordName)-1);
idx := MMSetupForm.MMName.ItemIndex;
MMSetupForm.MMName.Items[idx] := RecordName;
MMSetupForm.MMName.SetItemIndex(idx);
// MMSetupForm.MMName.Text := RecordName;
TMMSetupForm_WriteFormToIniFile(RecordName);
ShowMessage('Model data for ''' + RecordName + ''' has been saved');
end;
procedure TMMSetupForm.bnExitClick(Sender: TObject);
begin
Close;
end;
{..............................................................................}
{..............................................................................}
procedure TMMSetupForm.NewClick(Sender: TObject);
Var
NewMillName : string;
IniFile : TIniFile;
begin
IniFile := TIniFile.Create(TMMSetupForm_IniFilename);
if (InputQuery('Add New Mill','Name',NewMillName) <> 0) then
begin
//if name doesn't exist already then
if (IniFile.SectionExists(NewMillName)) then
ShowMessage('An entry with that name already exists')
else
begin
MMSetupForm.MMName.SetItemIndex(MMSetupForm.MMName.Items.Add(NewMillName + '*'));
TMMSetupForm_ReadIniFileToForm(NewMillName);
end;
IniFile.Free;
end
end;
procedure TMMSetupForm.DeleteClick(Sender: TObject);
Var
ButtonPressed : Integer;
RecordName : String;
IniFile : TIniFile;
begin
RecordName := MMSetupForm.MMName.Text;
ButtonPressed := MessageDlg('Entirely remove settings for ''' + RecordName + '''',mtWarning, mbOKCancel,0);
if (ButtonPressed = mrOK) then
begin
IniFile := TIniFile.Create(TMMSetupForm_IniFilename);
IniFile.EraseSection(RecordName);
ShowMessage('''' + RecordName + ''' deleted');
IniFile.Free;
MMSetupForm.MMName.Items.Delete(MMSetupForm.MMName.ItemIndex);
MMSetupForm.MMName.SetItemIndex(0);
TMMSetupForm_ReadIniFileToForm(MMSetupForm.MMName.Items[0]);
end;
end;
procedure TMMSetupForm.MMNameChange(Sender: TObject);
begin
TMMSetupForm_ReadIniFileToForm(MMSetupForm.MMName.Text);
end;
{..............................................................................}
{..............................................................................}
function TMMSetupForm_SetupMachineConfig(Idx : Integer) : Integer;
Var
Sections : TStrings;
IniFile : TIniFile;
begin
IniFile := TIniFile.Create(TMMSetupForm_IniFileName);
Sections := TStringList.Create;
IniFile.ReadSections(Sections);
MMSetupForm.MMName.SetItems(Sections);
MMSetupForm.MMName.SetItemIndex(Idx);
IniFile.Free;
TMMSetupForm_ReadIniFileToForm(MMSetupForm.MMName.Text);
Result := MMName.ItemIndex;
end;
{..............................................................................}
|
unit ViewTributacaoPis;
{$mode objfpc}{$H+}
interface
uses
HTTPDefs, BrookRESTActions, BrookUtils, FPJson, SysUtils, BrookHTTPConsts;
type
TViewTributacaoPisOptions = class(TBrookOptionsAction)
end;
TViewTributacaoPisRetrieve = class(TBrookRetrieveAction)
procedure Request({%H-}ARequest: TRequest; AResponse: TResponse); override;
end;
TViewTributacaoPisShow = class(TBrookShowAction)
end;
TViewTributacaoPisCreate = class(TBrookCreateAction)
end;
TViewTributacaoPisUpdate = class(TBrookUpdateAction)
end;
TViewTributacaoPisDestroy = class(TBrookDestroyAction)
end;
implementation
procedure TViewTributacaoPisRetrieve.Request(ARequest: TRequest; AResponse: TResponse);
var
VRow: TJSONObject;
IdOperacao: String;
IdGrupo: String;
begin
IdOperacao := Values['id_operacao'].AsString;
IdGrupo := Values['id_grupo'].AsString;
Values.Clear;
Table.Where('ID_TRIBUT_OPERACAO_FISCAL = "' + IdOperacao + '" and ID_TRIBUT_GRUPO_TRIBUTARIO = "' + IdGrupo + '"');
if Execute then
begin
Table.GetRow(VRow);
try
Write(VRow.AsJSON);
finally
FreeAndNil(VRow);
end;
end
else
begin
AResponse.Code := BROOK_HTTP_STATUS_CODE_NOT_FOUND;
AResponse.CodeText := BROOK_HTTP_REASON_PHRASE_NOT_FOUND;
end;
// inherited Request(ARequest, AResponse);
end;
initialization
TViewTributacaoPisOptions.Register('view_tributacao_pis', '/view_tributacao_pis');
TViewTributacaoPisRetrieve.Register('view_tributacao_pis', '/view_tributacao_pis/:id_operacao/:id_grupo/');
TViewTributacaoPisShow.Register('view_tributacao_pis', '/view_tributacao_pis/:id');
TViewTributacaoPisCreate.Register('view_tributacao_pis', '/view_tributacao_pis');
TViewTributacaoPisUpdate.Register('view_tributacao_pis', '/view_tributacao_pis/:id');
TViewTributacaoPisDestroy.Register('view_tributacao_pis', '/view_tributacao_pis/:id');
end.
|
unit uTFTPDownload;
interface
uses
Classes, NMFtp, uFrmNewLoader;
type
TFiles = record
LocalFile : String;
ServerFile : String;
Description : String;
end;
type
TFTPDownload = class(TThread)
private
{ Private declarations }
aFile : array[0..10] of TFiles;
Counted : integer;
MyFTP : TNMFtp;
MyDescription : String;
procedure UpdateMainThread;
public
procedure SetFTP(fFTP : TNMFTP);
procedure SetDownloadFiles(sServerFile, sLocalFile, sDescription : String);
function DownloadFiles:Boolean;
protected
procedure Execute; override;
end;
implementation
{ Important: Methods and properties of objects in VCL can only be used in a
method called using Synchronize, for example,
Synchronize(UpdateCaption);
and UpdateCaption could look like,
procedure TFTPDownload.UpdateCaption;
begin
Form1.Caption := 'Updated in a thread';
end; }
{ TFTPDownload }
procedure TFTPDownload.UpdateMainThread;
begin
with FrmNewLoader do
UpdateFTPInfo(MyDescription);
end;
procedure TFTPDownload.SetFTP(fFTP : TNMFTP);
begin
MyFTP := TNMFtp.Create(nil);
MyFTP := fFTP;
Counted := 0;
end;
function TFTPDownload.DownloadFiles:Boolean;
var
i : integer;
begin
{ Place thread code here }
try
MyFTP.Connect;
for i:=0 to Counted-1 do
begin
MyDescription := aFile[i].Description;
Synchronize(UpdateMainThread);
MyFTP.Download(aFile[i].ServerFile, aFile[i].LocalFile);
end;
MyFTP.Disconnect;
MyFTP.Free;
Result := true;
except
MyFTP.Disconnect;
MyFTP.Free;
Result := false;
end;
end;
procedure TFTPDownload.SetDownloadFiles(sServerFile, sLocalFile, sDescription : String);
begin
aFile[Counted].LocalFile := sLocalFile;
aFile[Counted].ServerFile := sServerFile;
aFile[Counted].Description := sDescription;
inc(Counted);
end;
procedure TFTPDownload.Execute;
begin
{ Place thread code here }
end;
end.
|
unit RegionsModel;
interface
uses connection, Ragna, System.JSON, 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.ConsoleUI.Wait, Data.DB,
FireDAC.Comp.Client, FireDAC.Phys.PG, FireDAC.Phys.PGDef, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt,
FireDAC.Comp.DataSet, Horse, System.SysUtils, Dataset.serialize,
System.Classes, System.NetEncoding, Soap.EncdDecd;
function save(regionJson: string ): TFDQuery;
function update(id: integer; regionJson: string ): TFDQuery;
function delete(id: integer ): boolean;
function findAll(page: integer; limit: integer; findName:string; findValue: string; var tot_page: integer): TFDQuery; overload;
function findAll(): TFDQuery; overload;
function findByPK(id: integer): TFDQuery;
implementation
function save(regionJson: string ): TFDQuery;
begin
DMConnection := TDMConnection.Create(DMConnection);
const Regions = DMConnection.Regioes_Atendimento;
var jsonObj := TJSONObject
.ParseJSONValue(TEncoding.UTF8.GetBytes(regionJson), 0) as TJSONObject;
Regions.New(jsonObj).OpenUp;
Result := Regions;
end;
function update(id: integer; regionJson: string ): TFDQuery;
begin
DMConnection := TDMConnection.Create(DMConnection);
const Regions = DMConnection.Regioes_Atendimento;
var jsonObj := TJSONObject
.ParseJSONValue(TEncoding.UTF8.GetBytes(regionJson), 0) as TJSONObject;
Regions.where('id').Equals(id).OpenUp;
Regions.MergeFromJSONObject(jsonObj);
Result := Regions;
end;
function delete(id: integer ): boolean;
begin
DMConnection := TDMConnection.Create(DMConnection);
const Regions = DMConnection.Regioes_Atendimento;
try
Regions.Remove(Regions.FieldByName('id'), id).OpenUp;
result:= true;
except
on E:Exception do
result:= false;
end;
end;
function findAll(page: integer; limit: integer; findName:string; findValue: string; var tot_page: integer): TFDQuery;
begin
DMConnection := TDMConnection.Create(DMConnection);
const regions = DMConnection.Regions_instituicoes;
regions.Close;
regions.SQL.Clear;
regions.SQL.Add('select ');
regions.SQL.Add('ra.*,');
regions.SQL.Add('i.nome_instituicao');
regions.SQL.Add('from ');
regions.SQL.Add('regioes_atendimento ra inner join');
regions.SQL.Add('instituicoes i on');
regions.SQL.Add('i.id = ra.id_instituicao');
var filtered := false;
var tot := false;
if ((findName <> '') and (findValue <> '')) then
begin
regions.SQL.Add(' where ');
regions.SQL.Add( findName +' like ' + QuotedStr('%' + findValue + '%'));
regions.Open;
filtered := true;
tot := Trunc((Regions.RowsAffected/limit)) < (Regions.RowsAffected/limit);
if tot then
tot_page := Trunc(Regions.RowsAffected/limit) + 1
else
tot_page := Trunc(Regions.RowsAffected/limit);
regions.close;
end;
if not filtered then
begin
tot := Trunc((Regions.OpenUp.RowsAffected/limit)) < (Regions.OpenUp.RowsAffected/limit);
if tot then
tot_page := Trunc(Regions.OpenUp.RowsAffected/limit) + 1
else
tot_page := Trunc(Regions.OpenUp.RowsAffected/limit);
end;
var initial := page - 1;
initial := initial * limit;
regions.SQL.Add('ORDER BY ');
regions.SQL.Add('ra.id OFFSET :offset ROWS FETCH NEXT :limit ROWS ONLY;');
regions.ParamByName('offset').AsInteger := initial;
regions.ParamByName('limit').AsInteger := limit;
regions.Open;
Result := Regions;
end;
function findAll(): TFDQuery; overload;
begin
DMConnection := TDMConnection.Create(DMConnection);
const Regions = DMConnection.Regioes_Atendimento;
Regions.OpenUp;
Result := Regions;
end;
function findByPk(id: integer): TFDQuery;
begin
DMConnection := TDMConnection.Create(DMConnection);
const Regions = DMConnection.Regioes_Atendimento;
Regions.where('id').equals(id).openUp;
result := Regions;
end;
end.
|
unit nsProcessFrm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, StdCtrls, ExtCtrls;
type
TfrmProcess = class(TForm)
aniProgress: TAnimate;
pbxFileName: TLabel;
pbxAction: TLabel;
ProgressBar1: TProgressBar;
Label1: TLabel;
lblTotalSize: TLabel;
ProgressBar2: TProgressBar;
lblProcSize: TLabel;
lblTimeElapsed: TLabel;
lblSpeed: TLabel;
lblTimeRemaining: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
Label6: TLabel;
pnlBottom: TPanel;
btnCancel: TButton;
procedure FormCreate(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
procedure FormShow(Sender: TObject);
private
FTotalProcessSize: int64;
FProcessed: int64;
FStartTick: DWORD;
FTimeElapsed: DWORD;
FTimeRemaining: DWORD;
FCurItemSize: int64;
FSpeed: int64;
procedure SetCurAction(const Value: string);
procedure SetCurFile(const Value: string);
procedure SetCurItemSize(const Value: int64);
{ Private declarations }
protected
FDivider: DWORD;
public
{ Public declarations }
procedure Initialize(const ATotalProcessSize: int64);
procedure UpdateProgress;
procedure SetProgress(const AOperation, AFileName: string; const ACurrent, ATotal: int64);
procedure FTPProgress(Current, Total: int64; var AClose: Boolean);
procedure HashProgress(CurBlock, TotBlock: integer; var AClose: Boolean);
procedure ZipProgress(CurBlock, TotBlock: integer; var AClose: Boolean);
procedure CopyProgress(CurBlock, TotBlock: integer; var AClose: Boolean);
procedure CopyProgressEx(CurBlock, TotBlock: integer; var AClose: Boolean);
// procedure CDRWProgress(Current, Total: Int64; var Abort: Boolean);
property CurAction: string write SetCurAction;
property CurFile: string write SetCurFile;
property CurItemSize: int64 read FCurItemSize write SetCurItemSize;
end;
var
frmProcess: TfrmProcess = nil;
implementation
uses
nsGlobals,
nsUtils,
nsTypes;
{$R *.dfm}
{$R avis.res}
procedure TfrmProcess.FormCreate(Sender: TObject);
begin
FDivider := MAXWORD;
DoubleBuffered := True;
aniProgress.ResName := AVI_PROCESS;
aniProgress.ResHandle := hInstance;
aniProgress.Active := True;
end;
procedure TfrmProcess.FormShow(Sender: TObject);
begin
UpdateVistaFonts(Self);
end;
procedure TfrmProcess.btnCancelClick(Sender: TObject);
begin
CurProject.KillProcessing;
end;
procedure TfrmProcess.FTPProgress(Current, Total: int64; var AClose: Boolean);
var
CurBlock, TotBlock: integer;
dt: DWORD;
begin
AClose := g_AbortProcess;
if Total > MaxInt then
begin
CurBlock := Current div FDivider;
TotBlock := Total div FDivider;
end
else
begin
CurBlock := Current;
TotBlock := Total;
end;
ProgressBar1.Max := TotBlock;
ProgressBar1.Position := CurBlock;
ProgressBar2.Max := FTotalProcessSize div FDivider + 1;
ProgressBar2.Position := FProcessed div FDivider + 1;
(* if (CurBlock <> LastBlock) and (CurBlock > 1) and (CurBlock mod 3 = 0) then
begin
ProgressBar2.Position := ProgressBar2.Position + 1;
LastBlock := CurBlock;
end;
*)
dt := GetTickCount - FStartTick - FTimeElapsed;
FTimeElapsed := GetTickCount - FStartTick;
lblTimeElapsed.Caption := TicksToTime(FTimeElapsed);
FTimeRemaining := FTimeRemaining - dt;
lblTimeRemaining.Caption := TicksToTime(FTimeRemaining);
Application.ProcessMessages;
end;
procedure TfrmProcess.SetCurAction(const Value: string);
begin
pbxAction.Caption := Value;
end;
procedure TfrmProcess.SetCurFile(const Value: string);
begin
pbxFileName.Caption := Value;
end;
procedure TfrmProcess.HashProgress(CurBlock, TotBlock: integer; var AClose: Boolean);
var
dt: DWORD;
begin
AClose := g_AbortProcess;
ProgressBar1.Max := Abs(TotBlock);
ProgressBar1.Position := Abs(CurBlock);
ProgressBar2.Max := FTotalProcessSize div FDivider + 1;
ProgressBar2.Position := FProcessed div FDivider + 1;
(*
if (CurBlock > 1) and (CurBlock mod (FDivider div 4) = 0) then
ProgressBar2.Position := ProgressBar2.Position + 1;
*)
dt := GetTickCount - FStartTick - FTimeElapsed;
FTimeElapsed := GetTickCount - FStartTick;
lblTimeElapsed.Caption := TicksToTime(FTimeElapsed);
FTimeRemaining := FTimeRemaining - dt;
lblTimeRemaining.Caption := TicksToTime(FTimeRemaining);
Application.ProcessMessages;
end;
procedure TfrmProcess.ZipProgress(CurBlock, TotBlock: integer; var AClose: Boolean);
var
dt: DWORD;
begin
AClose := g_AbortProcess;
ProgressBar1.Max := Abs(TotBlock);
ProgressBar1.Position := Abs(CurBlock);
(*
if (CurBlock > 3) and (CurBlock mod 3 = 0) then
ProgressBar2.Position := ProgressBar2.Position + 1;
*)
ProgressBar2.Max := FTotalProcessSize div FDivider + 1;
ProgressBar2.Position := FProcessed div FDivider + 1;
dt := GetTickCount - FStartTick - FTimeElapsed;
FTimeElapsed := GetTickCount - FStartTick;
lblTimeElapsed.Caption := TicksToTime(FTimeElapsed);
FTimeRemaining := FTimeRemaining - dt;
lblTimeRemaining.Caption := TicksToTime(FTimeRemaining);
Application.ProcessMessages;
end;
{procedure TProcessForm.CDRWProgress(Current, Total: Int64;
var Abort: Boolean);
begin
ProgressBar.Max := Total;
ProgressBar.Position := Current;
Abort := FNeedClose;
if Current = Total then
CurFile := sFinalizingTrack;
Application.ProcessMessages;
Update;
end;
}
procedure TfrmProcess.SetProgress(const AOperation, AFileName: string; const ACurrent, ATotal: int64);
var
dt: DWORD;
mx, ps: integer;
begin
CurAction := AOperation;
CurFile := AFileName;
if ATotal > MaxInt then
begin
mx := ATotal div FDivider;
ps := ACurrent div FDivider;
end
else
begin
mx := ATotal;
ps := ACurrent;
end;
ProgressBar1.Max := mx;
ProgressBar1.Position := ps;
ProgressBar2.Max := FTotalProcessSize div FDivider + 1;
ProgressBar2.Position := FProcessed div FDivider + 1;
// ProgressBar2.Position := ProgressBar2.Position + 1;
dt := GetTickCount - FStartTick - FTimeElapsed;
FTimeElapsed := GetTickCount - FStartTick;
lblTimeElapsed.Caption := TicksToTime(FTimeElapsed);
FTimeRemaining := FTimeRemaining - dt;
lblTimeRemaining.Caption := TicksToTime(FTimeRemaining);
Application.ProcessMessages;
end;
procedure TfrmProcess.Initialize(const ATotalProcessSize: int64);
begin
try
FDivider := MAXWORD;
FProcessed := 0;
FTimeElapsed := 0;
FStartTick := GetTickCount;
FTotalProcessSize := ATotalProcessSize;
lblTotalSize.Caption := FormatSize(FTotalProcessSize, False);
ProgressBar2.Position := 0;
ProgressBar2.Max := Abs(FTotalProcessSize div FDivider + 1);
lblProcSize.Caption := FormatSize(FProcessed, False);
lblTimeElapsed.Caption := TicksToTime(FTimeElapsed);
FSpeed := 100000;
lblSpeed.Caption := FormatSize(FSpeed, False) + sPerSec;
FTimeRemaining := round(1000 * FTotalProcessSize / (FSpeed + 1));
lblTimeRemaining.Caption := TicksToTime(FTimeRemaining);
except
end;
end;
procedure TfrmProcess.SetCurItemSize(const Value: int64);
begin
FCurItemSize := Value;
end;
procedure TfrmProcess.UpdateProgress;
begin
try
FProcessed := FProcessed + FCurItemSize;
lblProcSize.Caption := FormatSize(FProcessed, False);
lblTotalSize.Caption := FormatSize(FTotalProcessSize - FProcessed, False);
ProgressBar2.Max := FTotalProcessSize div FDivider + 1;
ProgressBar2.Position := FProcessed div FDivider + 1;
FTimeElapsed := GetTickCount - FStartTick;
lblTimeElapsed.Caption := TicksToTime(FTimeElapsed);
FSpeed := 1000 * Round(FProcessed / (FTimeElapsed + 1));
lblSpeed.Caption := FormatSize(FSpeed, False) + sPerSec;
FTimeRemaining := round(FTimeElapsed * (FTotalProcessSize - FProcessed) / (FProcessed + 1));
lblTimeRemaining.Caption := TicksToTime(FTimeRemaining);
Application.ProcessMessages;
except
end;
end;
procedure TfrmProcess.CopyProgress(CurBlock, TotBlock: integer; var AClose: Boolean);
var
dt: DWORD;
begin
AClose := g_AbortProcess;
ProgressBar1.Max := Abs(TotBlock);
ProgressBar1.Position := Abs(CurBlock);
ProgressBar2.Max := FTotalProcessSize div FDivider + 1;
ProgressBar2.Position := FProcessed div FDivider + 1;
dt := GetTickCount - FStartTick - FTimeElapsed;
FTimeElapsed := GetTickCount - FStartTick;
lblTimeElapsed.Caption := TicksToTime(FTimeElapsed);
FTimeRemaining := FTimeRemaining - dt;
lblTimeRemaining.Caption := TicksToTime(FTimeRemaining);
Application.ProcessMessages;
end;
procedure TfrmProcess.CopyProgressEx(CurBlock, TotBlock: integer; var AClose: Boolean);
var
dt: DWORD;
begin
AClose := g_AbortProcess;
ProgressBar1.Max := TotBlock;
ProgressBar1.Position := CurBlock;
ProgressBar2.Max := FTotalProcessSize div FDivider + 1;
ProgressBar2.Position := FProcessed div FDivider + 1;
(*
ProgressBar2.Max := ProgressBar1.Max;
ProgressBar2.Position := ProgressBar1.Position div 4;
*)
dt := GetTickCount - FStartTick - FTimeElapsed;
FTimeElapsed := GetTickCount - FStartTick;
lblTimeElapsed.Caption := TicksToTime(FTimeElapsed);
FTimeRemaining := FTimeRemaining - dt;
lblTimeRemaining.Caption := TicksToTime(FTimeRemaining);
Application.ProcessMessages;
end;
end.
|
unit RotateToolThreadUnit;
interface
uses
Windows,
Classes,
Effects,
Graphics,
RotateToolUnit,
uEditorTypes,
uMemory,
uDBThread;
type
TRotateEffectThread = class(TDBThread)
private
{ Private declarations }
FSID: string;
FProc: TBaseEffectProc;
BaseImage: TBitmap;
IntParam: Integer;
FOnExit: TBaseEffectProcThreadExit;
D: TBitmap;
FOwner: TObject;
FAngle: Double;
FBackColor: TColor;
FEditor: TObject;
protected
procedure Execute; override;
public
constructor Create(AOwner: TObject; CreateSuspended: Boolean; Proc: TBaseEffectProc; S: TBitmap; SID: string;
OnExit: TBaseEffectProcThreadExit; Angle: Double; BackColor: TColor; Editor: TObject);
procedure CallBack(Progress: Integer; var Break: Boolean);
procedure SetProgress;
procedure DoExit;
end;
implementation
{ TRotateEffectThread }
uses ImEditor;
procedure TRotateEffectThread.CallBack(Progress: Integer; var Break: Boolean);
begin
IntParam := Progress;
Synchronize(SetProgress);
if (FEditor as TImageEditor).ToolClass = FOwner then
Break := (FOwner as TRotateToolPanelClass).FSID <> FSID;
end;
constructor TRotateEffectThread.Create(AOwner: TObject;
CreateSuspended: Boolean; Proc: TBaseEffectProc; S: TBitmap; SID: string;
OnExit: TBaseEffectProcThreadExit; Angle: Double; BackColor: TColor; Editor : TObject);
begin
inherited Create(nil, False);
FOwner := AOwner;
FSID := SID;
FAngle := Angle;
FBackColor := BackColor;
FOnExit := OnExit;
FProc := Proc;
BaseImage := S;
FEditor := Editor;
end;
procedure TRotateEffectThread.DoExit;
begin
if (FEditor as TImageEditor).ToolClass = FOwner then
begin
FOnExit(D, FSID);
D := nil;
end;
end;
procedure TRotateEffectThread.Execute;
begin
inherited;
FreeOnTerminate := True;
Sleep(50);
try
if not (FEditor is TImageEditor) then
Exit;
if (FEditor as TImageEditor).ToolClass <> FOwner then
Exit;
if (FOwner as TRotateToolPanelClass).FSID <> FSID then
Exit;
D := TBitmap.Create;
try
if Assigned(FProc) then
FProc(BaseImage, D, CallBack)
else
RotateBitmap(BaseImage, D, FAngle, FBackColor, CallBack);
Synchronize(DoExit);
finally
F(D);
end;
finally
F(BaseImage)
end;
IntParam := 0;
Synchronize(SetProgress);
end;
procedure TRotateEffectThread.SetProgress;
begin
if (FEditor as TImageEditor).ToolClass = FOwner then
if (FOwner is TRotateToolPanelClass) then
(FOwner as TRotateToolPanelClass).SetProgress(IntParam, FSID);
end;
end.
|
unit ILPP_ColorCorrection;
{$INCLUDE '.\ILPP_defs.inc'}
interface
uses
ILPP_Base;
{===============================================================================
--------------------------------------------------------------------------------
Conversion using map
--------------------------------------------------------------------------------
===============================================================================}
procedure CompleteColorSpaceMap(IncompleteMap,CompletedMap: Pointer);
Function MapCorrectRGB(RGB: TRGBAQuadruplet; ConversionMap: Pointer): TRGBAQuadruplet; overload;
Function MapCorrectRGB(RGB: TRGBAQuadruplet): TRGBAQuadruplet; overload;
Function MapCorrectR(RGB: TRGBAQuadruplet; ConversionMap: Pointer): Byte; overload;
Function MapCorrectR(RGB: TRGBAQuadruplet): Byte; overload;
Function MapCorrectG(RGB: TRGBAQuadruplet; ConversionMap: Pointer): Byte; overload;
Function MapCorrectG(RGB: TRGBAQuadruplet): Byte; overload;
Function MapCorrectB(RGB: TRGBAQuadruplet; ConversionMap: Pointer): Byte; overload;
Function MapCorrectB(RGB: TRGBAQuadruplet): Byte; overload;
{===============================================================================
--------------------------------------------------------------------------------
Init/Final functions
--------------------------------------------------------------------------------
===============================================================================}
procedure Initialize;
procedure Finalize;
implementation
uses
SysUtils, Classes, Math,
StrRect,
ILPP_Utils;
{===============================================================================
--------------------------------------------------------------------------------
Conversion using map
--------------------------------------------------------------------------------
===============================================================================}
{$R '..\resources\rgb_map.res'}
{===============================================================================
Internal types, variables and constants
===============================================================================}
type
TRGBColorSpaceMap = array[{R}Byte,{G}Byte,{B}Byte] of TRGBAQuadruplet{32bit, RGBA};
PRGBColorSpaceMap = ^TRGBColorSpaceMap;
TRGBColorSpaceChannel = (chRed,chGreen,chBlue);
//------------------------------------------------------------------------------
TRGBColorSpaceProcMapEntry = record
Red,Green,Blue: Single;
Reserved: Integer; // - = original + = interpolated 0 = no value
end;
PRGBColorSpaceProcMapEntry = ^TRGBColorSpaceProcMapEntry;
TRGBColorSpaceProcMap = array[Byte,Byte,Byte] of TRGBColorSpaceProcMapEntry;
PRGBColorSpaceProcMap = ^TRGBColorSpaceProcMap;
TRGBColorSpaceProcMapSurface = (srfNoRed,srfFullRed,srfNoGreen,srfFullGreen,srfNoBlue,srfFullBlue);
var
DefaultMap: TRGBColorSpaceMap;
{===============================================================================
Filling of incomplete map
===============================================================================}
Function GetSurfaceRed(X,Y,Z: Byte; Surface: TRGBColorSpaceProcMapSurface): Byte;
begin
case Surface of
srfNoRed,
srfFullRed: Result := Z;
srfNoGreen,
srfFullGreen: Result := X;
srfNoBlue,
srfFullBlue: Result := X;
else
raise Exception.CreateFmt('GetSurfaceRed: Invalid surface (%d).',[Ord(Surface)]);
end;
end;
//------------------------------------------------------------------------------
Function GetSurfaceGreen(X,Y,Z: Byte; Surface: TRGBColorSpaceProcMapSurface): Byte;
begin
case Surface of
srfNoRed,
srfFullRed: Result := X;
srfNoGreen,
srfFullGreen: Result := Z;
srfNoBlue,
srfFullBlue: Result := Y;
else
raise Exception.CreateFmt('GetSurfaceGreen: Invalid surface (%d).',[Ord(Surface)]);
end;
end;
//------------------------------------------------------------------------------
Function GetSurfaceBlue(X,Y,Z: Byte; Surface: TRGBColorSpaceProcMapSurface): Byte;
begin
case Surface of
srfNoRed,
srfFullRed: Result := Y;
srfNoGreen,
srfFullGreen: Result := Y;
srfNoBlue,
srfFullBlue: Result := Z;
else
raise Exception.CreateFmt('GetSurfaceBlue: Invalid surface (%d).',[Ord(Surface)]);
end;
end;
//------------------------------------------------------------------------------
Function GetSurfaceChannnel(X,Y,Z: Byte; Surface: TRGBColorSpaceProcMapSurface; Channel: TRGBColorSpaceChannel): Byte;
begin
case Channel of
chRed: Result := GetSurfaceRed(X,Y,Z,Surface);
chGreen: Result := GetSurfaceGreen(X,Y,Z,Surface);
chBlue: Result := GetSurfaceBlue(X,Y,Z,Surface);
else
raise Exception.CreateFmt('GetSurfaceChannnel: Invalid surface (%d).',[Ord(Channel)]);
end;
end;
//==============================================================================
procedure FillRGBColorSpaceMapSurface(Map: PRGBColorSpaceProcMap; Surface: TRGBColorSpaceProcMapSurface);
var
X,Y,Z: Integer;
I1,I2: Integer;
i: Integer;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Function GetMapEntryPtr(A,B,C: Byte): PRGBColorSpaceProcMapEntry;
begin
Result := Addr(Map^[
GetSurfaceRed(A,B,C,Surface),
GetSurfaceGreen(A,B,C,Surface),
GetSurfaceBlue(A,B,C,Surface)]);
end;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
procedure InterpolateX(Secondary: Boolean);
var
II1,II2: Integer;
ii: Integer;
begin
// lower
II1 := -1;
ii := X;
repeat
If (GetMapEntryPtr(ii,Y,Z)^.Reserved < 0) or
(Secondary and (GetMapEntryPtr(ii,Y,Z)^.Reserved <> 0)) then
II1 := ii;
Dec(ii);
until (II1 >= 0) or (ii < 0);
// higher
II2 := -1;
ii := X;
repeat
If (GetMapEntryPtr(ii,Y,Z)^.Reserved < 0) or
(Secondary and (GetMapEntryPtr(ii,Y,Z)^.Reserved <> 0)) then
II2 := ii;
Inc(ii);
until (II2 >= 0) or (ii > 255);
If (II1 >= 0) and (II2 >= 0) then
begin
GetMapEntryPtr(X,Y,Z)^.Red := GetMapEntryPtr(X,Y,Z)^.Red + EnsureRange(InterpolateLinear(II1,II2,GetMapEntryPtr(II1,Y,Z)^.Red,GetMapEntryPtr(II2,Y,Z)^.Red,X),0,1);
GetMapEntryPtr(X,Y,Z)^.Green := GetMapEntryPtr(X,Y,Z)^.Green + EnsureRange(InterpolateLinear(II1,II2,GetMapEntryPtr(II1,Y,Z)^.Green,GetMapEntryPtr(II2,Y,Z)^.Green,X),0,1);
GetMapEntryPtr(X,Y,Z)^.Blue := GetMapEntryPtr(X,Y,Z)^.Blue + EnsureRange(InterpolateLinear(II1,II2,GetMapEntryPtr(II1,Y,Z)^.Blue,GetMapEntryPtr(II2,Y,Z)^.Blue,X),0,1);
Inc(GetMapEntryPtr(X,Y,Z)^.Reserved);
end;
end;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
procedure InterpolateY(Secondary: Boolean);
var
II1,II2: Integer;
ii: Integer;
begin
// lower
II1 := -1;
ii := Y;
repeat
If (GetMapEntryPtr(X,ii,Z)^.Reserved < 0) or
(Secondary and (GetMapEntryPtr(X,ii,Z)^.Reserved <> 0)) then
II1 := ii;
Dec(ii);
until (II1 >= 0) or (ii < 0);
// higher
II2 := -1;
ii := Y;
repeat
If (GetMapEntryPtr(X,ii,Z)^.Reserved < 0) or
(Secondary and (GetMapEntryPtr(X,ii,Z)^.Reserved <> 0)) then
II2 := ii;
Inc(ii);
until (II2 >= 0) or (ii > 255);
If (II1 >= 0) and (II2 >= 0) then
begin
GetMapEntryPtr(X,Y,Z)^.Red := GetMapEntryPtr(X,Y,Z)^.Red + EnsureRange(InterpolateLinear(II1,II2,GetMapEntryPtr(X,II1,Z)^.Red,GetMapEntryPtr(X,II2,Z)^.Red,Y),0,1);
GetMapEntryPtr(X,Y,Z)^.Green := GetMapEntryPtr(X,Y,Z)^.Green + EnsureRange(InterpolateLinear(II1,II2,GetMapEntryPtr(X,II1,Z)^.Green,GetMapEntryPtr(X,II2,Z)^.Green,Y),0,1);
GetMapEntryPtr(X,Y,Z)^.Blue := GetMapEntryPtr(X,Y,Z)^.Blue + EnsureRange(InterpolateLinear(II1,II2,GetMapEntryPtr(X,II1,Z)^.Blue,GetMapEntryPtr(X,II2,Z)^.Blue,Y),0,1);
Inc(GetMapEntryPtr(X,Y,Z)^.Reserved);
end;
end;
begin
If Surface in [srfNoRed,srfNoGreen,srfNoBlue] then
Z := 0
else
Z := 255;
// first round of interpolation
For X := 0 to 255 do
For Y := 0 to 255 do
If GetMapEntryPtr(X,Y,Z)^.Reserved = 0 then
begin
// interpolate from X
InterpolateX(False);
// intepolate from Y
InterpolateY(False);
// get average from interpolations
If GetMapEntryPtr(X,Y,Z)^.Reserved > 1 then
begin
GetMapEntryPtr(X,Y,Z)^.Red := GetMapEntryPtr(X,Y,Z)^.Red / GetMapEntryPtr(X,Y,Z)^.Reserved;
GetMapEntryPtr(X,Y,Z)^.Green := GetMapEntryPtr(X,Y,Z)^.Green / GetMapEntryPtr(X,Y,Z)^.Reserved;
GetMapEntryPtr(X,Y,Z)^.Blue := GetMapEntryPtr(X,Y,Z)^.Blue / GetMapEntryPtr(X,Y,Z)^.Reserved;
GetMapEntryPtr(X,Y,Z)^.Reserved := 1;
end;
end;
// second round of interpolation
For X := 0 to 255 do
For Y := 0 to 255 do
If GetMapEntryPtr(X,Y,Z)^.Reserved = 0 then
begin
// interpolate from X
InterpolateX(True);
// intepolate from Y
InterpolateY(True);
// get average from interpolations
If GetMapEntryPtr(X,Y,Z)^.Reserved > 1 then
begin
GetMapEntryPtr(X,Y,Z)^.Red := GetMapEntryPtr(X,Y,Z)^.Red / GetMapEntryPtr(X,Y,Z)^.Reserved;
GetMapEntryPtr(X,Y,Z)^.Green := GetMapEntryPtr(X,Y,Z)^.Green / GetMapEntryPtr(X,Y,Z)^.Reserved;
GetMapEntryPtr(X,Y,Z)^.Blue := GetMapEntryPtr(X,Y,Z)^.Blue / GetMapEntryPtr(X,Y,Z)^.Reserved;
GetMapEntryPtr(X,Y,Z)^.Reserved := 1;
end;
end;
// extrapolate where necessary
For X := 0 to 255 do
For Y := 0 to 255 do
If GetMapEntryPtr(X,Y,Z)^.Reserved = 0 then
begin
// extrapolate from Z axis
If GetMapEntryPtr(X,Y,Z)^.Reserved = 0 then
begin
I1 := -1;
I2 := -1;
i := Z;
repeat
If GetMapEntryPtr(X,Y,i)^.Reserved < 0 then
begin
If I1 < 0 then
I1 := i
else
I2 := i;
end;
If Surface in [srfNoRed,srfNoGreen,srfNoBlue] then
Inc(i)
else
Dec(i);
until ((I1 >= 0) and (I2 >= 0)) or ((i > 255) or (i < 0));
If (I1 >= 0) and (I2 >= 0) then
begin
// extrapolate color
GetMapEntryPtr(X,Y,Z)^.Red := EnsureRange(ExtrapolateLinear(I1,I2,GetMapEntryPtr(X,Y,I1)^.Red,GetMapEntryPtr(X,Y,I2)^.Red,Z),0,1);
GetMapEntryPtr(X,Y,Z)^.Green := EnsureRange(ExtrapolateLinear(I1,I2,GetMapEntryPtr(X,Y,I1)^.Green,GetMapEntryPtr(X,Y,I2)^.Green,Z),0,1);
GetMapEntryPtr(X,Y,Z)^.Blue := EnsureRange(ExtrapolateLinear(I1,I2,GetMapEntryPtr(X,Y,I1)^.Blue,GetMapEntryPtr(X,Y,I2)^.Blue,Z),0,1);
GetMapEntryPtr(X,Y,Z)^.Reserved := 1;
end
else raise Exception.CreateFmt('FillRGBColorSpaceMapSurface: Cannot extrapolate (%d,%d,%d,%d)',[Ord(Surface),X,Y,Z]);
end;
end;
end;
//------------------------------------------------------------------------------
procedure FillRGBColorSpaceMapSurfaces(Map: PRGBColorSpaceProcMap);
var
Surface: TRGBColorSpaceProcMapSurface;
begin
For Surface := Low(TRGBColorSpaceProcMapSurface) to High(TRGBColorSpaceProcMapSurface) do
FillRGBColorSpaceMapSurface(Map,Surface);
end;
//==============================================================================
procedure FillRGBColorSpaceMap(Map: PRGBColorSpaceProcMap);
var
R,G,B: Integer;
I1,I2: Integer;
i: Integer;
Cntr: Integer;
begin
// fill color space surfaces
FillRGBColorSpaceMapSurfaces(Map);
// interpolate missing points
For R := 1 to 254 do
For G := 1 to 254 do
For B := 1 to 254 do
If Map^[R,G,B].Reserved = 0 then
begin
Cntr := 0;
// interpolate in direction of red channel
// lower
I1 := -1;
i := R;
repeat
If Map^[i,G,B].Reserved <> 0 then
I1 := i;
Dec(i);
until (I1 >= 0) or (i < 0);
// higher
I2 := -1;
i := R;
repeat
If Map^[i,G,B].Reserved <> 0 then
I2 := i;
Inc(i);
until (I2 >= 0) or (i > 255);
If (I1 >= 0) and (I2 >= 0) then
begin
Map^[R,G,B].Red := Map^[R,G,B].Red + EnsureRange(InterpolateLinear(I1,I2,Map^[I1,G,B].Red,Map^[I2,G,B].Red,R),0,1);
Map^[R,G,B].Green := Map^[R,G,B].Green + EnsureRange(InterpolateLinear(I1,I2,Map^[I1,G,B].Green,Map^[I2,G,B].Green,R),0,1);
Map^[R,G,B].Blue := Map^[R,G,B].Blue + EnsureRange(InterpolateLinear(I1,I2,Map^[I1,G,B].Blue,Map^[I2,G,B].Blue,R),0,1);
Inc(Cntr);
end;
// interpolate in direction of green channel
// lower
I1 := -1;
i := G;
repeat
If Map^[R,i,B].Reserved <> 0 then
I1 := i;
Dec(i);
until (I1 >= 0) or (i < 0);
// higher
I2 := -1;
i := G;
repeat
If Map^[R,i,B].Reserved <> 0 then
I2 := i;
Inc(i);
until (I2 >= 0) or (i > 255);
If (I1 >= 0) and (I2 >= 0) then
begin
Map^[R,G,B].Red := Map^[R,G,B].Red + EnsureRange(InterpolateLinear(I1,I2,Map^[R,I1,B].Red,Map^[R,I2,B].Red,G),0,1);
Map^[R,G,B].Green := Map^[R,G,B].Green + EnsureRange(InterpolateLinear(I1,I2,Map^[R,I1,B].Green,Map^[R,I2,B].Green,G),0,1);
Map^[R,G,B].Blue := Map^[R,G,B].Blue + EnsureRange(InterpolateLinear(I1,I2,Map^[R,I1,B].Blue,Map^[R,I2,B].Blue,G),0,1);
Inc(Cntr);
end;
// interpolate in direction of blue channel
// lower
I1 := -1;
i := B;
repeat
If Map^[R,G,i].Reserved <> 0 then
I1 := i;
Dec(i);
until (I1 >= 0) or (i < 0);
// higher
I2 := -1;
i := B;
repeat
If Map^[R,G,i].Reserved <> 0 then
I2 := i;
Inc(i);
until (I2 >= 0) or (i > 255);
If (I1 >= 0) and (I2 >= 0) then
begin
Map^[R,G,B].Red := Map^[R,G,B].Red + EnsureRange(InterpolateLinear(I1,I2,Map^[R,G,I1].Red,Map^[R,G,I2].Red,B),0,1);
Map^[R,G,B].Green := Map^[R,G,B].Green + EnsureRange(InterpolateLinear(I1,I2,Map^[R,G,I1].Green,Map^[R,G,I2].Green,B),0,1);
Map^[R,G,B].Blue := Map^[R,G,B].Blue + EnsureRange(InterpolateLinear(I1,I2,Map^[R,G,I1].Blue,Map^[R,G,I2].Blue,B),0,1);
Inc(Cntr);
end;
// get average from interpolations
If Cntr > 1 then
begin
Map^[R,G,B].Red := Map^[R,G,B].Red / Cntr;
Map^[R,G,B].Green := Map^[R,G,B].Green / Cntr;
Map^[R,G,B].Blue := Map^[R,G,B].Blue / Cntr;
end;
Map^[R,G,B].Reserved := 1;
end;
// check if all points are set
For R := 0 to 255 do
For G := 0 to 255 do
For B := 0 to 255 do
If Map^[R,G,B].Reserved = 0 then
raise Exception.CreateFmt('FillRGBColorSpaceMap: Invalid value [%d,%d,%d].',[R,G,B]);
end;
//------------------------------------------------------------------------------
procedure CompleteColorSpaceMap(IncompleteMap,CompletedMap: Pointer);
var
R,G,B: Byte;
Map: PRGBColorSpaceProcMap;
begin
GetMem(Map,SizeOf(TRGBColorSpaceProcMap));
try
// copy all valid entries
FillChar(Map^,SizeOf(TRGBColorSpaceMap),0);
For R := 0 to 255 do
For G := 0 to 255 do
For B := 0 to 255 do
If PRGBColorSpaceMap(IncompleteMap)^[R,G,B].A <> 0 then
begin
Map^[R,G,B].Red := PRGBColorSpaceMap(IncompleteMap)^[R,G,B].R / 255;
Map^[R,G,B].Green := PRGBColorSpaceMap(IncompleteMap)^[R,G,B].G / 255;
Map^[R,G,B].Blue := PRGBColorSpaceMap(IncompleteMap)^[R,G,B].B / 255;
Map^[R,G,B].Reserved := -1;
end;
// do the actual calculations
FillRGBColorSpaceMap(Map);
// fill result
FillChar(CompletedMap^,SizeOf(TRGBColorSpaceMap),0);
For R := 0 to 255 do
For G := 0 to 255 do
For B := 0 to 255 do
begin
PRGBColorSpaceMap(IncompleteMap)^[R,G,B].R := EnsureRange(Round(Map^[R,G,B].Red * 255),0,255);
PRGBColorSpaceMap(IncompleteMap)^[R,G,B].G := EnsureRange(Round(Map^[R,G,B].Green * 255),0,255);
PRGBColorSpaceMap(IncompleteMap)^[R,G,B].B := EnsureRange(Round(Map^[R,G,B].Blue * 255),0,255);
PRGBColorSpaceMap(IncompleteMap)^[R,G,B].A := 1;
end;
finally
FreeMem(Map,SizeOf(TRGBColorSpaceProcMap));
end;
end;
//==============================================================================
Function MapCorrectRGB(RGB: TRGBAQuadruplet; ConversionMap: Pointer): TRGBAQuadruplet;
begin
Result := PRGBColorSpaceMap(ConversionMap)^[RGB.R,RGB.G,RGB.B];
Result.A := 0;
end;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Function MapCorrectRGB(RGB: TRGBAQuadruplet): TRGBAQuadruplet;
begin
Result := MapCorrectRGB(RGB,@DefaultMap);
end;
//------------------------------------------------------------------------------
Function MapCorrectR(RGB: TRGBAQuadruplet; ConversionMap: Pointer): Byte;
begin
Result := MapCorrectRGB(RGB,ConversionMap).R;
end;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Function MapCorrectR(RGB: TRGBAQuadruplet): Byte;
begin
Result := MapCorrectR(RGB,@DefaultMap);
end;
//------------------------------------------------------------------------------
Function MapCorrectG(RGB: TRGBAQuadruplet; ConversionMap: Pointer): Byte;
begin
Result := MapCorrectRGB(RGB,ConversionMap).G;
end;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Function MapCorrectG(RGB: TRGBAQuadruplet): Byte;
begin
Result := MapCorrectG(RGB,@DefaultMap);
end;
//------------------------------------------------------------------------------
Function MapCorrectB(RGB: TRGBAQuadruplet; ConversionMap: Pointer): Byte;
begin
Result := MapCorrectRGB(RGB,ConversionMap).B;
end;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Function MapCorrectB(RGB: TRGBAQuadruplet): Byte;
begin
Result := MapCorrectB(RGB,@DefaultMap);
end;
{===============================================================================
--------------------------------------------------------------------------------
Init/Final functions
--------------------------------------------------------------------------------
===============================================================================}
procedure Initialize;
var
ResStream: TResourceStream;
begin
ResStream := TResourceStream.Create(hInstance,StrToRTL('rgb_map'),PChar(10));
try
ResStream.ReadBuffer(DefaultMap,SizeOf(TRGBColorSpaceMap));
finally
ResStream.Free;
end;
end;
//------------------------------------------------------------------------------
procedure Finalize;
begin
// nothing to do
end;
end.
|
unit DummySyntaxHighlightMemo;
interface
uses
SysUtils,Windows,Messages,Classes,SyntaxHighlightMemo,SyntaxHighlighter,
Controls,Forms;
type
TDummySyntaxHighlightMemo=class(TCustomSyntaxHighlightMemo)
private
FSource:TCustomSyntaxHighlightMemo;
procedure WMSetCursor(var Message:TMessage);message WM_SETCURSOR;
protected
function PosClass(p:TPoint):TCharClass;override;
function GetHighlightClassCount:Integer;override;
function GetHighlightClassName(Index:Integer):string;override;
function GetHighlightData(Index:Integer):TCharClassHighlight;override;
procedure SetHighlightData(Index:Integer;const Value:TCharClassHighlight);override;
procedure MouseDown(Button:TMouseButton;Shift:TShiftState;X,Y:Integer);override;
procedure MouseMove(Shift:TShiftState;X,Y:Integer);override;
procedure MouseUp(Button:TMouseButton;Shift:TShiftState;X,Y:Integer);override;
procedure KeyDown(var Key:Word;Shift:TShiftState);override;
procedure KeyUp(var Key:Word;Shift:TShiftState);override;
procedure KeyPress(var Key:Char);override;
// function DoMouseWheelDown(Shift:TShiftState;MousePos:TPoint):Boolean;override;
// function DoMouseWheelUp(Shift:TShiftState;MousePos:TPoint):Boolean;override;
procedure DblClick;override;
public
constructor Create(AOwner:TComponent;ASource:TCustomSyntaxHighlightMemo);reintroduce;virtual;
procedure ClearMarks;override;
function CharClassHighlight(ClassID:TCharClass):TCharClassHighlight;override;
function CharClassCanJump(ClassID:TCharClass):Boolean;override;
procedure CharClassJump(ClassID:TCharClass;Text:string;Pos:TPoint);override;
function CharClassCanHint(ClassID:TCharClass):Boolean;override;
function CharClassHint(ClassID:TCharClass;Text:string;Pos:TPoint):string;override;
procedure TokenizeLineClass(const LastLineClass:TLineClass;var NewLineClass:TLineClass;const TextBuffer:PChar;const TextLength:Integer);override;
procedure TokenizeLine(const LineClass:TLineClass;const TextBuffer:PChar;const TextLength:Integer;CharClass:PCharClassArray);override;
end;
implementation
uses
SourceEditorCustomizeDialogUnit;
{ TDummySyntaxHighlightMemo }
function TDummySyntaxHighlightMemo.CharClassCanHint(
ClassID: TCharClass): Boolean;
begin
Result:=False;
end;
function TDummySyntaxHighlightMemo.CharClassCanJump(
ClassID: TCharClass): Boolean;
begin
Result:=FSource.CharClassCanJump(ClassID);
end;
function TDummySyntaxHighlightMemo.CharClassHighlight(
ClassID: TCharClass): TCharClassHighlight;
begin
Result:=FSource.CharClassHighlight(ClassID);
end;
function TDummySyntaxHighlightMemo.CharClassHint(ClassID: TCharClass;
Text: string; Pos: TPoint): string;
begin
end;
procedure TDummySyntaxHighlightMemo.CharClassJump(ClassID: TCharClass;
Text: string; Pos: TPoint);
begin
end;
procedure TDummySyntaxHighlightMemo.ClearMarks;
begin
end;
constructor TDummySyntaxHighlightMemo.Create(AOwner: TComponent;
ASource: TCustomSyntaxHighlightMemo);
var
h:THighlightData;
t:TTrackingData;
begin
inherited Create(AOwner);
Lines.BeginUpdate;
DoubleBuffered:=True;
FSource:=ASource;
Lines.Assign(FSource.CustomText);
Lines.Insert(0,'Selected text');
Lines.Insert(0,'Hot link');
Lines.Insert(0,'Warning line');
Lines.Insert(0,'Execute error line');
Lines.Insert(0,'Compile error line');
Lines.Insert(0,'Search match');
SelKind:=skLinear;
Select(Point(0,5),Point(13,5));
h:=_HighlightData;
with h do begin
BlockPositions[hbSearch].Y:=0;
BlockPositions[hbCompileError].Y:=1;
BlockPositions[hbExecuteError].Y:=2;
BlockPositions[hbWarning].Y:=3;
end;
_HighlightData:=h;
t:=_TrackingData;
with t do begin
JumpHighlight:=True;
p1:=Point(0,4);
p2:=Point(7,4);
end;
_TrackingData:=t;
Lines.EndUpdate;
BevelKind:=bkFlat;
end;
procedure TDummySyntaxHighlightMemo.DblClick;
begin
end;
function TDummySyntaxHighlightMemo.GetHighlightClassCount: Integer;
begin
Result:=FSource.HighlightClassCount;
end;
function TDummySyntaxHighlightMemo.GetHighlightClassName(
Index: Integer): string;
begin
Result:=FSource.HighlightClassName[Index];
end;
function TDummySyntaxHighlightMemo.GetHighlightData(
Index: Integer): TCharClassHighlight;
begin
Result:=FSource.HighlightData[Index];
end;
procedure TDummySyntaxHighlightMemo.KeyDown(var Key: Word;
Shift: TShiftState);
begin
end;
procedure TDummySyntaxHighlightMemo.KeyPress(var Key: Char);
begin
end;
procedure TDummySyntaxHighlightMemo.KeyUp(var Key: Word;
Shift: TShiftState);
begin
end;
procedure TDummySyntaxHighlightMemo.MouseDown(Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
var
p:TPoint;
c:TCharClass;
begin
p:=ClientToText(Point(X,Y));
c:=PosClass(p);
SourceEditorCustomizeDialogForm.ListBox1.ItemIndex:=c;
SourceEditorCustomizeDialogForm.ListBox1Click(nil);
end;
procedure TDummySyntaxHighlightMemo.MouseMove(Shift: TShiftState; X,
Y: Integer);
begin
end;
procedure TDummySyntaxHighlightMemo.MouseUp(Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
end;
function TDummySyntaxHighlightMemo.PosClass(p: TPoint): TCharClass;
begin
Result:=inherited PosClass(p);
end;
procedure TDummySyntaxHighlightMemo.SetHighlightData(Index: Integer;
const Value: TCharClassHighlight);
begin
FSource.HighlightData[Index]:=Value;
if Index<=Integer(hbWarning) then
inherited;
Invalidate;
end;
procedure TDummySyntaxHighlightMemo.TokenizeLine(
const LineClass: TLineClass; const TextBuffer: PChar;
const TextLength: Integer; CharClass: PCharClassArray);
begin
FSource.TokenizeLine(LineClass,TextBuffer,TextLength,CharClass);
end;
procedure TDummySyntaxHighlightMemo.TokenizeLineClass(
const LastLineClass: TLineClass; var NewLineClass: TLineClass;
const TextBuffer: PChar; const TextLength: Integer);
begin
FSource.TokenizeLineClass(LastLineClass,NewLineClass,TextBuffer,TextLength);
end;
procedure TDummySyntaxHighlightMemo.WMSetCursor(var Message: TMessage);
begin
SetCursor(LoadCursor(0,IDC_ARROW));
Message.Result:=1;
end;
end.
|
unit uPctPetTreatmentFch;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uParentButtonFch, mrConfigFch, DB, StdCtrls, XiButton, ExtCtrls,
cxControls, cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxDropDownEdit,
cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox, mrSuperCombo, cxDBEdit,
mrDBEdit, cxCalendar, mrDBDateEdit, cxMemo, mrDBMemo, cxButtonEdit,
uSystemTypes;
type
TPctPetTreatmentFch = class(TParentButtonFch)
scTreatment: TmrDBSuperCombo;
scTreatmentLot: TmrDBSuperCombo;
scSystemUser: TmrDBSuperCombo;
edtExpirationDate: TmrDBDateEdit;
edtTreatmentDate: TmrDBDateEdit;
edtDosesUsed: TmrDBEdit;
memNotes: TmrDBMemo;
scPet: TmrDBSuperCombo;
procedure ConfigFchAfterStart(Sender: TObject);
procedure scTreatmentPropertiesChange(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure ConfigFchBeforeApplyChanges(Sender: TObject;
var Apply: Boolean);
procedure scTreatmentLotPropertiesEditValueChanged(Sender: TObject);
procedure ConfigFchAfterAppend(Sender: TObject);
private
procedure ApplyTreatmentFilter;
public
{ Public declarations }
end;
implementation
uses uDMPetCenter, uDMPet, uParentCustomFch, uParentSearchForm;
{$R *.dfm}
procedure TPctPetTreatmentFch.ApplyTreatmentFilter;
var
sTrFilter : String;
begin
if (scTreatment.EditValue <> Null) and (scTreatment.EditValue <> 0) then
sTrFilter := 'IDTreatment = ' + IntToStr(scTreatment.EditValue)
else
sTrFilter := 'IDTreatment = -1';
scTreatmentLot.ApplyFilters(sTrFilter);
if (DataSet.State in dsEditModes) then
begin
scTreatmentLot.EditValue := Null;
DataSet.FieldByName('IDTreatmentLot').Value := Null;
end;
end;
procedure TPctPetTreatmentFch.ConfigFchAfterStart(Sender: TObject);
begin
scSystemUser.CreateListSource(TraceControl, DataSetControl, UpdateControl, Session, DMPet.SystemUser, '');
scTreatment.CreateListSource(TraceControl, DataSetControl, UpdateControl, Session, DMPet.SystemUser, 'MenuDisplay=Treatment;');
scTreatmentLot.CreateListSource(TraceControl, DataSetControl, UpdateControl, Session, DMPet.SystemUser, '');
scPet.CreateListSource(TraceControl, DataSetControl, UpdateControl, Session, DMPet.SystemUser, 'MenuDisplay=Puppy;');
inherited;
ApplyTreatmentFilter;
end;
procedure TPctPetTreatmentFch.scTreatmentPropertiesChange(Sender: TObject);
begin
inherited;
ApplyTreatmentFilter;
end;
procedure TPctPetTreatmentFch.FormShow(Sender: TObject);
begin
inherited;
scPet.Locked := (ActionType <> atAppend) or (not DataSet.FieldByName('IDPet').IsNull);
scPet.Visible := not scPet.Locked;
end;
procedure TPctPetTreatmentFch.ConfigFchBeforeApplyChanges(Sender: TObject;
var Apply: Boolean);
begin
inherited;
DataSet.FieldByName('SystemUser').Value := scSystemUser.EditingText;
DataSet.FieldByName('LotNumber').Value := scTreatmentLot.EditingText;
DataSet.FieldByName('Treatment').Value := scTreatment.EditingText;
end;
procedure TPctPetTreatmentFch.scTreatmentLotPropertiesEditValueChanged(
Sender: TObject);
begin
inherited;
if not (DataSet.State in [dsInactive, dsBrowse]) and (scTreatmentLot.EditValue <> Null) then
DataSet.FieldByName('ExpirationDate').Value := scTreatmentLot.GetFieldValue('ExpirationDate');
end;
procedure TPctPetTreatmentFch.ConfigFchAfterAppend(Sender: TObject);
begin
inherited;
DataSet.FieldByName('DosesUsed').AsInteger := 1;
DataSet.FieldByName('TreatmentDate').AsDateTime := Now;
DataSet.FieldByName('IDUser').Value := DMPet.SystemUser.ID;
end;
initialization
RegisterClass(TPctPetTreatmentFch);
end.
|
unit Grant_Ctrl_MainForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, ExtCtrls, cxMaskEdit, cxDropDownEdit,
cxCalendar, cxTextEdit, cxButtonEdit, cxContainer, cxEdit, cxLabel,
cxControls, cxGroupBox, StdCtrls, cxButtons, gr_uCommonConsts,
PackageLoad, DB, FIBDatabase, pFIBDatabase, FIBDataSet, pFIBDataSet, IBase,
ZTypes, cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox, GlobalSpr,
Grant_Ctrl_DM, gr_uMessage, ActnList, ZProc, uCommonSp,
Unit_NumericConsts, Dates, gr_uCommonLoader, gr_uCommonProc, cxSpinEdit,
cxCheckBox,UpKernelUnit;
type
TFGrantCtrl = class(TForm)
YesBtn: TcxButton;
CancelBtn: TcxButton;
BoxMan: TcxGroupBox;
LabelMan: TcxLabel;
EditMan: TcxButtonEdit;
BoxDatesSum: TcxGroupBox;
LabelSumma: TcxLabel;
Actions: TActionList;
ActionYes: TAction;
BoxVidOpl: TcxGroupBox;
EditVidopl: TcxButtonEdit;
LabelVidoplData: TcxLabel;
LabelVidopl: TcxLabel;
LabelSmetadata: TcxLabel;
EditSmeta: TcxButtonEdit;
LabelSmeta: TcxLabel;
MaskEditSumma: TcxMaskEdit;
LabelBal: TcxLabel;
MaskEditBal: TcxMaskEdit;
BoxDates: TPanel;
EditDateBeg: TcxDateEdit;
DateBegLabel: TcxLabel;
EditDateEnd: TcxDateEdit;
DateEndLabel: TcxLabel;
procedure CancelBtnClick(Sender: TObject);
procedure EditVidOplPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure ActionYesExecute(Sender: TObject);
procedure EditVidoplExit(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure EditSmetaExit(Sender: TObject);
procedure EditSmetaPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
private
PIdGrant:Integer;
PIdStud:int64;
PIdVidopl:integer;
PKodVidopl:integer;
PIdSmeta:int64;
PKodSmeta:integer;
DM:TDM;
PRes:Variant;
Pcfs:TZControlFormStyle;
PLanguageIndex:byte;
public
constructor Create(AOwner:TComponent);reintroduce;
function DeleteRecord(Db_Handle:TISC_DB_HANDLE;Id:integer):boolean;
function PrepareData(Db_Handle:TISC_DB_HANDLE;fs:TZControlFormStyle;Id:int64):boolean;
property Res:Variant read PRes;
end;
function ViewGrantCtrl(AParameter:TObject):Variant;stdcall;
exports ViewGrantCtrl;
implementation
uses FIBQuery, Math;
{$R *.dfm}
function TFGrantCtrl.DeleteRecord(Db_Handle:TISC_DB_HANDLE;Id:integer):boolean;
var PLanguageIndex:byte;
begin
Result:=False;
PLanguageIndex := IndexLanguage;
if grShowMessage(Caption_Delete[PLanguageIndex],
DeleteRecordQuestion_Text[PLanguageIndex],mtConfirmation,[mbYes,mbCancel])=mrYes then
with DM do
try
Result:=True;
DB.Handle:=Db_Handle;
StProc.Transaction.StartTransaction;
StProc.StoredProcName:='GR_DT_GRANTS_D';
StProc.Prepare;
StProc.ParamByName('ID_GRANT').AsInteger:=Id;
StProc.ExecProc;
StProc.Transaction.Commit;
PRes:=-1;
except
on E:Exception do
begin
grShowMessage(ECaption[PlanguageIndex],e.Message,mtError,[mbOK]);
StProc.Transaction.Rollback;
Result:=False;
end;
end;
end;
function ViewGrantCtrl(AParameter:TObject):Variant;stdcall;
var Form:TFGrantCtrl;
begin
Form:=TFGrantCtrl.Create(TgrCtrlSimpleParam(AParameter).Owner);
if TgrCtrlSimpleParam(AParameter).fs=zcfsDelete then
result:=Form.DeleteRecord(TgrCtrlSimpleParam(AParameter).DB_Handle,
TgrCtrlSimpleParam(AParameter).Id)
else
begin
result := Form.PrepareData(TgrCtrlSimpleParam(AParameter).DB_Handle,
TgrCtrlSimpleParam(AParameter).fs,
TgrCtrlSimpleParam(AParameter).Id);
if Result<>False then
begin
Result := Form.ShowModal;
if Result=mrYes then Result:=Form.Res
else Result := NULL;
end
else Result:=NULL;
end;
Form.Destroy;
end;
constructor TFGrantCtrl.Create(AOwner:TComponent);
begin
inherited Create(AOwner);
DM:=TDM.Create(Self);
PLanguageIndex:=LanguageIndex;
PRes:=NULL;
//******************************************************************************
LabelMan.Caption := LabelStudent_Caption[PLanguageIndex];
DateBegLabel.Caption := LabelDateBeg_Caption[PLanguageIndex];
DateEndLabel.Caption := LabelDateEnd_Caption[PLanguageIndex];
LabelSmeta.Caption := LabelSmeta_Caption[PLanguageIndex];
LabelVidopl.Caption := LabelVidOpl_Caption[PLanguageIndex];
LabelSumma.Caption := LabelSumma_Caption[PLanguageIndex];
LabelBal.Caption := LabelBal_Caption[PLanguageIndex];
BoxMan.Caption := '';
BoxVidOpl.Caption := '';
BoxDatesSum.Caption := '';
YesBtn.Caption := YesBtn_Caption[PLanguageIndex];
CancelBtn.Caption := CancelBtn_Caption[PLanguageIndex];
CancelBtn.Hint := CancelBtn.Caption+' (Esc)';
end;
function TFGrantCtrl.PrepareData(Db_Handle:TISC_DB_HANDLE;fs:TZControlFormStyle;Id:int64):boolean;
var PDay,PMonth,PYear:word;
DBegStud,DEndStud,DBeg,DEnd:TDate;
Smeta:variant;
begin
Result:=True;
Pcfs := fs;
case fs of
zcfsInsert:
begin
Caption:=Caption_Insert[PLanguageIndex];
with DM do
try
DB.Handle:=Db_Handle;
StProc.Transaction.StartTransaction;
StProc.StoredProcName:='GR_DT_GRANTS_S_FOR_I';
StProc.Prepare;
StProc.ParamByName('ID_STUD').AsInt64:=Id;
StProc.ExecProc;
PIdStud := Id;
EditMan.Text := StProc.ParamByName('FIO').AsString;
if VarIsNull(StProc.ParamByName('PERIOD_DB').AsVariant) then DBegStud:=Date
else DBegStud:=StProc.ParamByName('PERIOD_DB').AsDate;
if VarIsNull(StProc.ParamByName('PERIOD_DE').AsVariant) then DEndStud:=Date
else DEndStud:=StProc.ParamByName('PERIOD_DE').AsDate;
if DBegStud=DEndStud then
begin
EditDateBeg.Date := DBegStud;
EditDateEnd.Date := DEndStud;
BoxDates.Enabled := False;
end
else
begin
if VarIsNULL(StProc.ParamByName('DATE_BEG').AsVariant) then DBeg:=DBegStud
else
begin
DBeg := StProc.ParamByName('DATE_BEG').AsDate;
DecodeDate(DBeg,PYear,PMonth,PDay);
if(((PYear mod 4)=0)and(PMonth=2))then
PDay:=PDay-1;
if((((PYear+1) mod 4)=0)and(PMonth=2))then
PDay:=PDay+1;
DBeg := EncodeDate(PYear+1,PMonth,PDay);
end;
if VarIsNULL(StProc.ParamByName('DATE_END').AsVariant) then DEnd:=DEndStud
else
begin
DEnd := StProc.ParamByName('DATE_END').AsDate;
DecodeDate(DEnd,PYear,PMonth,PDay);
if(((PYear mod 4)=0)and(PMonth=2))then
PDay:=PDay-1;
if((((PYear+1) mod 4)=0)and(PMonth=2))then
PDay:=PDay+1;
DEnd := EncodeDate(PYear+1,PMonth,PDay);
end;
if DBegStud>DBeg then DBeg:=DBegStud;
if DEndStud<DEnd then DEnd:=DEndStud;
if DBeg>DEnd then DEnd:=DBeg;
EditDateBeg.Date := DBeg;
EditDateBeg.Properties.MaxDate := DEndStud;
EditDateBeg.Properties.MinDate := DBegStud;
EditDateEnd.Date := DEnd;
EditDateEnd.Properties.MaxDate := DEndStud;
EditDateEnd.Properties.MinDate := DBegStud;
end;
Smeta := grValueFieldFromZSetup(DB.Handle,'GR_DEFAULT_SMETA');
if not VarIsNull(Smeta) then
begin
EditSmeta.Text := VarToStr(Smeta);
EditSmetaExit(self);
end;
StProc.Transaction.Commit;
except
on E:Exception do
begin
grShowMessage(ECaption[PLanguageIndex],e.Message,mtError,[mbOK]);
StProc.Transaction.Rollback;
Result:=false;
end;
end;
end;
zcfsUpdate:
begin
Caption:=Caption_Update[PLanguageIndex];
with DM do
try
DB.Handle:=Db_Handle;
StProc.Transaction.StartTransaction;
StProc.StoredProcName:='GR_DT_GRANTS_S_BY_KEY';
StProc.Prepare;
StProc.ParamByName('OLD_ID_GRANT').AsInteger:=Id;
StProc.ExecProc;
PIdGrant := Id;
PIdStud := StProc.ParamByName('ID_STUD').AsInt64;
EditMan.Text := StProc.ParamByName('FIO').AsString;
if VarIsNull(StProc.ParamByName('PERIOD_DB').AsVariant) then DBegStud:=Date
else DBegStud:=StProc.ParamByName('PERIOD_DB').AsDate;
if VarIsNull(StProc.ParamByName('PERIOD_DE').AsVariant) then DEndStud:=Date
else DEndStud:=StProc.ParamByName('PERIOD_DE').AsDate;
if DBegStud=DEndStud then
begin
EditDateBeg.Date := DBegStud;
EditDateEnd.Date := DEndStud;
BoxDates.Enabled := False;
end
else
begin
if VarIsNULL(StProc.ParamByName('DATE_BEG').AsVariant) then DBeg:=DBegStud
else
begin
DBeg := StProc.ParamByName('DATE_BEG').AsDate;
DecodeDate(DBeg,PYear,PMonth,PDay);
// DBeg := EncodeDate(PYear+1,PMonth,PDay);
end;
if VarIsNULL(StProc.ParamByName('DATE_END').AsVariant) then DEnd:=DEndStud
else
begin
DEnd := StProc.ParamByName('DATE_END').AsDate;
DecodeDate(DEnd,PYear,PMonth,PDay);
// DEnd := EncodeDate(PYear+1,PMonth,PDay);
end;
if DBegStud>DBeg then DBeg:=DBegStud;
if DEndStud<DEnd then DEnd:=DEndStud;
if DBeg>DEnd then DEnd:=DBeg;
EditDateBeg.Date := DBeg;
EditDateBeg.Properties.MaxDate := DEndStud;
EditDateBeg.Properties.MinDate := DBegStud;
EditDateEnd.Date := DEnd;
EditDateEnd.Properties.MaxDate := DEndStud;
EditDateEnd.Properties.MinDate := DBegStud;
end;
PIdVidopl := StProc.ParamByName('ID_VIDOPL').AsInteger;
PIdSmeta := StProc.ParamByName('ID_SMETA').AsInt64;
EditVidopl.Text := VarToStrDef(StProc.ParamByName('KOD_VIDOPL').AsVariant,'');
LabelVidoplData.Caption := VarToStrDef(StProc.ParamByName('NAME_VIDOPL').AsVariant,'');
EditSmeta.Text := VarToStrDef(StProc.ParamByName('KOD_SMETA').AsVariant,'');
LabelSmetadata.Caption := VarToStrDef(StProc.ParamByName('NAME_SMETA').AsVariant,'');
MaskEditSumma.Text := FloatToStrF(StProc.ParamByName('SUMMA').AsFloat,ffFixed,16,2);
MaskEditBal.Text := FloatToStrF(StProc.ParamByName('BAL').AsFloat,ffFixed,5,2);
StProc.Transaction.Commit;
except
on E:Exception do
begin
grShowMessage(ECaption[PLanguageIndex],e.Message,mtError,[mbOK]);
StProc.Transaction.Rollback;
Result:=false;
end;
end;
end;
zcfsShowDetails:
begin
Caption:=Caption_Detail[PLanguageIndex];
self.BoxVidOpl.Enabled := false;
self.BoxDatesSum.Enabled := false;
YesBtn.Visible:=False;
CancelBtn.Caption := ExitBtn_Caption[PlanguageIndex];
with DM do
try
DB.Handle:=Db_Handle;
StProc.Transaction.StartTransaction;
StProc.StoredProcName:='GR_DT_GRANTS_S_BY_KEY';
StProc.Prepare;
StProc.ParamByName('OLD_ID_GRANT').AsInteger:=Id;
StProc.ExecProc;
PIdGrant := Id;
PIdStud := StProc.ParamByName('ID_STUD').AsInt64;
EditMan.Text := StProc.ParamByName('FIO').AsString;
EditDateEnd.Date := StProc.ParamByName('DATE_END').AsDate;
EditDateBeg.Date := StProc.ParamByName('DATE_BEG').AsDate;
PIdVidopl := StProc.ParamByName('ID_VIDOPL').AsInteger;
PIdSmeta := StProc.ParamByName('ID_SMETA').AsInt64;
EditVidopl.Text := VarToStrDef(StProc.ParamByName('KOD_VIDOPL').AsVariant,'');
LabelVidoplData.Caption := VarToStrDef(StProc.ParamByName('NAME_VIDOPL').AsVariant,'');
EditSmeta.Text := VarToStrDef(StProc.ParamByName('KOD_SMETA').AsVariant,'');
LabelSmetadata.Caption := VarToStrDef(StProc.ParamByName('NAME_SMETA').AsVariant,'');
MaskEditSumma.Text := FloatToStrF(StProc.ParamByName('SUMMA').AsFloat,ffFixed,16,2);
MaskEditBal.Text := FloatToStrF(StProc.ParamByName('BAL').AsFloat,ffFixed,5,2);
StProc.Transaction.Commit;
except
on E:Exception do
begin
grShowMessage(ECaption[PLanguageIndex],e.Message,mtError,[mbOK]);
StProc.Transaction.Rollback;
Result:=false;
end;
end;
end;
end;
end;
procedure TFGrantCtrl.CancelBtnClick(Sender: TObject);
begin
ModalResult := mrCancel;
end;
procedure TFGrantCtrl.EditVidOplPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var VidOpl:Variant;
begin
VidOPl:=LoadVidOpl(self,
DM.DB.Handle,zfsModal,
0,ValueFieldZSetup(DM.DB.Handle,'GR_ID_SYSTEM'));
if VarArrayDimCount(VidOpl)>0 then
begin
PIdVidopl:=VidOpl[0];
PKodVidopl:=VidOPl[2];
LabelVidOplData.Caption := VidOpl[1];
EditVidOpl.Text := IntToStr(PKodVidOpl);
end
else
EditVidOpl.SetFocus;
end;
procedure TFGrantCtrl.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
if DM.DefaulttTransaction.InTransaction then DM.DefaulttTransaction.Commit;
end;
procedure TFGrantCtrl.ActionYesExecute(Sender: TObject);
begin
if PIdVidopl=0 then
begin
grShowMessage(ECaption[PLanguageIndex],EVidOplInput_Text[PLanguageIndex],mtWarning,[mbOk]);
exit;
end;
if EditDateBeg.Date>EditDateEnd.Date then
begin
grShowMessage(ECaption[PLanguageIndex],EInputTerms_Text[PLanguageIndex],mtWarning,[mbOk]);
exit;
end;
with DM do
try
StProcTransaction.StartTransaction;
case Pcfs of
zcfsInsert: StProc.StoredProcName:='GR_DT_GRANTS_I';
zcfsUpdate: StProc.StoredProcName:='GR_DT_GRANTS_U';
end;
StProc.Prepare;
StProc.ParamByName('ID_STUD').AsInt64 := PIdStud;
StProc.ParamByName('DATE_BEG').AsDate := StrToDate(EditDateBeg.Text);
StProc.ParamByName('DATE_END').AsDate := StrToDate(EditDateEnd.Text);
StProc.ParamByName('ID_SMETA').AsInt64 := PIdSmeta;
StProc.ParamByName('ID_VIDOPL').AsInt64 := PIdVidopl;
StProc.ParamByName('SUMMA').AsCurrency := StrToFloat(MaskEditSumma.Text);
StProc.ParamByName('BAL').AsCurrency := StrToFloat(MaskEditBal.Text);
case Pcfs of
zcfsUpdate:
StProc.ParamByName('ID_GRANT').AsInteger := PIdGrant;
end;
StProc.ExecProc;
if pcfs=zcfsInsert then
PRes:=StProc.ParamByName('ID_GRANT').AsInteger
else PRes:=PIdGrant;
StProc.Transaction.Commit;
ModalResult:=mrYes;
except
on e:Exception do
begin
grShowMessage(ECaption[PLanguageIndex],e.message,mtError,[mbOk]);
StProc.transaction.RollBack;
PRes:=NULL;
end;
end;
end;
procedure TFGrantCtrl.EditVidoplExit(Sender: TObject);
var VidOpl:Variant;
begin
if EditVidOpl.Text<>'' then
begin
if StrToInt(EditVidOpl.Text)=PKodVidopl then Exit;
VidOpl:=VoByKod(StrToInt(EditVidOpl.Text),date,DM.DB.Handle,ValueFieldZSetup(DM.DB.Handle,'GR_ID_SYSTEM'),0);
if VarArrayDimCount(VidOpl)>0 then
begin
PIdVidOpl:=VidOpl[0];
PKodVidopl:=VidOPl[1];
LabelVidOplData.Caption := Vidopl[2];
end
else
EditVidOpl.SetFocus;
end;
end;
procedure TFGrantCtrl.FormDestroy(Sender: TObject);
begin
if DM<>nil then DM.Destroy;
end;
procedure TFGrantCtrl.EditSmetaExit(Sender: TObject);
var Smeta:Variant;
begin
if EditSmeta.Text<>'' then
begin
if StrToInt(EditSmeta.Text)=PKodSmeta then Exit;
Smeta:=SmetaByKod(StrToInt(EditSmeta.Text),DM.DB.Handle);
if VarArrayDimCount(Smeta)>0 then
begin
PIdsmeta:=Smeta[0];
PKodSmeta:=Smeta[1];
LabelSmetaData.Caption := Smeta[2];
end
else
EditSmeta.SetFocus;
end;
end;
procedure TFGrantCtrl.EditSmetaPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
var Smeta:Variant;
begin
Smeta:=GetSmets(self,DM.DB.Handle,Date,psmSmet);
if VarArrayDimCount(Smeta)> 0 then
If Smeta[0]<>NULL then
begin
PIdsmeta := Smeta[0];
PKodSmeta := Smeta[3];
EditSmeta.Text := IntToStr(PKodSmeta);
LabelSmetaData.Caption := Smeta[2];
end;
end;
end.
|
unit pSHDBSynEdit;
interface
uses Windows, Classes, Controls, DBCtrls, DB, Messages, SysUtils,
SynEditKeyCmds,
pSHSynEdit;
type
TpSHDBSynEdit = class(TpSHSynEdit)
private
FDataLink: TFieldDataLink;
FFocused: Boolean;
FMemoLoaded: Boolean;
// FPaintControl: TPaintControl;
procedure DataChange(Sender: TObject);
procedure EditingChange(Sender: TObject);
function GetDataField: string;
procedure SetDataField(const Value: string);
function GetDataSource: TDataSource;
procedure SetDataSource(Value: TDataSource);
function GetField: TField;
procedure SetFocused(Value: Boolean);
procedure UpdateData(Sender: TObject);
procedure WMCut(var Message: TMessage); message WM_CUT;
procedure WMPaste(var Message: TMessage); message WM_PASTE;
procedure WMUndo(var Message: TMessage); message WM_UNDO;
procedure CMEnter(var Message: TCMEnter); message CM_ENTER;
procedure CMExit(var Message: TCMExit); message CM_EXIT;
procedure CMGetDataLink(var Message: TMessage); message CM_GETDATALINK;
protected
function GetReadOnly: Boolean; override;
procedure SetReadOnly(Value: Boolean); override;
procedure DoChange; override;
procedure KeyDown(var Key: Word; Shift: TShiftState); override;
procedure KeyPress(var Key: Char); override;
procedure Loaded; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Notification(AComponent: TComponent;
Operation: TOperation); override;
function ExecuteAction(Action: TBasicAction): Boolean; override;
procedure DragDrop(Source: TObject; X, Y: Integer); override;
procedure ExecuteCommand(Command: TSynEditorCommand; AChar: char;
Data: pointer); override;
procedure LoadMemo; virtual;
function UpdateAction(Action: TBasicAction): Boolean; override;
function UseRightToLeftAlignment: Boolean; override;
property Field: TField read GetField;
published
property DataField: string read GetDataField write SetDataField;
property DataSource: TDataSource read GetDataSource write SetDataSource;
end;
implementation
uses SynEdit;
{ TpSHDBSynEdit }
constructor TpSHDBSynEdit.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
// ControlStyle := ControlStyle + [csReplicatable];
FDataLink := TFieldDataLink.Create;
FDataLink.Control := Self;
FDataLink.OnDataChange := DataChange;
FDataLink.OnEditingChange := EditingChange;
FDataLink.OnUpdateData := UpdateData;
inherited ReadOnly := True;
end;
destructor TpSHDBSynEdit.Destroy;
begin
FDataLink.Free;
FDataLink := nil;
inherited Destroy;
end;
procedure TpSHDBSynEdit.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if (Operation = opRemove) and (FDataLink <> nil) and
(AComponent = DataSource) then DataSource := nil;
end;
procedure TpSHDBSynEdit.DataChange(Sender: TObject);
begin
if not Assigned(FDataLink) then Exit;
if FDataLink.Field <> nil then
if FDataLink.Field.IsBlob then
begin
FMemoLoaded := False;
LoadMemo;
end else
begin
if FFocused and FDataLink.CanModify then
Text := FDataLink.Field.Text
else
Text := FDataLink.Field.DisplayText;
FMemoLoaded := True;
end
else
begin
if csDesigning in ComponentState then Text := Name else Text := '';
FMemoLoaded := False;
end;
// Invalidate;
// if HandleAllocated then
// RedrawWindow(Handle, nil, 0, RDW_INVALIDATE or RDW_ERASE or RDW_FRAME);
end;
procedure TpSHDBSynEdit.EditingChange(Sender: TObject);
begin
// inherited ReadOnly := not (FDataLink.Editing and FMemoLoaded);
inherited ReadOnly := not FMemoLoaded;
end;
function TpSHDBSynEdit.GetDataField: string;
begin
Result := FDataLink.FieldName;
end;
procedure TpSHDBSynEdit.SetDataField(const Value: string);
begin
FDataLink.FieldName := Value;
end;
function TpSHDBSynEdit.GetDataSource: TDataSource;
begin
Result := FDataLink.DataSource;
end;
procedure TpSHDBSynEdit.SetDataSource(Value: TDataSource);
begin
if not (FDataLink.DataSourceFixed and (csLoading in ComponentState)) then
FDataLink.DataSource := Value;
if Value <> nil then Value.FreeNotification(Self);
end;
function TpSHDBSynEdit.GetField: TField;
begin
Result := FDataLink.Field;
end;
procedure TpSHDBSynEdit.SetFocused(Value: Boolean);
begin
if FFocused <> Value then
begin
FFocused := Value;
if not Assigned(FDataLink.Field) or not FDataLink.Field.IsBlob then
FDataLink.Reset;
end;
end;
procedure TpSHDBSynEdit.UpdateData(Sender: TObject);
begin
FDataLink.Field.AsString := Text;
end;
procedure TpSHDBSynEdit.WMCut(var Message: TMessage);
begin
FDataLink.Edit;
inherited;
end;
procedure TpSHDBSynEdit.WMPaste(var Message: TMessage);
begin
FDataLink.Edit;
inherited;
end;
procedure TpSHDBSynEdit.WMUndo(var Message: TMessage);
begin
FDataLink.Edit;
inherited;
end;
procedure TpSHDBSynEdit.CMEnter(var Message: TCMEnter);
begin
SetFocused(True);
inherited;
if SysLocale.FarEast and FDataLink.CanModify then
inherited ReadOnly := False;
end;
procedure TpSHDBSynEdit.CMExit(var Message: TCMExit);
begin
try
FDataLink.UpdateRecord;
except
SetFocus;
raise;
end;
SetFocused(False);
inherited;
end;
procedure TpSHDBSynEdit.CMGetDataLink(var Message: TMessage);
begin
Message.Result := Integer(FDataLink);
end;
function TpSHDBSynEdit.GetReadOnly: Boolean;
begin
Result := FDataLink.ReadOnly;
end;
procedure TpSHDBSynEdit.SetReadOnly(Value: Boolean);
begin
FDataLink.ReadOnly := Value;
end;
procedure TpSHDBSynEdit.DoChange;
begin
if FMemoLoaded then FDataLink.Modified;
FMemoLoaded := True;
inherited DoChange;
end;
procedure TpSHDBSynEdit.KeyDown(var Key: Word; Shift: TShiftState);
begin
inherited KeyDown(Key, Shift);
if FMemoLoaded then
begin
if (Key = VK_DELETE) or ((Key = VK_INSERT) and (ssShift in Shift)) then
FDataLink.Edit;
end;
end;
procedure TpSHDBSynEdit.KeyPress(var Key: Char);
begin
inherited KeyPress(Key);
if FMemoLoaded then
begin
if (Key in [#32..#255]) and (FDataLink.Field <> nil) and
not FDataLink.Field.IsValidChar(Key) then
begin
MessageBeep(0);
Key := #0;
end;
case Key of
^H, ^I, ^J, ^M, ^V, ^X, #32..#255:
FDataLink.Edit;
#27:
FDataLink.Reset;
end;
end else
begin
if Key = #13 then LoadMemo;
Key := #0;
end;
end;
procedure TpSHDBSynEdit.Loaded;
begin
inherited Loaded;
if (csDesigning in ComponentState) then DataChange(Self);
end;
function TpSHDBSynEdit.ExecuteAction(Action: TBasicAction): Boolean;
begin
Result := inherited ExecuteAction(Action) or (FDataLink <> nil) and
FDataLink.ExecuteAction(Action);
end;
procedure TpSHDBSynEdit.DragDrop(Source: TObject; X, Y: Integer);
begin
FDataLink.Edit;
inherited DragDrop(Source, X, Y);
end;
procedure TpSHDBSynEdit.ExecuteCommand(Command: TSynEditorCommand;
AChar: char; Data: pointer);
begin
// cancel on [ESC]
if (Command = ecChar) and (AChar = #27) then
FDataLink.Reset
// set editing state if editor command
else begin
if (Command >= ecEditCommandFirst) and (Command <= ecEditCommandLast) then
FDataLink.Edit;
end;
inherited ExecuteCommand(Command, AChar, Data);
end;
procedure TpSHDBSynEdit.LoadMemo;
var
BlobStream: TStream;
begin
if not FMemoLoaded and Assigned(FDataLink.Field) and FDataLink.Field.IsBlob then
begin
try
BlobStream := FDataLink.DataSet.CreateBlobStream(FDataLink.Field, bmRead);
Lines.BeginUpdate;
Lines.LoadFromStream(BlobStream);
Lines.EndUpdate;
BlobStream.Free;
Modified := false;
ClearUndo;
FMemoLoaded := True;
except
{ Memo too large }
on E: EInvalidOperation do
Lines.Text := Format('(%s)', [E.Message]);
end;
EditingChange(Self);
end;
end;
function TpSHDBSynEdit.UpdateAction(Action: TBasicAction): Boolean;
begin
Result := inherited UpdateAction(Action) or (FDataLink <> nil) and
FDataLink.UpdateAction(Action);
end;
function TpSHDBSynEdit.UseRightToLeftAlignment: Boolean;
begin
Result := DBUseRightToLeftAlignment(Self, Field);
end;
end.
|
unit CurrentCtrl_ByPrev;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, FIBDatabase, pFIBDatabase, DB,
FIBDataSet, pFIBDataSet, ActnList, StdCtrls, cxButtons, cxTextEdit,
cxMaskEdit, cxControls, cxContainer, cxEdit, cxLabel, ExtCtrls, ZProc,
Unit_Zglobal_Consts;
Type TFPrev_Result=record
Summa:double;
Percent:double;
ModalResult:TModalResult;
end;
type
TFPrev = class(TForm)
Bevel1: TBevel;
LabelData: TcxLabel;
EditData: TcxMaskEdit;
YesBtn: TcxButton;
CancelBtn: TcxButton;
ActionList: TActionList;
ActionYes: TAction;
ActionCancel: TAction;
DB: TpFIBDatabase;
DSet: TpFIBDataSet;
ReadTransaction: TpFIBTransaction;
procedure ActionYesExecute(Sender: TObject);
procedure ActionCancelExecute(Sender: TObject);
private
PLanguageIndex:Byte;
CurrDecimalSeparator:string[1];
public
constructor Create(AOwner:TComponent);reintroduce;
end;
implementation
{$R *.dfm}
constructor TFPrev.Create(AOwner:TComponent);
begin
inherited Create(AOwner);
//------------------------------------------------------------------------------
PLanguageIndex:=LanguageIndex;
YesBtn.Caption := YesBtn_Caption[PLanguageIndex];
CancelBtn.Caption := CancelBtn_Caption[PLanguageIndex];
YesBtn.Hint := YesBtn.Caption;
CancelBtn.Hint :=CancelBtn.Caption;
//------------------------------------------------------------------------------
CurrDecimalSeparator:=ZSystemDecimalSeparator;
EditData.Properties.EditMask:='100(['+CurrDecimalSeparator+']0(0?))? | \d\d? (['+CurrDecimalSeparator+',]\d\d?)?';
LabelData.Caption := LabelPercent_Caption[PLanguageIndex];
end;
procedure TFPrev.ActionYesExecute(Sender: TObject);
begin
if EditData.Text='' then
begin
EditData.SetFocus;
Exit;
end;
ModalResult:=mrYes;
end;
procedure TFPrev.ActionCancelExecute(Sender: TObject);
begin
ModalResult:=mrCancel;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.